mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98fcda66f2 | ||
|
|
0f5c6a8ae0 |
No files matched your search
@@ -23,22 +23,15 @@ on:
|
||||
- all
|
||||
- standard
|
||||
- large_disk
|
||||
publish:
|
||||
description: 'Publish images and manifests'
|
||||
required: true
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
variants: ${{ steps.set-variants.outputs.variants }}
|
||||
publish: ${{ steps.set-publish.outputs.publish }}
|
||||
steps:
|
||||
- name: Select variants for this run
|
||||
id: set-variants
|
||||
@@ -49,14 +42,6 @@ jobs:
|
||||
variants='["standard","large_disk"]'
|
||||
fi
|
||||
echo "variants=$variants" >> "$GITHUB_OUTPUT"
|
||||
- name: Select publish mode
|
||||
id: set-publish
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
echo "publish=${{ github.event.inputs.publish }}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "publish=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
build:
|
||||
needs: [setup]
|
||||
@@ -126,13 +111,13 @@ jobs:
|
||||
buildkitd-flags: "--debug"
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
- name: Login to Docker Hub
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- name: Login to GHCR
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
@@ -144,7 +129,7 @@ jobs:
|
||||
DOCKER_BUILDKIT: 1
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ needs.setup.outputs.publish == 'true' }}
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
file: ./docker/Dockerfile.go_build
|
||||
platforms: linux/${{ matrix.platform }}
|
||||
# Push to GHCR only during build to avoid Docker Hub rate limits
|
||||
@@ -164,128 +149,10 @@ jobs:
|
||||
# Remove Go build cache
|
||||
sudo rm -rf /tmp/go-build*
|
||||
|
||||
trivy-scan:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [setup, build]
|
||||
strategy:
|
||||
matrix:
|
||||
variant: ${{ fromJSON(needs.setup.outputs.variants) }}
|
||||
steps:
|
||||
- name: Configure variant
|
||||
id: config
|
||||
run: |
|
||||
if [ "${{ matrix.variant }}" == "large_disk" ]; then
|
||||
echo "tag_suffix=_large_disk" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "tag_suffix=" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
- name: Login to GHCR
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
- name: Checkout for local scan build
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_ref || github.ref }}
|
||||
- name: Create BuildKit config for local scan build
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
run: |
|
||||
cat > /tmp/buildkitd.toml <<EOF
|
||||
[registry."docker.io"]
|
||||
mirrors = ["https://mirror.gcr.io"]
|
||||
EOF
|
||||
- name: Set up Docker Buildx for local scan build
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
buildkitd-flags: "--debug"
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
- name: Build local scan image tarball
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
uses: docker/build-push-action@v7
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
with:
|
||||
context: ./docker
|
||||
file: ./docker/Dockerfile.go_build
|
||||
platforms: linux/amd64
|
||||
outputs: type=docker,dest=/tmp/seaweedfs${{ steps.config.outputs.tag_suffix }}-amd64.tar
|
||||
build-args: |
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
BRANCH=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_ref || github.sha }}
|
||||
${{ matrix.variant == 'large_disk' && 'TAGS=5BytesOffset' || '' }}
|
||||
- name: Trivy report (published image)
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
# Pin to SHA - mutable tags were compromised (GHSA-69fq-xp46-6x23)
|
||||
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
with:
|
||||
scan-type: image
|
||||
# Scan amd64 only - OS packages are identical across architectures
|
||||
# since they all use the same alpine base, so a single-arch scan
|
||||
# provides sufficient coverage without multiplying CI time.
|
||||
image-ref: ghcr.io/chrislusf/seaweedfs:${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }}${{ steps.config.outputs.tag_suffix }}-amd64
|
||||
scanners: vuln
|
||||
vuln-type: os,library
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
limit-severities-for-sarif: true
|
||||
format: sarif
|
||||
output: trivy-results.sarif
|
||||
exit-code: '0'
|
||||
- name: Trivy report (local tarball)
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
with:
|
||||
input: /tmp/seaweedfs${{ steps.config.outputs.tag_suffix }}-amd64.tar
|
||||
scanners: vuln
|
||||
vuln-type: os,library
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
limit-severities-for-sarif: true
|
||||
format: sarif
|
||||
output: trivy-results.sarif
|
||||
exit-code: '0'
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
- name: Trivy gate (published image)
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
# Gate only on fixable high/critical vulnerabilities. Non-fixable
|
||||
# findings are still visible in the SARIF upload above.
|
||||
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
with:
|
||||
scan-type: image
|
||||
image-ref: ghcr.io/chrislusf/seaweedfs:${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }}${{ steps.config.outputs.tag_suffix }}-amd64
|
||||
scanners: vuln
|
||||
vuln-type: os,library
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
format: table
|
||||
exit-code: '1'
|
||||
skip-setup-trivy: true
|
||||
- name: Trivy gate (local tarball)
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
with:
|
||||
input: /tmp/seaweedfs${{ steps.config.outputs.tag_suffix }}-amd64.tar
|
||||
scanners: vuln
|
||||
vuln-type: os,library
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
format: table
|
||||
exit-code: '1'
|
||||
skip-setup-trivy: true
|
||||
|
||||
create-manifest:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [setup, build, trivy-scan]
|
||||
if: needs.setup.outputs.publish == 'true' && github.event_name != 'pull_request'
|
||||
needs: [setup, build]
|
||||
if: github.event_name != 'pull_request'
|
||||
strategy:
|
||||
matrix:
|
||||
variant: ${{ fromJSON(needs.setup.outputs.variants) }}
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
name: "S3 Mutation Regression Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'test/s3/delete/**'
|
||||
- 'test/s3/distributed_lock/**'
|
||||
- 'test/s3/versioning/**'
|
||||
- 'test/volume_server/framework/**'
|
||||
- 'docker/compose/s3.json'
|
||||
- '.github/workflows/s3-mutation-regression-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/s3-mutation-regression-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
s3-versioning-regressions:
|
||||
name: S3 Versioning Regression Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Run S3 versioning regression tests
|
||||
timeout-minutes: 20
|
||||
working-directory: test/s3/versioning
|
||||
run: |
|
||||
set -x
|
||||
make test-with-server TEST_PATTERN="TestVersioningCompleteMultipartUploadIsIdempotent|TestVersioningSelfCopyMetadataReplaceCreatesNewVersion|TestVersioningSelfCopyMetadataReplaceSuspendedKeepsNullVersion|TestSuspendedDeleteCreatesDeleteMarker"
|
||||
|
||||
- name: Show server logs on failure
|
||||
if: failure()
|
||||
working-directory: test/s3/versioning
|
||||
run: |
|
||||
echo "=== Server Logs ==="
|
||||
if [ -f weed-test.log ]; then
|
||||
tail -100 weed-test.log
|
||||
fi
|
||||
|
||||
- name: Upload versioning logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: s3-versioning-regression-logs
|
||||
path: test/s3/versioning/weed-test*.log
|
||||
retention-days: 3
|
||||
|
||||
s3-delete-regressions:
|
||||
name: S3 Delete Regression Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Run S3 delete regression tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/delete
|
||||
run: |
|
||||
set -x
|
||||
make test-with-server
|
||||
|
||||
- name: Show server logs on failure
|
||||
if: failure()
|
||||
working-directory: test/s3/delete
|
||||
run: |
|
||||
echo "=== Server Logs ==="
|
||||
if [ -f weed-test.log ]; then
|
||||
tail -100 weed-test.log
|
||||
fi
|
||||
|
||||
- name: Upload delete logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: s3-delete-regression-logs
|
||||
path: test/s3/delete/weed-test*.log
|
||||
retention-days: 3
|
||||
|
||||
s3-distributed-lock-regressions:
|
||||
name: S3 Distributed Lock Regression Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build SeaweedFS
|
||||
run: |
|
||||
go build -o weed/weed -buildvcs=false ./weed
|
||||
|
||||
- name: Run distributed lock regressions
|
||||
timeout-minutes: 25
|
||||
env:
|
||||
TMPDIR: ${{ github.workspace }}/test/s3/distributed_lock/tmp
|
||||
S3_DISTRIBUTED_LOCK_KEEP_LOGS: "1"
|
||||
WEED_BINARY: ${{ github.workspace }}/weed/weed
|
||||
run: |
|
||||
set -x
|
||||
mkdir -p "$TMPDIR"
|
||||
go test -v -count=1 -timeout=20m ./test/s3/distributed_lock
|
||||
|
||||
- name: Upload distributed lock logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: s3-distributed-lock-regression-logs
|
||||
path: test/s3/distributed_lock/tmp/seaweedfs_s3_distributed_lock_*
|
||||
retention-days: 3
|
||||
@@ -16,16 +16,15 @@ RUN cd /go/src/github.com/seaweedfs/seaweedfs/weed \
|
||||
&& export LDFLAGS="-X github.com/seaweedfs/seaweedfs/weed/util/version.COMMIT=$(git rev-parse --short HEAD)" \
|
||||
&& CGO_ENABLED=0 go install -tags "$TAGS" -ldflags "-extldflags -static ${LDFLAGS}"
|
||||
|
||||
# Rust volume server builder. Alpine packages avoid depending on the
|
||||
# upstream rust:alpine manifest list, which no longer includes linux/386.
|
||||
FROM alpine:3.23 as rust_builder
|
||||
# Rust volume server builder (amd64/arm64 only)
|
||||
FROM rust:1-alpine as rust_builder
|
||||
ARG TARGETARCH
|
||||
RUN apk add musl-dev protobuf-dev git
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/seaweed-volume /build/seaweed-volume
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/weed /build/weed
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/proto /build/proto
|
||||
WORKDIR /build/seaweed-volume
|
||||
ARG TAGS
|
||||
RUN if [ "$TARGETARCH" = "amd64" ] || [ "$TARGETARCH" = "arm64" ]; then \
|
||||
apk add --no-cache musl-dev openssl-dev protobuf-dev git rust cargo; \
|
||||
if [ "$TAGS" = "5BytesOffset" ]; then \
|
||||
cargo build --release; \
|
||||
else \
|
||||
|
||||
@@ -83,7 +83,7 @@ require (
|
||||
github.com/valyala/bytebufferpool v1.0.0
|
||||
github.com/viant/ptrie v1.0.1
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.2
|
||||
github.com/xdg-go/scram v1.1.2 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
go.etcd.io/etcd/client/v3 v3.6.7
|
||||
@@ -94,7 +94,7 @@ require (
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.45.0
|
||||
golang.org/x/crypto v0.49.0
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa
|
||||
golang.org/x/image v0.38.0
|
||||
golang.org/x/image v0.36.0
|
||||
golang.org/x/net v0.51.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sys v0.42.0
|
||||
|
||||
@@ -1838,6 +1838,8 @@ github.com/schollz/progressbar/v3 v3.19.0 h1:Ea18xuIRQXLAUidVDox3AbwfUhD0/1Ivohy
|
||||
github.com/schollz/progressbar/v3 v3.19.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
|
||||
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564 h1:TgxPraf1NmF6XTcUG53ULpLQrKvhtUJxQ3hyekxSDNQ=
|
||||
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.1 h1:gnKmfrKreCRGJmekGz5WMnNZqXEf9s9+V2hdWQdvx88=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.1/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.2 h1:IfP/yFjLGO4rALcJY2Gb39PlebHxLnj7dkIiQAjFres=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.2/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
|
||||
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
|
||||
@@ -2240,8 +2242,8 @@ golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeap
|
||||
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
|
||||
golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
|
||||
golang.org/x/image v0.36.0 h1:Iknbfm1afbgtwPTmHnS2gTM/6PPZfH+z2EFuOkSbqwc=
|
||||
golang.org/x/image v0.36.0/go.mod h1:YsWD2TyyGKiIX1kZlu9QfKIsQ4nAAK9bdgdrIsE7xy4=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
|
||||
@@ -122,7 +122,8 @@ func testGitCloneAndPull(t *testing.T, mountPoint, localDir string) {
|
||||
|
||||
// ---- Phase 5: Reset to older revision in on-mount clone ----
|
||||
t.Log("Phase 5: reset to older revision on mount clone")
|
||||
resetToCommitWithRecovery(t, bareRepo, localClone, mountClone, commit2)
|
||||
ensureMountClone(t, bareRepo, mountClone)
|
||||
gitRun(t, mountClone, "reset", "--hard", commit2)
|
||||
|
||||
resetHead := gitOutput(t, mountClone, "rev-parse", "HEAD")
|
||||
assert.Equal(t, commit2, resetHead, "should be at commit 2")
|
||||
@@ -323,21 +324,13 @@ func tryEnsureBareRepo(bareRepo, localClone string) error {
|
||||
if _, err := os.Stat(filepath.Join(bareRepo, "HEAD")); err == nil {
|
||||
return nil
|
||||
}
|
||||
branch, err := tryGitCommand(localClone, "rev-parse", "--abbrev-ref", "HEAD")
|
||||
if err != nil {
|
||||
return fmt.Errorf("detect local branch: %w", err)
|
||||
}
|
||||
os.RemoveAll(bareRepo)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
if _, err := tryGitCommand("", "init", "--bare", bareRepo); err != nil {
|
||||
return fmt.Errorf("re-init bare repo: %w", err)
|
||||
}
|
||||
refSpec := fmt.Sprintf("%s:refs/heads/%s", branch, branch)
|
||||
if _, err := tryGitCommand(localClone, "push", "--force", bareRepo, refSpec); err != nil {
|
||||
return fmt.Errorf("re-push branch %s to bare repo: %w", branch, err)
|
||||
}
|
||||
if _, err := tryGitCommand("", "--git-dir="+bareRepo, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil {
|
||||
return fmt.Errorf("set bare repo HEAD to %s: %w", branch, err)
|
||||
if _, err := tryGitCommand(localClone, "push", "--force", bareRepo, "master"); err != nil {
|
||||
return fmt.Errorf("re-push to bare repo: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -392,61 +385,6 @@ func pullFromCommitWithRecovery(t *testing.T, bareRepo, localClone, cloneDir, fr
|
||||
}
|
||||
}
|
||||
|
||||
// resetToCommitWithRecovery resets the on-mount clone to a given commit. If
|
||||
// the FUSE mount loses the directory after a failed reset (the kernel dcache
|
||||
// can drop the entry after "Could not write new index file"), it re-clones
|
||||
// from the bare repo and retries.
|
||||
func resetToCommitWithRecovery(t *testing.T, bareRepo, localClone, mountClone, commit string) {
|
||||
t.Helper()
|
||||
const maxAttempts = 3
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= maxAttempts; attempt++ {
|
||||
if err := tryEnsureBareRepo(bareRepo, localClone); err != nil {
|
||||
lastErr = err
|
||||
t.Logf("reset recovery attempt %d: ensure bare repo: %v", attempt, err)
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
if err := tryEnsureMountClone(bareRepo, mountClone); err != nil {
|
||||
lastErr = err
|
||||
t.Logf("reset recovery attempt %d: ensure mount clone: %v", attempt, err)
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
if _, err := tryGitCommand(mountClone, "reset", "--hard", commit); err != nil {
|
||||
lastErr = err
|
||||
if attempt < maxAttempts {
|
||||
t.Logf("reset recovery attempt %d: %v — removing clone for re-create", attempt, err)
|
||||
os.RemoveAll(mountClone)
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !waitForDirEventually(t, mountClone, 5*time.Second) {
|
||||
lastErr = fmt.Errorf("clone dir %s did not recover after reset", mountClone)
|
||||
if attempt < maxAttempts {
|
||||
t.Logf("reset recovery attempt %d: %v", attempt, lastErr)
|
||||
os.RemoveAll(mountClone)
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Verify git commands actually work in the directory — the kernel
|
||||
// dcache can transiently show the dir then lose it after reset.
|
||||
if _, err := tryGitCommand(mountClone, "rev-parse", "HEAD"); err != nil {
|
||||
lastErr = fmt.Errorf("post-reset verification failed: %w", err)
|
||||
if attempt < maxAttempts {
|
||||
t.Logf("reset recovery attempt %d: %v — removing clone for re-create", attempt, lastErr)
|
||||
os.RemoveAll(mountClone)
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
require.NoError(t, lastErr, "git reset --hard %s failed after %d recovery attempts", commit, maxAttempts)
|
||||
}
|
||||
|
||||
func tryPullFromCommit(t *testing.T, bareRepo, localClone, cloneDir, fromCommit string) error {
|
||||
t.Helper()
|
||||
// The bare repo lives on the FUSE mount and can also vanish.
|
||||
@@ -499,36 +437,3 @@ func leftPad(n, width int) string {
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestTryEnsureBareRepoPreservesCurrentBranch(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "git_bare_recovery_")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
bareRepo := filepath.Join(tempDir, "repo.git")
|
||||
localClone := filepath.Join(tempDir, "clone")
|
||||
restoredClone := filepath.Join(tempDir, "restored")
|
||||
|
||||
gitRun(t, "", "init", "--bare", bareRepo)
|
||||
gitRun(t, "", "clone", bareRepo, localClone)
|
||||
gitRun(t, localClone, "config", "user.email", "test@seaweedfs.test")
|
||||
gitRun(t, localClone, "config", "user.name", "Test")
|
||||
|
||||
writeFile(t, localClone, "README.md", "hello recovery\n")
|
||||
gitRun(t, localClone, "add", "README.md")
|
||||
gitRun(t, localClone, "commit", "-m", "initial commit")
|
||||
|
||||
branch := gitOutput(t, localClone, "rev-parse", "--abbrev-ref", "HEAD")
|
||||
require.NotEmpty(t, branch)
|
||||
|
||||
require.NoError(t, os.RemoveAll(bareRepo))
|
||||
require.NoError(t, tryEnsureBareRepo(bareRepo, localClone))
|
||||
|
||||
headRef := gitOutput(t, "", "--git-dir="+bareRepo, "symbolic-ref", "--short", "HEAD")
|
||||
assert.Equal(t, branch, headRef, "recovered bare repo should keep the current branch as HEAD")
|
||||
|
||||
gitRun(t, "", "clone", bareRepo, restoredClone)
|
||||
restoredHead := gitOutput(t, restoredClone, "rev-parse", "--abbrev-ref", "HEAD")
|
||||
assert.Equal(t, branch, restoredHead, "clone from recovered bare repo should check out the current branch")
|
||||
assertFileContains(t, filepath.Join(restoredClone, "README.md"), "hello recovery")
|
||||
}
|
||||
+20
-20
@@ -14,7 +14,7 @@ require (
|
||||
replace github.com/seaweedfs/seaweedfs => ../../
|
||||
|
||||
require (
|
||||
cloud.google.com/go/auth v0.18.1 // indirect
|
||||
cloud.google.com/go/auth v0.17.0 // indirect
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.9.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 // indirect
|
||||
@@ -45,19 +45,19 @@ require (
|
||||
github.com/aws/aws-sdk-go v1.55.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.20 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.20 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.20 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.20 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.95.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.17 // indirect
|
||||
@@ -124,8 +124,8 @@ require (
|
||||
github.com/google/btree v1.1.3 // indirect
|
||||
github.com/google/s2a-go v0.1.9 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.17.0 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.15.0 // indirect
|
||||
github.com/gorilla/mux v1.8.1 // indirect
|
||||
github.com/gorilla/schema v1.4.1 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
@@ -147,9 +147,9 @@ require (
|
||||
github.com/jtolio/noiseconn v0.0.0-20231127013910-f6d9ecbf1de7 // indirect
|
||||
github.com/jzelinskie/whirlpool v0.0.0-20201016144138-0675e54bb004 // indirect
|
||||
github.com/karlseguin/ccache/v2 v2.0.8 // indirect
|
||||
github.com/klauspost/compress v1.18.5 // indirect
|
||||
github.com/klauspost/compress v1.18.4 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/klauspost/reedsolomon v1.13.3 // indirect
|
||||
github.com/klauspost/reedsolomon v1.13.0 // indirect
|
||||
github.com/koofr/go-httpclient v0.0.0-20240520111329-e20f8f203988 // indirect
|
||||
github.com/koofr/go-koofrclient v0.0.0-20221207135200-cbd7fc9ad6a6 // indirect
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
@@ -237,7 +237,7 @@ require (
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
github.com/zeebo/errs v1.4.0 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
github.com/zeebo/xxh3 v1.0.2 // indirect
|
||||
go.etcd.io/bbolt v1.4.3 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.9 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
@@ -247,18 +247,18 @@ require (
|
||||
go.opentelemetry.io/otel/trace v1.40.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.49.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
|
||||
golang.org/x/image v0.38.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||
golang.org/x/image v0.36.0 // indirect
|
||||
golang.org/x/net v0.49.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/term v0.41.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
golang.org/x/term v0.40.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
google.golang.org/api v0.267.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 // indirect
|
||||
google.golang.org/api v0.258.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2 // indirect
|
||||
google.golang.org/grpc/security/advancedtls v1.0.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
|
||||
+48
-48
@@ -13,8 +13,8 @@ cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKV
|
||||
cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs=
|
||||
cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc=
|
||||
cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY=
|
||||
cloud.google.com/go/auth v0.18.1 h1:IwTEx92GFUo2pJ6Qea0EU3zYvKnTAeRCODxfA/G5UWs=
|
||||
cloud.google.com/go/auth v0.18.1/go.mod h1:GfTYoS9G3CWpRA3Va9doKN9mjPGRS+v41jmZAhBzbrA=
|
||||
cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4=
|
||||
cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
|
||||
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
|
||||
@@ -116,8 +116,8 @@ github.com/aws/aws-sdk-go-v2 v1.41.4 h1:10f50G7WyU02T56ox1wWXq+zTX9I1zxG46HYuG1h
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.4/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.9 h1:ktda/mtAydeObvJXlHzyGpK1xcsLaP16zfUPDGoW90A=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.9/go.mod h1:U+fCQ+9QKsLW786BCfEjYRj34VVTbPdsLP3CHSYXMOI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.12 h1:oqtA6v+y5fZg//tcTWahyN9PEn5eDU/Wpvc2+kJ4aY8=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.12/go.mod h1:U3R1RtSHx6NB0DvEQFGyf/0sbrpJrluENHdPy1j/3TE=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.20 h1:zOgq3uezl5nznfoK3ODuqbhVg1JzAGDUhXOsU0IDCAo=
|
||||
@@ -130,18 +130,18 @@ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.20 h1:tN6W/hg+pkM+tf9XDk
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.20/go.mod h1:YJ898MhD067hSHA6xYCx5ts/jEd8BSOLtQDL3iZsvbc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R50aTBHkA7vu0lK+k=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17/go.mod h1:CO+WeGmIdj/MlPel2KwID9Gt7CNq4M65HUfBW97liM0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.16 h1:CjMzUs78RDDv4ROu3JnJn/Ig1r6ZD7/T2DXLLRpejic=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.16/go.mod h1:uVW4OLBqbJXSHJYA9svT9BluSvvwbzLQ2Crf6UPzR3c=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 h1:5EniKhLZe4xzL7a+fU3C2tfUN4nWIqlLesfrjkuPFTY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7/go.mod h1:x0nZssQ3qZSnIcePWLvcoFisRXJzcTVvYpAAdYX8+GI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 h1:Z5EiPIzXKewUQK0QTMkutjiaPVeVYXX7KIqhXu/0fXs=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8/go.mod h1:FsTpJtvC4U1fyDXk7c71XoDv3HlRm8V3NiYLeYLh5YE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.7 h1:DIBqIrJ7hv+e4CmIk2z3pyKT+3B6qVMgRsawHiR3qso=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.7/go.mod h1:vLm00xmBke75UmpNvOcZQ/Q30ZFjbczeLFqGx5urmGo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.20 h1:2HvVAIq+YqgGotK6EkMf+KIEqTISmTYh5zLpYyeTo1Y=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.20/go.mod h1:V4X406Y666khGa8ghKmphma/7C0DAtEQYhkq9z4vpbk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 h1:bGeHBsGZx0Dvu/eJC0Lh9adJa3M1xREcndxLNZlve2U=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17/go.mod h1:dcW24lbU0CzHusTE8LLHhRLI42ejmINN8Lcr22bwh/g=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0 h1:oeu8VPlOre74lBA/PMhxa5vewaMIMmILM+RraSyB8KA=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0/go.mod h1:5jggDlZ2CLQhwJBiZJb4vfk4f0GxWdEDruWKEJ1xOdo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.16 h1:NSbvS17MlI2lurYgXnCOLvCFX38sBW4eiVER7+kkgsU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.16/go.mod h1:SwT8Tmqd4sA6G1qaGdzWCJN99bUmPGHfRwwq3G5Qb+A=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.95.0 h1:MIWra+MSq53CFaXXAywB2qg9YvVZifkk6vEGl/1Qor0=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.95.0/go.mod h1:79S2BdqCJpScXZA2y+cpZuocWsjGjJINyXnOsf5DTz8=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.8 h1:0GFOLzEbOyZABS3PhYfBIx2rNBACYcKty+XGkTgw1ow=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.8/go.mod h1:LXypKvk85AROkKhOG6/YEcHFPoX+prKTowKnVdcaIxE=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.13 h1:kiIDLZ005EcKomYYITtfsjn7dtOwHDOFy7IbPXKek2o=
|
||||
@@ -385,12 +385,12 @@ github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA=
|
||||
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
||||
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
||||
github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc=
|
||||
github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY=
|
||||
github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo=
|
||||
github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc=
|
||||
github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g=
|
||||
github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k=
|
||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||
@@ -467,12 +467,12 @@ github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRt
|
||||
github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
|
||||
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
|
||||
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/reedsolomon v1.13.3 h1:01GwnO2xoCSaM0ShP4qwl+FsHg3csFShC6Tu/RS1ji0=
|
||||
github.com/klauspost/reedsolomon v1.13.3/go.mod h1:yjqqjgMTQkBUHSG97/rm4zipffCNbCiZcB3kTqr++sQ=
|
||||
github.com/klauspost/reedsolomon v1.13.0 h1:E0Cmgf2kMuhZTj6eefnvpKC4/Q4jhCi9YIjcZjK4arc=
|
||||
github.com/klauspost/reedsolomon v1.13.0/go.mod h1:ggJT9lc71Vu+cSOPBlxGvBN6TfAS77qB4fp8vJ05NSA=
|
||||
github.com/koofr/go-httpclient v0.0.0-20240520111329-e20f8f203988 h1:CjEMN21Xkr9+zwPmZPaJJw+apzVbjGL5uK/6g9Q2jGU=
|
||||
github.com/koofr/go-httpclient v0.0.0-20240520111329-e20f8f203988/go.mod h1:/agobYum3uo/8V6yPVnq+R82pyVGCeuWW5arT4Txn8A=
|
||||
github.com/koofr/go-koofrclient v0.0.0-20221207135200-cbd7fc9ad6a6 h1:FHVoZMOVRA+6/y4yRlbiR3WvsrOcKBd/f64H7YiWR2U=
|
||||
@@ -739,8 +739,8 @@ github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM=
|
||||
github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4=
|
||||
github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=
|
||||
github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
|
||||
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
|
||||
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
|
||||
@@ -787,8 +787,8 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -799,12 +799,12 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
|
||||
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
|
||||
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
|
||||
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
|
||||
golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
|
||||
golang.org/x/image v0.36.0 h1:Iknbfm1afbgtwPTmHnS2gTM/6PPZfH+z2EFuOkSbqwc=
|
||||
golang.org/x/image v0.36.0/go.mod h1:YsWD2TyyGKiIX1kZlu9QfKIsQ4nAAK9bdgdrIsE7xy4=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
@@ -869,8 +869,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -894,8 +894,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -959,8 +959,8 @@ golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
|
||||
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
|
||||
golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
|
||||
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -976,8 +976,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
@@ -1030,14 +1030,14 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
|
||||
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
|
||||
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
|
||||
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
|
||||
@@ -1054,8 +1054,8 @@ google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0M
|
||||
google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE=
|
||||
google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM=
|
||||
google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc=
|
||||
google.golang.org/api v0.267.0 h1:w+vfWPMPYeRs8qH1aYYsFX68jMls5acWl/jocfLomwE=
|
||||
google.golang.org/api v0.267.0/go.mod h1:Jzc0+ZfLnyvXma3UtaTl023TdhZu6OMBP9tJ+0EmFD0=
|
||||
google.golang.org/api v0.258.0 h1:IKo1j5FBlN74fe5isA2PVozN3Y5pwNKriEgAXPOkDAc=
|
||||
google.golang.org/api v0.258.0/go.mod h1:qhOMTQEZ6lUps63ZNq9jhODswwjkjYYguA7fA3TBFww=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
@@ -1091,12 +1091,12 @@ google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7Fc
|
||||
google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM=
|
||||
google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20 h1:7ei4lp52gK1uSejlA8AZl5AJjeLUOHBQscRQZUgAcu0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20/go.mod h1:ZdbssH/1SOVnjnDlXzxDHK2MCidiqXtbYccJNzNYPEE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 h1:Jr5R2J6F6qWyzINc+4AM8t5pfUz6beZpHp678GNrMbE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/genproto v0.0.0-20251124214823-79d6a2a48846 h1:dDbsTLIK7EzwUq36kCSAsk0slouq/S0tWHeeGi97cD8=
|
||||
google.golang.org/genproto v0.0.0-20251124214823-79d6a2a48846/go.mod h1:PP0g88Dz3C7hRAfbQCQggeWAXjuqGsNPLE4s7jh0RGU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2 h1:2I6GHUeJ/4shcDpoUlLs/2WPnhg7yJwvXtqcMJt9liA=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251213004720-97cd9d5aeac2/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
|
||||
@@ -11,11 +11,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// VolumeServer provides a minimal volume server for erasure coding tests.
|
||||
@@ -198,25 +196,12 @@ func (v *VolumeServer) CopyFile(req *volume_server_pb.CopyFileRequest, stream vo
|
||||
defer file.Close()
|
||||
|
||||
buf := make([]byte, 64*1024)
|
||||
remaining := int64(req.GetStopOffset())
|
||||
for {
|
||||
if remaining == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
readBuf := buf
|
||||
if remaining > 0 && remaining < int64(len(buf)) {
|
||||
readBuf = buf[:remaining]
|
||||
}
|
||||
|
||||
n, readErr := file.Read(readBuf)
|
||||
n, readErr := file.Read(buf)
|
||||
if n > 0 {
|
||||
if err := stream.Send(&volume_server_pb.CopyFileResponse{FileContent: readBuf[:n]}); err != nil {
|
||||
if err := stream.Send(&volume_server_pb.CopyFileResponse{FileContent: buf[:n]}); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining > 0 {
|
||||
remaining -= int64(n)
|
||||
}
|
||||
}
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
@@ -322,21 +307,10 @@ func (v *VolumeServer) ReadVolumeFileStatus(ctx context.Context, req *volume_ser
|
||||
v.mu.Lock()
|
||||
v.readFileStatusCalls++
|
||||
v.mu.Unlock()
|
||||
|
||||
datInfo, err := os.Stat(v.filePath(req.VolumeId, ".dat"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
idxInfo, err := os.Stat(v.filePath(req.VolumeId, ".idx"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &volume_server_pb.ReadVolumeFileStatusResponse{
|
||||
VolumeId: req.VolumeId,
|
||||
DatFileSize: uint64(datInfo.Size()),
|
||||
IdxFileSize: uint64(idxInfo.Size()),
|
||||
DatFileSize: 1024,
|
||||
IdxFileSize: 16,
|
||||
FileCount: 1,
|
||||
}, nil
|
||||
}
|
||||
@@ -375,27 +349,7 @@ func (v *VolumeServer) VolumeCopy(req *volume_server_pb.VolumeCopyRequest, strea
|
||||
v.volumeCopyCalls++
|
||||
v.mu.Unlock()
|
||||
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
var statusResp *volume_server_pb.ReadVolumeFileStatusResponse
|
||||
if err := operation.WithVolumeServerClient(false, pb.ServerAddress(req.SourceDataNode), dialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
var readErr error
|
||||
statusResp, readErr = client.ReadVolumeFileStatus(stream.Context(), &volume_server_pb.ReadVolumeFileStatusRequest{
|
||||
VolumeId: req.VolumeId,
|
||||
})
|
||||
return readErr
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := v.copyRemoteFile(stream.Context(), req.SourceDataNode, req.VolumeId, ".dat", statusResp.DatFileSize, dialOption); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := v.copyRemoteFile(stream.Context(), req.SourceDataNode, req.VolumeId, ".idx", statusResp.IdxFileSize, dialOption); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := stream.Send(&volume_server_pb.VolumeCopyResponse{ProcessedBytes: int64(statusResp.DatFileSize + statusResp.IdxFileSize)}); err != nil {
|
||||
if err := stream.Send(&volume_server_pb.VolumeCopyResponse{ProcessedBytes: 1024}); err != nil {
|
||||
return err
|
||||
}
|
||||
return stream.Send(&volume_server_pb.VolumeCopyResponse{LastAppendAtNs: uint64(time.Now().UnixNano())})
|
||||
@@ -414,44 +368,3 @@ func (v *VolumeServer) VolumeTailReceiver(ctx context.Context, req *volume_serve
|
||||
v.mu.Unlock()
|
||||
return &volume_server_pb.VolumeTailReceiverResponse{}, nil
|
||||
}
|
||||
|
||||
func (v *VolumeServer) copyRemoteFile(ctx context.Context, sourceDataNode string, volumeID uint32, ext string, fileSize uint64, dialOption grpc.DialOption) error {
|
||||
path := v.filePath(volumeID, ext)
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
return operation.WithVolumeServerClient(true, pb.ServerAddress(sourceDataNode), dialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
stream, err := client.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
|
||||
VolumeId: volumeID,
|
||||
Ext: ext,
|
||||
StopOffset: fileSize,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if recvErr != nil {
|
||||
return recvErr
|
||||
}
|
||||
if len(resp.FileContent) == 0 {
|
||||
continue
|
||||
}
|
||||
if _, err := file.Write(resp.FileContent); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -16,8 +16,6 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const testVolumeDatSize = 1 * 1024 * 1024
|
||||
|
||||
func TestVolumeBalanceExecutionIntegration(t *testing.T) {
|
||||
volumeID := uint32(303)
|
||||
|
||||
@@ -33,7 +31,6 @@ func TestVolumeBalanceExecutionIntegration(t *testing.T) {
|
||||
|
||||
source := pluginworkers.NewVolumeServer(t, "")
|
||||
target := pluginworkers.NewVolumeServer(t, "")
|
||||
pluginworkers.WriteTestVolumeFiles(t, source.BaseDir(), volumeID, testVolumeDatSize)
|
||||
|
||||
job := &plugin_pb.JobSpec{
|
||||
JobId: fmt.Sprintf("balance-job-%d", volumeID),
|
||||
@@ -87,9 +84,6 @@ func TestVolumeBalanceBatchExecutionIntegration(t *testing.T) {
|
||||
|
||||
// Build a batch job with 3 volume moves from source → target.
|
||||
volumeIDs := []uint32{401, 402, 403}
|
||||
for _, vid := range volumeIDs {
|
||||
pluginworkers.WriteTestVolumeFiles(t, source.BaseDir(), vid, testVolumeDatSize)
|
||||
}
|
||||
moves := make([]*worker_pb.BalanceMoveSpec, len(volumeIDs))
|
||||
for i, vid := range volumeIDs {
|
||||
moves[i] = &worker_pb.BalanceMoveSpec{
|
||||
@@ -145,11 +139,10 @@ func TestVolumeBalanceBatchExecutionIntegration(t *testing.T) {
|
||||
require.True(t, deletedVols[vid], "volume %d should have been deleted from source", vid)
|
||||
}
|
||||
|
||||
// Each move reads source status once before copy and once inside the
|
||||
// target's fake VolumeCopy implementation, then reads target status once
|
||||
// before deleting the source.
|
||||
require.Equal(t, len(volumeIDs)*2, source.ReadFileStatusCount(),
|
||||
"each move should read source volume status before copy and during target copy")
|
||||
// Pre-delete verification should have called ReadVolumeFileStatus on both
|
||||
// source and target for each volume.
|
||||
require.Equal(t, len(volumeIDs), source.ReadFileStatusCount(),
|
||||
"each move should read source volume status before delete")
|
||||
require.Equal(t, len(volumeIDs), target.ReadFileStatusCount(),
|
||||
"each move should read target volume status before delete")
|
||||
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
# S3 delete regression test harness
|
||||
|
||||
.PHONY: all test help build-weed check-deps start-server stop-server test-delete test-with-server clean logs
|
||||
|
||||
WEED_BINARY := ../../../weed/weed_binary
|
||||
S3_PORT := 8333
|
||||
TEST_TIMEOUT := 10m
|
||||
SERVER_DIR := ./test-volume-data
|
||||
S3_CONFIG := ./test_s3.json
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
all: test
|
||||
|
||||
test: test-with-server
|
||||
|
||||
help:
|
||||
@echo "S3 delete regression test harness"
|
||||
@echo ""
|
||||
@echo "Available targets:"
|
||||
@echo " build-weed - Build the SeaweedFS binary"
|
||||
@echo " start-server - Start SeaweedFS with S3 enabled"
|
||||
@echo " stop-server - Stop the test server"
|
||||
@echo " test-delete - Run delete regression tests"
|
||||
@echo " test-with-server - Start server, run tests, stop server"
|
||||
@echo " logs - Show server logs"
|
||||
@echo " clean - Remove test artifacts"
|
||||
|
||||
build-weed:
|
||||
@echo "Building SeaweedFS binary..."
|
||||
@cd ../../../weed && go build -o weed_binary .
|
||||
@chmod +x $(WEED_BINARY)
|
||||
|
||||
check-deps: build-weed
|
||||
@command -v go >/dev/null 2>&1 || (echo "Go is required but not installed" && exit 1)
|
||||
@test -f $(WEED_BINARY) || (echo "SeaweedFS binary not found at $(WEED_BINARY)" && exit 1)
|
||||
@test -f $(S3_CONFIG) || (echo "S3 config not found at $(S3_CONFIG)" && exit 1)
|
||||
|
||||
start-server: check-deps
|
||||
@echo "Starting SeaweedFS server for delete regression tests..."
|
||||
@rm -f weed-server.pid
|
||||
@mkdir -p $(SERVER_DIR)
|
||||
@$(WEED_BINARY) mini \
|
||||
-dir=$(SERVER_DIR) \
|
||||
-s3 \
|
||||
-s3.port=$(S3_PORT) \
|
||||
-s3.config=$(S3_CONFIG) \
|
||||
-master.peers=none \
|
||||
> weed-test.log 2>&1 & echo $$! > weed-server.pid
|
||||
@for i in $$(seq 1 60); do \
|
||||
if curl -sS -o /dev/null http://127.0.0.1:$(S3_PORT)/ >/dev/null 2>&1; then \
|
||||
echo "SeaweedFS S3 server is ready on port $(S3_PORT)"; \
|
||||
exit 0; \
|
||||
fi; \
|
||||
sleep 1; \
|
||||
done; \
|
||||
echo "SeaweedFS S3 server failed to start"; \
|
||||
echo "=== Server logs ==="; \
|
||||
test -f weed-test.log && cat weed-test.log || true; \
|
||||
exit 1
|
||||
|
||||
stop-server:
|
||||
@echo "Stopping SeaweedFS server..."
|
||||
@if [ -f weed-server.pid ]; then \
|
||||
SERVER_PID=$$(cat weed-server.pid); \
|
||||
kill -TERM $$SERVER_PID 2>/dev/null || true; \
|
||||
for i in $$(seq 1 20); do \
|
||||
if ! kill -0 $$SERVER_PID >/dev/null 2>&1; then \
|
||||
break; \
|
||||
fi; \
|
||||
sleep 0.1; \
|
||||
done; \
|
||||
if kill -0 $$SERVER_PID >/dev/null 2>&1; then \
|
||||
kill -KILL $$SERVER_PID 2>/dev/null || true; \
|
||||
fi; \
|
||||
rm -f weed-server.pid; \
|
||||
fi
|
||||
|
||||
test-delete: check-deps
|
||||
@echo "Running delete regression tests..."
|
||||
@go test -v -timeout=$(TEST_TIMEOUT) .
|
||||
|
||||
test-with-server: start-server
|
||||
@trap "$(MAKE) stop-server" EXIT; \
|
||||
$(MAKE) test-delete || (echo "=== Last 100 lines of server logs ===" && tail -100 weed-test.log && exit 1)
|
||||
@$(MAKE) stop-server
|
||||
|
||||
logs:
|
||||
@if test -f weed-test.log; then \
|
||||
tail -f weed-test.log; \
|
||||
else \
|
||||
echo "No server log file found."; \
|
||||
fi
|
||||
|
||||
clean:
|
||||
@$(MAKE) stop-server
|
||||
@rm -f weed-test.log weed-server.pid
|
||||
@rm -rf $(SERVER_DIR)
|
||||
@@ -1,135 +0,0 @@
|
||||
package delete
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConditionalDeleteIfMatchOnLatestVersion(t *testing.T) {
|
||||
client := getTestClient(t)
|
||||
bucket := createTestBucket(t, client)
|
||||
defer cleanupBucket(t, client, bucket)
|
||||
|
||||
key := "conditional-delete.txt"
|
||||
putResp, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader([]byte("versioned body")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, putResp.ETag)
|
||||
|
||||
_, err = client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
IfMatch: aws.String(`"not-the-current-etag"`),
|
||||
})
|
||||
require.Error(t, err, "DeleteObject should reject a mismatched If-Match header")
|
||||
|
||||
var apiErr smithy.APIError
|
||||
if assert.True(t, errors.As(err, &apiErr), "Expected smithy API error for conditional delete") {
|
||||
assert.Equal(t, "PreconditionFailed", apiErr.ErrorCode())
|
||||
}
|
||||
|
||||
_, err = client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err, "Object should remain current after a failed conditional delete")
|
||||
|
||||
deleteResp, err := client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
IfMatch: putResp.ETag,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, deleteResp.DeleteMarker)
|
||||
assert.True(t, *deleteResp.DeleteMarker, "Successful conditional delete on a versioned bucket should create a delete marker")
|
||||
require.NotNil(t, deleteResp.VersionId)
|
||||
|
||||
_, err = client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
require.Error(t, err, "Delete marker should hide the current object after a successful conditional delete")
|
||||
}
|
||||
|
||||
func TestConditionalMultiDeletePerObjectETag(t *testing.T) {
|
||||
client := getTestClient(t)
|
||||
bucket := createTestBucket(t, client)
|
||||
defer cleanupBucket(t, client, bucket)
|
||||
|
||||
okKey := "delete-ok.txt"
|
||||
failKey := "delete-fail.txt"
|
||||
|
||||
okPutResp, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(okKey),
|
||||
Body: bytes.NewReader([]byte("delete me")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, okPutResp.ETag)
|
||||
|
||||
_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(failKey),
|
||||
Body: bytes.NewReader([]byte("keep me")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
deleteResp, err := client.DeleteObjects(context.TODO(), &s3.DeleteObjectsInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Delete: &types.Delete{
|
||||
Objects: []types.ObjectIdentifier{
|
||||
{
|
||||
Key: aws.String(okKey),
|
||||
ETag: okPutResp.ETag,
|
||||
},
|
||||
{
|
||||
Key: aws.String(failKey),
|
||||
ETag: aws.String(`"mismatched-etag"`),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, deleteResp.Deleted, 1, "One object should satisfy its ETag precondition")
|
||||
require.Len(t, deleteResp.Errors, 1, "One object should report a precondition failure")
|
||||
deletedKeys := make([]string, 0, len(deleteResp.Deleted))
|
||||
for _, deleted := range deleteResp.Deleted {
|
||||
deletedKeys = append(deletedKeys, aws.ToString(deleted.Key))
|
||||
}
|
||||
assert.Contains(t, deletedKeys, okKey)
|
||||
|
||||
var matchedError *types.Error
|
||||
for i := range deleteResp.Errors {
|
||||
if aws.ToString(deleteResp.Errors[i].Key) == failKey {
|
||||
matchedError = &deleteResp.Errors[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if assert.NotNil(t, matchedError, "Expected error entry for failed key") {
|
||||
assert.Equal(t, "PreconditionFailed", aws.ToString(matchedError.Code))
|
||||
}
|
||||
|
||||
_, err = client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(okKey),
|
||||
})
|
||||
require.Error(t, err, "Successfully deleted key should no longer be current")
|
||||
|
||||
_, err = client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(failKey),
|
||||
})
|
||||
require.NoError(t, err, "Object with mismatched ETag should remain untouched")
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"identities": [
|
||||
{
|
||||
"name": "admin",
|
||||
"credentials": [
|
||||
{
|
||||
"accessKey": "admin",
|
||||
"secretKey": "admin"
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
"Admin",
|
||||
"Read",
|
||||
"List",
|
||||
"Tagging",
|
||||
"Write"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,523 +0,0 @@
|
||||
package distributed_lock
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
const (
|
||||
distributedLockTestRegion = "us-east-1"
|
||||
distributedLockTestAccessKey = "some_access_key1"
|
||||
distributedLockTestSecretKey = "some_secret_key1"
|
||||
distributedLockTestGroup = "distributed-lock-it"
|
||||
)
|
||||
|
||||
type distributedLockCluster struct {
|
||||
t testing.TB
|
||||
baseDir string
|
||||
configDir string
|
||||
logsDir string
|
||||
keepLogs bool
|
||||
|
||||
weedBinary string
|
||||
filerGroup string
|
||||
s3Config string
|
||||
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
volumePort int
|
||||
volumeGrpcPort int
|
||||
filerPorts []int
|
||||
filerGrpcPorts []int
|
||||
s3Ports []int
|
||||
s3GrpcPorts []int
|
||||
|
||||
masterCmd *exec.Cmd
|
||||
volumeCmd *exec.Cmd
|
||||
filerCmds []*exec.Cmd
|
||||
s3Cmds []*exec.Cmd
|
||||
logFiles []*os.File
|
||||
|
||||
cleanupOnce sync.Once
|
||||
}
|
||||
|
||||
type s3IdentityConfig struct {
|
||||
Identities []s3Identity `json:"identities"`
|
||||
}
|
||||
|
||||
type s3Identity struct {
|
||||
Name string `json:"name"`
|
||||
Credentials []s3Credential `json:"credentials,omitempty"`
|
||||
Actions []string `json:"actions"`
|
||||
}
|
||||
|
||||
type s3Credential struct {
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
}
|
||||
|
||||
func startDistributedLockCluster(t *testing.T) *distributedLockCluster {
|
||||
t.Helper()
|
||||
|
||||
weedBinary, err := framework.FindOrBuildWeedBinary()
|
||||
require.NoError(t, err, "resolve weed binary")
|
||||
|
||||
baseDir, err := os.MkdirTemp("", "seaweedfs_s3_distributed_lock_")
|
||||
require.NoError(t, err, "create temp directory")
|
||||
|
||||
cluster := &distributedLockCluster{
|
||||
t: t,
|
||||
baseDir: baseDir,
|
||||
configDir: filepath.Join(baseDir, "config"),
|
||||
logsDir: filepath.Join(baseDir, "logs"),
|
||||
keepLogs: os.Getenv("S3_DISTRIBUTED_LOCK_KEEP_LOGS") == "1",
|
||||
weedBinary: weedBinary,
|
||||
filerGroup: distributedLockTestGroup,
|
||||
filerCmds: make([]*exec.Cmd, 0, 2),
|
||||
s3Cmds: make([]*exec.Cmd, 0, 2),
|
||||
}
|
||||
t.Cleanup(cluster.Stop)
|
||||
|
||||
dirs := []string{
|
||||
cluster.configDir,
|
||||
cluster.logsDir,
|
||||
filepath.Join(baseDir, "master"),
|
||||
filepath.Join(baseDir, "volume"),
|
||||
filepath.Join(baseDir, "filer0"),
|
||||
filepath.Join(baseDir, "filer1"),
|
||||
}
|
||||
for _, dir := range dirs {
|
||||
require.NoError(t, os.MkdirAll(dir, 0o755), "create %s", dir)
|
||||
}
|
||||
|
||||
ports, err := allocatePorts(12)
|
||||
require.NoError(t, err, "allocate ports")
|
||||
cluster.masterPort = ports[0]
|
||||
cluster.masterGrpcPort = ports[1]
|
||||
cluster.volumePort = ports[2]
|
||||
cluster.volumeGrpcPort = ports[3]
|
||||
cluster.filerPorts = []int{ports[4], ports[6]}
|
||||
cluster.filerGrpcPorts = []int{ports[5], ports[7]}
|
||||
cluster.s3Ports = []int{ports[8], ports[10]}
|
||||
cluster.s3GrpcPorts = []int{ports[9], ports[11]}
|
||||
|
||||
require.NoError(t, cluster.writeSecurityConfig(), "write security config")
|
||||
require.NoError(t, cluster.writeS3Config(), "write s3 config")
|
||||
|
||||
require.NoError(t, cluster.startMaster(), "start master")
|
||||
require.NoError(t, cluster.waitForHTTP("http://"+cluster.masterHTTPAddress()+"/dir/status", 30*time.Second), "wait for master\n%s", cluster.tailLog("master.log"))
|
||||
|
||||
require.NoError(t, cluster.startVolume(), "start volume")
|
||||
require.NoError(t, cluster.waitForHTTP("http://"+cluster.volumeHTTPAddress()+"/status", 30*time.Second), "wait for volume\n%s", cluster.tailLog("volume.log"))
|
||||
require.NoError(t, cluster.waitForTCP(cluster.volumeGRPCAddress(), 30*time.Second), "wait for volume grpc\n%s", cluster.tailLog("volume.log"))
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
require.NoError(t, cluster.startFiler(i), "start filer %d", i)
|
||||
require.NoError(t, cluster.waitForTCP(cluster.filerGRPCAddress(i), 30*time.Second), "wait for filer %d grpc\n%s", i, cluster.tailLog(fmt.Sprintf("filer%d.log", i)))
|
||||
}
|
||||
require.NoError(t, cluster.waitForFilerCount(2, 30*time.Second), "wait for filer group registration")
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
require.NoError(t, cluster.startS3(i), "start s3 %d", i)
|
||||
client := cluster.newS3Client(t, cluster.s3Endpoint(i))
|
||||
require.NoError(t, cluster.waitForS3Ready(client, 30*time.Second), "wait for s3 %d\n%s", i, cluster.tailLog(fmt.Sprintf("s3-%d.log", i)))
|
||||
}
|
||||
|
||||
return cluster
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) Stop() {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.cleanupOnce.Do(func() {
|
||||
for i := len(c.s3Cmds) - 1; i >= 0; i-- {
|
||||
stopProcess(c.s3Cmds[i])
|
||||
}
|
||||
for i := len(c.filerCmds) - 1; i >= 0; i-- {
|
||||
stopProcess(c.filerCmds[i])
|
||||
}
|
||||
stopProcess(c.volumeCmd)
|
||||
stopProcess(c.masterCmd)
|
||||
|
||||
for _, f := range c.logFiles {
|
||||
_ = f.Close()
|
||||
}
|
||||
|
||||
if !c.keepLogs && !c.t.Failed() {
|
||||
_ = os.RemoveAll(c.baseDir)
|
||||
} else if c.baseDir != "" {
|
||||
c.t.Logf("distributed lock integration logs kept at %s", c.baseDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) masterHTTPAddress() string {
|
||||
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.masterPort))
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) masterGRPCAddress() string {
|
||||
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.masterGrpcPort))
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) volumeHTTPAddress() string {
|
||||
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumePort))
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) volumeGRPCAddress() string {
|
||||
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.volumeGrpcPort))
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) filerServerAddress(index int) pb.ServerAddress {
|
||||
return pb.NewServerAddress("127.0.0.1", c.filerPorts[index], c.filerGrpcPorts[index])
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) filerGRPCAddress(index int) string {
|
||||
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.filerGrpcPorts[index]))
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) s3Endpoint(index int) string {
|
||||
return fmt.Sprintf("http://127.0.0.1:%d", c.s3Ports[index])
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) startMaster() error {
|
||||
logFile, err := c.openLog("master.log")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"-config_dir=" + c.configDir,
|
||||
"master",
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-port=" + strconv.Itoa(c.masterPort),
|
||||
"-port.grpc=" + strconv.Itoa(c.masterGrpcPort),
|
||||
"-mdir=" + filepath.Join(c.baseDir, "master"),
|
||||
"-peers=none",
|
||||
"-volumeSizeLimitMB=32",
|
||||
"-defaultReplication=000",
|
||||
}
|
||||
|
||||
c.masterCmd = exec.Command(c.weedBinary, args...)
|
||||
c.masterCmd.Dir = c.baseDir
|
||||
c.masterCmd.Stdout = logFile
|
||||
c.masterCmd.Stderr = logFile
|
||||
return c.masterCmd.Start()
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) startVolume() error {
|
||||
logFile, err := c.openLog("volume.log")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
masterAddress := string(pb.NewServerAddress("127.0.0.1", c.masterPort, c.masterGrpcPort))
|
||||
|
||||
args := []string{
|
||||
"-config_dir=" + c.configDir,
|
||||
"volume",
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-port=" + strconv.Itoa(c.volumePort),
|
||||
"-port.grpc=" + strconv.Itoa(c.volumeGrpcPort),
|
||||
"-dir=" + filepath.Join(c.baseDir, "volume"),
|
||||
"-max=16",
|
||||
"-master=" + masterAddress,
|
||||
"-readMode=proxy",
|
||||
}
|
||||
|
||||
c.volumeCmd = exec.Command(c.weedBinary, args...)
|
||||
c.volumeCmd.Dir = c.baseDir
|
||||
c.volumeCmd.Stdout = logFile
|
||||
c.volumeCmd.Stderr = logFile
|
||||
return c.volumeCmd.Start()
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) startFiler(index int) error {
|
||||
logFile, err := c.openLog(fmt.Sprintf("filer%d.log", index))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
masterAddress := string(pb.NewServerAddress("127.0.0.1", c.masterPort, c.masterGrpcPort))
|
||||
|
||||
args := []string{
|
||||
"-config_dir=" + c.configDir,
|
||||
"filer",
|
||||
"-master=" + masterAddress,
|
||||
"-filerGroup=" + c.filerGroup,
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-port=" + strconv.Itoa(c.filerPorts[index]),
|
||||
"-port.grpc=" + strconv.Itoa(c.filerGrpcPorts[index]),
|
||||
"-defaultStoreDir=" + filepath.Join(c.baseDir, fmt.Sprintf("filer%d", index)),
|
||||
}
|
||||
|
||||
cmd := exec.Command(c.weedBinary, args...)
|
||||
cmd.Dir = c.baseDir
|
||||
cmd.Stdout = logFile
|
||||
cmd.Stderr = logFile
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.filerCmds = append(c.filerCmds, cmd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) startS3(index int) error {
|
||||
logFile, err := c.openLog(fmt.Sprintf("s3-%d.log", index))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
filers := []string{string(c.filerServerAddress(0)), string(c.filerServerAddress(1))}
|
||||
if index%2 == 1 {
|
||||
filers[0], filers[1] = filers[1], filers[0]
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"-config_dir=" + c.configDir,
|
||||
"s3",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-port=" + strconv.Itoa(c.s3Ports[index]),
|
||||
"-port.grpc=" + strconv.Itoa(c.s3GrpcPorts[index]),
|
||||
"-port.iceberg=0",
|
||||
"-filer=" + strings.Join(filers, ","),
|
||||
"-config=" + c.s3Config,
|
||||
"-iam.readOnly=false",
|
||||
}
|
||||
|
||||
cmd := exec.Command(c.weedBinary, args...)
|
||||
cmd.Dir = c.baseDir
|
||||
cmd.Stdout = logFile
|
||||
cmd.Stderr = logFile
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.s3Cmds = append(c.s3Cmds, cmd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) writeSecurityConfig() error {
|
||||
return os.WriteFile(filepath.Join(c.configDir, "security.toml"), []byte("# generated for distributed lock integration tests\n"), 0o644)
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) writeS3Config() error {
|
||||
configPath := filepath.Join(c.configDir, "s3.json")
|
||||
payload := s3IdentityConfig{
|
||||
Identities: []s3Identity{
|
||||
{
|
||||
Name: "distributed-lock-admin",
|
||||
Credentials: []s3Credential{
|
||||
{
|
||||
AccessKey: distributedLockTestAccessKey,
|
||||
SecretKey: distributedLockTestSecretKey,
|
||||
},
|
||||
},
|
||||
Actions: []string{"Admin", "Read", "List", "Tagging", "Write"},
|
||||
},
|
||||
},
|
||||
}
|
||||
data, err := json.MarshalIndent(payload, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(configPath, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
c.s3Config = configPath
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) newS3Client(t testing.TB, endpoint string) *s3.Client {
|
||||
t.Helper()
|
||||
|
||||
cfg, err := config.LoadDefaultConfig(context.Background(),
|
||||
config.WithRegion(distributedLockTestRegion),
|
||||
config.WithRetryMaxAttempts(1),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
|
||||
distributedLockTestAccessKey,
|
||||
distributedLockTestSecretKey,
|
||||
"",
|
||||
)),
|
||||
)
|
||||
require.NoError(t, err, "load aws config")
|
||||
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) waitForS3Ready(client *s3.Client, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
_, err := client.ListBuckets(ctx, &s3.ListBucketsInput{})
|
||||
cancel()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("timed out waiting for s3 readiness")
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) waitForFilerCount(expected int, timeout time.Duration) error {
|
||||
conn, err := grpc.NewClient(c.masterGRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
client := master_pb.NewSeaweedClient(conn)
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
resp, err := client.ListClusterNodes(ctx, &master_pb.ListClusterNodesRequest{
|
||||
ClientType: "filer",
|
||||
FilerGroup: c.filerGroup,
|
||||
})
|
||||
cancel()
|
||||
if err == nil && len(resp.ClusterNodes) >= expected {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("timed out waiting for %d filers in group %q", expected, c.filerGroup)
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) waitForHTTP(url string, timeout time.Duration) error {
|
||||
client := &net.Dialer{Timeout: time.Second}
|
||||
httpClient := &httpClientWithDialer{dialer: client}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if err := httpClient.Get(url); err == nil {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("timed out waiting for http %s", url)
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) waitForTCP(addr string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
conn, err := net.DialTimeout("tcp", addr, time.Second)
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("timed out waiting for tcp %s", addr)
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) openLog(name string) (*os.File, error) {
|
||||
f, err := os.Create(filepath.Join(c.logsDir, name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.logFiles = append(c.logFiles, f)
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) tailLog(name string) string {
|
||||
f, err := os.Open(filepath.Join(c.logsDir, name))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
lines := make([]string, 0, 40)
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
if len(lines) > 40 {
|
||||
lines = lines[1:]
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func allocatePorts(count int) ([]int, error) {
|
||||
listeners := make([]net.Listener, 0, count)
|
||||
ports := make([]int, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
for _, openListener := range listeners {
|
||||
_ = openListener.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
ports = append(ports, l.Addr().(*net.TCPAddr).Port)
|
||||
}
|
||||
for _, l := range listeners {
|
||||
_ = l.Close()
|
||||
}
|
||||
return ports, nil
|
||||
}
|
||||
|
||||
func stopProcess(cmd *exec.Cmd) {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return
|
||||
}
|
||||
|
||||
_ = cmd.Process.Signal(os.Interrupt)
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- cmd.Wait()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
_ = cmd.Process.Kill()
|
||||
<-done
|
||||
}
|
||||
}
|
||||
|
||||
type httpClientWithDialer struct {
|
||||
dialer *net.Dialer
|
||||
}
|
||||
|
||||
func (h *httpClientWithDialer) Get(url string) error {
|
||||
client := &http.Client{
|
||||
Timeout: time.Second,
|
||||
Transport: &http.Transport{
|
||||
DialContext: h.dialer.DialContext,
|
||||
},
|
||||
}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package distributed_lock
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConditionalPutIfNoneMatchDistributedLockAcrossS3Gateways(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping distributed lock integration test in short mode")
|
||||
}
|
||||
|
||||
cluster := startDistributedLockCluster(t)
|
||||
clientA := cluster.newS3Client(t, cluster.s3Endpoint(0))
|
||||
clientB := cluster.newS3Client(t, cluster.s3Endpoint(1))
|
||||
|
||||
bucket := fmt.Sprintf("distributed-lock-%d", time.Now().UnixNano())
|
||||
_, err := clientA.CreateBucket(context.Background(), &s3.CreateBucketInput{
|
||||
Bucket: aws.String(bucket),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
_, err := clientB.HeadBucket(context.Background(), &s3.HeadBucketInput{
|
||||
Bucket: aws.String(bucket),
|
||||
})
|
||||
return err == nil
|
||||
}, 30*time.Second, 200*time.Millisecond, "bucket should replicate to the second filer-backed gateway")
|
||||
|
||||
keysByOwner := cluster.findLockOwnerKeys(bucket, "conditional-put")
|
||||
require.Len(t, keysByOwner, len(cluster.filerPorts), "should exercise both filer lock owners")
|
||||
|
||||
for owner, key := range keysByOwner {
|
||||
owner := owner
|
||||
key := key
|
||||
t.Run(lockOwnerLabel(owner), func(t *testing.T) {
|
||||
runConditionalPutRace(t, []s3RaceClient{
|
||||
{name: "s3-a", client: clientA},
|
||||
{name: "s3-b", client: clientB},
|
||||
}, bucket, key)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type s3RaceClient struct {
|
||||
name string
|
||||
client *s3.Client
|
||||
}
|
||||
|
||||
type putAttemptResult struct {
|
||||
clientName string
|
||||
body string
|
||||
err error
|
||||
}
|
||||
|
||||
func runConditionalPutRace(t *testing.T, clients []s3RaceClient, bucket, key string) {
|
||||
t.Helper()
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan putAttemptResult, len(clients))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for _, client := range clients {
|
||||
wg.Add(1)
|
||||
body := fmt.Sprintf("%s-race", client.name)
|
||||
go func(client s3RaceClient, body string) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := client.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
IfNoneMatch: aws.String("*"),
|
||||
Body: bytes.NewReader([]byte(body)),
|
||||
})
|
||||
results <- putAttemptResult{
|
||||
clientName: client.name,
|
||||
body: body,
|
||||
err: err,
|
||||
}
|
||||
}(client, body)
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
successes := 0
|
||||
preconditionFailures := 0
|
||||
winnerBody := ""
|
||||
unexpectedErrors := make([]string, 0)
|
||||
|
||||
for result := range results {
|
||||
if result.err == nil {
|
||||
successes++
|
||||
winnerBody = result.body
|
||||
continue
|
||||
}
|
||||
if isPreconditionFailed(result.err) {
|
||||
preconditionFailures++
|
||||
continue
|
||||
}
|
||||
unexpectedErrors = append(unexpectedErrors, fmt.Sprintf("%s: %v", result.clientName, result.err))
|
||||
}
|
||||
|
||||
require.Empty(t, unexpectedErrors, "unexpected race errors")
|
||||
require.Equal(t, 1, successes, "exactly one write should win")
|
||||
require.Equal(t, len(clients)-1, preconditionFailures, "all losing writes should fail with 412")
|
||||
|
||||
object, err := clients[0].client.GetObject(context.Background(), &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer object.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(object.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, winnerBody, string(data), "stored object body should match the successful request")
|
||||
}
|
||||
|
||||
func isPreconditionFailed(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
return errors.As(err, &apiErr) && apiErr.ErrorCode() == "PreconditionFailed"
|
||||
}
|
||||
|
||||
func (c *distributedLockCluster) findLockOwnerKeys(bucket, prefix string) map[pb.ServerAddress]string {
|
||||
owners := make([]pb.ServerAddress, 0, len(c.filerPorts))
|
||||
for i := range c.filerPorts {
|
||||
owners = append(owners, c.filerServerAddress(i))
|
||||
}
|
||||
sort.Slice(owners, func(i, j int) bool {
|
||||
return owners[i] < owners[j]
|
||||
})
|
||||
|
||||
keysByOwner := make(map[pb.ServerAddress]string, len(owners))
|
||||
for i := 0; i < 1024 && len(keysByOwner) < len(owners); i++ {
|
||||
key := fmt.Sprintf("%s-%03d.txt", prefix, i)
|
||||
lockOwner := ownerForObjectLock(bucket, key, owners)
|
||||
if _, exists := keysByOwner[lockOwner]; !exists {
|
||||
keysByOwner[lockOwner] = key
|
||||
}
|
||||
}
|
||||
return keysByOwner
|
||||
}
|
||||
|
||||
func ownerForObjectLock(bucket, object string, owners []pb.ServerAddress) pb.ServerAddress {
|
||||
lockKey := fmt.Sprintf("s3.object.write:/buckets/%s/%s", bucket, s3_constants.NormalizeObjectKey(object))
|
||||
hash := util.HashStringToLong(lockKey)
|
||||
if hash < 0 {
|
||||
hash = -hash
|
||||
}
|
||||
return owners[hash%int64(len(owners))]
|
||||
}
|
||||
|
||||
func lockOwnerLabel(owner pb.ServerAddress) string {
|
||||
replacer := strings.NewReplacer(":", "_", ".", "_")
|
||||
return "owner_" + replacer.Replace(string(owner))
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
# S3 API Test Makefile
|
||||
# This Makefile provides comprehensive targets for running S3 versioning tests
|
||||
|
||||
.PHONY: all test help build-weed setup-server start-server stop-server test-versioning test-versioning-quick test-versioning-regressions test-versioning-comprehensive test-all clean logs check-deps
|
||||
.PHONY: help build-weed setup-server start-server stop-server test-versioning test-versioning-quick test-versioning-comprehensive test-all clean logs check-deps
|
||||
|
||||
# Configuration
|
||||
WEED_BINARY := ../../../weed/weed_binary
|
||||
@@ -12,12 +12,6 @@ FILER_PORT := 8888
|
||||
TEST_TIMEOUT := 10m
|
||||
TEST_PATTERN := TestVersioning
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
all: test
|
||||
|
||||
test: test-with-server
|
||||
|
||||
# Default target
|
||||
help:
|
||||
@echo "S3 API Test Makefile"
|
||||
@@ -31,7 +25,6 @@ help:
|
||||
@echo " stop-server - Stop SeaweedFS server"
|
||||
@echo " test-versioning - Run all versioning tests"
|
||||
@echo " test-versioning-quick - Run core versioning tests only"
|
||||
@echo " test-versioning-regressions - Run targeted versioning regression tests"
|
||||
@echo " test-versioning-simple - Run tests without server management"
|
||||
@echo " test-versioning-comprehensive - Run comprehensive versioning tests"
|
||||
@echo " test-all - Run all S3 API tests"
|
||||
@@ -186,12 +179,6 @@ test-versioning-quick: check-deps
|
||||
@go test -v -timeout=$(TEST_TIMEOUT) -run "TestBucketListReturnDataVersioning|TestVersioningBasicWorkflow|TestVersioningDeleteMarkers" .
|
||||
@echo "✅ Core versioning tests completed"
|
||||
|
||||
# Targeted regressions for conditional mutation, multipart, copy, and suspended delete flows.
|
||||
test-versioning-regressions: check-deps
|
||||
@echo "Running targeted S3 versioning regression tests..."
|
||||
@go test -v -timeout=$(TEST_TIMEOUT) -run "TestVersioningCompleteMultipartUploadIsIdempotent|TestVersioningSelfCopyMetadataReplaceCreatesNewVersion|TestVersioningSelfCopyMetadataReplaceSuspendedKeepsNullVersion|TestSuspendedDeleteCreatesDeleteMarker" .
|
||||
@echo "✅ Targeted versioning regression tests completed"
|
||||
|
||||
# All versioning tests
|
||||
test-versioning: check-deps
|
||||
@echo "Running all S3 versioning tests..."
|
||||
@@ -361,4 +348,4 @@ compare-python-tests:
|
||||
@echo "Python equivalent: test_bucket_list_return_data_versioning"
|
||||
@echo ""
|
||||
@echo "Running Go version..."
|
||||
@time go test -v -run "TestBucketListReturnDataVersioning" . 2>&1 | grep -E "(PASS|FAIL|took)"
|
||||
@time go test -v -run "TestBucketListReturnDataVersioning" . 2>&1 | grep -E "(PASS|FAIL|took)"
|
||||
@@ -1,147 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func versioningCopySource(bucketName, key string) string {
|
||||
return fmt.Sprintf("%s/%s", bucketName, url.PathEscape(key))
|
||||
}
|
||||
|
||||
func suspendVersioning(t *testing.T, client *s3.Client, bucketName string) {
|
||||
_, err := client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
VersioningConfiguration: &types.VersioningConfiguration{
|
||||
Status: types.BucketVersioningStatusSuspended,
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestVersioningSelfCopyMetadataReplaceCreatesNewVersion(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
enableVersioning(t, client, bucketName)
|
||||
checkVersioningStatus(t, client, bucketName, types.BucketVersioningStatusEnabled)
|
||||
|
||||
objectKey := "self-copy-versioned.txt"
|
||||
initialContent := []byte("copy me without changing the body")
|
||||
|
||||
putResp, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
Body: bytes.NewReader(initialContent),
|
||||
Metadata: map[string]string{"stage": "one"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, putResp.VersionId)
|
||||
|
||||
copyResp, err := client.CopyObject(context.TODO(), &s3.CopyObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
CopySource: aws.String(versioningCopySource(bucketName, objectKey)),
|
||||
Metadata: map[string]string{"stage": "two"},
|
||||
MetadataDirective: types.MetadataDirectiveReplace,
|
||||
})
|
||||
require.NoError(t, err, "Self-copy with metadata replacement should succeed")
|
||||
require.NotNil(t, copyResp.VersionId, "Versioned self-copy should create a new version")
|
||||
require.NotEqual(t, *putResp.VersionId, *copyResp.VersionId, "Self-copy should create a distinct version")
|
||||
|
||||
headLatestResp, err := client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "two", headLatestResp.Metadata["stage"], "Latest version should expose replaced metadata")
|
||||
|
||||
headOriginalResp, err := client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
VersionId: putResp.VersionId,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "one", headOriginalResp.Metadata["stage"], "Previous version metadata should remain intact")
|
||||
|
||||
getResp, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer getResp.Body.Close()
|
||||
body, err := io.ReadAll(getResp.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, initialContent, body, "Self-copy should not alter the object body")
|
||||
|
||||
versionsResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Prefix: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versionsResp.Versions, 2, "Self-copy should append a new current version")
|
||||
assert.Equal(t, *copyResp.VersionId, *versionsResp.Versions[0].VersionId, "New copy version should be latest")
|
||||
}
|
||||
|
||||
func TestVersioningSelfCopyMetadataReplaceSuspendedKeepsNullVersion(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
enableVersioning(t, client, bucketName)
|
||||
suspendVersioning(t, client, bucketName)
|
||||
checkVersioningStatus(t, client, bucketName, types.BucketVersioningStatusSuspended)
|
||||
|
||||
objectKey := "self-copy-suspended.txt"
|
||||
initialContent := []byte("null version content")
|
||||
|
||||
_, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
Body: bytes.NewReader(initialContent),
|
||||
Metadata: map[string]string{"stage": "one"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
copyResp, err := client.CopyObject(context.TODO(), &s3.CopyObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
CopySource: aws.String(versioningCopySource(bucketName, objectKey)),
|
||||
Metadata: map[string]string{"stage": "two"},
|
||||
MetadataDirective: types.MetadataDirectiveReplace,
|
||||
})
|
||||
require.NoError(t, err, "Suspended self-copy with metadata replacement should succeed")
|
||||
assert.Nil(t, copyResp.VersionId, "Suspended versioning should not return a version header for the current null version")
|
||||
|
||||
headResp, err := client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "two", headResp.Metadata["stage"], "Null current version should be updated in place")
|
||||
|
||||
versionsResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Prefix: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versionsResp.Versions, 1, "Suspended self-copy should keep a single null current version")
|
||||
require.NotNil(t, versionsResp.Versions[0].VersionId)
|
||||
assert.Equal(t, "null", *versionsResp.Versions[0].VersionId, "Suspended self-copy should preserve null-version semantics")
|
||||
assert.True(t, *versionsResp.Versions[0].IsLatest, "Null version should remain latest")
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSuspendedDeleteCreatesDeleteMarker(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
enableVersioning(t, client, bucketName)
|
||||
|
||||
objectKey := "suspended-delete-marker.txt"
|
||||
versionedResp, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
Body: bytes.NewReader([]byte("versioned-content")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, versionedResp.VersionId)
|
||||
|
||||
suspendVersioning(t, client, bucketName)
|
||||
|
||||
_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
Body: bytes.NewReader([]byte("null-version-content")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
deleteResp, err := client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, deleteResp.DeleteMarker)
|
||||
assert.True(t, *deleteResp.DeleteMarker)
|
||||
require.NotNil(t, deleteResp.VersionId)
|
||||
|
||||
listResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, listResp.DeleteMarkers, 1)
|
||||
|
||||
deleteMarker := listResp.DeleteMarkers[0]
|
||||
require.NotNil(t, deleteMarker.Key)
|
||||
assert.Equal(t, objectKey, *deleteMarker.Key)
|
||||
require.NotNil(t, deleteMarker.VersionId)
|
||||
assert.Equal(t, *deleteResp.VersionId, *deleteMarker.VersionId)
|
||||
require.NotNil(t, deleteMarker.IsLatest)
|
||||
assert.True(t, *deleteMarker.IsLatest)
|
||||
|
||||
_, err = client.GetObject(context.TODO(), &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
})
|
||||
require.Error(t, err)
|
||||
|
||||
getVersionedResp, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
VersionId: versionedResp.VersionId,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer getVersionedResp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(getVersionedResp.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "versioned-content", string(body))
|
||||
}
|
||||
@@ -499,16 +499,12 @@ func TestMultipartUploadDeleteMarkerListBehavior(t *testing.T) {
|
||||
t.Logf("Successfully retrieved version %s after delete marker", multipartVersionId)
|
||||
|
||||
// Delete the delete marker to "undelete" the object
|
||||
undeleteResp, err := client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
|
||||
_, err = client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
VersionId: aws.String(deleteMarkerVersionId),
|
||||
})
|
||||
require.NoError(t, err, "Failed to delete the delete marker")
|
||||
require.NotNil(t, undeleteResp.DeleteMarker, "Deleting a delete marker version should report DeleteMarker=true")
|
||||
assert.True(t, *undeleteResp.DeleteMarker, "Deleting a delete marker version should report DeleteMarker=true")
|
||||
require.NotNil(t, undeleteResp.VersionId, "Deleting a delete marker version should echo the version ID")
|
||||
assert.Equal(t, deleteMarkerVersionId, *undeleteResp.VersionId, "DeleteObject should report the deleted delete-marker version ID")
|
||||
|
||||
// ListObjectsV2 should show the object again
|
||||
listAfterUndelete, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
|
||||
@@ -522,76 +518,3 @@ func TestMultipartUploadDeleteMarkerListBehavior(t *testing.T) {
|
||||
|
||||
t.Logf("Object restored after delete marker removal, ETag=%s", multipartETag)
|
||||
}
|
||||
|
||||
func TestVersioningCompleteMultipartUploadIsIdempotent(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
enableVersioning(t, client, bucketName)
|
||||
checkVersioningStatus(t, client, bucketName, types.BucketVersioningStatusEnabled)
|
||||
|
||||
objectKey := "multipart-idempotent-object"
|
||||
createResp, err := client.CreateMultipartUpload(context.TODO(), &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err, "Failed to create multipart upload")
|
||||
|
||||
partSize := 5 * 1024 * 1024
|
||||
part1Data := bytes.Repeat([]byte("i"), partSize)
|
||||
part2Data := bytes.Repeat([]byte("j"), partSize)
|
||||
|
||||
uploadPart1Resp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
UploadId: createResp.UploadId,
|
||||
PartNumber: aws.Int32(1),
|
||||
Body: bytes.NewReader(part1Data),
|
||||
})
|
||||
require.NoError(t, err, "Failed to upload first part")
|
||||
|
||||
uploadPart2Resp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
UploadId: createResp.UploadId,
|
||||
PartNumber: aws.Int32(2),
|
||||
Body: bytes.NewReader(part2Data),
|
||||
})
|
||||
require.NoError(t, err, "Failed to upload second part")
|
||||
|
||||
completeInput := &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
UploadId: createResp.UploadId,
|
||||
MultipartUpload: &types.CompletedMultipartUpload{
|
||||
Parts: []types.CompletedPart{
|
||||
{ETag: uploadPart1Resp.ETag, PartNumber: aws.Int32(1)},
|
||||
{ETag: uploadPart2Resp.ETag, PartNumber: aws.Int32(2)},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
firstCompleteResp, err := client.CompleteMultipartUpload(context.TODO(), completeInput)
|
||||
require.NoError(t, err, "First CompleteMultipartUpload should succeed")
|
||||
require.NotNil(t, firstCompleteResp.ETag)
|
||||
require.NotNil(t, firstCompleteResp.VersionId)
|
||||
|
||||
secondCompleteResp, err := client.CompleteMultipartUpload(context.TODO(), completeInput)
|
||||
require.NoError(t, err, "Repeated CompleteMultipartUpload should return the existing object instead of creating a second version")
|
||||
require.NotNil(t, secondCompleteResp.ETag)
|
||||
require.NotNil(t, secondCompleteResp.VersionId, "Repeated complete should report the existing version ID")
|
||||
assert.Equal(t, *firstCompleteResp.ETag, *secondCompleteResp.ETag, "Repeated complete should report the same ETag")
|
||||
assert.Equal(t, *firstCompleteResp.VersionId, *secondCompleteResp.VersionId, "Repeated complete should report the same version ID")
|
||||
|
||||
versionsResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Prefix: aws.String(objectKey),
|
||||
})
|
||||
require.NoError(t, err, "Failed to list object versions")
|
||||
require.Len(t, versionsResp.Versions, 1, "Repeated completion must not create a duplicate version")
|
||||
assert.Equal(t, *firstCompleteResp.VersionId, *versionsResp.Versions[0].VersionId, "The original multipart version should remain current")
|
||||
assert.Empty(t, versionsResp.DeleteMarkers, "Repeated completion should not create delete markers")
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -107,14 +106,6 @@ func (r *Plugin) schedulerLoop() {
|
||||
|
||||
// runLaneSchedulerIteration runs one scheduling pass for a single lane,
|
||||
// processing only the job types assigned to that lane.
|
||||
//
|
||||
// For lanes that require a lock (e.g. LaneDefault), all job types are
|
||||
// processed sequentially under one admin lock because their volume
|
||||
// management operations share global state.
|
||||
//
|
||||
// For lanes that do not require a lock (e.g. LaneIceberg, LaneLifecycle),
|
||||
// each job type runs independently in its own goroutine so they do not
|
||||
// block each other.
|
||||
func (r *Plugin) runLaneSchedulerIteration(ls *schedulerLaneState) bool {
|
||||
r.expireStaleJobs(time.Now().UTC())
|
||||
|
||||
@@ -131,23 +122,21 @@ func (r *Plugin) runLaneSchedulerIteration(ls *schedulerLaneState) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
if LaneRequiresLock(ls.lane) {
|
||||
return r.runLaneSchedulerIterationLocked(ls, jobTypes)
|
||||
r.setLaneLoopState(ls, "", "waiting_for_lock")
|
||||
lockName := fmt.Sprintf("plugin scheduler:%s", ls.lane)
|
||||
releaseLock, err := r.acquireAdminLock(lockName)
|
||||
if err != nil {
|
||||
glog.Warningf("Plugin scheduler [%s] failed to acquire lock: %v", ls.lane, err)
|
||||
r.setLaneLoopState(ls, "", "idle")
|
||||
return false
|
||||
}
|
||||
if releaseLock != nil {
|
||||
defer releaseLock()
|
||||
}
|
||||
return r.runLaneSchedulerIterationConcurrent(ls, jobTypes)
|
||||
}
|
||||
|
||||
// dueJobType pairs a job type with its resolved scheduling policy.
|
||||
type dueJobType struct {
|
||||
jobType string
|
||||
policy schedulerPolicy
|
||||
}
|
||||
active := make(map[string]struct{}, len(jobTypes))
|
||||
hadJobs := false
|
||||
|
||||
// collectDueJobTypes loads policies for all job types in the lane and
|
||||
// returns those whose detection interval has elapsed. It also returns
|
||||
// the full set of active job type names for later pruning.
|
||||
func (r *Plugin) collectDueJobTypes(ls *schedulerLaneState, jobTypes []string) (active map[string]struct{}, due []dueJobType) {
|
||||
active = make(map[string]struct{}, len(jobTypes))
|
||||
for _, jobType := range jobTypes {
|
||||
active[jobType] = struct{}{}
|
||||
|
||||
@@ -167,31 +156,9 @@ func (r *Plugin) collectDueJobTypes(ls *schedulerLaneState, jobTypes []string) (
|
||||
if !r.markDetectionDue(jobType, policy.DetectionInterval, initialDelay) {
|
||||
continue
|
||||
}
|
||||
due = append(due, dueJobType{jobType: jobType, policy: policy})
|
||||
}
|
||||
return active, due
|
||||
}
|
||||
|
||||
// runLaneSchedulerIterationLocked processes job types sequentially under a
|
||||
// single admin lock. Used by the default lane where volume management
|
||||
// operations must be serialised.
|
||||
func (r *Plugin) runLaneSchedulerIterationLocked(ls *schedulerLaneState, jobTypes []string) bool {
|
||||
r.setLaneLoopState(ls, "", "waiting_for_lock")
|
||||
lockName := fmt.Sprintf("plugin scheduler:%s", ls.lane)
|
||||
releaseLock, err := r.acquireAdminLock(lockName)
|
||||
if err != nil {
|
||||
glog.Warningf("Plugin scheduler [%s] failed to acquire lock: %v", ls.lane, err)
|
||||
r.setLaneLoopState(ls, "", "idle")
|
||||
return false
|
||||
}
|
||||
if releaseLock != nil {
|
||||
defer releaseLock()
|
||||
}
|
||||
|
||||
active, due := r.collectDueJobTypes(ls, jobTypes)
|
||||
hadJobs := false
|
||||
for _, w := range due {
|
||||
if r.runJobTypeIteration(w.jobType, w.policy) {
|
||||
detected := r.runJobTypeIteration(jobType, policy)
|
||||
if detected {
|
||||
hadJobs = true
|
||||
}
|
||||
}
|
||||
@@ -202,33 +169,6 @@ func (r *Plugin) runLaneSchedulerIterationLocked(ls *schedulerLaneState, jobType
|
||||
return hadJobs
|
||||
}
|
||||
|
||||
// runLaneSchedulerIterationConcurrent processes each job type in its own
|
||||
// goroutine so they run independently. Used by lanes (e.g. iceberg,
|
||||
// lifecycle) whose job types do not share global state.
|
||||
func (r *Plugin) runLaneSchedulerIterationConcurrent(ls *schedulerLaneState, jobTypes []string) bool {
|
||||
active, due := r.collectDueJobTypes(ls, jobTypes)
|
||||
|
||||
r.setLaneLoopState(ls, "", "busy")
|
||||
|
||||
var hadJobs atomic.Bool
|
||||
var wg sync.WaitGroup
|
||||
for _, w := range due {
|
||||
wg.Add(1)
|
||||
go func(jobType string, policy schedulerPolicy) {
|
||||
defer wg.Done()
|
||||
if r.runJobTypeIteration(jobType, policy) {
|
||||
hadJobs.Store(true)
|
||||
}
|
||||
}(w.jobType, w.policy)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
r.pruneSchedulerState(active)
|
||||
r.pruneDetectorLeases(active)
|
||||
r.setLaneLoopState(ls, "", "idle")
|
||||
return hadJobs.Load()
|
||||
}
|
||||
|
||||
// runSchedulerIteration is kept for backward compatibility. It runs a
|
||||
// single iteration across ALL job types (equivalent to the old single-loop
|
||||
// behavior). It is only used by the legacy schedulerLoop() fallback.
|
||||
@@ -327,7 +267,7 @@ func (r *Plugin) wakeScheduler() {
|
||||
func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) bool {
|
||||
r.recordSchedulerRunStart(jobType)
|
||||
r.clearWaitingJobQueue(jobType)
|
||||
r.setSchedulerLoopStateForJobType(jobType, "detecting")
|
||||
r.setSchedulerLoopState(jobType, "detecting")
|
||||
r.markJobTypeInFlight(jobType)
|
||||
defer r.finishDetection(jobType)
|
||||
|
||||
@@ -459,7 +399,7 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
return detected
|
||||
}
|
||||
|
||||
r.setSchedulerLoopStateForJobType(jobType, "executing")
|
||||
r.setSchedulerLoopState(jobType, "executing")
|
||||
|
||||
// Scan proposals for the maximum estimated_runtime_seconds so the
|
||||
// execution phase gets enough time for large jobs (e.g. vacuum on
|
||||
|
||||
@@ -3,7 +3,6 @@ package plugin
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -595,81 +594,3 @@ func TestPickDetectorReassignsWhenLeaseIsStale(t *testing.T) {
|
||||
t.Fatalf("expected detector lease to be updated to worker-a, got=%s", lease)
|
||||
}
|
||||
}
|
||||
|
||||
// trackingLockManager records whether Acquire was called and how many times.
|
||||
type trackingLockManager struct {
|
||||
mu sync.Mutex
|
||||
acquired int
|
||||
}
|
||||
|
||||
func (m *trackingLockManager) Acquire(reason string) (func(), error) {
|
||||
m.mu.Lock()
|
||||
m.acquired++
|
||||
m.mu.Unlock()
|
||||
return func() {}, nil
|
||||
}
|
||||
|
||||
func (m *trackingLockManager) count() int {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.acquired
|
||||
}
|
||||
|
||||
func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
lane SchedulerLane
|
||||
jobType string
|
||||
wantLock bool
|
||||
}{
|
||||
{"Default", LaneDefault, "vacuum", true},
|
||||
{"Iceberg", LaneIceberg, "iceberg_maintenance", false},
|
||||
{"Lifecycle", LaneLifecycle, "s3_lifecycle", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
lm := &trackingLockManager{}
|
||||
pluginSvc, err := New(Options{
|
||||
LockManager: lm,
|
||||
ClusterContextProvider: func(context.Context) (*plugin_pb.ClusterContext, error) {
|
||||
return &plugin_pb.ClusterContext{}, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
// Register a detectable worker for the job type.
|
||||
pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{
|
||||
WorkerId: "worker-a",
|
||||
Capabilities: []*plugin_pb.JobTypeCapability{
|
||||
{JobType: tt.jobType, CanDetect: true},
|
||||
},
|
||||
})
|
||||
|
||||
// Enable the job type so the scheduler picks it up.
|
||||
err = pluginSvc.SaveJobTypeConfig(&plugin_pb.PersistedJobTypeConfig{
|
||||
JobType: tt.jobType,
|
||||
AdminRuntime: &plugin_pb.AdminRuntimeConfig{
|
||||
Enabled: true,
|
||||
DetectionIntervalSeconds: 1,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SaveJobTypeConfig: %v", err)
|
||||
}
|
||||
|
||||
ls := pluginSvc.lanes[tt.lane]
|
||||
pluginSvc.runLaneSchedulerIteration(ls)
|
||||
|
||||
if got := lm.count(); (got > 0) != tt.wantLock {
|
||||
t.Errorf("lock acquired %d times, wantLock=%v", got, tt.wantLock)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -38,25 +38,6 @@ var laneIdleSleep = map[SchedulerLane]time.Duration{
|
||||
LaneLifecycle: 5 * time.Minute,
|
||||
}
|
||||
|
||||
// laneRequiresLock maps each lane to whether its job types must be
|
||||
// serialised under a single admin lock. The default lane needs this
|
||||
// because volume-management operations share global state. Other
|
||||
// lanes run each job type independently.
|
||||
var laneRequiresLock = map[SchedulerLane]bool{
|
||||
LaneDefault: true,
|
||||
LaneIceberg: false,
|
||||
LaneLifecycle: false,
|
||||
}
|
||||
|
||||
// LaneRequiresLock returns true if the given lane needs a single admin
|
||||
// lock to serialise its job types. Unknown lanes default to true.
|
||||
func LaneRequiresLock(lane SchedulerLane) bool {
|
||||
if v, ok := laneRequiresLock[lane]; ok {
|
||||
return v
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// LaneIdleSleep returns the idle sleep duration for the given lane,
|
||||
// falling back to defaultSchedulerIdleSleep if the lane is unknown.
|
||||
func LaneIdleSleep(lane SchedulerLane) time.Duration {
|
||||
|
||||
@@ -27,26 +27,6 @@ func TestAllLanesHaveIdleSleep(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLaneRequiresLock(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
lane SchedulerLane
|
||||
want bool
|
||||
}{
|
||||
{"Default", LaneDefault, true},
|
||||
{"Iceberg", LaneIceberg, false},
|
||||
{"Lifecycle", LaneLifecycle, false},
|
||||
{"Unknown", "unknown_lane", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := LaneRequiresLock(tt.lane); got != tt.want {
|
||||
t.Errorf("LaneRequiresLock(%q) = %v, want %v", tt.lane, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnownJobTypesInMap(t *testing.T) {
|
||||
// Ensure the well-known job types are mapped. This catches drift
|
||||
// if a handler's job type string changes without updating the map.
|
||||
|
||||
@@ -195,21 +195,6 @@ func (r *Plugin) setSchedulerLoopState(jobType, phase string) {
|
||||
r.schedulerLoopMu.Unlock()
|
||||
}
|
||||
|
||||
// setSchedulerLoopStateForJobType keeps the aggregate scheduler state and the
|
||||
// owning lane state in sync while a specific job type is active.
|
||||
func (r *Plugin) setSchedulerLoopStateForJobType(jobType, phase string) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
r.setSchedulerLoopState(jobType, phase)
|
||||
if jobType == "" {
|
||||
return
|
||||
}
|
||||
if ls := r.lanes[JobTypeLane(jobType)]; ls != nil {
|
||||
r.setLaneLoopState(ls, jobType, phase)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Plugin) recordSchedulerIterationComplete(hadJobs bool) {
|
||||
if r == nil {
|
||||
return
|
||||
@@ -266,6 +251,7 @@ func (r *Plugin) aggregateLaneLoopStates() schedulerLoopState {
|
||||
return agg
|
||||
}
|
||||
|
||||
|
||||
// --- Per-lane loop state helpers ---
|
||||
|
||||
func (r *Plugin) setLaneLoopState(ls *schedulerLaneState, jobType, phase string) {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
)
|
||||
@@ -64,84 +62,3 @@ func TestGetSchedulerStatusIncludesLastDetectionCount(t *testing.T) {
|
||||
t.Fatalf("expected job type status for %s", jobType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLaneSchedulerStatusShowsActiveConcurrentLaneWork(t *testing.T) {
|
||||
clusterContextStarted := make(chan struct{})
|
||||
releaseClusterContext := make(chan struct{})
|
||||
|
||||
// Create the Plugin without a ClusterContextProvider so no background
|
||||
// scheduler goroutines are started; they would race with the direct
|
||||
// runJobTypeIteration call below.
|
||||
pluginSvc, err := New(Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
// Set the provider after construction so runJobTypeIteration can use it.
|
||||
pluginSvc.clusterContextProvider = func(context.Context) (*plugin_pb.ClusterContext, error) {
|
||||
close(clusterContextStarted)
|
||||
<-releaseClusterContext
|
||||
return nil, context.Canceled
|
||||
}
|
||||
|
||||
const jobType = "s3_lifecycle"
|
||||
err = pluginSvc.SaveJobTypeConfig(&plugin_pb.PersistedJobTypeConfig{
|
||||
JobType: jobType,
|
||||
AdminRuntime: &plugin_pb.AdminRuntimeConfig{
|
||||
Enabled: true,
|
||||
DetectionIntervalSeconds: 30,
|
||||
DetectionTimeoutSeconds: 15,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SaveJobTypeConfig: %v", err)
|
||||
}
|
||||
|
||||
policy, enabled, err := pluginSvc.loadSchedulerPolicy(jobType)
|
||||
if err != nil {
|
||||
t.Fatalf("loadSchedulerPolicy: %v", err)
|
||||
}
|
||||
if !enabled {
|
||||
t.Fatalf("expected enabled policy")
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
pluginSvc.runJobTypeIteration(jobType, policy)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-clusterContextStarted:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("timed out waiting for job type iteration to start")
|
||||
}
|
||||
|
||||
var laneStatus SchedulerStatus
|
||||
var aggregateStatus SchedulerStatus
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
laneStatus = pluginSvc.GetLaneSchedulerStatus(LaneLifecycle)
|
||||
aggregateStatus = pluginSvc.GetSchedulerStatus()
|
||||
if laneStatus.CurrentJobType == jobType && laneStatus.CurrentPhase == "detecting" &&
|
||||
aggregateStatus.CurrentJobType == jobType && aggregateStatus.CurrentPhase == "detecting" {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
if laneStatus.CurrentJobType != jobType || laneStatus.CurrentPhase != "detecting" {
|
||||
t.Fatalf("unexpected lane status while work is active: job=%q phase=%q", laneStatus.CurrentJobType, laneStatus.CurrentPhase)
|
||||
}
|
||||
if aggregateStatus.CurrentJobType != jobType || aggregateStatus.CurrentPhase != "detecting" {
|
||||
t.Fatalf("unexpected aggregate status while work is active: job=%q phase=%q", aggregateStatus.CurrentJobType, aggregateStatus.CurrentPhase)
|
||||
}
|
||||
|
||||
close(releaseClusterContext)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("timed out waiting for job type iteration to finish")
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,6 @@ type MountOptions struct {
|
||||
uidMap *string
|
||||
gidMap *string
|
||||
readOnly *bool
|
||||
includeSystemEntries *bool
|
||||
debug *bool
|
||||
debugPort *int
|
||||
localSocket *string
|
||||
@@ -100,7 +99,6 @@ func init() {
|
||||
mountOptions.uidMap = cmdMount.Flag.String("map.uid", "", "map local uid to uid on filer, comma-separated <local_uid>:<filer_uid>")
|
||||
mountOptions.gidMap = cmdMount.Flag.String("map.gid", "", "map local gid to gid on filer, comma-separated <local_gid>:<filer_gid>")
|
||||
mountOptions.readOnly = cmdMount.Flag.Bool("readOnly", false, "read only")
|
||||
mountOptions.includeSystemEntries = cmdMount.Flag.Bool("includeSystemEntries", false, "show filer system entries (e.g. /topics, /etc) in directory listings")
|
||||
mountOptions.debug = cmdMount.Flag.Bool("debug", false, "serves runtime profiling data, e.g., http://localhost:<debug.port>/debug/pprof/goroutine?debug=2")
|
||||
mountOptions.debugPort = cmdMount.Flag.Int("debug.port", 6061, "http port for debugging")
|
||||
mountOptions.localSocket = cmdMount.Flag.String("localSocket", "", "default to /tmp/seaweedfs-mount-<mount_dir_hash>.sock")
|
||||
|
||||
@@ -340,7 +340,6 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
VolumeServerAccess: *mountOptions.volumeServerAccess,
|
||||
Cipher: cipher,
|
||||
UidGidMapper: uidGidMapper,
|
||||
IncludeSystemEntries: *option.includeSystemEntries,
|
||||
DisableXAttr: *option.disableXAttr,
|
||||
IsMacOs: runtime.GOOS == "darwin",
|
||||
MetadataFlushSeconds: *option.metadataFlushSeconds,
|
||||
|
||||
@@ -22,17 +22,6 @@ hosts = [
|
||||
topic = "seaweedfs_filer"
|
||||
offsetFile = "./last.offset"
|
||||
offsetSaveIntervalSeconds = 10
|
||||
# SASL Authentication
|
||||
sasl_enabled = false
|
||||
sasl_mechanism = "PLAIN" # PLAIN, SCRAM-SHA-256, SCRAM-SHA-512
|
||||
sasl_username = ""
|
||||
sasl_password = ""
|
||||
# TLS/SSL
|
||||
tls_enabled = false
|
||||
tls_ca_cert = "" # path to CA certificate PEM file
|
||||
tls_client_cert = "" # path to client certificate PEM file (for mTLS)
|
||||
tls_client_key = "" # path to client private key PEM file (for mTLS)
|
||||
tls_insecure_skip_verify = false
|
||||
|
||||
|
||||
[notification.aws_sqs]
|
||||
|
||||
@@ -27,7 +27,6 @@ type FilerOperations interface {
|
||||
CountDirectoryEntries(ctx context.Context, dirPath util.FullPath, limit int) (count int, err error)
|
||||
DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isRecursive, ignoreRecursiveError, shouldDeleteChunks, isFromOtherCluster bool, signatures []int32, ifNotModifiedAfter int64) error
|
||||
GetEntryAttributes(ctx context.Context, p util.FullPath) (attributes map[string][]byte, err error)
|
||||
IsDirectoryKeyObject(ctx context.Context, p util.FullPath) (bool, error)
|
||||
}
|
||||
|
||||
// folderState tracks the state of a folder for empty folder cleanup
|
||||
@@ -313,16 +312,6 @@ func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string)
|
||||
return
|
||||
}
|
||||
|
||||
// Skip explicitly created directory markers (e.g., PUT /bucket/folder/)
|
||||
// These have a MIME type set and should be preserved even when empty
|
||||
if isKeyObj, err := efc.filer.IsDirectoryKeyObject(ctx, util.FullPath(folder)); err != nil {
|
||||
glog.V(2).Infof("EmptyFolderCleaner: error checking directory key object %s: %v", folder, err)
|
||||
return
|
||||
} else if isKeyObj {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s (triggered by %s), explicit directory marker", folder, triggeredBy)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the empty folder
|
||||
glog.Infof("EmptyFolderCleaner: deleting empty folder %s (triggered by %s)", folder, triggeredBy)
|
||||
if err := efc.deleteFolder(ctx, folder); err != nil {
|
||||
|
||||
@@ -12,10 +12,9 @@ import (
|
||||
)
|
||||
|
||||
type mockFilerOps struct {
|
||||
countFn func(path util.FullPath) (int, error)
|
||||
deleteFn func(path util.FullPath) error
|
||||
attrsFn func(path util.FullPath) (map[string][]byte, error)
|
||||
isDirKeyObjFn func(path util.FullPath) (bool, error)
|
||||
countFn func(path util.FullPath) (int, error)
|
||||
deleteFn func(path util.FullPath) error
|
||||
attrsFn func(path util.FullPath) (map[string][]byte, error)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) CountDirectoryEntries(_ context.Context, dirPath util.FullPath, _ int) (int, error) {
|
||||
@@ -39,13 +38,6 @@ func (m *mockFilerOps) GetEntryAttributes(_ context.Context, p util.FullPath) (m
|
||||
return m.attrsFn(p)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) IsDirectoryKeyObject(_ context.Context, p util.FullPath) (bool, error) {
|
||||
if m.isDirKeyObjFn == nil {
|
||||
return false, nil
|
||||
}
|
||||
return m.isDirKeyObjFn(p)
|
||||
}
|
||||
|
||||
func Test_isUnderPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -741,70 +733,3 @@ func TestEmptyFolderCleaner_executeCleanup_bucketPolicyDisabledSkips(t *testing.
|
||||
t.Fatalf("expected folder %s to be skipped, got deletions %v", folder, deleted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_executeCleanup_directoryMarker(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
isDirKeyObj bool
|
||||
expectDeletion bool
|
||||
}{
|
||||
{
|
||||
name: "skips explicit directory marker",
|
||||
isDirKeyObj: true,
|
||||
expectDeletion: false,
|
||||
},
|
||||
{
|
||||
name: "deletes implicit empty folder",
|
||||
isDirKeyObj: false,
|
||||
expectDeletion: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
lockRing := lock_manager.NewLockRing(5 * time.Second)
|
||||
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"})
|
||||
|
||||
var deleted []string
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(_ util.FullPath) (int, error) {
|
||||
return 0, nil
|
||||
},
|
||||
deleteFn: func(path util.FullPath) error {
|
||||
deleted = append(deleted, string(path))
|
||||
return nil
|
||||
},
|
||||
isDirKeyObjFn: func(path util.FullPath) (bool, error) {
|
||||
return tc.isDirKeyObj, nil
|
||||
},
|
||||
}
|
||||
|
||||
cleaner := &EmptyFolderCleaner{
|
||||
filer: mock,
|
||||
lockRing: lockRing,
|
||||
host: "filer1:8888",
|
||||
bucketPath: "/buckets",
|
||||
enabled: true,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
cleanupQueue: NewCleanupQueue(1000, time.Minute),
|
||||
maxCountCheck: 1000,
|
||||
cacheExpiry: time.Minute,
|
||||
processorSleep: time.Second,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
folder := "/buckets/test/folder"
|
||||
cleaner.executeCleanup(folder, "triggered_item")
|
||||
|
||||
if tc.expectDeletion {
|
||||
if len(deleted) != 1 || deleted[0] != folder {
|
||||
t.Fatalf("expected implicit empty folder %s to be deleted, got deletions %v", folder, deleted)
|
||||
}
|
||||
} else {
|
||||
if len(deleted) != 0 {
|
||||
t.Fatalf("expected explicit directory marker %s to be preserved, got deletions %v", folder, deleted)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -559,17 +559,3 @@ func (f *Filer) GetEntryAttributes(ctx context.Context, p util.FullPath) (map[st
|
||||
}
|
||||
return entry.Extended, nil
|
||||
}
|
||||
|
||||
func (f *Filer) IsDirectoryKeyObject(ctx context.Context, p util.FullPath) (bool, error) {
|
||||
entry, err := f.FindEntry(ctx, p)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if entry == nil {
|
||||
return false, nil
|
||||
}
|
||||
return entry.IsDirectory() && entry.Mime != "", nil
|
||||
}
|
||||
@@ -179,10 +179,6 @@ func PrepareStreamContentWithThrottler(ctx context.Context, masterClient wdclien
|
||||
jwt := jwtFunc(chunkView.FileId)
|
||||
written, err := retriedStreamFetchChunkData(ctx, writer, urlStrings, jwt, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.OffsetInChunk, int(chunkView.ViewSize))
|
||||
|
||||
if err != nil && ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// If read failed, try to invalidate cache and re-lookup
|
||||
if err != nil && written == 0 {
|
||||
if invalidator, ok := masterClient.(CacheInvalidator); ok {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
@@ -174,37 +173,3 @@ func TestRetryLogicSkipsSameUrls(t *testing.T) {
|
||||
t.Error("Expected different URLs to not be equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanceledStreamSkipsCacheInvalidation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
fileId := "3,canceled"
|
||||
|
||||
mock := &mockMasterClient{
|
||||
lookupFunc: func(ctx context.Context, fid string) ([]string, error) {
|
||||
return []string{"http://server:8080"}, nil
|
||||
},
|
||||
}
|
||||
|
||||
chunks := []*filer_pb.FileChunk{
|
||||
{
|
||||
FileId: fileId,
|
||||
Offset: 0,
|
||||
Size: 10,
|
||||
},
|
||||
}
|
||||
|
||||
streamFn, err := PrepareStreamContentWithThrottler(ctx, mock, noJwtFunc, chunks, 0, 10, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("PrepareStreamContentWithThrottler failed: %v", err)
|
||||
}
|
||||
|
||||
cancel()
|
||||
|
||||
err = streamFn(&bytes.Buffer{})
|
||||
if err != context.Canceled {
|
||||
t.Fatalf("expected context.Canceled, got %v", err)
|
||||
}
|
||||
if len(mock.invalidatedFileIds) != 0 {
|
||||
t.Fatalf("expected no cache invalidation on cancellation, got %v", mock.invalidatedFileIds)
|
||||
}
|
||||
}
|
||||
@@ -27,19 +27,18 @@ type MetaCache struct {
|
||||
localStore filer.VirtualFilerStore
|
||||
leveldbStore *leveldb.LevelDBStore // direct reference for batch operations
|
||||
sync.RWMutex
|
||||
uidGidMapper *UidGidMapper
|
||||
markCachedFn func(fullpath util.FullPath)
|
||||
isCachedFn func(fullpath util.FullPath) bool
|
||||
invalidateFunc func(fullpath util.FullPath, entry *filer_pb.Entry)
|
||||
onDirectoryUpdate func(dir util.FullPath)
|
||||
visitGroup singleflight.Group // deduplicates concurrent EnsureVisited calls for the same path
|
||||
applyCh chan metadataApplyRequest
|
||||
applyDone chan struct{}
|
||||
applyStateMu sync.Mutex
|
||||
applyClosed bool
|
||||
buildingDirs map[util.FullPath]*directoryBuildState
|
||||
dedupRing dedupRingBuffer
|
||||
includeSystemEntries bool
|
||||
uidGidMapper *UidGidMapper
|
||||
markCachedFn func(fullpath util.FullPath)
|
||||
isCachedFn func(fullpath util.FullPath) bool
|
||||
invalidateFunc func(fullpath util.FullPath, entry *filer_pb.Entry)
|
||||
onDirectoryUpdate func(dir util.FullPath)
|
||||
visitGroup singleflight.Group // deduplicates concurrent EnsureVisited calls for the same path
|
||||
applyCh chan metadataApplyRequest
|
||||
applyDone chan struct{}
|
||||
applyStateMu sync.Mutex
|
||||
applyClosed bool
|
||||
buildingDirs map[util.FullPath]*directoryBuildState
|
||||
dedupRing dedupRingBuffer
|
||||
}
|
||||
|
||||
var errMetaCacheClosed = errors.New("metadata cache is shut down")
|
||||
@@ -85,18 +84,17 @@ type metadataApplyRequest struct {
|
||||
done chan error
|
||||
}
|
||||
|
||||
func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPath, includeSystemEntries bool,
|
||||
func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPath,
|
||||
markCachedFn func(path util.FullPath), isCachedFn func(path util.FullPath) bool, invalidateFunc func(util.FullPath, *filer_pb.Entry), onDirectoryUpdate func(dir util.FullPath)) *MetaCache {
|
||||
leveldbStore, virtualStore := openMetaStore(dbFolder)
|
||||
mc := &MetaCache{
|
||||
root: root,
|
||||
localStore: virtualStore,
|
||||
leveldbStore: leveldbStore,
|
||||
markCachedFn: markCachedFn,
|
||||
isCachedFn: isCachedFn,
|
||||
uidGidMapper: uidGidMapper,
|
||||
onDirectoryUpdate: onDirectoryUpdate,
|
||||
includeSystemEntries: includeSystemEntries,
|
||||
root: root,
|
||||
localStore: virtualStore,
|
||||
leveldbStore: leveldbStore,
|
||||
markCachedFn: markCachedFn,
|
||||
isCachedFn: isCachedFn,
|
||||
uidGidMapper: uidGidMapper,
|
||||
onDirectoryUpdate: onDirectoryUpdate,
|
||||
invalidateFunc: func(fullpath util.FullPath, entry *filer_pb.Entry) {
|
||||
invalidateFunc(fullpath, entry)
|
||||
},
|
||||
@@ -184,29 +182,6 @@ func (mc *MetaCache) atomicUpdateEntryFromFilerLocked(ctx context.Context, oldPa
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc *MetaCache) shouldHideEntry(fullpath util.FullPath) bool {
|
||||
if mc.includeSystemEntries {
|
||||
return false
|
||||
}
|
||||
dir, name := fullpath.DirAndName()
|
||||
return IsHiddenSystemEntry(dir, name)
|
||||
}
|
||||
|
||||
func (mc *MetaCache) purgeEntryLocked(ctx context.Context, fullpath util.FullPath, isDirectory bool) error {
|
||||
if fullpath == "" {
|
||||
return nil
|
||||
}
|
||||
if err := mc.localStore.DeleteEntry(ctx, fullpath); err != nil {
|
||||
return err
|
||||
}
|
||||
if isDirectory {
|
||||
if err := mc.localStore.DeleteFolderChildren(ctx, fullpath); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc *MetaCache) ApplyMetadataResponse(ctx context.Context, resp *filer_pb.SubscribeMetadataResponse, options MetadataResponseApplyOptions) error {
|
||||
if resp == nil || resp.EventNotification == nil {
|
||||
return nil
|
||||
@@ -545,9 +520,7 @@ func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *file
|
||||
}
|
||||
|
||||
var oldPath util.FullPath
|
||||
var newPath util.FullPath
|
||||
var newEntry *filer.Entry
|
||||
hideNewPath := false
|
||||
if message.OldEntry != nil {
|
||||
oldPath = util.NewFullPath(resp.Directory, message.OldEntry.Name)
|
||||
}
|
||||
@@ -557,20 +530,11 @@ func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *file
|
||||
if message.NewParentPath != "" {
|
||||
dir = message.NewParentPath
|
||||
}
|
||||
newPath = util.NewFullPath(dir, message.NewEntry.Name)
|
||||
hideNewPath = mc.shouldHideEntry(newPath)
|
||||
if !hideNewPath {
|
||||
newEntry = filer.FromPbEntry(dir, message.NewEntry)
|
||||
}
|
||||
newEntry = filer.FromPbEntry(dir, message.NewEntry)
|
||||
}
|
||||
|
||||
mc.Lock()
|
||||
err := mc.atomicUpdateEntryFromFilerLocked(ctx, oldPath, newEntry, allowUncachedInsert)
|
||||
if err == nil && hideNewPath {
|
||||
if purgeErr := mc.purgeEntryLocked(ctx, newPath, message.NewEntry.IsDirectory); purgeErr != nil {
|
||||
err = purgeErr
|
||||
}
|
||||
}
|
||||
// When a directory is deleted or moved, remove its cached descendants
|
||||
// so stale children cannot be served from the local cache.
|
||||
if err == nil && oldPath != "" && message.OldEntry != nil && message.OldEntry.IsDirectory {
|
||||
|
||||
@@ -2,7 +2,6 @@ package meta_cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -297,114 +296,6 @@ func TestApplyMetadataResponseDeduplicatesRepeatedFilerEvent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMetadataResponseSkipsHiddenSystemEntryWhenDisabled(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
createResp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: "topics",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: 1,
|
||||
Mtime: 1,
|
||||
FileMode: uint32(os.ModeDir | 0o755),
|
||||
},
|
||||
IsDirectory: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), createResp, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply create: %v", err)
|
||||
}
|
||||
|
||||
entry, err := mc.FindEntry(context.Background(), util.FullPath("/topics"))
|
||||
if err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("find hidden entry error = %v, want %v", err, filer_pb.ErrNotFound)
|
||||
}
|
||||
if entry != nil {
|
||||
t.Fatalf("hidden entry still cached: %+v", entry)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMetadataResponsePurgesHiddenDestinationPath(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/src": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: "/topics",
|
||||
Attr: filer.Attr{
|
||||
Crtime: time.Unix(1, 0),
|
||||
Mtime: time.Unix(1, 0),
|
||||
Mode: os.ModeDir | 0o755,
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("insert stale hidden dir: %v", err)
|
||||
}
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: "/topics/leaked.txt",
|
||||
Attr: filer.Attr{
|
||||
Crtime: time.Unix(1, 0),
|
||||
Mtime: time.Unix(1, 0),
|
||||
Mode: 0o644,
|
||||
FileSize: 7,
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("insert leaked hidden child: %v", err)
|
||||
}
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: "/src/visible",
|
||||
Attr: filer.Attr{
|
||||
Crtime: time.Unix(1, 0),
|
||||
Mtime: time.Unix(1, 0),
|
||||
Mode: os.ModeDir | 0o755,
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("insert source dir: %v", err)
|
||||
}
|
||||
|
||||
renameResp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/src",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{
|
||||
Name: "visible",
|
||||
IsDirectory: true,
|
||||
},
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: "topics",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: 2,
|
||||
Mtime: 2,
|
||||
FileMode: uint32(os.ModeDir | 0o755),
|
||||
},
|
||||
IsDirectory: true,
|
||||
},
|
||||
NewParentPath: "/",
|
||||
},
|
||||
}
|
||||
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), renameResp, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply rename: %v", err)
|
||||
}
|
||||
|
||||
if entry, err := mc.FindEntry(context.Background(), util.FullPath("/src/visible")); err != filer_pb.ErrNotFound || entry != nil {
|
||||
t.Fatalf("source dir after rename = %+v, %v; want nil, %v", entry, err, filer_pb.ErrNotFound)
|
||||
}
|
||||
if entry, err := mc.FindEntry(context.Background(), util.FullPath("/topics")); err != filer_pb.ErrNotFound || entry != nil {
|
||||
t.Fatalf("hidden destination after rename = %+v, %v; want nil, %v", entry, err, filer_pb.ErrNotFound)
|
||||
}
|
||||
if entry, err := mc.FindEntry(context.Background(), util.FullPath("/topics/leaked.txt")); err != filer_pb.ErrNotFound || entry != nil {
|
||||
t.Fatalf("hidden child after rename = %+v, %v; want nil, %v", entry, err, filer_pb.ErrNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestMetaCache(t *testing.T, cached map[util.FullPath]bool) (*MetaCache, map[util.FullPath]bool, *recordedPaths, *recordedPaths) {
|
||||
t.Helper()
|
||||
|
||||
@@ -421,7 +312,6 @@ func newTestMetaCache(t *testing.T, cached map[util.FullPath]bool) (*MetaCache,
|
||||
filepath.Join(t.TempDir(), "meta"),
|
||||
mapper,
|
||||
util.FullPath("/"),
|
||||
false,
|
||||
func(path util.FullPath) {
|
||||
cachedMu.Lock()
|
||||
defer cachedMu.Unlock()
|
||||
|
||||
@@ -107,7 +107,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
var err error
|
||||
snapshotTsNs, err = filer_pb.ReadDirAllEntriesWithSnapshot(ctx, client, path, "", func(pbEntry *filer_pb.Entry, isLast bool) error {
|
||||
entry := filer.FromPbEntry(string(path), pbEntry)
|
||||
if !mc.includeSystemEntries && IsHiddenSystemEntry(string(path), entry.Name()) {
|
||||
if IsHiddenSystemEntry(string(path), entry.Name()) {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,6 @@ type Option struct {
|
||||
VolumeServerAccess string // how to access volume servers
|
||||
Cipher bool // whether encrypt data on volume server
|
||||
UidGidMapper *meta_cache.UidGidMapper
|
||||
IncludeSystemEntries bool
|
||||
|
||||
// Periodic metadata flush interval in seconds (0 to disable)
|
||||
// This protects chunks from being purged by volume.fsck for long-running writes
|
||||
@@ -204,7 +203,6 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
|
||||
wfs.metaCache = meta_cache.NewMetaCache(path.Join(option.getUniqueCacheDirForRead(), "meta"), option.UidGidMapper,
|
||||
util.FullPath(option.FilerMountRootPath),
|
||||
option.IncludeSystemEntries,
|
||||
func(path util.FullPath) {
|
||||
wfs.inodeToPath.MarkChildrenCached(path)
|
||||
}, func(path util.FullPath) bool {
|
||||
|
||||
@@ -302,7 +302,7 @@ func (wfs *WFS) readDirectoryDirect(input *fuse.ReadIn, out *fuse.DirEntryList,
|
||||
if input.Offset >= dh.entryStreamOffset {
|
||||
if len(dh.entryStream) == 0 && input.Offset > dh.entryStreamOffset {
|
||||
skipCount := uint32(input.Offset-dh.entryStreamOffset) + batchSize
|
||||
entries, snapshotTs, err := loadDirectoryEntriesDirect(context.Background(), wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
|
||||
entries, snapshotTs, err := loadDirectoryEntriesDirect(context.Background(), wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs)
|
||||
if err != nil {
|
||||
glog.Errorf("list filer directory: %v", err)
|
||||
return fuse.EIO
|
||||
@@ -331,7 +331,7 @@ func (wfs *WFS) readDirectoryDirect(input *fuse.ReadIn, out *fuse.DirEntryList,
|
||||
}
|
||||
}
|
||||
|
||||
entries, snapshotTs, err := loadDirectoryEntriesDirect(context.Background(), wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
|
||||
entries, snapshotTs, err := loadDirectoryEntriesDirect(context.Background(), wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs)
|
||||
if err != nil {
|
||||
glog.Errorf("list filer directory: %v", err)
|
||||
return fuse.EIO
|
||||
@@ -360,13 +360,13 @@ func (wfs *WFS) readDirectoryDirect(input *fuse.ReadIn, out *fuse.DirEntryList,
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient, uidGidMapper *meta_cache.UidGidMapper, dirPath util.FullPath, startFileName string, includeStart bool, limit uint32, snapshotTsNs int64, includeSystemEntries bool) ([]*filer.Entry, int64, error) {
|
||||
func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient, uidGidMapper *meta_cache.UidGidMapper, dirPath util.FullPath, startFileName string, includeStart bool, limit uint32, snapshotTsNs int64) ([]*filer.Entry, int64, error) {
|
||||
entries := make([]*filer.Entry, 0, limit)
|
||||
var actualSnapshotTsNs int64
|
||||
err := client.WithFilerClient(false, func(sc filer_pb.SeaweedFilerClient) error {
|
||||
var innerErr error
|
||||
actualSnapshotTsNs, innerErr = filer_pb.DoSeaweedListWithSnapshot(ctx, sc, dirPath, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
if !includeSystemEntries && meta_cache.IsHiddenSystemEntry(string(dirPath), entry.Name) {
|
||||
if meta_cache.IsHiddenSystemEntry(string(dirPath), entry.Name) {
|
||||
return nil
|
||||
}
|
||||
if uidGidMapper != nil && entry.Attributes != nil {
|
||||
|
||||
@@ -84,7 +84,7 @@ func TestLoadDirectoryEntriesDirectFiltersHiddenEntriesAndMapsIds(t *testing.T)
|
||||
},
|
||||
}
|
||||
|
||||
entries, _, err := loadDirectoryEntriesDirect(context.Background(), client, mapper, util.FullPath("/"), "", false, 10, 0, false)
|
||||
entries, _, err := loadDirectoryEntriesDirect(context.Background(), client, mapper, util.FullPath("/"), "", false, 10, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("loadDirectoryEntriesDirect: %v", err)
|
||||
}
|
||||
@@ -98,25 +98,3 @@ func TestLoadDirectoryEntriesDirectFiltersHiddenEntriesAndMapsIds(t *testing.T)
|
||||
t.Fatalf("mapped uid/gid = %d/%d, want 10/20", entries[0].Attr.Uid, entries[0].Attr.Gid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadDirectoryEntriesDirectShowsSystemEntriesWhenEnabled(t *testing.T) {
|
||||
client := &directoryFilerAccessor{
|
||||
client: &directoryListClient{
|
||||
responses: []*filer_pb.ListEntriesResponse{
|
||||
{Entry: &filer_pb.Entry{Name: "topics"}},
|
||||
{Entry: &filer_pb.Entry{Name: "visible"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
entries, _, err := loadDirectoryEntriesDirect(context.Background(), client, nil, util.FullPath("/"), "", false, 10, 0, true)
|
||||
if err != nil {
|
||||
t.Fatalf("loadDirectoryEntriesDirect: %v", err)
|
||||
}
|
||||
if got := len(entries); got != 2 {
|
||||
t.Fatalf("entry count = %d, want 2", got)
|
||||
}
|
||||
if entries[0].Name() != "topics" || entries[1].Name() != "visible" {
|
||||
t.Fatalf("entry names = %q, %q, want topics, visible", entries[0].Name(), entries[1].Name())
|
||||
}
|
||||
}
|
||||
@@ -338,7 +338,6 @@ func newCopyRangeTestWFSWithMetaCache(t *testing.T) *WFS {
|
||||
filepath.Join(t.TempDir(), "meta"),
|
||||
uidGidMapper,
|
||||
root,
|
||||
false,
|
||||
func(path util.FullPath) {
|
||||
wfs.inodeToPath.MarkChildrenCached(path)
|
||||
},
|
||||
|
||||
@@ -120,7 +120,6 @@ func newCreateTestWFS(t *testing.T) (*WFS, *createEntryTestServer) {
|
||||
filepath.Join(t.TempDir(), "meta"),
|
||||
uidGidMapper,
|
||||
root,
|
||||
false,
|
||||
func(path util.FullPath) {
|
||||
wfs.inodeToPath.MarkChildrenCached(path)
|
||||
},
|
||||
|
||||
@@ -23,7 +23,6 @@ func TestHandleRenameResponseLeavesUncachedTargetOutOfCache(t *testing.T) {
|
||||
filepath.Join(t.TempDir(), "meta"),
|
||||
uidGidMapper,
|
||||
root,
|
||||
false,
|
||||
func(path util.FullPath) {
|
||||
inodeToPath.MarkChildrenCached(path)
|
||||
},
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Shopify/sarama"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/notification"
|
||||
@@ -29,29 +27,15 @@ func (k *KafkaQueue) Initialize(configuration util.Configuration, prefix string)
|
||||
return k.initialize(
|
||||
configuration.GetStringSlice(prefix+"hosts"),
|
||||
configuration.GetString(prefix+"topic"),
|
||||
SASLTLSConfig{
|
||||
SASLEnabled: configuration.GetBool(prefix + "sasl_enabled"),
|
||||
SASLMechanism: configuration.GetString(prefix + "sasl_mechanism"),
|
||||
SASLUsername: configuration.GetString(prefix + "sasl_username"),
|
||||
SASLPassword: configuration.GetString(prefix + "sasl_password"),
|
||||
TLSEnabled: configuration.GetBool(prefix + "tls_enabled"),
|
||||
TLSCACert: configuration.GetString(prefix + "tls_ca_cert"),
|
||||
TLSClientCert: configuration.GetString(prefix + "tls_client_cert"),
|
||||
TLSClientKey: configuration.GetString(prefix + "tls_client_key"),
|
||||
TLSInsecureSkipVerify: configuration.GetBool(prefix + "tls_insecure_skip_verify"),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (k *KafkaQueue) initialize(hosts []string, topic string, saslTLS SASLTLSConfig) (err error) {
|
||||
func (k *KafkaQueue) initialize(hosts []string, topic string) (err error) {
|
||||
config := sarama.NewConfig()
|
||||
config.Producer.RequiredAcks = sarama.WaitForLocal
|
||||
config.Producer.Partitioner = sarama.NewHashPartitioner
|
||||
config.Producer.Return.Successes = true
|
||||
config.Producer.Return.Errors = true
|
||||
if err = ConfigureSASLTLS(config, saslTLS); err != nil {
|
||||
return fmt.Errorf("kafka producer security configuration: %w", err)
|
||||
}
|
||||
k.producer, err = sarama.NewAsyncProducer(hosts, config)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/Shopify/sarama"
|
||||
"github.com/xdg-go/scram"
|
||||
)
|
||||
|
||||
// SASLTLSConfig holds SASL and TLS configuration for Kafka connections.
|
||||
type SASLTLSConfig struct {
|
||||
SASLEnabled bool
|
||||
SASLMechanism string
|
||||
SASLUsername string
|
||||
SASLPassword string
|
||||
|
||||
TLSEnabled bool
|
||||
TLSCACert string
|
||||
TLSClientCert string
|
||||
TLSClientKey string
|
||||
TLSInsecureSkipVerify bool
|
||||
}
|
||||
|
||||
// ConfigureSASLTLS applies SASL and TLS settings to a sarama config.
|
||||
func ConfigureSASLTLS(config *sarama.Config, st SASLTLSConfig) error {
|
||||
if st.SASLEnabled {
|
||||
config.Net.SASL.Enable = true
|
||||
config.Net.SASL.User = st.SASLUsername
|
||||
config.Net.SASL.Password = st.SASLPassword
|
||||
|
||||
mechanism := strings.ToUpper(st.SASLMechanism)
|
||||
switch mechanism {
|
||||
case "PLAIN", "":
|
||||
config.Net.SASL.Mechanism = sarama.SASLTypePlaintext
|
||||
case "SCRAM-SHA-256":
|
||||
config.Net.SASL.Mechanism = sarama.SASLTypeSCRAMSHA256
|
||||
config.Net.SASL.SCRAMClientGeneratorFunc = func() sarama.SCRAMClient {
|
||||
return &scramClient{HashGeneratorFcn: scram.SHA256}
|
||||
}
|
||||
case "SCRAM-SHA-512":
|
||||
config.Net.SASL.Mechanism = sarama.SASLTypeSCRAMSHA512
|
||||
config.Net.SASL.SCRAMClientGeneratorFunc = func() sarama.SCRAMClient {
|
||||
return &scramClient{HashGeneratorFcn: scram.SHA512}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unsupported SASL mechanism: %s", mechanism)
|
||||
}
|
||||
}
|
||||
|
||||
if st.TLSEnabled {
|
||||
if (st.TLSClientCert == "") != (st.TLSClientKey == "") {
|
||||
return fmt.Errorf("both tls_client_cert and tls_client_key must be provided for mTLS, or neither")
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: st.TLSInsecureSkipVerify,
|
||||
}
|
||||
|
||||
if st.TLSCACert != "" {
|
||||
caCert, err := os.ReadFile(st.TLSCACert)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read CA certificate: %w", err)
|
||||
}
|
||||
caCertPool := x509.NewCertPool()
|
||||
if !caCertPool.AppendCertsFromPEM(caCert) {
|
||||
return fmt.Errorf("failed to parse CA certificate")
|
||||
}
|
||||
tlsConfig.RootCAs = caCertPool
|
||||
}
|
||||
|
||||
if st.TLSClientCert != "" && st.TLSClientKey != "" {
|
||||
cert, err := tls.LoadX509KeyPair(st.TLSClientCert, st.TLSClientKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load client certificate/key: %w", err)
|
||||
}
|
||||
tlsConfig.Certificates = []tls.Certificate{cert}
|
||||
}
|
||||
|
||||
config.Net.TLS.Enable = true
|
||||
config.Net.TLS.Config = tlsConfig
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// scramClient implements the sarama.SCRAMClient interface.
|
||||
type scramClient struct {
|
||||
*scram.ClientConversation
|
||||
scram.HashGeneratorFcn
|
||||
}
|
||||
|
||||
func (c *scramClient) Begin(userName, password, authzID string) (err error) {
|
||||
client, err := c.HashGeneratorFcn.NewClient(userName, password, authzID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.ClientConversation = client.NewConversation()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *scramClient) Step(challenge string) (string, error) {
|
||||
return c.ClientConversation.Step(challenge)
|
||||
}
|
||||
|
||||
func (c *scramClient) Done() bool {
|
||||
return c.ClientConversation.Done()
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package kafka
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Shopify/sarama"
|
||||
)
|
||||
|
||||
func TestConfigureSASLTLSRejectsPartialMTLSConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg SASLTLSConfig
|
||||
}{
|
||||
{
|
||||
name: "missing key",
|
||||
cfg: SASLTLSConfig{
|
||||
TLSEnabled: true,
|
||||
TLSClientCert: "/tmp/client.crt",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing cert",
|
||||
cfg: SASLTLSConfig{
|
||||
TLSEnabled: true,
|
||||
TLSClientKey: "/tmp/client.key",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ConfigureSASLTLS(sarama.NewConfig(), tt.cfg)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "both tls_client_cert and tls_client_key must be provided") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSASLTLSConfiguresSCRAMSHA256(t *testing.T) {
|
||||
config := sarama.NewConfig()
|
||||
err := ConfigureSASLTLS(config, SASLTLSConfig{
|
||||
SASLEnabled: true,
|
||||
SASLMechanism: "SCRAM-SHA-256",
|
||||
SASLUsername: "alice",
|
||||
SASLPassword: "secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ConfigureSASLTLS returned error: %v", err)
|
||||
}
|
||||
|
||||
if !config.Net.SASL.Enable {
|
||||
t.Fatal("expected SASL to be enabled")
|
||||
}
|
||||
if config.Net.SASL.Mechanism != sarama.SASLTypeSCRAMSHA256 {
|
||||
t.Fatalf("unexpected mechanism: %v", config.Net.SASL.Mechanism)
|
||||
}
|
||||
if config.Net.SASL.SCRAMClientGeneratorFunc == nil {
|
||||
t.Fatal("expected SCRAM client generator")
|
||||
}
|
||||
}
|
||||
@@ -10,15 +10,11 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
|
||||
)
|
||||
|
||||
const lifecycleXMLKey = "s3-bucket-lifecycle-configuration-xml"
|
||||
|
||||
// detectBucketsWithLifecycleRules scans all S3 buckets to find those
|
||||
// with lifecycle rules, either TTL entries in filer.conf or lifecycle
|
||||
// XML stored in bucket metadata.
|
||||
// with lifecycle (TTL) rules configured in filer.conf.
|
||||
func (h *Handler) detectBucketsWithLifecycleRules(
|
||||
ctx context.Context,
|
||||
filerClient filer_pb.SeaweedFilerClient,
|
||||
@@ -57,38 +53,25 @@ func (h *Handler) detectBucketsWithLifecycleRules(
|
||||
continue
|
||||
}
|
||||
|
||||
// Check for lifecycle rules from two sources:
|
||||
// 1. filer.conf TTLs (legacy Expiration.Days fast path)
|
||||
// 2. Stored lifecycle XML in bucket metadata (full rule support)
|
||||
// Derive the collection name for this bucket.
|
||||
collection := bucketName
|
||||
ttls := fc.GetCollectionTtls(collection)
|
||||
|
||||
hasLifecycleXML := entry.Extended != nil && len(entry.Extended[lifecycleXMLKey]) > 0
|
||||
versioningStatus := ""
|
||||
if entry.Extended != nil {
|
||||
versioningStatus = string(entry.Extended[s3_constants.ExtVersioningKey])
|
||||
}
|
||||
|
||||
ruleCount := int64(len(ttls))
|
||||
if !hasLifecycleXML && ruleCount == 0 {
|
||||
if len(ttls) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
glog.V(2).Infof("s3_lifecycle: bucket %s has %d TTL rule(s), lifecycle_xml=%v, versioning=%s",
|
||||
bucketName, ruleCount, hasLifecycleXML, versioningStatus)
|
||||
glog.V(2).Infof("s3_lifecycle: bucket %s has %d lifecycle rule(s)", bucketName, len(ttls))
|
||||
|
||||
proposal := &plugin_pb.JobProposal{
|
||||
ProposalId: fmt.Sprintf("s3_lifecycle:%s", bucketName),
|
||||
JobType: jobType,
|
||||
Summary: fmt.Sprintf("Lifecycle management for bucket %s", bucketName),
|
||||
Summary: fmt.Sprintf("Lifecycle management for bucket %s (%d rules)", bucketName, len(ttls)),
|
||||
DedupeKey: fmt.Sprintf("s3_lifecycle:%s", bucketName),
|
||||
Parameters: map[string]*plugin_pb.ConfigValue{
|
||||
"bucket": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: bucketName}},
|
||||
"buckets_path": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: bucketsPath}},
|
||||
"collection": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: collection}},
|
||||
"rule_count": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: ruleCount}},
|
||||
"has_lifecycle_xml": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: hasLifecycleXML}},
|
||||
"versioning_status": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: versioningStatus}},
|
||||
"bucket": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: bucketName}},
|
||||
"buckets_path": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: bucketsPath}},
|
||||
"collection": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: collection}},
|
||||
"rule_count": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(len(ttls))}},
|
||||
},
|
||||
Labels: map[string]string{
|
||||
"bucket": bucketName,
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
func TestBucketHasLifecycleXML(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
extended map[string][]byte
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "has_lifecycle_xml",
|
||||
extended: map[string][]byte{lifecycleXMLKey: []byte("<LifecycleConfiguration/>")},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "empty_lifecycle_xml",
|
||||
extended: map[string][]byte{lifecycleXMLKey: {}},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "no_lifecycle_xml",
|
||||
extended: map[string][]byte{"other-key": []byte("value")},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "nil_extended",
|
||||
extended: nil,
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := tt.extended != nil && len(tt.extended[lifecycleXMLKey]) > 0
|
||||
if got != tt.want {
|
||||
t.Errorf("hasLifecycleXML = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketVersioningStatus(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
extended map[string][]byte
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "versioning_enabled",
|
||||
extended: map[string][]byte{
|
||||
s3_constants.ExtVersioningKey: []byte("Enabled"),
|
||||
},
|
||||
want: "Enabled",
|
||||
},
|
||||
{
|
||||
name: "versioning_suspended",
|
||||
extended: map[string][]byte{
|
||||
s3_constants.ExtVersioningKey: []byte("Suspended"),
|
||||
},
|
||||
want: "Suspended",
|
||||
},
|
||||
{
|
||||
name: "no_versioning",
|
||||
extended: map[string][]byte{},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "nil_extended",
|
||||
extended: nil,
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var got string
|
||||
if tt.extended != nil {
|
||||
got = string(tt.extended[s3_constants.ExtVersioningKey])
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("versioningStatus = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectionProposalParameters(t *testing.T) {
|
||||
// Verify that bucket entries with lifecycle XML or TTL rules produce
|
||||
// proposals with the expected parameters.
|
||||
t.Run("bucket_with_lifecycle_xml_and_versioning", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "my-bucket",
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
lifecycleXMLKey: []byte(`<LifecycleConfiguration><Rule><Status>Enabled</Status></Rule></LifecycleConfiguration>`),
|
||||
s3_constants.ExtVersioningKey: []byte("Enabled"),
|
||||
},
|
||||
}
|
||||
|
||||
hasXML := entry.Extended != nil && len(entry.Extended[lifecycleXMLKey]) > 0
|
||||
versioning := ""
|
||||
if entry.Extended != nil {
|
||||
versioning = string(entry.Extended[s3_constants.ExtVersioningKey])
|
||||
}
|
||||
|
||||
if !hasXML {
|
||||
t.Error("expected hasLifecycleXML=true")
|
||||
}
|
||||
if versioning != "Enabled" {
|
||||
t.Errorf("expected versioning=Enabled, got %q", versioning)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("bucket_without_lifecycle_or_ttl_is_skipped", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "empty-bucket",
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{},
|
||||
}
|
||||
|
||||
hasXML := entry.Extended != nil && len(entry.Extended[lifecycleXMLKey]) > 0
|
||||
ttlCount := 0 // simulated: no TTL rules in filer.conf
|
||||
|
||||
if hasXML || ttlCount > 0 {
|
||||
t.Error("expected bucket to be skipped (no lifecycle XML, no TTLs)")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -2,12 +2,9 @@ package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,11 +13,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
)
|
||||
|
||||
var errLimitReached = errors.New("limit reached")
|
||||
|
||||
type executionResult struct {
|
||||
objectsExpired int64
|
||||
objectsScanned int64
|
||||
@@ -43,37 +37,17 @@ func (h *Handler) executeLifecycleForBucket(
|
||||
) (*executionResult, error) {
|
||||
result := &executionResult{}
|
||||
|
||||
// Try to load lifecycle rules from stored XML first (full rule evaluation).
|
||||
// Fall back to filer.conf TTL-only evaluation only if no XML is configured.
|
||||
// If XML exists but is malformed, fail closed (don't fall back to TTL,
|
||||
// which could apply broader rules and delete objects the XML rules would keep).
|
||||
// Transient filer errors fall back to TTL with a warning.
|
||||
lifecycleRules, xmlErr := loadLifecycleRulesFromBucket(ctx, filerClient, bucketsPath, bucket)
|
||||
if xmlErr != nil && errors.Is(xmlErr, errMalformedLifecycleXML) {
|
||||
glog.Errorf("s3_lifecycle: bucket %s: %v (skipping bucket)", bucket, xmlErr)
|
||||
return result, xmlErr
|
||||
// Load filer.conf to verify TTL rules still exist.
|
||||
fc, err := loadFilerConf(ctx, filerClient)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("load filer conf: %w", err)
|
||||
}
|
||||
if xmlErr != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: bucket %s: transient error loading lifecycle XML: %v, falling back to TTL", bucket, xmlErr)
|
||||
}
|
||||
// lifecycleRules is non-nil when XML was present (even if empty/all disabled).
|
||||
// Only fall back to TTL when XML was truly absent (nil).
|
||||
xmlPresent := xmlErr == nil && lifecycleRules != nil
|
||||
useRuleEval := xmlPresent && len(lifecycleRules) > 0
|
||||
|
||||
if !useRuleEval && !xmlPresent {
|
||||
// Fall back to filer.conf TTL rules only when no lifecycle XML exists.
|
||||
// When XML is present but has no effective rules, skip TTL fallback.
|
||||
fc, err := loadFilerConf(ctx, filerClient)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("load filer conf: %w", err)
|
||||
}
|
||||
collection := bucket
|
||||
ttlRules := fc.GetCollectionTtls(collection)
|
||||
if len(ttlRules) == 0 {
|
||||
glog.V(1).Infof("s3_lifecycle: bucket %s has no lifecycle rules, skipping", bucket)
|
||||
return result, nil
|
||||
}
|
||||
collection := bucket
|
||||
ttlRules := fc.GetCollectionTtls(collection)
|
||||
if len(ttlRules) == 0 {
|
||||
glog.V(1).Infof("s3_lifecycle: bucket %s has no lifecycle rules, skipping", bucket)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
|
||||
@@ -82,23 +56,14 @@ func (h *Handler) executeLifecycleForBucket(
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING,
|
||||
ProgressPercent: 10,
|
||||
Stage: "scanning",
|
||||
Message: fmt.Sprintf("scanning bucket %s for expired objects", bucket),
|
||||
Message: fmt.Sprintf("scanning bucket %s for expired objects (%d rules)", bucket, len(ttlRules)),
|
||||
})
|
||||
|
||||
// Shared budget across all phases so we don't exceed MaxDeletesPerBucket.
|
||||
remaining := config.MaxDeletesPerBucket
|
||||
|
||||
// Find expired objects using rule-based evaluation or TTL fallback.
|
||||
var expired []expiredObject
|
||||
var scanned int64
|
||||
var err error
|
||||
if useRuleEval {
|
||||
expired, scanned, err = listExpiredObjectsByRules(ctx, filerClient, bucketsPath, bucket, lifecycleRules, remaining)
|
||||
} else if !xmlPresent {
|
||||
// TTL-only scan when no lifecycle XML exists.
|
||||
expired, scanned, err = listExpiredObjects(ctx, filerClient, bucketsPath, bucket, remaining)
|
||||
}
|
||||
// When xmlPresent but no effective rules (all disabled), skip object scanning.
|
||||
// Find expired objects.
|
||||
expired, scanned, err := listExpiredObjects(ctx, filerClient, bucketsPath, bucket, remaining)
|
||||
result.objectsScanned = scanned
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("list expired objects: %w", err)
|
||||
@@ -175,9 +140,6 @@ func (h *Handler) executeLifecycleForBucket(
|
||||
})
|
||||
}
|
||||
|
||||
// Clean up .versions directories left empty after version deletion.
|
||||
cleanupEmptyVersionsDirectories(ctx, filerClient, expired)
|
||||
|
||||
remaining -= result.objectsExpired + result.errors
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
@@ -191,7 +153,7 @@ func (h *Handler) executeLifecycleForBucket(
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING,
|
||||
Stage: "cleaning_delete_markers", Message: "cleaning expired delete markers",
|
||||
})
|
||||
cleaned, cleanErrs, cleanCtxErr := cleanupDeleteMarkers(ctx, filerClient, bucketsPath, bucket, lifecycleRules, remaining)
|
||||
cleaned, cleanErrs, cleanCtxErr := cleanupDeleteMarkers(ctx, filerClient, bucketsPath, bucket, remaining)
|
||||
result.deleteMarkersClean = int64(cleaned)
|
||||
result.errors += int64(cleanErrs)
|
||||
if cleanCtxErr != nil {
|
||||
@@ -204,23 +166,7 @@ func (h *Handler) executeLifecycleForBucket(
|
||||
}
|
||||
|
||||
// Abort incomplete multipart uploads.
|
||||
// When lifecycle XML exists, evaluate each upload against the rules
|
||||
// (respecting per-rule prefix filters and DaysAfterInitiation).
|
||||
// Fall back to worker config abort_mpu_days only when no lifecycle
|
||||
// XML is configured for the bucket.
|
||||
if xmlPresent && remaining > 0 {
|
||||
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
|
||||
JobId: jobID, JobType: jobType,
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING,
|
||||
Stage: "aborting_mpus", Message: "evaluating MPU abort rules",
|
||||
})
|
||||
aborted, abortErrs, abortCtxErr := abortMPUsByRules(ctx, filerClient, bucketsPath, bucket, lifecycleRules, remaining)
|
||||
result.mpuAborted = int64(aborted)
|
||||
result.errors += int64(abortErrs)
|
||||
if abortCtxErr != nil {
|
||||
return result, abortCtxErr
|
||||
}
|
||||
} else if !xmlPresent && config.AbortMPUDays > 0 && remaining > 0 {
|
||||
if config.AbortMPUDays > 0 && remaining > 0 {
|
||||
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
|
||||
JobId: jobID, JobType: jobType,
|
||||
State: plugin_pb.JobState_JOB_STATE_RUNNING,
|
||||
@@ -237,19 +183,18 @@ func (h *Handler) executeLifecycleForBucket(
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// cleanupDeleteMarkers scans versioned objects and removes delete markers
|
||||
// that are the sole remaining version. This matches AWS S3
|
||||
// ExpiredObjectDeleteMarker semantics: a delete marker is only removed when
|
||||
// it is the only version of an object (no non-current versions behind it).
|
||||
// cleanupDeleteMarkers scans the bucket for entries marked as delete markers
|
||||
// (via the S3 versioning extended attribute) and removes them.
|
||||
//
|
||||
// This phase should run AFTER NoncurrentVersionExpiration (PR 4) so that
|
||||
// non-current versions have already been cleaned up, potentially leaving
|
||||
// delete markers as sole versions eligible for removal.
|
||||
// NOTE: This currently removes delete markers unconditionally without checking
|
||||
// whether prior non-expired versions exist. In versioned buckets, removing a
|
||||
// delete marker can resurface an older version. A future enhancement should
|
||||
// query version metadata before removal to match AWS ExpiredObjectDeleteMarker
|
||||
// semantics (only remove when no non-current versions remain).
|
||||
func cleanupDeleteMarkers(
|
||||
ctx context.Context,
|
||||
client filer_pb.SeaweedFilerClient,
|
||||
bucketsPath, bucket string,
|
||||
rules []s3lifecycle.Rule,
|
||||
limit int64,
|
||||
) (cleaned, errors int, ctxErr error) {
|
||||
bucketPath := path.Join(bucketsPath, bucket)
|
||||
@@ -265,72 +210,14 @@ func cleanupDeleteMarkers(
|
||||
|
||||
listErr := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
if entry.IsDirectory {
|
||||
if dir == bucketPath && entry.Name == s3_constants.MultipartUploadsFolder {
|
||||
return nil
|
||||
// Skip .uploads directories.
|
||||
if entry.Name != ".uploads" {
|
||||
dirsToProcess = append(dirsToProcess, path.Join(dir, entry.Name))
|
||||
}
|
||||
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
|
||||
versionsDir := path.Join(dir, entry.Name)
|
||||
// Check if the latest version is a delete marker.
|
||||
latestIsMarker := string(entry.Extended[s3_constants.ExtLatestVersionIsDeleteMarker]) == "true"
|
||||
if !latestIsMarker {
|
||||
return nil
|
||||
}
|
||||
// Count versions in the directory.
|
||||
versionCount := 0
|
||||
countErr := filer_pb.SeaweedList(ctx, client, versionsDir, "", func(ve *filer_pb.Entry, _ bool) error {
|
||||
if !ve.IsDirectory {
|
||||
versionCount++
|
||||
}
|
||||
return nil
|
||||
}, "", false, 10000)
|
||||
if countErr != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: failed to count versions in %s: %v", versionsDir, countErr)
|
||||
errors++
|
||||
return nil
|
||||
}
|
||||
// Only remove if the delete marker is the sole version.
|
||||
if versionCount != 1 {
|
||||
return nil
|
||||
}
|
||||
// Check that a matching ExpiredObjectDeleteMarker rule exists.
|
||||
// The rule's prefix filter must match this object's key.
|
||||
relDir := strings.TrimPrefix(versionsDir, bucketPath+"/")
|
||||
objKey := strings.TrimSuffix(relDir, s3_constants.VersionsFolder)
|
||||
if len(rules) > 0 && !matchesDeleteMarkerRule(rules, objKey) {
|
||||
return nil
|
||||
}
|
||||
// Find and remove the sole delete marker entry.
|
||||
removedHere := false
|
||||
removeErr := filer_pb.SeaweedList(ctx, client, versionsDir, "", func(ve *filer_pb.Entry, _ bool) error {
|
||||
if !ve.IsDirectory && isDeleteMarker(ve) {
|
||||
if err := filer_pb.DoRemove(ctx, client, versionsDir, ve.Name, true, false, false, false, nil); err != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: failed to remove delete marker %s/%s: %v", versionsDir, ve.Name, err)
|
||||
errors++
|
||||
} else {
|
||||
cleaned++
|
||||
removedHere = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}, "", false, 10)
|
||||
if removeErr != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: failed to scan for delete marker in %s: %v", versionsDir, removeErr)
|
||||
}
|
||||
// Remove the now-empty .versions directory only if we
|
||||
// actually deleted the marker in this specific directory.
|
||||
if removedHere {
|
||||
_ = filer_pb.DoRemove(ctx, client, dir, entry.Name, true, true, true, false, nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
dirsToProcess = append(dirsToProcess, path.Join(dir, entry.Name))
|
||||
return nil
|
||||
}
|
||||
|
||||
// For non-versioned objects: only clean up if explicitly a delete marker
|
||||
// and a matching rule exists.
|
||||
relKey := strings.TrimPrefix(path.Join(dir, entry.Name), bucketPath+"/")
|
||||
if isDeleteMarker(entry) && matchesDeleteMarkerRule(rules, relKey) {
|
||||
if isDeleteMarker(entry) {
|
||||
if err := filer_pb.DoRemove(ctx, client, dir, entry.Name, true, false, false, false, nil); err != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: failed to remove delete marker %s/%s: %v", dir, entry.Name, err)
|
||||
errors++
|
||||
@@ -364,74 +251,6 @@ func isDeleteMarker(entry *filer_pb.Entry) bool {
|
||||
return string(entry.Extended[s3_constants.ExtDeleteMarkerKey]) == "true"
|
||||
}
|
||||
|
||||
// matchesDeleteMarkerRule checks if any enabled ExpiredObjectDeleteMarker rule
|
||||
// matches the given object key using the full filter model (prefix, tags, size).
|
||||
// When no lifecycle rules are provided (nil means no XML configured),
|
||||
// falls back to legacy behavior (returns true to allow cleanup).
|
||||
// A non-nil empty slice means XML was present but had no matching rules,
|
||||
// so cleanup is not allowed.
|
||||
func matchesDeleteMarkerRule(rules []s3lifecycle.Rule, objKey string) bool {
|
||||
if rules == nil {
|
||||
return true // legacy fallback: no lifecycle XML configured
|
||||
}
|
||||
// Delete markers have no size or tags, so build a minimal ObjectInfo.
|
||||
obj := s3lifecycle.ObjectInfo{Key: objKey}
|
||||
for _, r := range rules {
|
||||
if r.Status == "Enabled" && r.ExpiredObjectDeleteMarker && s3lifecycle.MatchesFilter(r, obj) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// abortMPUsByRules scans the .uploads directory and evaluates each upload
|
||||
// against lifecycle rules using EvaluateMPUAbort, which respects per-rule
|
||||
// prefix filters and DaysAfterInitiation thresholds.
|
||||
func abortMPUsByRules(
|
||||
ctx context.Context,
|
||||
client filer_pb.SeaweedFilerClient,
|
||||
bucketsPath, bucket string,
|
||||
rules []s3lifecycle.Rule,
|
||||
limit int64,
|
||||
) (aborted, errs int, ctxErr error) {
|
||||
uploadsDir := path.Join(bucketsPath, bucket, ".uploads")
|
||||
now := time.Now()
|
||||
|
||||
listErr := filer_pb.SeaweedList(ctx, client, uploadsDir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !entry.IsDirectory {
|
||||
return nil
|
||||
}
|
||||
if entry.Attributes == nil || entry.Attributes.Crtime <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
createdAt := time.Unix(entry.Attributes.Crtime, 0)
|
||||
result := s3lifecycle.EvaluateMPUAbort(rules, entry.Name, createdAt, now)
|
||||
if result.Action == s3lifecycle.ActionAbortMultipartUpload {
|
||||
uploadPath := path.Join(uploadsDir, entry.Name)
|
||||
if err := filer_pb.DoRemove(ctx, client, uploadsDir, entry.Name, true, true, true, false, nil); err != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: failed to abort MPU %s: %v", uploadPath, err)
|
||||
errs++
|
||||
} else {
|
||||
aborted++
|
||||
}
|
||||
}
|
||||
|
||||
if limit > 0 && int64(aborted+errs) >= limit {
|
||||
return errLimitReached
|
||||
}
|
||||
return nil
|
||||
}, "", false, 10000)
|
||||
|
||||
if listErr != nil && !errors.Is(listErr, errLimitReached) {
|
||||
return aborted, errs, fmt.Errorf("list uploads in %s: %w", uploadsDir, listErr)
|
||||
}
|
||||
return aborted, errs, nil
|
||||
}
|
||||
|
||||
// abortIncompleteMPUs scans the .uploads directory under a bucket and
|
||||
// removes multipart upload entries older than the specified number of days.
|
||||
func abortIncompleteMPUs(
|
||||
@@ -507,372 +326,3 @@ func deleteExpiredObjects(
|
||||
func nowUnix() int64 {
|
||||
return time.Now().Unix()
|
||||
}
|
||||
|
||||
// listExpiredObjectsByRules scans a bucket directory tree and evaluates
|
||||
// lifecycle rules against each object using the s3lifecycle evaluator.
|
||||
// This function handles non-versioned objects (IsLatest=true). Versioned
|
||||
// objects in .versions directories are handled by processVersionsDirectory
|
||||
// (added in a separate change for NoncurrentVersionExpiration support).
|
||||
func listExpiredObjectsByRules(
|
||||
ctx context.Context,
|
||||
client filer_pb.SeaweedFilerClient,
|
||||
bucketsPath, bucket string,
|
||||
rules []s3lifecycle.Rule,
|
||||
limit int64,
|
||||
) ([]expiredObject, int64, error) {
|
||||
var expired []expiredObject
|
||||
var scanned int64
|
||||
|
||||
bucketPath := path.Join(bucketsPath, bucket)
|
||||
now := time.Now()
|
||||
needTags := s3lifecycle.HasTagRules(rules)
|
||||
|
||||
dirsToProcess := []string{bucketPath}
|
||||
for len(dirsToProcess) > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return expired, scanned, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
dir := dirsToProcess[0]
|
||||
dirsToProcess = dirsToProcess[1:]
|
||||
|
||||
limitReached := false
|
||||
err := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
if entry.IsDirectory {
|
||||
if dir == bucketPath && entry.Name == s3_constants.MultipartUploadsFolder {
|
||||
return nil // skip .uploads at bucket root only
|
||||
}
|
||||
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
|
||||
versionsDir := path.Join(dir, entry.Name)
|
||||
|
||||
// Evaluate Expiration rules against the latest version.
|
||||
// In versioned buckets, data lives in .versions/ directories,
|
||||
// so we must evaluate the latest version here — it is never
|
||||
// seen as a regular file entry in the parent directory.
|
||||
if obj, ok := latestVersionExpiredByRules(ctx, client, entry, versionsDir, bucketPath, rules, now, needTags); ok {
|
||||
expired = append(expired, obj)
|
||||
scanned++
|
||||
if limit > 0 && int64(len(expired)) >= limit {
|
||||
limitReached = true
|
||||
return errLimitReached
|
||||
}
|
||||
}
|
||||
|
||||
// Process noncurrent versions.
|
||||
vExpired, vScanned, vErr := processVersionsDirectory(ctx, client, versionsDir, bucketPath, rules, now, needTags, limit-int64(len(expired)))
|
||||
if vErr != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: %v", vErr)
|
||||
return vErr
|
||||
}
|
||||
expired = append(expired, vExpired...)
|
||||
scanned += vScanned
|
||||
if limit > 0 && int64(len(expired)) >= limit {
|
||||
limitReached = true
|
||||
return errLimitReached
|
||||
}
|
||||
return nil
|
||||
}
|
||||
dirsToProcess = append(dirsToProcess, path.Join(dir, entry.Name))
|
||||
return nil
|
||||
}
|
||||
scanned++
|
||||
|
||||
// Skip objects already handled by TTL fast path.
|
||||
if entry.Attributes != nil && entry.Attributes.TtlSec > 0 {
|
||||
expirationUnix := entry.Attributes.Crtime + int64(entry.Attributes.TtlSec)
|
||||
if expirationUnix > nowUnix() {
|
||||
return nil // will be expired by RocksDB compaction
|
||||
}
|
||||
}
|
||||
|
||||
// Build ObjectInfo for the evaluator.
|
||||
relKey := strings.TrimPrefix(path.Join(dir, entry.Name), bucketPath+"/")
|
||||
objInfo := s3lifecycle.ObjectInfo{
|
||||
Key: relKey,
|
||||
IsLatest: true, // non-versioned objects are always "latest"
|
||||
}
|
||||
if entry.Attributes != nil {
|
||||
objInfo.Size = int64(entry.Attributes.GetFileSize())
|
||||
if entry.Attributes.Mtime > 0 {
|
||||
objInfo.ModTime = time.Unix(entry.Attributes.Mtime, 0)
|
||||
} else if entry.Attributes.Crtime > 0 {
|
||||
objInfo.ModTime = time.Unix(entry.Attributes.Crtime, 0)
|
||||
}
|
||||
}
|
||||
if needTags {
|
||||
objInfo.Tags = s3lifecycle.ExtractTags(entry.Extended)
|
||||
}
|
||||
|
||||
result := s3lifecycle.Evaluate(rules, objInfo, now)
|
||||
if result.Action == s3lifecycle.ActionDeleteObject {
|
||||
expired = append(expired, expiredObject{dir: dir, name: entry.Name})
|
||||
}
|
||||
|
||||
if limit > 0 && int64(len(expired)) >= limit {
|
||||
limitReached = true
|
||||
return errLimitReached
|
||||
}
|
||||
return nil
|
||||
}, "", false, 10000)
|
||||
|
||||
if err != nil && !errors.Is(err, errLimitReached) {
|
||||
return expired, scanned, fmt.Errorf("list %s: %w", dir, err)
|
||||
}
|
||||
|
||||
if limitReached || (limit > 0 && int64(len(expired)) >= limit) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return expired, scanned, nil
|
||||
}
|
||||
|
||||
// processVersionsDirectory evaluates NoncurrentVersionExpiration rules
|
||||
// against all versions in a .versions directory.
|
||||
func processVersionsDirectory(
|
||||
ctx context.Context,
|
||||
client filer_pb.SeaweedFilerClient,
|
||||
versionsDir, bucketPath string,
|
||||
rules []s3lifecycle.Rule,
|
||||
now time.Time,
|
||||
needTags bool,
|
||||
limit int64,
|
||||
) ([]expiredObject, int64, error) {
|
||||
var expired []expiredObject
|
||||
var scanned int64
|
||||
|
||||
// Check if any rule has NoncurrentVersionExpiration.
|
||||
hasNoncurrentRules := false
|
||||
for _, r := range rules {
|
||||
if r.Status == "Enabled" && r.NoncurrentVersionExpirationDays > 0 {
|
||||
hasNoncurrentRules = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasNoncurrentRules {
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
// List all versions in this directory.
|
||||
var versions []*filer_pb.Entry
|
||||
listErr := filer_pb.SeaweedList(ctx, client, versionsDir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
if !entry.IsDirectory {
|
||||
versions = append(versions, entry)
|
||||
}
|
||||
return nil
|
||||
}, "", false, 10000)
|
||||
if listErr != nil {
|
||||
return nil, 0, fmt.Errorf("list versions in %s: %w", versionsDir, listErr)
|
||||
}
|
||||
if len(versions) <= 1 {
|
||||
return nil, 0, nil // only one version (the latest), nothing to expire
|
||||
}
|
||||
|
||||
// Sort by version timestamp, newest first.
|
||||
sortVersionsByVersionId(versions)
|
||||
|
||||
// Derive the object key from the .versions directory path.
|
||||
// e.g., /buckets/mybucket/path/to/key.versions -> path/to/key
|
||||
relDir := strings.TrimPrefix(versionsDir, bucketPath+"/")
|
||||
objKey := strings.TrimSuffix(relDir, s3_constants.VersionsFolder)
|
||||
|
||||
// Walk versions: first is latest, rest are non-current.
|
||||
noncurrentIndex := 0
|
||||
for i := 1; i < len(versions); i++ {
|
||||
entry := versions[i]
|
||||
scanned++
|
||||
|
||||
// Skip delete markers from expiration evaluation, but count
|
||||
// them toward NewerNoncurrentVersions so data versions get
|
||||
// the correct noncurrent index.
|
||||
if isDeleteMarker(entry) {
|
||||
noncurrentIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
// Determine successor's timestamp (the version that replaced this one).
|
||||
successorEntry := versions[i-1]
|
||||
successorVersionId := strings.TrimPrefix(successorEntry.Name, "v_")
|
||||
successorTime := s3lifecycle.GetVersionTimestamp(successorVersionId)
|
||||
if successorTime.IsZero() && successorEntry.Attributes != nil && successorEntry.Attributes.Mtime > 0 {
|
||||
successorTime = time.Unix(successorEntry.Attributes.Mtime, 0)
|
||||
}
|
||||
|
||||
objInfo := s3lifecycle.ObjectInfo{
|
||||
Key: objKey,
|
||||
IsLatest: false,
|
||||
SuccessorModTime: successorTime,
|
||||
NumVersions: len(versions),
|
||||
NoncurrentIndex: noncurrentIndex,
|
||||
}
|
||||
if entry.Attributes != nil {
|
||||
objInfo.Size = int64(entry.Attributes.GetFileSize())
|
||||
if entry.Attributes.Mtime > 0 {
|
||||
objInfo.ModTime = time.Unix(entry.Attributes.Mtime, 0)
|
||||
}
|
||||
}
|
||||
if needTags {
|
||||
objInfo.Tags = s3lifecycle.ExtractTags(entry.Extended)
|
||||
}
|
||||
|
||||
// Evaluate using the detailed ShouldExpireNoncurrentVersion which
|
||||
// handles NewerNoncurrentVersions.
|
||||
for _, rule := range rules {
|
||||
if s3lifecycle.ShouldExpireNoncurrentVersion(rule, objInfo, noncurrentIndex, now) {
|
||||
expired = append(expired, expiredObject{dir: versionsDir, name: entry.Name})
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
noncurrentIndex++
|
||||
|
||||
if limit > 0 && int64(len(expired)) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return expired, scanned, nil
|
||||
}
|
||||
|
||||
// latestVersionExpiredByRules evaluates Expiration rules (Days/Date) against
|
||||
// the latest version in a .versions directory. In versioned buckets all data
|
||||
// lives inside .versions/ directories, so the latest version is never seen as
|
||||
// a regular file entry during the bucket walk. Without this check, Expiration
|
||||
// rules would never fire for versioned objects (issue #8757).
|
||||
//
|
||||
// The .versions directory entry caches metadata about the latest version in
|
||||
// its Extended attributes, so we can evaluate expiration without an extra
|
||||
// filer round-trip.
|
||||
func latestVersionExpiredByRules(
|
||||
ctx context.Context,
|
||||
client filer_pb.SeaweedFilerClient,
|
||||
dirEntry *filer_pb.Entry,
|
||||
versionsDir, bucketPath string,
|
||||
rules []s3lifecycle.Rule,
|
||||
now time.Time,
|
||||
needTags bool,
|
||||
) (expiredObject, bool) {
|
||||
if dirEntry.Extended == nil {
|
||||
return expiredObject{}, false
|
||||
}
|
||||
|
||||
// Skip if the latest version is a delete marker — those are handled
|
||||
// by the ExpiredObjectDeleteMarker rule in cleanupDeleteMarkers.
|
||||
if string(dirEntry.Extended[s3_constants.ExtLatestVersionIsDeleteMarker]) == "true" {
|
||||
return expiredObject{}, false
|
||||
}
|
||||
|
||||
latestFileName := string(dirEntry.Extended[s3_constants.ExtLatestVersionFileNameKey])
|
||||
if latestFileName == "" {
|
||||
return expiredObject{}, false
|
||||
}
|
||||
|
||||
// Derive the object key: /buckets/b/path/key.versions → path/key
|
||||
relDir := strings.TrimPrefix(versionsDir, bucketPath+"/")
|
||||
objKey := strings.TrimSuffix(relDir, s3_constants.VersionsFolder)
|
||||
|
||||
objInfo := s3lifecycle.ObjectInfo{
|
||||
Key: objKey,
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
// Populate ModTime from cached metadata.
|
||||
if mtimeStr := string(dirEntry.Extended[s3_constants.ExtLatestVersionMtimeKey]); mtimeStr != "" {
|
||||
if mtime, err := strconv.ParseInt(mtimeStr, 10, 64); err == nil {
|
||||
objInfo.ModTime = time.Unix(mtime, 0)
|
||||
}
|
||||
}
|
||||
if objInfo.ModTime.IsZero() && dirEntry.Attributes != nil && dirEntry.Attributes.Mtime > 0 {
|
||||
objInfo.ModTime = time.Unix(dirEntry.Attributes.Mtime, 0)
|
||||
}
|
||||
|
||||
// Populate Size from cached metadata.
|
||||
if sizeStr := string(dirEntry.Extended[s3_constants.ExtLatestVersionSizeKey]); sizeStr != "" {
|
||||
if size, err := strconv.ParseInt(sizeStr, 10, 64); err == nil {
|
||||
objInfo.Size = size
|
||||
}
|
||||
}
|
||||
|
||||
if needTags {
|
||||
// Tags are stored on the version file entry, not the .versions
|
||||
// directory. Fetch the actual version file to get them.
|
||||
resp, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: versionsDir,
|
||||
Name: latestFileName,
|
||||
})
|
||||
if err == nil && resp.Entry != nil {
|
||||
objInfo.Tags = s3lifecycle.ExtractTags(resp.Entry.Extended)
|
||||
}
|
||||
}
|
||||
|
||||
result := s3lifecycle.Evaluate(rules, objInfo, now)
|
||||
if result.Action == s3lifecycle.ActionDeleteObject {
|
||||
return expiredObject{dir: versionsDir, name: latestFileName}, true
|
||||
}
|
||||
|
||||
return expiredObject{}, false
|
||||
}
|
||||
|
||||
// cleanupEmptyVersionsDirectories removes .versions directories that became
|
||||
// empty after their contents were deleted. This is called after
|
||||
// deleteExpiredObjects to avoid leaving orphaned directories.
|
||||
func cleanupEmptyVersionsDirectories(
|
||||
ctx context.Context,
|
||||
client filer_pb.SeaweedFilerClient,
|
||||
deleted []expiredObject,
|
||||
) int {
|
||||
// Collect unique .versions directories that had entries deleted.
|
||||
versionsDirs := map[string]struct{}{}
|
||||
for _, obj := range deleted {
|
||||
if strings.HasSuffix(obj.dir, s3_constants.VersionsFolder) {
|
||||
versionsDirs[obj.dir] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
cleaned := 0
|
||||
for vDir := range versionsDirs {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
// Check if the directory is now empty.
|
||||
empty := true
|
||||
listErr := filer_pb.SeaweedList(ctx, client, vDir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
empty = false
|
||||
return errLimitReached // stop after first entry
|
||||
}, "", false, 1)
|
||||
|
||||
if listErr != nil && !errors.Is(listErr, errLimitReached) {
|
||||
glog.V(1).Infof("s3_lifecycle: failed to check if versions dir %s is empty: %v", vDir, listErr)
|
||||
continue
|
||||
}
|
||||
|
||||
if !empty {
|
||||
continue
|
||||
}
|
||||
|
||||
// Remove the empty .versions directory.
|
||||
parentDir, dirName := path.Split(vDir)
|
||||
parentDir = strings.TrimSuffix(parentDir, "/")
|
||||
if err := filer_pb.DoRemove(ctx, client, parentDir, dirName, false, true, true, false, nil); err != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: failed to clean up empty versions dir %s: %v", vDir, err)
|
||||
} else {
|
||||
cleaned++
|
||||
}
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
// sortVersionsByVersionId sorts version entries newest-first using full
|
||||
// version ID comparison (matching compareVersionIds in s3api_version_id.go).
|
||||
// This uses the complete version ID string, not just the decoded timestamp,
|
||||
// so entries with the same timestamp prefix are correctly ordered by their
|
||||
// random suffix.
|
||||
func sortVersionsByVersionId(versions []*filer_pb.Entry) {
|
||||
sort.Slice(versions, func(i, j int) bool {
|
||||
vidI := strings.TrimPrefix(versions[i].Name, "v_")
|
||||
vidJ := strings.TrimPrefix(versions[j].Name, "v_")
|
||||
return s3lifecycle.CompareVersionIds(vidI, vidJ) < 0
|
||||
})
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
)
|
||||
|
||||
func TestMatchesDeleteMarkerRule(t *testing.T) {
|
||||
t.Run("nil_rules_legacy_fallback", func(t *testing.T) {
|
||||
if !matchesDeleteMarkerRule(nil, "any/key") {
|
||||
t.Error("nil rules should return true (legacy fallback)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty_rules_xml_present_no_match", func(t *testing.T) {
|
||||
rules := []s3lifecycle.Rule{}
|
||||
if matchesDeleteMarkerRule(rules, "any/key") {
|
||||
t.Error("empty rules (XML present) should return false")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("matching_prefix_rule", func(t *testing.T) {
|
||||
rules := []s3lifecycle.Rule{
|
||||
{ID: "cleanup", Status: "Enabled", Prefix: "logs/", ExpiredObjectDeleteMarker: true},
|
||||
}
|
||||
if !matchesDeleteMarkerRule(rules, "logs/app.log") {
|
||||
t.Error("should match rule with matching prefix")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("non_matching_prefix", func(t *testing.T) {
|
||||
rules := []s3lifecycle.Rule{
|
||||
{ID: "cleanup", Status: "Enabled", Prefix: "logs/", ExpiredObjectDeleteMarker: true},
|
||||
}
|
||||
if matchesDeleteMarkerRule(rules, "data/file.txt") {
|
||||
t.Error("should not match rule with non-matching prefix")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disabled_rule", func(t *testing.T) {
|
||||
rules := []s3lifecycle.Rule{
|
||||
{ID: "cleanup", Status: "Disabled", ExpiredObjectDeleteMarker: true},
|
||||
}
|
||||
if matchesDeleteMarkerRule(rules, "any/key") {
|
||||
t.Error("disabled rule should not match")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rule_without_delete_marker_flag", func(t *testing.T) {
|
||||
rules := []s3lifecycle.Rule{
|
||||
{ID: "expire", Status: "Enabled", ExpirationDays: 30},
|
||||
}
|
||||
if matchesDeleteMarkerRule(rules, "any/key") {
|
||||
t.Error("rule without ExpiredObjectDeleteMarker should not match")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("tag_filtered_rule_no_tags_on_marker", func(t *testing.T) {
|
||||
rules := []s3lifecycle.Rule{
|
||||
{
|
||||
ID: "tagged", Status: "Enabled",
|
||||
ExpiredObjectDeleteMarker: true,
|
||||
FilterTags: map[string]string{"env": "dev"},
|
||||
},
|
||||
}
|
||||
// Delete markers have no tags, so a tag-filtered rule should not match.
|
||||
if matchesDeleteMarkerRule(rules, "any/key") {
|
||||
t.Error("tag-filtered rule should not match delete marker (no tags)")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,781 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// testFilerServer is an in-memory filer gRPC server for integration tests.
|
||||
type testFilerServer struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
mu sync.RWMutex
|
||||
entries map[string]*filer_pb.Entry // key: "dir\x00name"
|
||||
}
|
||||
|
||||
func newTestFilerServer() *testFilerServer {
|
||||
return &testFilerServer{entries: make(map[string]*filer_pb.Entry)}
|
||||
}
|
||||
|
||||
func (s *testFilerServer) key(dir, name string) string { return dir + "\x00" + name }
|
||||
|
||||
func (s *testFilerServer) splitKey(key string) (string, string) {
|
||||
for i := range key {
|
||||
if key[i] == '\x00' {
|
||||
return key[:i], key[i+1:]
|
||||
}
|
||||
}
|
||||
return key, ""
|
||||
}
|
||||
|
||||
func (s *testFilerServer) putEntry(dir string, entry *filer_pb.Entry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.entries[s.key(dir, entry.Name)] = proto.Clone(entry).(*filer_pb.Entry)
|
||||
}
|
||||
|
||||
func (s *testFilerServer) getEntry(dir, name string) *filer_pb.Entry {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
e := s.entries[s.key(dir, name)]
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return proto.Clone(e).(*filer_pb.Entry)
|
||||
}
|
||||
|
||||
func (s *testFilerServer) hasEntry(dir, name string) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
_, ok := s.entries[s.key(dir, name)]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *testFilerServer) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
entry, found := s.entries[s.key(req.Directory, req.Name)]
|
||||
if !found {
|
||||
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil
|
||||
}
|
||||
|
||||
func (s *testFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
|
||||
// Snapshot entries under lock, then stream without holding the lock
|
||||
// (streaming callbacks may trigger DeleteEntry which needs a write lock).
|
||||
s.mu.RLock()
|
||||
var names []string
|
||||
for key := range s.entries {
|
||||
dir, name := s.splitKey(key)
|
||||
if dir == req.Directory {
|
||||
if req.StartFromFileName != "" && name <= req.StartFromFileName {
|
||||
continue
|
||||
}
|
||||
if req.Prefix != "" && !strings.HasPrefix(name, req.Prefix) {
|
||||
continue
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
// Clone entries while still holding the lock.
|
||||
type namedEntry struct {
|
||||
name string
|
||||
entry *filer_pb.Entry
|
||||
}
|
||||
snapshot := make([]namedEntry, 0, len(names))
|
||||
for _, name := range names {
|
||||
if req.Limit > 0 && uint32(len(snapshot)) >= req.Limit {
|
||||
break
|
||||
}
|
||||
snapshot = append(snapshot, namedEntry{
|
||||
name: name,
|
||||
entry: proto.Clone(s.entries[s.key(req.Directory, name)]).(*filer_pb.Entry),
|
||||
})
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
|
||||
// Stream responses without holding any lock.
|
||||
for _, ne := range snapshot {
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: ne.entry}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *testFilerServer) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.entries[s.key(req.Directory, req.Entry.Name)] = proto.Clone(req.Entry).(*filer_pb.Entry)
|
||||
return &filer_pb.CreateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *testFilerServer) DeleteEntry(_ context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
k := s.key(req.Directory, req.Name)
|
||||
if _, found := s.entries[k]; !found {
|
||||
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
delete(s.entries, k)
|
||||
if req.IsRecursive {
|
||||
// Delete all descendants: any entry whose directory starts with
|
||||
// the deleted path (handles nested subdirectories).
|
||||
deletedPath := req.Directory + "/" + req.Name
|
||||
for key := range s.entries {
|
||||
dir, _ := s.splitKey(key)
|
||||
if dir == deletedPath || strings.HasPrefix(dir, deletedPath+"/") {
|
||||
delete(s.entries, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &filer_pb.DeleteEntryResponse{}, nil
|
||||
}
|
||||
|
||||
// startTestFiler starts an in-memory filer gRPC server and returns a client.
|
||||
func startTestFiler(t *testing.T) (*testFilerServer, filer_pb.SeaweedFilerClient) {
|
||||
t.Helper()
|
||||
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
|
||||
server := newTestFilerServer()
|
||||
grpcServer := pb.NewGrpcServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, server)
|
||||
go func() { _ = grpcServer.Serve(lis) }()
|
||||
|
||||
t.Cleanup(func() {
|
||||
grpcServer.Stop()
|
||||
_ = lis.Close()
|
||||
})
|
||||
|
||||
host, portStr, err := net.SplitHostPort(lis.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil {
|
||||
t.Fatalf("parse port: %v", err)
|
||||
}
|
||||
addr := pb.NewServerAddress(host, 1, port)
|
||||
|
||||
conn, err := pb.GrpcDial(context.Background(), addr.ToGrpcAddress(), false, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
|
||||
return server, filer_pb.NewSeaweedFilerClient(conn)
|
||||
}
|
||||
|
||||
// Helper to create a version ID from a timestamp.
|
||||
func testVersionId(ts time.Time) string {
|
||||
inverted := math.MaxInt64 - ts.UnixNano()
|
||||
return fmt.Sprintf("%016x", inverted) + "0000000000000000"
|
||||
}
|
||||
|
||||
func TestIntegration_ListExpiredObjectsByRules(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "test-bucket"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
|
||||
now := time.Now()
|
||||
old := now.Add(-60 * 24 * time.Hour) // 60 days ago
|
||||
recent := now.Add(-5 * 24 * time.Hour) // 5 days ago
|
||||
|
||||
// Create bucket directory.
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
|
||||
// Create objects.
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "old-file.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: old.Unix(), FileSize: 1024},
|
||||
})
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "recent-file.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: recent.Unix(), FileSize: 1024},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "expire-30d", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
}}
|
||||
|
||||
expired, scanned, err := listExpiredObjectsByRules(context.Background(), client, bucketsPath, bucket, rules, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("listExpiredObjectsByRules: %v", err)
|
||||
}
|
||||
|
||||
if scanned != 2 {
|
||||
t.Errorf("expected 2 scanned, got %d", scanned)
|
||||
}
|
||||
if len(expired) != 1 {
|
||||
t.Fatalf("expected 1 expired, got %d", len(expired))
|
||||
}
|
||||
if expired[0].name != "old-file.txt" {
|
||||
t.Errorf("expected old-file.txt expired, got %s", expired[0].name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegration_ListExpiredObjectsByRules_TagFilter(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "tag-bucket"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
|
||||
old := time.Now().Add(-60 * 24 * time.Hour)
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
|
||||
// Object with matching tag.
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "tagged.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: old.Unix(), FileSize: 100},
|
||||
Extended: map[string][]byte{"X-Amz-Tagging-env": []byte("dev")},
|
||||
})
|
||||
// Object without tag.
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "untagged.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: old.Unix(), FileSize: 100},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "tag-expire", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
FilterTags: map[string]string{"env": "dev"},
|
||||
}}
|
||||
|
||||
expired, _, err := listExpiredObjectsByRules(context.Background(), client, bucketsPath, bucket, rules, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("listExpiredObjectsByRules: %v", err)
|
||||
}
|
||||
|
||||
if len(expired) != 1 {
|
||||
t.Fatalf("expected 1 expired (tagged only), got %d", len(expired))
|
||||
}
|
||||
if expired[0].name != "tagged.txt" {
|
||||
t.Errorf("expected tagged.txt, got %s", expired[0].name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegration_ProcessVersionsDirectory(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "versioned-bucket"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
versionsDir := bucketDir + "/key.versions"
|
||||
|
||||
now := time.Now()
|
||||
t1 := now.Add(-90 * 24 * time.Hour) // oldest
|
||||
t2 := now.Add(-60 * 24 * time.Hour)
|
||||
t3 := now.Add(-1 * 24 * time.Hour) // newest (latest)
|
||||
|
||||
vid1 := testVersionId(t1)
|
||||
vid2 := testVersionId(t2)
|
||||
vid3 := testVersionId(t3)
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "key.versions", IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(vid3),
|
||||
},
|
||||
})
|
||||
|
||||
// Three versions: vid3 (latest), vid2 (noncurrent), vid1 (noncurrent)
|
||||
server.putEntry(versionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vid3,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: t3.Unix(), FileSize: 100},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(vid3),
|
||||
},
|
||||
})
|
||||
server.putEntry(versionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vid2,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: t2.Unix(), FileSize: 100},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(vid2),
|
||||
},
|
||||
})
|
||||
server.putEntry(versionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vid1,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: t1.Unix(), FileSize: 100},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(vid1),
|
||||
},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "noncurrent-30d", Status: "Enabled",
|
||||
NoncurrentVersionExpirationDays: 30,
|
||||
}}
|
||||
|
||||
expired, scanned, err := processVersionsDirectory(
|
||||
context.Background(), client, versionsDir, bucketDir,
|
||||
rules, now, false, 100,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("processVersionsDirectory: %v", err)
|
||||
}
|
||||
|
||||
// vid3 is latest (not expired). vid2 became noncurrent when vid3 was created
|
||||
// (1 day ago), so vid2 is NOT old enough (< 30 days noncurrent).
|
||||
// vid1 became noncurrent when vid2 was created (60 days ago), so vid1 IS expired.
|
||||
if scanned != 2 {
|
||||
t.Errorf("expected 2 scanned (non-current versions), got %d", scanned)
|
||||
}
|
||||
if len(expired) != 1 {
|
||||
t.Fatalf("expected 1 expired (only vid1), got %d", len(expired))
|
||||
}
|
||||
if expired[0].name != "v_"+vid1 {
|
||||
t.Errorf("expected v_%s expired, got %s", vid1, expired[0].name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegration_ProcessVersionsDirectory_NewerNoncurrentVersions(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "keep-n-bucket"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
versionsDir := bucketDir + "/obj.versions"
|
||||
|
||||
now := time.Now()
|
||||
// Create 5 versions, all old enough to expire by days alone.
|
||||
versions := make([]time.Time, 5)
|
||||
vids := make([]string, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
versions[i] = now.Add(time.Duration(-(90 - i*10)) * 24 * time.Hour)
|
||||
vids[i] = testVersionId(versions[i])
|
||||
}
|
||||
// vids[4] is newest (latest), vids[0] is oldest
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "obj.versions", IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(vids[4]),
|
||||
},
|
||||
})
|
||||
|
||||
for i, vid := range vids {
|
||||
server.putEntry(versionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vid,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: versions[i].Unix(), FileSize: 100},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(vid),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "keep-2", Status: "Enabled",
|
||||
NoncurrentVersionExpirationDays: 7,
|
||||
NewerNoncurrentVersions: 2,
|
||||
}}
|
||||
|
||||
expired, _, err := processVersionsDirectory(
|
||||
context.Background(), client, versionsDir, bucketDir,
|
||||
rules, now, false, 100,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("processVersionsDirectory: %v", err)
|
||||
}
|
||||
|
||||
// 4 noncurrent versions (vids[0..3]). Keep newest 2 (vids[3], vids[2]).
|
||||
// Expire vids[1] and vids[0].
|
||||
if len(expired) != 2 {
|
||||
t.Fatalf("expected 2 expired (keep 2 newest noncurrent), got %d", len(expired))
|
||||
}
|
||||
expiredNames := map[string]bool{}
|
||||
for _, e := range expired {
|
||||
expiredNames[e.name] = true
|
||||
}
|
||||
if !expiredNames["v_"+vids[0]] {
|
||||
t.Errorf("expected vids[0] (oldest) to be expired")
|
||||
}
|
||||
if !expiredNames["v_"+vids[1]] {
|
||||
t.Errorf("expected vids[1] to be expired")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegration_AbortMPUsByRules(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "mpu-bucket"
|
||||
uploadsDir := bucketsPath + "/" + bucket + "/.uploads"
|
||||
|
||||
now := time.Now()
|
||||
old := now.Add(-10 * 24 * time.Hour)
|
||||
recent := now.Add(-2 * 24 * time.Hour)
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
server.putEntry(bucketsPath+"/"+bucket, &filer_pb.Entry{Name: ".uploads", IsDirectory: true})
|
||||
|
||||
// Old upload under logs/ prefix.
|
||||
server.putEntry(uploadsDir, &filer_pb.Entry{
|
||||
Name: "logs_upload1", IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: old.Unix()},
|
||||
})
|
||||
// Recent upload under logs/ prefix.
|
||||
server.putEntry(uploadsDir, &filer_pb.Entry{
|
||||
Name: "logs_upload2", IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: recent.Unix()},
|
||||
})
|
||||
// Old upload under data/ prefix (should not match logs/ rule).
|
||||
server.putEntry(uploadsDir, &filer_pb.Entry{
|
||||
Name: "data_upload1", IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: old.Unix()},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "abort-logs", Status: "Enabled",
|
||||
Prefix: "logs",
|
||||
AbortMPUDaysAfterInitiation: 7,
|
||||
}}
|
||||
|
||||
aborted, errs, err := abortMPUsByRules(context.Background(), client, bucketsPath, bucket, rules, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("abortMPUsByRules: %v", err)
|
||||
}
|
||||
if errs != 0 {
|
||||
t.Errorf("expected 0 errors, got %d", errs)
|
||||
}
|
||||
|
||||
// Only logs_upload1 should be aborted (old + matches prefix).
|
||||
// logs_upload2 is too recent, data_upload1 doesn't match prefix.
|
||||
if aborted != 1 {
|
||||
t.Errorf("expected 1 aborted, got %d", aborted)
|
||||
}
|
||||
|
||||
// Verify the correct upload was removed.
|
||||
if server.hasEntry(uploadsDir, "logs_upload1") {
|
||||
t.Error("logs_upload1 should have been removed")
|
||||
}
|
||||
if !server.hasEntry(uploadsDir, "logs_upload2") {
|
||||
t.Error("logs_upload2 should still exist")
|
||||
}
|
||||
if !server.hasEntry(uploadsDir, "data_upload1") {
|
||||
t.Error("data_upload1 should still exist (wrong prefix)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegration_DeleteExpiredObjects(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "delete-bucket"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
|
||||
now := time.Now()
|
||||
old := now.Add(-60 * 24 * time.Hour)
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "to-delete.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: old.Unix(), FileSize: 100},
|
||||
})
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "to-keep.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: now.Unix(), FileSize: 100},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "expire", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
}}
|
||||
|
||||
expired, _, err := listExpiredObjectsByRules(context.Background(), client, bucketsPath, bucket, rules, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
|
||||
// Actually delete them.
|
||||
deleted, errs, err := deleteExpiredObjects(context.Background(), client, expired)
|
||||
if err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if deleted != 1 || errs != 0 {
|
||||
t.Errorf("expected 1 deleted 0 errors, got %d deleted %d errors", deleted, errs)
|
||||
}
|
||||
|
||||
if server.hasEntry(bucketDir, "to-delete.txt") {
|
||||
t.Error("to-delete.txt should have been removed")
|
||||
}
|
||||
if !server.hasEntry(bucketDir, "to-keep.txt") {
|
||||
t.Error("to-keep.txt should still exist")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegration_VersionedBucket_ExpirationDays verifies that Expiration.Days
|
||||
// rules correctly detect and delete the latest version in a versioned bucket
|
||||
// where all data lives in .versions/ directories (issue #8757).
|
||||
func TestIntegration_VersionedBucket_ExpirationDays(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "versioned-expire"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
|
||||
now := time.Now()
|
||||
old := now.Add(-60 * 24 * time.Hour) // 60 days ago — should expire
|
||||
recent := now.Add(-5 * 24 * time.Hour) // 5 days ago — should NOT expire
|
||||
|
||||
vidOld := testVersionId(old)
|
||||
vidRecent := testVersionId(recent)
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
|
||||
// --- Single-version object (old, should expire) ---
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "old-file.txt" + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(vidOld),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_" + vidOld),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(old.Unix(), 10)),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("3400000000"),
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker: []byte("false"),
|
||||
},
|
||||
})
|
||||
oldVersionsDir := bucketDir + "/old-file.txt" + s3_constants.VersionsFolder
|
||||
server.putEntry(oldVersionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vidOld,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: old.Unix(), FileSize: 3400000000},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(vidOld),
|
||||
},
|
||||
})
|
||||
|
||||
// --- Single-version object (recent, should NOT expire) ---
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "recent-file.txt" + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(vidRecent),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_" + vidRecent),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(recent.Unix(), 10)),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("3400000000"),
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker: []byte("false"),
|
||||
},
|
||||
})
|
||||
recentVersionsDir := bucketDir + "/recent-file.txt" + s3_constants.VersionsFolder
|
||||
server.putEntry(recentVersionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vidRecent,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: recent.Unix(), FileSize: 3400000000},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(vidRecent),
|
||||
},
|
||||
})
|
||||
|
||||
// --- Object with delete marker as latest (should NOT be expired by Expiration.Days) ---
|
||||
vidMarker := testVersionId(old)
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "deleted-obj.txt" + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(vidMarker),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_" + vidMarker),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(old.Unix(), 10)),
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker: []byte("true"),
|
||||
},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "expire-30d", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
}}
|
||||
|
||||
expired, scanned, err := listExpiredObjectsByRules(context.Background(), client, bucketsPath, bucket, rules, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("listExpiredObjectsByRules: %v", err)
|
||||
}
|
||||
|
||||
// Only old-file.txt's latest version should be expired.
|
||||
// recent-file.txt is too young; deleted-obj.txt is a delete marker.
|
||||
if len(expired) != 1 {
|
||||
t.Fatalf("expected 1 expired, got %d: %+v", len(expired), expired)
|
||||
}
|
||||
if expired[0].dir != oldVersionsDir {
|
||||
t.Errorf("expected dir=%s, got %s", oldVersionsDir, expired[0].dir)
|
||||
}
|
||||
if expired[0].name != "v_"+vidOld {
|
||||
t.Errorf("expected name=v_%s, got %s", vidOld, expired[0].name)
|
||||
}
|
||||
// The old-file.txt latest version should count as scanned.
|
||||
if scanned < 1 {
|
||||
t.Errorf("expected at least 1 scanned, got %d", scanned)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegration_VersionedBucket_ExpirationDays_DeleteAndCleanup verifies
|
||||
// end-to-end deletion and .versions directory cleanup for a single-version
|
||||
// versioned object expired by Expiration.Days.
|
||||
func TestIntegration_VersionedBucket_ExpirationDays_DeleteAndCleanup(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "versioned-cleanup"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
|
||||
now := time.Now()
|
||||
old := now.Add(-60 * 24 * time.Hour)
|
||||
vidOld := testVersionId(old)
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
|
||||
// Single-version object that should expire.
|
||||
versionsDir := bucketDir + "/data.bin" + s3_constants.VersionsFolder
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "data.bin" + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(vidOld),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_" + vidOld),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(old.Unix(), 10)),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("1024"),
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker: []byte("false"),
|
||||
},
|
||||
})
|
||||
server.putEntry(versionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vidOld,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: old.Unix(), FileSize: 1024},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(vidOld),
|
||||
},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "expire-30d", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
}}
|
||||
|
||||
// Step 1: Detect expired.
|
||||
expired, _, err := listExpiredObjectsByRules(context.Background(), client, bucketsPath, bucket, rules, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
if len(expired) != 1 {
|
||||
t.Fatalf("expected 1 expired, got %d", len(expired))
|
||||
}
|
||||
|
||||
// Step 2: Delete the expired version file.
|
||||
deleted, errs, delErr := deleteExpiredObjects(context.Background(), client, expired)
|
||||
if delErr != nil {
|
||||
t.Fatalf("delete: %v", delErr)
|
||||
}
|
||||
if deleted != 1 || errs != 0 {
|
||||
t.Errorf("expected 1 deleted 0 errors, got %d deleted %d errors", deleted, errs)
|
||||
}
|
||||
|
||||
// Version file should be gone.
|
||||
if server.hasEntry(versionsDir, "v_"+vidOld) {
|
||||
t.Error("version file should have been removed")
|
||||
}
|
||||
|
||||
// Step 3: Cleanup empty .versions directory.
|
||||
cleaned := cleanupEmptyVersionsDirectories(context.Background(), client, expired)
|
||||
if cleaned != 1 {
|
||||
t.Errorf("expected 1 directory cleaned, got %d", cleaned)
|
||||
}
|
||||
|
||||
// The .versions directory itself should be gone.
|
||||
if server.hasEntry(bucketDir, "data.bin"+s3_constants.VersionsFolder) {
|
||||
t.Error(".versions directory should have been removed after cleanup")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegration_VersionedBucket_MultiVersion_ExpirationDays verifies that
|
||||
// when a multi-version object's latest version expires, only the latest
|
||||
// version is deleted and noncurrent versions remain.
|
||||
func TestIntegration_VersionedBucket_MultiVersion_ExpirationDays(t *testing.T) {
|
||||
server, client := startTestFiler(t)
|
||||
bucketsPath := "/buckets"
|
||||
bucket := "versioned-multi"
|
||||
bucketDir := bucketsPath + "/" + bucket
|
||||
|
||||
now := time.Now()
|
||||
tOld := now.Add(-60 * 24 * time.Hour)
|
||||
tNoncurrent := now.Add(-90 * 24 * time.Hour)
|
||||
vidLatest := testVersionId(tOld)
|
||||
vidNoncurrent := testVersionId(tNoncurrent)
|
||||
|
||||
server.putEntry(bucketsPath, &filer_pb.Entry{Name: bucket, IsDirectory: true})
|
||||
|
||||
versionsDir := bucketDir + "/multi.txt" + s3_constants.VersionsFolder
|
||||
server.putEntry(bucketDir, &filer_pb.Entry{
|
||||
Name: "multi.txt" + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(vidLatest),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_" + vidLatest),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(tOld.Unix(), 10)),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("500"),
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker: []byte("false"),
|
||||
},
|
||||
})
|
||||
server.putEntry(versionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vidLatest,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: tOld.Unix(), FileSize: 500},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte(vidLatest)},
|
||||
})
|
||||
server.putEntry(versionsDir, &filer_pb.Entry{
|
||||
Name: "v_" + vidNoncurrent,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: tNoncurrent.Unix(), FileSize: 500},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte(vidNoncurrent)},
|
||||
})
|
||||
|
||||
rules := []s3lifecycle.Rule{{
|
||||
ID: "expire-30d", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
}}
|
||||
|
||||
expired, _, err := listExpiredObjectsByRules(context.Background(), client, bucketsPath, bucket, rules, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
// Only the latest version should be detected as expired.
|
||||
if len(expired) != 1 {
|
||||
t.Fatalf("expected 1 expired (latest only), got %d", len(expired))
|
||||
}
|
||||
if expired[0].name != "v_"+vidLatest {
|
||||
t.Errorf("expected latest version expired, got %s", expired[0].name)
|
||||
}
|
||||
|
||||
// Delete it.
|
||||
deleted, errs, delErr := deleteExpiredObjects(context.Background(), client, expired)
|
||||
if delErr != nil {
|
||||
t.Fatalf("delete: %v", delErr)
|
||||
}
|
||||
if deleted != 1 || errs != 0 {
|
||||
t.Errorf("expected 1 deleted 0 errors, got %d deleted %d errors", deleted, errs)
|
||||
}
|
||||
|
||||
// Noncurrent version should still exist.
|
||||
if !server.hasEntry(versionsDir, "v_"+vidNoncurrent) {
|
||||
t.Error("noncurrent version should still exist")
|
||||
}
|
||||
|
||||
// .versions directory should NOT be cleaned up (not empty).
|
||||
cleaned := cleanupEmptyVersionsDirectories(context.Background(), client, expired)
|
||||
if cleaned != 0 {
|
||||
t.Errorf("expected 0 directories cleaned (not empty), got %d", cleaned)
|
||||
}
|
||||
if !server.hasEntry(bucketDir, "multi.txt"+s3_constants.VersionsFolder) {
|
||||
t.Error(".versions directory should still exist (has noncurrent version)")
|
||||
}
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
)
|
||||
|
||||
// lifecycleConfig mirrors the XML structure just enough to parse rules.
|
||||
// We define a minimal local struct to avoid importing the s3api package
|
||||
// (which would create a circular dependency if s3api ever imports the worker).
|
||||
type lifecycleConfig struct {
|
||||
XMLName xml.Name `xml:"LifecycleConfiguration"`
|
||||
Rules []lifecycleConfigRule `xml:"Rule"`
|
||||
}
|
||||
|
||||
type lifecycleConfigRule struct {
|
||||
ID string `xml:"ID"`
|
||||
Status string `xml:"Status"`
|
||||
Filter lifecycleFilter `xml:"Filter"`
|
||||
Prefix string `xml:"Prefix"`
|
||||
Expiration lifecycleExpiration `xml:"Expiration"`
|
||||
NoncurrentVersionExpiration noncurrentVersionExpiration `xml:"NoncurrentVersionExpiration"`
|
||||
AbortIncompleteMultipartUpload abortMPU `xml:"AbortIncompleteMultipartUpload"`
|
||||
}
|
||||
|
||||
type lifecycleFilter struct {
|
||||
Prefix string `xml:"Prefix"`
|
||||
Tag lifecycleTag `xml:"Tag"`
|
||||
And lifecycleAnd `xml:"And"`
|
||||
ObjectSizeGreaterThan int64 `xml:"ObjectSizeGreaterThan"`
|
||||
ObjectSizeLessThan int64 `xml:"ObjectSizeLessThan"`
|
||||
}
|
||||
|
||||
type lifecycleAnd struct {
|
||||
Prefix string `xml:"Prefix"`
|
||||
Tags []lifecycleTag `xml:"Tag"`
|
||||
ObjectSizeGreaterThan int64 `xml:"ObjectSizeGreaterThan"`
|
||||
ObjectSizeLessThan int64 `xml:"ObjectSizeLessThan"`
|
||||
}
|
||||
|
||||
type lifecycleTag struct {
|
||||
Key string `xml:"Key"`
|
||||
Value string `xml:"Value"`
|
||||
}
|
||||
|
||||
type lifecycleExpiration struct {
|
||||
Days int `xml:"Days"`
|
||||
Date string `xml:"Date"`
|
||||
ExpiredObjectDeleteMarker bool `xml:"ExpiredObjectDeleteMarker"`
|
||||
}
|
||||
|
||||
type noncurrentVersionExpiration struct {
|
||||
NoncurrentDays int `xml:"NoncurrentDays"`
|
||||
NewerNoncurrentVersions int `xml:"NewerNoncurrentVersions"`
|
||||
}
|
||||
|
||||
type abortMPU struct {
|
||||
DaysAfterInitiation int `xml:"DaysAfterInitiation"`
|
||||
}
|
||||
|
||||
// errMalformedLifecycleXML indicates the lifecycle XML exists but could not be parsed.
|
||||
// Callers should fail closed (not fall back to TTL) to avoid broader deletions.
|
||||
var errMalformedLifecycleXML = errors.New("malformed lifecycle XML")
|
||||
|
||||
// loadLifecycleRulesFromBucket reads the lifecycle XML from a bucket's
|
||||
// metadata and converts it to evaluator-friendly rules.
|
||||
//
|
||||
// Returns:
|
||||
// - (rules, nil) when lifecycle XML is configured and parseable
|
||||
// - (nil, nil) when no lifecycle XML is configured (caller should use TTL fallback)
|
||||
// - (nil, errMalformedLifecycleXML) when XML exists but is malformed (fail closed)
|
||||
// - (nil, err) for transient filer errors (caller should use TTL fallback with warning)
|
||||
func loadLifecycleRulesFromBucket(
|
||||
ctx context.Context,
|
||||
client filer_pb.SeaweedFilerClient,
|
||||
bucketsPath, bucket string,
|
||||
) ([]s3lifecycle.Rule, error) {
|
||||
bucketDir := bucketsPath
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: bucketDir,
|
||||
Name: bucket,
|
||||
})
|
||||
if err != nil {
|
||||
// Transient filer error — not the same as malformed XML.
|
||||
return nil, fmt.Errorf("lookup bucket %s: %w", bucket, err)
|
||||
}
|
||||
if resp.Entry == nil || resp.Entry.Extended == nil {
|
||||
return nil, nil
|
||||
}
|
||||
xmlData := resp.Entry.Extended[lifecycleXMLKey]
|
||||
if len(xmlData) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rules, parseErr := parseLifecycleXML(xmlData)
|
||||
if parseErr != nil {
|
||||
return nil, fmt.Errorf("%w: bucket %s: %v", errMalformedLifecycleXML, bucket, parseErr)
|
||||
}
|
||||
// Return non-nil empty slice when XML was present but yielded no rules
|
||||
// (e.g., all rules disabled). This lets callers distinguish "no XML" (nil)
|
||||
// from "XML present, no effective rules" (empty slice).
|
||||
if rules == nil {
|
||||
rules = []s3lifecycle.Rule{}
|
||||
}
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
// parseLifecycleXML parses lifecycle configuration XML and converts it
|
||||
// to evaluator-friendly rules.
|
||||
func parseLifecycleXML(data []byte) ([]s3lifecycle.Rule, error) {
|
||||
var config lifecycleConfig
|
||||
if err := xml.NewDecoder(bytes.NewReader(data)).Decode(&config); err != nil {
|
||||
return nil, fmt.Errorf("decode lifecycle XML: %w", err)
|
||||
}
|
||||
|
||||
var rules []s3lifecycle.Rule
|
||||
for _, r := range config.Rules {
|
||||
rule := s3lifecycle.Rule{
|
||||
ID: r.ID,
|
||||
Status: r.Status,
|
||||
}
|
||||
|
||||
// Resolve prefix: Filter.And.Prefix > Filter.Prefix > Rule.Prefix
|
||||
switch {
|
||||
case r.Filter.And.Prefix != "" || len(r.Filter.And.Tags) > 0 ||
|
||||
r.Filter.And.ObjectSizeGreaterThan > 0 || r.Filter.And.ObjectSizeLessThan > 0:
|
||||
rule.Prefix = r.Filter.And.Prefix
|
||||
rule.FilterTags = tagsToMap(r.Filter.And.Tags)
|
||||
rule.FilterSizeGreaterThan = r.Filter.And.ObjectSizeGreaterThan
|
||||
rule.FilterSizeLessThan = r.Filter.And.ObjectSizeLessThan
|
||||
case r.Filter.Tag.Key != "":
|
||||
rule.Prefix = r.Filter.Prefix
|
||||
rule.FilterTags = map[string]string{r.Filter.Tag.Key: r.Filter.Tag.Value}
|
||||
rule.FilterSizeGreaterThan = r.Filter.ObjectSizeGreaterThan
|
||||
rule.FilterSizeLessThan = r.Filter.ObjectSizeLessThan
|
||||
default:
|
||||
if r.Filter.Prefix != "" {
|
||||
rule.Prefix = r.Filter.Prefix
|
||||
} else {
|
||||
rule.Prefix = r.Prefix
|
||||
}
|
||||
rule.FilterSizeGreaterThan = r.Filter.ObjectSizeGreaterThan
|
||||
rule.FilterSizeLessThan = r.Filter.ObjectSizeLessThan
|
||||
}
|
||||
|
||||
rule.ExpirationDays = r.Expiration.Days
|
||||
rule.ExpiredObjectDeleteMarker = r.Expiration.ExpiredObjectDeleteMarker
|
||||
rule.NoncurrentVersionExpirationDays = r.NoncurrentVersionExpiration.NoncurrentDays
|
||||
rule.NewerNoncurrentVersions = r.NoncurrentVersionExpiration.NewerNoncurrentVersions
|
||||
rule.AbortMPUDaysAfterInitiation = r.AbortIncompleteMultipartUpload.DaysAfterInitiation
|
||||
|
||||
// Parse Date if present.
|
||||
if r.Expiration.Date != "" {
|
||||
// Date may be RFC3339 or ISO 8601 date-only.
|
||||
parsed, parseErr := parseExpirationDate(r.Expiration.Date)
|
||||
if parseErr != nil {
|
||||
glog.V(1).Infof("s3_lifecycle: skipping rule %s: invalid expiration date %q: %v", r.ID, r.Expiration.Date, parseErr)
|
||||
continue
|
||||
}
|
||||
rule.ExpirationDate = parsed
|
||||
}
|
||||
|
||||
rules = append(rules, rule)
|
||||
}
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
func tagsToMap(tags []lifecycleTag) map[string]string {
|
||||
if len(tags) == 0 {
|
||||
return nil
|
||||
}
|
||||
m := make(map[string]string, len(tags))
|
||||
for _, t := range tags {
|
||||
m[t.Key] = t.Value
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func parseExpirationDate(s string) (time.Time, error) {
|
||||
// Try RFC3339 first, then ISO 8601 date-only.
|
||||
formats := []string{
|
||||
"2006-01-02T15:04:05Z07:00",
|
||||
"2006-01-02",
|
||||
}
|
||||
for _, f := range formats {
|
||||
t, err := time.Parse(f, s)
|
||||
if err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("unrecognized date format: %s", s)
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseLifecycleXML_CompleteConfig(t *testing.T) {
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>rotation</ID>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<Status>Enabled</Status>
|
||||
<Expiration><Days>30</Days></Expiration>
|
||||
<NoncurrentVersionExpiration>
|
||||
<NoncurrentDays>7</NoncurrentDays>
|
||||
<NewerNoncurrentVersions>2</NewerNoncurrentVersions>
|
||||
</NoncurrentVersionExpiration>
|
||||
<AbortIncompleteMultipartUpload>
|
||||
<DaysAfterInitiation>3</DaysAfterInitiation>
|
||||
</AbortIncompleteMultipartUpload>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("expected 1 rule, got %d", len(rules))
|
||||
}
|
||||
|
||||
r := rules[0]
|
||||
if r.ID != "rotation" {
|
||||
t.Errorf("expected ID 'rotation', got %q", r.ID)
|
||||
}
|
||||
if r.Status != "Enabled" {
|
||||
t.Errorf("expected Status 'Enabled', got %q", r.Status)
|
||||
}
|
||||
if r.ExpirationDays != 30 {
|
||||
t.Errorf("expected ExpirationDays=30, got %d", r.ExpirationDays)
|
||||
}
|
||||
if r.NoncurrentVersionExpirationDays != 7 {
|
||||
t.Errorf("expected NoncurrentVersionExpirationDays=7, got %d", r.NoncurrentVersionExpirationDays)
|
||||
}
|
||||
if r.NewerNoncurrentVersions != 2 {
|
||||
t.Errorf("expected NewerNoncurrentVersions=2, got %d", r.NewerNoncurrentVersions)
|
||||
}
|
||||
if r.AbortMPUDaysAfterInitiation != 3 {
|
||||
t.Errorf("expected AbortMPUDaysAfterInitiation=3, got %d", r.AbortMPUDaysAfterInitiation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLifecycleXML_PrefixFilter(t *testing.T) {
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>logs</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix>logs/</Prefix></Filter>
|
||||
<Expiration><Days>7</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("expected 1 rule, got %d", len(rules))
|
||||
}
|
||||
if rules[0].Prefix != "logs/" {
|
||||
t.Errorf("expected Prefix='logs/', got %q", rules[0].Prefix)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLifecycleXML_LegacyPrefix(t *testing.T) {
|
||||
// Old-style <Prefix> at rule level instead of inside <Filter>.
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>old</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Prefix>archive/</Prefix>
|
||||
<Expiration><Days>90</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("expected 1 rule, got %d", len(rules))
|
||||
}
|
||||
if rules[0].Prefix != "archive/" {
|
||||
t.Errorf("expected Prefix='archive/', got %q", rules[0].Prefix)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLifecycleXML_TagFilter(t *testing.T) {
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>tag-rule</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter>
|
||||
<Tag><Key>env</Key><Value>dev</Value></Tag>
|
||||
</Filter>
|
||||
<Expiration><Days>1</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("expected 1 rule, got %d", len(rules))
|
||||
}
|
||||
r := rules[0]
|
||||
if len(r.FilterTags) != 1 || r.FilterTags["env"] != "dev" {
|
||||
t.Errorf("expected FilterTags={env:dev}, got %v", r.FilterTags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLifecycleXML_AndFilter(t *testing.T) {
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>and-rule</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter>
|
||||
<And>
|
||||
<Prefix>data/</Prefix>
|
||||
<Tag><Key>env</Key><Value>staging</Value></Tag>
|
||||
<ObjectSizeGreaterThan>1024</ObjectSizeGreaterThan>
|
||||
</And>
|
||||
</Filter>
|
||||
<Expiration><Days>14</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("expected 1 rule, got %d", len(rules))
|
||||
}
|
||||
r := rules[0]
|
||||
if r.Prefix != "data/" {
|
||||
t.Errorf("expected Prefix='data/', got %q", r.Prefix)
|
||||
}
|
||||
if r.FilterTags["env"] != "staging" {
|
||||
t.Errorf("expected tag env=staging, got %v", r.FilterTags)
|
||||
}
|
||||
if r.FilterSizeGreaterThan != 1024 {
|
||||
t.Errorf("expected FilterSizeGreaterThan=1024, got %d", r.FilterSizeGreaterThan)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLifecycleXML_ExpirationDate(t *testing.T) {
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>date-rule</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<Expiration><Date>2026-06-01T00:00:00Z</Date></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
expected := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)
|
||||
if !rules[0].ExpirationDate.Equal(expected) {
|
||||
t.Errorf("expected ExpirationDate=%v, got %v", expected, rules[0].ExpirationDate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLifecycleXML_ExpiredObjectDeleteMarker(t *testing.T) {
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>marker-cleanup</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<Expiration><ExpiredObjectDeleteMarker>true</ExpiredObjectDeleteMarker></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
if !rules[0].ExpiredObjectDeleteMarker {
|
||||
t.Error("expected ExpiredObjectDeleteMarker=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLifecycleXML_MultipleRules(t *testing.T) {
|
||||
xml := []byte(`<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>rule1</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix>logs/</Prefix></Filter>
|
||||
<Expiration><Days>7</Days></Expiration>
|
||||
</Rule>
|
||||
<Rule>
|
||||
<ID>rule2</ID>
|
||||
<Status>Disabled</Status>
|
||||
<Filter><Prefix>temp/</Prefix></Filter>
|
||||
<Expiration><Days>1</Days></Expiration>
|
||||
</Rule>
|
||||
<Rule>
|
||||
<ID>rule3</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<Expiration><Days>365</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`)
|
||||
|
||||
rules, err := parseLifecycleXML(xml)
|
||||
if err != nil {
|
||||
t.Fatalf("parseLifecycleXML: %v", err)
|
||||
}
|
||||
if len(rules) != 3 {
|
||||
t.Fatalf("expected 3 rules, got %d", len(rules))
|
||||
}
|
||||
if rules[1].Status != "Disabled" {
|
||||
t.Errorf("expected rule2 Status=Disabled, got %q", rules[1].Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseExpirationDate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want time.Time
|
||||
wantErr bool
|
||||
}{
|
||||
{"rfc3339_utc", "2026-06-01T00:00:00Z", time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC), false},
|
||||
{"rfc3339_offset", "2026-06-01T00:00:00+05:00", time.Date(2026, 6, 1, 0, 0, 0, 0, time.FixedZone("", 5*3600)), false},
|
||||
{"date_only", "2026-06-01", time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC), false},
|
||||
{"invalid", "not-a-date", time.Time{}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := parseExpirationDate(tt.input)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("parseExpirationDate(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !tt.wantErr && !got.Equal(tt.want) {
|
||||
t.Errorf("parseExpirationDate(%q) = %v, want %v", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
)
|
||||
|
||||
// makeVersionId creates a new-format version ID from a timestamp.
|
||||
func makeVersionId(t time.Time) string {
|
||||
inverted := math.MaxInt64 - t.UnixNano()
|
||||
return fmt.Sprintf("%016x", inverted) + "0000000000000000"
|
||||
}
|
||||
|
||||
func TestSortVersionsByVersionId(t *testing.T) {
|
||||
t1 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
t2 := time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC)
|
||||
t3 := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
vid1 := makeVersionId(t1)
|
||||
vid2 := makeVersionId(t2)
|
||||
vid3 := makeVersionId(t3)
|
||||
|
||||
entries := []*filer_pb.Entry{
|
||||
{Name: "v_" + vid1},
|
||||
{Name: "v_" + vid3},
|
||||
{Name: "v_" + vid2},
|
||||
}
|
||||
|
||||
sortVersionsByVersionId(entries)
|
||||
|
||||
// Should be sorted newest first: t3, t2, t1.
|
||||
expected := []string{"v_" + vid3, "v_" + vid2, "v_" + vid1}
|
||||
for i, want := range expected {
|
||||
if entries[i].Name != want {
|
||||
t.Errorf("entries[%d].Name = %s, want %s", i, entries[i].Name, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortVersionsByVersionId_SameTimestampDifferentSuffix(t *testing.T) {
|
||||
// Two versions with the same timestamp prefix but different random suffix.
|
||||
// The sort must still produce a deterministic order.
|
||||
base := makeVersionId(time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC))
|
||||
vid1 := base[:16] + "aaaaaaaaaaaaaaaa"
|
||||
vid2 := base[:16] + "bbbbbbbbbbbbbbbb"
|
||||
|
||||
entries := []*filer_pb.Entry{
|
||||
{Name: "v_" + vid2},
|
||||
{Name: "v_" + vid1},
|
||||
}
|
||||
|
||||
sortVersionsByVersionId(entries)
|
||||
|
||||
// New format: smaller hex = newer. vid1 ("aaa...") < vid2 ("bbb...") so vid1 is newer.
|
||||
if strings.TrimPrefix(entries[0].Name, "v_") != vid1 {
|
||||
t.Errorf("expected vid1 (newer) first, got %s", entries[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareVersionIdsMixedFormats(t *testing.T) {
|
||||
// Old format: raw nanosecond timestamp (below threshold ~0x17...).
|
||||
// New format: inverted timestamp (above threshold ~0x68...).
|
||||
oldTs := time.Date(2023, 6, 15, 12, 0, 0, 0, time.UTC)
|
||||
newTs := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
oldFormatId := fmt.Sprintf("%016x", oldTs.UnixNano()) + "abcdef0123456789"
|
||||
newFormatId := makeVersionId(newTs) // uses inverted timestamp
|
||||
|
||||
// newTs is more recent, so newFormatId should sort as "newer".
|
||||
cmp := s3lifecycle.CompareVersionIds(newFormatId, oldFormatId)
|
||||
if cmp >= 0 {
|
||||
t.Errorf("expected new-format ID (2026) to be newer than old-format ID (2023), got cmp=%d", cmp)
|
||||
}
|
||||
|
||||
// Reverse comparison.
|
||||
cmp2 := s3lifecycle.CompareVersionIds(oldFormatId, newFormatId)
|
||||
if cmp2 <= 0 {
|
||||
t.Errorf("expected old-format ID (2023) to be older than new-format ID (2026), got cmp=%d", cmp2)
|
||||
}
|
||||
|
||||
// Sort a mixed slice: should be newest-first.
|
||||
entries := []*filer_pb.Entry{
|
||||
{Name: "v_" + oldFormatId},
|
||||
{Name: "v_" + newFormatId},
|
||||
}
|
||||
sortVersionsByVersionId(entries)
|
||||
|
||||
if strings.TrimPrefix(entries[0].Name, "v_") != newFormatId {
|
||||
t.Errorf("expected new-format (newer) entry first after sort")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionsDirectoryNaming(t *testing.T) {
|
||||
if s3_constants.VersionsFolder != ".versions" {
|
||||
t.Fatalf("unexpected VersionsFolder constant: %q", s3_constants.VersionsFolder)
|
||||
}
|
||||
|
||||
versionsDir := "/buckets/mybucket/path/to/key.versions"
|
||||
bucketPath := "/buckets/mybucket"
|
||||
relDir := strings.TrimPrefix(versionsDir, bucketPath+"/")
|
||||
objKey := strings.TrimSuffix(relDir, s3_constants.VersionsFolder)
|
||||
if objKey != "path/to/key" {
|
||||
t.Errorf("expected 'path/to/key', got %q", objKey)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/Shopify/sarama"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
kafkanotif "github.com/seaweedfs/seaweedfs/weed/notification/kafka"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -37,38 +36,25 @@ func (k *KafkaInput) Initialize(configuration util.Configuration, prefix string)
|
||||
configuration.GetString(prefix+"topic"),
|
||||
configuration.GetString(prefix+"offsetFile"),
|
||||
configuration.GetInt(prefix+"offsetSaveIntervalSeconds"),
|
||||
kafkanotif.SASLTLSConfig{
|
||||
SASLEnabled: configuration.GetBool(prefix + "sasl_enabled"),
|
||||
SASLMechanism: configuration.GetString(prefix + "sasl_mechanism"),
|
||||
SASLUsername: configuration.GetString(prefix + "sasl_username"),
|
||||
SASLPassword: configuration.GetString(prefix + "sasl_password"),
|
||||
TLSEnabled: configuration.GetBool(prefix + "tls_enabled"),
|
||||
TLSCACert: configuration.GetString(prefix + "tls_ca_cert"),
|
||||
TLSClientCert: configuration.GetString(prefix + "tls_client_cert"),
|
||||
TLSClientKey: configuration.GetString(prefix + "tls_client_key"),
|
||||
TLSInsecureSkipVerify: configuration.GetBool(prefix + "tls_insecure_skip_verify"),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (k *KafkaInput) initialize(hosts []string, topic string, offsetFile string, offsetSaveIntervalSeconds int, saslTLS kafkanotif.SASLTLSConfig) (err error) {
|
||||
func (k *KafkaInput) initialize(hosts []string, topic string, offsetFile string, offsetSaveIntervalSeconds int) (err error) {
|
||||
config := sarama.NewConfig()
|
||||
config.Consumer.Return.Errors = true
|
||||
if err = kafkanotif.ConfigureSASLTLS(config, saslTLS); err != nil {
|
||||
return fmt.Errorf("kafka consumer security configuration: %w", err)
|
||||
}
|
||||
k.consumer, err = sarama.NewConsumer(hosts, config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create kafka consumer: %w", err)
|
||||
panic(err)
|
||||
} else {
|
||||
glog.V(0).Infof("connected to %v", hosts)
|
||||
}
|
||||
glog.V(0).Infof("connected to %v", hosts)
|
||||
|
||||
k.topic = topic
|
||||
k.messageChan = make(chan *sarama.ConsumerMessage, 1)
|
||||
|
||||
partitions, err := k.consumer.Partitions(topic)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get kafka partitions for topic %q: %w", topic, err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
progress := loadProgress(offsetFile)
|
||||
@@ -91,7 +77,7 @@ func (k *KafkaInput) initialize(hosts []string, topic string, offsetFile string,
|
||||
}
|
||||
partitionConsumer, err := k.consumer.ConsumePartition(topic, partition, offset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("consume kafka topic %q partition %d: %w", topic, partition, err)
|
||||
panic(err)
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
|
||||
@@ -1039,6 +1039,13 @@ func getMD5HashBase64(data []byte) string {
|
||||
return base64.StdEncoding.EncodeToString(getMD5Sum(data))
|
||||
}
|
||||
|
||||
// getSHA256Sum returns SHA-256 sum of given data.
|
||||
func getSHA256Sum(data []byte) []byte {
|
||||
hash := sha256.New()
|
||||
hash.Write(data)
|
||||
return hash.Sum(nil)
|
||||
}
|
||||
|
||||
// getMD5Sum returns MD5 sum of given data.
|
||||
func getMD5Sum(data []byte) []byte {
|
||||
hash := md5.New()
|
||||
@@ -1046,6 +1053,11 @@ func getMD5Sum(data []byte) []byte {
|
||||
return hash.Sum(nil)
|
||||
}
|
||||
|
||||
// getMD5Hash returns MD5 hash in hex encoding of given data.
|
||||
func getMD5Hash(data []byte) string {
|
||||
return hex.EncodeToString(getMD5Sum(data))
|
||||
}
|
||||
|
||||
var ignoredHeaders = map[string]bool{
|
||||
"Authorization": true,
|
||||
"Content-Type": true,
|
||||
|
||||
+253
-287
@@ -14,6 +14,7 @@ import (
|
||||
"net/url"
|
||||
"path"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -165,73 +166,63 @@ func copySSEHeadersFromFirstPart(dst *filer_pb.Entry, firstPart *filer_pb.Entry,
|
||||
}
|
||||
}
|
||||
|
||||
type multipartPartBoundary struct {
|
||||
PartNumber int `json:"part"`
|
||||
StartChunk int `json:"start"`
|
||||
EndChunk int `json:"end"`
|
||||
ETag string `json:"etag"`
|
||||
}
|
||||
func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.CompleteMultipartUploadInput, parts *CompleteMultipartUpload) (output *CompleteMultipartUploadResult, code s3err.ErrorCode) {
|
||||
|
||||
type multipartCompletionState struct {
|
||||
deleteEntries []*filer_pb.Entry
|
||||
partEntries map[int][]*filer_pb.Entry
|
||||
pentry *filer_pb.Entry
|
||||
mime string
|
||||
finalParts []*filer_pb.FileChunk
|
||||
offset int64
|
||||
partBoundaries []multipartPartBoundary
|
||||
multipartETag string
|
||||
entityWithTtl bool
|
||||
}
|
||||
|
||||
func completeMultipartResult(r *http.Request, input *s3.CompleteMultipartUploadInput, etag string, entry *filer_pb.Entry) *CompleteMultipartUploadResult {
|
||||
result := &CompleteMultipartUploadResult{
|
||||
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
|
||||
Bucket: input.Bucket,
|
||||
ETag: aws.String(etag),
|
||||
Key: objectKey(input.Key),
|
||||
glog.V(2).Infof("completeMultipartUpload input %v", input)
|
||||
if len(parts.Parts) == 0 {
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
if entry != nil && entry.Extended != nil {
|
||||
if versionIdBytes, ok := entry.Extended[s3_constants.ExtVersionIdKey]; ok {
|
||||
versionId := string(versionIdBytes)
|
||||
if versionId != "" && versionId != "null" {
|
||||
result.VersionId = aws.String(versionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
completedPartNumbers := []int{}
|
||||
completedPartMap := make(map[int][]string)
|
||||
|
||||
func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *s3.CompleteMultipartUploadInput, uploadDirectory, entryName, dirName string, completedPartNumbers []int, completedPartMap map[int][]string, maxPartNo int) (*multipartCompletionState, *CompleteMultipartUploadResult, s3err.ErrorCode) {
|
||||
if entry, err := s3a.resolveObjectEntry(*input.Bucket, *input.Key); err == nil && entry != nil && entry.Extended != nil {
|
||||
if uploadId, ok := entry.Extended[s3_constants.SeaweedFSUploadId]; ok && *input.UploadId == string(uploadId) {
|
||||
cleanupEntries, _, cleanupErr := s3a.list(uploadDirectory, "", "", false, s3_constants.MaxS3MultipartParts+1)
|
||||
if cleanupErr != nil && !errors.Is(cleanupErr, filer_pb.ErrNotFound) {
|
||||
glog.Warningf("completeMultipartUpload: failed to list stale upload directory %s for cleanup: %v", uploadDirectory, cleanupErr)
|
||||
}
|
||||
return &multipartCompletionState{deleteEntries: cleanupEntries}, completeMultipartResult(r, input, getEtagFromEntry(entry), entry), s3err.ErrNone
|
||||
maxPartNo := 1
|
||||
|
||||
for _, part := range parts.Parts {
|
||||
if _, ok := completedPartMap[part.PartNumber]; !ok {
|
||||
completedPartNumbers = append(completedPartNumbers, part.PartNumber)
|
||||
}
|
||||
completedPartMap[part.PartNumber] = append(completedPartMap[part.PartNumber], part.ETag)
|
||||
maxPartNo = maxInt(maxPartNo, part.PartNumber)
|
||||
}
|
||||
sort.Ints(completedPartNumbers)
|
||||
|
||||
uploadDirectory := s3a.genUploadsFolder(*input.Bucket) + "/" + *input.UploadId
|
||||
// Use explicit limit to ensure all parts are listed (up to S3's max of 10,000 parts)
|
||||
// Previously limit=0 relied on server's DirListingLimit default (1000 in weed server mode),
|
||||
// which caused CompleteMultipartUpload to fail for uploads with more than 1000 parts.
|
||||
entries, _, err := s3a.list(uploadDirectory, "", "", false, s3_constants.MaxS3MultipartParts+1)
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s %s error: %v", *input.Bucket, *input.UploadId, err)
|
||||
glog.Errorf("completeMultipartUpload %s %s error: %v, entries:%d", *input.Bucket, *input.UploadId, err, len(entries))
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, nil, s3err.ErrNoSuchUpload
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
|
||||
if len(entries) == 0 {
|
||||
entryName, dirName := s3a.getEntryNameAndDir(input)
|
||||
if entry, _ := s3a.getEntry(dirName, entryName); entry != nil && entry.Extended != nil {
|
||||
if uploadId, ok := entry.Extended[s3_constants.SeaweedFSUploadId]; ok && *input.UploadId == string(uploadId) {
|
||||
// Location uses the S3 endpoint that the client connected to
|
||||
// Format: scheme://s3-endpoint/bucket/object (following AWS S3 API)
|
||||
return &CompleteMultipartUploadResult{
|
||||
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
|
||||
Bucket: input.Bucket,
|
||||
ETag: aws.String(getEtagFromEntry(entry)),
|
||||
Key: objectKey(input.Key),
|
||||
}, s3err.ErrNone
|
||||
}
|
||||
}
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, nil, s3err.ErrNoSuchUpload
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
|
||||
pentry, err := s3a.getEntry(s3a.genUploadsFolder(*input.Bucket), *input.UploadId)
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s %s error: %v", *input.Bucket, *input.UploadId, err)
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, nil, s3err.ErrNoSuchUpload
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
|
||||
deleteEntries := make([]*filer_pb.Entry, 0)
|
||||
deleteEntries := []*filer_pb.Entry{}
|
||||
partEntries := make(map[int][]*filer_pb.Entry, len(entries))
|
||||
entityTooSmall := false
|
||||
entityWithTtl := false
|
||||
@@ -241,10 +232,10 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
if entry.IsDirectory || !strings.HasSuffix(entry.Name, multipartExt) {
|
||||
continue
|
||||
}
|
||||
partNumber, parseErr := parsePartNumber(entry.Name)
|
||||
if parseErr != nil {
|
||||
partNumber, err := parsePartNumber(entry.Name)
|
||||
if err != nil {
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedPartNumber).Inc()
|
||||
glog.Errorf("completeMultipartUpload failed to parse partNumber %s:%s", entry.Name, parseErr)
|
||||
glog.Errorf("completeMultipartUpload failed to pasre partNumber %s:%s", entry.Name, err)
|
||||
continue
|
||||
}
|
||||
completedPartsByNumber, ok := completedPartMap[partNumber]
|
||||
@@ -268,6 +259,7 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedPartEmpty).Inc()
|
||||
continue
|
||||
}
|
||||
//there maybe multi same part, because of client retry
|
||||
partEntries[partNumber] = append(partEntries[partNumber], entry)
|
||||
foundEntry = true
|
||||
}
|
||||
@@ -286,23 +278,27 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
}
|
||||
if entityTooSmall {
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompleteEntityTooSmall).Inc()
|
||||
return nil, nil, s3err.ErrEntityTooSmall
|
||||
return nil, s3err.ErrEntityTooSmall
|
||||
}
|
||||
|
||||
mime := ""
|
||||
if pentry.Attributes != nil {
|
||||
mime = pentry.Attributes.Mime
|
||||
}
|
||||
finalParts := make([]*filer_pb.FileChunk, 0)
|
||||
partBoundaries := make([]multipartPartBoundary, 0, len(completedPartNumbers))
|
||||
mime := pentry.Attributes.Mime
|
||||
var finalParts []*filer_pb.FileChunk
|
||||
var offset int64
|
||||
|
||||
// Track part boundaries for later retrieval with PartNumber parameter
|
||||
type PartBoundary struct {
|
||||
PartNumber int `json:"part"`
|
||||
StartChunk int `json:"start"`
|
||||
EndChunk int `json:"end"` // exclusive
|
||||
ETag string `json:"etag"`
|
||||
}
|
||||
var partBoundaries []PartBoundary
|
||||
|
||||
for _, partNumber := range completedPartNumbers {
|
||||
partEntriesByNumber, ok := partEntries[partNumber]
|
||||
if !ok {
|
||||
glog.Errorf("part %d has no entry", partNumber)
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedPartNotFound).Inc()
|
||||
return nil, nil, s3err.ErrInvalidPart
|
||||
return nil, s3err.ErrInvalidPart
|
||||
}
|
||||
found := false
|
||||
|
||||
@@ -316,11 +312,20 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
continue
|
||||
}
|
||||
|
||||
// Record the start chunk index for this part
|
||||
partStartChunk := len(finalParts)
|
||||
|
||||
// Calculate the part's ETag (for GetObject with PartNumber)
|
||||
partETag := filer.ETag(entry)
|
||||
|
||||
for _, chunk := range entry.GetChunks() {
|
||||
finalParts = append(finalParts, &filer_pb.FileChunk{
|
||||
// CRITICAL: Do NOT modify SSE metadata offsets during assembly!
|
||||
// The encrypted data was created with the offset stored in chunk.SseMetadata.
|
||||
// Changing the offset here would cause decryption to fail because CTR mode
|
||||
// uses the offset to initialize the counter. We must decrypt with the same
|
||||
// offset that was used during encryption.
|
||||
|
||||
p := &filer_pb.FileChunk{
|
||||
FileId: chunk.GetFileIdString(),
|
||||
Offset: offset,
|
||||
Size: chunk.Size,
|
||||
@@ -328,14 +333,17 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
CipherKey: chunk.CipherKey,
|
||||
ETag: chunk.ETag,
|
||||
IsCompressed: chunk.IsCompressed,
|
||||
SseType: chunk.SseType,
|
||||
SseMetadata: chunk.SseMetadata,
|
||||
})
|
||||
// Preserve SSE metadata UNCHANGED - do not modify the offset!
|
||||
SseType: chunk.SseType,
|
||||
SseMetadata: chunk.SseMetadata,
|
||||
}
|
||||
finalParts = append(finalParts, p)
|
||||
offset += int64(chunk.Size)
|
||||
}
|
||||
|
||||
// Record the part boundary
|
||||
partEndChunk := len(finalParts)
|
||||
partBoundaries = append(partBoundaries, multipartPartBoundary{
|
||||
partBoundaries = append(partBoundaries, PartBoundary{
|
||||
PartNumber: partNumber,
|
||||
StartChunk: partStartChunk,
|
||||
EndChunk: partEndChunk,
|
||||
@@ -346,218 +354,183 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
}
|
||||
}
|
||||
|
||||
return &multipartCompletionState{
|
||||
deleteEntries: deleteEntries,
|
||||
partEntries: partEntries,
|
||||
pentry: pentry,
|
||||
mime: mime,
|
||||
finalParts: finalParts,
|
||||
offset: offset,
|
||||
partBoundaries: partBoundaries,
|
||||
multipartETag: calculateMultipartETag(partEntries, completedPartNumbers),
|
||||
entityWithTtl: entityWithTtl,
|
||||
}, nil, s3err.ErrNone
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.CompleteMultipartUploadInput, parts *CompleteMultipartUpload) (output *CompleteMultipartUploadResult, code s3err.ErrorCode) {
|
||||
|
||||
glog.V(2).Infof("completeMultipartUpload input %v", input)
|
||||
if len(parts.Parts) == 0 {
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
completedPartNumbers := []int{}
|
||||
completedPartMap := make(map[int][]string)
|
||||
|
||||
maxPartNo := 1
|
||||
lastSeenPartNo := 0
|
||||
|
||||
for _, part := range parts.Parts {
|
||||
if part.PartNumber < lastSeenPartNo {
|
||||
return nil, s3err.ErrInvalidPartOrder
|
||||
}
|
||||
lastSeenPartNo = part.PartNumber
|
||||
if _, ok := completedPartMap[part.PartNumber]; !ok {
|
||||
completedPartNumbers = append(completedPartNumbers, part.PartNumber)
|
||||
}
|
||||
completedPartMap[part.PartNumber] = append(completedPartMap[part.PartNumber], part.ETag)
|
||||
maxPartNo = maxInt(maxPartNo, part.PartNumber)
|
||||
}
|
||||
|
||||
uploadDirectory := s3a.genUploadsFolder(*input.Bucket) + "/" + *input.UploadId
|
||||
entryName, dirName := s3a.getEntryNameAndDir(input)
|
||||
var completionState *multipartCompletionState
|
||||
finalizeCode := s3a.withObjectWriteLock(*input.Bucket, *input.Key, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, *input.Bucket, *input.Key)
|
||||
}, func() s3err.ErrorCode {
|
||||
var prepCode s3err.ErrorCode
|
||||
completionState, output, prepCode = s3a.prepareMultipartCompletionState(r, input, uploadDirectory, entryName, dirName, completedPartNumbers, completedPartMap, maxPartNo)
|
||||
if prepCode != s3err.ErrNone || output != nil {
|
||||
return prepCode
|
||||
}
|
||||
|
||||
etagQuote := "\"" + completionState.multipartETag + "\""
|
||||
// Check if versioning is configured for this bucket BEFORE creating any files.
|
||||
versioningState, vErr := s3a.getVersioningState(*input.Bucket)
|
||||
if vErr != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to get versioning state for bucket %s: %v", *input.Bucket, vErr)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
if versioningState == s3_constants.VersioningEnabled {
|
||||
// Use full object key (not just entryName) to ensure correct .versions directory is checked
|
||||
normalizedKey := strings.TrimPrefix(*input.Key, "/")
|
||||
useInvertedFormat := s3a.getVersionIdFormat(*input.Bucket, normalizedKey)
|
||||
versionId := generateVersionId(useInvertedFormat)
|
||||
versionFileName := s3a.getVersionFileName(versionId)
|
||||
versionDir := dirName + "/" + entryName + s3_constants.VersionsFolder
|
||||
// Precompute ETag once for consistency across all paths
|
||||
multipartETag := calculateMultipartETag(partEntries, completedPartNumbers)
|
||||
etagQuote := "\"" + multipartETag + "\""
|
||||
|
||||
// Capture timestamp and owner once for consistency between version entry and cache entry
|
||||
versionMtime := time.Now().Unix()
|
||||
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
|
||||
// Check if versioning is configured for this bucket BEFORE creating any files
|
||||
versioningState, vErr := s3a.getVersioningState(*input.Bucket)
|
||||
if vErr == nil && versioningState == s3_constants.VersioningEnabled {
|
||||
// Use full object key (not just entryName) to ensure correct .versions directory is checked
|
||||
normalizedKey := strings.TrimPrefix(*input.Key, "/")
|
||||
useInvertedFormat := s3a.getVersionIdFormat(*input.Bucket, normalizedKey)
|
||||
versionId := generateVersionId(useInvertedFormat)
|
||||
versionFileName := s3a.getVersionFileName(versionId)
|
||||
versionDir := dirName + "/" + entryName + s3_constants.VersionsFolder
|
||||
|
||||
// Create the version file in the .versions directory
|
||||
if err := s3a.mkFile(versionDir, versionFileName, completionState.finalParts, func(versionEntry *filer_pb.Entry) {
|
||||
if versionEntry.Extended == nil {
|
||||
versionEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
versionEntry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionId)
|
||||
versionEntry.Extended[s3_constants.SeaweedFSUploadId] = []byte(*input.UploadId)
|
||||
// Store parts count for x-amz-mp-parts-count header
|
||||
versionEntry.Extended[s3_constants.SeaweedFSMultipartPartsCount] = []byte(fmt.Sprintf("%d", len(completedPartNumbers)))
|
||||
// Store part boundaries for GetObject with PartNumber
|
||||
if partBoundariesJSON, err := json.Marshal(completionState.partBoundaries); err == nil {
|
||||
versionEntry.Extended[s3_constants.SeaweedFSMultipartPartBoundaries] = partBoundariesJSON
|
||||
}
|
||||
// Capture timestamp and owner once for consistency between version entry and cache entry
|
||||
versionMtime := time.Now().Unix()
|
||||
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
|
||||
|
||||
// Set object owner for versioned multipart objects
|
||||
if amzAccountId != "" {
|
||||
versionEntry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
}
|
||||
|
||||
for k, v := range completionState.pentry.Extended {
|
||||
if k != s3_constants.ExtMultipartObjectKey {
|
||||
versionEntry.Extended[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// Persist ETag to ensure subsequent HEAD/GET uses the same value
|
||||
versionEntry.Extended[s3_constants.ExtETagKey] = []byte(completionState.multipartETag)
|
||||
|
||||
// Preserve ALL SSE metadata from the first part (if any)
|
||||
// SSE metadata is stored in individual parts, not the upload directory
|
||||
if len(completedPartNumbers) > 0 && len(completionState.partEntries[completedPartNumbers[0]]) > 0 {
|
||||
firstPartEntry := completionState.partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(versionEntry, firstPartEntry, "versioned")
|
||||
}
|
||||
if completionState.pentry.Attributes != nil && completionState.pentry.Attributes.Mime != "" {
|
||||
versionEntry.Attributes.Mime = completionState.pentry.Attributes.Mime
|
||||
} else if completionState.mime != "" {
|
||||
versionEntry.Attributes.Mime = completionState.mime
|
||||
}
|
||||
versionEntry.Attributes.FileSize = uint64(completionState.offset)
|
||||
versionEntry.Attributes.Mtime = versionMtime
|
||||
}); err != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to create version %s: %v", versionId, err)
|
||||
return s3err.ErrInternalError
|
||||
// Create the version file in the .versions directory
|
||||
err = s3a.mkFile(versionDir, versionFileName, finalParts, func(versionEntry *filer_pb.Entry) {
|
||||
if versionEntry.Extended == nil {
|
||||
versionEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
versionEntry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionId)
|
||||
versionEntry.Extended[s3_constants.SeaweedFSUploadId] = []byte(*input.UploadId)
|
||||
// Store parts count for x-amz-mp-parts-count header
|
||||
versionEntry.Extended[s3_constants.SeaweedFSMultipartPartsCount] = []byte(fmt.Sprintf("%d", len(completedPartNumbers)))
|
||||
// Store part boundaries for GetObject with PartNumber
|
||||
if partBoundariesJSON, err := json.Marshal(partBoundaries); err == nil {
|
||||
versionEntry.Extended[s3_constants.SeaweedFSMultipartPartBoundaries] = partBoundariesJSON
|
||||
}
|
||||
|
||||
// Construct entry with metadata for caching in .versions directory
|
||||
// Reuse versionMtime to keep list vs. HEAD timestamps aligned
|
||||
// multipartETag is precomputed
|
||||
versionEntryForCache := &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileSize: uint64(completionState.offset),
|
||||
Mtime: versionMtime,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtETagKey: []byte(completionState.multipartETag),
|
||||
},
|
||||
}
|
||||
// Set object owner for versioned multipart objects
|
||||
if amzAccountId != "" {
|
||||
versionEntryForCache.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
versionEntry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
}
|
||||
|
||||
// Update the .versions directory metadata to indicate this is the latest version
|
||||
// Pass entry to cache its metadata for single-scan list efficiency
|
||||
if err := s3a.updateLatestVersionInDirectory(*input.Bucket, *input.Key, versionId, versionFileName, versionEntryForCache); err != nil {
|
||||
if rollbackErr := s3a.rollbackMultipartVersion(versionDir, versionFileName); rollbackErr != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to rollback version %s for %s/%s after latest pointer update error: %v", versionId, *input.Bucket, *input.Key, rollbackErr)
|
||||
for k, v := range pentry.Extended {
|
||||
if k != s3_constants.ExtMultipartObjectKey {
|
||||
versionEntry.Extended[k] = v
|
||||
}
|
||||
glog.Errorf("completeMultipartUpload: failed to update latest version in directory: %v", err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// For versioned buckets, all content is stored in .versions directory
|
||||
// The latest version information is tracked in the .versions directory metadata
|
||||
output = &CompleteMultipartUploadResult{
|
||||
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
|
||||
Bucket: input.Bucket,
|
||||
ETag: aws.String(etagQuote),
|
||||
Key: objectKey(input.Key),
|
||||
VersionId: aws.String(versionId),
|
||||
// Persist ETag to ensure subsequent HEAD/GET uses the same value
|
||||
versionEntry.Extended[s3_constants.ExtETagKey] = []byte(multipartETag)
|
||||
|
||||
// Preserve ALL SSE metadata from the first part (if any)
|
||||
// SSE metadata is stored in individual parts, not the upload directory
|
||||
if len(completedPartNumbers) > 0 && len(partEntries[completedPartNumbers[0]]) > 0 {
|
||||
firstPartEntry := partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(versionEntry, firstPartEntry, "versioned")
|
||||
}
|
||||
return s3err.ErrNone
|
||||
if pentry.Attributes.Mime != "" {
|
||||
versionEntry.Attributes.Mime = pentry.Attributes.Mime
|
||||
} else if mime != "" {
|
||||
versionEntry.Attributes.Mime = mime
|
||||
}
|
||||
versionEntry.Attributes.FileSize = uint64(offset)
|
||||
versionEntry.Attributes.Mtime = versionMtime
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to create version %s: %v", versionId, err)
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
if versioningState == s3_constants.VersioningSuspended {
|
||||
// For suspended versioning, add "null" version ID metadata and return "null" version ID
|
||||
if err := s3a.mkFile(dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
entry.Extended[s3_constants.ExtVersionIdKey] = []byte("null")
|
||||
entry.Extended[s3_constants.SeaweedFSUploadId] = []byte(*input.UploadId)
|
||||
// Store parts count for x-amz-mp-parts-count header
|
||||
entry.Extended[s3_constants.SeaweedFSMultipartPartsCount] = []byte(fmt.Sprintf("%d", len(completedPartNumbers)))
|
||||
// Store part boundaries for GetObject with PartNumber
|
||||
if partBoundariesJSON, jsonErr := json.Marshal(completionState.partBoundaries); jsonErr == nil {
|
||||
entry.Extended[s3_constants.SeaweedFSMultipartPartBoundaries] = partBoundariesJSON
|
||||
}
|
||||
|
||||
// Set object owner for suspended versioning multipart objects
|
||||
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
|
||||
if amzAccountId != "" {
|
||||
entry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
}
|
||||
|
||||
for k, v := range completionState.pentry.Extended {
|
||||
if k != s3_constants.ExtMultipartObjectKey {
|
||||
entry.Extended[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve ALL SSE metadata from the first part (if any)
|
||||
// SSE metadata is stored in individual parts, not the upload directory
|
||||
if len(completedPartNumbers) > 0 && len(completionState.partEntries[completedPartNumbers[0]]) > 0 {
|
||||
firstPartEntry := completionState.partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(entry, firstPartEntry, "suspended versioning")
|
||||
}
|
||||
// Persist ETag to ensure subsequent HEAD/GET uses the same value
|
||||
entry.Extended[s3_constants.ExtETagKey] = []byte(completionState.multipartETag)
|
||||
if completionState.pentry.Attributes != nil && completionState.pentry.Attributes.Mime != "" {
|
||||
entry.Attributes.Mime = completionState.pentry.Attributes.Mime
|
||||
} else if completionState.mime != "" {
|
||||
entry.Attributes.Mime = completionState.mime
|
||||
}
|
||||
entry.Attributes.FileSize = uint64(completionState.offset)
|
||||
}); err != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to create suspended versioning object: %v", err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// Note: Suspended versioning should NOT return VersionId field according to AWS S3 spec
|
||||
output = &CompleteMultipartUploadResult{
|
||||
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
|
||||
Bucket: input.Bucket,
|
||||
ETag: aws.String(etagQuote),
|
||||
Key: objectKey(input.Key),
|
||||
// VersionId field intentionally omitted for suspended versioning
|
||||
}
|
||||
return s3err.ErrNone
|
||||
// Construct entry with metadata for caching in .versions directory
|
||||
// Reuse versionMtime to keep list vs. HEAD timestamps aligned
|
||||
// multipartETag is precomputed
|
||||
versionEntryForCache := &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileSize: uint64(offset),
|
||||
Mtime: versionMtime,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtETagKey: []byte(multipartETag),
|
||||
},
|
||||
}
|
||||
if amzAccountId != "" {
|
||||
versionEntryForCache.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
}
|
||||
|
||||
// Update the .versions directory metadata to indicate this is the latest version
|
||||
// Pass entry to cache its metadata for single-scan list efficiency
|
||||
err = s3a.updateLatestVersionInDirectory(*input.Bucket, *input.Key, versionId, versionFileName, versionEntryForCache)
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to update latest version in directory: %v", err)
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// For versioned buckets, all content is stored in .versions directory
|
||||
// The latest version information is tracked in the .versions directory metadata
|
||||
output = &CompleteMultipartUploadResult{
|
||||
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
|
||||
Bucket: input.Bucket,
|
||||
ETag: aws.String(etagQuote),
|
||||
Key: objectKey(input.Key),
|
||||
VersionId: aws.String(versionId),
|
||||
}
|
||||
} else if vErr == nil && versioningState == s3_constants.VersioningSuspended {
|
||||
// For suspended versioning, add "null" version ID metadata and return "null" version ID
|
||||
// If conditional headers are present, acquire a distributed lock to atomically
|
||||
// re-check conditions and create the entry, preventing TOCTOU races.
|
||||
condLock, condErr := s3a.lockAndRecheckConditionalHeaders(r, *input.Bucket, *input.Key)
|
||||
if condErr != s3err.ErrNone {
|
||||
return nil, condErr
|
||||
}
|
||||
if condLock != nil {
|
||||
defer condLock.StopShortLivedLock()
|
||||
}
|
||||
err = s3a.mkFile(dirName, entryName, finalParts, func(entry *filer_pb.Entry) {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
entry.Extended[s3_constants.ExtVersionIdKey] = []byte("null")
|
||||
// Store parts count for x-amz-mp-parts-count header
|
||||
entry.Extended[s3_constants.SeaweedFSMultipartPartsCount] = []byte(fmt.Sprintf("%d", len(completedPartNumbers)))
|
||||
// Store part boundaries for GetObject with PartNumber
|
||||
if partBoundariesJSON, jsonErr := json.Marshal(partBoundaries); jsonErr == nil {
|
||||
entry.Extended[s3_constants.SeaweedFSMultipartPartBoundaries] = partBoundariesJSON
|
||||
}
|
||||
|
||||
// Set object owner for suspended versioning multipart objects
|
||||
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
|
||||
if amzAccountId != "" {
|
||||
entry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
}
|
||||
|
||||
for k, v := range pentry.Extended {
|
||||
if k != s3_constants.ExtMultipartObjectKey {
|
||||
entry.Extended[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve ALL SSE metadata from the first part (if any)
|
||||
// SSE metadata is stored in individual parts, not the upload directory
|
||||
if len(completedPartNumbers) > 0 && len(partEntries[completedPartNumbers[0]]) > 0 {
|
||||
firstPartEntry := partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(entry, firstPartEntry, "suspended versioning")
|
||||
}
|
||||
// Persist ETag to ensure subsequent HEAD/GET uses the same value
|
||||
entry.Extended[s3_constants.ExtETagKey] = []byte(multipartETag)
|
||||
if pentry.Attributes.Mime != "" {
|
||||
entry.Attributes.Mime = pentry.Attributes.Mime
|
||||
} else if mime != "" {
|
||||
entry.Attributes.Mime = mime
|
||||
}
|
||||
entry.Attributes.FileSize = uint64(offset)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to create suspended versioning object: %v", err)
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// Note: Suspended versioning should NOT return VersionId field according to AWS S3 spec
|
||||
output = &CompleteMultipartUploadResult{
|
||||
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
|
||||
Bucket: input.Bucket,
|
||||
ETag: aws.String(etagQuote),
|
||||
Key: objectKey(input.Key),
|
||||
// VersionId field intentionally omitted for suspended versioning
|
||||
}
|
||||
} else {
|
||||
// For non-versioned buckets, create main object file
|
||||
if err := s3a.mkFile(dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
|
||||
// If conditional headers are present, acquire a distributed lock to atomically
|
||||
// re-check conditions and create the entry, preventing TOCTOU races.
|
||||
condLock, condErr := s3a.lockAndRecheckConditionalHeaders(r, *input.Bucket, *input.Key)
|
||||
if condErr != s3err.ErrNone {
|
||||
return nil, condErr
|
||||
}
|
||||
if condLock != nil {
|
||||
defer condLock.StopShortLivedLock()
|
||||
}
|
||||
err = s3a.mkFile(dirName, entryName, finalParts, func(entry *filer_pb.Entry) {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
@@ -565,7 +538,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
// Store parts count for x-amz-mp-parts-count header
|
||||
entry.Extended[s3_constants.SeaweedFSMultipartPartsCount] = []byte(fmt.Sprintf("%d", len(completedPartNumbers)))
|
||||
// Store part boundaries for GetObject with PartNumber
|
||||
if partBoundariesJSON, err := json.Marshal(completionState.partBoundaries); err == nil {
|
||||
if partBoundariesJSON, err := json.Marshal(partBoundaries); err == nil {
|
||||
entry.Extended[s3_constants.SeaweedFSMultipartPartBoundaries] = partBoundariesJSON
|
||||
}
|
||||
|
||||
@@ -575,7 +548,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
entry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
}
|
||||
|
||||
for k, v := range completionState.pentry.Extended {
|
||||
for k, v := range pentry.Extended {
|
||||
if k != s3_constants.ExtMultipartObjectKey {
|
||||
entry.Extended[k] = v
|
||||
}
|
||||
@@ -583,25 +556,27 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
|
||||
// Preserve ALL SSE metadata from the first part (if any)
|
||||
// SSE metadata is stored in individual parts, not the upload directory
|
||||
if len(completedPartNumbers) > 0 && len(completionState.partEntries[completedPartNumbers[0]]) > 0 {
|
||||
firstPartEntry := completionState.partEntries[completedPartNumbers[0]][0]
|
||||
if len(completedPartNumbers) > 0 && len(partEntries[completedPartNumbers[0]]) > 0 {
|
||||
firstPartEntry := partEntries[completedPartNumbers[0]][0]
|
||||
copySSEHeadersFromFirstPart(entry, firstPartEntry, "non-versioned")
|
||||
}
|
||||
// Persist ETag to ensure subsequent HEAD/GET uses the same value
|
||||
entry.Extended[s3_constants.ExtETagKey] = []byte(completionState.multipartETag)
|
||||
if completionState.pentry.Attributes != nil && completionState.pentry.Attributes.Mime != "" {
|
||||
entry.Attributes.Mime = completionState.pentry.Attributes.Mime
|
||||
} else if completionState.mime != "" {
|
||||
entry.Attributes.Mime = completionState.mime
|
||||
entry.Extended[s3_constants.ExtETagKey] = []byte(multipartETag)
|
||||
if pentry.Attributes.Mime != "" {
|
||||
entry.Attributes.Mime = pentry.Attributes.Mime
|
||||
} else if mime != "" {
|
||||
entry.Attributes.Mime = mime
|
||||
}
|
||||
entry.Attributes.FileSize = uint64(completionState.offset)
|
||||
entry.Attributes.FileSize = uint64(offset)
|
||||
// Set TTL-based S3 expiry (modification time)
|
||||
if completionState.entityWithTtl {
|
||||
if entityWithTtl {
|
||||
entry.Extended[s3_constants.SeaweedFSExpiresS3] = []byte("true")
|
||||
}
|
||||
}); err != nil {
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s/%s error: %v", dirName, entryName, err)
|
||||
return s3err.ErrInternalError
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// For non-versioned buckets, return response without VersionId
|
||||
@@ -611,30 +586,21 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
ETag: aws.String(etagQuote),
|
||||
Key: objectKey(input.Key),
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
if finalizeCode != s3err.ErrNone {
|
||||
return nil, finalizeCode
|
||||
}
|
||||
|
||||
if completionState != nil {
|
||||
for _, deleteEntry := range completionState.deleteEntries {
|
||||
if err := s3a.rm(uploadDirectory, deleteEntry.Name, true, true); err != nil {
|
||||
glog.Warningf("completeMultipartUpload cleanup %s upload %s unused %s : %v", *input.Bucket, *input.UploadId, deleteEntry.Name, err)
|
||||
}
|
||||
}
|
||||
if err := s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, false, true); err != nil {
|
||||
glog.V(1).Infof("completeMultipartUpload cleanup %s upload %s: %v", *input.Bucket, *input.UploadId, err)
|
||||
for _, deleteEntry := range deleteEntries {
|
||||
//delete unused part data
|
||||
if err = s3a.rm(uploadDirectory, deleteEntry.Name, true, true); err != nil {
|
||||
glog.Warningf("completeMultipartUpload cleanup %s upload %s unused %s : %v", *input.Bucket, *input.UploadId, deleteEntry.Name, err)
|
||||
}
|
||||
}
|
||||
if err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, false, true); err != nil {
|
||||
glog.V(1).Infof("completeMultipartUpload cleanup %s upload %s: %v", *input.Bucket, *input.UploadId, err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) rollbackMultipartVersion(versionDir, versionFileName string) error {
|
||||
return s3a.rmObject(versionDir, versionFileName, true, false)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) getEntryNameAndDir(input *s3.CompleteMultipartUploadInput) (string, string) {
|
||||
entryName := path.Base(*input.Key)
|
||||
dirName := path.Dir(*input.Key)
|
||||
|
||||
@@ -2,7 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -55,42 +54,6 @@ func TestListPartsResult(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
func TestCompleteMultipartResultIncludesVersionId(t *testing.T) {
|
||||
r := &http.Request{Host: "localhost", Header: make(http.Header)}
|
||||
input := &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String("example-bucket"),
|
||||
Key: aws.String("example-object"),
|
||||
}
|
||||
|
||||
entry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte("version-123"),
|
||||
},
|
||||
}
|
||||
|
||||
result := completeMultipartResult(r, input, "\"etag-value\"", entry)
|
||||
if assert.NotNil(t, result.VersionId) {
|
||||
assert.Equal(t, "version-123", *result.VersionId)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteMultipartResultOmitsNullVersionId(t *testing.T) {
|
||||
r := &http.Request{Host: "localhost", Header: make(http.Header)}
|
||||
input := &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String("example-bucket"),
|
||||
Key: aws.String("example-object"),
|
||||
}
|
||||
|
||||
entry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte("null"),
|
||||
},
|
||||
}
|
||||
|
||||
result := completeMultipartResult(r, input, "\"etag-value\"", entry)
|
||||
assert.Nil(t, result.VersionId)
|
||||
}
|
||||
|
||||
func Test_parsePartNumber(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -227,41 +190,3 @@ func TestValidateCompletePartETag(t *testing.T) {
|
||||
assert.True(t, invalid)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompleteMultipartUploadRejectsOutOfOrderParts(t *testing.T) {
|
||||
s3a := NewS3ApiServerForTest()
|
||||
input := &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
Key: aws.String("object"),
|
||||
UploadId: aws.String("upload"),
|
||||
}
|
||||
parts := &CompleteMultipartUpload{
|
||||
Parts: []CompletedPart{
|
||||
{PartNumber: 2, ETag: "\"etag-2\""},
|
||||
{PartNumber: 1, ETag: "\"etag-1\""},
|
||||
},
|
||||
}
|
||||
|
||||
result, errCode := s3a.completeMultipartUpload(&http.Request{Header: make(http.Header)}, input, parts)
|
||||
assert.Nil(t, result)
|
||||
assert.Equal(t, s3err.ErrInvalidPartOrder, errCode)
|
||||
}
|
||||
|
||||
func TestCompleteMultipartUploadAllowsDuplicatePartNumbers(t *testing.T) {
|
||||
s3a := NewS3ApiServerForTest()
|
||||
input := &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
Key: aws.String("object"),
|
||||
UploadId: aws.String("upload"),
|
||||
}
|
||||
parts := &CompleteMultipartUpload{
|
||||
Parts: []CompletedPart{
|
||||
{PartNumber: 1, ETag: "\"etag-older\""},
|
||||
{PartNumber: 1, ETag: "\"etag-newer\""},
|
||||
},
|
||||
}
|
||||
|
||||
result, errCode := s3a.completeMultipartUpload(&http.Request{Header: make(http.Header)}, input, parts)
|
||||
assert.Nil(t, result)
|
||||
assert.Equal(t, s3err.ErrNoSuchUpload, errCode)
|
||||
}
|
||||
@@ -167,6 +167,12 @@ func (s3a *S3ApiServer) exists(parentDirectoryPath string, entryName string, isD
|
||||
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) touch(parentDirectoryPath string, entryName string, entry *filer_pb.Entry) (err error) {
|
||||
|
||||
return filer_pb.Touch(context.Background(), s3a, parentDirectoryPath, entryName, entry)
|
||||
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) getEntry(parentDirectoryPath, entryName string) (entry *filer_pb.Entry, err error) {
|
||||
fullPath := util.NewFullPath(parentDirectoryPath, entryName)
|
||||
return filer_pb.GetEntry(context.Background(), s3a, fullPath)
|
||||
|
||||
@@ -210,15 +210,7 @@ func (engine *PolicyEngine) evaluateStatement(stmt *CompiledStatement, args *Pol
|
||||
|
||||
// Check conditions
|
||||
if len(stmt.Statement.Condition) > 0 {
|
||||
condCtx := args.Conditions
|
||||
// Multipart continuation actions (UploadPart, UploadPartCopy) inherit SSE
|
||||
// from CreateMultipartUpload and do not carry their own SSE header.
|
||||
// Inject the real inherited algorithm so Null/StringEquals conditions
|
||||
// evaluate against the value that was set at upload initiation.
|
||||
if IsMultipartContinuationAction(args.Action) {
|
||||
condCtx = injectSSEForMultipart(args.Conditions, args.InheritedSSEAlgorithm)
|
||||
}
|
||||
match := EvaluateConditions(stmt.Statement.Condition, condCtx, args.ObjectEntry, args.Claims)
|
||||
match := EvaluateConditions(stmt.Statement.Condition, args.Conditions, args.ObjectEntry, args.Claims)
|
||||
if !match {
|
||||
return false
|
||||
}
|
||||
@@ -443,62 +435,9 @@ func ExtractConditionValuesFromRequest(r *http.Request) map[string][]string {
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize s3:x-amz-server-side-encryption value to canonical form.
|
||||
// AWS accepts "AES256" case-insensitively; normalise so that policy
|
||||
// StringEquals conditions work regardless of client capitalisation.
|
||||
const sseKey = "s3:x-amz-server-side-encryption"
|
||||
if sseVals, ok := values[sseKey]; ok {
|
||||
normalized := make([]string, len(sseVals))
|
||||
for i, v := range sseVals {
|
||||
switch strings.ToUpper(v) {
|
||||
case "AES256":
|
||||
normalized[i] = "AES256"
|
||||
case "AWS:KMS":
|
||||
normalized[i] = "aws:kms"
|
||||
default:
|
||||
normalized[i] = v
|
||||
}
|
||||
}
|
||||
values[sseKey] = normalized
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
// IsMultipartContinuationAction returns true for actions that do not carry
|
||||
// their own SSE header because SSE is inherited from CreateMultipartUpload.
|
||||
func IsMultipartContinuationAction(action string) bool {
|
||||
return action == "s3:UploadPart" || action == "s3:UploadPartCopy"
|
||||
}
|
||||
|
||||
// injectSSEForMultipart returns a condition context augmented with the
|
||||
// inherited SSE algorithm for multipart continuation actions.
|
||||
//
|
||||
// UploadPart and UploadPartCopy do not re-send the SSE header because
|
||||
// encryption is set once at CreateMultipartUpload. The caller supplies
|
||||
// inheritedSSE (the canonical algorithm, e.g. "AES256" or "aws:kms") so
|
||||
// that Null/StringEquals conditions on s3:x-amz-server-side-encryption
|
||||
// evaluate against the real value.
|
||||
//
|
||||
// If inheritedSSE is empty (no SSE was requested at initiation), the
|
||||
// conditions map is returned unchanged so Null("true") will correctly
|
||||
// match and deny the request.
|
||||
func injectSSEForMultipart(conditions map[string][]string, inheritedSSE string) map[string][]string {
|
||||
const sseKey = "s3:x-amz-server-side-encryption"
|
||||
if inheritedSSE == "" {
|
||||
return conditions // no SSE at upload initiation; let Null("true") fire
|
||||
}
|
||||
if _, exists := conditions[sseKey]; exists {
|
||||
return conditions // SSE header was actually sent on this request
|
||||
}
|
||||
modified := make(map[string][]string, len(conditions)+1)
|
||||
for k, v := range conditions {
|
||||
modified[k] = v
|
||||
}
|
||||
modified[sseKey] = []string{inheritedSSE}
|
||||
return modified
|
||||
}
|
||||
|
||||
// extractSourceIP returns the best-effort client IP address for condition evaluation.
|
||||
// Preference order: X-Forwarded-For (first valid IP), X-Real-Ip, then RemoteAddr.
|
||||
// IMPORTANT: X-Forwarded-For and X-Real-Ip are trusted without validation.
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
package policy_engine
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// requiresSSEPolicy is a bucket policy that denies PutObject when the
|
||||
// x-amz-server-side-encryption header is absent (Null == true).
|
||||
const requiresSSEPolicy = `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "DenyUnencryptedUploads",
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::test-bucket/*",
|
||||
"Condition": {
|
||||
"Null": {
|
||||
"s3:x-amz-server-side-encryption": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
// requiresAES256Policy denies PutObject unless AES256 is explicitly requested.
|
||||
const requiresAES256Policy = `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "AllowAES256Only",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::test-bucket/*",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"s3:x-amz-server-side-encryption": "AES256"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
// requiresKMSPolicy allows PutObject only when aws:kms encryption is requested.
|
||||
const requiresKMSPolicy = `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "AllowKMSOnly",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::test-bucket/*",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"s3:x-amz-server-side-encryption": "aws:kms"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
// multipartPolicy denies PutObject when SSE is absent but should NOT block UploadPart.
|
||||
const multipartPolicy = `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "DenyUnencryptedUploads",
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": ["s3:PutObject", "s3:UploadPart", "s3:UploadPartCopy"],
|
||||
"Resource": "arn:aws:s3:::test-bucket/*",
|
||||
"Condition": {
|
||||
"Null": {
|
||||
"s3:x-amz-server-side-encryption": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
func newEngineWithPolicy(t *testing.T, policy string) *PolicyEngine {
|
||||
t.Helper()
|
||||
engine := NewPolicyEngine()
|
||||
if err := engine.SetBucketPolicy("test-bucket", policy); err != nil {
|
||||
t.Fatalf("SetBucketPolicy: %v", err)
|
||||
}
|
||||
return engine
|
||||
}
|
||||
|
||||
func evalArgs(action string, conditions map[string][]string) *PolicyEvaluationArgs {
|
||||
return &PolicyEvaluationArgs{
|
||||
Action: action,
|
||||
Resource: "arn:aws:s3:::test-bucket/object.txt",
|
||||
Principal: "*",
|
||||
Conditions: conditions,
|
||||
}
|
||||
}
|
||||
|
||||
func evalArgsWithSSE(action, inheritedSSE string) *PolicyEvaluationArgs {
|
||||
return &PolicyEvaluationArgs{
|
||||
Action: action,
|
||||
Resource: "arn:aws:s3:::test-bucket/object.txt",
|
||||
Principal: "*",
|
||||
Conditions: map[string][]string{},
|
||||
InheritedSSEAlgorithm: inheritedSSE,
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEStringEqualsPresent – StringEquals with AES256 header present should Allow.
|
||||
func TestSSEStringEqualsPresent(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, requiresAES256Policy)
|
||||
|
||||
conditions := map[string][]string{
|
||||
"s3:x-amz-server-side-encryption": {"AES256"},
|
||||
}
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgs("s3:PutObject", conditions))
|
||||
if result != PolicyResultAllow {
|
||||
t.Errorf("expected Allow, got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEStringEqualsWrongValue – StringEquals with wrong SSE value should not Allow.
|
||||
func TestSSEStringEqualsWrongValue(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, requiresAES256Policy)
|
||||
|
||||
conditions := map[string][]string{
|
||||
"s3:x-amz-server-side-encryption": {"aws:kms"},
|
||||
}
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgs("s3:PutObject", conditions))
|
||||
if result == PolicyResultAllow {
|
||||
t.Errorf("expected non-Allow, got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSENullConditionAbsent – Null("true") matches when header is absent → Deny.
|
||||
func TestSSENullConditionAbsent(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, requiresSSEPolicy)
|
||||
|
||||
// No SSE header → condition "Null == true" matches → Deny statement fires
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgs("s3:PutObject", map[string][]string{}))
|
||||
if result != PolicyResultDeny {
|
||||
t.Errorf("expected Deny (no SSE header), got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSENullConditionPresent – Null("true") does NOT match when header is present → not Deny.
|
||||
func TestSSENullConditionPresent(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, requiresSSEPolicy)
|
||||
|
||||
conditions := map[string][]string{
|
||||
"s3:x-amz-server-side-encryption": {"AES256"},
|
||||
}
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgs("s3:PutObject", conditions))
|
||||
// Deny condition not matched; no explicit Allow → Indeterminate
|
||||
if result == PolicyResultDeny {
|
||||
t.Errorf("expected non-Deny when SSE header present, got Deny")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSECaseInsensitiveNormalizationAES256 drives the AES256 normalisation
|
||||
// through EvaluatePolicyForRequest so that a regression in the production
|
||||
// code path would be caught. The request carries the header in lowercase
|
||||
// ("aes256"); after normalisation it must match the policy's "AES256" value.
|
||||
func TestSSECaseInsensitiveNormalizationAES256(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, requiresAES256Policy)
|
||||
|
||||
req, _ := http.NewRequest(http.MethodPut, "/", nil)
|
||||
req.RemoteAddr = "1.2.3.4:1234"
|
||||
req.Header.Set("X-Amz-Server-Side-Encryption", "aes256") // lowercase
|
||||
|
||||
result := engine.EvaluatePolicyForRequest("test-bucket", "object.txt", "PutObject", "*", req)
|
||||
if result != PolicyResultAllow {
|
||||
t.Errorf("expected Allow after AES256 case normalisation, got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSECaseInsensitiveNormalizationKMS drives the aws:kms branch of the
|
||||
// normalisation through the production code path. The request carries
|
||||
// "AWS:KMS" (mixed case); after normalisation it must match "aws:kms".
|
||||
func TestSSECaseInsensitiveNormalizationKMS(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, requiresKMSPolicy)
|
||||
|
||||
req, _ := http.NewRequest(http.MethodPut, "/", nil)
|
||||
req.RemoteAddr = "1.2.3.4:1234"
|
||||
req.Header.Set("X-Amz-Server-Side-Encryption", "AWS:KMS") // mixed case
|
||||
|
||||
result := engine.EvaluatePolicyForRequest("test-bucket", "object.txt", "PutObject", "*", req)
|
||||
if result != PolicyResultAllow {
|
||||
t.Errorf("expected Allow after aws:kms case normalisation, got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEMultipartAES256Exempt – UploadPart with AES256 inherited from
|
||||
// CreateMultipartUpload is not blocked by the Null("true") deny condition.
|
||||
func TestSSEMultipartAES256Exempt(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, multipartPolicy)
|
||||
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgsWithSSE("s3:UploadPart", "AES256"))
|
||||
if result == PolicyResultDeny {
|
||||
t.Errorf("UploadPart with inherited AES256 should not be Deny, got Deny")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEMultipartKMSExempt – UploadPart with aws:kms inherited from
|
||||
// CreateMultipartUpload is not blocked by the Null("true") deny condition.
|
||||
func TestSSEMultipartKMSExempt(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, multipartPolicy)
|
||||
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgsWithSSE("s3:UploadPart", "aws:kms"))
|
||||
if result == PolicyResultDeny {
|
||||
t.Errorf("UploadPart with inherited aws:kms should not be Deny, got Deny")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEMultipartNoSSEDenied – UploadPart for an upload that had no SSE
|
||||
// must still be denied by the Null("true") deny condition.
|
||||
func TestSSEMultipartNoSSEDenied(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, multipartPolicy)
|
||||
|
||||
// inheritedSSE="" means CreateMultipartUpload was sent without SSE
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgsWithSSE("s3:UploadPart", ""))
|
||||
if result != PolicyResultDeny {
|
||||
t.Errorf("UploadPart with no inherited SSE should be Deny, got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEUploadPartCopyKMSExempt – UploadPartCopy with aws:kms is also exempt.
|
||||
func TestSSEUploadPartCopyKMSExempt(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, multipartPolicy)
|
||||
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgsWithSSE("s3:UploadPartCopy", "aws:kms"))
|
||||
if result == PolicyResultDeny {
|
||||
t.Errorf("UploadPartCopy with inherited aws:kms should not be Deny, got Deny")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEPutObjectStillBlockedWithoutHeader – regular PutObject still denied without SSE.
|
||||
func TestSSEPutObjectStillBlockedWithoutHeader(t *testing.T) {
|
||||
engine := newEngineWithPolicy(t, multipartPolicy)
|
||||
|
||||
result := engine.EvaluatePolicy("test-bucket", evalArgs("s3:PutObject", map[string][]string{}))
|
||||
if result != PolicyResultDeny {
|
||||
t.Errorf("PutObject without SSE should be Deny, got %v", result)
|
||||
}
|
||||
}
|
||||
@@ -100,11 +100,6 @@ func NewStringOrStringSlicePtr(values ...string) *StringOrStringSlice {
|
||||
return &StringOrStringSlice{values: values}
|
||||
}
|
||||
|
||||
// CloneStringOrStringSlice returns a copy with its own backing slice.
|
||||
func CloneStringOrStringSlice(value StringOrStringSlice) StringOrStringSlice {
|
||||
return StringOrStringSlice{values: append([]string(nil), value.values...)}
|
||||
}
|
||||
|
||||
// PolicyConditions represents policy conditions with proper typing
|
||||
type PolicyConditions map[string]map[string]StringOrStringSlice
|
||||
|
||||
@@ -177,10 +172,6 @@ type PolicyEvaluationArgs struct {
|
||||
ObjectEntry map[string][]byte
|
||||
// Claims are JWT claims for jwt:* policy variables (can be nil)
|
||||
Claims map[string]interface{}
|
||||
// InheritedSSEAlgorithm is the canonical SSE algorithm ("AES256" or "aws:kms")
|
||||
// inherited from the CreateMultipartUpload request for UploadPart and
|
||||
// UploadPartCopy actions. The empty string means no SSE was used.
|
||||
InheritedSSEAlgorithm string
|
||||
}
|
||||
|
||||
// PolicyCache for caching compiled policies
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package policy_engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCloneStringOrStringSliceCopiesBackingSlice(t *testing.T) {
|
||||
original := NewStringOrStringSlice("s3:GetObject", "s3:PutObject")
|
||||
|
||||
cloned := CloneStringOrStringSlice(original)
|
||||
cloned.values[0] = "s3:DeleteObject"
|
||||
|
||||
assert.Equal(t, []string{"s3:GetObject", "s3:PutObject"}, original.Strings())
|
||||
assert.Equal(t, []string{"s3:DeleteObject", "s3:PutObject"}, cloned.Strings())
|
||||
}
|
||||
@@ -36,6 +36,18 @@ type ApplyServerSideEncryptionByDefault struct {
|
||||
KMSMasterKeyID string `xml:"KMSMasterKeyID,omitempty"`
|
||||
}
|
||||
|
||||
// encryptionConfigToProto converts EncryptionConfiguration to protobuf format
|
||||
func encryptionConfigToProto(config *s3_pb.EncryptionConfiguration) *s3_pb.EncryptionConfiguration {
|
||||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
return &s3_pb.EncryptionConfiguration{
|
||||
SseAlgorithm: config.SseAlgorithm,
|
||||
KmsKeyId: config.KmsKeyId,
|
||||
BucketKeyEnabled: config.BucketKeyEnabled,
|
||||
}
|
||||
}
|
||||
|
||||
// encryptionConfigFromXML converts XML ServerSideEncryptionConfiguration to protobuf
|
||||
func encryptionConfigFromXML(xmlConfig *ServerSideEncryptionConfiguration) *s3_pb.EncryptionConfiguration {
|
||||
if xmlConfig == nil || len(xmlConfig.Rules) == 0 {
|
||||
|
||||
@@ -7,6 +7,17 @@ import (
|
||||
|
||||
// ErrorHandlers provide common error handling patterns for S3 API operations
|
||||
|
||||
// handlePutToFilerError logs an error and returns the standard putToFiler error format
|
||||
func handlePutToFilerError(operation string, err error, errorCode s3err.ErrorCode) (string, s3err.ErrorCode, string) {
|
||||
glog.Errorf("Failed to %s: %v", operation, err)
|
||||
return "", errorCode, ""
|
||||
}
|
||||
|
||||
// handlePutToFilerInternalError is a convenience wrapper for internal errors in putToFiler
|
||||
func handlePutToFilerInternalError(operation string, err error) (string, s3err.ErrorCode, string) {
|
||||
return handlePutToFilerError(operation, err, s3err.ErrInternalError)
|
||||
}
|
||||
|
||||
// handleMultipartError logs an error and returns the standard multipart error format
|
||||
func handleMultipartError(operation string, err error, errorCode s3err.ErrorCode) (interface{}, s3err.ErrorCode) {
|
||||
glog.Errorf("Failed to %s: %v", operation, err)
|
||||
@@ -17,3 +28,27 @@ func handleMultipartError(operation string, err error, errorCode s3err.ErrorCode
|
||||
func handleMultipartInternalError(operation string, err error) (interface{}, s3err.ErrorCode) {
|
||||
return handleMultipartError(operation, err, s3err.ErrInternalError)
|
||||
}
|
||||
|
||||
// logErrorAndReturn logs an error with operation context and returns the specified error code
|
||||
func logErrorAndReturn(operation string, err error, errorCode s3err.ErrorCode) s3err.ErrorCode {
|
||||
glog.Errorf("Failed to %s: %v", operation, err)
|
||||
return errorCode
|
||||
}
|
||||
|
||||
// logInternalError is a convenience wrapper for internal error logging
|
||||
func logInternalError(operation string, err error) s3err.ErrorCode {
|
||||
return logErrorAndReturn(operation, err, s3err.ErrInternalError)
|
||||
}
|
||||
|
||||
// SSE-specific error handlers
|
||||
|
||||
// handleSSEError handles common SSE-related errors with appropriate context
|
||||
func handleSSEError(sseType string, operation string, err error, errorCode s3err.ErrorCode) (string, s3err.ErrorCode, string) {
|
||||
glog.Errorf("Failed to %s for %s: %v", operation, sseType, err)
|
||||
return "", errorCode, ""
|
||||
}
|
||||
|
||||
// handleSSEInternalError is a convenience wrapper for SSE internal errors
|
||||
func handleSSEInternalError(sseType string, operation string, err error) (string, s3err.ErrorCode, string) {
|
||||
return handleSSEError(sseType, operation, err, s3err.ErrInternalError)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -381,6 +382,84 @@ func buildS3ResourceArn(bucket string, objectKey string) string {
|
||||
return "arn:aws:s3:::" + bucket + "/" + objectKey
|
||||
}
|
||||
|
||||
// hasSpecificQueryParameters checks if the request has query parameters that indicate specific granular operations
|
||||
func hasSpecificQueryParameters(query url.Values) bool {
|
||||
// Check for object-level operation indicators
|
||||
objectParams := []string{
|
||||
"acl", // ACL operations
|
||||
"tagging", // Tagging operations
|
||||
"retention", // Object retention
|
||||
"legal-hold", // Legal hold
|
||||
"versions", // Versioning operations
|
||||
}
|
||||
|
||||
// Check for multipart operation indicators
|
||||
multipartParams := []string{
|
||||
"uploads", // List/initiate multipart uploads
|
||||
"uploadId", // Part operations, complete, abort
|
||||
"partNumber", // Upload part
|
||||
}
|
||||
|
||||
// Check for bucket-level operation indicators
|
||||
bucketParams := []string{
|
||||
"policy", // Bucket policy operations
|
||||
"website", // Website configuration
|
||||
"cors", // CORS configuration
|
||||
"lifecycle", // Lifecycle configuration
|
||||
"notification", // Event notification
|
||||
"replication", // Cross-region replication
|
||||
"encryption", // Server-side encryption
|
||||
"accelerate", // Transfer acceleration
|
||||
"requestPayment", // Request payment
|
||||
"logging", // Access logging
|
||||
"versioning", // Versioning configuration
|
||||
"inventory", // Inventory configuration
|
||||
"analytics", // Analytics configuration
|
||||
"metrics", // CloudWatch metrics
|
||||
"location", // Bucket location
|
||||
}
|
||||
|
||||
// Check if any of these parameters are present
|
||||
allParams := append(append(objectParams, multipartParams...), bucketParams...)
|
||||
for _, param := range allParams {
|
||||
if _, exists := query[param]; exists {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// isMethodActionMismatch detects when HTTP method doesn't align with the intended S3 action
|
||||
// This provides a mechanism to use fallback action mapping when there's a semantic mismatch
|
||||
func isMethodActionMismatch(method string, fallbackAction Action) bool {
|
||||
switch fallbackAction {
|
||||
case s3_constants.ACTION_WRITE:
|
||||
// WRITE actions should typically use PUT, POST, or DELETE methods
|
||||
// GET/HEAD methods indicate read-oriented operations
|
||||
return method == "GET" || method == "HEAD"
|
||||
|
||||
case s3_constants.ACTION_READ:
|
||||
// READ actions should typically use GET or HEAD methods
|
||||
// PUT, POST, DELETE methods indicate write-oriented operations
|
||||
return method == "PUT" || method == "POST" || method == "DELETE"
|
||||
|
||||
case s3_constants.ACTION_LIST:
|
||||
// LIST actions should typically use GET method
|
||||
// PUT, POST, DELETE methods indicate write-oriented operations
|
||||
return method == "PUT" || method == "POST" || method == "DELETE"
|
||||
|
||||
case s3_constants.ACTION_DELETE_BUCKET:
|
||||
// DELETE_BUCKET should use DELETE method
|
||||
// Other methods indicate different operation types
|
||||
return method != "DELETE"
|
||||
|
||||
default:
|
||||
// For unknown actions or actions that already have s3: prefix, don't assume mismatch
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// mapLegacyActionToIAM provides fallback mapping for legacy actions
|
||||
// This ensures backward compatibility while the system transitions to granular actions
|
||||
func mapLegacyActionToIAM(legacyAction Action) string {
|
||||
@@ -537,6 +616,14 @@ func ParseUnverifiedJWTToken(tokenString string) (jwt.MapClaims, error) {
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
// minInt returns the minimum of two integers
|
||||
func minInt(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// SetIAMIntegration adds advanced IAM integration to the S3ApiServer
|
||||
func (s3a *S3ApiServer) SetIAMIntegration(iamManager *integration.IAMManager) {
|
||||
if s3a.iam != nil {
|
||||
|
||||
@@ -539,6 +539,10 @@ func testJWTAuthentication(t *testing.T, iam *IdentityAccessManagement, token st
|
||||
return iam.authenticateJWTWithIAM(req)
|
||||
}
|
||||
|
||||
func testJWTAuthorization(t *testing.T, iam *IdentityAccessManagement, identity *Identity, action Action, bucket, object, token string) bool {
|
||||
return testJWTAuthorizationWithRole(t, iam, identity, action, bucket, object, token, "TestRole")
|
||||
}
|
||||
|
||||
func testJWTAuthorizationWithRole(t *testing.T, iam *IdentityAccessManagement, identity *Identity, action Action, bucket, object, token, roleName string) bool {
|
||||
// Create test request
|
||||
req := httptest.NewRequest("GET", "/"+bucket+"/"+object, http.NoBody)
|
||||
|
||||
@@ -272,6 +272,19 @@ func createCTRStreamWithOffset(block cipher.Block, iv []byte, counterOffset uint
|
||||
return stream
|
||||
}
|
||||
|
||||
// addCounterToIV adds a counter value to the IV (treating last 8 bytes as big-endian counter)
|
||||
func addCounterToIV(iv []byte, counter uint64) {
|
||||
// Use the last 8 bytes as a big-endian counter
|
||||
for i := 7; i >= 0; i-- {
|
||||
carry := counter & 0xff
|
||||
iv[len(iv)-8+i] += byte(carry)
|
||||
if iv[len(iv)-8+i] >= byte(carry) {
|
||||
break // No overflow
|
||||
}
|
||||
counter >>= 8
|
||||
}
|
||||
}
|
||||
|
||||
// GetSourceSSECInfo extracts SSE-C information from source object metadata
|
||||
func GetSourceSSECInfo(metadata map[string][]byte) (algorithm string, keyMD5 string, isEncrypted bool) {
|
||||
if alg, exists := metadata[s3_constants.AmzServerSideEncryptionCustomerAlgorithm]; exists {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// ResponseRecorder that also implements http.Flusher
|
||||
type recorderFlusher struct{ *httptest.ResponseRecorder }
|
||||
|
||||
func (r recorderFlusher) Flush() {}
|
||||
|
||||
// TestSSECRangeRequestsSupported verifies that HTTP Range requests are now supported
|
||||
// for SSE-C encrypted objects since the IV is stored in metadata and CTR mode allows seeking
|
||||
func TestSSECRangeRequestsSupported(t *testing.T) {
|
||||
// Create a request with Range header and valid SSE-C headers
|
||||
req := httptest.NewRequest(http.MethodGet, "/b/o", nil)
|
||||
req.Header.Set("Range", "bytes=10-20")
|
||||
req.Header.Set(s3_constants.AmzServerSideEncryptionCustomerAlgorithm, "AES256")
|
||||
|
||||
key := make([]byte, 32)
|
||||
for i := range key {
|
||||
key[i] = byte(i)
|
||||
}
|
||||
s := md5.Sum(key)
|
||||
keyMD5 := base64.StdEncoding.EncodeToString(s[:])
|
||||
|
||||
req.Header.Set(s3_constants.AmzServerSideEncryptionCustomerKey, base64.StdEncoding.EncodeToString(key))
|
||||
req.Header.Set(s3_constants.AmzServerSideEncryptionCustomerKeyMD5, keyMD5)
|
||||
|
||||
// Attach mux vars to avoid panic in error writer
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "b", "object": "o"})
|
||||
|
||||
// Create a mock HTTP response that simulates SSE-C encrypted object metadata
|
||||
proxyResponse := &http.Response{
|
||||
StatusCode: 200,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(bytes.NewReader([]byte("mock encrypted data"))),
|
||||
}
|
||||
proxyResponse.Header.Set(s3_constants.AmzServerSideEncryptionCustomerAlgorithm, "AES256")
|
||||
proxyResponse.Header.Set(s3_constants.AmzServerSideEncryptionCustomerKeyMD5, keyMD5)
|
||||
|
||||
// Call the function under test - should no longer reject range requests
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
w := recorderFlusher{rec}
|
||||
// Pass nil for entry since this test focuses on Range request handling
|
||||
statusCode, _ := s3a.handleSSECResponse(req, proxyResponse, w, nil)
|
||||
|
||||
// Range requests should now be allowed to proceed (will be handled by filer layer)
|
||||
// The exact status code depends on the object existence and filer response
|
||||
if statusCode == http.StatusRequestedRangeNotSatisfiable {
|
||||
t.Fatalf("Range requests should no longer be rejected for SSE-C objects, got status %d", statusCode)
|
||||
}
|
||||
}
|
||||
@@ -331,6 +331,47 @@ func TestDetectPrimarySSETypeS3(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddSSES3HeadersToResponse tests that SSE-S3 headers are added to responses
|
||||
func TestAddSSES3HeadersToResponse(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
|
||||
entry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.AmzServerSideEncryption: []byte("AES256"),
|
||||
},
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{
|
||||
FileId: "1,123",
|
||||
Offset: 0,
|
||||
Size: 1024,
|
||||
SseType: filer_pb.SSEType_SSE_S3,
|
||||
SseMetadata: []byte("metadata"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
proxyResponse := &http.Response{
|
||||
Header: make(http.Header),
|
||||
}
|
||||
|
||||
s3a.addSSEHeadersToResponse(proxyResponse, entry)
|
||||
|
||||
algorithm := proxyResponse.Header.Get(s3_constants.AmzServerSideEncryption)
|
||||
if algorithm != "AES256" {
|
||||
t.Errorf("Expected SSE algorithm AES256, got %s", algorithm)
|
||||
}
|
||||
|
||||
// Should NOT have SSE-C or SSE-KMS specific headers
|
||||
if proxyResponse.Header.Get(s3_constants.AmzServerSideEncryptionCustomerAlgorithm) != "" {
|
||||
t.Error("Should not have SSE-C customer algorithm header")
|
||||
}
|
||||
|
||||
if proxyResponse.Header.Get(s3_constants.AmzServerSideEncryptionAwsKmsKeyId) != "" {
|
||||
t.Error("Should not have SSE-KMS key ID header")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSES3EncryptionWithBaseIV tests multipart encryption with base IV
|
||||
func TestSSES3EncryptionWithBaseIV(t *testing.T) {
|
||||
// Generate SSE-S3 key
|
||||
|
||||
@@ -425,62 +425,44 @@ func (s3a *S3ApiServer) updateBucketConfig(bucket string, updateFn func(*BucketC
|
||||
return errCode
|
||||
}
|
||||
|
||||
nextConfig := cloneBucketConfig(config)
|
||||
if nextConfig == nil {
|
||||
glog.Errorf("updateBucketConfig: failed to clone config for bucket %s", bucket)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// Apply update function
|
||||
if err := updateFn(nextConfig); err != nil {
|
||||
if err := updateFn(config); err != nil {
|
||||
glog.Errorf("updateBucketConfig: update function failed for bucket %s: %v", bucket, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// Prepare extended attributes
|
||||
if nextConfig.Entry == nil {
|
||||
glog.Errorf("updateBucketConfig: missing bucket entry for %s", bucket)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
if nextConfig.Entry.Extended == nil {
|
||||
nextConfig.Entry.Extended = make(map[string][]byte)
|
||||
if config.Entry.Extended == nil {
|
||||
config.Entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
|
||||
// Update extended attributes
|
||||
if nextConfig.Versioning != "" {
|
||||
nextConfig.Entry.Extended[s3_constants.ExtVersioningKey] = []byte(nextConfig.Versioning)
|
||||
} else {
|
||||
delete(nextConfig.Entry.Extended, s3_constants.ExtVersioningKey)
|
||||
if config.Versioning != "" {
|
||||
config.Entry.Extended[s3_constants.ExtVersioningKey] = []byte(config.Versioning)
|
||||
}
|
||||
if nextConfig.Ownership != "" {
|
||||
nextConfig.Entry.Extended[s3_constants.ExtOwnershipKey] = []byte(nextConfig.Ownership)
|
||||
} else {
|
||||
delete(nextConfig.Entry.Extended, s3_constants.ExtOwnershipKey)
|
||||
if config.Ownership != "" {
|
||||
config.Entry.Extended[s3_constants.ExtOwnershipKey] = []byte(config.Ownership)
|
||||
}
|
||||
if nextConfig.ACL != nil {
|
||||
nextConfig.Entry.Extended[s3_constants.ExtAmzAclKey] = nextConfig.ACL
|
||||
} else {
|
||||
delete(nextConfig.Entry.Extended, s3_constants.ExtAmzAclKey)
|
||||
if config.ACL != nil {
|
||||
config.Entry.Extended[s3_constants.ExtAmzAclKey] = config.ACL
|
||||
}
|
||||
if nextConfig.Owner != "" {
|
||||
nextConfig.Entry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(nextConfig.Owner)
|
||||
} else {
|
||||
delete(nextConfig.Entry.Extended, s3_constants.ExtAmzOwnerKey)
|
||||
if config.Owner != "" {
|
||||
config.Entry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(config.Owner)
|
||||
}
|
||||
// Update Object Lock configuration
|
||||
if nextConfig.ObjectLockConfig != nil {
|
||||
glog.V(3).Infof("updateBucketConfig: storing Object Lock config for bucket %s: %+v", bucket, nextConfig.ObjectLockConfig)
|
||||
if err := StoreObjectLockConfigurationInExtended(nextConfig.Entry, nextConfig.ObjectLockConfig); err != nil {
|
||||
if config.ObjectLockConfig != nil {
|
||||
glog.V(3).Infof("updateBucketConfig: storing Object Lock config for bucket %s: %+v", bucket, config.ObjectLockConfig)
|
||||
if err := StoreObjectLockConfigurationInExtended(config.Entry, config.ObjectLockConfig); err != nil {
|
||||
glog.Errorf("updateBucketConfig: failed to store Object Lock configuration for bucket %s: %v", bucket, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
glog.V(3).Infof("updateBucketConfig: stored Object Lock config in extended attributes for bucket %s, key=%s, value=%s",
|
||||
bucket, s3_constants.ExtObjectLockEnabledKey, string(nextConfig.Entry.Extended[s3_constants.ExtObjectLockEnabledKey]))
|
||||
bucket, s3_constants.ExtObjectLockEnabledKey, string(config.Entry.Extended[s3_constants.ExtObjectLockEnabledKey]))
|
||||
}
|
||||
|
||||
// Save to filer
|
||||
glog.V(3).Infof("updateBucketConfig: saving entry to filer for bucket %s", bucket)
|
||||
err := s3a.updateEntry(s3a.bucketRoot(bucket), nextConfig.Entry)
|
||||
err := s3a.updateEntry(s3a.bucketRoot(bucket), config.Entry)
|
||||
if err != nil {
|
||||
glog.Errorf("updateBucketConfig: failed to update bucket entry for %s: %v", bucket, err)
|
||||
return s3err.ErrInternalError
|
||||
@@ -488,140 +470,11 @@ func (s3a *S3ApiServer) updateBucketConfig(bucket string, updateFn func(*BucketC
|
||||
glog.V(3).Infof("updateBucketConfig: saved entry to filer for bucket %s", bucket)
|
||||
|
||||
// Update cache
|
||||
s3a.bucketConfigCache.Set(bucket, nextConfig)
|
||||
s3a.bucketConfigCache.Set(bucket, config)
|
||||
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
func cloneBucketConfig(config *BucketConfig) *BucketConfig {
|
||||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
cloned := *config
|
||||
if config.ACL != nil {
|
||||
cloned.ACL = append([]byte(nil), config.ACL...)
|
||||
}
|
||||
if config.Entry != nil {
|
||||
cloned.Entry = proto.Clone(config.Entry).(*filer_pb.Entry)
|
||||
}
|
||||
if config.CORS != nil {
|
||||
cloned.CORS = cloneCORSConfiguration(config.CORS)
|
||||
}
|
||||
if config.ObjectLockConfig != nil {
|
||||
cloned.ObjectLockConfig = cloneObjectLockConfiguration(config.ObjectLockConfig)
|
||||
}
|
||||
if config.BucketPolicy != nil {
|
||||
cloned.BucketPolicy = cloneBucketPolicy(config.BucketPolicy)
|
||||
}
|
||||
|
||||
return &cloned
|
||||
}
|
||||
|
||||
func cloneCORSConfiguration(config *cors.CORSConfiguration) *cors.CORSConfiguration {
|
||||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
cloned := &cors.CORSConfiguration{
|
||||
CORSRules: make([]cors.CORSRule, len(config.CORSRules)),
|
||||
}
|
||||
for i, rule := range config.CORSRules {
|
||||
cloned.CORSRules[i] = cors.CORSRule{
|
||||
AllowedHeaders: append([]string(nil), rule.AllowedHeaders...),
|
||||
AllowedMethods: append([]string(nil), rule.AllowedMethods...),
|
||||
AllowedOrigins: append([]string(nil), rule.AllowedOrigins...),
|
||||
ExposeHeaders: append([]string(nil), rule.ExposeHeaders...),
|
||||
ID: rule.ID,
|
||||
}
|
||||
if rule.MaxAgeSeconds != nil {
|
||||
maxAge := *rule.MaxAgeSeconds
|
||||
cloned.CORSRules[i].MaxAgeSeconds = &maxAge
|
||||
}
|
||||
}
|
||||
|
||||
return cloned
|
||||
}
|
||||
|
||||
func cloneObjectLockConfiguration(config *ObjectLockConfiguration) *ObjectLockConfiguration {
|
||||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
cloned := &ObjectLockConfiguration{
|
||||
XMLNS: config.XMLNS,
|
||||
XMLName: config.XMLName,
|
||||
ObjectLockEnabled: config.ObjectLockEnabled,
|
||||
}
|
||||
if config.Rule != nil {
|
||||
cloned.Rule = &ObjectLockRule{
|
||||
XMLName: config.Rule.XMLName,
|
||||
}
|
||||
if config.Rule.DefaultRetention != nil {
|
||||
cloned.Rule.DefaultRetention = &DefaultRetention{
|
||||
XMLName: config.Rule.DefaultRetention.XMLName,
|
||||
Mode: config.Rule.DefaultRetention.Mode,
|
||||
Days: config.Rule.DefaultRetention.Days,
|
||||
Years: config.Rule.DefaultRetention.Years,
|
||||
DaysSet: config.Rule.DefaultRetention.DaysSet,
|
||||
YearsSet: config.Rule.DefaultRetention.YearsSet,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cloned
|
||||
}
|
||||
|
||||
func cloneBucketPolicy(policyDoc *policy_engine.PolicyDocument) *policy_engine.PolicyDocument {
|
||||
if policyDoc == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
cloned := &policy_engine.PolicyDocument{
|
||||
Version: policyDoc.Version,
|
||||
Statement: make([]policy_engine.PolicyStatement, len(policyDoc.Statement)),
|
||||
}
|
||||
for i, statement := range policyDoc.Statement {
|
||||
cloned.Statement[i] = clonePolicyStatement(statement)
|
||||
}
|
||||
|
||||
return cloned
|
||||
}
|
||||
|
||||
func clonePolicyStatement(statement policy_engine.PolicyStatement) policy_engine.PolicyStatement {
|
||||
cloned := policy_engine.PolicyStatement{
|
||||
Sid: statement.Sid,
|
||||
Effect: statement.Effect,
|
||||
Action: cloneStringOrStringSlice(statement.Action),
|
||||
NotResource: cloneStringOrStringSlicePtr(statement.NotResource),
|
||||
Principal: cloneStringOrStringSlicePtr(statement.Principal),
|
||||
Resource: cloneStringOrStringSlicePtr(statement.Resource),
|
||||
}
|
||||
if statement.Condition != nil {
|
||||
cloned.Condition = make(policy_engine.PolicyConditions, len(statement.Condition))
|
||||
for operator, operands := range statement.Condition {
|
||||
copiedOperands := make(map[string]policy_engine.StringOrStringSlice, len(operands))
|
||||
for key, value := range operands {
|
||||
copiedOperands[key] = cloneStringOrStringSlice(value)
|
||||
}
|
||||
cloned.Condition[operator] = copiedOperands
|
||||
}
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
func cloneStringOrStringSlice(value policy_engine.StringOrStringSlice) policy_engine.StringOrStringSlice {
|
||||
return policy_engine.CloneStringOrStringSlice(value)
|
||||
}
|
||||
|
||||
func cloneStringOrStringSlicePtr(value *policy_engine.StringOrStringSlice) *policy_engine.StringOrStringSlice {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := policy_engine.CloneStringOrStringSlice(*value)
|
||||
return &cloned
|
||||
}
|
||||
|
||||
// isVersioningEnabled checks if versioning is enabled for a bucket (with caching)
|
||||
func (s3a *S3ApiServer) isVersioningEnabled(bucket string) (bool, error) {
|
||||
config, errCode := s3a.getBucketConfig(bucket)
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestUpdateBucketConfigDoesNotMutateCacheOnPersistFailure(t *testing.T) {
|
||||
const bucket = "cleanup-test-net"
|
||||
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, nil)
|
||||
s3a.option = &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
}
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{
|
||||
Name: bucket,
|
||||
Versioning: "",
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: bucket,
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{},
|
||||
},
|
||||
})
|
||||
|
||||
// This test server only has in-memory IAM state and no filer connection, so
|
||||
// updateBucketConfig is expected to fail during the persist step with an
|
||||
// internal error. The assertion below verifies that the cached config stays
|
||||
// unchanged when that write path fails.
|
||||
errCode := s3a.updateBucketConfig(bucket, func(config *BucketConfig) error {
|
||||
config.Versioning = s3_constants.VersioningEnabled
|
||||
return nil
|
||||
})
|
||||
|
||||
require.Equal(t, s3err.ErrInternalError, errCode)
|
||||
|
||||
config, found := s3a.bucketConfigCache.Get(bucket)
|
||||
require.True(t, found)
|
||||
assert.Empty(t, config.Versioning)
|
||||
assert.NotContains(t, config.Entry.Extended, s3_constants.ExtVersioningKey)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -816,14 +815,6 @@ func (s3a *S3ApiServer) GetBucketLifecycleConfigurationHandler(w http.ResponseWr
|
||||
s3err.WriteErrorResponse(w, r, err)
|
||||
return
|
||||
}
|
||||
if lifecycleXML, transitionMinimumObjectSize, found, errCode := s3a.getStoredBucketLifecycleConfiguration(bucket); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
} else if found {
|
||||
w.Header().Set(bucketLifecycleTransitionMinimumObjectSizeHeader, transitionMinimumObjectSize)
|
||||
writeSuccessResponseXMLBytes(w, r, lifecycleXML)
|
||||
return
|
||||
}
|
||||
// ReadFilerConfFromFilers provides multi-filer failover
|
||||
fc, err := filer.ReadFilerConfFromFilers(s3a.option.Filers, s3a.option.GrpcDialOption, nil)
|
||||
if err != nil {
|
||||
@@ -864,9 +855,6 @@ func (s3a *S3ApiServer) GetBucketLifecycleConfigurationHandler(w http.ResponseWr
|
||||
})
|
||||
}
|
||||
|
||||
if len(response.Rules) > 0 {
|
||||
w.Header().Set(bucketLifecycleTransitionMinimumObjectSizeHeader, defaultLifecycleTransitionMinimumObjectSize)
|
||||
}
|
||||
writeSuccessResponseXML(w, r, response)
|
||||
}
|
||||
|
||||
@@ -904,21 +892,8 @@ func (s3a *S3ApiServer) PutBucketLifecycleConfigurationHandler(w http.ResponseWr
|
||||
return
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBucketLifecycleConfigurationSize)
|
||||
lifecycleXML, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
glog.Warningf("PutBucketLifecycleConfigurationHandler read body: %s", err)
|
||||
var maxBytesErr *http.MaxBytesError
|
||||
if errors.As(err, &maxBytesErr) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrEntityTooLarge)
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
|
||||
lifeCycleConfig := Lifecycle{}
|
||||
if err := xmlDecoder(bytes.NewReader(lifecycleXML), &lifeCycleConfig, int64(len(lifecycleXML))); err != nil {
|
||||
if err := xmlDecoder(r.Body, &lifeCycleConfig, r.ContentLength); err != nil {
|
||||
glog.Warningf("PutBucketLifecycleConfigurationHandler xml decode: %s", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
|
||||
return
|
||||
@@ -952,67 +927,24 @@ func (s3a *S3ApiServer) PutBucketLifecycleConfigurationHandler(w http.ResponseWr
|
||||
collectionTtls := fc.GetCollectionTtls(collectionName)
|
||||
changed := false
|
||||
|
||||
// Check whether the bucket has versioning enabled. Versioned buckets must
|
||||
// NOT use the TTL fast-path because:
|
||||
// 1. TTL volumes expire as a unit, destroying all data — including
|
||||
// noncurrent versions that should be preserved.
|
||||
// 2. Filer-backend TTL (RocksDB compaction, Redis expire) removes entries
|
||||
// without triggering chunk deletion, leaving orphaned volume data.
|
||||
// 3. On AWS S3, Expiration.Days on a versioned bucket creates a delete
|
||||
// marker — it does not delete data. TTL has no such nuance.
|
||||
// For versioned buckets the lifecycle worker handles all rule evaluation
|
||||
// at scan time, which correctly operates on individual versions.
|
||||
bucketVersioning, versioningErr := s3a.getBucketVersioningStatus(bucket)
|
||||
if versioningErr != s3err.ErrNone {
|
||||
// Fail closed: if we cannot determine versioning status, treat the
|
||||
// bucket as versioned to avoid creating TTL entries that would
|
||||
// destroy noncurrent versions.
|
||||
glog.V(1).Infof("PutBucketLifecycleConfigurationHandler: could not determine versioning status for %s (err %v), skipping TTL fast-path", bucket, versioningErr)
|
||||
}
|
||||
isVersioned := versioningErr != s3err.ErrNone ||
|
||||
bucketVersioning == s3_constants.VersioningEnabled ||
|
||||
bucketVersioning == s3_constants.VersioningSuspended
|
||||
|
||||
for _, rule := range lifeCycleConfig.Rules {
|
||||
if rule.Status != Enabled {
|
||||
continue
|
||||
}
|
||||
// Reject Transition rules — they require storage class migration
|
||||
// infrastructure that does not exist yet.
|
||||
if rule.Transition.set || rule.NoncurrentVersionTransition.set {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
if isVersioned {
|
||||
continue // all rules evaluated by lifecycle worker at scan time
|
||||
}
|
||||
|
||||
var rulePrefix string
|
||||
switch {
|
||||
case rule.Filter.andSet:
|
||||
rulePrefix = rule.Filter.And.Prefix.val
|
||||
case rule.Filter.Prefix.set:
|
||||
rulePrefix = rule.Filter.Prefix.val
|
||||
case rule.Prefix.set:
|
||||
rulePrefix = rule.Prefix.val
|
||||
case !rule.Expiration.Date.IsZero() || rule.Transition.Days > 0 || !rule.Transition.Date.IsZero():
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
// Only create filer.conf TTL entries for simple Expiration.Days rules
|
||||
// with prefix-only filters (the fast path handled by RocksDB compaction
|
||||
// filter). Rules with tag or size filters must be evaluated at scan time
|
||||
// by the lifecycle worker, because TTL applies to all objects under the
|
||||
// prefix regardless of tags or size.
|
||||
if rule.Expiration.Days == 0 {
|
||||
continue
|
||||
}
|
||||
hasTagOrSizeFilter := rule.Filter.tagSet ||
|
||||
rule.Filter.ObjectSizeGreaterThan > 0 || rule.Filter.ObjectSizeLessThan > 0 ||
|
||||
(rule.Filter.andSet && (len(rule.Filter.And.Tags) > 0 ||
|
||||
rule.Filter.And.ObjectSizeGreaterThan > 0 || rule.Filter.And.ObjectSizeLessThan > 0))
|
||||
if hasTagOrSizeFilter {
|
||||
continue // evaluated by lifecycle worker at scan time
|
||||
}
|
||||
locationPrefix := fmt.Sprintf("%s/%s/%s", s3a.option.BucketsPath, bucket, rulePrefix)
|
||||
locConf := &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: locationPrefix,
|
||||
@@ -1056,11 +988,6 @@ func (s3a *S3ApiServer) PutBucketLifecycleConfigurationHandler(w http.ResponseWr
|
||||
}
|
||||
}
|
||||
|
||||
if errCode := s3a.storeBucketLifecycleConfiguration(bucket, lifecycleXML, r.Header.Get(bucketLifecycleTransitionMinimumObjectSizeHeader)); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccessResponseEmpty(w, r)
|
||||
}
|
||||
|
||||
@@ -1111,11 +1038,6 @@ func (s3a *S3ApiServer) DeleteBucketLifecycleHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
}
|
||||
|
||||
if errCode := s3a.clearStoredBucketLifecycleConfiguration(bucket); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
s3err.WriteEmptyResponse(w, r, http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
const (
|
||||
bucketLifecycleConfigurationXMLKey = "s3-bucket-lifecycle-configuration-xml"
|
||||
bucketLifecycleTransitionMinimumObjectSizeKey = "s3-bucket-lifecycle-transition-default-minimum-object-size"
|
||||
bucketLifecycleTransitionMinimumObjectSizeHeader = "X-Amz-Transition-Default-Minimum-Object-Size"
|
||||
defaultLifecycleTransitionMinimumObjectSize = "all_storage_classes_128K"
|
||||
maxBucketLifecycleConfigurationSize = 1 << 20
|
||||
)
|
||||
|
||||
func normalizeBucketLifecycleTransitionMinimumObjectSize(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return defaultLifecycleTransitionMinimumObjectSize
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) getStoredBucketLifecycleConfiguration(bucket string) ([]byte, string, bool, s3err.ErrorCode) {
|
||||
config, errCode := s3a.getBucketConfig(bucket)
|
||||
if errCode != s3err.ErrNone {
|
||||
return nil, "", false, errCode
|
||||
}
|
||||
if config.Entry == nil || config.Entry.Extended == nil {
|
||||
return nil, "", false, s3err.ErrNone
|
||||
}
|
||||
|
||||
lifecycleXML, found := config.Entry.Extended[bucketLifecycleConfigurationXMLKey]
|
||||
if !found || len(lifecycleXML) == 0 {
|
||||
return nil, "", false, s3err.ErrNone
|
||||
}
|
||||
|
||||
transitionMinimumObjectSize := normalizeBucketLifecycleTransitionMinimumObjectSize(
|
||||
string(config.Entry.Extended[bucketLifecycleTransitionMinimumObjectSizeKey]),
|
||||
)
|
||||
|
||||
return append([]byte(nil), lifecycleXML...), transitionMinimumObjectSize, true, s3err.ErrNone
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) storeBucketLifecycleConfiguration(bucket string, lifecycleXML []byte, transitionMinimumObjectSize string) s3err.ErrorCode {
|
||||
return s3a.updateBucketConfig(bucket, func(config *BucketConfig) error {
|
||||
if config.Entry == nil {
|
||||
return fmt.Errorf("bucket %s is missing its filer entry", bucket)
|
||||
}
|
||||
if config.Entry.Extended == nil {
|
||||
config.Entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
|
||||
config.Entry.Extended[bucketLifecycleConfigurationXMLKey] = append([]byte(nil), lifecycleXML...)
|
||||
config.Entry.Extended[bucketLifecycleTransitionMinimumObjectSizeKey] = []byte(
|
||||
normalizeBucketLifecycleTransitionMinimumObjectSize(transitionMinimumObjectSize),
|
||||
)
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) clearStoredBucketLifecycleConfiguration(bucket string) s3err.ErrorCode {
|
||||
return s3a.updateBucketConfig(bucket, func(config *BucketConfig) error {
|
||||
if config.Entry == nil {
|
||||
return fmt.Errorf("bucket %s is missing its filer entry", bucket)
|
||||
}
|
||||
|
||||
delete(config.Entry.Extended, bucketLifecycleConfigurationXMLKey)
|
||||
delete(config.Entry.Extended, bucketLifecycleTransitionMinimumObjectSizeKey)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetBucketLifecycleConfigurationHandlerUsesStoredLifecycleConfig(t *testing.T) {
|
||||
const bucket = "cleanup-test-net"
|
||||
const lifecycleXML = `<?xml version="1.0" encoding="UTF-8"?><LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><Filter></Filter><ID>rotation</ID><Expiration><Days>1</Days></Expiration><Status>Enabled</Status></Rule></LifecycleConfiguration>`
|
||||
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, nil)
|
||||
s3a.option = &S3ApiServerOption{BucketsPath: "/buckets"}
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{
|
||||
Name: bucket,
|
||||
Entry: &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
bucketLifecycleConfigurationXMLKey: []byte(lifecycleXML),
|
||||
bucketLifecycleTransitionMinimumObjectSizeKey: []byte("varies_by_storage_class"),
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"?lifecycle", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
resp := httptest.NewRecorder()
|
||||
|
||||
s3a.GetBucketLifecycleConfigurationHandler(resp, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
assert.Equal(t, "varies_by_storage_class", resp.Header().Get(bucketLifecycleTransitionMinimumObjectSizeHeader))
|
||||
assert.Equal(t, lifecycleXML, resp.Body.String())
|
||||
}
|
||||
|
||||
func TestGetBucketLifecycleConfigurationHandlerDefaultsTransitionMinimumObjectSize(t *testing.T) {
|
||||
const bucket = "cleanup-test-net"
|
||||
const lifecycleXML = `<?xml version="1.0" encoding="UTF-8"?><LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><Filter></Filter><ID>rotation</ID><Expiration><Days>1</Days></Expiration><Status>Enabled</Status></Rule></LifecycleConfiguration>`
|
||||
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, nil)
|
||||
s3a.option = &S3ApiServerOption{BucketsPath: "/buckets"}
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{
|
||||
Name: bucket,
|
||||
Entry: &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
bucketLifecycleConfigurationXMLKey: []byte(lifecycleXML),
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"?lifecycle", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
resp := httptest.NewRecorder()
|
||||
|
||||
s3a.GetBucketLifecycleConfigurationHandler(resp, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
assert.Equal(t, defaultLifecycleTransitionMinimumObjectSize, resp.Header().Get(bucketLifecycleTransitionMinimumObjectSizeHeader))
|
||||
assert.Equal(t, lifecycleXML, resp.Body.String())
|
||||
}
|
||||
|
||||
func TestPutBucketLifecycleConfigurationHandlerRejectsOversizedBody(t *testing.T) {
|
||||
const bucket = "cleanup-test-net"
|
||||
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, nil)
|
||||
s3a.option = &S3ApiServerOption{BucketsPath: "/buckets"}
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{
|
||||
Name: bucket,
|
||||
Entry: &filer_pb.Entry{},
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/"+bucket+"?lifecycle", strings.NewReader(strings.Repeat("x", maxBucketLifecycleConfigurationSize+1)))
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
resp := httptest.NewRecorder()
|
||||
|
||||
s3a.PutBucketLifecycleConfigurationHandler(resp, req)
|
||||
|
||||
require.Equal(t, s3err.GetAPIError(s3err.ErrEntityTooLarge).HTTPStatusCode, resp.Code)
|
||||
assert.Contains(t, resp.Body.String(), "<Code>EntityTooLarge</Code>")
|
||||
}
|
||||
|
||||
func TestPutBucketLifecycleConfigurationHandlerMapsReadErrorsToInvalidRequest(t *testing.T) {
|
||||
const bucket = "cleanup-test-net"
|
||||
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, nil)
|
||||
s3a.option = &S3ApiServerOption{BucketsPath: "/buckets"}
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{
|
||||
Name: bucket,
|
||||
Entry: &filer_pb.Entry{},
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/"+bucket+"?lifecycle", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
req.Body = failingReadCloser{err: errors.New("read failed")}
|
||||
resp := httptest.NewRecorder()
|
||||
|
||||
s3a.PutBucketLifecycleConfigurationHandler(resp, req)
|
||||
|
||||
require.Equal(t, s3err.GetAPIError(s3err.ErrInvalidRequest).HTTPStatusCode, resp.Code)
|
||||
assert.Contains(t, resp.Body.String(), "<Code>InvalidRequest</Code>")
|
||||
}
|
||||
|
||||
type failingReadCloser struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (f failingReadCloser) Read(_ []byte) (int, error) {
|
||||
return 0, f.err
|
||||
}
|
||||
|
||||
func (f failingReadCloser) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestShouldSkipTTLFastPathForVersionedBuckets verifies the versioning guard
|
||||
// logic that PutBucketLifecycleConfigurationHandler uses to decide whether
|
||||
// to create filer.conf TTL entries. On AWS S3, Expiration.Days on a versioned
|
||||
// bucket creates a delete marker — it does not delete data. TTL volumes
|
||||
// would destroy all versions indiscriminately, so the lifecycle worker must
|
||||
// handle versioned buckets at scan time instead. (issue #8757)
|
||||
//
|
||||
// Note: an integration test that invokes PutBucketLifecycleConfigurationHandler
|
||||
// directly is not feasible here because the handler requires filer gRPC
|
||||
// connectivity (ReadFilerConfFromFilers, WithFilerClient) before it reaches
|
||||
// the versioning check. The lifecycle worker integration tests in
|
||||
// weed/plugin/worker/lifecycle/ cover the end-to-end versioned-bucket behavior.
|
||||
func TestShouldSkipTTLFastPathForVersionedBuckets(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
versioning string
|
||||
expectSkip bool
|
||||
}{
|
||||
{"versioning_enabled_skips_ttl", s3_constants.VersioningEnabled, true},
|
||||
{"versioning_suspended_skips_ttl", s3_constants.VersioningSuspended, true},
|
||||
{"unversioned_allows_ttl", "", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// This mirrors the guard in PutBucketLifecycleConfigurationHandler:
|
||||
// isVersioned := versioningErr != s3err.ErrNone ||
|
||||
// bucketVersioning == s3_constants.VersioningEnabled ||
|
||||
// bucketVersioning == s3_constants.VersioningSuspended
|
||||
// When isVersioned is true, the TTL fast-path is skipped entirely.
|
||||
isVersioned := tt.versioning == s3_constants.VersioningEnabled ||
|
||||
tt.versioning == s3_constants.VersioningSuspended
|
||||
assert.Equal(t, tt.expectSkip, isVersioned)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,6 @@ import (
|
||||
// BucketPolicyEngine wraps the policy_engine to provide bucket policy evaluation
|
||||
type BucketPolicyEngine struct {
|
||||
engine *policy_engine.PolicyEngine
|
||||
// MultipartSSELookup retrieves the canonical SSE algorithm ("AES256" or
|
||||
// "aws:kms") that was stored when a multipart upload was initiated.
|
||||
// Returns "" when the upload had no SSE or when the entry cannot be found.
|
||||
// Set by S3ApiServer after construction to give the engine filer access.
|
||||
MultipartSSELookup func(bucket, uploadID string) string
|
||||
}
|
||||
|
||||
// NewBucketPolicyEngine creates a new bucket policy engine
|
||||
@@ -161,16 +156,6 @@ func (bpe *BucketPolicyEngine) EvaluatePolicy(bucket, object, action, principal
|
||||
// But the caller is responsible for passing them.
|
||||
// Falling back to empty claims if not provided.
|
||||
}
|
||||
|
||||
// For multipart continuation actions look up the SSE algorithm that was
|
||||
// set at CreateMultipartUpload time. UploadPart/UploadPartCopy do not
|
||||
// re-send the SSE header, so we inject the stored value so that bucket
|
||||
// policy conditions on s3:x-amz-server-side-encryption evaluate correctly.
|
||||
if policy_engine.IsMultipartContinuationAction(s3Action) && bpe.MultipartSSELookup != nil {
|
||||
if uploadID := r.URL.Query().Get("uploadId"); uploadID != "" {
|
||||
args.InheritedSSEAlgorithm = bpe.MultipartSSELookup(bucket, uploadID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result := bpe.engine.EvaluatePolicy(bucket, args)
|
||||
|
||||
@@ -778,7 +778,6 @@ func NewS3ApiServerForTest() *S3ApiServer {
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
bucketConfigCache: NewBucketConfigCache(60 * time.Minute),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -929,56 +928,3 @@ func TestConditionalHeadersMultipartUpload(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestConditionalHeadersTreatDeleteMarkerAsMissing(t *testing.T) {
|
||||
bucket := "test-bucket"
|
||||
object := "/deleted-object"
|
||||
deleteMarkerEntry := &filer_pb.Entry{
|
||||
Name: "deleted-object",
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtDeleteMarkerKey: []byte("true"),
|
||||
},
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC).Unix(),
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("WriteIfNoneMatchAsteriskSucceeds", func(t *testing.T) {
|
||||
getter := createMockEntryGetter(deleteMarkerEntry)
|
||||
req := createTestPutRequest(bucket, object, "new content")
|
||||
req.Header.Set(s3_constants.IfNoneMatch, "*")
|
||||
|
||||
s3a := NewS3ApiServerForTest()
|
||||
errCode := s3a.checkConditionalHeadersWithGetter(getter, req, bucket, object)
|
||||
if errCode != s3err.ErrNone {
|
||||
t.Fatalf("expected ErrNone for delete marker with If-None-Match=*, got %v", errCode)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("WriteIfMatchAsteriskFails", func(t *testing.T) {
|
||||
getter := createMockEntryGetter(deleteMarkerEntry)
|
||||
req := createTestPutRequest(bucket, object, "new content")
|
||||
req.Header.Set(s3_constants.IfMatch, "*")
|
||||
|
||||
s3a := NewS3ApiServerForTest()
|
||||
errCode := s3a.checkConditionalHeadersWithGetter(getter, req, bucket, object)
|
||||
if errCode != s3err.ErrPreconditionFailed {
|
||||
t.Fatalf("expected ErrPreconditionFailed for delete marker with If-Match=*, got %v", errCode)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ReadIfMatchAsteriskFails", func(t *testing.T) {
|
||||
getter := createMockEntryGetter(deleteMarkerEntry)
|
||||
req := &http.Request{Method: http.MethodGet, Header: make(http.Header)}
|
||||
req.Header.Set(s3_constants.IfMatch, "*")
|
||||
|
||||
s3a := NewS3ApiServerForTest()
|
||||
result := s3a.checkConditionalHeadersForReadsWithGetter(getter, req, bucket, object)
|
||||
if result.ErrorCode != s3err.ErrPreconditionFailed {
|
||||
t.Fatalf("expected ErrPreconditionFailed for read against delete marker with If-Match=*, got %v", result.ErrorCode)
|
||||
}
|
||||
if result.Entry != nil {
|
||||
t.Fatalf("expected no entry to be returned for delete marker, got %#v", result.Entry)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -100,11 +100,6 @@ func writeSuccessResponseXML(w http.ResponseWriter, r *http.Request, response in
|
||||
s3err.PostLog(r, http.StatusOK, s3err.ErrNone)
|
||||
}
|
||||
|
||||
func writeSuccessResponseXMLBytes(w http.ResponseWriter, r *http.Request, response []byte) {
|
||||
s3err.WriteResponse(w, r, http.StatusOK, response, s3err.MimeXML)
|
||||
s3err.PostLog(r, http.StatusOK, s3err.ErrNone)
|
||||
}
|
||||
|
||||
func writeSuccessResponseEmpty(w http.ResponseWriter, r *http.Request) {
|
||||
s3err.WriteEmptyResponse(w, r, http.StatusOK)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,275 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// rotateSSECKey handles SSE-C key rotation for same-object copies
|
||||
func (s3a *S3ApiServer) rotateSSECKey(entry *filer_pb.Entry, r *http.Request) ([]*filer_pb.FileChunk, error) {
|
||||
// Parse source and destination SSE-C keys
|
||||
sourceKey, err := ParseSSECCopySourceHeaders(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse SSE-C copy source headers: %w", err)
|
||||
}
|
||||
|
||||
destKey, err := ParseSSECHeaders(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse SSE-C destination headers: %w", err)
|
||||
}
|
||||
|
||||
// Validate that we have both keys
|
||||
if sourceKey == nil {
|
||||
return nil, fmt.Errorf("source SSE-C key required for key rotation")
|
||||
}
|
||||
|
||||
if destKey == nil {
|
||||
return nil, fmt.Errorf("destination SSE-C key required for key rotation")
|
||||
}
|
||||
|
||||
// Check if keys are actually different
|
||||
if sourceKey.KeyMD5 == destKey.KeyMD5 {
|
||||
glog.V(2).Infof("SSE-C key rotation: keys are identical, using direct copy")
|
||||
return entry.GetChunks(), nil
|
||||
}
|
||||
|
||||
glog.V(2).Infof("SSE-C key rotation: rotating from key %s to key %s",
|
||||
sourceKey.KeyMD5[:8], destKey.KeyMD5[:8])
|
||||
|
||||
// For SSE-C key rotation, we need to re-encrypt all chunks
|
||||
// This cannot be a metadata-only operation because the encryption key changes
|
||||
return s3a.rotateSSECChunks(entry, sourceKey, destKey)
|
||||
}
|
||||
|
||||
// rotateSSEKMSKey handles SSE-KMS key rotation for same-object copies
|
||||
func (s3a *S3ApiServer) rotateSSEKMSKey(entry *filer_pb.Entry, r *http.Request) ([]*filer_pb.FileChunk, error) {
|
||||
// Get source and destination key IDs
|
||||
srcKeyID, srcEncrypted := GetSourceSSEKMSInfo(entry.Extended)
|
||||
if !srcEncrypted {
|
||||
return nil, fmt.Errorf("source object is not SSE-KMS encrypted")
|
||||
}
|
||||
|
||||
dstKeyID := r.Header.Get(s3_constants.AmzServerSideEncryptionAwsKmsKeyId)
|
||||
if dstKeyID == "" {
|
||||
// Use default key if not specified
|
||||
dstKeyID = "default"
|
||||
}
|
||||
|
||||
// Check if keys are actually different
|
||||
if srcKeyID == dstKeyID {
|
||||
glog.V(2).Infof("SSE-KMS key rotation: keys are identical, using direct copy")
|
||||
return entry.GetChunks(), nil
|
||||
}
|
||||
|
||||
glog.V(2).Infof("SSE-KMS key rotation: rotating from key %s to key %s", srcKeyID, dstKeyID)
|
||||
|
||||
// For SSE-KMS, we can potentially do metadata-only rotation
|
||||
// if the KMS service supports key aliasing and the data encryption key can be re-wrapped
|
||||
if s3a.CanDoMetadataOnlyKMSRotation(srcKeyID, dstKeyID) {
|
||||
return s3a.rotateSSEKMSMetadataOnly(entry, srcKeyID, dstKeyID)
|
||||
}
|
||||
|
||||
// Fallback to full re-encryption
|
||||
return s3a.rotateSSEKMSChunks(entry, srcKeyID, dstKeyID, r)
|
||||
}
|
||||
|
||||
// CanDoMetadataOnlyKMSRotation determines if KMS key rotation can be done metadata-only
|
||||
func (s3a *S3ApiServer) CanDoMetadataOnlyKMSRotation(srcKeyID, dstKeyID string) bool {
|
||||
// For now, we'll be conservative and always re-encrypt
|
||||
// In a full implementation, this would check if:
|
||||
// 1. Both keys are in the same KMS instance
|
||||
// 2. The KMS supports key re-wrapping
|
||||
// 3. The user has permissions for both keys
|
||||
return false
|
||||
}
|
||||
|
||||
// rotateSSEKMSMetadataOnly performs metadata-only SSE-KMS key rotation
|
||||
func (s3a *S3ApiServer) rotateSSEKMSMetadataOnly(entry *filer_pb.Entry, srcKeyID, dstKeyID string) ([]*filer_pb.FileChunk, error) {
|
||||
// This would re-wrap the data encryption key with the new KMS key
|
||||
// For now, return an error since we don't support this yet
|
||||
return nil, fmt.Errorf("metadata-only KMS key rotation not yet implemented")
|
||||
}
|
||||
|
||||
// rotateSSECChunks re-encrypts all chunks with new SSE-C key
|
||||
func (s3a *S3ApiServer) rotateSSECChunks(entry *filer_pb.Entry, sourceKey, destKey *SSECustomerKey) ([]*filer_pb.FileChunk, error) {
|
||||
// Get IV from entry metadata
|
||||
iv, err := GetSSECIVFromMetadata(entry.Extended)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get SSE-C IV from metadata: %w", err)
|
||||
}
|
||||
|
||||
var rotatedChunks []*filer_pb.FileChunk
|
||||
|
||||
for _, chunk := range entry.GetChunks() {
|
||||
rotatedChunk, err := s3a.rotateSSECChunk(chunk, sourceKey, destKey, iv)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("rotate SSE-C chunk: %w", err)
|
||||
}
|
||||
rotatedChunks = append(rotatedChunks, rotatedChunk)
|
||||
}
|
||||
|
||||
// Generate new IV for the destination and store it in entry metadata
|
||||
newIV := make([]byte, s3_constants.AESBlockSize)
|
||||
if _, err := io.ReadFull(rand.Reader, newIV); err != nil {
|
||||
return nil, fmt.Errorf("generate new IV: %w", err)
|
||||
}
|
||||
|
||||
// Update entry metadata with new IV and SSE-C headers
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
StoreSSECIVInMetadata(entry.Extended, newIV)
|
||||
entry.Extended[s3_constants.AmzServerSideEncryptionCustomerAlgorithm] = []byte("AES256")
|
||||
entry.Extended[s3_constants.AmzServerSideEncryptionCustomerKeyMD5] = []byte(destKey.KeyMD5)
|
||||
|
||||
return rotatedChunks, nil
|
||||
}
|
||||
|
||||
// rotateSSEKMSChunks re-encrypts all chunks with new SSE-KMS key
|
||||
func (s3a *S3ApiServer) rotateSSEKMSChunks(entry *filer_pb.Entry, srcKeyID, dstKeyID string, r *http.Request) ([]*filer_pb.FileChunk, error) {
|
||||
var rotatedChunks []*filer_pb.FileChunk
|
||||
|
||||
// Parse encryption context and bucket key settings
|
||||
_, encryptionContext, bucketKeyEnabled, err := ParseSSEKMSCopyHeaders(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse SSE-KMS copy headers: %w", err)
|
||||
}
|
||||
|
||||
for _, chunk := range entry.GetChunks() {
|
||||
rotatedChunk, err := s3a.rotateSSEKMSChunk(chunk, srcKeyID, dstKeyID, encryptionContext, bucketKeyEnabled)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("rotate SSE-KMS chunk: %w", err)
|
||||
}
|
||||
rotatedChunks = append(rotatedChunks, rotatedChunk)
|
||||
}
|
||||
|
||||
return rotatedChunks, nil
|
||||
}
|
||||
|
||||
// rotateSSECChunk rotates a single SSE-C encrypted chunk
|
||||
func (s3a *S3ApiServer) rotateSSECChunk(chunk *filer_pb.FileChunk, sourceKey, destKey *SSECustomerKey, iv []byte) (*filer_pb.FileChunk, error) {
|
||||
// Create new chunk with same properties
|
||||
newChunk := &filer_pb.FileChunk{
|
||||
Offset: chunk.Offset,
|
||||
Size: chunk.Size,
|
||||
ModifiedTsNs: chunk.ModifiedTsNs,
|
||||
ETag: chunk.ETag,
|
||||
}
|
||||
|
||||
// Assign new volume for the rotated chunk
|
||||
assignResult, err := s3a.assignNewVolume("")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("assign new volume: %w", err)
|
||||
}
|
||||
|
||||
// Set file ID on new chunk
|
||||
if err := s3a.setChunkFileId(newChunk, assignResult); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get source chunk data
|
||||
fileId := chunk.GetFileIdString()
|
||||
srcUrl, err := s3a.lookupVolumeUrl(fileId)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lookup source volume: %w", err)
|
||||
}
|
||||
|
||||
// Download encrypted data
|
||||
encryptedData, err := s3a.downloadChunkData(srcUrl, fileId, 0, int64(chunk.Size), chunk.CipherKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download chunk data: %w", err)
|
||||
}
|
||||
|
||||
// Decrypt with source key using provided IV
|
||||
decryptedReader, err := CreateSSECDecryptedReader(bytes.NewReader(encryptedData), sourceKey, iv)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create decrypted reader: %w", err)
|
||||
}
|
||||
|
||||
decryptedData, err := io.ReadAll(decryptedReader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt data: %w", err)
|
||||
}
|
||||
|
||||
// Re-encrypt with destination key
|
||||
encryptedReader, _, err := CreateSSECEncryptedReader(bytes.NewReader(decryptedData), destKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create encrypted reader: %w", err)
|
||||
}
|
||||
|
||||
// Note: IV will be handled at the entry level by the calling function
|
||||
|
||||
reencryptedData, err := io.ReadAll(encryptedReader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("re-encrypt data: %w", err)
|
||||
}
|
||||
|
||||
// Update chunk size to include new IV
|
||||
newChunk.Size = uint64(len(reencryptedData))
|
||||
|
||||
// Upload re-encrypted data
|
||||
if err := s3a.uploadChunkData(reencryptedData, assignResult, false); err != nil {
|
||||
return nil, fmt.Errorf("upload re-encrypted data: %w", err)
|
||||
}
|
||||
|
||||
return newChunk, nil
|
||||
}
|
||||
|
||||
// rotateSSEKMSChunk rotates a single SSE-KMS encrypted chunk
|
||||
func (s3a *S3ApiServer) rotateSSEKMSChunk(chunk *filer_pb.FileChunk, srcKeyID, dstKeyID string, encryptionContext map[string]string, bucketKeyEnabled bool) (*filer_pb.FileChunk, error) {
|
||||
// Create new chunk with same properties
|
||||
newChunk := &filer_pb.FileChunk{
|
||||
Offset: chunk.Offset,
|
||||
Size: chunk.Size,
|
||||
ModifiedTsNs: chunk.ModifiedTsNs,
|
||||
ETag: chunk.ETag,
|
||||
}
|
||||
|
||||
// Assign new volume for the rotated chunk
|
||||
assignResult, err := s3a.assignNewVolume("")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("assign new volume: %w", err)
|
||||
}
|
||||
|
||||
// Set file ID on new chunk
|
||||
if err := s3a.setChunkFileId(newChunk, assignResult); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get source chunk data
|
||||
fileId := chunk.GetFileIdString()
|
||||
srcUrl, err := s3a.lookupVolumeUrl(fileId)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lookup source volume: %w", err)
|
||||
}
|
||||
|
||||
// Download data (this would be encrypted with the old KMS key)
|
||||
chunkData, err := s3a.downloadChunkData(srcUrl, fileId, 0, int64(chunk.Size), chunk.CipherKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download chunk data: %w", err)
|
||||
}
|
||||
|
||||
// For now, we'll just re-upload the data as-is
|
||||
// In a full implementation, this would:
|
||||
// 1. Decrypt with old KMS key
|
||||
// 2. Re-encrypt with new KMS key
|
||||
// 3. Update metadata accordingly
|
||||
|
||||
// Upload data with new key (placeholder implementation)
|
||||
if err := s3a.uploadChunkData(chunkData, assignResult, false); err != nil {
|
||||
return nil, fmt.Errorf("upload rotated data: %w", err)
|
||||
}
|
||||
|
||||
return newChunk, nil
|
||||
}
|
||||
|
||||
// IsSameObjectCopy determines if this is a same-object copy operation
|
||||
func IsSameObjectCopy(r *http.Request, srcBucket, srcObject, dstBucket, dstObject string) bool {
|
||||
return srcBucket == dstBucket && srcObject == dstObject
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/mem"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
@@ -243,15 +244,16 @@ func (e *StreamError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// newStreamError creates a StreamError for cases where response hasn't been written yet
|
||||
func newStreamError(err error) *StreamError {
|
||||
return &StreamError{Err: err, ResponseWritten: false}
|
||||
}
|
||||
|
||||
// newStreamErrorWithResponse creates a StreamError for cases where response was already written
|
||||
func newStreamErrorWithResponse(err error) *StreamError {
|
||||
return &StreamError{Err: err, ResponseWritten: true}
|
||||
}
|
||||
|
||||
func shouldWriteStreamingErrorResponse(err error) bool {
|
||||
return err != nil && !errors.Is(err, context.Canceled)
|
||||
}
|
||||
|
||||
func mimeDetect(r *http.Request, dataReader io.Reader) io.ReadCloser {
|
||||
mimeBuffer := make([]byte, 512)
|
||||
size, _ := dataReader.Read(mimeBuffer)
|
||||
@@ -883,15 +885,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
err = s3a.streamFromVolumeServersWithSSE(w, r, objectEntryForSSE, primarySSEType, bucket, object, versionId)
|
||||
streamTime = time.Since(tStream)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
glog.V(3).Infof("GetObjectHandler: client disconnected while streaming %s/%s: %v", bucket, object, err)
|
||||
return
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
glog.Warningf("GetObjectHandler: deadline exceeded while streaming %s/%s: %v", bucket, object, err)
|
||||
default:
|
||||
glog.Errorf("GetObjectHandler: failed to stream %s/%s from volume servers: %v", bucket, object, err)
|
||||
}
|
||||
glog.Errorf("GetObjectHandler: failed to stream %s/%s from volume servers: %v", bucket, object, err)
|
||||
// Check if the streaming function already wrote an HTTP response
|
||||
var streamErr *StreamError
|
||||
if errors.As(err, &streamErr) && streamErr.ResponseWritten {
|
||||
@@ -903,7 +897,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
// Check if error is due to volume server rate limiting (HTTP 429)
|
||||
if errors.Is(err, util_http.ErrTooManyRequests) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrRequestBytesExceed)
|
||||
} else if shouldWriteStreamingErrorResponse(err) {
|
||||
} else {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
}
|
||||
return
|
||||
@@ -1039,15 +1033,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
|
||||
resolvedChunks, _, err := filer.ResolveChunkManifest(ctx, lookupFileIdFn, chunks, offset, offset+size)
|
||||
chunkResolveTime = time.Since(tChunkResolve)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
glog.V(3).Infof("streamFromVolumeServers: request canceled while resolving chunks: %v", err)
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
glog.Warningf("streamFromVolumeServers: request deadline exceeded while resolving chunks: %v", err)
|
||||
} else {
|
||||
glog.Errorf("streamFromVolumeServers: failed to resolve chunks: %v", err)
|
||||
}
|
||||
glog.Errorf("streamFromVolumeServers: failed to resolve chunks: %v", err)
|
||||
// Write S3-compliant XML error response
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return newStreamErrorWithResponse(fmt.Errorf("failed to resolve chunks: %v", err))
|
||||
@@ -1067,15 +1053,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
|
||||
)
|
||||
streamPrepTime = time.Since(tStreamPrep)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
glog.V(3).Infof("streamFromVolumeServers: request canceled while preparing stream: %v", err)
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
glog.Warningf("streamFromVolumeServers: request deadline exceeded while preparing stream: %v", err)
|
||||
} else {
|
||||
glog.Errorf("streamFromVolumeServers: failed to prepare stream: %v", err)
|
||||
}
|
||||
glog.Errorf("streamFromVolumeServers: failed to prepare stream: %v", err)
|
||||
// Write S3-compliant XML error response
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return newStreamErrorWithResponse(fmt.Errorf("failed to prepare stream: %v", err))
|
||||
@@ -2421,6 +2399,45 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func captureCORSHeaders(w http.ResponseWriter, headersToCapture []string) map[string]string {
|
||||
captured := make(map[string]string)
|
||||
for _, corsHeader := range headersToCapture {
|
||||
if value := w.Header().Get(corsHeader); value != "" {
|
||||
captured[corsHeader] = value
|
||||
}
|
||||
}
|
||||
return captured
|
||||
}
|
||||
|
||||
func restoreCORSHeaders(w http.ResponseWriter, capturedCORSHeaders map[string]string) {
|
||||
for corsHeader, value := range capturedCORSHeaders {
|
||||
w.Header().Set(corsHeader, value)
|
||||
}
|
||||
}
|
||||
|
||||
// writeFinalResponse handles the common response writing logic shared between
|
||||
// passThroughResponse and handleSSECResponse
|
||||
func writeFinalResponse(w http.ResponseWriter, proxyResponse *http.Response, bodyReader io.Reader, capturedCORSHeaders map[string]string) (statusCode int, bytesTransferred int64) {
|
||||
// Restore CORS headers that were set by middleware
|
||||
restoreCORSHeaders(w, capturedCORSHeaders)
|
||||
|
||||
if proxyResponse.Header.Get("Content-Range") != "" && proxyResponse.StatusCode == 200 {
|
||||
statusCode = http.StatusPartialContent
|
||||
} else {
|
||||
statusCode = proxyResponse.StatusCode
|
||||
}
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
// Stream response data
|
||||
buf := mem.Allocate(128 * 1024)
|
||||
defer mem.Free(buf)
|
||||
bytesTransferred, err := io.CopyBuffer(w, bodyReader, buf)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("response read %d bytes: %v", bytesTransferred, err)
|
||||
}
|
||||
return statusCode, bytesTransferred
|
||||
}
|
||||
|
||||
// fetchObjectEntry fetches the filer entry for an object
|
||||
// Returns nil if not found (not an error), or propagates other errors
|
||||
func (s3a *S3ApiServer) fetchObjectEntry(bucket, object string) (*filer_pb.Entry, error) {
|
||||
@@ -2446,6 +2463,187 @@ func (s3a *S3ApiServer) fetchObjectEntryRequired(bucket, object string) (*filer_
|
||||
return fetchedEntry, nil
|
||||
}
|
||||
|
||||
// copyResponseHeaders copies headers from proxy response to the response writer,
|
||||
// excluding internal SeaweedFS headers and optionally excluding body-related headers
|
||||
func copyResponseHeaders(w http.ResponseWriter, proxyResponse *http.Response, excludeBodyHeaders bool) {
|
||||
for k, v := range proxyResponse.Header {
|
||||
// Always exclude internal SeaweedFS headers
|
||||
if s3_constants.IsSeaweedFSInternalHeader(k) {
|
||||
continue
|
||||
}
|
||||
// Optionally exclude body-related headers that might change after decryption
|
||||
if excludeBodyHeaders && (k == "Content-Length" || k == "Content-Encoding") {
|
||||
continue
|
||||
}
|
||||
w.Header()[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int, bytesTransferred int64) {
|
||||
// Capture existing CORS headers that may have been set by middleware
|
||||
capturedCORSHeaders := captureCORSHeaders(w, corsHeaders)
|
||||
|
||||
// Copy headers from proxy response (excluding internal SeaweedFS headers)
|
||||
copyResponseHeaders(w, proxyResponse, false)
|
||||
|
||||
return writeFinalResponse(w, proxyResponse, proxyResponse.Body, capturedCORSHeaders)
|
||||
}
|
||||
|
||||
// handleSSECResponse handles SSE-C decryption and response processing
|
||||
func (s3a *S3ApiServer) handleSSECResponse(r *http.Request, proxyResponse *http.Response, w http.ResponseWriter, entry *filer_pb.Entry) (statusCode int, bytesTransferred int64) {
|
||||
// Check if the object has SSE-C metadata
|
||||
sseAlgorithm := proxyResponse.Header.Get(s3_constants.AmzServerSideEncryptionCustomerAlgorithm)
|
||||
sseKeyMD5 := proxyResponse.Header.Get(s3_constants.AmzServerSideEncryptionCustomerKeyMD5)
|
||||
isObjectEncrypted := sseAlgorithm != "" && sseKeyMD5 != ""
|
||||
|
||||
// Parse SSE-C headers from request once (avoid duplication)
|
||||
customerKey, err := ParseSSECHeaders(r)
|
||||
if err != nil {
|
||||
errCode := MapSSECErrorToS3Error(err)
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return http.StatusBadRequest, 0
|
||||
}
|
||||
|
||||
if isObjectEncrypted {
|
||||
// This object was encrypted with SSE-C, validate customer key
|
||||
if customerKey == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrSSECustomerKeyMissing)
|
||||
return http.StatusBadRequest, 0
|
||||
}
|
||||
|
||||
// SSE-C MD5 is base64 and case-sensitive
|
||||
if customerKey.KeyMD5 != sseKeyMD5 {
|
||||
// For GET/HEAD requests, AWS S3 returns 403 Forbidden for a key mismatch.
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return http.StatusForbidden, 0
|
||||
}
|
||||
|
||||
// SSE-C encrypted objects support HTTP Range requests
|
||||
// The IV is stored in metadata and CTR mode allows seeking to any offset
|
||||
// Range requests will be handled by the filer layer with proper offset-based decryption
|
||||
|
||||
// Check if this is a chunked or small content SSE-C object
|
||||
// Use the entry parameter passed from the caller (avoids redundant lookup)
|
||||
if entry != nil {
|
||||
// Check for SSE-C chunks
|
||||
sseCChunks := 0
|
||||
for _, chunk := range entry.GetChunks() {
|
||||
if chunk.GetSseType() == filer_pb.SSEType_SSE_C {
|
||||
sseCChunks++
|
||||
}
|
||||
}
|
||||
|
||||
if sseCChunks >= 1 {
|
||||
|
||||
// Handle chunked SSE-C objects - each chunk needs independent decryption
|
||||
multipartReader, decErr := s3a.createMultipartSSECDecryptedReader(r, proxyResponse, entry)
|
||||
if decErr != nil {
|
||||
glog.Errorf("Failed to create multipart SSE-C decrypted reader: %v", decErr)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return http.StatusInternalServerError, 0
|
||||
}
|
||||
|
||||
// Capture existing CORS headers
|
||||
capturedCORSHeaders := captureCORSHeaders(w, corsHeaders)
|
||||
|
||||
// Copy headers from proxy response (excluding internal SeaweedFS headers)
|
||||
copyResponseHeaders(w, proxyResponse, false)
|
||||
|
||||
// Set proper headers for range requests
|
||||
rangeHeader := r.Header.Get("Range")
|
||||
if rangeHeader != "" {
|
||||
|
||||
// Parse range header (e.g., "bytes=0-99")
|
||||
if len(rangeHeader) > 6 && rangeHeader[:6] == "bytes=" {
|
||||
rangeSpec := rangeHeader[6:]
|
||||
parts := strings.Split(rangeSpec, "-")
|
||||
if len(parts) == 2 {
|
||||
startOffset, endOffset := int64(0), int64(-1)
|
||||
if parts[0] != "" {
|
||||
startOffset, _ = strconv.ParseInt(parts[0], 10, 64)
|
||||
}
|
||||
if parts[1] != "" {
|
||||
endOffset, _ = strconv.ParseInt(parts[1], 10, 64)
|
||||
}
|
||||
|
||||
if endOffset >= startOffset {
|
||||
// Specific range - set proper Content-Length and Content-Range headers
|
||||
rangeLength := endOffset - startOffset + 1
|
||||
totalSize := proxyResponse.Header.Get("Content-Length")
|
||||
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(rangeLength, 10))
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%s", startOffset, endOffset, totalSize))
|
||||
// writeFinalResponse will set status to 206 if Content-Range is present
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return writeFinalResponse(w, proxyResponse, multipartReader, capturedCORSHeaders)
|
||||
} else if len(entry.GetChunks()) == 0 && len(entry.Content) > 0 {
|
||||
// Small content SSE-C object stored directly in entry.Content
|
||||
|
||||
// Fall through to traditional single-object SSE-C handling below
|
||||
}
|
||||
}
|
||||
|
||||
// Single-part SSE-C object: Get IV from proxy response headers (stored during upload)
|
||||
ivBase64 := proxyResponse.Header.Get(s3_constants.SeaweedFSSSEIVHeader)
|
||||
if ivBase64 == "" {
|
||||
glog.Errorf("SSE-C encrypted single-part object missing IV in metadata")
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return http.StatusInternalServerError, 0
|
||||
}
|
||||
|
||||
iv, err := base64.StdEncoding.DecodeString(ivBase64)
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to decode IV from metadata: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return http.StatusInternalServerError, 0
|
||||
}
|
||||
|
||||
// Create decrypted reader with IV from metadata
|
||||
decryptedReader, decErr := CreateSSECDecryptedReader(proxyResponse.Body, customerKey, iv)
|
||||
if decErr != nil {
|
||||
glog.Errorf("Failed to create SSE-C decrypted reader: %v", decErr)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return http.StatusInternalServerError, 0
|
||||
}
|
||||
|
||||
// Capture existing CORS headers that may have been set by middleware
|
||||
capturedCORSHeaders := captureCORSHeaders(w, corsHeaders)
|
||||
|
||||
// Copy headers from proxy response (excluding body-related headers that might change and internal SeaweedFS headers)
|
||||
copyResponseHeaders(w, proxyResponse, true)
|
||||
|
||||
// Set correct Content-Length for SSE-C (only for full object requests)
|
||||
// With IV stored in metadata, the encrypted length equals the original length
|
||||
if proxyResponse.Header.Get("Content-Range") == "" {
|
||||
// Full object request: encrypted length equals original length (IV not in stream)
|
||||
if contentLengthStr := proxyResponse.Header.Get("Content-Length"); contentLengthStr != "" {
|
||||
// Content-Length is already correct since IV is stored in metadata, not in data stream
|
||||
w.Header().Set("Content-Length", contentLengthStr)
|
||||
}
|
||||
}
|
||||
// For range requests, let the actual bytes transferred determine the response length
|
||||
|
||||
// Add SSE-C response headers
|
||||
w.Header().Set(s3_constants.AmzServerSideEncryptionCustomerAlgorithm, sseAlgorithm)
|
||||
w.Header().Set(s3_constants.AmzServerSideEncryptionCustomerKeyMD5, sseKeyMD5)
|
||||
|
||||
return writeFinalResponse(w, proxyResponse, decryptedReader, capturedCORSHeaders)
|
||||
} else {
|
||||
// Object is not encrypted, but check if customer provided SSE-C headers unnecessarily
|
||||
if customerKey != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrSSECustomerKeyNotNeeded)
|
||||
return http.StatusBadRequest, 0
|
||||
}
|
||||
|
||||
// Normal pass-through response
|
||||
return passThroughResponse(proxyResponse, w)
|
||||
}
|
||||
}
|
||||
|
||||
// addObjectLockHeadersToResponse extracts object lock metadata from entry Extended attributes
|
||||
// and adds the appropriate S3 headers to the response
|
||||
func (s3a *S3ApiServer) addObjectLockHeadersToResponse(w http.ResponseWriter, entry *filer_pb.Entry) {
|
||||
@@ -2487,6 +2685,54 @@ func (s3a *S3ApiServer) addObjectLockHeadersToResponse(w http.ResponseWriter, en
|
||||
}
|
||||
}
|
||||
|
||||
// addSSEHeadersToResponse converts stored SSE metadata from entry.Extended to HTTP response headers
|
||||
// Uses intelligent prioritization: only set headers for the PRIMARY encryption type to avoid conflicts
|
||||
func (s3a *S3ApiServer) addSSEHeadersToResponse(proxyResponse *http.Response, entry *filer_pb.Entry) {
|
||||
if entry == nil || entry.Extended == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Determine the primary encryption type by examining chunks (most reliable)
|
||||
primarySSEType := s3a.detectPrimarySSEType(entry)
|
||||
|
||||
// Only set headers for the PRIMARY encryption type
|
||||
switch primarySSEType {
|
||||
case s3_constants.SSETypeC:
|
||||
// Add only SSE-C headers
|
||||
if algorithmBytes, exists := entry.Extended[s3_constants.AmzServerSideEncryptionCustomerAlgorithm]; exists && len(algorithmBytes) > 0 {
|
||||
proxyResponse.Header.Set(s3_constants.AmzServerSideEncryptionCustomerAlgorithm, string(algorithmBytes))
|
||||
}
|
||||
|
||||
if keyMD5Bytes, exists := entry.Extended[s3_constants.AmzServerSideEncryptionCustomerKeyMD5]; exists && len(keyMD5Bytes) > 0 {
|
||||
proxyResponse.Header.Set(s3_constants.AmzServerSideEncryptionCustomerKeyMD5, string(keyMD5Bytes))
|
||||
}
|
||||
|
||||
if ivBytes, exists := entry.Extended[s3_constants.SeaweedFSSSEIV]; exists && len(ivBytes) > 0 {
|
||||
ivBase64 := base64.StdEncoding.EncodeToString(ivBytes)
|
||||
proxyResponse.Header.Set(s3_constants.SeaweedFSSSEIVHeader, ivBase64)
|
||||
}
|
||||
|
||||
case s3_constants.SSETypeKMS:
|
||||
// Add only SSE-KMS headers
|
||||
if sseAlgorithm, exists := entry.Extended[s3_constants.AmzServerSideEncryption]; exists && len(sseAlgorithm) > 0 {
|
||||
proxyResponse.Header.Set(s3_constants.AmzServerSideEncryption, string(sseAlgorithm))
|
||||
}
|
||||
|
||||
if kmsKeyID, exists := entry.Extended[s3_constants.AmzServerSideEncryptionAwsKmsKeyId]; exists && len(kmsKeyID) > 0 {
|
||||
proxyResponse.Header.Set(s3_constants.AmzServerSideEncryptionAwsKmsKeyId, string(kmsKeyID))
|
||||
}
|
||||
|
||||
case s3_constants.SSETypeS3:
|
||||
// Add only SSE-S3 headers
|
||||
proxyResponse.Header.Set(s3_constants.AmzServerSideEncryption, SSES3Algorithm)
|
||||
|
||||
default:
|
||||
// Unencrypted or unknown - don't set any SSE headers
|
||||
}
|
||||
|
||||
glog.V(3).Infof("addSSEHeadersToResponse: processed %d extended metadata entries", len(entry.Extended))
|
||||
}
|
||||
|
||||
// detectPrimarySSEType determines the primary SSE type by examining chunk metadata
|
||||
func (s3a *S3ApiServer) detectPrimarySSEType(entry *filer_pb.Entry) string {
|
||||
// Safety check: handle nil entry
|
||||
@@ -2942,6 +3188,140 @@ func (r *SSERangeReader) Read(p []byte) (n int, err error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
// createMultipartSSECDecryptedReader creates a decrypted reader for multipart SSE-C objects
|
||||
// Each chunk has its own IV and encryption key from the original multipart parts
|
||||
func (s3a *S3ApiServer) createMultipartSSECDecryptedReader(r *http.Request, proxyResponse *http.Response, entry *filer_pb.Entry) (io.Reader, error) {
|
||||
ctx := r.Context()
|
||||
|
||||
// Parse SSE-C headers from the request for decryption key
|
||||
customerKey, err := ParseSSECHeaders(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid SSE-C headers for multipart decryption: %v", err)
|
||||
}
|
||||
|
||||
// Entry is passed from caller to avoid redundant filer lookup
|
||||
|
||||
// Sort chunks by offset to ensure correct order
|
||||
chunks := entry.GetChunks()
|
||||
sort.Slice(chunks, func(i, j int) bool {
|
||||
return chunks[i].GetOffset() < chunks[j].GetOffset()
|
||||
})
|
||||
|
||||
// Check for Range header to optimize chunk processing
|
||||
var startOffset, endOffset int64 = 0, -1
|
||||
rangeHeader := r.Header.Get("Range")
|
||||
if rangeHeader != "" {
|
||||
// Parse range header (e.g., "bytes=0-99")
|
||||
if len(rangeHeader) > 6 && rangeHeader[:6] == "bytes=" {
|
||||
rangeSpec := rangeHeader[6:]
|
||||
parts := strings.Split(rangeSpec, "-")
|
||||
if len(parts) == 2 {
|
||||
if parts[0] != "" {
|
||||
startOffset, _ = strconv.ParseInt(parts[0], 10, 64)
|
||||
}
|
||||
if parts[1] != "" {
|
||||
endOffset, _ = strconv.ParseInt(parts[1], 10, 64)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Filter chunks to only those needed for the range request
|
||||
var neededChunks []*filer_pb.FileChunk
|
||||
for _, chunk := range chunks {
|
||||
chunkStart := chunk.GetOffset()
|
||||
chunkEnd := chunkStart + int64(chunk.GetSize()) - 1
|
||||
|
||||
// Check if this chunk overlaps with the requested range
|
||||
if endOffset == -1 {
|
||||
// No end specified, take all chunks from startOffset
|
||||
if chunkEnd >= startOffset {
|
||||
neededChunks = append(neededChunks, chunk)
|
||||
}
|
||||
} else {
|
||||
// Specific range: check for overlap
|
||||
if chunkStart <= endOffset && chunkEnd >= startOffset {
|
||||
neededChunks = append(neededChunks, chunk)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create readers for only the needed chunks
|
||||
var readers []io.Reader
|
||||
|
||||
for _, chunk := range neededChunks {
|
||||
|
||||
// Get this chunk's encrypted data
|
||||
chunkReader, err := s3a.createEncryptedChunkReader(ctx, chunk)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create chunk reader: %v", err)
|
||||
}
|
||||
|
||||
if chunk.GetSseType() == filer_pb.SSEType_SSE_C {
|
||||
// For SSE-C chunks, extract the IV from the stored per-chunk metadata (unified approach)
|
||||
if len(chunk.GetSseMetadata()) > 0 {
|
||||
// Deserialize the SSE-C metadata stored in the unified metadata field
|
||||
ssecMetadata, decErr := DeserializeSSECMetadata(chunk.GetSseMetadata())
|
||||
if decErr != nil {
|
||||
chunkReader.Close()
|
||||
return nil, fmt.Errorf("failed to deserialize SSE-C metadata for chunk %s: %v", chunk.GetFileIdString(), decErr)
|
||||
}
|
||||
|
||||
// Decode the IV from the metadata
|
||||
iv, ivErr := base64.StdEncoding.DecodeString(ssecMetadata.IV)
|
||||
if ivErr != nil {
|
||||
chunkReader.Close()
|
||||
return nil, fmt.Errorf("failed to decode IV for SSE-C chunk %s: %v", chunk.GetFileIdString(), ivErr)
|
||||
}
|
||||
|
||||
partOffset := ssecMetadata.PartOffset
|
||||
if partOffset < 0 {
|
||||
chunkReader.Close()
|
||||
return nil, fmt.Errorf("invalid SSE-C part offset %d for chunk %s", partOffset, chunk.GetFileIdString())
|
||||
}
|
||||
|
||||
// Use stored IV and advance CTR stream by PartOffset within the encrypted stream
|
||||
decryptedReader, decErr := CreateSSECDecryptedReaderWithOffset(chunkReader, customerKey, iv, uint64(partOffset))
|
||||
if decErr != nil {
|
||||
chunkReader.Close()
|
||||
return nil, fmt.Errorf("failed to create SSE-C decrypted reader for chunk %s: %v", chunk.GetFileIdString(), decErr)
|
||||
}
|
||||
readers = append(readers, decryptedReader)
|
||||
} else {
|
||||
chunkReader.Close()
|
||||
return nil, fmt.Errorf("SSE-C chunk %s missing required metadata", chunk.GetFileIdString())
|
||||
}
|
||||
} else {
|
||||
// Non-SSE-C chunk, use as-is
|
||||
readers = append(readers, chunkReader)
|
||||
}
|
||||
}
|
||||
|
||||
multiReader := NewMultipartSSEReader(readers)
|
||||
|
||||
// Apply range logic if a range was requested
|
||||
if rangeHeader != "" && startOffset >= 0 {
|
||||
if endOffset == -1 {
|
||||
// Open-ended range (e.g., "bytes=100-")
|
||||
return &SSERangeReader{
|
||||
reader: multiReader,
|
||||
offset: startOffset,
|
||||
remaining: -1, // Read until EOF
|
||||
}, nil
|
||||
} else {
|
||||
// Specific range (e.g., "bytes=0-99")
|
||||
rangeLength := endOffset - startOffset + 1
|
||||
return &SSERangeReader{
|
||||
reader: multiReader,
|
||||
offset: startOffset,
|
||||
remaining: rangeLength,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
return multiReader, nil
|
||||
}
|
||||
|
||||
// PartBoundaryInfo holds information about a part's chunk boundaries
|
||||
type PartBoundaryInfo struct {
|
||||
PartNumber int `json:"part"`
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -25,7 +24,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -83,6 +81,33 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
|
||||
replaceMeta, replaceTagging := replaceDirective(r.Header)
|
||||
|
||||
if (srcBucket == dstBucket && srcObject == dstObject || cpSrcPath == "") && (replaceMeta || replaceTagging) {
|
||||
fullPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), dstObject))
|
||||
dir, name := fullPath.DirAndName()
|
||||
entry, err := s3a.getEntry(dir, name)
|
||||
if err != nil || entry.IsDirectory {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
return
|
||||
}
|
||||
entry.Extended, err = processMetadataBytes(r.Header, entry.Extended, replaceMeta, replaceTagging)
|
||||
entry.Attributes.Mtime = t.Unix()
|
||||
if err != nil {
|
||||
glog.Errorf("CopyObjectHandler ValidateTags error %s: %v", r.URL, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidTag)
|
||||
return
|
||||
}
|
||||
err = s3a.touch(dir, name, entry)
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
return
|
||||
}
|
||||
writeSuccessResponseXML(w, r, CopyObjectResult{
|
||||
ETag: filer.ETag(entry),
|
||||
LastModified: t,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// If source object is empty or bucket is empty, reply back invalid copy source.
|
||||
if srcObject == "" || srcBucket == "" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
@@ -97,14 +122,38 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := s3a.resolveCopySourceEntry(srcBucket, srcObject, srcVersionId, srcVersioningState)
|
||||
// Get the source entry with version awareness based on versioning state
|
||||
var entry *filer_pb.Entry
|
||||
if srcVersionId != "" {
|
||||
// Specific version requested - always use version-aware retrieval
|
||||
entry, err = s3a.getSpecificObjectVersion(srcBucket, srcObject, srcVersionId)
|
||||
} else if srcVersioningState == s3_constants.VersioningEnabled {
|
||||
// Versioning enabled - get latest version from .versions directory
|
||||
entry, err = s3a.getLatestObjectVersion(srcBucket, srcObject)
|
||||
} else if srcVersioningState == s3_constants.VersioningSuspended {
|
||||
// Versioning suspended - current object is stored as regular file ("null" version)
|
||||
// Try regular file first, fall back to latest version if needed
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(srcBucket), srcObject))
|
||||
dir, name := srcPath.DirAndName()
|
||||
entry, err = s3a.getEntry(dir, name)
|
||||
if err != nil {
|
||||
// If regular file doesn't exist, try latest version as fallback
|
||||
glog.V(2).Infof("CopyObject: regular file not found for suspended versioning, trying latest version")
|
||||
entry, err = s3a.getLatestObjectVersion(srcBucket, srcObject)
|
||||
}
|
||||
} else {
|
||||
// No versioning configured - use regular retrieval
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(srcBucket), srcObject))
|
||||
dir, name := srcPath.DirAndName()
|
||||
entry, err = s3a.getEntry(dir, name)
|
||||
}
|
||||
|
||||
if err != nil || entry.IsDirectory {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
return
|
||||
}
|
||||
|
||||
sameDestination := srcBucket == dstBucket && srcObject == dstObject
|
||||
if sameDestination && !(replaceMeta || replaceTagging) {
|
||||
if srcBucket == dstBucket && srcObject == dstObject {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopyDest)
|
||||
return
|
||||
}
|
||||
@@ -114,10 +163,6 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
s3err.WriteErrorResponse(w, r, err)
|
||||
return
|
||||
}
|
||||
if errCode := s3a.checkConditionalHeaders(r, dstBucket, dstObject); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate encryption parameters
|
||||
if err := ValidateCopyEncryption(entry.Extended, r.Header); err != nil {
|
||||
@@ -127,62 +172,6 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
dstVersioningState, err := s3a.getVersioningState(dstBucket)
|
||||
if err != nil {
|
||||
glog.Errorf("Error checking versioning state for destination bucket %s: %v", dstBucket, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
if sameDestination && (replaceMeta || replaceTagging) && s3a.canUseMetadataOnlySelfCopy(entry, r, dstBucket, dstObject) {
|
||||
var dstVersionId string
|
||||
var etag string
|
||||
updateCode := s3a.withObjectWriteLock(dstBucket, dstObject, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, dstBucket, dstObject)
|
||||
}, func() s3err.ErrorCode {
|
||||
currentEntry, currentErr := s3a.resolveCopySourceEntry(srcBucket, srcObject, srcVersionId, srcVersioningState)
|
||||
if currentErr != nil || currentEntry.IsDirectory {
|
||||
return s3err.ErrInvalidCopySource
|
||||
}
|
||||
if errCode := s3a.validateConditionalCopyHeaders(r, currentEntry); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
|
||||
updatedEntry := cloneProtoEntry(currentEntry)
|
||||
updatedMetadata, metadataErr := processMetadataBytes(r.Header, updatedEntry.Extended, replaceMeta, replaceTagging)
|
||||
currentErr = metadataErr
|
||||
if currentErr != nil {
|
||||
glog.Errorf("CopyObjectHandler ValidateTags error %s: %v", r.URL, currentErr)
|
||||
return s3err.ErrInvalidTag
|
||||
}
|
||||
updatedEntry.Extended = mergeCopyMetadata(updatedEntry.Extended, updatedMetadata)
|
||||
if updatedEntry.Attributes == nil {
|
||||
updatedEntry.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
updatedEntry.Attributes.Mtime = t.Unix()
|
||||
|
||||
dstVersionId, etag, currentErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, updatedEntry)
|
||||
if currentErr != nil {
|
||||
return filerErrorToS3Error(currentErr)
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
if updateCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, updateCode)
|
||||
return
|
||||
}
|
||||
|
||||
if dstVersionId != "" {
|
||||
w.Header().Set("x-amz-version-id", dstVersionId)
|
||||
}
|
||||
setEtag(w, etag)
|
||||
writeSuccessResponseXML(w, r, CopyObjectResult{
|
||||
ETag: etag,
|
||||
LastModified: t,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Determine whether we can reuse the source MD5 (direct copy without encryption changes).
|
||||
canReuseSourceMd5 := false
|
||||
var sourceMd5 []byte
|
||||
@@ -313,26 +302,107 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
}
|
||||
|
||||
var dstVersionId string
|
||||
var etag string
|
||||
|
||||
finalizeCode := s3a.withObjectWriteLock(dstBucket, dstObject, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, dstBucket, dstObject)
|
||||
}, func() s3err.ErrorCode {
|
||||
var finalizeErr error
|
||||
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry)
|
||||
if finalizeErr != nil {
|
||||
return filerErrorToS3Error(finalizeErr)
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
if finalizeCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, finalizeCode)
|
||||
// Check if destination bucket has versioning enabled
|
||||
// Only create versions if versioning is explicitly "Enabled", not "Suspended" or unconfigured
|
||||
dstVersioningState, err := s3a.getVersioningState(dstBucket)
|
||||
if err != nil {
|
||||
glog.Errorf("Error checking versioning state for destination bucket %s: %v", dstBucket, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
if dstVersionId != "" {
|
||||
var dstVersionId string
|
||||
var etag string
|
||||
|
||||
if shouldCreateVersionForCopy(dstVersioningState) {
|
||||
// For versioned destination, create a new version using appropriate format
|
||||
dstVersionId = s3a.generateVersionIdForObject(dstBucket, dstObject)
|
||||
glog.V(2).Infof("CopyObjectHandler: creating version %s for destination %s/%s", dstVersionId, dstBucket, dstObject)
|
||||
|
||||
// Add version metadata to the entry
|
||||
if dstEntry.Extended == nil {
|
||||
dstEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
dstEntry.Extended[s3_constants.ExtVersionIdKey] = []byte(dstVersionId)
|
||||
|
||||
// Calculate ETag for versioning
|
||||
filerEntry := &filer.Entry{
|
||||
FullPath: util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), dstObject)),
|
||||
Attr: filer.Attr{
|
||||
FileSize: dstEntry.Attributes.FileSize,
|
||||
Mtime: time.Unix(dstEntry.Attributes.Mtime, 0),
|
||||
Crtime: time.Unix(dstEntry.Attributes.Crtime, 0),
|
||||
Mime: dstEntry.Attributes.Mime,
|
||||
},
|
||||
Chunks: dstEntry.Chunks,
|
||||
}
|
||||
etag = filer.ETagEntry(filerEntry)
|
||||
if !strings.HasPrefix(etag, "\"") {
|
||||
etag = "\"" + etag + "\""
|
||||
}
|
||||
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
// Create version file
|
||||
versionFileName := s3a.getVersionFileName(dstVersionId)
|
||||
versionObjectPath := dstObject + ".versions/" + versionFileName
|
||||
bucketDir := s3a.bucketDir(dstBucket)
|
||||
|
||||
if err := s3a.mkFile(bucketDir, versionObjectPath, dstEntry.Chunks, func(entry *filer_pb.Entry) {
|
||||
entry.Attributes = dstEntry.Attributes
|
||||
entry.Extended = dstEntry.Extended
|
||||
}); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, filerErrorToS3Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
// Update the .versions directory metadata
|
||||
// Pass dstEntry to cache its metadata for single-scan list efficiency
|
||||
err = s3a.updateLatestVersionInDirectory(dstBucket, dstObject, dstVersionId, versionFileName, dstEntry)
|
||||
if err != nil {
|
||||
glog.Errorf("CopyObjectHandler: failed to update latest version in directory: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
// Set version ID in response header
|
||||
w.Header().Set("x-amz-version-id", dstVersionId)
|
||||
} else {
|
||||
// For non-versioned destination, use regular copy
|
||||
// Remove any versioning-related metadata from source that shouldn't carry over
|
||||
cleanupVersioningMetadata(dstEntry.Extended)
|
||||
|
||||
dstPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), dstObject))
|
||||
dstDir, dstName := dstPath.DirAndName()
|
||||
|
||||
// Check if destination exists and remove it first (S3 copy overwrites)
|
||||
if exists, _ := s3a.exists(dstDir, dstName, false); exists {
|
||||
if err := s3a.rmObject(dstDir, dstName, false, false); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Create the new file
|
||||
if err := s3a.mkFile(dstDir, dstName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
|
||||
entry.Attributes = dstEntry.Attributes
|
||||
entry.Extended = dstEntry.Extended
|
||||
}); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, filerErrorToS3Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
// Calculate ETag
|
||||
filerEntry := &filer.Entry{
|
||||
FullPath: dstPath,
|
||||
Attr: filer.Attr{
|
||||
FileSize: dstEntry.Attributes.FileSize,
|
||||
Mtime: time.Unix(dstEntry.Attributes.Mtime, 0),
|
||||
Crtime: time.Unix(dstEntry.Attributes.Crtime, 0),
|
||||
Mime: dstEntry.Attributes.Mime,
|
||||
},
|
||||
Chunks: dstEntry.Chunks,
|
||||
}
|
||||
etag = filer.ETagEntry(filerEntry)
|
||||
}
|
||||
|
||||
setEtag(w, etag)
|
||||
@@ -346,202 +416,6 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
|
||||
}
|
||||
|
||||
func cloneProtoEntry(entry *filer_pb.Entry) *filer_pb.Entry {
|
||||
if entry == nil {
|
||||
return nil
|
||||
}
|
||||
return proto.Clone(entry).(*filer_pb.Entry)
|
||||
}
|
||||
|
||||
func copyEntryETag(fullPath util.FullPath, entry *filer_pb.Entry) string {
|
||||
if entry != nil && entry.Extended != nil {
|
||||
if etag, ok := entry.Extended[s3_constants.ExtETagKey]; ok && len(etag) > 0 {
|
||||
return string(etag)
|
||||
}
|
||||
}
|
||||
attr := filer.Attr{}
|
||||
if entry.Attributes != nil {
|
||||
attr = filer.Attr{
|
||||
FileSize: entry.Attributes.FileSize,
|
||||
Mtime: time.Unix(entry.Attributes.Mtime, 0),
|
||||
Crtime: time.Unix(entry.Attributes.Crtime, 0),
|
||||
Mime: entry.Attributes.Mime,
|
||||
Md5: entry.Attributes.Md5,
|
||||
}
|
||||
}
|
||||
return filer.ETagEntry(&filer.Entry{
|
||||
FullPath: fullPath,
|
||||
Attr: attr,
|
||||
Chunks: entry.Chunks,
|
||||
Content: entry.Content,
|
||||
Remote: entry.RemoteEntry,
|
||||
})
|
||||
}
|
||||
|
||||
func copyEntryToTarget(dst, src *filer_pb.Entry) {
|
||||
dst.IsDirectory = src.IsDirectory
|
||||
dst.Attributes = src.Attributes
|
||||
dst.Extended = src.Extended
|
||||
dst.Chunks = src.Chunks
|
||||
dst.Content = src.Content
|
||||
dst.RemoteEntry = src.RemoteEntry
|
||||
dst.HardLinkId = src.HardLinkId
|
||||
dst.HardLinkCounter = src.HardLinkCounter
|
||||
dst.Quota = src.Quota
|
||||
dst.WormEnforcedAtTsNs = src.WormEnforcedAtTsNs
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersioningState string, dstEntry *filer_pb.Entry) (versionId string, etag string, err error) {
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(dstObject)
|
||||
dstPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), normalizedObject))
|
||||
dstDir, dstName := dstPath.DirAndName()
|
||||
|
||||
if dstEntry.Attributes == nil {
|
||||
dstEntry.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
if dstEntry.Extended == nil {
|
||||
dstEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
|
||||
etag = copyEntryETag(dstPath, dstEntry)
|
||||
|
||||
switch dstVersioningState {
|
||||
case s3_constants.VersioningEnabled:
|
||||
versionId = s3a.generateVersionIdForObject(dstBucket, normalizedObject)
|
||||
glog.V(2).Infof("CopyObjectHandler: creating version %s for destination %s/%s", versionId, dstBucket, normalizedObject)
|
||||
|
||||
dstEntry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionId)
|
||||
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
versionFileName := s3a.getVersionFileName(versionId)
|
||||
versionObjectPath := normalizedObject + s3_constants.VersionsFolder + "/" + versionFileName
|
||||
bucketDir := s3a.bucketDir(dstBucket)
|
||||
|
||||
if err = s3a.mkFile(bucketDir, versionObjectPath, dstEntry.Chunks, func(entry *filer_pb.Entry) {
|
||||
copyEntryToTarget(entry, dstEntry)
|
||||
}); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
if err = s3a.updateLatestVersionInDirectory(dstBucket, normalizedObject, versionId, versionFileName, dstEntry); err != nil {
|
||||
if rollbackErr := s3a.rollbackCopyVersion(bucketDir, versionObjectPath); rollbackErr != nil {
|
||||
glog.Errorf("CopyObjectHandler: failed to rollback version %s for %s/%s after latest pointer update error: %v", versionId, dstBucket, normalizedObject, rollbackErr)
|
||||
}
|
||||
glog.Errorf("CopyObjectHandler: failed to update latest version in directory: %v", err)
|
||||
return "", "", fmt.Errorf("update latest version metadata: %w", err)
|
||||
}
|
||||
|
||||
return versionId, etag, nil
|
||||
|
||||
case s3_constants.VersioningSuspended:
|
||||
cleanupVersioningMetadata(dstEntry.Extended)
|
||||
dstEntry.Extended[s3_constants.ExtVersionIdKey] = []byte("null")
|
||||
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
if err = s3a.mkFile(dstDir, dstName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
|
||||
copyEntryToTarget(entry, dstEntry)
|
||||
}); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
if err = s3a.updateIsLatestFlagsForSuspendedVersioning(dstBucket, normalizedObject); err != nil {
|
||||
glog.Warningf("CopyObjectHandler: failed to update suspended version latest flags for %s/%s: %v", dstBucket, normalizedObject, err)
|
||||
}
|
||||
|
||||
return "", etag, nil
|
||||
|
||||
default:
|
||||
cleanupVersioningMetadata(dstEntry.Extended)
|
||||
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
if err = s3a.mkFile(dstDir, dstName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
|
||||
copyEntryToTarget(entry, dstEntry)
|
||||
}); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
return "", etag, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) rollbackCopyVersion(bucketDir, versionObjectPath string) error {
|
||||
versionPath := util.FullPath(fmt.Sprintf("%s/%s", bucketDir, versionObjectPath))
|
||||
versionDir, versionName := versionPath.DirAndName()
|
||||
return s3a.rmObject(versionDir, versionName, true, false)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) resolveCopySourceEntry(bucket, object, versionId, versioningState string) (*filer_pb.Entry, error) {
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(object)
|
||||
|
||||
if versionId != "" {
|
||||
return s3a.getSpecificObjectVersion(bucket, normalizedObject, versionId)
|
||||
}
|
||||
|
||||
switch versioningState {
|
||||
case s3_constants.VersioningEnabled:
|
||||
return s3a.getLatestObjectVersion(bucket, normalizedObject)
|
||||
case s3_constants.VersioningSuspended:
|
||||
return s3a.resolveSuspendedCopySourceEntry(bucket, normalizedObject, "CopyObject")
|
||||
default:
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), normalizedObject))
|
||||
dir, name := srcPath.DirAndName()
|
||||
return s3a.getEntry(dir, name)
|
||||
}
|
||||
}
|
||||
|
||||
func mergeCopyMetadata(existing, updated map[string][]byte) map[string][]byte {
|
||||
merged := make(map[string][]byte, len(existing)+len(updated))
|
||||
for k, v := range existing {
|
||||
merged[k] = v
|
||||
}
|
||||
for k := range merged {
|
||||
if isManagedCopyMetadataKey(k) {
|
||||
delete(merged, k)
|
||||
}
|
||||
}
|
||||
for k, v := range updated {
|
||||
merged[k] = v
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
func isManagedCopyMetadataKey(key string) bool {
|
||||
switch key {
|
||||
case s3_constants.AmzStorageClass,
|
||||
s3_constants.AmzServerSideEncryption,
|
||||
s3_constants.AmzServerSideEncryptionAwsKmsKeyId,
|
||||
s3_constants.AmzServerSideEncryptionContext,
|
||||
s3_constants.AmzServerSideEncryptionBucketKeyEnabled,
|
||||
s3_constants.AmzServerSideEncryptionCustomerAlgorithm,
|
||||
s3_constants.AmzServerSideEncryptionCustomerKeyMD5,
|
||||
s3_constants.AmzTagCount:
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(key, s3_constants.AmzUserMetaPrefix) || strings.HasPrefix(key, s3_constants.AmzObjectTagging)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) resolveSuspendedCopySourceEntry(bucket, normalizedObject, operation string) (*filer_pb.Entry, error) {
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), normalizedObject))
|
||||
dir, name := srcPath.DirAndName()
|
||||
entry, err := s3a.getEntry(dir, name)
|
||||
if err == nil {
|
||||
return entry, nil
|
||||
}
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
glog.V(2).Infof("%s: regular file not found for suspended versioning, trying latest version", operation)
|
||||
return s3a.getLatestObjectVersion(bucket, normalizedObject)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) canUseMetadataOnlySelfCopy(entry *filer_pb.Entry, r *http.Request, bucket, object string) bool {
|
||||
srcPath := fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), s3_constants.NormalizeObjectKey(object))
|
||||
state := DetectEncryptionStateWithEntry(entry, r, srcPath, srcPath)
|
||||
s3a.applyCopyBucketDefaultEncryption(state, bucket)
|
||||
strategy, err := DetermineUnifiedCopyStrategy(state, entry.Extended, r)
|
||||
return err == nil && strategy == CopyStrategyDirect
|
||||
}
|
||||
|
||||
func pathToBucketAndObject(path string) (bucket, object string) {
|
||||
// Remove leading slash if present
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
@@ -679,7 +553,14 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
} else if srcVersioningState == s3_constants.VersioningSuspended {
|
||||
// Versioning suspended - current object is stored as regular file ("null" version)
|
||||
// Try regular file first, fall back to latest version if needed
|
||||
entry, err = s3a.resolveSuspendedCopySourceEntry(srcBucket, s3_constants.NormalizeObjectKey(srcObject), "CopyObjectPart")
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(srcBucket), srcObject))
|
||||
dir, name := srcPath.DirAndName()
|
||||
entry, err = s3a.getEntry(dir, name)
|
||||
if err != nil {
|
||||
// If regular file doesn't exist, try latest version as fallback
|
||||
glog.V(2).Infof("CopyObjectPart: regular file not found for suspended versioning, trying latest version")
|
||||
entry, err = s3a.getLatestObjectVersion(srcBucket, srcObject)
|
||||
}
|
||||
} else {
|
||||
// No versioning configured - use regular retrieval
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(srcBucket), srcObject))
|
||||
@@ -2099,6 +1980,18 @@ func (s3a *S3ApiServer) copyCrossEncryptionChunk(chunk *filer_pb.FileChunk, sour
|
||||
return dstChunk, nil
|
||||
}
|
||||
|
||||
// getEncryptionTypeString returns a string representation of encryption type for logging
|
||||
func (s3a *S3ApiServer) getEncryptionTypeString(isSSEC, isSSEKMS, isSSES3 bool) string {
|
||||
if isSSEC {
|
||||
return s3_constants.SSETypeC
|
||||
} else if isSSEKMS {
|
||||
return s3_constants.SSETypeKMS
|
||||
} else if isSSES3 {
|
||||
return s3_constants.SSETypeS3
|
||||
}
|
||||
return "Plain"
|
||||
}
|
||||
|
||||
// copyChunksWithSSEC handles SSE-C aware copying with smart fast/slow path selection
|
||||
// Returns chunks and destination metadata that should be applied to the destination entry
|
||||
func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Request) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
|
||||
@@ -8,9 +8,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
type H map[string]string
|
||||
@@ -398,58 +396,6 @@ func TestProcessMetadataBytes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeCopyMetadataPreservesInternalFields(t *testing.T) {
|
||||
existing := map[string][]byte{
|
||||
s3_constants.SeaweedFSSSEKMSKey: []byte("kms-secret"),
|
||||
s3_constants.SeaweedFSSSEIV: []byte("iv"),
|
||||
"X-Amz-Meta-Old": []byte("old"),
|
||||
"X-Amz-Tagging-Old": []byte("old-tag"),
|
||||
s3_constants.AmzStorageClass: []byte("STANDARD"),
|
||||
}
|
||||
updated := map[string][]byte{
|
||||
"X-Amz-Meta-New": []byte("new"),
|
||||
"X-Amz-Tagging-New": []byte("new-tag"),
|
||||
s3_constants.AmzStorageClass: []byte("GLACIER"),
|
||||
}
|
||||
|
||||
merged := mergeCopyMetadata(existing, updated)
|
||||
|
||||
if got := string(merged[s3_constants.SeaweedFSSSEKMSKey]); got != "kms-secret" {
|
||||
t.Fatalf("expected internal KMS key to be preserved, got %q", got)
|
||||
}
|
||||
if got := string(merged[s3_constants.SeaweedFSSSEIV]); got != "iv" {
|
||||
t.Fatalf("expected internal IV to be preserved, got %q", got)
|
||||
}
|
||||
if _, ok := merged["X-Amz-Meta-Old"]; ok {
|
||||
t.Fatalf("expected stale user metadata to be removed, got %#v", merged)
|
||||
}
|
||||
if _, ok := merged["X-Amz-Tagging-Old"]; ok {
|
||||
t.Fatalf("expected stale tagging metadata to be removed, got %#v", merged)
|
||||
}
|
||||
if got := string(merged["X-Amz-Meta-New"]); got != "new" {
|
||||
t.Fatalf("expected replacement user metadata to be applied, got %q", got)
|
||||
}
|
||||
if got := string(merged["X-Amz-Tagging-New"]); got != "new-tag" {
|
||||
t.Fatalf("expected replacement tagging metadata to be applied, got %q", got)
|
||||
}
|
||||
if got := string(merged[s3_constants.AmzStorageClass]); got != "GLACIER" {
|
||||
t.Fatalf("expected storage class to be updated, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyEntryETagPrefersStoredETag(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtETagKey: []byte("\"stored-etag\""),
|
||||
},
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
}
|
||||
|
||||
if got := copyEntryETag(util.FullPath("/buckets/test-bucket/object.txt"), entry); got != "\"stored-etag\"" {
|
||||
t.Fatalf("copyEntryETag() = %q, want %q", got, "\"stored-etag\"")
|
||||
}
|
||||
}
|
||||
|
||||
func fmtTagging(maps ...map[string]string) {
|
||||
for _, m := range maps {
|
||||
if tagging := m[s3_constants.AmzObjectTagging]; len(tagging) > 0 {
|
||||
@@ -610,8 +556,9 @@ func TestCleanupVersioningMetadata(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCopyVersioningIntegration validates the metadata shaping that happens
|
||||
// before copy finalization for each destination versioning mode.
|
||||
// TestCopyVersioningIntegration validates the interaction between
|
||||
// shouldCreateVersionForCopy and cleanupVersioningMetadata functions.
|
||||
// This integration test ensures the complete fix for issue #7505.
|
||||
func TestCopyVersioningIntegration(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
@@ -634,7 +581,7 @@ func TestCopyVersioningIntegration(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "SuspendedCleansVersionMetadataBeforeFinalize",
|
||||
name: "SuspendedCleansMetadata",
|
||||
versioningState: s3_constants.VersioningSuspended,
|
||||
sourceMetadata: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte("v123"),
|
||||
|
||||
@@ -2,7 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -19,159 +18,6 @@ const (
|
||||
deleteMultipleObjectsLimit = 1000
|
||||
)
|
||||
|
||||
type deleteMutationResult struct {
|
||||
versionId string
|
||||
deleteMarker bool
|
||||
}
|
||||
|
||||
func deleteErrorFromCode(code s3err.ErrorCode, key, versionId string) DeleteError {
|
||||
apiErr := s3err.GetAPIError(code)
|
||||
return DeleteError{
|
||||
Code: apiErr.Code,
|
||||
Message: apiErr.Description,
|
||||
Key: key,
|
||||
VersionId: versionId,
|
||||
}
|
||||
}
|
||||
|
||||
// isMissingDeleteConditionTarget normalizes missing-target detection for conditional deletes.
|
||||
// Prefer errors.Is(err, filer_pb.ErrNotFound) and errors.Is(err, ErrDeleteMarker); keep the
|
||||
// string-based fallback only as a defensive bridge for filer paths that still return plain text.
|
||||
func isMissingDeleteConditionTarget(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrDeleteMarker) {
|
||||
return true
|
||||
}
|
||||
|
||||
lowerErr := strings.ToLower(err.Error())
|
||||
return strings.Contains(lowerErr, "not found")
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) resolveDeleteConditionalEntry(bucket, object, versionId, versioningState string) (*filer_pb.Entry, error) {
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(object)
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
|
||||
if versionId != "" {
|
||||
if versionId == "null" {
|
||||
return s3a.getEntry(bucketDir, normalizedObject)
|
||||
}
|
||||
return s3a.getEntry(s3a.getVersionedObjectDir(bucket, normalizedObject), s3a.getVersionFileName(versionId))
|
||||
}
|
||||
|
||||
switch versioningState {
|
||||
case s3_constants.VersioningEnabled:
|
||||
entry, err := s3a.getLatestObjectVersion(bucket, normalizedObject)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return normalizeConditionalTargetEntry(entry), nil
|
||||
default:
|
||||
entry, err := s3a.resolveObjectEntry(bucket, normalizedObject)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return normalizeConditionalTargetEntry(entry), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) validateDeleteIfMatch(entry *filer_pb.Entry, ifMatch string, missingCode s3err.ErrorCode) s3err.ErrorCode {
|
||||
if ifMatch == "" {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if entry == nil {
|
||||
return missingCode
|
||||
}
|
||||
if ifMatch == "*" {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if !s3a.etagMatches(ifMatch, s3a.getObjectETag(entry)) {
|
||||
return s3err.ErrPreconditionFailed
|
||||
}
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) checkDeleteIfMatch(bucket, object, versionId, versioningState, ifMatch string, missingCode s3err.ErrorCode) s3err.ErrorCode {
|
||||
if ifMatch == "" {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
entry, err := s3a.resolveDeleteConditionalEntry(bucket, object, versionId, versioningState)
|
||||
if err != nil {
|
||||
if isMissingDeleteConditionTarget(err) {
|
||||
return missingCode
|
||||
}
|
||||
glog.Errorf("checkDeleteIfMatch: failed to resolve %s/%s (versionId=%s): %v", bucket, object, versionId, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
return s3a.validateDeleteIfMatch(entry, ifMatch, missingCode)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, versionId, versioningState string) (deleteMutationResult, s3err.ErrorCode) {
|
||||
var result deleteMutationResult
|
||||
|
||||
switch {
|
||||
case versionId != "":
|
||||
versionEntry, versionLookupErr := s3a.getSpecificObjectVersion(bucket, object, versionId)
|
||||
if versionLookupErr == nil && versionEntry != nil && versionEntry.Extended != nil {
|
||||
if deleteMarker, ok := versionEntry.Extended[s3_constants.ExtDeleteMarkerKey]; ok && string(deleteMarker) == "true" {
|
||||
result.deleteMarker = true
|
||||
}
|
||||
}
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, versionId, governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s version %s: %v", bucket, object, versionId, err)
|
||||
return result, s3err.ErrAccessDenied
|
||||
}
|
||||
if err := s3a.deleteSpecificObjectVersion(bucket, object, versionId); err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to delete specific version %s for %s/%s: %v", versionId, bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
result.versionId = versionId
|
||||
return result, s3err.ErrNone
|
||||
|
||||
case versioningState == s3_constants.VersioningEnabled:
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
|
||||
if err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to create delete marker for %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
result.versionId = deleteMarkerVersionId
|
||||
result.deleteMarker = true
|
||||
return result, s3err.ErrNone
|
||||
|
||||
case versioningState == s3_constants.VersioningSuspended:
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, "null", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s null version: %v", bucket, object, err)
|
||||
return result, s3err.ErrAccessDenied
|
||||
}
|
||||
if err := s3a.deleteSpecificObjectVersion(bucket, object, "null"); err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to delete null version for %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
|
||||
if err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to create delete marker for suspended versioning %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
result.versionId = deleteMarkerVersionId
|
||||
result.deleteMarker = true
|
||||
return result, s3err.ErrNone
|
||||
}
|
||||
|
||||
glog.Errorf("deleteVersionedObject: unsupported versioning state %q for %s/%s", versioningState, bucket, object)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string) error {
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object)
|
||||
dir, name := target.DirAndName()
|
||||
return deleteObjectEntry(client, dir, name, true, false)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
@@ -196,6 +42,8 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
versioningEnabled := (versioningState == s3_constants.VersioningEnabled)
|
||||
versioningSuspended := (versioningState == s3_constants.VersioningSuspended)
|
||||
versioningConfigured := (versioningState != "")
|
||||
|
||||
var auditLog *s3err.AccessLog
|
||||
@@ -203,49 +51,93 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
auditLog = s3err.GetAccessLog(r, http.StatusNoContent, s3err.ErrNone)
|
||||
}
|
||||
|
||||
if ifMatchResult := s3a.checkDeleteIfMatch(bucket, object, versionId, versioningState, r.Header.Get(s3_constants.IfMatch), s3err.ErrPreconditionFailed); ifMatchResult != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, ifMatchResult)
|
||||
return
|
||||
}
|
||||
|
||||
var deleteResult deleteMutationResult
|
||||
deleteCode := s3a.withObjectWriteLock(bucket, object, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, object, versionId, versioningState, r.Header.Get(s3_constants.IfMatch), s3err.ErrPreconditionFailed)
|
||||
}, func() s3err.ErrorCode {
|
||||
if versioningConfigured {
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, object, versionId, versioningState)
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
if versioningConfigured {
|
||||
// Handle versioned delete based on specific versioning state
|
||||
if versionId != "" {
|
||||
// Delete specific version (same for both enabled and suspended)
|
||||
// Check object lock permissions before deleting specific version
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, versionId, governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteObjectHandler: object lock check failed for %s/%s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
deleteResult = result
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
// Delete specific version
|
||||
err := s3a.deleteSpecificObjectVersion(bucket, object, versionId)
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to delete specific version %s: %v", versionId, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
// Set version ID in response header
|
||||
w.Header().Set("x-amz-version-id", versionId)
|
||||
} else {
|
||||
// Delete without version ID - behavior depends on versioning state
|
||||
if versioningEnabled {
|
||||
// Enabled versioning: Create delete marker (logical delete)
|
||||
// AWS S3 behavior: Delete marker creation is NOT blocked by object retention
|
||||
// because it's a logical delete that doesn't actually remove the retained version
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to create delete marker: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
// Set delete marker version ID in response header
|
||||
w.Header().Set("x-amz-version-id", deleteMarkerVersionId)
|
||||
w.Header().Set("x-amz-delete-marker", "true")
|
||||
} else if versioningSuspended {
|
||||
// Suspended versioning: Actually delete the "null" version object
|
||||
glog.V(2).Infof("DeleteObjectHandler: deleting null version for suspended versioning %s/%s", bucket, object)
|
||||
|
||||
// Check object lock permissions before deleting "null" version
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, "null", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteObjectHandler: object lock check failed for %s/%s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the "null" version (the regular file)
|
||||
err := s3a.deleteSpecificObjectVersion(bucket, object, "null")
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to delete null version: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
// Note: According to AWS S3 spec, suspended versioning should NOT return version ID headers
|
||||
// The object is deleted but no version information is returned
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle regular delete (non-versioned)
|
||||
// Check object lock permissions before deleting object
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteObjectHandler: object lock check failed for %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrAccessDenied
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s3a.deleteUnversionedObjectWithClient(client, bucket, object)
|
||||
}); err != nil {
|
||||
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrInternalError
|
||||
// Normalize trailing-slash object keys (e.g. "path/") to the
|
||||
// underlying directory entry path so DeleteEntry gets a valid name.
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object)
|
||||
dir, name := target.DirAndName()
|
||||
|
||||
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return deleteObjectEntry(client, dir, name, true, false)
|
||||
// Note: Empty folder cleanup is now handled asynchronously by EmptyFolderCleaner
|
||||
// which listens to metadata events and uses consistent hashing for coordination
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
return s3err.ErrNone
|
||||
})
|
||||
if deleteCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, deleteCode)
|
||||
return
|
||||
}
|
||||
|
||||
if deleteResult.versionId != "" {
|
||||
w.Header().Set("x-amz-version-id", deleteResult.versionId)
|
||||
}
|
||||
if deleteResult.deleteMarker {
|
||||
w.Header().Set("x-amz-delete-marker", "true")
|
||||
}
|
||||
|
||||
if auditLog != nil {
|
||||
@@ -262,7 +154,6 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
type ObjectIdentifier struct {
|
||||
Key string `xml:"Key"`
|
||||
VersionId string `xml:"VersionId,omitempty"`
|
||||
ETag string `xml:"ETag,omitempty"`
|
||||
DeleteMarker bool `xml:"DeleteMarker,omitempty"`
|
||||
DeleteMarkerVersionId string `xml:"DeleteMarkerVersionId,omitempty"`
|
||||
}
|
||||
@@ -337,63 +228,133 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
return
|
||||
}
|
||||
|
||||
versioningEnabled := (versioningState == s3_constants.VersioningEnabled)
|
||||
versioningSuspended := (versioningState == s3_constants.VersioningSuspended)
|
||||
versioningConfigured := (versioningState != "")
|
||||
deletedCount := 0
|
||||
|
||||
err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// delete file entries
|
||||
for _, object := range deleteObjects.Objects {
|
||||
if object.Key == "" {
|
||||
continue
|
||||
}
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object.Key); err != nil {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(s3err.ErrAccessDenied, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
|
||||
var deleteResult deleteMutationResult
|
||||
deleteCode := s3a.withObjectWriteLock(bucket, object.Key, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, object.Key, object.VersionId, versioningState, object.ETag, s3err.ErrNoSuchKey)
|
||||
}, func() s3err.ErrorCode {
|
||||
if versioningConfigured {
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, object.Key, object.VersionId, versioningState)
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
deleteResult = result
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object.Key)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object.Key, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteMultipleObjectsHandler: object lock check failed for %s/%s: %v", bucket, object.Key, err)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
if err := s3a.deleteUnversionedObjectWithClient(client, bucket, object.Key); err != nil {
|
||||
glog.Errorf("DeleteMultipleObjectsHandler: failed to delete %s/%s: %v", bucket, object.Key, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
return s3err.ErrNone
|
||||
})
|
||||
if deleteCode != s3err.ErrNone {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(deleteCode, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
|
||||
deletedCount++
|
||||
if !deleteObjects.Quiet {
|
||||
deletedObject := ObjectIdentifier{
|
||||
deleteErrors = append(deleteErrors, DeleteError{
|
||||
Code: s3err.GetAPIError(s3err.ErrAccessDenied).Code,
|
||||
Message: s3err.GetAPIError(s3err.ErrAccessDenied).Description,
|
||||
Key: object.Key,
|
||||
VersionId: deleteResult.versionId,
|
||||
VersionId: object.VersionId,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// Check object lock permissions before deletion (only for versioned buckets)
|
||||
if versioningConfigured {
|
||||
// Validate governance bypass for this specific object
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object.Key)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object.Key, object.VersionId, governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteMultipleObjectsHandler: object lock check failed for %s/%s (version: %s): %v", bucket, object.Key, object.VersionId, err)
|
||||
deleteErrors = append(deleteErrors, DeleteError{
|
||||
Code: s3err.GetAPIError(s3err.ErrAccessDenied).Code,
|
||||
Message: s3err.GetAPIError(s3err.ErrAccessDenied).Description,
|
||||
Key: object.Key,
|
||||
VersionId: object.VersionId,
|
||||
})
|
||||
continue
|
||||
}
|
||||
if deleteResult.deleteMarker {
|
||||
deletedObject.DeleteMarker = true
|
||||
deletedObject.DeleteMarkerVersionId = deleteResult.versionId
|
||||
}
|
||||
|
||||
var deleteVersionId string
|
||||
var isDeleteMarker bool
|
||||
|
||||
if versioningConfigured {
|
||||
// Handle versioned delete based on specific versioning state
|
||||
if object.VersionId != "" {
|
||||
// Delete specific version (same for both enabled and suspended)
|
||||
err := s3a.deleteSpecificObjectVersion(bucket, object.Key, object.VersionId)
|
||||
if err != nil {
|
||||
deleteErrors = append(deleteErrors, DeleteError{
|
||||
Code: "",
|
||||
Message: err.Error(),
|
||||
Key: object.Key,
|
||||
VersionId: object.VersionId,
|
||||
})
|
||||
continue
|
||||
}
|
||||
deleteVersionId = object.VersionId
|
||||
} else {
|
||||
// Delete without version ID - behavior depends on versioning state
|
||||
if versioningEnabled {
|
||||
// Enabled versioning: Create delete marker (logical delete)
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object.Key)
|
||||
if err != nil {
|
||||
deleteErrors = append(deleteErrors, DeleteError{
|
||||
Code: "",
|
||||
Message: err.Error(),
|
||||
Key: object.Key,
|
||||
VersionId: object.VersionId,
|
||||
})
|
||||
continue
|
||||
}
|
||||
deleteVersionId = deleteMarkerVersionId
|
||||
isDeleteMarker = true
|
||||
} else if versioningSuspended {
|
||||
// Suspended versioning: Actually delete the "null" version object
|
||||
glog.V(2).Infof("DeleteMultipleObjectsHandler: deleting null version for suspended versioning %s/%s", bucket, object.Key)
|
||||
|
||||
err := s3a.deleteSpecificObjectVersion(bucket, object.Key, "null")
|
||||
if err != nil {
|
||||
deleteErrors = append(deleteErrors, DeleteError{
|
||||
Code: "",
|
||||
Message: err.Error(),
|
||||
Key: object.Key,
|
||||
VersionId: "null",
|
||||
})
|
||||
continue
|
||||
}
|
||||
deleteVersionId = "null"
|
||||
// Note: For suspended versioning, we don't set isDeleteMarker=true
|
||||
// because we actually deleted the object, not created a delete marker
|
||||
}
|
||||
}
|
||||
|
||||
// Add to successful deletions with version info
|
||||
deletedObject := ObjectIdentifier{
|
||||
Key: object.Key,
|
||||
VersionId: deleteVersionId,
|
||||
DeleteMarker: isDeleteMarker,
|
||||
}
|
||||
|
||||
// For delete markers, also set DeleteMarkerVersionId field
|
||||
if isDeleteMarker {
|
||||
deletedObject.DeleteMarkerVersionId = deleteVersionId
|
||||
// Don't set VersionId for delete markers, use DeleteMarkerVersionId instead
|
||||
deletedObject.VersionId = ""
|
||||
}
|
||||
deletedObjects = append(deletedObjects, deletedObject)
|
||||
if !deleteObjects.Quiet {
|
||||
deletedObjects = append(deletedObjects, deletedObject)
|
||||
}
|
||||
if isDeleteMarker {
|
||||
// For delete markers, we don't need to track directories for cleanup
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
// Handle non-versioned delete (original logic)
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object.Key)
|
||||
parentDirectoryPath, entryName := target.DirAndName()
|
||||
isDeleteData, isRecursive := true, false
|
||||
|
||||
err := deleteObjectEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
|
||||
if err == nil {
|
||||
deletedObjects = append(deletedObjects, object)
|
||||
} else {
|
||||
deleteErrors = append(deleteErrors, DeleteError{
|
||||
Code: "",
|
||||
Message: err.Error(),
|
||||
Key: object.Key,
|
||||
VersionId: object.VersionId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if auditLog != nil {
|
||||
@@ -407,11 +368,6 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("DeleteMultipleObjectsHandler: failed to initialize filer client for bucket %s: %v", bucket, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
deleteResp := DeleteObjectsResponse{}
|
||||
if !deleteObjects.Quiet {
|
||||
@@ -419,7 +375,7 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
deleteResp.Errors = deleteErrors
|
||||
stats_collect.RecordBucketActiveTime(bucket)
|
||||
stats_collect.S3DeletedObjectsCounter.WithLabelValues(bucket).Add(float64(deletedCount))
|
||||
stats_collect.S3DeletedObjectsCounter.WithLabelValues(bucket).Add(float64(len(deletedObjects)))
|
||||
|
||||
writeSuccessResponseXML(w, r, deleteResp)
|
||||
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
func TestValidateDeleteIfMatch(t *testing.T) {
|
||||
s3a := NewS3ApiServerForTest()
|
||||
existingEntry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtETagKey: []byte("\"abc123\""),
|
||||
},
|
||||
}
|
||||
deleteMarkerEntry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtDeleteMarkerKey: []byte("true"),
|
||||
},
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
entry *filer_pb.Entry
|
||||
ifMatch string
|
||||
missingCode s3err.ErrorCode
|
||||
expected s3err.ErrorCode
|
||||
}{
|
||||
{
|
||||
name: "matching etag succeeds",
|
||||
entry: existingEntry,
|
||||
ifMatch: "\"abc123\"",
|
||||
missingCode: s3err.ErrPreconditionFailed,
|
||||
expected: s3err.ErrNone,
|
||||
},
|
||||
{
|
||||
name: "wildcard succeeds for existing entry",
|
||||
entry: existingEntry,
|
||||
ifMatch: "*",
|
||||
missingCode: s3err.ErrPreconditionFailed,
|
||||
expected: s3err.ErrNone,
|
||||
},
|
||||
{
|
||||
name: "mismatched etag fails",
|
||||
entry: existingEntry,
|
||||
ifMatch: "\"other\"",
|
||||
missingCode: s3err.ErrPreconditionFailed,
|
||||
expected: s3err.ErrPreconditionFailed,
|
||||
},
|
||||
{
|
||||
name: "missing current object fails single delete",
|
||||
entry: nil,
|
||||
ifMatch: "*",
|
||||
missingCode: s3err.ErrPreconditionFailed,
|
||||
expected: s3err.ErrPreconditionFailed,
|
||||
},
|
||||
{
|
||||
name: "missing current object returns no such key for batch delete",
|
||||
entry: nil,
|
||||
ifMatch: "*",
|
||||
missingCode: s3err.ErrNoSuchKey,
|
||||
expected: s3err.ErrNoSuchKey,
|
||||
},
|
||||
{
|
||||
name: "current delete marker behaves like missing object",
|
||||
entry: normalizeConditionalTargetEntry(deleteMarkerEntry),
|
||||
ifMatch: "*",
|
||||
missingCode: s3err.ErrPreconditionFailed,
|
||||
expected: s3err.ErrPreconditionFailed,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if errCode := s3a.validateDeleteIfMatch(tc.entry, tc.ifMatch, tc.missingCode); errCode != tc.expected {
|
||||
t.Fatalf("validateDeleteIfMatch() = %v, want %v", errCode, tc.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteObjectsRequestUnmarshalConditionalETags(t *testing.T) {
|
||||
var req DeleteObjectsRequest
|
||||
body := []byte(`
|
||||
<Delete>
|
||||
<Quiet>true</Quiet>
|
||||
<Object>
|
||||
<Key>first.txt</Key>
|
||||
<ETag>*</ETag>
|
||||
</Object>
|
||||
<Object>
|
||||
<Key>second.txt</Key>
|
||||
<VersionId>3HL4kqCxf3vjVBH40Nrjfkd</VersionId>
|
||||
<ETag>"abc123"</ETag>
|
||||
</Object>
|
||||
</Delete>`)
|
||||
|
||||
if err := xml.Unmarshal(body, &req); err != nil {
|
||||
t.Fatalf("xml.Unmarshal() error = %v", err)
|
||||
}
|
||||
if !req.Quiet {
|
||||
t.Fatalf("expected Quiet=true")
|
||||
}
|
||||
if len(req.Objects) != 2 {
|
||||
t.Fatalf("expected 2 objects, got %d", len(req.Objects))
|
||||
}
|
||||
if req.Objects[0].ETag != "*" {
|
||||
t.Fatalf("expected first object ETag to be '*', got %q", req.Objects[0].ETag)
|
||||
}
|
||||
if req.Objects[1].ETag != "\"abc123\"" {
|
||||
t.Fatalf("expected second object ETag to preserve quotes, got %q", req.Objects[1].ETag)
|
||||
}
|
||||
if req.Objects[1].VersionId != "3HL4kqCxf3vjVBH40Nrjfkd" {
|
||||
t.Fatalf("expected second object VersionId to unmarshal, got %q", req.Objects[1].VersionId)
|
||||
}
|
||||
}
|
||||
@@ -762,6 +762,60 @@ func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string,
|
||||
return
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) ensureDirectoryAllEmpty(filerClient filer_pb.SeaweedFilerClient, parentDir, name string) (isEmpty bool, err error) {
|
||||
// println("+ ensureDirectoryAllEmpty", dir, name)
|
||||
glog.V(4).Infof("+ isEmpty %s/%s", parentDir, name)
|
||||
defer glog.V(4).Infof("- isEmpty %s/%s %v", parentDir, name, isEmpty)
|
||||
var fileCounter int
|
||||
var subDirs []string
|
||||
currentDir := parentDir + "/" + name
|
||||
var startFrom string
|
||||
var isExhausted bool
|
||||
var foundEntry bool
|
||||
for fileCounter == 0 && !isExhausted && err == nil {
|
||||
err = filer_pb.SeaweedList(context.Background(), filerClient, currentDir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
foundEntry = true
|
||||
if entry.IsOlderDir() {
|
||||
subDirs = append(subDirs, entry.Name)
|
||||
} else {
|
||||
fileCounter++
|
||||
}
|
||||
startFrom = entry.Name
|
||||
isExhausted = isExhausted || isLast
|
||||
glog.V(4).Infof(" * %s/%s isLast: %t", currentDir, startFrom, isLast)
|
||||
return nil
|
||||
}, startFrom, false, 8)
|
||||
if !foundEntry {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if fileCounter > 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
for _, subDir := range subDirs {
|
||||
isSubEmpty, subErr := s3a.ensureDirectoryAllEmpty(filerClient, currentDir, subDir)
|
||||
if subErr != nil {
|
||||
return false, subErr
|
||||
}
|
||||
if !isSubEmpty {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
glog.V(1).Infof("deleting empty folder %s", currentDir)
|
||||
if err = doDeleteEntry(filerClient, parentDir, name, true, false); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// compareWithDelimiter compares two strings for sorting, treating the delimiter character
|
||||
// as having lower precedence than other characters to match AWS S3 behavior.
|
||||
// For example, with delimiter '/', 'foo/' should come before 'foo+1/' even though '+' < '/' in ASCII.
|
||||
|
||||
@@ -447,7 +447,7 @@ func (s3a *S3ApiServer) PutObjectPartHandler(w http.ResponseWriter, r *http.Requ
|
||||
glog.V(2).Infof("PutObjectPart: bucket=%s, object=%s, uploadId=%s, partNumber=%d, size=%d",
|
||||
bucket, object, uploadID, partID, r.ContentLength)
|
||||
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, "", partID, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, partID)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("PutObjectPart: putToFiler failed with error code %v for bucket=%s, object=%s, partNumber=%d",
|
||||
errCode, bucket, object, partID)
|
||||
@@ -471,25 +471,6 @@ func (s3a *S3ApiServer) genUploadsFolder(bucket string) string {
|
||||
return fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), s3_constants.MultipartUploadsFolder)
|
||||
}
|
||||
|
||||
// getMultipartSSEAlgorithm returns the canonical SSE algorithm ("AES256" or
|
||||
// "aws:kms") that was stored when the multipart upload was initiated, or ""
|
||||
// if the upload entry is not found or had no SSE. It is used by the bucket
|
||||
// policy engine to evaluate s3:x-amz-server-side-encryption conditions for
|
||||
// UploadPart and UploadPartCopy, which do not re-send the SSE header.
|
||||
func (s3a *S3ApiServer) getMultipartSSEAlgorithm(bucket, uploadID string) string {
|
||||
entry, err := s3a.getEntry(s3a.genUploadsFolder(bucket), uploadID)
|
||||
if err != nil || entry == nil || entry.Extended == nil {
|
||||
return ""
|
||||
}
|
||||
if _, ok := entry.Extended[s3_constants.SeaweedFSSSEKMSKeyID]; ok {
|
||||
return "aws:kms"
|
||||
}
|
||||
if _, ok := entry.Extended[s3_constants.SeaweedFSSSES3Encryption]; ok {
|
||||
return "AES256"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) genPartUploadPath(bucket, uploadID string, partID int) string {
|
||||
// Returns just the file path - no filer address needed
|
||||
// Upload traffic goes directly to volume servers, not through filer
|
||||
|
||||
@@ -140,7 +140,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
}
|
||||
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, fileBody, bucket, object, 1, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, fileBody, bucket, 1)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pquerna/cachecontrol/cacheobject"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
@@ -292,7 +293,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
dataReader = mimeDetect(r, dataReader)
|
||||
}
|
||||
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, object, 1, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, 1)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -312,42 +313,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
writeSuccessResponseEmpty(w, r)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) withObjectWriteLock(bucket, object string, preconditionFn func() s3err.ErrorCode, fn func() s3err.ErrorCode) s3err.ErrorCode {
|
||||
runPrecondition := func() s3err.ErrorCode {
|
||||
if preconditionFn == nil {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
return preconditionFn()
|
||||
}
|
||||
|
||||
if object == "" || s3a.newObjectWriteLock == nil {
|
||||
if errCode := runPrecondition(); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
return fn()
|
||||
}
|
||||
|
||||
lock := s3a.newObjectWriteLock(bucket, object)
|
||||
if lock == nil {
|
||||
if errCode := runPrecondition(); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
return fn()
|
||||
}
|
||||
defer func() {
|
||||
if err := lock.StopShortLivedLock(); err != nil {
|
||||
glog.Warningf("withObjectWriteLock: failed to release lock for %s/%s: %v", bucket, object, err)
|
||||
}
|
||||
}()
|
||||
|
||||
if errCode := runPrecondition(); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
|
||||
return fn()
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader io.Reader, bucket string, object string, partNumber int, afterCreate func(entry *filer_pb.Entry) s3err.ErrorCode) (etag string, code s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
|
||||
func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader io.Reader, bucket string, partNumber int) (etag string, code s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
|
||||
// NEW OPTIMIZATION: Write directly to volume servers, bypassing filer proxy
|
||||
// This eliminates the filer proxy overhead for PUT operations
|
||||
// Note: filePath is now passed directly instead of URL (no parsing needed)
|
||||
@@ -633,8 +599,12 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
// Store ETag in Extended attribute for future retrieval (e.g. multipart parts)
|
||||
entry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
// Set object owner according to bucket ownership settings.
|
||||
s3a.setObjectOwnerFromRequest(r, bucket, entry)
|
||||
// Set object owner
|
||||
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
|
||||
if amzAccountId != "" {
|
||||
entry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
glog.V(2).Infof("putToFiler: setting owner %s for object %s", amzAccountId, filePath)
|
||||
}
|
||||
|
||||
// Set version ID if present
|
||||
if versionIdHeader := r.Header.Get(s3_constants.ExtVersionIdKey); versionIdHeader != "" {
|
||||
@@ -642,16 +612,6 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
glog.V(3).Infof("putToFiler: setting version ID %s for object %s", versionIdHeader, filePath)
|
||||
}
|
||||
|
||||
for _, metadataHeader := range []string{
|
||||
s3_constants.ExtObjectLockModeKey,
|
||||
s3_constants.ExtRetentionUntilDateKey,
|
||||
s3_constants.ExtLegalHoldKey,
|
||||
} {
|
||||
if value := r.Header.Get(metadataHeader); value != "" {
|
||||
entry.Extended[metadataHeader] = []byte(value)
|
||||
}
|
||||
}
|
||||
|
||||
// Set TTL-based S3 expiry flag only if object has a TTL
|
||||
if entry.Attributes.TtlSec > 0 {
|
||||
entry.Extended[s3_constants.SeaweedFSExpiresS3] = []byte("true")
|
||||
@@ -738,59 +698,45 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
// Step 4: Save metadata to filer via gRPC
|
||||
// Use context.Background() to ensure metadata save completes even if HTTP request is cancelled
|
||||
// This matches the chunk upload behavior and prevents orphaned chunks
|
||||
//
|
||||
// If conditional headers are present, acquire a distributed lock to atomically
|
||||
// re-check conditions and create the entry. This prevents TOCTOU races where
|
||||
// concurrent requests all pass the early check before any write completes.
|
||||
condBucket, condObject := s3_constants.GetBucketAndObject(r)
|
||||
condLock, condErr := s3a.lockAndRecheckConditionalHeaders(r, condBucket, condObject)
|
||||
if condErr != s3err.ErrNone {
|
||||
s3a.deleteOrphanedChunks(chunkResult.FileChunks)
|
||||
return "", condErr, SSEResponseMetadata{}
|
||||
}
|
||||
if condLock != nil {
|
||||
defer condLock.StopShortLivedLock()
|
||||
}
|
||||
glog.V(3).Infof("putToFiler: About to create entry - dir=%s, name=%s, chunks=%d, extended keys=%d",
|
||||
path.Dir(filePath), path.Base(filePath), len(entry.Chunks), len(entry.Extended))
|
||||
var createErr error
|
||||
var rollbackErr error
|
||||
entryCreated := false
|
||||
preconditionFn := func() s3err.ErrorCode {
|
||||
if object == "" {
|
||||
return s3err.ErrNone
|
||||
createErr := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
req := &filer_pb.CreateEntryRequest{
|
||||
Directory: path.Dir(filePath),
|
||||
Entry: entry,
|
||||
}
|
||||
return s3a.checkConditionalHeaders(r, bucket, object)
|
||||
}
|
||||
createCode := s3a.withObjectWriteLock(bucket, object, preconditionFn, func() s3err.ErrorCode {
|
||||
createErr = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
req := &filer_pb.CreateEntryRequest{
|
||||
Directory: path.Dir(filePath),
|
||||
Entry: entry,
|
||||
}
|
||||
glog.V(3).Infof("putToFiler: Calling CreateEntry for %s", filePath)
|
||||
if err := filer_pb.CreateEntry(context.Background(), client, req); err != nil {
|
||||
glog.Errorf("putToFiler: CreateEntry returned error: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if createErr != nil {
|
||||
return filerErrorToS3Error(createErr)
|
||||
glog.V(3).Infof("putToFiler: Calling CreateEntry for %s", filePath)
|
||||
if err := filer_pb.CreateEntry(context.Background(), client, req); err != nil {
|
||||
glog.Errorf("putToFiler: CreateEntry returned error: %v", err)
|
||||
return err
|
||||
}
|
||||
entryCreated = true
|
||||
if afterCreate != nil {
|
||||
if afterCreateCode := afterCreate(entry); afterCreateCode != s3err.ErrNone {
|
||||
rollbackErr = s3a.rmObject(path.Dir(filePath), path.Base(filePath), true, false)
|
||||
if rollbackErr != nil {
|
||||
glog.Errorf("putToFiler: failed to rollback created entry for %s after post-create error: %v", filePath, rollbackErr)
|
||||
} else {
|
||||
entryCreated = false
|
||||
}
|
||||
return afterCreateCode
|
||||
}
|
||||
}
|
||||
return s3err.ErrNone
|
||||
return nil
|
||||
})
|
||||
if createCode != s3err.ErrNone {
|
||||
if createErr != nil {
|
||||
glog.Errorf("putToFiler: failed to create entry for %s: %v", filePath, createErr)
|
||||
}
|
||||
if createErr != nil {
|
||||
glog.Errorf("putToFiler: failed to create entry for %s: %v", filePath, createErr)
|
||||
|
||||
// If the entry was never created, the uploaded chunks are orphaned and must be deleted.
|
||||
if !entryCreated && len(chunkResult.FileChunks) > 0 {
|
||||
glog.Warningf("putToFiler: finalization failed, attempting to cleanup %d orphaned chunks", len(chunkResult.FileChunks))
|
||||
// CRITICAL: Cleanup orphaned chunks before returning error
|
||||
// If CreateEntry fails, the uploaded chunks are orphaned and must be deleted
|
||||
// to prevent resource leaks and wasted storage
|
||||
if len(chunkResult.FileChunks) > 0 {
|
||||
glog.Warningf("putToFiler: CreateEntry failed, attempting to cleanup %d orphaned chunks", len(chunkResult.FileChunks))
|
||||
s3a.deleteOrphanedChunks(chunkResult.FileChunks)
|
||||
}
|
||||
|
||||
return "", createCode, SSEResponseMetadata{}
|
||||
return "", filerErrorToS3Error(createErr), SSEResponseMetadata{}
|
||||
}
|
||||
glog.V(3).Infof("putToFiler: CreateEntry SUCCESS for %s", filePath)
|
||||
|
||||
@@ -1050,7 +996,7 @@ func (s3a *S3ApiServer) putSuspendedVersioningObject(r *http.Request, bucket, ob
|
||||
}
|
||||
|
||||
// Upload the file using putToFiler - this will create the file with version metadata
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, nil)
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, 1)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("putSuspendedVersioningObject: failed to upload object: %v", errCode)
|
||||
return "", errCode, SSEResponseMetadata{}
|
||||
@@ -1156,6 +1102,8 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
|
||||
// We need to construct the object path relative to the bucket
|
||||
versionObjectPath := normalizedObject + s3_constants.VersionsFolder + "/" + versionFileName
|
||||
versionFilePath := s3a.toFilerPath(bucket, versionObjectPath)
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
|
||||
body := dataReader
|
||||
if objectContentType == "" {
|
||||
body = mimeDetect(r, body)
|
||||
@@ -1163,55 +1111,71 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
|
||||
|
||||
glog.V(2).Infof("putVersionedObject: uploading %s/%s version %s to %s", bucket, object, versionId, versionFilePath)
|
||||
|
||||
r.Header.Set(s3_constants.ExtVersionIdKey, versionId)
|
||||
defer r.Header.Del(s3_constants.ExtVersionIdKey)
|
||||
|
||||
explicitMode := r.Header.Get(s3_constants.AmzObjectLockMode)
|
||||
explicitRetainUntilDate := r.Header.Get(s3_constants.AmzObjectLockRetainUntilDate)
|
||||
|
||||
if explicitMode != "" {
|
||||
r.Header.Set(s3_constants.ExtObjectLockModeKey, explicitMode)
|
||||
defer r.Header.Del(s3_constants.ExtObjectLockModeKey)
|
||||
}
|
||||
if explicitRetainUntilDate != "" {
|
||||
parsedTime, parseErr := time.Parse(time.RFC3339, explicitRetainUntilDate)
|
||||
if parseErr != nil {
|
||||
glog.Errorf("putVersionedObject: failed to parse retention until date: %v", parseErr)
|
||||
return "", "", s3err.ErrInvalidRequest, SSEResponseMetadata{}
|
||||
}
|
||||
r.Header.Set(s3_constants.ExtRetentionUntilDateKey, strconv.FormatInt(parsedTime.Unix(), 10))
|
||||
defer r.Header.Del(s3_constants.ExtRetentionUntilDateKey)
|
||||
}
|
||||
if legalHold := r.Header.Get(s3_constants.AmzObjectLockLegalHold); legalHold != "" {
|
||||
r.Header.Set(s3_constants.ExtLegalHoldKey, legalHold)
|
||||
defer r.Header.Del(s3_constants.ExtLegalHoldKey)
|
||||
}
|
||||
if explicitMode == "" && explicitRetainUntilDate == "" {
|
||||
tempEntry := &filer_pb.Entry{Extended: make(map[string][]byte)}
|
||||
if err := s3a.applyBucketDefaultRetention(bucket, tempEntry); err == nil {
|
||||
if modeBytes, ok := tempEntry.Extended[s3_constants.ExtObjectLockModeKey]; ok {
|
||||
r.Header.Set(s3_constants.ExtObjectLockModeKey, string(modeBytes))
|
||||
defer r.Header.Del(s3_constants.ExtObjectLockModeKey)
|
||||
}
|
||||
if dateBytes, ok := tempEntry.Extended[s3_constants.ExtRetentionUntilDateKey]; ok {
|
||||
r.Header.Set(s3_constants.ExtRetentionUntilDateKey, string(dateBytes))
|
||||
defer r.Header.Del(s3_constants.ExtRetentionUntilDateKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, versionFilePath, body, bucket, normalizedObject, 1, func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateLatestVersionInDirectory(bucket, normalizedObject, versionId, versionFileName, versionEntry); err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, versionFilePath, body, bucket, 1)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("putVersionedObject: failed to upload version: %v", errCode)
|
||||
return "", "", errCode, SSEResponseMetadata{}
|
||||
}
|
||||
|
||||
// Get the uploaded entry to add versioning metadata
|
||||
// Use retry logic to handle filer consistency delays
|
||||
var versionEntry *filer_pb.Entry
|
||||
var err error
|
||||
maxRetries := 8
|
||||
for attempt := 1; attempt <= maxRetries; attempt++ {
|
||||
versionEntry, err = s3a.getEntry(bucketDir, versionObjectPath)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
if attempt < maxRetries {
|
||||
// Exponential backoff: 10ms, 20ms, 40ms, 80ms, 160ms, 320ms, 640ms
|
||||
delay := time.Millisecond * time.Duration(10*(1<<(attempt-1)))
|
||||
time.Sleep(delay)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to get version entry after %d attempts: %v", maxRetries, err)
|
||||
return "", "", s3err.ErrInternalError, SSEResponseMetadata{}
|
||||
}
|
||||
|
||||
// Add versioning metadata to this version
|
||||
if versionEntry.Extended == nil {
|
||||
versionEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
versionEntry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionId)
|
||||
|
||||
// Store ETag (unquoted) in Extended attribute
|
||||
versionEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
// Set object owner for versioned objects
|
||||
s3a.setObjectOwnerFromRequest(r, bucket, versionEntry)
|
||||
|
||||
// Extract and store object lock metadata from request headers
|
||||
if err := s3a.extractObjectLockMetadataFromRequest(r, versionEntry); err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to extract object lock metadata: %v", err)
|
||||
return "", "", s3err.ErrInvalidRequest, SSEResponseMetadata{}
|
||||
}
|
||||
|
||||
// Update the version entry with metadata
|
||||
err = s3a.mkFile(bucketDir, versionObjectPath, versionEntry.Chunks, func(updatedEntry *filer_pb.Entry) {
|
||||
updatedEntry.Extended = versionEntry.Extended
|
||||
updatedEntry.Attributes = versionEntry.Attributes
|
||||
updatedEntry.Chunks = versionEntry.Chunks
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to update version metadata: %v", err)
|
||||
return "", "", s3err.ErrInternalError, SSEResponseMetadata{}
|
||||
}
|
||||
|
||||
// Update the .versions directory metadata to indicate this is the latest version
|
||||
// Pass versionEntry to cache its metadata for single-scan list efficiency
|
||||
err = s3a.updateLatestVersionInDirectory(bucket, normalizedObject, versionId, versionFileName, versionEntry)
|
||||
if err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
|
||||
return "", "", s3err.ErrInternalError, SSEResponseMetadata{}
|
||||
}
|
||||
glog.V(2).Infof("putVersionedObject: successfully created version %s for %s/%s (normalized: %s)", versionId, bucket, object, normalizedObject)
|
||||
return versionId, etag, s3err.ErrNone, sseMetadata
|
||||
}
|
||||
@@ -1735,25 +1699,12 @@ func (s3a *S3ApiServer) etagMatches(headerValue, objectETag string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func normalizeConditionalTargetEntry(entry *filer_pb.Entry) *filer_pb.Entry {
|
||||
if entry == nil {
|
||||
return nil
|
||||
}
|
||||
if entry.Extended != nil {
|
||||
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
// validateConditionalHeaders checks conditional headers against the provided entry
|
||||
func (s3a *S3ApiServer) validateConditionalHeaders(r *http.Request, headers conditionalHeaders, entry *filer_pb.Entry, bucket, object string) s3err.ErrorCode {
|
||||
if !headers.isSet {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
entry = normalizeConditionalTargetEntry(entry)
|
||||
objectExists := entry != nil
|
||||
|
||||
// For PUT requests, all specified conditions must be met.
|
||||
@@ -1875,7 +1826,7 @@ func (s3a *S3ApiServer) checkConditionalHeaders(r *http.Request, bucket, object
|
||||
// This ensures we check conditions against the LATEST version, not a null version.
|
||||
entry, err := s3a.resolveObjectEntry(bucket, object)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrDeleteMarker) {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
entry = nil
|
||||
} else {
|
||||
glog.Errorf("checkConditionalHeaders: error resolving object entry for %s/%s: %v", bucket, object, err)
|
||||
@@ -1885,13 +1836,49 @@ func (s3a *S3ApiServer) checkConditionalHeaders(r *http.Request, bucket, object
|
||||
return s3a.validateConditionalHeaders(r, headers, entry, bucket, object)
|
||||
}
|
||||
|
||||
// lockAndRecheckConditionalHeaders acquires a distributed lock and re-checks conditional
|
||||
// headers atomically before a write operation. This prevents TOCTOU races where concurrent
|
||||
// requests could all pass the early (unlocked) check before any write completes.
|
||||
//
|
||||
// Returns (nil, ErrNone) if no conditional headers are present (no lock needed).
|
||||
// Returns (lock, ErrNone) if the re-check passes — the caller MUST defer lock.StopShortLivedLock()
|
||||
// to hold the lock across the subsequent write and release it after.
|
||||
// Returns (nil, errCode) if the re-check fails — no lock to release.
|
||||
func (s3a *S3ApiServer) lockAndRecheckConditionalHeaders(r *http.Request, bucket, object string) (*cluster.LiveLock, s3err.ErrorCode) {
|
||||
headers, errCode := parseConditionalHeaders(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
return nil, errCode
|
||||
}
|
||||
if !headers.isSet {
|
||||
return nil, s3err.ErrNone
|
||||
}
|
||||
|
||||
lockKey := s3a.toFilerPath(bucket, object)
|
||||
lock := s3a.lockClient.NewShortLivedLock(lockKey, fmt.Sprintf("s3-cond-%d", s3a.randomClientId))
|
||||
|
||||
entry, err := s3a.resolveObjectEntry(bucket, object)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
entry = nil
|
||||
} else {
|
||||
lock.StopShortLivedLock()
|
||||
glog.Errorf("lockAndRecheckConditionalHeaders: error resolving object entry for %s/%s: %v", bucket, object, err)
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
}
|
||||
if errCode = s3a.validateConditionalHeaders(r, headers, entry, bucket, object); errCode != s3err.ErrNone {
|
||||
lock.StopShortLivedLock()
|
||||
return nil, errCode
|
||||
}
|
||||
return lock, s3err.ErrNone
|
||||
}
|
||||
|
||||
// validateConditionalHeadersForReads checks conditional headers for read operations against the provided entry
|
||||
func (s3a *S3ApiServer) validateConditionalHeadersForReads(r *http.Request, headers conditionalHeaders, entry *filer_pb.Entry, bucket, object string) ConditionalHeaderResult {
|
||||
if !headers.isSet {
|
||||
return ConditionalHeaderResult{ErrorCode: s3err.ErrNone, Entry: entry}
|
||||
}
|
||||
|
||||
entry = normalizeConditionalTargetEntry(entry)
|
||||
objectExists := entry != nil
|
||||
|
||||
// If object doesn't exist, fail for If-Match and If-Unmodified-Since
|
||||
@@ -2018,7 +2005,7 @@ func (s3a *S3ApiServer) checkConditionalHeadersForReads(r *http.Request, bucket,
|
||||
// This ensures we check conditions against the LATEST version, not a null version.
|
||||
entry, err := s3a.resolveObjectEntry(bucket, object)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrDeleteMarker) {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
entry = nil
|
||||
} else {
|
||||
glog.Errorf("checkConditionalHeadersForReads: error resolving object entry for %s/%s: %v", bucket, object, err)
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
@@ -200,104 +199,3 @@ func TestNewMultipartUploadHandler_KeyTooLong(t *testing.T) {
|
||||
t.Errorf("expected error code KeyTooLongError, got %s", errResp.Code)
|
||||
}
|
||||
}
|
||||
|
||||
type testObjectWriteLockFactory struct {
|
||||
mu sync.Mutex
|
||||
locks map[string]*sync.Mutex
|
||||
}
|
||||
|
||||
func (f *testObjectWriteLockFactory) newLock(bucket, object string) objectWriteLock {
|
||||
key := bucket + "|" + object
|
||||
|
||||
f.mu.Lock()
|
||||
lock, ok := f.locks[key]
|
||||
if !ok {
|
||||
lock = &sync.Mutex{}
|
||||
f.locks[key] = lock
|
||||
}
|
||||
f.mu.Unlock()
|
||||
|
||||
lock.Lock()
|
||||
return &testObjectWriteLock{unlock: lock.Unlock}
|
||||
}
|
||||
|
||||
type testObjectWriteLock struct {
|
||||
once sync.Once
|
||||
unlock func()
|
||||
}
|
||||
|
||||
func (l *testObjectWriteLock) StopShortLivedLock() error {
|
||||
l.once.Do(l.unlock)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestWithObjectWriteLockSerializesConcurrentPreconditions(t *testing.T) {
|
||||
s3a := NewS3ApiServerForTest()
|
||||
lockFactory := &testObjectWriteLockFactory{
|
||||
locks: make(map[string]*sync.Mutex),
|
||||
}
|
||||
s3a.newObjectWriteLock = lockFactory.newLock
|
||||
|
||||
const workers = 3
|
||||
const bucket = "test-bucket"
|
||||
const object = "/file.txt"
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan s3err.ErrorCode, workers)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
var stateMu sync.Mutex
|
||||
objectExists := false
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
errCode := s3a.withObjectWriteLock(bucket, object,
|
||||
func() s3err.ErrorCode {
|
||||
stateMu.Lock()
|
||||
defer stateMu.Unlock()
|
||||
if objectExists {
|
||||
return s3err.ErrPreconditionFailed
|
||||
}
|
||||
return s3err.ErrNone
|
||||
},
|
||||
func() s3err.ErrorCode {
|
||||
stateMu.Lock()
|
||||
defer stateMu.Unlock()
|
||||
objectExists = true
|
||||
return s3err.ErrNone
|
||||
},
|
||||
)
|
||||
|
||||
results <- errCode
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
var successCount int
|
||||
var preconditionFailedCount int
|
||||
|
||||
for errCode := range results {
|
||||
switch errCode {
|
||||
case s3err.ErrNone:
|
||||
successCount++
|
||||
case s3err.ErrPreconditionFailed:
|
||||
preconditionFailedCount++
|
||||
default:
|
||||
t.Fatalf("unexpected error code: %v", errCode)
|
||||
}
|
||||
}
|
||||
|
||||
if successCount != 1 {
|
||||
t.Fatalf("expected exactly one successful writer, got %d", successCount)
|
||||
}
|
||||
if preconditionFailedCount != workers-1 {
|
||||
t.Fatalf("expected %d precondition failures, got %d", workers-1, preconditionFailedCount)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,22 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// mockAccountManager implements AccountManager for testing
|
||||
type mockAccountManager struct {
|
||||
accounts map[string]string
|
||||
}
|
||||
|
||||
func (m *mockAccountManager) GetAccountNameById(id string) string {
|
||||
if name, exists := m.accounts[id]; exists {
|
||||
return name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *mockAccountManager) GetAccountIdByEmail(email string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestNewListEntryOwnerDisplayName(t *testing.T) {
|
||||
// Create S3ApiServer with a properly initialized IAM
|
||||
s3a := &S3ApiServer{
|
||||
|
||||
@@ -463,6 +463,24 @@ func (s3a *S3ApiServer) setObjectLegalHold(bucket, object, versionId string, leg
|
||||
// PROTECTION ENFORCEMENT
|
||||
// ====================================================================
|
||||
|
||||
// isObjectRetentionActive checks if object has active retention
|
||||
func (s3a *S3ApiServer) isObjectRetentionActive(bucket, object, versionId string) (bool, error) {
|
||||
retention, err := s3a.getObjectRetention(bucket, object, versionId)
|
||||
if err != nil {
|
||||
// If no retention found, object is not under retention
|
||||
if errors.Is(err, ErrNoRetentionConfiguration) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
if retention.RetainUntilDate != nil && retention.RetainUntilDate.After(time.Now()) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// getRetentionFromEntry extracts retention configuration from filer entry
|
||||
func (s3a *S3ApiServer) getRetentionFromEntry(entry *filer_pb.Entry) (*ObjectRetention, bool, error) {
|
||||
if entry.Extended == nil {
|
||||
|
||||
@@ -72,6 +72,16 @@ func setCachedListMetadata(versionsEntry, versionEntry *filer_pb.Entry) {
|
||||
}
|
||||
}
|
||||
|
||||
// clearCachedListMetadata removes all cached list metadata from the .versions directory entry
|
||||
func clearCachedListMetadata(extended map[string][]byte) {
|
||||
if extended == nil {
|
||||
return
|
||||
}
|
||||
delete(extended, s3_constants.ExtLatestVersionIdKey)
|
||||
delete(extended, s3_constants.ExtLatestVersionFileNameKey)
|
||||
clearCachedVersionMetadata(extended)
|
||||
}
|
||||
|
||||
// S3ListObjectVersionsResult - Custom struct for S3 list-object-versions response.
|
||||
// This avoids conflicts with the XSD generated ListVersionsResult struct.
|
||||
//
|
||||
|
||||
+12
-201
@@ -22,16 +22,13 @@ type Lifecycle struct {
|
||||
|
||||
// Rule - a rule for lifecycle configuration.
|
||||
type Rule struct {
|
||||
XMLName xml.Name `xml:"Rule"`
|
||||
ID string `xml:"ID,omitempty"`
|
||||
Status ruleStatus `xml:"Status"`
|
||||
Filter Filter `xml:"Filter,omitempty"`
|
||||
Prefix Prefix `xml:"Prefix,omitempty"`
|
||||
Expiration Expiration `xml:"Expiration,omitempty"`
|
||||
Transition Transition `xml:"Transition,omitempty"`
|
||||
NoncurrentVersionExpiration NoncurrentVersionExpiration `xml:"NoncurrentVersionExpiration,omitempty"`
|
||||
NoncurrentVersionTransition NoncurrentVersionTransition `xml:"NoncurrentVersionTransition,omitempty"`
|
||||
AbortIncompleteMultipartUpload AbortIncompleteMultipartUpload `xml:"AbortIncompleteMultipartUpload,omitempty"`
|
||||
XMLName xml.Name `xml:"Rule"`
|
||||
ID string `xml:"ID,omitempty"`
|
||||
Status ruleStatus `xml:"Status"`
|
||||
Filter Filter `xml:"Filter,omitempty"`
|
||||
Prefix Prefix `xml:"Prefix,omitempty"`
|
||||
Expiration Expiration `xml:"Expiration,omitempty"`
|
||||
Transition Transition `xml:"Transition,omitempty"`
|
||||
}
|
||||
|
||||
// Filter - a filter for a lifecycle configuration Rule.
|
||||
@@ -46,9 +43,6 @@ type Filter struct {
|
||||
|
||||
Tag Tag
|
||||
tagSet bool
|
||||
|
||||
ObjectSizeGreaterThan int64
|
||||
ObjectSizeLessThan int64
|
||||
}
|
||||
|
||||
// Prefix holds the prefix xml tag in <Rule> and <Filter>
|
||||
@@ -86,83 +80,17 @@ func (f Filter) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
||||
if err := e.EncodeToken(start); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.andSet {
|
||||
if err := e.EncodeElement(f.And, xml.StartElement{Name: xml.Name{Local: "And"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if f.tagSet {
|
||||
if err := e.EncodeElement(f.Tag, xml.StartElement{Name: xml.Name{Local: "Tag"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := e.EncodeElement(f.Prefix, xml.StartElement{Name: xml.Name{Local: "Prefix"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if f.ObjectSizeGreaterThan > 0 {
|
||||
if err := e.EncodeElement(f.ObjectSizeGreaterThan, xml.StartElement{Name: xml.Name{Local: "ObjectSizeGreaterThan"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if f.ObjectSizeLessThan > 0 {
|
||||
if err := e.EncodeElement(f.ObjectSizeLessThan, xml.StartElement{Name: xml.Name{Local: "ObjectSizeLessThan"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := e.EncodeElement(f.Prefix, xml.StartElement{Name: xml.Name{Local: "Prefix"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
return e.EncodeToken(xml.EndElement{Name: start.Name})
|
||||
}
|
||||
|
||||
// UnmarshalXML decodes Filter from XML, handling all child elements.
|
||||
func (f *Filter) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
f.set = true
|
||||
for {
|
||||
tok, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch t := tok.(type) {
|
||||
case xml.StartElement:
|
||||
switch t.Name.Local {
|
||||
case "Prefix":
|
||||
if err := d.DecodeElement(&f.Prefix, &t); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Tag":
|
||||
f.tagSet = true
|
||||
if err := d.DecodeElement(&f.Tag, &t); err != nil {
|
||||
return err
|
||||
}
|
||||
case "And":
|
||||
f.andSet = true
|
||||
if err := d.DecodeElement(&f.And, &t); err != nil {
|
||||
return err
|
||||
}
|
||||
case "ObjectSizeGreaterThan":
|
||||
if err := d.DecodeElement(&f.ObjectSizeGreaterThan, &t); err != nil {
|
||||
return err
|
||||
}
|
||||
case "ObjectSizeLessThan":
|
||||
if err := d.DecodeElement(&f.ObjectSizeLessThan, &t); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
if err := d.Skip(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case xml.EndElement:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// And - a tag to combine a prefix and multiple tags for lifecycle configuration rule.
|
||||
type And struct {
|
||||
XMLName xml.Name `xml:"And"`
|
||||
Prefix Prefix `xml:"Prefix,omitempty"`
|
||||
Tags []Tag `xml:"Tag,omitempty"`
|
||||
ObjectSizeGreaterThan int64 `xml:"ObjectSizeGreaterThan,omitempty"`
|
||||
ObjectSizeLessThan int64 `xml:"ObjectSizeLessThan,omitempty"`
|
||||
XMLName xml.Name `xml:"And"`
|
||||
Prefix Prefix `xml:"Prefix,omitempty"`
|
||||
Tags []Tag `xml:"Tag,omitempty"`
|
||||
}
|
||||
|
||||
// Expiration - expiration actions for a rule in lifecycle configuration.
|
||||
@@ -184,17 +112,6 @@ func (e Expiration) MarshalXML(enc *xml.Encoder, startElement xml.StartElement)
|
||||
return enc.EncodeElement(expirationWrapper(e), startElement)
|
||||
}
|
||||
|
||||
func (e *Expiration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
type wrapper Expiration
|
||||
var w wrapper
|
||||
if err := d.DecodeElement(&w, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
*e = Expiration(w)
|
||||
e.set = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExpireDeleteMarker represents value of ExpiredObjectDeleteMarker field in Expiration XML element.
|
||||
type ExpireDeleteMarker struct {
|
||||
val bool
|
||||
@@ -209,15 +126,6 @@ func (b ExpireDeleteMarker) MarshalXML(e *xml.Encoder, startElement xml.StartEle
|
||||
return e.EncodeElement(b.val, startElement)
|
||||
}
|
||||
|
||||
func (b *ExpireDeleteMarker) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
var v bool
|
||||
if err := d.DecodeElement(&v, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
*b = ExpireDeleteMarker{val: v, set: true}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExpirationDate is a embedded type containing time.Time to unmarshal
|
||||
// Date in Expiration
|
||||
type ExpirationDate struct {
|
||||
@@ -252,102 +160,5 @@ func (t Transition) MarshalXML(enc *xml.Encoder, start xml.StartElement) error {
|
||||
return enc.EncodeElement(transitionWrapper(t), start)
|
||||
}
|
||||
|
||||
func (t *Transition) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
type wrapper Transition
|
||||
var w wrapper
|
||||
if err := d.DecodeElement(&w, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = Transition(w)
|
||||
t.set = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// TransitionDays is a type alias to unmarshal Days in Transition
|
||||
type TransitionDays int
|
||||
|
||||
// NoncurrentVersionExpiration - expiration actions for non-current object versions.
|
||||
type NoncurrentVersionExpiration struct {
|
||||
XMLName xml.Name `xml:"NoncurrentVersionExpiration"`
|
||||
NoncurrentDays int `xml:"NoncurrentDays,omitempty"`
|
||||
NewerNoncurrentVersions int `xml:"NewerNoncurrentVersions,omitempty"`
|
||||
|
||||
set bool
|
||||
}
|
||||
|
||||
// MarshalXML encodes NoncurrentVersionExpiration field into an XML form.
|
||||
func (n NoncurrentVersionExpiration) MarshalXML(enc *xml.Encoder, start xml.StartElement) error {
|
||||
if !n.set {
|
||||
return nil
|
||||
}
|
||||
type wrapper NoncurrentVersionExpiration
|
||||
return enc.EncodeElement(wrapper(n), start)
|
||||
}
|
||||
|
||||
func (n *NoncurrentVersionExpiration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
type wrapper NoncurrentVersionExpiration
|
||||
var w wrapper
|
||||
if err := d.DecodeElement(&w, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
*n = NoncurrentVersionExpiration(w)
|
||||
n.set = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// NoncurrentVersionTransition - transition actions for non-current object versions.
|
||||
type NoncurrentVersionTransition struct {
|
||||
XMLName xml.Name `xml:"NoncurrentVersionTransition"`
|
||||
NoncurrentDays int `xml:"NoncurrentDays,omitempty"`
|
||||
StorageClass string `xml:"StorageClass,omitempty"`
|
||||
|
||||
set bool
|
||||
}
|
||||
|
||||
// MarshalXML encodes NoncurrentVersionTransition field into an XML form.
|
||||
func (n NoncurrentVersionTransition) MarshalXML(enc *xml.Encoder, start xml.StartElement) error {
|
||||
if !n.set {
|
||||
return nil
|
||||
}
|
||||
type wrapper NoncurrentVersionTransition
|
||||
return enc.EncodeElement(wrapper(n), start)
|
||||
}
|
||||
|
||||
func (n *NoncurrentVersionTransition) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
type wrapper NoncurrentVersionTransition
|
||||
var w wrapper
|
||||
if err := d.DecodeElement(&w, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
*n = NoncurrentVersionTransition(w)
|
||||
n.set = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// AbortIncompleteMultipartUpload - abort action for incomplete multipart uploads.
|
||||
type AbortIncompleteMultipartUpload struct {
|
||||
XMLName xml.Name `xml:"AbortIncompleteMultipartUpload"`
|
||||
DaysAfterInitiation int `xml:"DaysAfterInitiation,omitempty"`
|
||||
|
||||
set bool
|
||||
}
|
||||
|
||||
// MarshalXML encodes AbortIncompleteMultipartUpload field into an XML form.
|
||||
func (a AbortIncompleteMultipartUpload) MarshalXML(enc *xml.Encoder, start xml.StartElement) error {
|
||||
if !a.set {
|
||||
return nil
|
||||
}
|
||||
type wrapper AbortIncompleteMultipartUpload
|
||||
return enc.EncodeElement(wrapper(a), start)
|
||||
}
|
||||
|
||||
func (a *AbortIncompleteMultipartUpload) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
type wrapper AbortIncompleteMultipartUpload
|
||||
var w wrapper
|
||||
if err := d.DecodeElement(&w, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
*a = AbortIncompleteMultipartUpload(w)
|
||||
a.set = true
|
||||
return nil
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLifecycleXMLRoundTrip_NoncurrentVersionExpiration(t *testing.T) {
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>expire-noncurrent</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<NoncurrentVersionExpiration>
|
||||
<NoncurrentDays>30</NoncurrentDays>
|
||||
<NewerNoncurrentVersions>2</NewerNoncurrentVersions>
|
||||
</NoncurrentVersionExpiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
if len(lc.Rules) != 1 {
|
||||
t.Fatalf("expected 1 rule, got %d", len(lc.Rules))
|
||||
}
|
||||
rule := lc.Rules[0]
|
||||
if rule.ID != "expire-noncurrent" {
|
||||
t.Errorf("expected ID 'expire-noncurrent', got %q", rule.ID)
|
||||
}
|
||||
if rule.NoncurrentVersionExpiration.NoncurrentDays != 30 {
|
||||
t.Errorf("expected NoncurrentDays=30, got %d", rule.NoncurrentVersionExpiration.NoncurrentDays)
|
||||
}
|
||||
if rule.NoncurrentVersionExpiration.NewerNoncurrentVersions != 2 {
|
||||
t.Errorf("expected NewerNoncurrentVersions=2, got %d", rule.NoncurrentVersionExpiration.NewerNoncurrentVersions)
|
||||
}
|
||||
|
||||
// Re-marshal and verify it round-trips.
|
||||
out, err := xml.Marshal(lc)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
s := string(out)
|
||||
if !strings.Contains(s, "<NoncurrentDays>30</NoncurrentDays>") {
|
||||
t.Errorf("marshaled XML missing NoncurrentDays: %s", s)
|
||||
}
|
||||
if !strings.Contains(s, "<NewerNoncurrentVersions>2</NewerNoncurrentVersions>") {
|
||||
t.Errorf("marshaled XML missing NewerNoncurrentVersions: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleXMLRoundTrip_AbortIncompleteMultipartUpload(t *testing.T) {
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>abort-mpu</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<AbortIncompleteMultipartUpload>
|
||||
<DaysAfterInitiation>7</DaysAfterInitiation>
|
||||
</AbortIncompleteMultipartUpload>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
rule := lc.Rules[0]
|
||||
if rule.AbortIncompleteMultipartUpload.DaysAfterInitiation != 7 {
|
||||
t.Errorf("expected DaysAfterInitiation=7, got %d", rule.AbortIncompleteMultipartUpload.DaysAfterInitiation)
|
||||
}
|
||||
|
||||
out, err := xml.Marshal(lc)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(out), "<DaysAfterInitiation>7</DaysAfterInitiation>") {
|
||||
t.Errorf("marshaled XML missing DaysAfterInitiation: %s", string(out))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleXMLRoundTrip_FilterWithTag(t *testing.T) {
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>tag-filter</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter>
|
||||
<Tag><Key>env</Key><Value>dev</Value></Tag>
|
||||
</Filter>
|
||||
<Expiration><Days>7</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
rule := lc.Rules[0]
|
||||
if !rule.Filter.tagSet {
|
||||
t.Error("expected Filter.tagSet to be true")
|
||||
}
|
||||
if rule.Filter.Tag.Key != "env" || rule.Filter.Tag.Value != "dev" {
|
||||
t.Errorf("expected Tag{env:dev}, got Tag{%s:%s}", rule.Filter.Tag.Key, rule.Filter.Tag.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleXMLRoundTrip_FilterWithAnd(t *testing.T) {
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>and-filter</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter>
|
||||
<And>
|
||||
<Prefix>logs/</Prefix>
|
||||
<Tag><Key>env</Key><Value>dev</Value></Tag>
|
||||
<Tag><Key>tier</Key><Value>hot</Value></Tag>
|
||||
<ObjectSizeGreaterThan>1024</ObjectSizeGreaterThan>
|
||||
<ObjectSizeLessThan>1048576</ObjectSizeLessThan>
|
||||
</And>
|
||||
</Filter>
|
||||
<Expiration><Days>7</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
rule := lc.Rules[0]
|
||||
if !rule.Filter.andSet {
|
||||
t.Error("expected Filter.andSet to be true")
|
||||
}
|
||||
if rule.Filter.And.Prefix.String() != "logs/" {
|
||||
t.Errorf("expected And.Prefix='logs/', got %q", rule.Filter.And.Prefix.String())
|
||||
}
|
||||
if len(rule.Filter.And.Tags) != 2 {
|
||||
t.Fatalf("expected 2 And tags, got %d", len(rule.Filter.And.Tags))
|
||||
}
|
||||
if rule.Filter.And.ObjectSizeGreaterThan != 1024 {
|
||||
t.Errorf("expected ObjectSizeGreaterThan=1024, got %d", rule.Filter.And.ObjectSizeGreaterThan)
|
||||
}
|
||||
if rule.Filter.And.ObjectSizeLessThan != 1048576 {
|
||||
t.Errorf("expected ObjectSizeLessThan=1048576, got %d", rule.Filter.And.ObjectSizeLessThan)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleXMLRoundTrip_FilterWithSizeOnly(t *testing.T) {
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>size-filter</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter>
|
||||
<ObjectSizeGreaterThan>512</ObjectSizeGreaterThan>
|
||||
<ObjectSizeLessThan>10485760</ObjectSizeLessThan>
|
||||
</Filter>
|
||||
<Expiration><Days>30</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
rule := lc.Rules[0]
|
||||
if rule.Filter.ObjectSizeGreaterThan != 512 {
|
||||
t.Errorf("expected ObjectSizeGreaterThan=512, got %d", rule.Filter.ObjectSizeGreaterThan)
|
||||
}
|
||||
if rule.Filter.ObjectSizeLessThan != 10485760 {
|
||||
t.Errorf("expected ObjectSizeLessThan=10485760, got %d", rule.Filter.ObjectSizeLessThan)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleXML_TransitionSetFlag(t *testing.T) {
|
||||
// Verify that Transition.set is true after unmarshaling.
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>transition</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<Transition>
|
||||
<Days>30</Days>
|
||||
<StorageClass>GLACIER</StorageClass>
|
||||
</Transition>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if !lc.Rules[0].Transition.set {
|
||||
t.Error("expected Transition.set=true after unmarshal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleXML_NoncurrentVersionTransitionSetFlag(t *testing.T) {
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>nv-transition</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<NoncurrentVersionTransition>
|
||||
<NoncurrentDays>60</NoncurrentDays>
|
||||
<StorageClass>GLACIER</StorageClass>
|
||||
</NoncurrentVersionTransition>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if !lc.Rules[0].NoncurrentVersionTransition.set {
|
||||
t.Error("expected NoncurrentVersionTransition.set=true after unmarshal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleXMLRoundTrip_CompleteRule(t *testing.T) {
|
||||
// A complete lifecycle config similar to what Terraform sends.
|
||||
input := `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>rotation</ID>
|
||||
<Filter><Prefix></Prefix></Filter>
|
||||
<Status>Enabled</Status>
|
||||
<Expiration><Days>30</Days></Expiration>
|
||||
<NoncurrentVersionExpiration>
|
||||
<NoncurrentDays>1</NoncurrentDays>
|
||||
</NoncurrentVersionExpiration>
|
||||
<AbortIncompleteMultipartUpload>
|
||||
<DaysAfterInitiation>1</DaysAfterInitiation>
|
||||
</AbortIncompleteMultipartUpload>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
var lc Lifecycle
|
||||
if err := xml.Unmarshal([]byte(input), &lc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
rule := lc.Rules[0]
|
||||
if rule.ID != "rotation" {
|
||||
t.Errorf("expected ID 'rotation', got %q", rule.ID)
|
||||
}
|
||||
if rule.Expiration.Days != 30 {
|
||||
t.Errorf("expected Expiration.Days=30, got %d", rule.Expiration.Days)
|
||||
}
|
||||
if rule.NoncurrentVersionExpiration.NoncurrentDays != 1 {
|
||||
t.Errorf("expected NoncurrentDays=1, got %d", rule.NoncurrentVersionExpiration.NoncurrentDays)
|
||||
}
|
||||
if rule.AbortIncompleteMultipartUpload.DaysAfterInitiation != 1 {
|
||||
t.Errorf("expected DaysAfterInitiation=1, got %d", rule.AbortIncompleteMultipartUpload.DaysAfterInitiation)
|
||||
}
|
||||
|
||||
// Re-marshal and verify all fields survive.
|
||||
out, err := xml.Marshal(lc)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
s := string(out)
|
||||
for _, expected := range []string{
|
||||
"<Days>30</Days>",
|
||||
"<NoncurrentDays>1</NoncurrentDays>",
|
||||
"<DaysAfterInitiation>1</DaysAfterInitiation>",
|
||||
} {
|
||||
if !strings.Contains(s, expected) {
|
||||
t.Errorf("marshaled XML missing %q: %s", expected, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,20 @@ type PutToFilerEncryptionResult struct {
|
||||
SSES3Metadata []byte
|
||||
}
|
||||
|
||||
// calculatePartOffset calculates unique offset for each part to prevent IV reuse in multipart uploads
|
||||
// AWS S3 part numbers must start from 1, never 0 or negative
|
||||
func calculatePartOffset(partNumber int) int64 {
|
||||
// AWS S3 part numbers must start from 1, never 0 or negative
|
||||
if partNumber < 1 {
|
||||
glog.Errorf("Invalid partNumber: %d. Must be >= 1.", partNumber)
|
||||
return 0
|
||||
}
|
||||
// Using a large multiplier to ensure block offsets for different parts do not overlap.
|
||||
// S3 part size limit is 5GB, so this provides a large safety margin.
|
||||
partOffset := int64(partNumber-1) * s3_constants.PartOffsetMultiplier
|
||||
return partOffset
|
||||
}
|
||||
|
||||
// handleSSECEncryption processes SSE-C encryption for the data reader
|
||||
func (s3a *S3ApiServer) handleSSECEncryption(r *http.Request, dataReader io.Reader) (io.Reader, *SSECustomerKey, []byte, s3err.ErrorCode) {
|
||||
// Handle SSE-C encryption if requested
|
||||
|
||||
@@ -82,17 +82,9 @@ type S3ApiServer struct {
|
||||
embeddedIam *EmbeddedIamApi // Embedded IAM API server (when enabled)
|
||||
stsHandlers *STSHandlers // STS HTTP handlers for AssumeRoleWithWebIdentity
|
||||
cipher bool // encrypt data on volume servers
|
||||
newObjectWriteLock func(bucket, object string) objectWriteLock
|
||||
lockClient *cluster.LockClient
|
||||
}
|
||||
|
||||
type objectWriteLock interface {
|
||||
StopShortLivedLock() error
|
||||
}
|
||||
|
||||
const (
|
||||
objectWriteLockTTL = 15 * time.Second
|
||||
)
|
||||
|
||||
func NewS3ApiServer(router *mux.Router, option *S3ApiServerOption) (s3ApiServer *S3ApiServer, err error) {
|
||||
return NewS3ApiServerWithStore(router, option, "")
|
||||
}
|
||||
@@ -189,21 +181,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
policyEngine: policyEngine, // Initialize bucket policy engine
|
||||
inFlightDataLimitCond: sync.NewCond(new(sync.Mutex)),
|
||||
cipher: option.Cipher,
|
||||
}
|
||||
|
||||
if len(option.Filers) > 0 {
|
||||
objectWriteLockClient := cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
s3ApiServer.newObjectWriteLock = func(bucket, object string) objectWriteLock {
|
||||
lockKey := fmt.Sprintf("s3.object.write:%s", s3ApiServer.toFilerPath(bucket, object))
|
||||
owner := fmt.Sprintf("s3api-%d", s3ApiServer.randomClientId)
|
||||
lock := objectWriteLockClient.NewShortLivedLock(lockKey, owner)
|
||||
if err := lock.AttemptToLock(objectWriteLockTTL); err != nil {
|
||||
// The initial acquisition already succeeded with the default short TTL.
|
||||
// Renewal to a longer TTL is opportunistic to cover slower metadata paths.
|
||||
glog.Warningf("objectWriteLock: failed to extend lock TTL for %s: %v", lockKey, err)
|
||||
}
|
||||
return lock
|
||||
}
|
||||
lockClient: cluster.NewLockClient(option.GrpcDialOption, option.Filers[0]),
|
||||
}
|
||||
|
||||
// Set s3a reference in circuit breaker for upload limiting
|
||||
@@ -213,11 +191,6 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
// This avoids circular dependency by not passing the entire S3ApiServer
|
||||
iam.policyEngine = policyEngine
|
||||
|
||||
// Give the policy engine a way to look up the SSE algorithm that was
|
||||
// stored at CreateMultipartUpload time, so that UploadPart/UploadPartCopy
|
||||
// policy conditions on s3:x-amz-server-side-encryption evaluate correctly.
|
||||
policyEngine.MultipartSSELookup = s3ApiServer.getMultipartSSEAlgorithm
|
||||
|
||||
// Initialize advanced IAM system if config is provided or explicitly enabled
|
||||
if option.IamConfig != "" || option.EnableIam {
|
||||
configSource := "defaults"
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestShouldWriteStreamingErrorResponse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "nil error",
|
||||
err: nil,
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "context canceled",
|
||||
err: context.Canceled,
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "wrapped context canceled",
|
||||
err: &StreamError{Err: context.Canceled},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "deadline exceeded",
|
||||
err: context.DeadlineExceeded,
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "wrapped deadline exceeded",
|
||||
err: &StreamError{Err: context.DeadlineExceeded},
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := shouldWriteStreamingErrorResponse(tt.err); got != tt.expected {
|
||||
t.Fatalf("shouldWriteStreamingErrorResponse(%v) = %v, want %v", tt.err, got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,6 @@ const (
|
||||
ErrInvalidMaxDeleteObjects
|
||||
ErrInvalidPartNumberMarker
|
||||
ErrInvalidPart
|
||||
ErrInvalidPartOrder
|
||||
ErrInvalidRange
|
||||
ErrInternalError
|
||||
ErrInvalidCopyDest
|
||||
@@ -292,11 +291,6 @@ var errorCodeResponse = map[ErrorCode]APIError{
|
||||
Description: "One or more of the specified parts could not be found. The part may not have been uploaded, or the specified entity tag may not match the part's entity tag.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrInvalidPartOrder: {
|
||||
Code: "InvalidPartOrder",
|
||||
Description: "The list of parts was not in ascending order. The parts list must be specified in order by part number.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
|
||||
ErrInvalidCopyDest: {
|
||||
Code: "InvalidRequest",
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
package s3lifecycle
|
||||
|
||||
import "time"
|
||||
|
||||
// Evaluate checks the given lifecycle rules against an object and returns
|
||||
// the highest-priority action that applies. The evaluation follows S3's
|
||||
// action priority:
|
||||
// 1. ExpiredObjectDeleteMarker (delete marker is sole version)
|
||||
// 2. NoncurrentVersionExpiration (non-current version age/count)
|
||||
// 3. Current version Expiration (Days or Date)
|
||||
//
|
||||
// AbortIncompleteMultipartUpload is evaluated separately since it applies
|
||||
// to uploads, not objects. Use EvaluateMPUAbort for that.
|
||||
func Evaluate(rules []Rule, obj ObjectInfo, now time.Time) EvalResult {
|
||||
// Phase 1: ExpiredObjectDeleteMarker
|
||||
if obj.IsDeleteMarker && obj.IsLatest && obj.NumVersions == 1 {
|
||||
for _, rule := range rules {
|
||||
if rule.Status != "Enabled" {
|
||||
continue
|
||||
}
|
||||
if !MatchesFilter(rule, obj) {
|
||||
continue
|
||||
}
|
||||
if rule.ExpiredObjectDeleteMarker {
|
||||
return EvalResult{Action: ActionExpireDeleteMarker, RuleID: rule.ID}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: NoncurrentVersionExpiration
|
||||
if !obj.IsLatest && !obj.SuccessorModTime.IsZero() {
|
||||
for _, rule := range rules {
|
||||
if ShouldExpireNoncurrentVersion(rule, obj, obj.NoncurrentIndex, now) {
|
||||
return EvalResult{Action: ActionDeleteVersion, RuleID: rule.ID}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 3: Current version Expiration
|
||||
if obj.IsLatest && !obj.IsDeleteMarker {
|
||||
for _, rule := range rules {
|
||||
if rule.Status != "Enabled" {
|
||||
continue
|
||||
}
|
||||
if !MatchesFilter(rule, obj) {
|
||||
continue
|
||||
}
|
||||
// Date-based expiration
|
||||
if !rule.ExpirationDate.IsZero() && !now.Before(rule.ExpirationDate) {
|
||||
return EvalResult{Action: ActionDeleteObject, RuleID: rule.ID}
|
||||
}
|
||||
// Days-based expiration
|
||||
if rule.ExpirationDays > 0 {
|
||||
expiryTime := expectedExpiryTime(obj.ModTime, rule.ExpirationDays)
|
||||
if !now.Before(expiryTime) {
|
||||
return EvalResult{Action: ActionDeleteObject, RuleID: rule.ID}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return EvalResult{Action: ActionNone}
|
||||
}
|
||||
|
||||
// ShouldExpireNoncurrentVersion checks whether a non-current version should
|
||||
// be expired considering both NoncurrentDays and NewerNoncurrentVersions.
|
||||
// noncurrentIndex is the 0-based position among non-current versions sorted
|
||||
// newest-first (0 = newest non-current version).
|
||||
func ShouldExpireNoncurrentVersion(rule Rule, obj ObjectInfo, noncurrentIndex int, now time.Time) bool {
|
||||
if rule.Status != "Enabled" {
|
||||
return false
|
||||
}
|
||||
if rule.NoncurrentVersionExpirationDays <= 0 {
|
||||
return false
|
||||
}
|
||||
if obj.IsLatest || obj.SuccessorModTime.IsZero() {
|
||||
return false
|
||||
}
|
||||
if !MatchesFilter(rule, obj) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check age threshold.
|
||||
expiryTime := expectedExpiryTime(obj.SuccessorModTime, rule.NoncurrentVersionExpirationDays)
|
||||
if now.Before(expiryTime) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check NewerNoncurrentVersions count threshold.
|
||||
if rule.NewerNoncurrentVersions > 0 && noncurrentIndex < rule.NewerNoncurrentVersions {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// EvaluateMPUAbort finds the applicable AbortIncompleteMultipartUpload rule
|
||||
// for a multipart upload with the given key prefix and creation time.
|
||||
func EvaluateMPUAbort(rules []Rule, uploadKey string, createdAt time.Time, now time.Time) EvalResult {
|
||||
for _, rule := range rules {
|
||||
if rule.Status != "Enabled" {
|
||||
continue
|
||||
}
|
||||
if rule.AbortMPUDaysAfterInitiation <= 0 {
|
||||
continue
|
||||
}
|
||||
if !matchesPrefix(rule.Prefix, uploadKey) {
|
||||
continue
|
||||
}
|
||||
cutoff := expectedExpiryTime(createdAt, rule.AbortMPUDaysAfterInitiation)
|
||||
if !now.Before(cutoff) {
|
||||
return EvalResult{Action: ActionAbortMultipartUpload, RuleID: rule.ID}
|
||||
}
|
||||
}
|
||||
return EvalResult{Action: ActionNone}
|
||||
}
|
||||
|
||||
// expectedExpiryTime computes the expiration time given a reference time and
|
||||
// a number of days. Following S3 semantics, expiration happens at midnight UTC
|
||||
// of the day after the specified number of days.
|
||||
func expectedExpiryTime(refTime time.Time, days int) time.Time {
|
||||
if days == 0 {
|
||||
return refTime
|
||||
}
|
||||
t := refTime.UTC().Add(time.Duration(days+1) * 24 * time.Hour)
|
||||
return t.Truncate(24 * time.Hour)
|
||||
}
|
||||
@@ -1,495 +0,0 @@
|
||||
package s3lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var now = time.Date(2026, 3, 27, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestEvaluate_ExpirationDays(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "expire-30d", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
}}
|
||||
|
||||
t.Run("object_older_than_days_is_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "data/file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-31 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
assertEqual(t, "expire-30d", result.RuleID)
|
||||
})
|
||||
|
||||
t.Run("object_younger_than_days_is_not_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "data/file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("non_latest_version_not_affected_by_expiration_days", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "data/file.txt", IsLatest: false,
|
||||
ModTime: now.Add(-60 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("delete_marker_not_affected_by_expiration_days", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "data/file.txt", IsLatest: true, IsDeleteMarker: true,
|
||||
ModTime: now.Add(-60 * 24 * time.Hour), NumVersions: 3,
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_ExpirationDate(t *testing.T) {
|
||||
expirationDate := time.Date(2026, 3, 15, 0, 0, 0, 0, time.UTC)
|
||||
rules := []Rule{{
|
||||
ID: "expire-date", Status: "Enabled",
|
||||
ExpirationDate: expirationDate,
|
||||
}}
|
||||
|
||||
t.Run("object_expired_after_date", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-60 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
})
|
||||
|
||||
t.Run("object_not_expired_before_date", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-1 * time.Hour),
|
||||
}
|
||||
beforeDate := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
result := Evaluate(rules, obj, beforeDate)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_ExpiredObjectDeleteMarker(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "cleanup-markers", Status: "Enabled",
|
||||
ExpiredObjectDeleteMarker: true,
|
||||
}}
|
||||
|
||||
t.Run("sole_delete_marker_is_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true, IsDeleteMarker: true,
|
||||
NumVersions: 1,
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionExpireDeleteMarker, result.Action)
|
||||
})
|
||||
|
||||
t.Run("delete_marker_with_other_versions_not_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true, IsDeleteMarker: true,
|
||||
NumVersions: 3,
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("non_latest_delete_marker_not_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: false, IsDeleteMarker: true,
|
||||
NumVersions: 1,
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("non_delete_marker_not_affected", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true, IsDeleteMarker: false,
|
||||
NumVersions: 1,
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_NoncurrentVersionExpiration(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "expire-noncurrent", Status: "Enabled",
|
||||
NoncurrentVersionExpirationDays: 30,
|
||||
}}
|
||||
|
||||
t.Run("old_noncurrent_version_is_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: false,
|
||||
SuccessorModTime: now.Add(-45 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteVersion, result.Action)
|
||||
})
|
||||
|
||||
t.Run("recent_noncurrent_version_is_not_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: false,
|
||||
SuccessorModTime: now.Add(-10 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("latest_version_not_affected", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-60 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestShouldExpireNoncurrentVersion(t *testing.T) {
|
||||
rule := Rule{
|
||||
ID: "noncurrent-rule", Status: "Enabled",
|
||||
NoncurrentVersionExpirationDays: 30,
|
||||
NewerNoncurrentVersions: 2,
|
||||
}
|
||||
|
||||
t.Run("old_version_beyond_count_is_expired", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: false,
|
||||
SuccessorModTime: now.Add(-45 * 24 * time.Hour),
|
||||
}
|
||||
// noncurrentIndex=2 means this is the 3rd noncurrent version (0-indexed)
|
||||
// With NewerNoncurrentVersions=2, indices 0 and 1 are kept.
|
||||
if !ShouldExpireNoncurrentVersion(rule, obj, 2, now) {
|
||||
t.Error("expected version at index 2 to be expired")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("old_version_within_count_is_kept", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: false,
|
||||
SuccessorModTime: now.Add(-45 * 24 * time.Hour),
|
||||
}
|
||||
// noncurrentIndex=1 is within the keep threshold (NewerNoncurrentVersions=2).
|
||||
if ShouldExpireNoncurrentVersion(rule, obj, 1, now) {
|
||||
t.Error("expected version at index 1 to be kept")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("recent_version_beyond_count_is_kept", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: false,
|
||||
SuccessorModTime: now.Add(-5 * 24 * time.Hour),
|
||||
}
|
||||
// Even at index 5 (beyond count), if too young, it's kept.
|
||||
if ShouldExpireNoncurrentVersion(rule, obj, 5, now) {
|
||||
t.Error("expected recent version to be kept regardless of index")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disabled_rule_never_expires", func(t *testing.T) {
|
||||
disabled := Rule{
|
||||
ID: "disabled", Status: "Disabled",
|
||||
NoncurrentVersionExpirationDays: 1,
|
||||
}
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: false,
|
||||
SuccessorModTime: now.Add(-365 * 24 * time.Hour),
|
||||
}
|
||||
if ShouldExpireNoncurrentVersion(disabled, obj, 10, now) {
|
||||
t.Error("disabled rule should never expire")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_PrefixFilter(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "logs-only", Status: "Enabled",
|
||||
Prefix: "logs/",
|
||||
ExpirationDays: 7,
|
||||
}}
|
||||
|
||||
t.Run("matching_prefix", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "logs/app.log", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
})
|
||||
|
||||
t.Run("non_matching_prefix", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "data/file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_TagFilter(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "temp-only", Status: "Enabled",
|
||||
ExpirationDays: 1,
|
||||
FilterTags: map[string]string{"env": "temp"},
|
||||
}}
|
||||
|
||||
t.Run("matching_tags", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-5 * 24 * time.Hour),
|
||||
Tags: map[string]string{"env": "temp", "project": "foo"},
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
})
|
||||
|
||||
t.Run("missing_tag", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-5 * 24 * time.Hour),
|
||||
Tags: map[string]string{"project": "foo"},
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("wrong_tag_value", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-5 * 24 * time.Hour),
|
||||
Tags: map[string]string{"env": "prod"},
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("nil_object_tags", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-5 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_SizeFilter(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "large-files", Status: "Enabled",
|
||||
ExpirationDays: 7,
|
||||
FilterSizeGreaterThan: 1024 * 1024, // > 1 MB
|
||||
FilterSizeLessThan: 100 * 1024 * 1024, // < 100 MB
|
||||
}}
|
||||
|
||||
t.Run("matching_size", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.bin", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
Size: 10 * 1024 * 1024, // 10 MB
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
})
|
||||
|
||||
t.Run("too_small", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.bin", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
Size: 512, // 512 bytes
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("too_large", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "file.bin", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
Size: 200 * 1024 * 1024, // 200 MB
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_CombinedFilters(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "combined", Status: "Enabled",
|
||||
Prefix: "logs/",
|
||||
ExpirationDays: 7,
|
||||
FilterTags: map[string]string{"env": "dev"},
|
||||
FilterSizeGreaterThan: 100,
|
||||
}}
|
||||
|
||||
t.Run("all_filters_match", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "logs/app.log", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
Size: 1024,
|
||||
Tags: map[string]string{"env": "dev"},
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
})
|
||||
|
||||
t.Run("prefix_doesnt_match", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "data/app.log", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
Size: 1024,
|
||||
Tags: map[string]string{"env": "dev"},
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("tag_doesnt_match", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "logs/app.log", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
Size: 1024,
|
||||
Tags: map[string]string{"env": "prod"},
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("size_doesnt_match", func(t *testing.T) {
|
||||
obj := ObjectInfo{
|
||||
Key: "logs/app.log", IsLatest: true,
|
||||
ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
Size: 50, // too small
|
||||
Tags: map[string]string{"env": "dev"},
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_DisabledRule(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "disabled", Status: "Disabled",
|
||||
ExpirationDays: 1,
|
||||
}}
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-365 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
}
|
||||
|
||||
func TestEvaluate_MultipleRules_Priority(t *testing.T) {
|
||||
t.Run("delete_marker_takes_priority_over_expiration", func(t *testing.T) {
|
||||
rules := []Rule{
|
||||
{ID: "expire", Status: "Enabled", ExpirationDays: 1},
|
||||
{ID: "marker", Status: "Enabled", ExpiredObjectDeleteMarker: true},
|
||||
}
|
||||
obj := ObjectInfo{
|
||||
Key: "file.txt", IsLatest: true, IsDeleteMarker: true,
|
||||
NumVersions: 1, ModTime: now.Add(-10 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionExpireDeleteMarker, result.Action)
|
||||
assertEqual(t, "marker", result.RuleID)
|
||||
})
|
||||
|
||||
t.Run("first_matching_expiration_rule_wins", func(t *testing.T) {
|
||||
rules := []Rule{
|
||||
{ID: "rule1", Status: "Enabled", ExpirationDays: 30, Prefix: "logs/"},
|
||||
{ID: "rule2", Status: "Enabled", ExpirationDays: 7},
|
||||
}
|
||||
obj := ObjectInfo{
|
||||
Key: "logs/app.log", IsLatest: true,
|
||||
ModTime: now.Add(-31 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
assertEqual(t, "rule1", result.RuleID)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEvaluate_EmptyPrefix(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "all", Status: "Enabled",
|
||||
ExpirationDays: 30,
|
||||
}}
|
||||
obj := ObjectInfo{
|
||||
Key: "any/path/file.txt", IsLatest: true,
|
||||
ModTime: now.Add(-31 * 24 * time.Hour),
|
||||
}
|
||||
result := Evaluate(rules, obj, now)
|
||||
assertAction(t, ActionDeleteObject, result.Action)
|
||||
}
|
||||
|
||||
func TestEvaluateMPUAbort(t *testing.T) {
|
||||
rules := []Rule{{
|
||||
ID: "abort-mpu", Status: "Enabled",
|
||||
AbortMPUDaysAfterInitiation: 7,
|
||||
}}
|
||||
|
||||
t.Run("old_upload_is_aborted", func(t *testing.T) {
|
||||
result := EvaluateMPUAbort(rules, "uploads/file.bin", now.Add(-10*24*time.Hour), now)
|
||||
assertAction(t, ActionAbortMultipartUpload, result.Action)
|
||||
})
|
||||
|
||||
t.Run("recent_upload_is_not_aborted", func(t *testing.T) {
|
||||
result := EvaluateMPUAbort(rules, "uploads/file.bin", now.Add(-3*24*time.Hour), now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
|
||||
t.Run("prefix_scoped_abort", func(t *testing.T) {
|
||||
prefixRules := []Rule{{
|
||||
ID: "abort-logs", Status: "Enabled",
|
||||
Prefix: "logs/",
|
||||
AbortMPUDaysAfterInitiation: 1,
|
||||
}}
|
||||
result := EvaluateMPUAbort(prefixRules, "data/file.bin", now.Add(-5*24*time.Hour), now)
|
||||
assertAction(t, ActionNone, result.Action)
|
||||
})
|
||||
}
|
||||
|
||||
func TestExpectedExpiryTime(t *testing.T) {
|
||||
ref := time.Date(2026, 3, 1, 15, 30, 0, 0, time.UTC)
|
||||
|
||||
t.Run("30_days", func(t *testing.T) {
|
||||
// S3 spec: expires at midnight UTC of day 32 (ref + 31 days, truncated).
|
||||
expiry := expectedExpiryTime(ref, 30)
|
||||
expected := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
|
||||
if !expiry.Equal(expected) {
|
||||
t.Errorf("expected %v, got %v", expected, expiry)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero_days_returns_ref", func(t *testing.T) {
|
||||
expiry := expectedExpiryTime(ref, 0)
|
||||
if !expiry.Equal(ref) {
|
||||
t.Errorf("expected %v, got %v", ref, expiry)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func assertAction(t *testing.T, expected, actual Action) {
|
||||
t.Helper()
|
||||
if expected != actual {
|
||||
t.Errorf("expected action %d, got %d", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func assertEqual(t *testing.T, expected, actual string) {
|
||||
t.Helper()
|
||||
if expected != actual {
|
||||
t.Errorf("expected %q, got %q", expected, actual)
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package s3lifecycle
|
||||
|
||||
import "strings"
|
||||
|
||||
// MatchesFilter checks if an object matches the rule's filter criteria
|
||||
// (prefix, tags, and size constraints).
|
||||
func MatchesFilter(rule Rule, obj ObjectInfo) bool {
|
||||
if !matchesPrefix(rule.Prefix, obj.Key) {
|
||||
return false
|
||||
}
|
||||
if !matchesTags(rule.FilterTags, obj.Tags) {
|
||||
return false
|
||||
}
|
||||
if !matchesSize(rule.FilterSizeGreaterThan, rule.FilterSizeLessThan, obj.Size) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// matchesPrefix returns true if the object key starts with the given prefix.
|
||||
// An empty prefix matches all keys.
|
||||
func matchesPrefix(prefix, key string) bool {
|
||||
if prefix == "" {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(key, prefix)
|
||||
}
|
||||
|
||||
// matchesTags returns true if all rule tags are present in the object's tags
|
||||
// with matching values. An empty or nil rule tag set matches all objects.
|
||||
func matchesTags(ruleTags, objTags map[string]string) bool {
|
||||
if len(ruleTags) == 0 {
|
||||
return true
|
||||
}
|
||||
if len(objTags) == 0 {
|
||||
return false
|
||||
}
|
||||
for k, v := range ruleTags {
|
||||
if objVal, ok := objTags[k]; !ok || objVal != v {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// matchesSize returns true if the object's size falls within the specified
|
||||
// bounds. Zero values mean no constraint on that side.
|
||||
func matchesSize(greaterThan, lessThan, objSize int64) bool {
|
||||
if greaterThan > 0 && objSize <= greaterThan {
|
||||
return false
|
||||
}
|
||||
if lessThan > 0 && objSize >= lessThan {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user