mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fc2fefb4a | ||
|
|
6e393f3326 | ||
|
|
7939e5808e | ||
|
|
c1a9263e37 | ||
|
|
6bd6bba594 | ||
|
|
b8ef48c8f1 | ||
|
|
75faf826d4 | ||
|
|
221bd237c4 | ||
|
|
a3136c523f | ||
|
|
ac242d04ee | ||
|
|
21543134c8 | ||
|
|
8b5d31e5eb | ||
|
|
7151181d54 | ||
|
|
e657e7d827 | ||
|
|
2a73219397 | ||
|
|
7fcbffed7f | ||
|
|
be0379f6fd | ||
|
|
b57429ef2e | ||
|
|
5c365e7090 | ||
|
|
822dbed552 | ||
|
|
2d97685390 | ||
|
|
1b2f719d7c | ||
|
|
b73bd08470 | ||
|
|
17f85361e9 | ||
|
|
b261c89675 | ||
|
|
0385acba02 | ||
|
|
d6825ffce2 | ||
|
|
d88f6ed0af | ||
|
|
5ae3be44d1 | ||
|
|
1c62808c0e | ||
|
|
db76eb26e7 | ||
|
|
4ccc7668ce | ||
|
|
aef2de3109 | ||
|
|
be26ce74ce |
No files matched your search
@@ -3,7 +3,6 @@ name: "docker: build dev containers"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -4,22 +4,58 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
workflow_dispatch: {}
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
source_ref:
|
||||
description: 'Git ref to build (branch, tag, or commit SHA)'
|
||||
required: true
|
||||
default: 'master'
|
||||
image_tag:
|
||||
description: 'Docker tag to publish (without variant suffix)'
|
||||
required: true
|
||||
default: 'latest'
|
||||
variant:
|
||||
description: 'Variant to build manually'
|
||||
required: true
|
||||
type: choice
|
||||
default: all
|
||||
options:
|
||||
- all
|
||||
- standard
|
||||
- large_disk
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
variants: ${{ steps.set-variants.outputs.variants }}
|
||||
steps:
|
||||
- name: Select variants for this run
|
||||
id: set-variants
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ "${{ github.event.inputs.variant }}" != "all" ]; then
|
||||
variants="[\"${{ github.event.inputs.variant }}\"]"
|
||||
else
|
||||
variants='["standard","large_disk"]'
|
||||
fi
|
||||
echo "variants=$variants" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
needs: [setup]
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [amd64, arm64, arm, 386]
|
||||
variant: [standard, large_disk]
|
||||
variant: ${{ fromJSON(needs.setup.outputs.variants) }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_ref || github.ref }}
|
||||
- name: Free Disk Space
|
||||
run: |
|
||||
echo "Available disk space before cleanup:"
|
||||
@@ -55,7 +91,7 @@ jobs:
|
||||
images: |
|
||||
chrislusf/seaweedfs
|
||||
ghcr.io/chrislusf/seaweedfs
|
||||
tags: type=raw,value=latest,suffix=${{ steps.config.outputs.tag_suffix }}
|
||||
tags: type=raw,value=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }},suffix=${{ steps.config.outputs.tag_suffix }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=seaweedfs
|
||||
org.opencontainers.image.description=SeaweedFS is a distributed storage system for blobs, objects, files, and data lake, to store and serve billions of files fast!
|
||||
@@ -97,13 +133,13 @@ jobs:
|
||||
file: ./docker/Dockerfile.go_build
|
||||
platforms: linux/${{ matrix.platform }}
|
||||
# Push to GHCR only during build to avoid Docker Hub rate limits
|
||||
tags: ghcr.io/chrislusf/seaweedfs:latest${{ steps.config.outputs.tag_suffix }}-${{ matrix.platform }}
|
||||
tags: ghcr.io/chrislusf/seaweedfs:${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }}${{ steps.config.outputs.tag_suffix }}-${{ matrix.platform }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
cache-from: type=gha,scope=${{ matrix.variant }}-${{ matrix.platform }}
|
||||
cache-to: type=gha,mode=max,scope=${{ matrix.variant }}-${{ matrix.platform }}
|
||||
build-args: |
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
BRANCH=${{ github.sha }}
|
||||
BRANCH=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_ref || github.sha }}
|
||||
${{ steps.config.outputs.build_args }}
|
||||
- name: Clean up build artifacts
|
||||
if: always()
|
||||
@@ -115,14 +151,16 @@ jobs:
|
||||
|
||||
create-manifest:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build]
|
||||
needs: [setup, build]
|
||||
if: github.event_name != 'pull_request'
|
||||
strategy:
|
||||
matrix:
|
||||
variant: [standard, large_disk]
|
||||
variant: ${{ fromJSON(needs.setup.outputs.variants) }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_ref || github.ref }}
|
||||
|
||||
- name: Configure variant
|
||||
id: config
|
||||
@@ -140,7 +178,7 @@ jobs:
|
||||
images: |
|
||||
chrislusf/seaweedfs
|
||||
ghcr.io/chrislusf/seaweedfs
|
||||
tags: type=raw,value=latest,suffix=${{ steps.config.outputs.tag_suffix }}
|
||||
tags: type=raw,value=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }},suffix=${{ steps.config.outputs.tag_suffix }}
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
@@ -162,14 +200,15 @@ jobs:
|
||||
- name: Create and push manifest
|
||||
run: |
|
||||
SUFFIX="${{ steps.config.outputs.tag_suffix }}"
|
||||
BASE_TAG="${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }}"
|
||||
|
||||
# Create manifest on GHCR first (no rate limits)
|
||||
echo "Creating GHCR manifest (no rate limits)..."
|
||||
docker buildx imagetools create -t ghcr.io/chrislusf/seaweedfs:latest${SUFFIX} \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-386
|
||||
docker buildx imagetools create -t ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX} \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386
|
||||
|
||||
# Copy the complete multi-arch image from GHCR to Docker Hub
|
||||
# This only requires one pull from GHCR (no rate limit) and one push to Docker Hub
|
||||
@@ -205,16 +244,16 @@ jobs:
|
||||
# Use crane or skopeo to copy, fallback to docker if not available
|
||||
if command -v crane &> /dev/null; then
|
||||
echo "Using crane to copy..."
|
||||
retry_with_backoff crane copy ghcr.io/chrislusf/seaweedfs:latest${SUFFIX} chrislusf/seaweedfs:latest${SUFFIX}
|
||||
retry_with_backoff crane copy ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX} chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}
|
||||
elif command -v skopeo &> /dev/null; then
|
||||
echo "Using skopeo to copy..."
|
||||
retry_with_backoff skopeo copy --all docker://ghcr.io/chrislusf/seaweedfs:latest${SUFFIX} docker://chrislusf/seaweedfs:latest${SUFFIX}
|
||||
retry_with_backoff skopeo copy --all docker://ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX} docker://chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}
|
||||
else
|
||||
echo "Using docker buildx imagetools (pulling 4 images from Docker Hub)..."
|
||||
# Fallback: create manifest directly on Docker Hub (pulls from Docker Hub - rate limited)
|
||||
retry_with_backoff docker buildx imagetools create -t chrislusf/seaweedfs:latest${SUFFIX} \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:latest${SUFFIX}-386
|
||||
retry_with_backoff docker buildx imagetools create -t chrislusf/seaweedfs:${BASE_TAG}${SUFFIX} \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386
|
||||
fi
|
||||
@@ -1,152 +0,0 @@
|
||||
name: "docker: build release containers for normal volume"
|
||||
|
||||
# DISABLED: Merged into container_release_unified.yml
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force_run:
|
||||
description: 'This workflow is disabled. Use container_release_unified.yml instead'
|
||||
required: true
|
||||
default: 'disabled'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [amd64, arm64, arm, 386]
|
||||
include:
|
||||
- platform: amd64
|
||||
qemu: false
|
||||
- platform: arm64
|
||||
qemu: true
|
||||
- platform: arm
|
||||
qemu: true
|
||||
- platform: 386
|
||||
qemu: true
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
- name: Free Disk Space
|
||||
run: |
|
||||
echo "Available disk space before cleanup:"
|
||||
df -h
|
||||
# Remove pre-installed tools
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
|
||||
# Clean package managers
|
||||
sudo apt-get clean
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
# Clean Docker aggressively
|
||||
sudo docker system prune -af --volumes
|
||||
# Clean Go cache if it exists
|
||||
[ -d ~/.cache/go-build ] && rm -rf ~/.cache/go-build || true
|
||||
[ -d /go/pkg ] && rm -rf /go/pkg || true
|
||||
echo "Available disk space after cleanup:"
|
||||
df -h
|
||||
- name: Docker meta
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: chrislusf/seaweedfs
|
||||
tags: type=ref,event=tag
|
||||
flavor: latest=false
|
||||
- name: Set up QEMU
|
||||
if: matrix.qemu
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Create BuildKit config
|
||||
run: |
|
||||
cat > /tmp/buildkitd.toml <<EOF
|
||||
[registry."docker.io"]
|
||||
mirrors = ["https://mirror.gcr.io"]
|
||||
EOF
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
- name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- name: Build ${{ matrix.platform }}
|
||||
uses: docker/build-push-action@v6
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
file: ./docker/Dockerfile.go_build
|
||||
platforms: linux/${{ matrix.platform }}
|
||||
tags: ${{ steps.docker_meta.outputs.tags }}-${{ matrix.platform }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
BRANCH=${{ github.sha }}
|
||||
- name: Clean up build artifacts
|
||||
if: always()
|
||||
run: |
|
||||
# Clean up Docker build cache and temporary files
|
||||
sudo docker system prune -f
|
||||
# Remove Go build cache
|
||||
sudo rm -rf /tmp/go-build*
|
||||
|
||||
create-manifest:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build]
|
||||
if: github.event_name != 'pull_request'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
- name: Docker meta
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: chrislusf/seaweedfs
|
||||
tags: type=ref,event=tag
|
||||
flavor: latest=false
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- name: Create and push manifest
|
||||
run: |
|
||||
# Function to retry command with exponential backoff
|
||||
retry_with_backoff() {
|
||||
local max_attempts=5
|
||||
local timeout=1
|
||||
local attempt=1
|
||||
local exit_code=0
|
||||
|
||||
while [ $attempt -le $max_attempts ]; do
|
||||
if "$@"; then
|
||||
return 0
|
||||
else
|
||||
exit_code=$?
|
||||
fi
|
||||
|
||||
if [ $attempt -lt $max_attempts ]; then
|
||||
echo "Attempt $attempt failed. Retrying in ${timeout}s..." >&2
|
||||
sleep $timeout
|
||||
timeout=$((timeout * 2))
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
|
||||
echo "Command failed after $max_attempts attempts" >&2
|
||||
return $exit_code
|
||||
}
|
||||
|
||||
# Create manifest with retry
|
||||
retry_with_backoff docker buildx imagetools create -t ${{ steps.docker_meta.outputs.tags }} \
|
||||
${{ steps.docker_meta.outputs.tags }}-amd64 \
|
||||
${{ steps.docker_meta.outputs.tags }}-arm64 \
|
||||
${{ steps.docker_meta.outputs.tags }}-arm \
|
||||
${{ steps.docker_meta.outputs.tags }}-386
|
||||
@@ -1,153 +0,0 @@
|
||||
name: "docker: build release containers for large volume"
|
||||
|
||||
# DISABLED: Merged into container_release_unified.yml
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force_run:
|
||||
description: 'This workflow is disabled. Use container_release_unified.yml instead'
|
||||
required: true
|
||||
default: 'disabled'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [amd64, arm64, arm, 386]
|
||||
include:
|
||||
- platform: amd64
|
||||
qemu: false
|
||||
- platform: arm64
|
||||
qemu: true
|
||||
- platform: arm
|
||||
qemu: true
|
||||
- platform: 386
|
||||
qemu: true
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
- name: Free Disk Space
|
||||
run: |
|
||||
echo "Available disk space before cleanup:"
|
||||
df -h
|
||||
# Remove pre-installed tools
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
|
||||
# Clean package managers
|
||||
sudo apt-get clean
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
# Clean Docker aggressively
|
||||
sudo docker system prune -af --volumes
|
||||
# Clean Go cache if it exists
|
||||
[ -d ~/.cache/go-build ] && rm -rf ~/.cache/go-build || true
|
||||
[ -d /go/pkg ] && rm -rf /go/pkg || true
|
||||
echo "Available disk space after cleanup:"
|
||||
df -h
|
||||
- name: Docker meta
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: chrislusf/seaweedfs
|
||||
tags: type=ref,event=tag,suffix=_large_disk
|
||||
flavor: latest=false
|
||||
- name: Set up QEMU
|
||||
if: matrix.qemu
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Create BuildKit config
|
||||
run: |
|
||||
cat > /tmp/buildkitd.toml <<EOF
|
||||
[registry."docker.io"]
|
||||
mirrors = ["https://mirror.gcr.io"]
|
||||
EOF
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
- name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- name: Build ${{ matrix.platform }}
|
||||
uses: docker/build-push-action@v6
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
file: ./docker/Dockerfile.go_build
|
||||
build-args: |
|
||||
TAGS=5BytesOffset
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
BRANCH=${{ github.sha }}
|
||||
platforms: linux/${{ matrix.platform }}
|
||||
tags: ${{ steps.docker_meta.outputs.tags }}-${{ matrix.platform }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
- name: Clean up build artifacts
|
||||
if: always()
|
||||
run: |
|
||||
# Clean up Docker build cache and temporary files
|
||||
sudo docker system prune -f
|
||||
# Remove Go build cache
|
||||
sudo rm -rf /tmp/go-build*
|
||||
|
||||
create-manifest:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build]
|
||||
if: github.event_name != 'pull_request'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
- name: Docker meta
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: chrislusf/seaweedfs
|
||||
tags: type=ref,event=tag,suffix=_large_disk
|
||||
flavor: latest=false
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- name: Create and push manifest
|
||||
run: |
|
||||
# Function to retry command with exponential backoff
|
||||
retry_with_backoff() {
|
||||
local max_attempts=5
|
||||
local timeout=1
|
||||
local attempt=1
|
||||
local exit_code=0
|
||||
|
||||
while [ $attempt -le $max_attempts ]; do
|
||||
if "$@"; then
|
||||
return 0
|
||||
else
|
||||
exit_code=$?
|
||||
fi
|
||||
|
||||
if [ $attempt -lt $max_attempts ]; then
|
||||
echo "Attempt $attempt failed. Retrying in ${timeout}s..." >&2
|
||||
sleep $timeout
|
||||
timeout=$((timeout * 2))
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
|
||||
echo "Command failed after $max_attempts attempts" >&2
|
||||
return $exit_code
|
||||
}
|
||||
|
||||
# Create manifest with retry
|
||||
retry_with_backoff docker buildx imagetools create -t ${{ steps.docker_meta.outputs.tags }} \
|
||||
${{ steps.docker_meta.outputs.tags }}-amd64 \
|
||||
${{ steps.docker_meta.outputs.tags }}-arm64 \
|
||||
${{ steps.docker_meta.outputs.tags }}-arm \
|
||||
${{ steps.docker_meta.outputs.tags }}-386
|
||||
@@ -1,73 +0,0 @@
|
||||
name: "docker: build release containers for rocksdb"
|
||||
|
||||
# DISABLED: Merged into container_release_unified.yml
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force_run:
|
||||
description: 'This workflow is disabled. Use container_release_unified.yml instead'
|
||||
required: true
|
||||
default: 'disabled'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
|
||||
build-large-release-container_rocksdb:
|
||||
runs-on: [ubuntu-latest]
|
||||
|
||||
steps:
|
||||
-
|
||||
name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
-
|
||||
name: Free Disk Space
|
||||
run: |
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
|
||||
sudo docker system prune -af
|
||||
-
|
||||
name: Docker meta
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: chrislusf/seaweedfs
|
||||
tags: type=ref,event=tag,suffix=_large_disk_rocksdb
|
||||
flavor: latest=false
|
||||
labels: |
|
||||
org.opencontainers.image.title=seaweedfs
|
||||
org.opencontainers.image.description=SeaweedFS is a distributed storage system for blobs, objects, files, and data lake, to store and serve billions of files fast!
|
||||
org.opencontainers.image.vendor=Chris Lu
|
||||
-
|
||||
name: Create BuildKit config
|
||||
run: |
|
||||
cat > /tmp/buildkitd.toml <<EOF
|
||||
[registry."docker.io"]
|
||||
mirrors = ["https://mirror.gcr.io"]
|
||||
EOF
|
||||
-
|
||||
name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
-
|
||||
name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
-
|
||||
name: Build
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
file: ./docker/Dockerfile.rocksdb_large
|
||||
build-args: |
|
||||
BRANCH=${{ github.sha }}
|
||||
platforms: linux/amd64
|
||||
tags: ${{ steps.docker_meta.outputs.tags }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -1,72 +0,0 @@
|
||||
name: "docker: build release containers for all tags"
|
||||
|
||||
# DISABLED: Merged into container_release_unified.yml
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force_run:
|
||||
description: 'This workflow is disabled. Use container_release_unified.yml instead'
|
||||
required: true
|
||||
default: 'disabled'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-default-release-container:
|
||||
runs-on: [ubuntu-latest]
|
||||
|
||||
steps:
|
||||
-
|
||||
name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
-
|
||||
name: Free Disk Space
|
||||
run: |
|
||||
echo "Before cleanup:"
|
||||
df -h
|
||||
sudo rm -rf /usr/share/dotnet
|
||||
sudo rm -rf /usr/local/lib/android
|
||||
sudo rm -rf /opt/ghc
|
||||
sudo rm -rf /opt/hostedtoolcache/CodeQL
|
||||
sudo docker system prune -af
|
||||
echo "After cleanup:"
|
||||
df -h
|
||||
-
|
||||
name: Docker meta
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
chrislusf/seaweedfs
|
||||
tags: |
|
||||
type=ref,event=tag,suffix=_full
|
||||
flavor: |
|
||||
latest=false
|
||||
labels: |
|
||||
org.opencontainers.image.title=seaweedfs
|
||||
org.opencontainers.image.description=SeaweedFS is a distributed storage system for blobs, objects, files, and data lake, to store and serve billions of files fast!
|
||||
org.opencontainers.image.vendor=Chris Lu
|
||||
-
|
||||
name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
-
|
||||
name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
-
|
||||
name: Build
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
file: ./docker/Dockerfile.go_build
|
||||
build-args: TAGS=elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb
|
||||
platforms: linux/amd64
|
||||
tags: ${{ steps.docker_meta.outputs.tags }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -1,62 +0,0 @@
|
||||
name: "docker: build release containers for all tags and large volume"
|
||||
|
||||
# DISABLED: Merged into container_release_unified.yml
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force_run:
|
||||
description: 'This workflow is disabled. Use container_release_unified.yml instead'
|
||||
required: true
|
||||
default: 'disabled'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-default-release-container:
|
||||
runs-on: [ubuntu-latest]
|
||||
|
||||
steps:
|
||||
-
|
||||
name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
-
|
||||
name: Free Disk Space
|
||||
run: |
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
|
||||
sudo docker system prune -af
|
||||
-
|
||||
name: Docker meta
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: chrislusf/seaweedfs
|
||||
tags: type=ref,event=tag,suffix=_large_disk_full
|
||||
flavor: latest=false
|
||||
labels: |
|
||||
org.opencontainers.image.title=seaweedfs
|
||||
org.opencontainers.image.description=SeaweedFS is a distributed storage system for blobs, objects, files, and data lake, to store and serve billions of files fast!
|
||||
org.opencontainers.image.vendor=Chris Lu
|
||||
-
|
||||
name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
-
|
||||
name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
-
|
||||
name: Build
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
file: ./docker/Dockerfile.go_build
|
||||
build-args: TAGS=5BytesOffset,elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb
|
||||
platforms: linux/amd64
|
||||
tags: ${{ steps.docker_meta.outputs.tags }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -4,11 +4,35 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
workflow_dispatch: {}
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
variant:
|
||||
description: 'Variant to build manually'
|
||||
required: true
|
||||
type: choice
|
||||
default: all
|
||||
options:
|
||||
- all
|
||||
- normal
|
||||
- large_disk
|
||||
- full
|
||||
- large_disk_full
|
||||
- rocksdb
|
||||
release_tag:
|
||||
description: 'Release tag to publish (e.g. 3.93)'
|
||||
required: true
|
||||
default: ''
|
||||
rocksdb_version:
|
||||
description: 'RocksDB git tag to use when variant=rocksdb'
|
||||
required: false
|
||||
default: 'v10.10.1'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.release_tag || github.ref_name }}
|
||||
|
||||
# Limit concurrent builds to avoid rate limits
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
@@ -59,9 +83,11 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Free Disk Space
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
run: |
|
||||
echo "Available disk space before cleanup:"
|
||||
df -h
|
||||
@@ -75,13 +101,14 @@ jobs:
|
||||
df -h
|
||||
|
||||
- name: Docker meta
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
id: docker_meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
chrislusf/seaweedfs
|
||||
ghcr.io/chrislusf/seaweedfs
|
||||
tags: type=ref,event=tag,suffix=${{ matrix.tag_suffix }}
|
||||
tags: type=raw,value=${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }}
|
||||
flavor: latest=false
|
||||
labels: |
|
||||
org.opencontainers.image.title=seaweedfs
|
||||
@@ -89,10 +116,11 @@ jobs:
|
||||
org.opencontainers.image.vendor=Chris Lu
|
||||
|
||||
- name: Set up QEMU
|
||||
if: contains(matrix.platforms, 'arm')
|
||||
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && contains(matrix.platforms, 'arm')
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Create BuildKit config
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
run: |
|
||||
cat > /tmp/buildkitd.toml <<EOF
|
||||
[registry."docker.io"]
|
||||
@@ -100,19 +128,20 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
|
||||
- name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
if: github.event_name != 'pull_request'
|
||||
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
@@ -120,6 +149,7 @@ jobs:
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
|
||||
- name: Build and push ${{ matrix.variant }}
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/build-push-action@v6
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
@@ -130,7 +160,7 @@ jobs:
|
||||
platforms: ${{ matrix.platforms }}
|
||||
# Push to GHCR to avoid Docker Hub rate limits on pulls
|
||||
tags: |
|
||||
ghcr.io/chrislusf/seaweedfs:${{ github.ref_name }}${{ matrix.tag_suffix }}
|
||||
ghcr.io/chrislusf/seaweedfs:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
cache-from: type=gha,scope=${{ matrix.variant }}
|
||||
cache-to: type=gha,mode=max,scope=${{ matrix.variant }}
|
||||
@@ -138,9 +168,10 @@ jobs:
|
||||
${{ matrix.build_args }}
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
BRANCH=${{ github.sha }}
|
||||
${{ matrix.variant == 'rocksdb' && format('ROCKSDB_VERSION={0}', github.event.inputs.rocksdb_version || 'v10.10.1') || '' }}
|
||||
|
||||
- name: Clean up build artifacts
|
||||
if: always()
|
||||
if: always() && (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant)
|
||||
run: |
|
||||
sudo docker system prune -f
|
||||
sudo rm -rf /tmp/go-build*
|
||||
@@ -166,12 +197,14 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Login to Docker Hub
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
@@ -179,6 +212,7 @@ jobs:
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
|
||||
- name: Install crane
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
run: |
|
||||
cd $(mktemp -d)
|
||||
curl -sL "https://github.com/google/go-containerregistry/releases/latest/download/go-containerregistry_Linux_x86_64.tar.gz" | tar xz
|
||||
@@ -186,6 +220,7 @@ jobs:
|
||||
crane version
|
||||
|
||||
- name: Copy ${{ matrix.variant }} from GHCR to Docker Hub
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
run: |
|
||||
# Function to retry with exponential backoff
|
||||
retry_with_backoff() {
|
||||
@@ -218,14 +253,15 @@ jobs:
|
||||
# This is much more efficient than pulling/pushing individual arch images
|
||||
echo "Copying ${{ matrix.variant }} from GHCR to Docker Hub..."
|
||||
retry_with_backoff crane copy \
|
||||
ghcr.io/chrislusf/seaweedfs:${{ github.ref_name }}${{ matrix.tag_suffix }} \
|
||||
chrislusf/seaweedfs:${{ github.ref_name }}${{ matrix.tag_suffix }}
|
||||
ghcr.io/chrislusf/seaweedfs:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }} \
|
||||
chrislusf/seaweedfs:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }}
|
||||
|
||||
echo "✓ Successfully copied ${{ matrix.variant }} to Docker Hub"
|
||||
|
||||
helm-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [copy-to-dockerhub]
|
||||
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
|
||||
permissions:
|
||||
contents: write
|
||||
pages: write
|
||||
@@ -239,7 +275,3 @@ jobs:
|
||||
target_dir: helm
|
||||
branch: gh-pages
|
||||
helm_version: "3.18.4"
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
rocksdb_version:
|
||||
description: 'RocksDB git tag or branch to build (e.g. v10.5.1)'
|
||||
description: 'RocksDB git tag or branch to build (e.g. v10.10.1)'
|
||||
required: true
|
||||
default: 'v10.5.1'
|
||||
default: 'v10.10.1'
|
||||
seaweedfs_ref:
|
||||
description: 'SeaweedFS git tag, branch, or commit to build'
|
||||
required: true
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
name: "helm: manual release"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pages: write
|
||||
|
||||
jobs:
|
||||
helm-release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Publish Helm charts
|
||||
uses: stefanprodan/helm-gh-pages@v1.7.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
charts_dir: k8s/charts
|
||||
target_dir: helm
|
||||
branch: gh-pages
|
||||
helm_version: "3.18.4"
|
||||
@@ -260,6 +260,140 @@ jobs:
|
||||
path: test/s3tables/catalog_spark/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
risingwave-catalog-tests:
|
||||
name: RisingWave Catalog Integration 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'
|
||||
id: go
|
||||
|
||||
- name: Set up Docker
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Pre-pull RisingWave image
|
||||
run: |
|
||||
docker pull risingwavelabs/risingwave:v2.5.0
|
||||
docker pull postgres:16-alpine
|
||||
|
||||
- name: Run go mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
go install -buildvcs=false ./weed
|
||||
|
||||
- name: Run RisingWave Catalog Integration Tests
|
||||
timeout-minutes: 25
|
||||
working-directory: test/s3tables/catalog_risingwave
|
||||
run: |
|
||||
set -x
|
||||
set -o pipefail
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
echo "=== Starting RisingWave Catalog Tests ==="
|
||||
|
||||
# Run RisingWave catalog integration tests
|
||||
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
|
||||
echo "RisingWave catalog integration tests failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Show test output on failure
|
||||
if: failure()
|
||||
working-directory: test/s3tables/catalog_risingwave
|
||||
run: |
|
||||
echo "=== Test Output ==="
|
||||
if [ -f test-output.log ]; then
|
||||
tail -200 test-output.log
|
||||
fi
|
||||
|
||||
echo "=== Process information ==="
|
||||
ps aux | grep -E "(weed|test|docker)" || true
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: risingwave-catalog-test-logs
|
||||
path: test/s3tables/catalog_risingwave/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
sts-integration-tests:
|
||||
name: STS Integration 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'
|
||||
id: go
|
||||
|
||||
- name: Set up Docker
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Pre-pull Python image
|
||||
run: docker pull python:3
|
||||
|
||||
- name: Run go mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
go install -buildvcs=false ./weed
|
||||
|
||||
- name: Run STS Integration Tests
|
||||
timeout-minutes: 25
|
||||
working-directory: test/s3tables/sts_integration
|
||||
run: |
|
||||
set -x
|
||||
set -o pipefail
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
echo "=== Starting STS Integration Tests ==="
|
||||
|
||||
# Run STS integration tests
|
||||
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
|
||||
echo "STS integration tests failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Show test output on failure
|
||||
if: failure()
|
||||
working-directory: test/s3tables/sts_integration
|
||||
run: |
|
||||
echo "=== Test Output ==="
|
||||
if [ -f test-output.log ]; then
|
||||
tail -200 test-output.log
|
||||
fi
|
||||
|
||||
echo "=== Process information ==="
|
||||
ps aux | grep -E "(weed|test|docker)" || true
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: sts-integration-test-logs
|
||||
path: test/s3tables/sts_integration/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
s3-tables-build-verification:
|
||||
name: S3 Tables Build Verification
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
@@ -3,7 +3,7 @@ FROM golang:1.24 AS builder
|
||||
RUN apt-get update
|
||||
RUN apt-get install -y build-essential libsnappy-dev zlib1g-dev libbz2-dev libgflags-dev liblz4-dev libzstd-dev
|
||||
|
||||
ARG ROCKSDB_VERSION=v10.5.1
|
||||
ARG ROCKSDB_VERSION=v10.10.1
|
||||
ENV ROCKSDB_VERSION=${ROCKSDB_VERSION}
|
||||
|
||||
# build RocksDB
|
||||
|
||||
@@ -3,7 +3,7 @@ FROM golang:1.24 AS builder
|
||||
RUN apt-get update
|
||||
RUN apt-get install -y build-essential libsnappy-dev zlib1g-dev libbz2-dev libgflags-dev liblz4-dev libzstd-dev
|
||||
|
||||
ARG ROCKSDB_VERSION=v10.5.1
|
||||
ARG ROCKSDB_VERSION=v10.10.1
|
||||
ENV ROCKSDB_VERSION=${ROCKSDB_VERSION}
|
||||
|
||||
# build RocksDB
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ printf "%s-admin" (include "seaweedfs.fullname" .) | trunc 63 | trimSuffix "-" }}
|
||||
name: {{ include "seaweedfs.componentName" (list . "admin") }}
|
||||
namespace: {{ .Release.Namespace }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
|
||||
|
||||
@@ -134,7 +134,7 @@ spec:
|
||||
{{- if .Values.worker.adminServer }}
|
||||
-admin={{ .Values.worker.adminServer }} \
|
||||
{{- else }}
|
||||
-admin={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
|
||||
-admin={{ include "seaweedfs.componentName" (list . "admin") }}.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
|
||||
{{- end }}
|
||||
-capabilities={{ .Values.worker.capabilities }} \
|
||||
-maxConcurrent={{ .Values.worker.maxConcurrent }} \
|
||||
|
||||
@@ -14,7 +14,7 @@ func setupSparkIssue8234Env(t *testing.T) *TestEnvironment {
|
||||
}
|
||||
|
||||
env.StartSeaweedFS(t)
|
||||
t.Cleanup(func() { env.Cleanup() })
|
||||
t.Cleanup(func() { env.Cleanup(t) })
|
||||
|
||||
createObjectBucket(t, env, "test")
|
||||
env.startSparkContainer(t)
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package spark
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
)
|
||||
|
||||
func TestSparkS3TemporaryDirectoryCleanupIssue8285Regression(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping Spark integration test in short mode")
|
||||
}
|
||||
|
||||
env := setupSparkIssue8234Env(t)
|
||||
|
||||
script := `
|
||||
import pyspark.sql.functions as F
|
||||
|
||||
target = "s3a://test/issue-8285/output"
|
||||
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.name", "directory")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.magic.enabled", "false")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.staging.abort.pending.uploads", "true")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.staging.conflict-mode", "append")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.committer.staging.tmp.path", "/tmp")
|
||||
spark.conf.set("spark.hadoop.fs.s3a.directory.marker.retention", "keep")
|
||||
|
||||
df = spark.range(0, 200).repartition(12).withColumn("value", F.col("id") * 2)
|
||||
df.write.format("parquet").mode("overwrite").save(target)
|
||||
count = spark.read.parquet(target).count()
|
||||
print("WRITE_COUNT=" + str(count))
|
||||
`
|
||||
|
||||
code, output := runSparkPyScript(t, env.sparkContainer, script, env.s3Port)
|
||||
if code != 0 {
|
||||
t.Fatalf("Spark script exited with code %d; output:\n%s", code, output)
|
||||
}
|
||||
if !strings.Contains(output, "WRITE_COUNT=200") {
|
||||
t.Fatalf("expected write/read success marker in output, got:\n%s", output)
|
||||
}
|
||||
|
||||
keys := listObjectKeysByPrefix(t, env, "test", "issue-8285/")
|
||||
var temporaryKeys []string
|
||||
for _, key := range keys {
|
||||
if hasTemporaryPathSegment(key) {
|
||||
temporaryKeys = append(temporaryKeys, key)
|
||||
}
|
||||
}
|
||||
|
||||
if len(temporaryKeys) > 0 {
|
||||
t.Fatalf("issue #8285 regression detected: found lingering _temporary artifacts: %v\nall keys: %v", temporaryKeys, keys)
|
||||
}
|
||||
|
||||
temporaryCandidates := []string{
|
||||
"issue-8285/output/_temporary/",
|
||||
"issue-8285/output/_temporary/0/",
|
||||
"issue-8285/output/_temporary/0/_temporary/",
|
||||
}
|
||||
lingering := waitForObjectsToDisappear(t, env, "test", temporaryCandidates, 35*time.Second)
|
||||
if len(lingering) > 0 {
|
||||
t.Fatalf("issue #8285 regression detected: lingering temporary directories: %v", lingering)
|
||||
}
|
||||
}
|
||||
|
||||
func listObjectKeysByPrefix(t *testing.T, env *TestEnvironment, bucketName, prefix string) []string {
|
||||
t.Helper()
|
||||
client := newS3Client(env)
|
||||
|
||||
pager := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName),
|
||||
Prefix: aws.String(prefix),
|
||||
})
|
||||
|
||||
var keys []string
|
||||
for pager.HasMorePages() {
|
||||
page, err := pager.NextPage(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("failed listing objects for prefix %q: %v", prefix, err)
|
||||
}
|
||||
for _, object := range page.Contents {
|
||||
keys = append(keys, aws.ToString(object.Key))
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func headObjectInfo(t *testing.T, env *TestEnvironment, bucketName, key string) (bool, string, error) {
|
||||
t.Helper()
|
||||
|
||||
client := newS3Client(env)
|
||||
output, err := client.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err == nil {
|
||||
return true, aws.ToString(output.ContentType), nil
|
||||
}
|
||||
|
||||
var notFound *s3types.NotFound
|
||||
if strings.Contains(err.Error(), "NotFound") || strings.Contains(err.Error(), "NoSuchKey") || errors.As(err, ¬Found) {
|
||||
return false, "", nil
|
||||
}
|
||||
return false, "", err
|
||||
}
|
||||
|
||||
func waitForObjectsToDisappear(t *testing.T, env *TestEnvironment, bucketName string, keys []string, timeout time.Duration) []string {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(timeout)
|
||||
pending := make(map[string]struct{}, len(keys))
|
||||
details := make(map[string]string, len(keys))
|
||||
for _, key := range keys {
|
||||
pending[key] = struct{}{}
|
||||
}
|
||||
|
||||
for len(pending) > 0 && time.Now().Before(deadline) {
|
||||
for key := range pending {
|
||||
exists, contentType, err := headObjectInfo(t, env, bucketName, key)
|
||||
if err != nil {
|
||||
details[key] = fmt.Sprintf("%s (head_error=%v)", key, err)
|
||||
continue
|
||||
}
|
||||
if !exists {
|
||||
delete(pending, key)
|
||||
delete(details, key)
|
||||
continue
|
||||
}
|
||||
details[key] = fmt.Sprintf("%s (exists=true, contentType=%q)", key, contentType)
|
||||
}
|
||||
if len(pending) > 0 {
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
if len(pending) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var lingering []string
|
||||
for _, key := range keys {
|
||||
if _, ok := pending[key]; !ok {
|
||||
continue
|
||||
}
|
||||
if detail, hasDetail := details[key]; hasDetail {
|
||||
lingering = append(lingering, detail)
|
||||
} else {
|
||||
lingering = append(lingering, key)
|
||||
}
|
||||
}
|
||||
return lingering
|
||||
}
|
||||
|
||||
func newS3Client(env *TestEnvironment) *s3.Client {
|
||||
cfg := aws.Config{
|
||||
Region: "us-east-1",
|
||||
Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(env.accessKey, env.secretKey, "")),
|
||||
BaseEndpoint: aws.String(fmt.Sprintf("http://localhost:%d", env.s3Port)),
|
||||
}
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
func hasTemporaryPathSegment(key string) bool {
|
||||
for _, segment := range strings.Split(strings.TrimSuffix(key, "/"), "/") {
|
||||
if segment == "_temporary" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -53,6 +54,8 @@ type TestEnvironment struct {
|
||||
dockerAvailable bool
|
||||
weedBinary string
|
||||
seaweedfsDataDir string
|
||||
weedLogPath string
|
||||
weedLogFile *os.File
|
||||
masterPort int
|
||||
filerPort int
|
||||
s3Port int
|
||||
@@ -113,6 +116,15 @@ func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
"-s3.config", iamConfigPath,
|
||||
"-dir", env.seaweedfsDataDir,
|
||||
)
|
||||
weedLogPath := filepath.Join(env.seaweedfsDataDir, "weed-mini.log")
|
||||
weedLogFile, err := os.Create(weedLogPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create weed log file: %v", err)
|
||||
}
|
||||
env.weedLogPath = weedLogPath
|
||||
env.weedLogFile = weedLogFile
|
||||
env.masterProcess.Stdout = weedLogFile
|
||||
env.masterProcess.Stderr = weedLogFile
|
||||
env.masterProcess.Env = append(os.Environ(),
|
||||
"AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
@@ -160,12 +172,30 @@ func (env *TestEnvironment) startSparkContainer(t *testing.T) {
|
||||
env.sparkContainer = container
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Cleanup() {
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
if env.masterProcess != nil && env.masterProcess.Process != nil {
|
||||
_ = env.masterProcess.Process.Kill()
|
||||
_ = env.masterProcess.Wait()
|
||||
}
|
||||
clearMiniProcess(env.masterProcess)
|
||||
if env.weedLogFile != nil {
|
||||
_ = env.weedLogFile.Close()
|
||||
}
|
||||
|
||||
if t.Failed() && os.Getenv("CI") != "" && env.weedLogPath != "" {
|
||||
logData, err := os.ReadFile(env.weedLogPath)
|
||||
if err != nil {
|
||||
t.Logf("failed to read weed mini log file %s: %v", env.weedLogPath, err)
|
||||
} else {
|
||||
// Print the tail to keep CI output manageable while preserving failure context.
|
||||
const maxTailBytes = 64 * 1024
|
||||
start := 0
|
||||
if len(logData) > maxTailBytes {
|
||||
start = len(logData) - maxTailBytes
|
||||
}
|
||||
t.Logf("weed mini logs (tail, %d bytes):\n%s", len(logData)-start, string(logData[start:]))
|
||||
}
|
||||
}
|
||||
|
||||
if env.sparkContainer != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
@@ -300,7 +300,6 @@ populate-spark: ensure-table-bucket ensure-work-dir ## Populate sample data via
|
||||
--conf "spark.sql.catalog.iceberg.s3.region=$(AWS_REGION)" \
|
||||
--conf "spark.sql.catalog.iceberg.rest.sigv4-enabled=true" \
|
||||
--conf "spark.sql.catalog.iceberg.rest.signing-name=s3tables" \
|
||||
--conf "spark.sql.catalog.iceberg.rest.signing-region=$(AWS_REGION)" \
|
||||
--conf "spark.sql.catalog.spark_catalog=org.apache.iceberg.spark.SparkCatalog" \
|
||||
--conf "spark.sql.catalog.spark_catalog.type=rest" \
|
||||
--conf "spark.sql.catalog.spark_catalog.uri=$(CATALOG_ENDPOINT_DOCKER)" \
|
||||
@@ -314,7 +313,6 @@ populate-spark: ensure-table-bucket ensure-work-dir ## Populate sample data via
|
||||
--conf "spark.sql.catalog.spark_catalog.s3.region=$(AWS_REGION)" \
|
||||
--conf "spark.sql.catalog.spark_catalog.rest.sigv4-enabled=true" \
|
||||
--conf "spark.sql.catalog.spark_catalog.rest.signing-name=s3tables" \
|
||||
--conf "spark.sql.catalog.spark_catalog.rest.signing-region=$(AWS_REGION)" \
|
||||
-f /work/spark_seed.sql'
|
||||
|
||||
populate: populate-trino populate-spark ## Populate sample data through Trino and Spark
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -41,16 +43,15 @@ func hasDocker() bool {
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
// getFreePort returns an available ephemeral port
|
||||
func getFreePort() (int, error) {
|
||||
// getFreePort returns an available ephemeral port and its listener
|
||||
func getFreePort() (int, net.Listener, error) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, nil, err
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
addr := listener.Addr().(*net.TCPAddr)
|
||||
return addr.Port, nil
|
||||
return addr.Port, listener, nil
|
||||
}
|
||||
|
||||
// NewTestEnvironment creates a new test environment
|
||||
@@ -89,43 +90,67 @@ func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
}
|
||||
|
||||
// Allocate free ephemeral ports for each service
|
||||
s3Port, err := getFreePort()
|
||||
var listeners []net.Listener
|
||||
defer func() {
|
||||
for _, l := range listeners {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
var l net.Listener
|
||||
s3Port, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for S3: %v", err)
|
||||
}
|
||||
icebergPort, err := getFreePort()
|
||||
listeners = append(listeners, l)
|
||||
|
||||
icebergPort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Iceberg: %v", err)
|
||||
}
|
||||
s3GrpcPort, err := getFreePort()
|
||||
listeners = append(listeners, l)
|
||||
|
||||
s3GrpcPort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for S3 gRPC: %v", err)
|
||||
}
|
||||
masterPort, err := getFreePort()
|
||||
listeners = append(listeners, l)
|
||||
|
||||
masterPort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Master: %v", err)
|
||||
}
|
||||
masterGrpcPort, err := getFreePort()
|
||||
listeners = append(listeners, l)
|
||||
|
||||
masterGrpcPort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Master gRPC: %v", err)
|
||||
}
|
||||
filerPort, err := getFreePort()
|
||||
listeners = append(listeners, l)
|
||||
|
||||
filerPort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Filer: %v", err)
|
||||
}
|
||||
filerGrpcPort, err := getFreePort()
|
||||
listeners = append(listeners, l)
|
||||
|
||||
filerGrpcPort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Filer gRPC: %v", err)
|
||||
}
|
||||
volumePort, err := getFreePort()
|
||||
listeners = append(listeners, l)
|
||||
|
||||
volumePort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Volume: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
volumeGrpcPort, err := getFreePort()
|
||||
volumeGrpcPort, l, err := getFreePort()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port for Volume gRPC: %v", err)
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
|
||||
return &TestEnvironment{
|
||||
seaweedDir: seaweedDir,
|
||||
@@ -290,6 +315,182 @@ func TestIcebergNamespaces(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestStageCreateAndFinalizeFlow verifies staged create remains invisible until assert-create commit finalizes table creation.
|
||||
func TestStageCreateAndFinalizeFlow(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
env.StartSeaweedFS(t)
|
||||
createTableBucket(t, env, "warehouse")
|
||||
|
||||
namespace := "stage_ns"
|
||||
tableName := "orders"
|
||||
|
||||
status, _, err := doIcebergJSONRequest(env, http.MethodPost, "/v1/namespaces", map[string]any{
|
||||
"namespace": []string{namespace},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create namespace request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusOK && status != http.StatusConflict {
|
||||
t.Fatalf("Create namespace status = %d, want 200 or 409", status)
|
||||
}
|
||||
|
||||
status, badReqResp, err := doIcebergJSONRequest(env, http.MethodPost, fmt.Sprintf("/v1/namespaces/%s/tables", namespace), map[string]any{
|
||||
"stage-create": true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Stage create missing-name request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("Stage create missing-name status = %d, want 400", status)
|
||||
}
|
||||
errorObj, _ := badReqResp["error"].(map[string]any)
|
||||
if got := errorObj["type"]; got != "BadRequestException" {
|
||||
t.Fatalf("error.type = %v, want BadRequestException", got)
|
||||
}
|
||||
msg, _ := errorObj["message"].(string)
|
||||
if !strings.Contains(strings.ToLower(msg), "table name is required") {
|
||||
t.Fatalf("error.message = %v, want it to include %q", errorObj["message"], "table name is required")
|
||||
}
|
||||
|
||||
status, stageResp, err := doIcebergJSONRequest(env, http.MethodPost, fmt.Sprintf("/v1/namespaces/%s/tables", namespace), map[string]any{
|
||||
"name": tableName,
|
||||
"stage-create": true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Stage create request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("Stage create status = %d, want 200", status)
|
||||
}
|
||||
stageLocation, _ := stageResp["metadata-location"].(string)
|
||||
if !strings.HasSuffix(stageLocation, "/metadata/v1.metadata.json") {
|
||||
t.Fatalf("stage metadata-location = %q, want suffix /metadata/v1.metadata.json", stageLocation)
|
||||
}
|
||||
|
||||
status, _, err = doIcebergJSONRequest(env, http.MethodGet, fmt.Sprintf("/v1/namespaces/%s/tables/%s", namespace, tableName), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Load staged table request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("Load staged table status = %d, want 404", status)
|
||||
}
|
||||
|
||||
status, commitResp, err := doIcebergJSONRequest(env, http.MethodPost, fmt.Sprintf("/v1/namespaces/%s/tables/%s", namespace, tableName), map[string]any{
|
||||
"requirements": []map[string]any{
|
||||
{"type": "assert-create"},
|
||||
},
|
||||
"updates": []any{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Finalize commit request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("Finalize commit status = %d, want 200", status)
|
||||
}
|
||||
commitLocation, _ := commitResp["metadata-location"].(string)
|
||||
if !strings.HasSuffix(commitLocation, "/metadata/v1.metadata.json") {
|
||||
t.Fatalf("final metadata-location = %q, want suffix /metadata/v1.metadata.json", commitLocation)
|
||||
}
|
||||
|
||||
status, loadResp, err := doIcebergJSONRequest(env, http.MethodGet, fmt.Sprintf("/v1/namespaces/%s/tables/%s", namespace, tableName), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Load finalized table request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("Load finalized table status = %d, want 200", status)
|
||||
}
|
||||
loadLocation, _ := loadResp["metadata-location"].(string)
|
||||
if loadLocation != commitLocation {
|
||||
t.Fatalf("loaded metadata-location = %q, want %q", loadLocation, commitLocation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommitMissingTableWithoutAssertCreate ensures missing-table commits still require assert-create for creation.
|
||||
func TestCommitMissingTableWithoutAssertCreate(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
env.StartSeaweedFS(t)
|
||||
createTableBucket(t, env, "warehouse")
|
||||
|
||||
namespace := "stage_missing_assert_ns"
|
||||
tableName := "missing_table"
|
||||
|
||||
status, _, err := doIcebergJSONRequest(env, http.MethodPost, "/v1/namespaces", map[string]any{
|
||||
"namespace": []string{namespace},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create namespace request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusOK && status != http.StatusConflict {
|
||||
t.Fatalf("Create namespace status = %d, want 200 or 409", status)
|
||||
}
|
||||
|
||||
status, _, err = doIcebergJSONRequest(env, http.MethodPost, fmt.Sprintf("/v1/namespaces/%s/tables/%s", namespace, tableName), map[string]any{
|
||||
"requirements": []any{},
|
||||
"updates": []any{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Commit missing table request failed: %v", err)
|
||||
}
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("Commit missing table status = %d, want 404", status)
|
||||
}
|
||||
}
|
||||
|
||||
// doIcebergJSONRequest decodes JSON object responses used by catalog tests.
|
||||
func doIcebergJSONRequest(env *TestEnvironment, method, path string, payload any) (int, map[string]any, error) {
|
||||
url := env.IcebergURL() + path
|
||||
|
||||
var bodyReader io.Reader
|
||||
if payload != nil {
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
bodyReader = bytes.NewReader(data)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, url, bodyReader)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return resp.StatusCode, nil, err
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return resp.StatusCode, nil, nil
|
||||
}
|
||||
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
return resp.StatusCode, nil, fmt.Errorf("failed to decode %s %s response: %w body=%s", method, path, err, string(data))
|
||||
}
|
||||
return resp.StatusCode, decoded, nil
|
||||
}
|
||||
|
||||
// createTableBucket creates a table bucket via the S3Tables REST API
|
||||
func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Helper()
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package catalog_risingwave
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRisingWaveIcebergCatalog(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
if !env.dockerAvailable {
|
||||
t.Skip("Docker not available, skipping RisingWave integration test")
|
||||
}
|
||||
|
||||
t.Log(">>> Starting SeaweedFS...")
|
||||
env.StartSeaweedFS(t)
|
||||
t.Log(">>> SeaweedFS started.")
|
||||
|
||||
tableBucket := "iceberg-tables"
|
||||
t.Logf(">>> Creating table bucket: %s", tableBucket)
|
||||
createTableBucket(t, env, tableBucket)
|
||||
|
||||
t.Log(">>> Starting RisingWave...")
|
||||
env.StartRisingWave(t)
|
||||
t.Log(">>> RisingWave started.")
|
||||
|
||||
// Create Iceberg namespace
|
||||
createIcebergNamespace(t, env, "default")
|
||||
|
||||
// Create a catalog in RisingWave that points to SeaweedFS Iceberg REST API
|
||||
icebergUri := env.dockerIcebergEndpoint()
|
||||
s3Endpoint := env.dockerS3Endpoint()
|
||||
|
||||
tableName := "test_table_" + randomString(6)
|
||||
createIcebergTable(t, env, tableBucket, "default", tableName)
|
||||
|
||||
sourceName := "test_source_" + randomString(6)
|
||||
createSourceSql := fmt.Sprintf(`
|
||||
CREATE SOURCE %s WITH (
|
||||
connector = 'iceberg',
|
||||
catalog.type = 'rest',
|
||||
catalog.uri = '%s',
|
||||
catalog.name = 'default',
|
||||
database.name = 'default',
|
||||
table.name = '%s',
|
||||
warehouse.path = 's3://%s',
|
||||
s3.endpoint = '%s',
|
||||
s3.region = 'us-east-1',
|
||||
s3.access.key = '%s',
|
||||
s3.secret.key = '%s',
|
||||
s3.path.style.access = 'true',
|
||||
catalog.rest.sigv4_enabled = 'true',
|
||||
catalog.rest.signing_region = 'us-east-1',
|
||||
catalog.rest.signing_name = 's3'
|
||||
);`, sourceName, icebergUri, tableName, tableBucket, s3Endpoint, env.accessKey, env.secretKey)
|
||||
|
||||
t.Logf(">>> Creating source %s...", sourceName)
|
||||
runRisingWaveSQL(t, env.postgresSidecar, createSourceSql)
|
||||
|
||||
showSourcesOutput := runRisingWaveSQL(t, env.postgresSidecar, "SHOW SOURCES;")
|
||||
if !strings.Contains(showSourcesOutput, sourceName) {
|
||||
t.Fatalf("Expected source %s in SHOW SOURCES output:\n%s", sourceName, showSourcesOutput)
|
||||
}
|
||||
|
||||
describeOutput := runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("DESCRIBE %s;", sourceName))
|
||||
if !strings.Contains(describeOutput, "id") || !strings.Contains(describeOutput, "name") {
|
||||
t.Fatalf("Expected id/name columns in DESCRIBE output:\n%s", describeOutput)
|
||||
}
|
||||
|
||||
runRisingWaveSQL(t, env.postgresSidecar, fmt.Sprintf("SELECT * FROM %s LIMIT 0;", sourceName))
|
||||
|
||||
t.Log(">>> RisingWave Iceberg Catalog test passed!")
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
package catalog_risingwave
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/seaweedfs/seaweedfs/test/s3tables/testutil"
|
||||
)
|
||||
|
||||
var (
|
||||
miniProcessMu sync.Mutex
|
||||
lastMiniProcess *exec.Cmd
|
||||
)
|
||||
|
||||
func stopPreviousMini() {
|
||||
miniProcessMu.Lock()
|
||||
defer miniProcessMu.Unlock()
|
||||
|
||||
if lastMiniProcess != nil && lastMiniProcess.Process != nil {
|
||||
_ = lastMiniProcess.Process.Kill()
|
||||
_ = lastMiniProcess.Wait()
|
||||
}
|
||||
lastMiniProcess = nil
|
||||
}
|
||||
|
||||
func registerMiniProcess(cmd *exec.Cmd) {
|
||||
miniProcessMu.Lock()
|
||||
lastMiniProcess = cmd
|
||||
miniProcessMu.Unlock()
|
||||
}
|
||||
|
||||
func clearMiniProcess(cmd *exec.Cmd) {
|
||||
miniProcessMu.Lock()
|
||||
if lastMiniProcess == cmd {
|
||||
lastMiniProcess = nil
|
||||
}
|
||||
miniProcessMu.Unlock()
|
||||
}
|
||||
|
||||
type TestEnvironment struct {
|
||||
t *testing.T
|
||||
dockerAvailable bool
|
||||
seaweedfsDataDir string
|
||||
masterPort int
|
||||
filerPort int
|
||||
s3Port int
|
||||
icebergRestPort int
|
||||
risingwavePort int
|
||||
bindIP string
|
||||
accessKey string
|
||||
secretKey string
|
||||
risingwaveContainer string
|
||||
postgresSidecar string
|
||||
masterProcess *exec.Cmd
|
||||
logFile *os.File
|
||||
}
|
||||
|
||||
func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
env := &TestEnvironment{
|
||||
t: t,
|
||||
accessKey: "AKIAIOSFODNN7EXAMPLE",
|
||||
secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
|
||||
}
|
||||
|
||||
// Check if Docker is available
|
||||
cmd := exec.Command("docker", "version")
|
||||
env.dockerAvailable = cmd.Run() == nil
|
||||
|
||||
return env
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) hostMasterAddress() string {
|
||||
return fmt.Sprintf("127.0.0.1:%d", env.masterPort)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) hostS3Endpoint() string {
|
||||
return fmt.Sprintf("http://127.0.0.1:%d", env.s3Port)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) hostIcebergEndpoint() string {
|
||||
return fmt.Sprintf("http://127.0.0.1:%d", env.icebergRestPort)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) dockerS3Endpoint() string {
|
||||
return fmt.Sprintf("http://host.docker.internal:%d", env.s3Port)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) dockerIcebergEndpoint() string {
|
||||
return fmt.Sprintf("http://host.docker.internal:%d", env.icebergRestPort)
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
stopPreviousMini()
|
||||
|
||||
var err error
|
||||
env.seaweedfsDataDir, err = os.MkdirTemp("", "seaweed-risingwave-test-")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp directory: %v", err)
|
||||
}
|
||||
|
||||
env.masterPort = mustFreePort(t, "Master")
|
||||
env.filerPort = mustFreePort(t, "Filer")
|
||||
env.s3Port = mustFreePort(t, "S3")
|
||||
env.icebergRestPort = mustFreePort(t, "Iceberg")
|
||||
env.risingwavePort = mustFreePort(t, "RisingWave")
|
||||
|
||||
env.bindIP = testutil.FindBindIP()
|
||||
|
||||
iamConfigPath, err := testutil.WriteIAMConfig(env.seaweedfsDataDir, env.accessKey, env.secretKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create IAM config: %v", err)
|
||||
}
|
||||
|
||||
// Create log file for SeaweedFS
|
||||
logFile, err := os.Create(filepath.Join(env.seaweedfsDataDir, "seaweedfs.log"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create log file: %v", err)
|
||||
}
|
||||
env.logFile = logFile
|
||||
|
||||
// Start SeaweedFS using weed mini (all-in-one including Iceberg REST)
|
||||
env.masterProcess = exec.Command(
|
||||
"weed", "mini",
|
||||
"-ip", env.bindIP,
|
||||
"-ip.bind", "0.0.0.0",
|
||||
"-master.port", fmt.Sprintf("%d", env.masterPort),
|
||||
"-filer.port", fmt.Sprintf("%d", env.filerPort),
|
||||
"-s3.port", fmt.Sprintf("%d", env.s3Port),
|
||||
"-s3.port.iceberg", fmt.Sprintf("%d", env.icebergRestPort),
|
||||
"-s3.config", iamConfigPath,
|
||||
"-dir", env.seaweedfsDataDir,
|
||||
)
|
||||
env.masterProcess.Stdout = logFile
|
||||
env.masterProcess.Stderr = logFile
|
||||
env.masterProcess.Env = append(os.Environ(),
|
||||
"AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
"ICEBERG_WAREHOUSE=s3://iceberg-tables",
|
||||
"S3TABLES_DEFAULT_BUCKET=iceberg-tables",
|
||||
)
|
||||
if err := env.masterProcess.Start(); err != nil {
|
||||
t.Fatalf("failed to start weed mini: %v", err)
|
||||
}
|
||||
registerMiniProcess(env.masterProcess)
|
||||
|
||||
// Wait for all services to be ready
|
||||
if !waitForPort(env.masterPort, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - master port %d not listening", env.masterPort)
|
||||
}
|
||||
if !waitForPort(env.filerPort, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - filer port %d not listening", env.filerPort)
|
||||
}
|
||||
if !waitForPort(env.s3Port, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - s3 port %d not listening", env.s3Port)
|
||||
}
|
||||
if !waitForPort(env.icebergRestPort, 15*time.Second) {
|
||||
t.Fatalf("weed mini failed to start - iceberg rest port %d not listening", env.icebergRestPort)
|
||||
}
|
||||
}
|
||||
|
||||
func mustFreePort(t *testing.T, name string) int {
|
||||
t.Helper()
|
||||
minPort := 10000
|
||||
maxPort := 55000 // Ensure port+10000 < 65535
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
for i := 0; i < 1000; i++ {
|
||||
port := minPort + r.Intn(maxPort-minPort)
|
||||
|
||||
// Check http port
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ln.Close()
|
||||
|
||||
// Check grpc port (weed mini uses port+10000)
|
||||
ln2, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port+10000))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ln2.Close()
|
||||
|
||||
return port
|
||||
}
|
||||
t.Fatalf("failed to find a free port < %d for %s after 1000 attempts", maxPort, name)
|
||||
return 0
|
||||
}
|
||||
|
||||
func waitForPort(port int, timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
conn, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), 500*time.Millisecond)
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
return true
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) StartRisingWave(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
containerName := "seaweed-risingwave-" + randomString(8)
|
||||
env.risingwaveContainer = containerName
|
||||
|
||||
cmd := exec.Command("docker", "run", "-d",
|
||||
"--name", containerName,
|
||||
"-p", fmt.Sprintf("%d:4566", env.risingwavePort),
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-e", "AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"-e", "AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
"-e", "AWS_REGION=us-east-1",
|
||||
"-e", "AWS_S3_PATH_STYLE_ACCESS=true",
|
||||
"-e", "AWS_S3_FORCE_PATH_STYLE=true",
|
||||
"risingwavelabs/risingwave:v2.5.0",
|
||||
"playground",
|
||||
)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to start RisingWave container: %v\n%s", err, string(output))
|
||||
}
|
||||
|
||||
// Start a sidecar postgres container for running psql commands
|
||||
sidecarName := "seaweed-risingwave-sidecar-" + randomString(8)
|
||||
env.postgresSidecar = sidecarName
|
||||
sidecarCmd := exec.Command("docker", "run", "-d", "--rm",
|
||||
"--name", sidecarName,
|
||||
"--network", fmt.Sprintf("container:%s", containerName),
|
||||
"postgres:16-alpine",
|
||||
"sleep", "infinity",
|
||||
)
|
||||
if output, err := sidecarCmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to start postgres sidecar: %v\n%s", err, string(output))
|
||||
}
|
||||
|
||||
// Wait for RisingWave port to be open on host
|
||||
if !waitForPort(env.risingwavePort, 120*time.Second) {
|
||||
t.Fatalf("timed out waiting for RisingWave port %d to be open", env.risingwavePort)
|
||||
}
|
||||
|
||||
// Wait for RisingWave to be truly ready via psql in the sidecar.
|
||||
if !env.waitForRisingWave(120 * time.Second) {
|
||||
t.Fatalf("timed out waiting for RisingWave to be ready via psql")
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) waitForRisingWave(timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
env.t.Logf(">>> Waiting for RisingWave to be ready (timeout %v)...\n", timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if output, err := runPostgresClientSQL(env.postgresSidecar, "SELECT 1;"); err == nil {
|
||||
env.t.Logf(">>> RisingWave is ready.\n")
|
||||
return true
|
||||
} else {
|
||||
env.t.Logf(">>> RisingWave not ready yet: %v (Output: %s)\n", err, string(output))
|
||||
}
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func runPostgresClientSQL(containerName, sql string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, "docker", "exec",
|
||||
containerName,
|
||||
"psql",
|
||||
"-h", "127.0.0.1",
|
||||
"-p", "4566",
|
||||
"-U", "root",
|
||||
"-d", "dev",
|
||||
"-v", "ON_ERROR_STOP=1",
|
||||
"-c", sql,
|
||||
)
|
||||
return cmd.CombinedOutput()
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if env.risingwaveContainer != "" {
|
||||
if t.Failed() {
|
||||
logs, err := exec.Command("docker", "logs", env.risingwaveContainer).CombinedOutput()
|
||||
if err == nil {
|
||||
env.t.Logf(">>> RisingWave Logs:\n%s\n", string(logs))
|
||||
} else {
|
||||
env.t.Logf(">>> Failed to get RisingWave logs: %v\n", err)
|
||||
}
|
||||
}
|
||||
_ = exec.Command("docker", "rm", "-f", env.risingwaveContainer).Run()
|
||||
}
|
||||
|
||||
if env.postgresSidecar != "" {
|
||||
_ = exec.Command("docker", "rm", "-f", env.postgresSidecar).Run()
|
||||
}
|
||||
|
||||
if env.seaweedfsDataDir != "" && t.Failed() {
|
||||
logPath := filepath.Join(env.seaweedfsDataDir, "seaweedfs.log")
|
||||
if content, err := os.ReadFile(logPath); err == nil {
|
||||
env.t.Logf(">>> SeaweedFS Logs:\n%s\n", string(content))
|
||||
}
|
||||
env.t.Logf(">>> Filer Contents:\n")
|
||||
listFilerContents(t, env, "/")
|
||||
}
|
||||
|
||||
if env.masterProcess != nil && env.masterProcess.Process != nil {
|
||||
_ = env.masterProcess.Process.Kill()
|
||||
_ = env.masterProcess.Wait()
|
||||
}
|
||||
clearMiniProcess(env.masterProcess)
|
||||
|
||||
if env.seaweedfsDataDir != "" {
|
||||
if env.logFile != nil {
|
||||
env.logFile.Close()
|
||||
}
|
||||
_ = os.RemoveAll(env.seaweedfsDataDir)
|
||||
}
|
||||
}
|
||||
|
||||
func runRisingWaveSQL(t *testing.T, containerName, sql string) string {
|
||||
t.Helper()
|
||||
|
||||
output, err := runPostgresClientSQL(containerName, sql)
|
||||
if err != nil {
|
||||
t.Fatalf("RisingWave command failed: %v\nSQL: %s\nOutput:\n%s", err, sql, string(output))
|
||||
}
|
||||
return string(output)
|
||||
}
|
||||
|
||||
func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Helper()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, "weed", "shell",
|
||||
fmt.Sprintf("-master=%s", env.hostMasterAddress()),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("s3tables.bucket -create -name %s -account 000000000000\nexit\n", bucketName))
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create table bucket %s via weed shell: %v\nOutput: %s", bucketName, err, string(output))
|
||||
}
|
||||
}
|
||||
|
||||
func doIcebergSignedJSONRequest(env *TestEnvironment, method, path string, payload any) (int, string, error) {
|
||||
url := env.hostIcebergEndpoint() + path
|
||||
|
||||
var body io.Reader
|
||||
var payloadHash string
|
||||
|
||||
if payload != nil {
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
body = bytes.NewReader(data)
|
||||
// hash := sha256.Sum256(data)
|
||||
// payloadHash = hex.EncodeToString(hash[:])
|
||||
payloadHash = "UNSIGNED-PAYLOAD"
|
||||
} else {
|
||||
payloadHash = "UNSIGNED-PAYLOAD"
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, url, body)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("X-Amz-Content-Sha256", payloadHash)
|
||||
|
||||
// Sign the request
|
||||
credsProvider := credentials.NewStaticCredentialsProvider(env.accessKey, env.secretKey, "")
|
||||
creds, err := credsProvider.Retrieve(context.Background())
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("failed to retrieve credentials: %w", err)
|
||||
}
|
||||
signer := v4.NewSigner()
|
||||
|
||||
if err := signer.SignHTTP(context.Background(), creds, req, payloadHash, "s3", "us-east-1", time.Now()); err != nil {
|
||||
return 0, "", fmt.Errorf("failed to sign request: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
return resp.StatusCode, string(respBody), nil
|
||||
}
|
||||
|
||||
func createIcebergNamespace(t *testing.T, env *TestEnvironment, namespace string) {
|
||||
t.Helper()
|
||||
|
||||
status, raw, err := doIcebergSignedJSONRequest(env, "POST", "/v1/namespaces", map[string]any{
|
||||
"namespace": []string{namespace},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Iceberg namespace %s: %v", namespace, err)
|
||||
}
|
||||
if status != 200 && status != 409 {
|
||||
t.Fatalf("failed to create Iceberg namespace %s: status %d body: %s", namespace, status, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func createIcebergTable(t *testing.T, env *TestEnvironment, bucketName, namespace, tableName string) {
|
||||
t.Helper()
|
||||
|
||||
createPath := fmt.Sprintf("/v1/namespaces/%s/tables", namespace)
|
||||
status, raw, err := doIcebergSignedJSONRequest(env, "POST", createPath, map[string]any{
|
||||
"name": tableName,
|
||||
"location": fmt.Sprintf("s3://%s/%s/%s", bucketName, namespace, tableName),
|
||||
"schema": map[string]any{
|
||||
"type": "struct",
|
||||
"fields": []map[string]any{
|
||||
{"id": 1, "name": "id", "required": false, "type": "int"},
|
||||
{"id": 2, "name": "name", "required": false, "type": "string"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Iceberg table %s.%s in bucket %s: %v", namespace, tableName, bucketName, err)
|
||||
}
|
||||
if status != 200 && status != 409 {
|
||||
t.Fatalf("failed to create Iceberg table %s.%s in bucket %s: status %d body: %s", namespace, tableName, bucketName, status, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func listFilerContents(t *testing.T, env *TestEnvironment, path string) {
|
||||
t.Helper()
|
||||
|
||||
cmd := exec.Command("weed", "shell",
|
||||
fmt.Sprintf("-master=%s", env.hostMasterAddress()),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("fs.ls -R %s\nexit\n", path))
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
env.t.Logf(">>> Warning: failed to list filer contents: %v\nOutput: %s\n", err, string(output))
|
||||
} else {
|
||||
env.t.Logf("%s\n", string(output))
|
||||
}
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = letters[rand.Intn(len(letters))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -326,7 +326,6 @@ spark = (SparkSession.builder
|
||||
.config("spark.sql.catalog.iceberg.rest.auth.type", "sigv4")
|
||||
.config("spark.sql.catalog.iceberg.rest.auth.sigv4.delegate-auth-type", "none")
|
||||
.config("spark.sql.catalog.iceberg.rest.sigv4-enabled", "true")
|
||||
.config("spark.sql.catalog.iceberg.rest.signing-region", "us-west-2")
|
||||
.config("spark.sql.catalog.iceberg.rest.signing-name", "s3")
|
||||
.config("spark.sql.catalog.iceberg.rest.access-key-id", "test")
|
||||
.config("spark.sql.catalog.iceberg.rest.secret-access-key", "test")
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package sts_integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/s3tables/testutil"
|
||||
)
|
||||
|
||||
// TestEnvironment mirrors the one in trino_catalog_test.go but simplified
|
||||
type TestEnvironment struct {
|
||||
seaweedDir string
|
||||
weedBinary string
|
||||
dataDir string
|
||||
bindIP string
|
||||
s3Port int
|
||||
s3GrpcPort int
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
filerPort int
|
||||
filerGrpcPort int
|
||||
volumePort int
|
||||
volumeGrpcPort int
|
||||
weedProcess *exec.Cmd
|
||||
weedCancel context.CancelFunc
|
||||
dockerAvailable bool
|
||||
accessKey string
|
||||
secretKey string
|
||||
}
|
||||
|
||||
func TestSTSIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
if !env.dockerAvailable {
|
||||
t.Skip("Docker not available, skipping STS integration test")
|
||||
}
|
||||
|
||||
fmt.Printf(">>> Starting SeaweedFS...\n")
|
||||
env.StartSeaweedFS(t)
|
||||
fmt.Printf(">>> SeaweedFS started.\n")
|
||||
|
||||
// Run python script in docker to test STS
|
||||
runPythonSTSClient(t, env)
|
||||
}
|
||||
|
||||
func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
t.Helper()
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get working directory: %v", err)
|
||||
}
|
||||
|
||||
seaweedDir := wd
|
||||
for i := 0; i < 6; i++ {
|
||||
if _, err := os.Stat(filepath.Join(seaweedDir, "go.mod")); err == nil {
|
||||
break
|
||||
}
|
||||
seaweedDir = filepath.Dir(seaweedDir)
|
||||
}
|
||||
|
||||
weedBinary := filepath.Join(seaweedDir, "weed", "weed")
|
||||
info, err := os.Stat(weedBinary)
|
||||
if err != nil || info.IsDir() {
|
||||
weedBinary = "weed"
|
||||
if _, err := exec.LookPath(weedBinary); err != nil {
|
||||
t.Skip("weed binary not found, skipping integration test")
|
||||
}
|
||||
}
|
||||
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("Docker not available, skipping integration test")
|
||||
}
|
||||
|
||||
// Create a unique temporary directory for this test run
|
||||
dataDir, err := os.MkdirTemp("", "seaweed-sts-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
// The Cleanup method will remove this directory, so no need for defer here.
|
||||
|
||||
bindIP := testutil.FindBindIP()
|
||||
|
||||
masterPort, masterGrpcPort := testutil.MustFreePortPair(t, "Master")
|
||||
volumePort, volumeGrpcPort := testutil.MustFreePortPair(t, "Volume")
|
||||
filerPort, filerGrpcPort := testutil.MustFreePortPair(t, "Filer")
|
||||
s3Port, s3GrpcPort := testutil.MustFreePortPair(t, "S3") // Changed to use testutil.MustFreePortPair
|
||||
|
||||
return &TestEnvironment{
|
||||
seaweedDir: seaweedDir,
|
||||
weedBinary: weedBinary,
|
||||
dataDir: dataDir,
|
||||
bindIP: bindIP,
|
||||
s3Port: s3Port,
|
||||
s3GrpcPort: s3GrpcPort,
|
||||
masterPort: masterPort,
|
||||
masterGrpcPort: masterGrpcPort,
|
||||
filerPort: filerPort,
|
||||
filerGrpcPort: filerGrpcPort,
|
||||
volumePort: volumePort,
|
||||
volumeGrpcPort: volumeGrpcPort,
|
||||
dockerAvailable: testutil.HasDocker(),
|
||||
accessKey: "admin", // Matching default in testutil.WriteIAMConfig
|
||||
secretKey: "admin",
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
// Create IAM config file
|
||||
iamConfigPath, err := testutil.WriteIAMConfig(env.dataDir, env.accessKey, env.secretKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create IAM config: %v", err)
|
||||
}
|
||||
|
||||
// Create empty security.toml
|
||||
securityToml := filepath.Join(env.dataDir, "security.toml")
|
||||
if err := os.WriteFile(securityToml, []byte("# Empty security config for testing\n"), 0644); err != nil {
|
||||
t.Fatalf("Failed to create security.toml: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
env.weedCancel = cancel
|
||||
|
||||
cmd := exec.CommandContext(ctx, env.weedBinary, "mini",
|
||||
"-master.port", fmt.Sprintf("%d", env.masterPort),
|
||||
"-master.port.grpc", fmt.Sprintf("%d", env.masterGrpcPort),
|
||||
"-volume.port", fmt.Sprintf("%d", env.volumePort),
|
||||
"-volume.port.grpc", fmt.Sprintf("%d", env.volumeGrpcPort),
|
||||
"-filer.port", fmt.Sprintf("%d", env.filerPort),
|
||||
"-filer.port.grpc", fmt.Sprintf("%d", env.filerGrpcPort),
|
||||
"-s3.port", fmt.Sprintf("%d", env.s3Port),
|
||||
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
|
||||
"-s3.config", iamConfigPath,
|
||||
"-ip", env.bindIP,
|
||||
"-ip.bind", "0.0.0.0",
|
||||
"-dir", env.dataDir,
|
||||
)
|
||||
cmd.Dir = env.dataDir
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("Failed to start SeaweedFS: %v", err)
|
||||
}
|
||||
env.weedProcess = cmd
|
||||
|
||||
// Wait for S3 API to be ready
|
||||
if !testutil.WaitForService(fmt.Sprintf("http://localhost:%d/status", env.s3Port), 30*time.Second) {
|
||||
t.Fatalf("S3 API failed to become ready")
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Start(t *testing.T) {
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("Docker not available")
|
||||
}
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
t.Helper()
|
||||
if env.weedCancel != nil {
|
||||
env.weedCancel()
|
||||
}
|
||||
if env.weedProcess != nil {
|
||||
time.Sleep(1 * time.Second)
|
||||
_ = env.weedProcess.Wait()
|
||||
}
|
||||
if env.dataDir != "" {
|
||||
_ = os.RemoveAll(env.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
func runPythonSTSClient(t *testing.T, env *TestEnvironment) {
|
||||
t.Helper()
|
||||
|
||||
// Write python script to temp dir
|
||||
scriptContent := fmt.Sprintf(`
|
||||
import boto3
|
||||
import botocore.config
|
||||
from botocore.exceptions import ClientError
|
||||
import os
|
||||
import sys
|
||||
|
||||
print("Starting STS test...")
|
||||
|
||||
endpoint_url = "http://host.docker.internal:%d"
|
||||
access_key = "%s"
|
||||
secret_key = "%s"
|
||||
region = "us-east-1"
|
||||
|
||||
print(f"Connecting to {endpoint_url} with key {access_key}")
|
||||
|
||||
try:
|
||||
config = botocore.config.Config(
|
||||
retries={'max_attempts': 0}
|
||||
)
|
||||
sts = boto3.client(
|
||||
'sts',
|
||||
endpoint_url=endpoint_url,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
region_name=region,
|
||||
config=config
|
||||
)
|
||||
|
||||
role_arn = "arn:aws:iam::000000000000:role/test-role"
|
||||
session_name = "test-session"
|
||||
|
||||
print(f"Calling AssumeRole on {role_arn}")
|
||||
|
||||
# This call typically sends parameters in POST body by default in boto3
|
||||
response = sts.assume_role(
|
||||
RoleArn=role_arn,
|
||||
RoleSessionName=session_name
|
||||
)
|
||||
|
||||
print("Success! Got credentials:")
|
||||
print(response['Credentials'])
|
||||
|
||||
except ClientError as e:
|
||||
# Print available keys for debugging if needed
|
||||
# print(e.response.keys())
|
||||
|
||||
response_meta = e.response.get('ResponseMetadata', {})
|
||||
http_code = response_meta.get('HTTPStatusCode')
|
||||
|
||||
error_data = e.response.get('Error', {})
|
||||
error_code = error_data.get('Code', 'Unknown')
|
||||
|
||||
print(f"Got error: {http_code} {error_code}")
|
||||
|
||||
# We expect 503 ServiceUnavailable because stsHandlers is nil in weed mini
|
||||
# This confirms the request was routed to STS handler logic (UnifiedPostHandler)
|
||||
# instead of IAM handler (which would return 403 AccessDenied or 501 NotImplemented)
|
||||
if http_code == 503:
|
||||
print("SUCCESS: Got expected 503 Service Unavailable (STS not configured)")
|
||||
sys.exit(0)
|
||||
|
||||
print(f"FAILED: Unexpected error {e}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"FAILED: {e}")
|
||||
sys.exit(1)
|
||||
`, env.s3Port, env.accessKey, env.secretKey)
|
||||
|
||||
scriptPath := filepath.Join(env.dataDir, "sts_test.py")
|
||||
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0644); err != nil {
|
||||
t.Fatalf("Failed to write python script: %v", err)
|
||||
}
|
||||
|
||||
containerName := "seaweed-sts-client-" + fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
|
||||
cmd := exec.Command("docker", "run", "--rm",
|
||||
"--name", containerName,
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-v", fmt.Sprintf("%s:/work", env.dataDir),
|
||||
"python:3",
|
||||
"/bin/bash", "-c", "pip install boto3 && python /work/sts_test.py",
|
||||
)
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("Python STS client failed: %v\nOutput:\n%s", err, string(output))
|
||||
}
|
||||
t.Logf("Python STS client output:\n%s", string(output))
|
||||
}
|
||||
|
||||
// Helpers copied from trino_catalog_test.go
|
||||
@@ -0,0 +1,66 @@
|
||||
package testutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func HasDocker() bool {
|
||||
cmd := exec.Command("docker", "version")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
func MustFreePortPair(t *testing.T, name string) (int, int) {
|
||||
httpPort, grpcPort, err := findAvailablePortPair()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get free port pair for %s: %v", name, err)
|
||||
}
|
||||
return httpPort, grpcPort
|
||||
}
|
||||
|
||||
func findAvailablePortPair() (int, int, error) {
|
||||
httpPort, err := GetFreePort()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
grpcPort, err := GetFreePort()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return httpPort, grpcPort, nil
|
||||
}
|
||||
|
||||
func GetFreePort() (int, error) {
|
||||
listener, err := net.Listen("tcp", "0.0.0.0:0")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer listener.Close()
|
||||
return listener.Addr().(*net.TCPAddr).Port, nil
|
||||
}
|
||||
|
||||
func WaitForService(url string, timeout time.Duration) bool {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
ticker := time.NewTicker(500 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-ticker.C:
|
||||
resp, err := client.Get(url)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,19 @@ type tableBucketMetadata struct {
|
||||
|
||||
const s3TablesAdminListLimit = 1000
|
||||
|
||||
func parseNamespaceInput(namespace string) ([]string, error) {
|
||||
return s3tables.ParseNamespace(namespace)
|
||||
}
|
||||
|
||||
func (s *AdminServer) parseNamespaceFromGin(c *gin.Context, namespace string) ([]string, bool) {
|
||||
parts, err := parseNamespaceInput(namespace)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid namespace: " + err.Error()})
|
||||
return nil, false
|
||||
}
|
||||
return parts, true
|
||||
}
|
||||
|
||||
func newS3TablesManager() *s3tables.Manager {
|
||||
manager := s3tables.NewManager()
|
||||
manager.SetAccountID(s3_constants.AccountAdminId)
|
||||
@@ -158,7 +171,11 @@ func (s *AdminServer) GetS3TablesTablesData(ctx context.Context, bucketArn, name
|
||||
var resp s3tables.ListTablesResponse
|
||||
var ns []string
|
||||
if namespace != "" {
|
||||
ns = []string{namespace}
|
||||
parts, err := parseNamespaceInput(namespace)
|
||||
if err != nil {
|
||||
return S3TablesTablesData{}, err
|
||||
}
|
||||
ns = parts
|
||||
}
|
||||
req := &s3tables.ListTablesRequest{TableBucketARN: bucketArn, Namespace: ns, MaxTables: s3TablesAdminListLimit}
|
||||
if err := s.executeS3TablesOperation(ctx, "ListTables", req, &resp); err != nil {
|
||||
@@ -257,9 +274,13 @@ func (s *AdminServer) GetIcebergTablesData(ctx context.Context, catalogName, buc
|
||||
// GetIcebergTableDetailsData returns Iceberg table metadata and snapshot information.
|
||||
func (s *AdminServer) GetIcebergTableDetailsData(ctx context.Context, catalogName, bucketArn, namespace, tableName string) (IcebergTableDetailsData, error) {
|
||||
var resp s3tables.GetTableResponse
|
||||
namespaceParts, err := parseNamespaceInput(namespace)
|
||||
if err != nil {
|
||||
return IcebergTableDetailsData{}, err
|
||||
}
|
||||
req := &s3tables.GetTableRequest{
|
||||
TableBucketARN: bucketArn,
|
||||
Namespace: []string{namespace},
|
||||
Namespace: namespaceParts,
|
||||
Name: tableName,
|
||||
}
|
||||
if err := s.executeS3TablesOperation(ctx, "GetTable", req, &resp); err != nil {
|
||||
@@ -686,7 +707,11 @@ func (s *AdminServer) CreateS3TablesNamespace(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "bucket_arn and name are required"})
|
||||
return
|
||||
}
|
||||
createReq := &s3tables.CreateNamespaceRequest{TableBucketARN: req.BucketARN, Namespace: []string{req.Name}}
|
||||
namespaceParts, ok := s.parseNamespaceFromGin(c, req.Name)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
createReq := &s3tables.CreateNamespaceRequest{TableBucketARN: req.BucketARN, Namespace: namespaceParts}
|
||||
var resp s3tables.CreateNamespaceResponse
|
||||
if err := s.executeS3TablesOperation(c.Request.Context(), "CreateNamespace", createReq, &resp); err != nil {
|
||||
writeS3TablesError(c, err)
|
||||
@@ -705,7 +730,11 @@ func (s *AdminServer) DeleteS3TablesNamespace(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "bucket and name query parameters are required"})
|
||||
return
|
||||
}
|
||||
req := &s3tables.DeleteNamespaceRequest{TableBucketARN: bucketArn, Namespace: []string{namespace}}
|
||||
namespaceParts, ok := s.parseNamespaceFromGin(c, namespace)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
req := &s3tables.DeleteNamespaceRequest{TableBucketARN: bucketArn, Namespace: namespaceParts}
|
||||
if err := s.executeS3TablesOperation(c.Request.Context(), "DeleteNamespace", req, nil); err != nil {
|
||||
writeS3TablesError(c, err)
|
||||
return
|
||||
@@ -745,6 +774,10 @@ func (s *AdminServer) CreateS3TablesTable(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "bucket_arn, namespace, and name are required"})
|
||||
return
|
||||
}
|
||||
namespaceParts, ok := s.parseNamespaceFromGin(c, req.Namespace)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
format := req.Format
|
||||
if format == "" {
|
||||
format = "ICEBERG"
|
||||
@@ -757,7 +790,7 @@ func (s *AdminServer) CreateS3TablesTable(c *gin.Context) {
|
||||
}
|
||||
createReq := &s3tables.CreateTableRequest{
|
||||
TableBucketARN: req.BucketARN,
|
||||
Namespace: []string{req.Namespace},
|
||||
Namespace: namespaceParts,
|
||||
Name: req.Name,
|
||||
Format: format,
|
||||
Tags: req.Tags,
|
||||
@@ -780,7 +813,11 @@ func (s *AdminServer) DeleteS3TablesTable(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "bucket, namespace, and name query parameters are required"})
|
||||
return
|
||||
}
|
||||
req := &s3tables.DeleteTableRequest{TableBucketARN: bucketArn, Namespace: []string{namespace}, Name: name, VersionToken: version}
|
||||
namespaceParts, ok := s.parseNamespaceFromGin(c, namespace)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
req := &s3tables.DeleteTableRequest{TableBucketARN: bucketArn, Namespace: namespaceParts, Name: name, VersionToken: version}
|
||||
if err := s.executeS3TablesOperation(c.Request.Context(), "DeleteTable", req, nil); err != nil {
|
||||
writeS3TablesError(c, err)
|
||||
return
|
||||
@@ -853,7 +890,11 @@ func (s *AdminServer) PutS3TablesTablePolicy(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "bucket_arn, namespace, name, and policy are required"})
|
||||
return
|
||||
}
|
||||
putReq := &s3tables.PutTablePolicyRequest{TableBucketARN: req.BucketARN, Namespace: []string{req.Namespace}, Name: req.Name, ResourcePolicy: req.Policy}
|
||||
namespaceParts, ok := s.parseNamespaceFromGin(c, req.Namespace)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
putReq := &s3tables.PutTablePolicyRequest{TableBucketARN: req.BucketARN, Namespace: namespaceParts, Name: req.Name, ResourcePolicy: req.Policy}
|
||||
if err := s.executeS3TablesOperation(c.Request.Context(), "PutTablePolicy", putReq, nil); err != nil {
|
||||
writeS3TablesError(c, err)
|
||||
return
|
||||
@@ -869,7 +910,11 @@ func (s *AdminServer) GetS3TablesTablePolicy(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "bucket, namespace, and name query parameters are required"})
|
||||
return
|
||||
}
|
||||
getReq := &s3tables.GetTablePolicyRequest{TableBucketARN: bucketArn, Namespace: []string{namespace}, Name: name}
|
||||
namespaceParts, ok := s.parseNamespaceFromGin(c, namespace)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
getReq := &s3tables.GetTablePolicyRequest{TableBucketARN: bucketArn, Namespace: namespaceParts, Name: name}
|
||||
var resp s3tables.GetTablePolicyResponse
|
||||
if err := s.executeS3TablesOperation(c.Request.Context(), "GetTablePolicy", getReq, &resp); err != nil {
|
||||
writeS3TablesError(c, err)
|
||||
@@ -886,7 +931,11 @@ func (s *AdminServer) DeleteS3TablesTablePolicy(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "bucket, namespace, and name query parameters are required"})
|
||||
return
|
||||
}
|
||||
deleteReq := &s3tables.DeleteTablePolicyRequest{TableBucketARN: bucketArn, Namespace: []string{namespace}, Name: name}
|
||||
namespaceParts, ok := s.parseNamespaceFromGin(c, namespace)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
deleteReq := &s3tables.DeleteTablePolicyRequest{TableBucketARN: bucketArn, Namespace: namespaceParts, Name: name}
|
||||
if err := s.executeS3TablesOperation(c.Request.Context(), "DeleteTablePolicy", deleteReq, nil); err != nil {
|
||||
writeS3TablesError(c, err)
|
||||
return
|
||||
|
||||
@@ -725,20 +725,27 @@ function s3TablesNamespaceNameError(name) {
|
||||
if (name.includes('/')) {
|
||||
return "namespace name cannot contain '/'";
|
||||
}
|
||||
if (!isLowercaseLetterOrDigit(name[0])) {
|
||||
return 'Namespace name must start with a letter or digit';
|
||||
}
|
||||
if (!isLowercaseLetterOrDigit(name[name.length - 1])) {
|
||||
return 'Namespace name must end with a letter or digit';
|
||||
}
|
||||
for (const ch of name) {
|
||||
if (isLowercaseLetterOrDigit(ch) || ch === '_') {
|
||||
continue;
|
||||
|
||||
const parts = name.split('.');
|
||||
for (const part of parts) {
|
||||
if (!part) {
|
||||
return 'namespace levels cannot be empty';
|
||||
}
|
||||
if (!isLowercaseLetterOrDigit(part[0])) {
|
||||
return 'Namespace name must start with a letter or digit';
|
||||
}
|
||||
if (!isLowercaseLetterOrDigit(part[part.length - 1])) {
|
||||
return 'Namespace name must end with a letter or digit';
|
||||
}
|
||||
for (const ch of part) {
|
||||
if (isLowercaseLetterOrDigit(ch) || ch === '_') {
|
||||
continue;
|
||||
}
|
||||
return "invalid namespace name: only 'a-z', '0-9', and '_' are allowed";
|
||||
}
|
||||
if (part.startsWith('aws')) {
|
||||
return "namespace name cannot start with reserved prefix 'aws'";
|
||||
}
|
||||
return "invalid namespace name: only 'a-z', '0-9', and '_' are allowed";
|
||||
}
|
||||
if (name.startsWith('aws')) {
|
||||
return "namespace name cannot start with reserved prefix 'aws'";
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -7,8 +7,12 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
|
||||
)
|
||||
|
||||
script changePageSize(path string, lastFileName string) {
|
||||
window.location.href = '/files?path=' + encodeURIComponent(path) + '&lastFileName=' + encodeURIComponent(lastFileName) + '&limit=' + this.value
|
||||
script changePageSize(path string, lastFileName string, pageSizeSelectId string) {
|
||||
const pageSizeSelect = document.getElementById(pageSizeSelectId)
|
||||
if (pageSizeSelect == null) {
|
||||
return
|
||||
}
|
||||
window.location.href = '/files?path=' + encodeURIComponent(path) + '&lastFileName=' + encodeURIComponent(lastFileName) + '&limit=' + pageSizeSelect.value
|
||||
}
|
||||
|
||||
templ FileBrowser(data dash.FileBrowserData) {
|
||||
@@ -94,7 +98,7 @@ templ FileBrowser(data dash.FileBrowserData) {
|
||||
<div class="d-flex align-items-center gap-2 ms-auto">
|
||||
<div class="d-flex align-items-center">
|
||||
<label class="me-1 mb-0 small text-muted">Show:</label>
|
||||
<select class="form-select form-select-sm" style="width: 70px; font-size: 0.875rem;" onchange={ changePageSize(data.CurrentPath, data.CurrentLastFileName) }>
|
||||
<select id="file-browser-page-size-top" class="form-select form-select-sm" style="width: 70px; font-size: 0.875rem;" onchange={ changePageSize(data.CurrentPath, data.CurrentLastFileName, "file-browser-page-size-top") }>
|
||||
<option value="20" selected?={ data.PageSize == 20 }>20</option>
|
||||
<option value="50" selected?={ data.PageSize == 50 }>50</option>
|
||||
<option value="100" selected?={ data.PageSize == 100 }>100</option>
|
||||
@@ -221,7 +225,7 @@ templ FileBrowser(data dash.FileBrowserData) {
|
||||
<div class="col-md-6">
|
||||
<div class="d-flex align-items-center">
|
||||
<label class="me-2 mb-0">Show:</label>
|
||||
<select class="form-select form-select-sm" style="width: auto;" onchange={ changePageSize(data.CurrentPath, data.CurrentLastFileName) }>
|
||||
<select id="file-browser-page-size-bottom" class="form-select form-select-sm" style="width: auto;" onchange={ changePageSize(data.CurrentPath, data.CurrentLastFileName, "file-browser-page-size-bottom") }>
|
||||
<option value="20" selected?={ data.PageSize == 20 }>20</option>
|
||||
<option value="50" selected?={ data.PageSize == 50 }>50</option>
|
||||
<option value="100" selected?={ data.PageSize == 100 }>100</option>
|
||||
|
||||
@@ -15,13 +15,17 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
func changePageSize(path string, lastFileName string) templ.ComponentScript {
|
||||
func changePageSize(path string, lastFileName string, pageSizeSelectId string) templ.ComponentScript {
|
||||
return templ.ComponentScript{
|
||||
Name: `__templ_changePageSize_6f57`,
|
||||
Function: `function __templ_changePageSize_6f57(path, lastFileName){window.location.href = '/files?path=' + encodeURIComponent(path) + '&lastFileName=' + encodeURIComponent(lastFileName) + '&limit=' + this.value
|
||||
Name: `__templ_changePageSize_43f7`,
|
||||
Function: `function __templ_changePageSize_43f7(path, lastFileName, pageSizeSelectId){const pageSizeSelect = document.getElementById(pageSizeSelectId)
|
||||
if (pageSizeSelect == null) {
|
||||
return
|
||||
}
|
||||
window.location.href = '/files?path=' + encodeURIComponent(path) + '&lastFileName=' + encodeURIComponent(lastFileName) + '&limit=' + pageSizeSelect.value
|
||||
}`,
|
||||
Call: templ.SafeScript(`__templ_changePageSize_6f57`, path, lastFileName),
|
||||
CallInline: templ.SafeScriptInline(`__templ_changePageSize_6f57`, path, lastFileName),
|
||||
Call: templ.SafeScript(`__templ_changePageSize_43f7`, path, lastFileName, pageSizeSelectId),
|
||||
CallInline: templ.SafeScriptInline(`__templ_changePageSize_43f7`, path, lastFileName, pageSizeSelectId),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +62,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(data.TableBucketName)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 18, Col: 71}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 22, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -72,7 +76,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(data.BucketName)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 20, Col: 62}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 24, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -112,7 +116,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var4 templ.SafeURL
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=%s", crumb.Path)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 58, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 62, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -125,7 +129,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(crumb.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 59, Col: 19}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 63, Col: 19}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -143,7 +147,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var6 templ.SafeURL
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=%s", crumb.Path)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 64, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 68, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -162,7 +166,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(crumb.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 68, Col: 19}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 72, Col: 19}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -196,7 +200,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var8 templ.SafeURL
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=%s", data.CurrentPath)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 89, Col: 76}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 93, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -209,7 +213,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(filepath.Base(data.CurrentPath))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 89, Col: 154}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 93, Col: 154}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -224,15 +228,15 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_Buffer, changePageSize(data.CurrentPath, data.CurrentLastFileName))
|
||||
templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_Buffer, changePageSize(data.CurrentPath, data.CurrentLastFileName, "file-browser-page-size-top"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<select class=\"form-select form-select-sm\" style=\"width: 70px; font-size: 0.875rem;\" onchange=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<select id=\"file-browser-page-size-top\" class=\"form-select form-select-sm\" style=\"width: 70px; font-size: 0.875rem;\" onchange=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 templ.ComponentScript = changePageSize(data.CurrentPath, data.CurrentLastFileName)
|
||||
var templ_7745c5c3_Var10 templ.ComponentScript = changePageSize(data.CurrentPath, data.CurrentLastFileName, "file-browser-page-size-top")
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10.Call)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
@@ -289,7 +293,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var11 templ.SafeURL
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=%s&lastFileName=%s&limit=%d", data.CurrentPath, data.LastFileName, data.PageSize)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 106, Col: 137}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 110, Col: 137}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -313,7 +317,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var12 templ.SafeURL
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=%s", data.ParentPath)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 115, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 119, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -341,7 +345,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(entry.FullPath)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 143, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 147, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -359,7 +363,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var14 templ.SafeURL
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=%s", entry.FullPath)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 149, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 153, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -372,7 +376,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(entry.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 150, Col: 25}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 154, Col: 25}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -408,7 +412,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(entry.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 154, Col: 30}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 158, Col: 30}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -432,7 +436,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(entry.Size))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 162, Col: 36}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 166, Col: 36}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -452,7 +456,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(getMimeDisplayName(entry.Mime))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 170, Col: 44}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 174, Col: 44}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -467,7 +471,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(entry.ModTime.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 176, Col: 53}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 180, Col: 53}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -486,7 +490,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(entry.Mode)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 182, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 186, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -499,7 +503,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", entry.IsDirectory))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 182, Col: 131}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 186, Col: 131}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -512,7 +516,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(entry.Mode)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 182, Col: 146}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 186, Col: 146}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -530,7 +534,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(entry.FullPath)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 187, Col: 139}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 191, Col: 139}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -543,7 +547,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(entry.FullPath)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 190, Col: 128}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 194, Col: 128}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -561,7 +565,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(entry.FullPath)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 194, Col: 144}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 198, Col: 144}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -574,7 +578,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(entry.FullPath)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 197, Col: 133}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 201, Col: 133}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -599,15 +603,15 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_Buffer, changePageSize(data.CurrentPath, data.CurrentLastFileName))
|
||||
templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_Buffer, changePageSize(data.CurrentPath, data.CurrentLastFileName, "file-browser-page-size-bottom"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "<select class=\"form-select form-select-sm\" style=\"width: auto;\" onchange=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "<select id=\"file-browser-page-size-bottom\" class=\"form-select form-select-sm\" style=\"width: auto;\" onchange=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var29 templ.ComponentScript = changePageSize(data.CurrentPath, data.CurrentLastFileName)
|
||||
var templ_7745c5c3_Var29 templ.ComponentScript = changePageSize(data.CurrentPath, data.CurrentLastFileName, "file-browser-page-size-bottom")
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29.Call)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
@@ -664,7 +668,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var30 templ.SafeURL
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=%s&lastFileName=%s&limit=%d", data.CurrentPath, data.LastFileName, data.PageSize)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 237, Col: 137}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 241, Col: 137}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -687,7 +691,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 252, Col: 66}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 256, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -700,7 +704,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(data.CurrentPath)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 277, Col: 87}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 281, Col: 87}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -713,7 +717,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(data.CurrentPath)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 309, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/file_browser.templ`, Line: 313, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
|
||||
@@ -195,7 +195,7 @@ templ IcebergNamespaces(data dash.IcebergNamespacesData) {
|
||||
<div class="mb-3">
|
||||
<label for="icebergNamespaceName" class="form-label">Namespace</label>
|
||||
<input type="text" class="form-control" id="icebergNamespaceName" name="name" placeholder="analytics" required/>
|
||||
<div class="form-text">Use lowercase letters, numbers, and underscores. Nested namespaces are not supported.</div>
|
||||
<div class="form-text">Use lowercase letters, numbers, and underscores. Use dots for nested namespaces (for example, analytics.daily).</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
|
||||
@@ -327,7 +327,7 @@ func IcebergNamespaces(data dash.IcebergNamespacesData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "\"> <input type=\"hidden\" id=\"icebergNamespaceCsrfToken\" name=\"csrf_token\"><div class=\"mb-3\"><label for=\"icebergNamespaceName\" class=\"form-label\">Namespace</label> <input type=\"text\" class=\"form-control\" id=\"icebergNamespaceName\" name=\"name\" placeholder=\"analytics\" required><div class=\"form-text\">Use lowercase letters, numbers, and underscores. Nested namespaces are not supported.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><script>\n\t\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t\tinitIcebergNamespaces();\n\t\t});\n\t</script>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "\"> <input type=\"hidden\" id=\"icebergNamespaceCsrfToken\" name=\"csrf_token\"><div class=\"mb-3\"><label for=\"icebergNamespaceName\" class=\"form-label\">Namespace</label> <input type=\"text\" class=\"form-control\" id=\"icebergNamespaceName\" name=\"name\" placeholder=\"analytics\" required><div class=\"form-text\">Use lowercase letters, numbers, and underscores. Use dots for nested namespaces (for example, analytics.daily).</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><script>\n\t\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t\tinitIcebergNamespaces();\n\t\t});\n\t</script>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -154,14 +154,14 @@ templ S3TablesNamespaces(data dash.S3TablesNamespacesData) {
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form id="createS3TablesNamespaceForm">
|
||||
<div class="modal-body">
|
||||
<input type="hidden" name="bucket_arn" value={ data.BucketARN }/>
|
||||
<div class="mb-3">
|
||||
<label for="s3tablesNamespaceName" class="form-label">Namespace</label>
|
||||
<input type="text" class="form-control" id="s3tablesNamespaceName" name="name" placeholder="analytics" required/>
|
||||
<div class="form-text">Use lowercase letters, numbers, and underscores. Nested namespaces are not supported.</div>
|
||||
<div class="modal-body">
|
||||
<input type="hidden" name="bucket_arn" value={ data.BucketARN }/>
|
||||
<div class="mb-3">
|
||||
<label for="s3tablesNamespaceName" class="form-label">Namespace</label>
|
||||
<input type="text" class="form-control" id="s3tablesNamespaceName" name="name" placeholder="analytics" required/>
|
||||
<div class="form-text">Use lowercase letters, numbers, and underscores. Use dots for nested namespaces (for example, analytics.daily).</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary">
|
||||
@@ -235,41 +235,53 @@ templ S3TablesNamespaces(data dash.S3TablesNamespacesData) {
|
||||
input.setCustomValidity('');
|
||||
return '';
|
||||
}
|
||||
let message = '';
|
||||
if (!name) {
|
||||
message = 'Namespace name is required';
|
||||
} else if (name.length < 1 || name.length > 255) {
|
||||
message = 'Namespace name must be between 1 and 255 characters';
|
||||
} else if (name === '.' || name === '..') {
|
||||
message = "namespace name cannot be '.' or '..'";
|
||||
} else if (name.includes('/')) {
|
||||
message = "namespace name cannot contain '/'";
|
||||
} else {
|
||||
const start = name[0];
|
||||
const end = name[name.length - 1];
|
||||
const isStartValid = (start >= 'a' && start <= 'z') || (start >= '0' && start <= '9');
|
||||
const isEndValid = (end >= 'a' && end <= 'z') || (end >= '0' && end <= '9');
|
||||
if (!isStartValid) {
|
||||
message = 'Namespace name must start with a letter or digit';
|
||||
} else if (!isEndValid) {
|
||||
message = 'Namespace name must end with a letter or digit';
|
||||
let message = '';
|
||||
if (!name) {
|
||||
message = 'Namespace name is required';
|
||||
} else if (name.length < 1 || name.length > 255) {
|
||||
message = 'Namespace name must be between 1 and 255 characters';
|
||||
} else if (name === '.' || name === '..') {
|
||||
message = "namespace name cannot be '.' or '..'";
|
||||
} else if (name.includes('/')) {
|
||||
message = "namespace name cannot contain '/'";
|
||||
} else {
|
||||
for (const ch of name) {
|
||||
const isLower = ch >= 'a' && ch <= 'z';
|
||||
const isDigit = ch >= '0' && ch <= '9';
|
||||
if (!(isLower || isDigit || ch === '_')) {
|
||||
message = "invalid namespace name: only 'a-z', '0-9', and '_' are allowed";
|
||||
for (const part of name.split('.')) {
|
||||
if (!part) {
|
||||
message = 'namespace levels cannot be empty';
|
||||
break;
|
||||
}
|
||||
const start = part[0];
|
||||
const end = part[part.length - 1];
|
||||
const isStartValid = (start >= 'a' && start <= 'z') || (start >= '0' && start <= '9');
|
||||
const isEndValid = (end >= 'a' && end <= 'z') || (end >= '0' && end <= '9');
|
||||
if (!isStartValid) {
|
||||
message = 'Namespace name must start with a letter or digit';
|
||||
break;
|
||||
}
|
||||
if (!isEndValid) {
|
||||
message = 'Namespace name must end with a letter or digit';
|
||||
break;
|
||||
}
|
||||
for (const ch of part) {
|
||||
const isLower = ch >= 'a' && ch <= 'z';
|
||||
const isDigit = ch >= '0' && ch <= '9';
|
||||
if (!(isLower || isDigit || ch === '_')) {
|
||||
message = "invalid namespace name: only 'a-z', '0-9', and '_' are allowed";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (message) {
|
||||
break;
|
||||
}
|
||||
if (part.startsWith('aws')) {
|
||||
message = "namespace name cannot start with reserved prefix 'aws'";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!message && name.startsWith('aws')) {
|
||||
message = "namespace name cannot start with reserved prefix 'aws'";
|
||||
}
|
||||
}
|
||||
input.setCustomValidity(message);
|
||||
return message;
|
||||
}
|
||||
input.setCustomValidity(message);
|
||||
return message;
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
s3tablesNamespaceDeleteModalInstance = new bootstrap.Modal(document.getElementById('deleteS3TablesNamespaceModal'));
|
||||
|
||||
@@ -236,13 +236,13 @@ func S3TablesNamespaces(data dash.S3TablesNamespacesData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(data.BucketARN)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_namespaces.templ`, Line: 158, Col: 67}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3tables_namespaces.templ`, Line: 158, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\"><div class=\"mb-3\"><label for=\"s3tablesNamespaceName\" class=\"form-label\">Namespace</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesNamespaceName\" name=\"name\" placeholder=\"analytics\" required><div class=\"form-text\">Use lowercase letters, numbers, and underscores. Nested namespaces are not supported.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><div class=\"modal fade\" id=\"deleteS3TablesNamespaceModal\" tabindex=\"-1\" aria-labelledby=\"deleteS3TablesNamespaceModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteS3TablesNamespaceModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Namespace</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the namespace <strong id=\"deleteS3TablesNamespaceName\"></strong>?</p></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteS3TablesNamespace()\"><i class=\"fas fa-trash me-1\"></i>Delete</button></div></div></div></div><script>\n\t\tlet s3tablesNamespaceDeleteModalInstance = null;\n\t\tconst dataBucketArn = document.getElementById('s3tables-namespaces-content').dataset.bucketArn || '';\n\t\tconst csrfTokenMeta = document.querySelector('meta[name=\"csrf-token\"]');\n\t\tconst csrfToken = csrfTokenMeta ? (csrfTokenMeta.getAttribute('content') || '') : '';\n\n\t\tfunction makeJSONHeaders() {\n\t\t\tconst headers = { 'Content-Type': 'application/json' };\n\t\t\tif (csrfToken) {\n\t\t\t\theaders['X-CSRF-Token'] = csrfToken;\n\t\t\t}\n\t\t\treturn headers;\n\t\t}\n\n\t\tasync function readErrorMessage(response, fallbackMessage) {\n\t\t\tconst responseBody = await response.text();\n\t\t\tif (!responseBody) {\n\t\t\t\treturn fallbackMessage;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(responseBody);\n\t\t\t\tif (payload && typeof payload.error === 'string' && payload.error) {\n\t\t\t\t\treturn payload.error;\n\t\t\t\t}\n\t\t\t\tif (payload && typeof payload.message === 'string' && payload.message) {\n\t\t\t\t\treturn payload.message;\n\t\t\t\t}\n\t\t\t} catch (parseError) {\n\t\t\t\t// Fall through to the raw response body when parsing fails.\n\t\t\t}\n\t\t\treturn responseBody;\n\t\t}\n\n\t\tfunction validateNamespaceInput(input, allowEmpty) {\n\t\t\tif (typeof window.applyS3TablesNamespaceNameValidity === 'function') {\n\t\t\t\treturn window.applyS3TablesNamespaceNameValidity(input, allowEmpty);\n\t\t\t}\n\t\t\tconst name = (input.value || '').trim();\n\t\t\tif (allowEmpty && name === '') {\n\t\t\t\tinput.setCustomValidity('');\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tlet message = '';\n\t\t\tif (!name) {\n\t\t\t\tmessage = 'Namespace name is required';\n\t\t\t} else if (name.length < 1 || name.length > 255) {\n\t\t\t\tmessage = 'Namespace name must be between 1 and 255 characters';\n\t\t\t} else if (name === '.' || name === '..') {\n\t\t\t\tmessage = \"namespace name cannot be '.' or '..'\";\n\t\t\t} else if (name.includes('/')) {\n\t\t\t\tmessage = \"namespace name cannot contain '/'\";\n\t\t\t} else {\n\t\t\t\tconst start = name[0];\n\t\t\t\tconst end = name[name.length - 1];\n\t\t\t\tconst isStartValid = (start >= 'a' && start <= 'z') || (start >= '0' && start <= '9');\n\t\t\t\tconst isEndValid = (end >= 'a' && end <= 'z') || (end >= '0' && end <= '9');\n\t\t\t\tif (!isStartValid) {\n\t\t\t\t\tmessage = 'Namespace name must start with a letter or digit';\n\t\t\t\t} else if (!isEndValid) {\n\t\t\t\t\tmessage = 'Namespace name must end with a letter or digit';\n\t\t\t\t} else {\n\t\t\t\t\tfor (const ch of name) {\n\t\t\t\t\t\tconst isLower = ch >= 'a' && ch <= 'z';\n\t\t\t\t\t\tconst isDigit = ch >= '0' && ch <= '9';\n\t\t\t\t\t\tif (!(isLower || isDigit || ch === '_')) {\n\t\t\t\t\t\t\tmessage = \"invalid namespace name: only 'a-z', '0-9', and '_' are allowed\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!message && name.startsWith('aws')) {\n\t\t\t\t\t\tmessage = \"namespace name cannot start with reserved prefix 'aws'\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tinput.setCustomValidity(message);\n\t\t\treturn message;\n\t\t}\n\n\t\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t\ts3tablesNamespaceDeleteModalInstance = new bootstrap.Modal(document.getElementById('deleteS3TablesNamespaceModal'));\n\n\t\t\tdocument.querySelectorAll('.s3tables-delete-namespace-btn').forEach(button => {\n\t\t\t\tbutton.addEventListener(Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\"><div class=\"mb-3\"><label for=\"s3tablesNamespaceName\" class=\"form-label\">Namespace</label> <input type=\"text\" class=\"form-control\" id=\"s3tablesNamespaceName\" name=\"name\" placeholder=\"analytics\" required><div class=\"form-text\">Use lowercase letters, numbers, and underscores. Use dots for nested namespaces (for example, analytics.daily).</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create</button></div></form></div></div></div><div class=\"modal fade\" id=\"deleteS3TablesNamespaceModal\" tabindex=\"-1\" aria-labelledby=\"deleteS3TablesNamespaceModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteS3TablesNamespaceModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Namespace</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the namespace <strong id=\"deleteS3TablesNamespaceName\"></strong>?</p></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteS3TablesNamespace()\"><i class=\"fas fa-trash me-1\"></i>Delete</button></div></div></div></div><script>\n\t\tlet s3tablesNamespaceDeleteModalInstance = null;\n\t\tconst dataBucketArn = document.getElementById('s3tables-namespaces-content').dataset.bucketArn || '';\n\t\tconst csrfTokenMeta = document.querySelector('meta[name=\"csrf-token\"]');\n\t\tconst csrfToken = csrfTokenMeta ? (csrfTokenMeta.getAttribute('content') || '') : '';\n\n\t\tfunction makeJSONHeaders() {\n\t\t\tconst headers = { 'Content-Type': 'application/json' };\n\t\t\tif (csrfToken) {\n\t\t\t\theaders['X-CSRF-Token'] = csrfToken;\n\t\t\t}\n\t\t\treturn headers;\n\t\t}\n\n\t\tasync function readErrorMessage(response, fallbackMessage) {\n\t\t\tconst responseBody = await response.text();\n\t\t\tif (!responseBody) {\n\t\t\t\treturn fallbackMessage;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(responseBody);\n\t\t\t\tif (payload && typeof payload.error === 'string' && payload.error) {\n\t\t\t\t\treturn payload.error;\n\t\t\t\t}\n\t\t\t\tif (payload && typeof payload.message === 'string' && payload.message) {\n\t\t\t\t\treturn payload.message;\n\t\t\t\t}\n\t\t\t} catch (parseError) {\n\t\t\t\t// Fall through to the raw response body when parsing fails.\n\t\t\t}\n\t\t\treturn responseBody;\n\t\t}\n\n\t\tfunction validateNamespaceInput(input, allowEmpty) {\n\t\t\tif (typeof window.applyS3TablesNamespaceNameValidity === 'function') {\n\t\t\t\treturn window.applyS3TablesNamespaceNameValidity(input, allowEmpty);\n\t\t\t}\n\t\t\tconst name = (input.value || '').trim();\n\t\t\tif (allowEmpty && name === '') {\n\t\t\t\tinput.setCustomValidity('');\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\t\tlet message = '';\n\t\t\t\tif (!name) {\n\t\t\t\t\tmessage = 'Namespace name is required';\n\t\t\t\t} else if (name.length < 1 || name.length > 255) {\n\t\t\t\t\tmessage = 'Namespace name must be between 1 and 255 characters';\n\t\t\t\t} else if (name === '.' || name === '..') {\n\t\t\t\t\tmessage = \"namespace name cannot be '.' or '..'\";\n\t\t\t\t} else if (name.includes('/')) {\n\t\t\t\t\tmessage = \"namespace name cannot contain '/'\";\n\t\t\t\t} else {\n\t\t\t\t\tfor (const part of name.split('.')) {\n\t\t\t\t\t\tif (!part) {\n\t\t\t\t\t\t\tmessage = 'namespace levels cannot be empty';\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst start = part[0];\n\t\t\t\t\t\tconst end = part[part.length - 1];\n\t\t\t\t\t\tconst isStartValid = (start >= 'a' && start <= 'z') || (start >= '0' && start <= '9');\n\t\t\t\t\t\tconst isEndValid = (end >= 'a' && end <= 'z') || (end >= '0' && end <= '9');\n\t\t\t\t\t\tif (!isStartValid) {\n\t\t\t\t\t\t\tmessage = 'Namespace name must start with a letter or digit';\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!isEndValid) {\n\t\t\t\t\t\t\tmessage = 'Namespace name must end with a letter or digit';\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const ch of part) {\n\t\t\t\t\t\t\tconst isLower = ch >= 'a' && ch <= 'z';\n\t\t\t\t\t\t\tconst isDigit = ch >= '0' && ch <= '9';\n\t\t\t\t\t\t\tif (!(isLower || isDigit || ch === '_')) {\n\t\t\t\t\t\t\t\tmessage = \"invalid namespace name: only 'a-z', '0-9', and '_' are allowed\";\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (message) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (part.startsWith('aws')) {\n\t\t\t\t\t\t\tmessage = \"namespace name cannot start with reserved prefix 'aws'\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -390,11 +390,10 @@ func (option *RemoteGatewayOptions) detectBucketInfo(actualDir string) (bucket u
|
||||
}
|
||||
|
||||
func extractBucketPath(bucketsDir, dir string) (util.FullPath, bool) {
|
||||
if !strings.HasPrefix(dir, bucketsDir+"/") {
|
||||
return "", false
|
||||
if bucketPath, ok := util.ExtractBucketPath(bucketsDir, dir, false); ok {
|
||||
return util.FullPath(bucketPath), true
|
||||
}
|
||||
parts := strings.SplitN(dir[len(bucketsDir)+1:], "/", 2)
|
||||
return util.FullPath(bucketsDir).Child(parts[0]), true
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (option *RemoteGatewayOptions) collectRemoteStorageConf() (err error) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/user"
|
||||
"path"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -26,6 +27,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"google.golang.org/grpc/reflection"
|
||||
@@ -59,6 +61,63 @@ func runMount(cmd *Command, args []string) bool {
|
||||
return RunMount(&mountOptions, os.FileMode(umask))
|
||||
}
|
||||
|
||||
func ensureBucketAllowEmptyFolders(ctx context.Context, filerClient filer_pb.FilerClient, mountRoot, bucketRootPath string) error {
|
||||
bucketPath, isBucketRootMount := bucketPathForMountRoot(mountRoot, bucketRootPath)
|
||||
if !isBucketRootMount {
|
||||
return nil
|
||||
}
|
||||
|
||||
entry, err := filer_pb.GetEntry(ctx, filerClient, util.FullPath(bucketPath))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry == nil {
|
||||
return fmt.Errorf("bucket %s not found", bucketPath)
|
||||
}
|
||||
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(string(entry.Extended[s3_constants.ExtAllowEmptyFolders])), "true") {
|
||||
return nil
|
||||
}
|
||||
|
||||
entry.Extended[s3_constants.ExtAllowEmptyFolders] = []byte("true")
|
||||
|
||||
bucketFullPath := util.FullPath(bucketPath)
|
||||
parent, _ := bucketFullPath.DirAndName()
|
||||
if err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
|
||||
Directory: parent,
|
||||
Entry: entry,
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glog.V(3).Infof("RunMount: set bucket %s %s=true", bucketPath, s3_constants.ExtAllowEmptyFolders)
|
||||
return nil
|
||||
}
|
||||
|
||||
func bucketPathForMountRoot(mountRoot, bucketRootPath string) (string, bool) {
|
||||
cleanPath := path.Clean("/" + strings.TrimPrefix(mountRoot, "/"))
|
||||
cleanBucketRoot := path.Clean("/" + strings.TrimPrefix(bucketRootPath, "/"))
|
||||
if cleanBucketRoot == "/" {
|
||||
return "", false
|
||||
}
|
||||
prefix := cleanBucketRoot + "/"
|
||||
if !strings.HasPrefix(cleanPath, prefix) {
|
||||
return "", false
|
||||
}
|
||||
rest := strings.TrimPrefix(cleanPath, prefix)
|
||||
|
||||
bucketParts := strings.Split(rest, "/")
|
||||
if len(bucketParts) != 1 || bucketParts[0] == "" {
|
||||
return "", false
|
||||
}
|
||||
return cleanBucketRoot + "/" + bucketParts[0], true
|
||||
}
|
||||
|
||||
func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
|
||||
// basic checks
|
||||
@@ -73,6 +132,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
var cipher bool
|
||||
var bucketRootPath string
|
||||
var err error
|
||||
for i := 0; i < 10; i++ {
|
||||
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
@@ -81,6 +141,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err)
|
||||
}
|
||||
cipher = resp.Cipher
|
||||
bucketRootPath = resp.DirBuckets
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -93,6 +154,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
glog.Errorf("failed to talk to filer %v: %v", filerAddresses, err)
|
||||
return true
|
||||
}
|
||||
if bucketRootPath == "" {
|
||||
bucketRootPath = "/buckets"
|
||||
}
|
||||
|
||||
filerMountRootPath := *option.filerMountRootPath
|
||||
|
||||
@@ -287,6 +351,10 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
fmt.Printf("failed to create dir %s on filer %s: %v\n", mountRoot, filerAddresses, err)
|
||||
return false
|
||||
}
|
||||
if err := ensureBucketAllowEmptyFolders(context.Background(), seaweedFileSystem, mountRoot, bucketRootPath); err != nil {
|
||||
fmt.Printf("failed to set bucket auto-remove-empty-folders policy for %s: %v\n", mountRoot, err)
|
||||
return false
|
||||
}
|
||||
|
||||
server, err := fuse.NewServer(seaweedFileSystem, dir, fuseMountOptions)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//go:build linux || darwin || freebsd
|
||||
// +build linux darwin freebsd
|
||||
|
||||
package command
|
||||
|
||||
import "testing"
|
||||
|
||||
func Test_bucketPathForMountRoot(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mountRoot string
|
||||
expected string
|
||||
ok bool
|
||||
}{
|
||||
{
|
||||
name: "bucket root mount",
|
||||
mountRoot: "/buckets/test",
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "bucket root with trailing slash",
|
||||
mountRoot: "/buckets/test/",
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "subdirectory mount",
|
||||
mountRoot: "/buckets/test/data",
|
||||
expected: "",
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "non-bucket mount",
|
||||
mountRoot: "/data/test",
|
||||
expected: "",
|
||||
ok: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotPath, gotOK := bucketPathForMountRoot(tt.mountRoot, "/buckets")
|
||||
if gotOK != tt.ok {
|
||||
t.Fatalf("expected ok=%v, got %v", tt.ok, gotOK)
|
||||
}
|
||||
if gotPath != tt.expected {
|
||||
t.Fatalf("expected path %q, got %q", tt.expected, gotPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,9 @@ type CleanupQueue struct {
|
||||
|
||||
// queueItem represents an item in the cleanup queue
|
||||
type queueItem struct {
|
||||
folder string
|
||||
queueTime time.Time
|
||||
folder string
|
||||
triggeredBy string
|
||||
queueTime time.Time
|
||||
}
|
||||
|
||||
// NewCleanupQueue creates a new CleanupQueue with the specified limits
|
||||
@@ -39,7 +40,7 @@ func NewCleanupQueue(maxSize int, maxAge time.Duration) *CleanupQueue {
|
||||
// The item is inserted in time-sorted order (oldest at front) to handle out-of-order events.
|
||||
// If folder already exists with an older time, the time is updated and position adjusted.
|
||||
// Returns true if the folder was newly added, false if it was updated.
|
||||
func (q *CleanupQueue) Add(folder string, eventTime time.Time) bool {
|
||||
func (q *CleanupQueue) Add(folder string, triggeredBy string, eventTime time.Time) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
|
||||
@@ -51,23 +52,24 @@ func (q *CleanupQueue) Add(folder string, eventTime time.Time) bool {
|
||||
// Remove from current position
|
||||
q.items.Remove(elem)
|
||||
// Re-insert with new time in sorted position
|
||||
newElem := q.insertSorted(folder, eventTime)
|
||||
newElem := q.insertSorted(folder, triggeredBy, eventTime)
|
||||
q.itemsMap[folder] = newElem
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Insert new folder in sorted position
|
||||
elem := q.insertSorted(folder, eventTime)
|
||||
elem := q.insertSorted(folder, triggeredBy, eventTime)
|
||||
q.itemsMap[folder] = elem
|
||||
return true
|
||||
}
|
||||
|
||||
// insertSorted inserts an item in the correct position to maintain time ordering (oldest at front)
|
||||
func (q *CleanupQueue) insertSorted(folder string, eventTime time.Time) *list.Element {
|
||||
func (q *CleanupQueue) insertSorted(folder string, triggeredBy string, eventTime time.Time) *list.Element {
|
||||
item := &queueItem{
|
||||
folder: folder,
|
||||
queueTime: eventTime,
|
||||
folder: folder,
|
||||
triggeredBy: triggeredBy,
|
||||
queueTime: eventTime,
|
||||
}
|
||||
|
||||
// Find the correct position (insert before the first item with a later time)
|
||||
@@ -135,35 +137,35 @@ func (q *CleanupQueue) shouldProcessLocked() bool {
|
||||
|
||||
// Pop removes and returns the oldest folder from the queue.
|
||||
// Returns the folder and true if an item was available, or empty string and false if queue is empty.
|
||||
func (q *CleanupQueue) Pop() (string, bool) {
|
||||
func (q *CleanupQueue) Pop() (string, string, bool) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
|
||||
front := q.items.Front()
|
||||
if front == nil {
|
||||
return "", false
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
item := front.Value.(*queueItem)
|
||||
q.items.Remove(front)
|
||||
delete(q.itemsMap, item.folder)
|
||||
|
||||
return item.folder, true
|
||||
return item.folder, item.triggeredBy, true
|
||||
}
|
||||
|
||||
// Peek returns the oldest folder without removing it.
|
||||
// Returns the folder and queue time if available, or empty values if queue is empty.
|
||||
func (q *CleanupQueue) Peek() (folder string, queueTime time.Time, ok bool) {
|
||||
func (q *CleanupQueue) Peek() (folder string, triggeredBy string, queueTime time.Time, ok bool) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
|
||||
front := q.items.Front()
|
||||
if front == nil {
|
||||
return "", time.Time{}, false
|
||||
return "", "", time.Time{}, false
|
||||
}
|
||||
|
||||
item := front.Value.(*queueItem)
|
||||
return item.folder, item.queueTime, true
|
||||
return item.folder, item.triggeredBy, item.queueTime, true
|
||||
}
|
||||
|
||||
// Len returns the current queue size.
|
||||
|
||||
@@ -10,7 +10,7 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
// Add first item
|
||||
if !q.Add("/buckets/b1/folder1", now) {
|
||||
if !q.Add("/buckets/b1/folder1", "item1", now) {
|
||||
t.Error("expected Add to return true for new item")
|
||||
}
|
||||
if q.Len() != 1 {
|
||||
@@ -18,7 +18,7 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
}
|
||||
|
||||
// Add second item with later time
|
||||
if !q.Add("/buckets/b1/folder2", now.Add(1*time.Second)) {
|
||||
if !q.Add("/buckets/b1/folder2", "item2", now.Add(1*time.Second)) {
|
||||
t.Error("expected Add to return true for new item")
|
||||
}
|
||||
if q.Len() != 2 {
|
||||
@@ -26,7 +26,7 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
}
|
||||
|
||||
// Add duplicate with newer time - should update and reposition
|
||||
if q.Add("/buckets/b1/folder1", now.Add(2*time.Second)) {
|
||||
if q.Add("/buckets/b1/folder1", "item1-updated", now.Add(2*time.Second)) {
|
||||
t.Error("expected Add to return false for existing item")
|
||||
}
|
||||
if q.Len() != 2 {
|
||||
@@ -34,11 +34,14 @@ func TestCleanupQueue_Add(t *testing.T) {
|
||||
}
|
||||
|
||||
// folder1 should now be at the back (newer time) - verify by popping
|
||||
folder1, _ := q.Pop()
|
||||
folder2, _ := q.Pop()
|
||||
folder1, triggered1, _ := q.Pop()
|
||||
folder2, triggered2, _ := q.Pop()
|
||||
if folder1 != "/buckets/b1/folder2" || folder2 != "/buckets/b1/folder1" {
|
||||
t.Errorf("expected folder1 to be moved to back, got %s, %s", folder1, folder2)
|
||||
}
|
||||
if triggered1 != "item2" || triggered2 != "item1-updated" {
|
||||
t.Errorf("triggeredBy mismatch: got %s, %s", triggered1, triggered2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupQueue_Add_OutOfOrder(t *testing.T) {
|
||||
@@ -46,16 +49,23 @@ func TestCleanupQueue_Add_OutOfOrder(t *testing.T) {
|
||||
baseTime := time.Now()
|
||||
|
||||
// Add items out of order
|
||||
q.Add("/buckets/b1/folder3", baseTime.Add(3*time.Second))
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder2", baseTime.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "f3", baseTime.Add(3*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "f1", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder2", "f2", baseTime.Add(2*time.Second))
|
||||
|
||||
// Items should be in time order (oldest first) - verify by popping
|
||||
expected := []string{"/buckets/b1/folder1", "/buckets/b1/folder2", "/buckets/b1/folder3"}
|
||||
expected := []struct {
|
||||
folder string
|
||||
item string
|
||||
}{
|
||||
{"/buckets/b1/folder1", "f1"},
|
||||
{"/buckets/b1/folder2", "f2"},
|
||||
{"/buckets/b1/folder3", "f3"},
|
||||
}
|
||||
for i, exp := range expected {
|
||||
folder, ok := q.Pop()
|
||||
if !ok || folder != exp {
|
||||
t.Errorf("at index %d: expected %s, got %s", i, exp, folder)
|
||||
folder, item, ok := q.Pop()
|
||||
if !ok || folder != exp.folder || item != exp.item {
|
||||
t.Errorf("at index %d: expected %s by %s, got %s by %s", i, exp.folder, exp.item, folder, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,15 +75,15 @@ func TestCleanupQueue_Add_DuplicateWithOlderTime(t *testing.T) {
|
||||
baseTime := time.Now()
|
||||
|
||||
// Add folder at t=5
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(5*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "t5", baseTime.Add(5*time.Second))
|
||||
|
||||
// Try to add same folder with older time - should NOT update
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "t2", baseTime.Add(2*time.Second))
|
||||
|
||||
// Time should remain at t=5
|
||||
_, queueTime, _ := q.Peek()
|
||||
if queueTime != baseTime.Add(5*time.Second) {
|
||||
t.Errorf("expected time to remain unchanged, got %v", queueTime)
|
||||
// Time and triggeredBy should remain at t=5
|
||||
_, triggered, queueTime, _ := q.Peek()
|
||||
if queueTime != baseTime.Add(5*time.Second) || triggered != "t5" {
|
||||
t.Errorf("expected time to remain unchanged, got %v and %s", queueTime, triggered)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,9 +91,9 @@ func TestCleanupQueue_Remove(t *testing.T) {
|
||||
q := NewCleanupQueue(100, 10*time.Minute)
|
||||
now := time.Now()
|
||||
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
|
||||
// Remove middle item
|
||||
if !q.Remove("/buckets/b1/folder2") {
|
||||
@@ -102,8 +112,8 @@ func TestCleanupQueue_Remove(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify order is preserved by popping
|
||||
folder1, _ := q.Pop()
|
||||
folder3, _ := q.Pop()
|
||||
folder1, _, _ := q.Pop()
|
||||
folder3, _, _ := q.Pop()
|
||||
if folder1 != "/buckets/b1/folder1" || folder3 != "/buckets/b1/folder3" {
|
||||
t.Errorf("unexpected order: %s, %s", folder1, folder3)
|
||||
}
|
||||
@@ -114,30 +124,30 @@ func TestCleanupQueue_Pop(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
// Pop from empty queue
|
||||
folder, ok := q.Pop()
|
||||
folder, item, ok := q.Pop()
|
||||
if ok {
|
||||
t.Error("expected Pop to return false for empty queue")
|
||||
}
|
||||
if folder != "" {
|
||||
t.Errorf("expected empty folder, got %s", folder)
|
||||
if folder != "" || item != "" {
|
||||
t.Errorf("expected empty results, got %s by %s", folder, item)
|
||||
}
|
||||
|
||||
// Add items and pop in order
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
|
||||
folder, ok = q.Pop()
|
||||
folder, _, ok = q.Pop()
|
||||
if !ok || folder != "/buckets/b1/folder1" {
|
||||
t.Errorf("expected folder1, got %s (ok=%v)", folder, ok)
|
||||
}
|
||||
|
||||
folder, ok = q.Pop()
|
||||
folder, _, ok = q.Pop()
|
||||
if !ok || folder != "/buckets/b1/folder2" {
|
||||
t.Errorf("expected folder2, got %s (ok=%v)", folder, ok)
|
||||
}
|
||||
|
||||
folder, ok = q.Pop()
|
||||
folder, _, ok = q.Pop()
|
||||
if !ok || folder != "/buckets/b1/folder3" {
|
||||
t.Errorf("expected folder3, got %s (ok=%v)", folder, ok)
|
||||
}
|
||||
@@ -153,16 +163,16 @@ func TestCleanupQueue_Peek(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
// Peek empty queue
|
||||
folder, _, ok := q.Peek()
|
||||
folder, item, _, ok := q.Peek()
|
||||
if ok {
|
||||
t.Error("expected Peek to return false for empty queue")
|
||||
}
|
||||
|
||||
// Add item and peek
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
folder, queueTime, ok := q.Peek()
|
||||
if !ok || folder != "/buckets/b1/folder1" {
|
||||
t.Errorf("expected folder1, got %s (ok=%v)", folder, ok)
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
folder, item, queueTime, ok := q.Peek()
|
||||
if !ok || folder != "/buckets/b1/folder1" || item != "i1" {
|
||||
t.Errorf("expected folder1 by i1, got %s by %s (ok=%v)", folder, item, ok)
|
||||
}
|
||||
if queueTime != now {
|
||||
t.Errorf("expected queue time %v, got %v", now, queueTime)
|
||||
@@ -178,7 +188,7 @@ func TestCleanupQueue_Contains(t *testing.T) {
|
||||
q := NewCleanupQueue(100, 10*time.Minute)
|
||||
now := time.Now()
|
||||
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
|
||||
if !q.Contains("/buckets/b1/folder1") {
|
||||
t.Error("expected Contains to return true")
|
||||
@@ -198,14 +208,14 @@ func TestCleanupQueue_ShouldProcess_MaxSize(t *testing.T) {
|
||||
}
|
||||
|
||||
// Add items below max
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
if q.ShouldProcess() {
|
||||
t.Error("queue below max should not need processing")
|
||||
}
|
||||
|
||||
// Add item to reach max
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
if !q.ShouldProcess() {
|
||||
t.Error("queue at max should need processing")
|
||||
}
|
||||
@@ -216,7 +226,7 @@ func TestCleanupQueue_ShouldProcess_MaxAge(t *testing.T) {
|
||||
|
||||
// Add item with old event time
|
||||
oldTime := time.Now().Add(-1 * time.Second) // 1 second ago
|
||||
q.Add("/buckets/b1/folder1", oldTime)
|
||||
q.Add("/buckets/b1/folder1", "i1", oldTime)
|
||||
|
||||
// Item is older than maxAge, should need processing
|
||||
if !q.ShouldProcess() {
|
||||
@@ -225,7 +235,7 @@ func TestCleanupQueue_ShouldProcess_MaxAge(t *testing.T) {
|
||||
|
||||
// Clear and add fresh item
|
||||
q.Clear()
|
||||
q.Add("/buckets/b1/folder2", time.Now())
|
||||
q.Add("/buckets/b1/folder2", "i2", time.Now())
|
||||
|
||||
// Fresh item should not trigger processing
|
||||
if q.ShouldProcess() {
|
||||
@@ -237,9 +247,9 @@ func TestCleanupQueue_Clear(t *testing.T) {
|
||||
q := NewCleanupQueue(100, 10*time.Minute)
|
||||
now := time.Now()
|
||||
|
||||
q.Add("/buckets/b1/folder1", now)
|
||||
q.Add("/buckets/b1/folder2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", now.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "i1", now)
|
||||
q.Add("/buckets/b1/folder2", "i2", now.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", now.Add(2*time.Second))
|
||||
|
||||
q.Clear()
|
||||
|
||||
@@ -261,7 +271,7 @@ func TestCleanupQueue_OldestAge(t *testing.T) {
|
||||
|
||||
// Add item with time in the past
|
||||
oldTime := time.Now().Add(-5 * time.Minute)
|
||||
q.Add("/buckets/b1/folder1", oldTime)
|
||||
q.Add("/buckets/b1/folder1", "i1", oldTime)
|
||||
|
||||
// Age should be approximately 5 minutes
|
||||
age := q.OldestAge()
|
||||
@@ -283,12 +293,12 @@ func TestCleanupQueue_TimeOrder(t *testing.T) {
|
||||
"/buckets/b1/e",
|
||||
}
|
||||
for i, item := range items {
|
||||
q.Add(item, baseTime.Add(time.Duration(i)*time.Second))
|
||||
q.Add(item, "i", baseTime.Add(time.Duration(i)*time.Second))
|
||||
}
|
||||
|
||||
// Pop should return in time order
|
||||
for i, expected := range items {
|
||||
got, ok := q.Pop()
|
||||
got, _, ok := q.Pop()
|
||||
if !ok {
|
||||
t.Errorf("Pop %d: expected item, got empty", i)
|
||||
}
|
||||
@@ -303,17 +313,17 @@ func TestCleanupQueue_DuplicateWithNewerTime(t *testing.T) {
|
||||
baseTime := time.Now()
|
||||
|
||||
// Add items
|
||||
q.Add("/buckets/b1/folder1", baseTime)
|
||||
q.Add("/buckets/b1/folder2", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", baseTime.Add(2*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "i1", baseTime)
|
||||
q.Add("/buckets/b1/folder2", "i2", baseTime.Add(1*time.Second))
|
||||
q.Add("/buckets/b1/folder3", "i3", baseTime.Add(2*time.Second))
|
||||
|
||||
// Add duplicate with newer time - should update and reposition
|
||||
q.Add("/buckets/b1/folder1", baseTime.Add(3*time.Second))
|
||||
q.Add("/buckets/b1/folder1", "i1-new", baseTime.Add(3*time.Second))
|
||||
|
||||
// folder1 should now be at the back (newest time) - verify by popping
|
||||
expected := []string{"/buckets/b1/folder2", "/buckets/b1/folder3", "/buckets/b1/folder1"}
|
||||
for i, exp := range expected {
|
||||
folder, ok := q.Pop()
|
||||
folder, _, ok := q.Pop()
|
||||
if !ok || folder != exp {
|
||||
t.Errorf("at index %d: expected %s, got %s", i, exp, folder)
|
||||
}
|
||||
@@ -328,7 +338,7 @@ func TestCleanupQueue_Concurrent(t *testing.T) {
|
||||
// Concurrent adds
|
||||
go func() {
|
||||
for i := 0; i < 100; i++ {
|
||||
q.Add("/buckets/b1/folder"+string(rune('A'+i%26)), now.Add(time.Duration(i)*time.Millisecond))
|
||||
q.Add("/buckets/b1/folder"+string(rune('A'+i%26)), "item", now.Add(time.Duration(i)*time.Millisecond))
|
||||
}
|
||||
done <- true
|
||||
}()
|
||||
|
||||
@@ -18,7 +18,7 @@ const (
|
||||
DefaultMaxCountCheck = 1000
|
||||
DefaultCacheExpiry = 5 * time.Minute
|
||||
DefaultQueueMaxSize = 1000
|
||||
DefaultQueueMaxAge = 10 * time.Minute
|
||||
DefaultQueueMaxAge = 5 * time.Second
|
||||
DefaultProcessorSleep = 10 * time.Second // How often to check queue
|
||||
)
|
||||
|
||||
@@ -32,12 +32,17 @@ type FilerOperations interface {
|
||||
// folderState tracks the state of a folder for empty folder cleanup
|
||||
type folderState struct {
|
||||
roughCount int // Cached rough count (up to maxCountCheck)
|
||||
isImplicit *bool // Tri-state boolean: nil (unknown), true (implicit), false (explicit)
|
||||
lastAddTime time.Time // Last time an item was added
|
||||
lastDelTime time.Time // Last time an item was deleted
|
||||
lastCheck time.Time // Last time we checked the actual count
|
||||
}
|
||||
|
||||
type bucketCleanupPolicyState struct {
|
||||
autoRemove bool
|
||||
attrValue string
|
||||
lastCheck time.Time
|
||||
}
|
||||
|
||||
// EmptyFolderCleaner handles asynchronous cleanup of empty folders
|
||||
// Each filer owns specific folders via consistent hashing based on the peer filer list
|
||||
type EmptyFolderCleaner struct {
|
||||
@@ -46,8 +51,9 @@ type EmptyFolderCleaner struct {
|
||||
host pb.ServerAddress
|
||||
|
||||
// Folder state tracking
|
||||
mu sync.RWMutex
|
||||
folderCounts map[string]*folderState // Rough count cache
|
||||
mu sync.RWMutex
|
||||
folderCounts map[string]*folderState // Rough count cache
|
||||
bucketCleanupPolicies map[string]*bucketCleanupPolicyState // bucket path -> cleanup policy cache
|
||||
|
||||
// Cleanup queue (thread-safe, has its own lock)
|
||||
cleanupQueue *CleanupQueue
|
||||
@@ -66,17 +72,18 @@ type EmptyFolderCleaner struct {
|
||||
// NewEmptyFolderCleaner creates a new EmptyFolderCleaner
|
||||
func NewEmptyFolderCleaner(filer FilerOperations, lockRing *lock_manager.LockRing, host pb.ServerAddress, bucketPath string) *EmptyFolderCleaner {
|
||||
efc := &EmptyFolderCleaner{
|
||||
filer: filer,
|
||||
lockRing: lockRing,
|
||||
host: host,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
cleanupQueue: NewCleanupQueue(DefaultQueueMaxSize, DefaultQueueMaxAge),
|
||||
maxCountCheck: DefaultMaxCountCheck,
|
||||
cacheExpiry: DefaultCacheExpiry,
|
||||
processorSleep: DefaultProcessorSleep,
|
||||
bucketPath: bucketPath,
|
||||
enabled: true,
|
||||
stopCh: make(chan struct{}),
|
||||
filer: filer,
|
||||
lockRing: lockRing,
|
||||
host: host,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
bucketCleanupPolicies: make(map[string]*bucketCleanupPolicyState),
|
||||
cleanupQueue: NewCleanupQueue(DefaultQueueMaxSize, DefaultQueueMaxAge),
|
||||
maxCountCheck: DefaultMaxCountCheck,
|
||||
cacheExpiry: DefaultCacheExpiry,
|
||||
processorSleep: DefaultProcessorSleep,
|
||||
bucketPath: bucketPath,
|
||||
enabled: true,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
go efc.cacheEvictionLoop()
|
||||
go efc.cleanupProcessor()
|
||||
@@ -162,8 +169,8 @@ func (efc *EmptyFolderCleaner) OnDeleteEvent(directory string, entryName string,
|
||||
}
|
||||
|
||||
// Add to cleanup queue with event time (handles out-of-order events)
|
||||
if efc.cleanupQueue.Add(directory, eventTime) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: queued %s for cleanup", directory)
|
||||
if efc.cleanupQueue.Add(directory, entryName, eventTime) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: queued %s for cleanup (triggered by %s)", directory, entryName)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +221,10 @@ func (efc *EmptyFolderCleaner) cleanupProcessor() {
|
||||
func (efc *EmptyFolderCleaner) processCleanupQueue() {
|
||||
// Check if we should process
|
||||
if !efc.cleanupQueue.ShouldProcess() {
|
||||
if efc.cleanupQueue.Len() > 0 {
|
||||
glog.Infof("EmptyFolderCleaner: pending queue not processed yet (len=%d, oldest_age=%v, max_size=%d, max_age=%v)",
|
||||
efc.cleanupQueue.Len(), efc.cleanupQueue.OldestAge(), efc.cleanupQueue.maxSize, efc.cleanupQueue.maxAge)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -228,35 +239,30 @@ func (efc *EmptyFolderCleaner) processCleanupQueue() {
|
||||
}
|
||||
|
||||
// Pop the oldest item
|
||||
folder, ok := efc.cleanupQueue.Pop()
|
||||
folder, triggeredBy, ok := efc.cleanupQueue.Pop()
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
|
||||
// Execute cleanup for this folder
|
||||
efc.executeCleanup(folder)
|
||||
|
||||
// If queue is no longer full and oldest item is not old enough, stop processing
|
||||
if !efc.cleanupQueue.ShouldProcess() {
|
||||
break
|
||||
}
|
||||
efc.executeCleanup(folder, triggeredBy)
|
||||
}
|
||||
}
|
||||
|
||||
// executeCleanup performs the actual cleanup of an empty folder
|
||||
func (efc *EmptyFolderCleaner) executeCleanup(folder string) {
|
||||
func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string) {
|
||||
efc.mu.Lock()
|
||||
|
||||
// Quick check: if we have cached count and it's > 0, skip
|
||||
if state, exists := efc.folderCounts[folder]; exists {
|
||||
if state.roughCount > 0 {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s, cached count=%d", folder, state.roughCount)
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s (triggered by %s), cached count=%d", folder, triggeredBy, state.roughCount)
|
||||
efc.mu.Unlock()
|
||||
return
|
||||
}
|
||||
// If there was an add after our delete, skip
|
||||
if !state.lastAddTime.IsZero() && state.lastAddTime.After(state.lastDelTime) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s, add happened after delete", folder)
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping %s (triggered by %s), add happened after delete", folder, triggeredBy)
|
||||
efc.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -265,47 +271,23 @@ func (efc *EmptyFolderCleaner) executeCleanup(folder string) {
|
||||
|
||||
// Re-check ownership (topology might have changed)
|
||||
if !efc.ownsFolder(folder) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: no longer owner of %s, skipping", folder)
|
||||
glog.V(3).Infof("EmptyFolderCleaner: no longer owner of %s (triggered by %s), skipping", folder, triggeredBy)
|
||||
return
|
||||
}
|
||||
|
||||
// Check for explicit implicit_dir attribute
|
||||
// First check cache
|
||||
ctx := context.Background()
|
||||
efc.mu.RLock()
|
||||
var cachedImplicit *bool
|
||||
if state, exists := efc.folderCounts[folder]; exists {
|
||||
cachedImplicit = state.isImplicit
|
||||
}
|
||||
efc.mu.RUnlock()
|
||||
|
||||
var isImplicit bool
|
||||
if cachedImplicit != nil {
|
||||
isImplicit = *cachedImplicit
|
||||
} else {
|
||||
// Not cached, check filer
|
||||
attrs, err := efc.filer.GetEntryAttributes(ctx, util.FullPath(folder))
|
||||
if err != nil {
|
||||
if err == filer_pb.ErrNotFound {
|
||||
return
|
||||
}
|
||||
glog.V(2).Infof("EmptyFolderCleaner: error getting attributes for %s: %v", folder, err)
|
||||
bucketPath, autoRemove, source, attrValue, err := efc.getBucketCleanupPolicy(ctx, folder)
|
||||
if err != nil {
|
||||
if err == filer_pb.ErrNotFound {
|
||||
return
|
||||
}
|
||||
|
||||
isImplicit = attrs != nil && string(attrs[s3_constants.ExtS3ImplicitDir]) == "true"
|
||||
|
||||
// Update cache
|
||||
efc.mu.Lock()
|
||||
if _, exists := efc.folderCounts[folder]; !exists {
|
||||
efc.folderCounts[folder] = &folderState{}
|
||||
}
|
||||
efc.folderCounts[folder].isImplicit = &isImplicit
|
||||
efc.mu.Unlock()
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to load bucket cleanup policy for folder %s (triggered by %s): %v", folder, triggeredBy, err)
|
||||
return
|
||||
}
|
||||
|
||||
if !isImplicit {
|
||||
glog.V(4).Infof("EmptyFolderCleaner: folder %s is not marked as implicit, skipping", folder)
|
||||
if !autoRemove {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: skipping folder %s (triggered by %s), bucket %s auto-remove-empty-folders disabled (source=%s attr=%s)",
|
||||
folder, triggeredBy, bucketPath, source, attrValue)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -326,14 +308,14 @@ func (efc *EmptyFolderCleaner) executeCleanup(folder string) {
|
||||
efc.mu.Unlock()
|
||||
|
||||
if count > 0 {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: folder %s has %d items, not empty", folder, count)
|
||||
glog.Infof("EmptyFolderCleaner: folder %s (triggered by %s) has %d items, not empty", folder, triggeredBy, count)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the empty folder
|
||||
glog.V(2).Infof("EmptyFolderCleaner: deleting empty folder %s", folder)
|
||||
glog.Infof("EmptyFolderCleaner: deleting empty folder %s (triggered by %s)", folder, triggeredBy)
|
||||
if err := efc.deleteFolder(ctx, folder); err != nil {
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to delete empty folder %s: %v", folder, err)
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to delete empty folder %s (triggered by %s): %v", folder, triggeredBy, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -357,6 +339,60 @@ func (efc *EmptyFolderCleaner) deleteFolder(ctx context.Context, folder string)
|
||||
return efc.filer.DeleteEntryMetaAndData(ctx, util.FullPath(folder), false, false, false, false, nil, 0)
|
||||
}
|
||||
|
||||
func (efc *EmptyFolderCleaner) getBucketCleanupPolicy(ctx context.Context, folder string) (bucketPath string, autoRemove bool, source string, attrValue string, err error) {
|
||||
bucketPath, ok := util.ExtractBucketPath(efc.bucketPath, folder, true)
|
||||
if !ok {
|
||||
return "", true, "default", "<not_bucket_path>", nil
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
efc.mu.RLock()
|
||||
if state, found := efc.bucketCleanupPolicies[bucketPath]; found && now.Sub(state.lastCheck) <= efc.cacheExpiry {
|
||||
efc.mu.RUnlock()
|
||||
return bucketPath, state.autoRemove, "cache", state.attrValue, nil
|
||||
}
|
||||
efc.mu.RUnlock()
|
||||
|
||||
attrs, err := efc.filer.GetEntryAttributes(ctx, util.FullPath(bucketPath))
|
||||
if err != nil {
|
||||
return "", true, "", "", err
|
||||
}
|
||||
|
||||
autoRemove, attrValue = autoRemoveEmptyFoldersEnabled(attrs)
|
||||
|
||||
efc.mu.Lock()
|
||||
if efc.bucketCleanupPolicies == nil {
|
||||
efc.bucketCleanupPolicies = make(map[string]*bucketCleanupPolicyState)
|
||||
}
|
||||
efc.bucketCleanupPolicies[bucketPath] = &bucketCleanupPolicyState{
|
||||
autoRemove: autoRemove,
|
||||
attrValue: attrValue,
|
||||
lastCheck: now,
|
||||
}
|
||||
efc.mu.Unlock()
|
||||
|
||||
return bucketPath, autoRemove, "filer", attrValue, nil
|
||||
}
|
||||
|
||||
func autoRemoveEmptyFoldersEnabled(attrs map[string][]byte) (bool, string) {
|
||||
if attrs == nil {
|
||||
return true, "<no_attrs>"
|
||||
}
|
||||
|
||||
value, found := attrs[s3_constants.ExtAllowEmptyFolders]
|
||||
if !found {
|
||||
return true, "<missing>"
|
||||
}
|
||||
|
||||
text := strings.TrimSpace(string(value))
|
||||
if text == "" {
|
||||
return true, "<empty>"
|
||||
}
|
||||
|
||||
return !strings.EqualFold(text, "true"), text
|
||||
}
|
||||
|
||||
// isUnderPath checks if child is under parent path
|
||||
func isUnderPath(child, parent string) bool {
|
||||
if parent == "" || parent == "/" {
|
||||
@@ -445,6 +481,12 @@ func (efc *EmptyFolderCleaner) evictStaleCacheEntries() {
|
||||
}
|
||||
}
|
||||
|
||||
for bucketPath, state := range efc.bucketCleanupPolicies {
|
||||
if now.Sub(state.lastCheck) > efc.cacheExpiry {
|
||||
delete(efc.bucketCleanupPolicies, bucketPath)
|
||||
}
|
||||
}
|
||||
|
||||
if expiredCount > 0 {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: evicted %d stale cache entries", expiredCount)
|
||||
}
|
||||
@@ -460,6 +502,7 @@ func (efc *EmptyFolderCleaner) Stop() {
|
||||
efc.enabled = false
|
||||
efc.cleanupQueue.Clear()
|
||||
efc.folderCounts = make(map[string]*folderState) // Clear cache on stop
|
||||
efc.bucketCleanupPolicies = make(map[string]*bucketCleanupPolicyState)
|
||||
}
|
||||
|
||||
// GetPendingCleanupCount returns the number of pending cleanup tasks (for testing)
|
||||
|
||||
@@ -1,13 +1,43 @@
|
||||
package empty_folder_cleanup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) CountDirectoryEntries(_ context.Context, dirPath util.FullPath, _ int) (int, error) {
|
||||
if m.countFn == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return m.countFn(dirPath)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) DeleteEntryMetaAndData(_ context.Context, p util.FullPath, _, _, _, _ bool, _ []int32, _ int64) error {
|
||||
if m.deleteFn == nil {
|
||||
return nil
|
||||
}
|
||||
return m.deleteFn(p)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) GetEntryAttributes(_ context.Context, p util.FullPath) (map[string][]byte, error) {
|
||||
if m.attrsFn == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return m.attrsFn(p)
|
||||
}
|
||||
|
||||
func Test_isUnderPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -66,6 +96,56 @@ func Test_isUnderBucketPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test_autoRemoveEmptyFoldersEnabled(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
attrs map[string][]byte
|
||||
enabled bool
|
||||
attrValue string
|
||||
}{
|
||||
{
|
||||
name: "no attrs defaults enabled",
|
||||
attrs: nil,
|
||||
enabled: true,
|
||||
attrValue: "<no_attrs>",
|
||||
},
|
||||
{
|
||||
name: "missing key defaults enabled",
|
||||
attrs: map[string][]byte{},
|
||||
enabled: true,
|
||||
attrValue: "<missing>",
|
||||
},
|
||||
{
|
||||
name: "allow-empty disables cleanup",
|
||||
attrs: map[string][]byte{
|
||||
s3_constants.ExtAllowEmptyFolders: []byte("true"),
|
||||
},
|
||||
enabled: false,
|
||||
attrValue: "true",
|
||||
},
|
||||
{
|
||||
name: "explicit false keeps cleanup enabled",
|
||||
attrs: map[string][]byte{
|
||||
s3_constants.ExtAllowEmptyFolders: []byte("false"),
|
||||
},
|
||||
enabled: true,
|
||||
attrValue: "false",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
enabled, attrValue := autoRemoveEmptyFoldersEnabled(tt.attrs)
|
||||
if enabled != tt.enabled {
|
||||
t.Fatalf("expected enabled=%v, got %v", tt.enabled, enabled)
|
||||
}
|
||||
if attrValue != tt.attrValue {
|
||||
t.Fatalf("expected attrValue=%q, got %q", tt.attrValue, attrValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_ownsFolder(t *testing.T) {
|
||||
// Create a LockRing with multiple servers
|
||||
lockRing := lock_manager.NewLockRing(5 * time.Second)
|
||||
@@ -512,7 +592,7 @@ func TestEmptyFolderCleaner_cacheEviction_skipsEntriesInQueue(t *testing.T) {
|
||||
// Add a stale cache entry
|
||||
cleaner.folderCounts[folder] = &folderState{roughCount: 0, lastCheck: oldTime}
|
||||
// Also add to cleanup queue
|
||||
cleaner.cleanupQueue.Add(folder, time.Now())
|
||||
cleaner.cleanupQueue.Add(folder, "item", time.Now())
|
||||
|
||||
// Run eviction
|
||||
cleaner.evictStaleCacheEntries()
|
||||
@@ -558,7 +638,7 @@ func TestEmptyFolderCleaner_queueFIFOOrder(t *testing.T) {
|
||||
|
||||
// Verify time-sorted order by popping
|
||||
for i, expected := range folders {
|
||||
folder, ok := cleaner.cleanupQueue.Pop()
|
||||
folder, _, ok := cleaner.cleanupQueue.Pop()
|
||||
if !ok || folder != expected {
|
||||
t.Errorf("expected folder %s at index %d, got %s", expected, i, folder)
|
||||
}
|
||||
@@ -566,3 +646,90 @@ func TestEmptyFolderCleaner_queueFIFOOrder(t *testing.T) {
|
||||
|
||||
cleaner.Stop()
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_processCleanupQueue_drainsAllOnceTriggered(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
|
||||
},
|
||||
}
|
||||
|
||||
cleaner := &EmptyFolderCleaner{
|
||||
filer: mock,
|
||||
lockRing: lockRing,
|
||||
host: "filer1:8888",
|
||||
bucketPath: "/buckets",
|
||||
enabled: true,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
cleanupQueue: NewCleanupQueue(2, time.Hour),
|
||||
maxCountCheck: 1000,
|
||||
cacheExpiry: time.Minute,
|
||||
processorSleep: time.Second,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
cleaner.cleanupQueue.Add("/buckets/test/folder1", "i1", now)
|
||||
cleaner.cleanupQueue.Add("/buckets/test/folder2", "i2", now.Add(time.Millisecond))
|
||||
cleaner.cleanupQueue.Add("/buckets/test/folder3", "i3", now.Add(2*time.Millisecond))
|
||||
|
||||
cleaner.processCleanupQueue()
|
||||
|
||||
if got := cleaner.cleanupQueue.Len(); got != 0 {
|
||||
t.Fatalf("expected queue to be drained, got len=%d", got)
|
||||
}
|
||||
if len(deleted) != 3 {
|
||||
t.Fatalf("expected 3 deleted folders, got %d", len(deleted))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_executeCleanup_bucketPolicyDisabledSkips(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
|
||||
},
|
||||
attrsFn: func(path util.FullPath) (map[string][]byte, error) {
|
||||
if string(path) == "/buckets/test" {
|
||||
return map[string][]byte{s3_constants.ExtAllowEmptyFolders: []byte("true")}, nil
|
||||
}
|
||||
return nil, 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 len(deleted) != 0 {
|
||||
t.Fatalf("expected folder %s to be skipped, got deletions %v", folder, deleted)
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -9,7 +9,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
@@ -303,12 +302,8 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di
|
||||
GroupNames: entry.GroupNames,
|
||||
},
|
||||
}
|
||||
// level > 3 corresponds to a path depth greater than "/buckets/<bucket_name>",
|
||||
// ensuring we only mark subdirectories within a bucket as implicit.
|
||||
if isUnderBuckets && level > 3 {
|
||||
dirEntry.Extended = map[string][]byte{
|
||||
s3_constants.ExtS3ImplicitDir: []byte("true"),
|
||||
}
|
||||
// Parent directories under buckets are created automatically; no additional logging.
|
||||
}
|
||||
|
||||
glog.V(2).InfofCtx(ctx, "create directory: %s %v", dirPath, dirEntry.Mode)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
@@ -103,7 +104,15 @@ func (m *IAMManager) Initialize(config *IAMConfig, filerAddressProvider func() s
|
||||
|
||||
// Initialize STS service
|
||||
m.stsService = sts.NewSTSService()
|
||||
if err := m.stsService.Initialize(config.STS); err != nil {
|
||||
|
||||
// Use default config if none provided
|
||||
stsConfig := config.STS
|
||||
if stsConfig == nil {
|
||||
glog.V(1).Infof("No STS configuration provided, using defaults")
|
||||
stsConfig = sts.DefaultSTSConfig()
|
||||
}
|
||||
|
||||
if err := m.stsService.Initialize(stsConfig); err != nil {
|
||||
return fmt.Errorf("failed to initialize STS service: %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
)
|
||||
|
||||
// TestIAMManagerInitializeWithoutSTSConfig tests that IAM manager can initialize
|
||||
// without an explicit STS configuration by using defaults
|
||||
func TestIAMManagerInitializeWithoutSTSConfig(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
|
||||
// Create config without STS section (nil)
|
||||
// But with minimal policy and role configs to satisfy other components
|
||||
config := &IAMConfig{
|
||||
STS: nil, // No STS config provided - will use defaults
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
DefaultEffect: "Deny",
|
||||
StoreType: "memory",
|
||||
},
|
||||
Roles: &RoleStoreConfig{
|
||||
StoreType: "memory",
|
||||
},
|
||||
}
|
||||
|
||||
// Initialize should succeed with default STS config
|
||||
err := manager.Initialize(config, func() string { return "localhost:8888" })
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize IAM manager without STS config: %v", err)
|
||||
}
|
||||
|
||||
// Verify STS service is initialized
|
||||
stsService := manager.GetSTSService()
|
||||
if stsService == nil {
|
||||
t.Fatal("STS service is nil after initialization")
|
||||
}
|
||||
|
||||
if !stsService.IsInitialized() {
|
||||
t.Fatal("STS service is not initialized")
|
||||
}
|
||||
|
||||
// Verify the default config was applied
|
||||
if stsService.Config.Issuer != "seaweedfs-sts" {
|
||||
t.Errorf("Expected default issuer 'seaweedfs-sts', got '%s'", stsService.Config.Issuer)
|
||||
}
|
||||
|
||||
if stsService.Config.TokenDuration.Duration != 1*time.Hour {
|
||||
t.Errorf("Expected default token duration 1h, got %v", stsService.Config.TokenDuration.Duration)
|
||||
}
|
||||
|
||||
if stsService.Config.MaxSessionLength.Duration != 12*time.Hour {
|
||||
t.Errorf("Expected default max session length 12h, got %v", stsService.Config.MaxSessionLength.Duration)
|
||||
}
|
||||
|
||||
t.Logf("Successfully initialized STS service with default configuration")
|
||||
}
|
||||
|
||||
// TestIAMManagerInitializeWithExplicitSTSConfig tests that explicit STS config still works
|
||||
func TestIAMManagerInitializeWithExplicitSTSConfig(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
|
||||
// Create config with explicit STS section
|
||||
config := &IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: 30 * time.Minute},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 2 * time.Hour},
|
||||
Issuer: "custom-issuer",
|
||||
SigningKey: []byte("custom-signing-key-for-testing-purposes-only"),
|
||||
AccountId: "999888777666",
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{
|
||||
DefaultEffect: "Deny",
|
||||
StoreType: "memory",
|
||||
},
|
||||
Roles: &RoleStoreConfig{
|
||||
StoreType: "memory",
|
||||
},
|
||||
}
|
||||
|
||||
// Initialize should succeed with explicit config
|
||||
err := manager.Initialize(config, func() string { return "localhost:8888" })
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize IAM manager with explicit STS config: %v", err)
|
||||
}
|
||||
|
||||
// Verify STS service uses the custom config
|
||||
stsService := manager.GetSTSService()
|
||||
if stsService == nil {
|
||||
t.Fatal("STS service is nil after initialization")
|
||||
}
|
||||
|
||||
if !stsService.IsInitialized() {
|
||||
t.Fatal("STS service is not initialized")
|
||||
}
|
||||
|
||||
if stsService.Config.Issuer != "custom-issuer" {
|
||||
t.Errorf("Expected issuer 'custom-issuer', got '%s'", stsService.Config.Issuer)
|
||||
}
|
||||
|
||||
if stsService.Config.AccountId != "999888777666" {
|
||||
t.Errorf("Expected account ID '999888777666', got '%s'", stsService.Config.AccountId)
|
||||
}
|
||||
|
||||
t.Logf("Successfully initialized STS service with explicit configuration")
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package sts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -258,6 +259,28 @@ func NewSTSService() *STSService {
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultSTSConfig returns a default STS configuration with sensible defaults
|
||||
// This ensures the STS service can be initialized even when no explicit configuration is provided
|
||||
func DefaultSTSConfig() *STSConfig {
|
||||
// Generate a secure random signing key
|
||||
signingKey := make([]byte, 32) // 256 bits
|
||||
if _, err := rand.Read(signingKey); err != nil {
|
||||
// Fallback to a warning message if random generation fails
|
||||
// This should never happen in practice, but we handle it defensively
|
||||
glog.Warningf("Failed to generate random signing key, using deterministic fallback: %v", err)
|
||||
signingKey = []byte("default-signing-key-change-in-production-environments")
|
||||
}
|
||||
|
||||
return &STSConfig{
|
||||
TokenDuration: FlexibleDuration{Duration: 1 * time.Hour}, // 1 hour default
|
||||
MaxSessionLength: FlexibleDuration{Duration: 12 * time.Hour}, // 12 hours max
|
||||
Issuer: "seaweedfs-sts",
|
||||
SigningKey: signingKey,
|
||||
AccountId: "111122223333", // Default AWS account ID
|
||||
Providers: nil, // No providers by default
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize initializes the STS service with configuration
|
||||
func (s *STSService) Initialize(config *STSConfig) error {
|
||||
if config == nil {
|
||||
|
||||
@@ -129,6 +129,17 @@ func newUploader(httpClient HTTPClient) *Uploader {
|
||||
// UploadWithRetry will retry both assigning volume request and uploading content
|
||||
// The option parameter does not need to specify UploadUrl and Jwt, which will come from assigning volume.
|
||||
func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assignRequest *filer_pb.AssignVolumeRequest, uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
|
||||
bytesReader, ok := reader.(*util.BytesReader)
|
||||
if ok {
|
||||
data = bytesReader.Bytes
|
||||
} else {
|
||||
data, err = io.ReadAll(reader)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("read input: %w", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
doUploadFunc := func() error {
|
||||
|
||||
var host string
|
||||
@@ -158,7 +169,7 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
|
||||
uploadOption.Jwt = auth
|
||||
|
||||
var uploadErr error
|
||||
uploadResult, uploadErr, data = uploader.doUpload(context.Background(), reader, uploadOption)
|
||||
uploadResult, uploadErr = uploader.retriedUploadData(context.Background(), data, uploadOption)
|
||||
return uploadErr
|
||||
}
|
||||
if uploadOption.RetryForever {
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
package filersink
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
@@ -18,10 +24,13 @@ import (
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
func (fs *FilerSink) replicateChunks(sourceChunks []*filer_pb.FileChunk, path string) (replicatedChunks []*filer_pb.FileChunk, err error) {
|
||||
func (fs *FilerSink) replicateChunks(ctx context.Context, sourceChunks []*filer_pb.FileChunk, path string, sourceMtime int64) (replicatedChunks []*filer_pb.FileChunk, err error) {
|
||||
if len(sourceChunks) == 0 {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
// a simple progress bar. Not ideal. Fix me.
|
||||
var bar *progressbar.ProgressBar
|
||||
@@ -38,26 +47,64 @@ func (fs *FilerSink) replicateChunks(sourceChunks []*filer_pb.FileChunk, path st
|
||||
}
|
||||
|
||||
replicatedChunks = make([]*filer_pb.FileChunk, len(sourceChunks))
|
||||
var errLock sync.Mutex
|
||||
setError := func(e error) {
|
||||
if e == nil {
|
||||
return
|
||||
}
|
||||
errLock.Lock()
|
||||
if err == nil {
|
||||
err = e
|
||||
}
|
||||
errLock.Unlock()
|
||||
}
|
||||
hasError := func() bool {
|
||||
errLock.Lock()
|
||||
defer errLock.Unlock()
|
||||
return err != nil
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for chunkIndex, sourceChunk := range sourceChunks {
|
||||
if hasError() {
|
||||
break
|
||||
}
|
||||
|
||||
if sourceChunk.IsChunkManifest {
|
||||
replicatedChunk, replicateErr := fs.replicateOneManifestChunk(ctx, sourceChunk, path, sourceMtime)
|
||||
if replicateErr != nil {
|
||||
setError(replicateErr)
|
||||
break
|
||||
}
|
||||
replicatedChunks[chunkIndex] = replicatedChunk
|
||||
if bar != nil {
|
||||
bar.Add(1)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
index, source := chunkIndex, sourceChunk
|
||||
fs.executor.Execute(func() {
|
||||
defer wg.Done()
|
||||
util.Retry("replicate chunks", func() error {
|
||||
replicatedChunk, e := fs.replicateOneChunk(source, path)
|
||||
var replicatedChunk *filer_pb.FileChunk
|
||||
retryErr := util.Retry("replicate chunks", func() error {
|
||||
chunk, e := fs.replicateOneChunk(source, path, sourceMtime)
|
||||
if e != nil {
|
||||
err = e
|
||||
return e
|
||||
}
|
||||
replicatedChunks[index] = replicatedChunk
|
||||
if bar != nil {
|
||||
bar.Add(1)
|
||||
}
|
||||
err = nil
|
||||
replicatedChunk = chunk
|
||||
return nil
|
||||
})
|
||||
if retryErr != nil {
|
||||
setError(retryErr)
|
||||
return
|
||||
}
|
||||
|
||||
replicatedChunks[index] = replicatedChunk
|
||||
if bar != nil {
|
||||
bar.Add(1)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
@@ -65,9 +112,9 @@ func (fs *FilerSink) replicateChunks(sourceChunks []*filer_pb.FileChunk, path st
|
||||
return
|
||||
}
|
||||
|
||||
func (fs *FilerSink) replicateOneChunk(sourceChunk *filer_pb.FileChunk, path string) (*filer_pb.FileChunk, error) {
|
||||
func (fs *FilerSink) replicateOneChunk(sourceChunk *filer_pb.FileChunk, path string, sourceMtime int64) (*filer_pb.FileChunk, error) {
|
||||
|
||||
fileId, err := fs.fetchAndWrite(sourceChunk, path)
|
||||
fileId, err := fs.fetchAndWrite(sourceChunk, path, sourceMtime)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("copy %s: %v", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
@@ -81,63 +128,236 @@ func (fs *FilerSink) replicateOneChunk(sourceChunk *filer_pb.FileChunk, path str
|
||||
SourceFileId: sourceChunk.GetFileIdString(),
|
||||
CipherKey: sourceChunk.CipherKey,
|
||||
IsCompressed: sourceChunk.IsCompressed,
|
||||
SseType: sourceChunk.SseType,
|
||||
SseMetadata: sourceChunk.SseMetadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string) (fileId string, err error) {
|
||||
|
||||
filename, header, resp, err := fs.filerSource.ReadPart(sourceChunk.GetFileIdString())
|
||||
func (fs *FilerSink) replicateOneManifestChunk(ctx context.Context, sourceChunk *filer_pb.FileChunk, path string, sourceMtime int64) (*filer_pb.FileChunk, error) {
|
||||
resolvedChunks, err := filer.ResolveOneChunkManifest(ctx, fs.filerSource.LookupFileId, sourceChunk)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read part %s: %v", sourceChunk.GetFileIdString(), err)
|
||||
return nil, fmt.Errorf("resolve manifest %s: %w", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
defer util_http.CloseResponse(resp)
|
||||
|
||||
replicatedResolvedChunks, err := fs.replicateChunks(ctx, resolvedChunks, path, sourceMtime)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("replicate manifest data chunks %s: %w", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
manifestDataChunks := make([]*filer_pb.FileChunk, len(replicatedResolvedChunks))
|
||||
for i, chunk := range replicatedResolvedChunks {
|
||||
copied := *chunk
|
||||
manifestDataChunks[i] = &copied
|
||||
}
|
||||
filer_pb.BeforeEntrySerialization(manifestDataChunks)
|
||||
manifestData, err := proto.Marshal(&filer_pb.FileChunkManifest{
|
||||
Chunks: manifestDataChunks,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal manifest %s: %w", sourceChunk.GetFileIdString(), err)
|
||||
}
|
||||
|
||||
manifestFileId, err := fs.uploadManifestChunk(path, sourceMtime, sourceChunk.GetFileIdString(), manifestData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &filer_pb.FileChunk{
|
||||
FileId: manifestFileId,
|
||||
Offset: sourceChunk.Offset,
|
||||
Size: sourceChunk.Size,
|
||||
ModifiedTsNs: sourceChunk.ModifiedTsNs,
|
||||
ETag: sourceChunk.ETag,
|
||||
SourceFileId: sourceChunk.GetFileIdString(),
|
||||
IsChunkManifest: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) uploadManifestChunk(path string, sourceMtime int64, sourceFileId string, manifestData []byte) (fileId string, err error) {
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
glog.V(0).Infof("upload manifest data %v: %v", sourceFileId, err)
|
||||
return "", fmt.Errorf("upload manifest data: %w", err)
|
||||
}
|
||||
|
||||
retryName := fmt.Sprintf("replicate manifest chunk %s", sourceFileId)
|
||||
err = util.RetryUntil(retryName, func() error {
|
||||
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: fs.replication,
|
||||
Collection: fs.collection,
|
||||
TtlSec: fs.ttlSec,
|
||||
DataCenter: fs.dataCenter,
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: "",
|
||||
Cipher: false,
|
||||
IsInputCompressed: false,
|
||||
MimeType: "application/octet-stream",
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
return fs.buildUploadUrl(host, fileId)
|
||||
},
|
||||
bytes.NewReader(manifestData),
|
||||
)
|
||||
if uploadErr != nil {
|
||||
return fmt.Errorf("upload manifest data: %w", uploadErr)
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
return fmt.Errorf("upload manifest result: %v", uploadResult.Error)
|
||||
}
|
||||
|
||||
fileId = currentFileId
|
||||
return nil
|
||||
}, func(uploadErr error) (shouldContinue bool) {
|
||||
if fs.hasSourceNewerVersion(path, sourceMtime) {
|
||||
glog.V(1).Infof("skip retrying stale source manifest %s for %s: %v", sourceFileId, path, uploadErr)
|
||||
return false
|
||||
}
|
||||
glog.V(0).Infof("upload source manifest %v: %v", sourceFileId, uploadErr)
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return fileId, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string, sourceMtime int64) (fileId string, err error) {
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
glog.V(0).Infof("upload source data %v: %v", sourceChunk.GetFileIdString(), err)
|
||||
return "", fmt.Errorf("upload data: %w", err)
|
||||
}
|
||||
|
||||
fileId, uploadResult, err, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: fs.replication,
|
||||
Collection: fs.collection,
|
||||
TtlSec: fs.ttlSec,
|
||||
DataCenter: fs.dataCenter,
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: filename,
|
||||
Cipher: false,
|
||||
IsInputCompressed: "gzip" == header.Get("Content-Encoding"),
|
||||
MimeType: header.Get("Content-Type"),
|
||||
PairMap: nil,
|
||||
RetryForever: true,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
if fs.writeChunkByFiler {
|
||||
fileUrl = fmt.Sprintf("http://%s/?proxyChunkId=%s", fs.address, fileId)
|
||||
}
|
||||
glog.V(4).Infof("replicating %s to %s header:%+v", filename, fileUrl, header)
|
||||
return fileUrl
|
||||
},
|
||||
resp.Body,
|
||||
)
|
||||
retryName := fmt.Sprintf("replicate chunk %s", sourceChunk.GetFileIdString())
|
||||
err = util.RetryUntil(retryName, func() error {
|
||||
filename, header, resp, readErr := fs.filerSource.ReadPart(sourceChunk.GetFileIdString())
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("read part %s: %w", sourceChunk.GetFileIdString(), readErr)
|
||||
}
|
||||
defer util_http.CloseResponse(resp)
|
||||
|
||||
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: fs.replication,
|
||||
Collection: fs.collection,
|
||||
TtlSec: fs.ttlSec,
|
||||
DataCenter: fs.dataCenter,
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: filename,
|
||||
Cipher: false,
|
||||
IsInputCompressed: "gzip" == header.Get("Content-Encoding"),
|
||||
MimeType: header.Get("Content-Type"),
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
fileUrl := fs.buildUploadUrl(host, fileId)
|
||||
glog.V(4).Infof("replicating %s to %s header:%+v", filename, fileUrl, header)
|
||||
return fileUrl
|
||||
},
|
||||
resp.Body,
|
||||
)
|
||||
if uploadErr != nil {
|
||||
return fmt.Errorf("upload data: %w", uploadErr)
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
return fmt.Errorf("upload result: %v", uploadResult.Error)
|
||||
}
|
||||
|
||||
fileId = currentFileId
|
||||
return nil
|
||||
}, func(uploadErr error) (shouldContinue bool) {
|
||||
if fs.hasSourceNewerVersion(path, sourceMtime) {
|
||||
glog.V(1).Infof("skip retrying stale source %s for %s: %v", sourceChunk.GetFileIdString(), path, uploadErr)
|
||||
return false
|
||||
}
|
||||
glog.V(0).Infof("upload source data %v: %v", sourceChunk.GetFileIdString(), uploadErr)
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(0).Infof("upload source data %v: %v", sourceChunk.GetFileIdString(), err)
|
||||
return "", fmt.Errorf("upload data: %w", err)
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
glog.V(0).Infof("upload failure %v: %v", filename, err)
|
||||
return "", fmt.Errorf("upload result: %v", uploadResult.Error)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return
|
||||
return fileId, nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) buildUploadUrl(host, fileId string) string {
|
||||
if fs.writeChunkByFiler {
|
||||
return fmt.Sprintf("http://%s/?proxyChunkId=%s", fs.address, fileId)
|
||||
}
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
}
|
||||
|
||||
func (fs *FilerSink) hasSourceNewerVersion(targetPath string, sourceMtime int64) bool {
|
||||
if sourceMtime <= 0 || fs.filerSource == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
sourcePath, ok := fs.targetPathToSourcePath(targetPath)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
sourceEntry, err := filer_pb.GetEntry(context.Background(), fs.filerSource, sourcePath)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("lookup source entry %s: %v", sourcePath, err)
|
||||
return false
|
||||
}
|
||||
if sourceEntry == nil {
|
||||
glog.V(1).Infof("source entry %s no longer exists", sourcePath)
|
||||
return true
|
||||
}
|
||||
|
||||
return sourceEntry.Attributes != nil && sourceEntry.Attributes.Mtime > sourceMtime
|
||||
}
|
||||
|
||||
func (fs *FilerSink) targetPathToSourcePath(targetPath string) (util.FullPath, bool) {
|
||||
if fs.filerSource == nil {
|
||||
return "", false
|
||||
}
|
||||
|
||||
normalizePath := func(p string) string {
|
||||
p = strings.TrimSuffix(p, "/")
|
||||
if p == "" {
|
||||
return "/"
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
sourceRoot := normalizePath(fs.filerSource.Dir)
|
||||
targetRoot := normalizePath(fs.dir)
|
||||
targetPath = normalizePath(targetPath)
|
||||
|
||||
var relative string
|
||||
switch {
|
||||
case targetRoot == "/":
|
||||
relative = strings.TrimPrefix(targetPath, "/")
|
||||
case targetPath == targetRoot:
|
||||
relative = ""
|
||||
case strings.HasPrefix(targetPath, targetRoot+"/"):
|
||||
relative = targetPath[len(targetRoot)+1:]
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
|
||||
if relative == "" {
|
||||
return util.FullPath(sourceRoot), true
|
||||
}
|
||||
return util.FullPath(sourceRoot).Child(relative), true
|
||||
}
|
||||
|
||||
var _ = filer_pb.FilerClient(&FilerSink{})
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package filersink
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestTargetPathToSourcePath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
targetRoot string
|
||||
sourceRoot string
|
||||
targetPath string
|
||||
wantPath util.FullPath
|
||||
wantOK bool
|
||||
}{
|
||||
{
|
||||
name: "basic mapping",
|
||||
targetRoot: "/target",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/target/path/file.txt",
|
||||
wantPath: "/source/path/file.txt",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "trailing slash roots",
|
||||
targetRoot: "/target/",
|
||||
sourceRoot: "/source/",
|
||||
targetPath: "/target/path/file.txt",
|
||||
wantPath: "/source/path/file.txt",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "root target mapping",
|
||||
targetRoot: "/",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/path/file.txt",
|
||||
wantPath: "/source/path/file.txt",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "target root itself",
|
||||
targetRoot: "/target",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/target",
|
||||
wantPath: "/source",
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "outside target root",
|
||||
targetRoot: "/target",
|
||||
sourceRoot: "/source",
|
||||
targetPath: "/other/path/file.txt",
|
||||
wantPath: "",
|
||||
wantOK: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fs := &FilerSink{
|
||||
dir: tc.targetRoot,
|
||||
filerSource: &source.FilerSource{
|
||||
Dir: tc.sourceRoot,
|
||||
},
|
||||
}
|
||||
|
||||
gotPath, ok := fs.targetPathToSourcePath(tc.targetPath)
|
||||
if ok != tc.wantOK {
|
||||
t.Fatalf("ok mismatch: got %v, want %v", ok, tc.wantOK)
|
||||
}
|
||||
if gotPath != tc.wantPath {
|
||||
t.Fatalf("path mismatch: got %q, want %q", gotPath, tc.wantPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,7 @@ func (fs *FilerSink) CreateEntry(key string, entry *filer_pb.Entry, signatures [
|
||||
}
|
||||
}
|
||||
|
||||
replicatedChunks, err := fs.replicateChunks(entry.GetChunks(), key)
|
||||
replicatedChunks, err := fs.replicateChunks(context.Background(), entry.GetChunks(), key, getEntryMtime(entry))
|
||||
|
||||
if err != nil {
|
||||
// only warning here since the source chunk may have been deleted already
|
||||
@@ -211,7 +211,7 @@ func (fs *FilerSink) UpdateEntry(key string, oldEntry *filer_pb.Entry, newParent
|
||||
}
|
||||
|
||||
// replicate the chunks that are new in the source
|
||||
replicatedChunks, err := fs.replicateChunks(newChunks, key)
|
||||
replicatedChunks, err := fs.replicateChunks(context.Background(), newChunks, key, getEntryMtime(newEntry))
|
||||
if err != nil {
|
||||
glog.Warningf("replicate entry chunks %s: %v", key, err)
|
||||
return true, nil
|
||||
@@ -261,3 +261,10 @@ func compareChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunc
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func getEntryMtime(entry *filer_pb.Entry) int64 {
|
||||
if entry == nil || entry.Attributes == nil {
|
||||
return 0
|
||||
}
|
||||
return entry.Attributes.Mtime
|
||||
}
|
||||
@@ -49,7 +49,7 @@ type BucketRegistry struct {
|
||||
metadataCache map[string]*BucketMetaData
|
||||
metadataCacheLock sync.RWMutex
|
||||
|
||||
tableLocationCache map[string]string // Cache for table location mappings (bucket -> table path)
|
||||
tableLocationCache map[string]string // Cache for table location mappings (external bucket -> mapped root path)
|
||||
tableLocationLock sync.RWMutex
|
||||
|
||||
notFound map[string]struct{}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
@@ -58,8 +60,13 @@ func (s3a *S3ApiServer) tableLocationDir(bucket string) (string, bool) {
|
||||
|
||||
entry, err := s3a.getEntry(s3tables.GetTableLocationMappingDir(), bucket)
|
||||
tablePath := ""
|
||||
if err == nil && entry != nil && len(entry.Content) > 0 {
|
||||
tablePath = strings.TrimSpace(string(entry.Content))
|
||||
if err == nil && entry != nil {
|
||||
if entry.IsDirectory {
|
||||
tablePath, err = s3a.readTableLocationMappingFromDirectory(bucket)
|
||||
} else if len(entry.Content) > 0 {
|
||||
// Backward compatibility with legacy single-file mappings.
|
||||
tablePath = normalizeTableLocationMappingPath(string(entry.Content))
|
||||
}
|
||||
}
|
||||
|
||||
// Only cache definitive results: successful lookup (tablePath set) or definitive not-found (ErrNotFound)
|
||||
@@ -82,6 +89,77 @@ func (s3a *S3ApiServer) tableLocationDir(bucket string) (string, bool) {
|
||||
return tablePath, true
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) readTableLocationMappingFromDirectory(bucket string) (string, error) {
|
||||
mappingDir := s3tables.GetTableLocationMappingPath(bucket)
|
||||
var mappedPath string
|
||||
conflict := false
|
||||
|
||||
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{
|
||||
Directory: mappingDir,
|
||||
Limit: 4294967295, // math.MaxUint32
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if recvErr != nil {
|
||||
return recvErr
|
||||
}
|
||||
if resp == nil || resp.Entry == nil || resp.Entry.IsDirectory || len(resp.Entry.Content) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
candidate := normalizeTableLocationMappingPath(string(resp.Entry.Content))
|
||||
if candidate == "" {
|
||||
continue
|
||||
}
|
||||
if mappedPath == "" {
|
||||
mappedPath = candidate
|
||||
continue
|
||||
}
|
||||
if mappedPath != candidate {
|
||||
conflict = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if conflict {
|
||||
glog.V(1).Infof("table location mapping conflict for %s: multiple mapped roots found", bucket)
|
||||
return "", nil
|
||||
}
|
||||
return mappedPath, nil
|
||||
}
|
||||
|
||||
func normalizeTableLocationMappingPath(rawPath string) string {
|
||||
rawPath = strings.TrimSpace(rawPath)
|
||||
if rawPath == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
normalized := path.Clean("/" + strings.TrimPrefix(rawPath, "/"))
|
||||
tablesPrefix := strings.TrimSuffix(s3tables.TablesPath, "/") + "/"
|
||||
if !strings.HasPrefix(normalized, tablesPrefix) {
|
||||
return normalized
|
||||
}
|
||||
|
||||
remaining := strings.TrimPrefix(normalized, tablesPrefix)
|
||||
bucketName, _, _ := strings.Cut(remaining, "/")
|
||||
if bucketName == "" {
|
||||
return ""
|
||||
}
|
||||
return path.Join(s3tables.TablesPath, bucketName)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) bucketRoot(bucket string) string {
|
||||
// Returns the unified buckets root path for all bucket types
|
||||
return s3a.option.BucketsPath
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package s3api
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeTableLocationMappingPath(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "legacy table path maps to bucket root",
|
||||
raw: "/buckets/warehouse/analytics/orders",
|
||||
want: "/buckets/warehouse",
|
||||
},
|
||||
{
|
||||
name: "already bucket root",
|
||||
raw: "/buckets/warehouse",
|
||||
want: "/buckets/warehouse",
|
||||
},
|
||||
{
|
||||
name: "relative buckets path normalized and reduced",
|
||||
raw: "buckets/warehouse/analytics/orders",
|
||||
want: "/buckets/warehouse",
|
||||
},
|
||||
{
|
||||
name: "non buckets path preserved",
|
||||
raw: "/tmp/custom/path",
|
||||
want: "/tmp/custom/path",
|
||||
},
|
||||
{
|
||||
name: "empty path",
|
||||
raw: "",
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := normalizeTableLocationMappingPath(tc.raw); got != tc.want {
|
||||
t.Fatalf("normalizeTableLocationMappingPath(%q)=%q, want %q", tc.raw, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/google/uuid"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
const requirementAssertCreate = "assert-create"
|
||||
|
||||
type icebergRequestError struct {
|
||||
status int
|
||||
errType string
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *icebergRequestError) Error() string {
|
||||
return e.message
|
||||
}
|
||||
|
||||
type createOnCommitInput struct {
|
||||
bucketARN string
|
||||
markerBucket string
|
||||
namespace []string
|
||||
tableName string
|
||||
identityName string
|
||||
location string
|
||||
tableUUID uuid.UUID
|
||||
baseMetadata table.Metadata
|
||||
baseMetadataLoc string
|
||||
baseMetadataVer int
|
||||
updates table.Updates
|
||||
statisticsUpdates []statisticsUpdate
|
||||
}
|
||||
|
||||
func isS3TablesConflict(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, s3tables.ErrVersionTokenMismatch) {
|
||||
return true
|
||||
}
|
||||
var tableErr *s3tables.S3TablesError
|
||||
return errors.As(err, &tableErr) && tableErr.Type == s3tables.ErrCodeConflict
|
||||
}
|
||||
|
||||
func isS3TablesNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(strings.ToLower(err.Error()), "not found") {
|
||||
return true
|
||||
}
|
||||
var tableErr *s3tables.S3TablesError
|
||||
return errors.As(err, &tableErr) &&
|
||||
(tableErr.Type == s3tables.ErrCodeNoSuchTable || tableErr.Type == s3tables.ErrCodeNoSuchNamespace || strings.Contains(strings.ToLower(tableErr.Message), "not found"))
|
||||
}
|
||||
|
||||
func hasAssertCreateRequirement(requirements table.Requirements) bool {
|
||||
for _, requirement := range requirements {
|
||||
if requirement.GetType() == requirementAssertCreate {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isS3TablesAlreadyExists(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(strings.ToLower(err.Error()), "already exists") {
|
||||
return true
|
||||
}
|
||||
var tableErr *s3tables.S3TablesError
|
||||
return errors.As(err, &tableErr) &&
|
||||
(tableErr.Type == s3tables.ErrCodeTableAlreadyExists || tableErr.Type == s3tables.ErrCodeNamespaceAlreadyExists || strings.Contains(strings.ToLower(tableErr.Message), "already exists"))
|
||||
}
|
||||
|
||||
func parseMetadataVersionFromLocation(metadataLocation string) int {
|
||||
base := path.Base(metadataLocation)
|
||||
if !strings.HasPrefix(base, "v") || !strings.HasSuffix(base, ".metadata.json") {
|
||||
return 0
|
||||
}
|
||||
rawVersion := strings.TrimPrefix(strings.TrimSuffix(base, ".metadata.json"), "v")
|
||||
version, err := strconv.Atoi(rawVersion)
|
||||
if err != nil || version <= 0 {
|
||||
return 0
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommitInput) (*CommitTableResponse, *icebergRequestError) {
|
||||
builder, err := table.MetadataBuilderFromBase(input.baseMetadata, input.baseMetadataLoc)
|
||||
if err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusInternalServerError,
|
||||
errType: "InternalServerError",
|
||||
message: "Failed to create metadata builder: " + err.Error(),
|
||||
}
|
||||
}
|
||||
for _, update := range input.updates {
|
||||
if err := update.Apply(builder); err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusBadRequest,
|
||||
errType: "BadRequestException",
|
||||
message: "Failed to apply update: " + err.Error(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
newMetadata, err := builder.Build()
|
||||
if err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusBadRequest,
|
||||
errType: "BadRequestException",
|
||||
message: "Failed to build new metadata: " + err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
metadataVersion := input.baseMetadataVer + 1
|
||||
if metadataVersion <= 0 {
|
||||
metadataVersion = 1
|
||||
}
|
||||
metadataFileName := fmt.Sprintf("v%d.metadata.json", metadataVersion)
|
||||
newMetadataLocation := fmt.Sprintf("%s/metadata/%s", strings.TrimSuffix(input.location, "/"), metadataFileName)
|
||||
|
||||
metadataBytes, err := json.Marshal(newMetadata)
|
||||
if err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusInternalServerError,
|
||||
errType: "InternalServerError",
|
||||
message: "Failed to serialize metadata: " + err.Error(),
|
||||
}
|
||||
}
|
||||
metadataBytes, err = applyStatisticsUpdates(metadataBytes, input.statisticsUpdates)
|
||||
if err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusBadRequest,
|
||||
errType: "BadRequestException",
|
||||
message: "Failed to apply statistics updates: " + err.Error(),
|
||||
}
|
||||
}
|
||||
newMetadata, err = table.ParseMetadataBytes(metadataBytes)
|
||||
if err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusInternalServerError,
|
||||
errType: "InternalServerError",
|
||||
message: "Failed to parse committed metadata: " + err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
metadataBucket, metadataPath, err := parseS3Location(input.location)
|
||||
if err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusInternalServerError,
|
||||
errType: "InternalServerError",
|
||||
message: "Invalid table location: " + err.Error(),
|
||||
}
|
||||
}
|
||||
if err := s.saveMetadataFile(ctx, metadataBucket, metadataPath, metadataFileName, metadataBytes); err != nil {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusInternalServerError,
|
||||
errType: "InternalServerError",
|
||||
message: "Failed to save metadata file: " + err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
createReq := &s3tables.CreateTableRequest{
|
||||
TableBucketARN: input.bucketARN,
|
||||
Namespace: input.namespace,
|
||||
Name: input.tableName,
|
||||
Format: "ICEBERG",
|
||||
Metadata: &s3tables.TableMetadata{
|
||||
Iceberg: &s3tables.IcebergMetadata{
|
||||
TableUUID: input.tableUUID.String(),
|
||||
},
|
||||
FullMetadata: metadataBytes,
|
||||
},
|
||||
MetadataVersion: metadataVersion,
|
||||
MetadataLocation: newMetadataLocation,
|
||||
}
|
||||
createErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(ctx, mgrClient, "CreateTable", createReq, nil, input.identityName)
|
||||
})
|
||||
if createErr != nil {
|
||||
if cleanupErr := s.deleteMetadataFile(ctx, metadataBucket, metadataPath, metadataFileName); cleanupErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to cleanup metadata file %s after create-on-commit failure: %v", newMetadataLocation, cleanupErr)
|
||||
}
|
||||
if isS3TablesConflict(createErr) || isS3TablesAlreadyExists(createErr) {
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusConflict,
|
||||
errType: "CommitFailedException",
|
||||
message: "Table was created concurrently",
|
||||
}
|
||||
}
|
||||
glog.Errorf("Iceberg: CommitTable CreateTable error: %v", createErr)
|
||||
return nil, &icebergRequestError{
|
||||
status: http.StatusInternalServerError,
|
||||
errType: "InternalServerError",
|
||||
message: "Failed to commit table creation: " + createErr.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
markerBucket := input.markerBucket
|
||||
if markerBucket == "" {
|
||||
markerBucket = metadataBucket
|
||||
}
|
||||
if markerErr := s.deleteStageCreateMarkers(ctx, markerBucket, input.namespace, input.tableName); markerErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to cleanup stage-create markers for %s.%s after finalize: %v", encodeNamespace(input.namespace), input.tableName, markerErr)
|
||||
}
|
||||
|
||||
return &CommitTableResponse{
|
||||
MetadataLocation: newMetadataLocation,
|
||||
Metadata: newMetadata,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/apache/iceberg-go/table"
|
||||
)
|
||||
|
||||
type statisticsUpdate struct {
|
||||
set *table.StatisticsFile
|
||||
remove *int64
|
||||
}
|
||||
|
||||
var ErrIncompleteSetStatistics = errors.New("set-statistics requires snapshot-id, statistics-path, file-size-in-bytes, and file-footer-size-in-bytes")
|
||||
|
||||
type commitAction struct {
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
type setStatisticsUpdate struct {
|
||||
Action string `json:"action"`
|
||||
SnapshotID *int64 `json:"snapshot-id,omitempty"`
|
||||
StatisticsPath string `json:"statistics-path,omitempty"`
|
||||
FileSizeInBytes *int64 `json:"file-size-in-bytes,omitempty"`
|
||||
FileFooterSizeInBytes *int64 `json:"file-footer-size-in-bytes,omitempty"`
|
||||
KeyMetadata *string `json:"key-metadata,omitempty"`
|
||||
BlobMetadata []table.BlobMetadata `json:"blob-metadata,omitempty"`
|
||||
Statistics *table.StatisticsFile `json:"statistics,omitempty"`
|
||||
}
|
||||
|
||||
func (u *setStatisticsUpdate) asStatisticsFile() (*table.StatisticsFile, error) {
|
||||
if u.Statistics != nil {
|
||||
if u.Statistics.BlobMetadata == nil {
|
||||
u.Statistics.BlobMetadata = []table.BlobMetadata{}
|
||||
}
|
||||
return u.Statistics, nil
|
||||
}
|
||||
if u.SnapshotID == nil || u.StatisticsPath == "" || u.FileSizeInBytes == nil || u.FileFooterSizeInBytes == nil {
|
||||
return nil, ErrIncompleteSetStatistics
|
||||
}
|
||||
|
||||
stats := &table.StatisticsFile{
|
||||
SnapshotID: *u.SnapshotID,
|
||||
StatisticsPath: u.StatisticsPath,
|
||||
FileSizeInBytes: *u.FileSizeInBytes,
|
||||
FileFooterSizeInBytes: *u.FileFooterSizeInBytes,
|
||||
KeyMetadata: u.KeyMetadata,
|
||||
BlobMetadata: u.BlobMetadata,
|
||||
}
|
||||
if stats.BlobMetadata == nil {
|
||||
stats.BlobMetadata = []table.BlobMetadata{}
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
type removeStatisticsUpdate struct {
|
||||
Action string `json:"action"`
|
||||
SnapshotID int64 `json:"snapshot-id"`
|
||||
}
|
||||
|
||||
func parseCommitUpdates(rawUpdates []json.RawMessage) (table.Updates, []statisticsUpdate, error) {
|
||||
filtered := make([]json.RawMessage, 0, len(rawUpdates))
|
||||
statisticsUpdates := make([]statisticsUpdate, 0)
|
||||
|
||||
for _, raw := range rawUpdates {
|
||||
var action commitAction
|
||||
if err := json.Unmarshal(raw, &action); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
switch action.Action {
|
||||
case "set-statistics":
|
||||
var setUpdate setStatisticsUpdate
|
||||
if err := json.Unmarshal(raw, &setUpdate); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
stats, err := setUpdate.asStatisticsFile()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
statisticsUpdates = append(statisticsUpdates, statisticsUpdate{set: stats})
|
||||
case "remove-statistics":
|
||||
var removeUpdate removeStatisticsUpdate
|
||||
if err := json.Unmarshal(raw, &removeUpdate); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
snapshotID := removeUpdate.SnapshotID
|
||||
statisticsUpdates = append(statisticsUpdates, statisticsUpdate{remove: &snapshotID})
|
||||
default:
|
||||
filtered = append(filtered, raw)
|
||||
}
|
||||
}
|
||||
|
||||
if len(filtered) == 0 {
|
||||
return nil, statisticsUpdates, nil
|
||||
}
|
||||
|
||||
data, err := json.Marshal(filtered)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var updates table.Updates
|
||||
if err := json.Unmarshal(data, &updates); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return updates, statisticsUpdates, nil
|
||||
}
|
||||
|
||||
func applyStatisticsUpdates(metadataBytes []byte, updates []statisticsUpdate) ([]byte, error) {
|
||||
if len(updates) == 0 {
|
||||
return metadataBytes, nil
|
||||
}
|
||||
|
||||
var metadata map[string]json.RawMessage
|
||||
if err := json.Unmarshal(metadataBytes, &metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var statistics []table.StatisticsFile
|
||||
if rawStatistics, ok := metadata["statistics"]; ok && len(rawStatistics) > 0 {
|
||||
if err := json.Unmarshal(rawStatistics, &statistics); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
statisticsBySnapshot := make(map[int64]table.StatisticsFile, len(statistics))
|
||||
orderedSnapshotIDs := make([]int64, 0, len(statistics))
|
||||
inOrder := make(map[int64]bool, len(statistics))
|
||||
for _, stat := range statistics {
|
||||
statisticsBySnapshot[stat.SnapshotID] = stat
|
||||
if !inOrder[stat.SnapshotID] {
|
||||
orderedSnapshotIDs = append(orderedSnapshotIDs, stat.SnapshotID)
|
||||
inOrder[stat.SnapshotID] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, update := range updates {
|
||||
if update.set != nil {
|
||||
statisticsBySnapshot[update.set.SnapshotID] = *update.set
|
||||
if !inOrder[update.set.SnapshotID] {
|
||||
orderedSnapshotIDs = append(orderedSnapshotIDs, update.set.SnapshotID)
|
||||
inOrder[update.set.SnapshotID] = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if update.remove != nil {
|
||||
delete(statisticsBySnapshot, *update.remove)
|
||||
}
|
||||
}
|
||||
|
||||
statistics = make([]table.StatisticsFile, 0, len(statisticsBySnapshot))
|
||||
for _, snapshotID := range orderedSnapshotIDs {
|
||||
stat, ok := statisticsBySnapshot[snapshotID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
statistics = append(statistics, stat)
|
||||
}
|
||||
|
||||
if len(statistics) == 0 {
|
||||
delete(metadata, "statistics")
|
||||
} else {
|
||||
data, err := json.Marshal(statistics)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadata["statistics"] = data
|
||||
}
|
||||
|
||||
return json.Marshal(metadata)
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// handleUpdateTable commits updates to a table.
|
||||
// Implements the Iceberg REST Catalog commit protocol.
|
||||
func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
tableName := vars["table"]
|
||||
|
||||
if len(namespace) == 0 || tableName == "" {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace and table name are required")
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
// Parse commit request and keep statistics updates separate because iceberg-go v0.4.0
|
||||
// does not decode set/remove-statistics update actions yet.
|
||||
var raw struct {
|
||||
Identifier *TableIdentifier `json:"identifier,omitempty"`
|
||||
Requirements json.RawMessage `json:"requirements"`
|
||||
Updates []json.RawMessage `json:"updates"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid request body: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var req CommitTableRequest
|
||||
req.Identifier = raw.Identifier
|
||||
var statisticsUpdates []statisticsUpdate
|
||||
if len(raw.Requirements) > 0 {
|
||||
if err := json.Unmarshal(raw.Requirements, &req.Requirements); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid requirements: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(raw.Updates) > 0 {
|
||||
var err error
|
||||
req.Updates, statisticsUpdates, err = parseCommitUpdates(raw.Updates)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid updates: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
maxCommitAttempts := 3
|
||||
generatedLegacyUUID := uuid.New()
|
||||
stageCreateEnabled := isStageCreateEnabled()
|
||||
for attempt := 1; attempt <= maxCommitAttempts; attempt++ {
|
||||
getReq := &s3tables.GetTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}
|
||||
var getResp s3tables.GetTableResponse
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", getReq, &getResp, identityName)
|
||||
})
|
||||
if err != nil {
|
||||
if isS3TablesNotFound(err) {
|
||||
location := fmt.Sprintf("s3://%s/%s/%s", bucketName, encodeNamespace(namespace), tableName)
|
||||
tableUUID := generatedLegacyUUID
|
||||
baseMetadataVersion := 0
|
||||
baseMetadataLocation := ""
|
||||
var baseMetadata table.Metadata
|
||||
|
||||
var latestMarker *stageCreateMarker
|
||||
if stageCreateEnabled {
|
||||
var markerErr error
|
||||
latestMarker, markerErr = s.loadLatestStageCreateMarker(r.Context(), bucketName, namespace, tableName)
|
||||
if markerErr != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to load stage-create marker: "+markerErr.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if latestMarker != nil {
|
||||
if latestMarker.Location != "" {
|
||||
location = strings.TrimSuffix(latestMarker.Location, "/")
|
||||
}
|
||||
if latestMarker.TableUUID != "" {
|
||||
if parsedUUID, parseErr := uuid.Parse(latestMarker.TableUUID); parseErr == nil {
|
||||
tableUUID = parsedUUID
|
||||
}
|
||||
}
|
||||
|
||||
stagedMetadataLocation := latestMarker.StagedMetadataLocation
|
||||
if stagedMetadataLocation == "" {
|
||||
stagedMetadataLocation = fmt.Sprintf("%s/metadata/v1.metadata.json", strings.TrimSuffix(location, "/"))
|
||||
}
|
||||
stagedLocation := tableLocationFromMetadataLocation(stagedMetadataLocation)
|
||||
stagedFileName := path.Base(stagedMetadataLocation)
|
||||
stagedBucket, stagedPath, parseLocationErr := parseS3Location(stagedLocation)
|
||||
if parseLocationErr != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Invalid staged metadata location: "+parseLocationErr.Error())
|
||||
return
|
||||
}
|
||||
stagedMetadataBytes, loadErr := s.loadMetadataFile(r.Context(), stagedBucket, stagedPath, stagedFileName)
|
||||
if loadErr != nil {
|
||||
if !errors.Is(loadErr, filer_pb.ErrNotFound) {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to load staged metadata: "+loadErr.Error())
|
||||
return
|
||||
}
|
||||
} else if len(stagedMetadataBytes) > 0 {
|
||||
stagedMetadata, parseErr := table.ParseMetadataBytes(stagedMetadataBytes)
|
||||
if parseErr != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to parse staged metadata: "+parseErr.Error())
|
||||
return
|
||||
}
|
||||
// Staged metadata is only a template for table creation; commit starts from version 1.
|
||||
baseMetadata = stagedMetadata
|
||||
baseMetadataLocation = ""
|
||||
baseMetadataVersion = 0
|
||||
if stagedMetadata.TableUUID() != uuid.Nil {
|
||||
tableUUID = stagedMetadata.TableUUID()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasAssertCreate := hasAssertCreateRequirement(req.Requirements)
|
||||
hasStagedTemplate := baseMetadata != nil
|
||||
if !(stageCreateEnabled && (hasAssertCreate || hasStagedTemplate)) {
|
||||
writeError(w, http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName))
|
||||
return
|
||||
}
|
||||
|
||||
for _, requirement := range req.Requirements {
|
||||
validateAgainst := table.Metadata(nil)
|
||||
if hasStagedTemplate && requirement.GetType() != requirementAssertCreate {
|
||||
validateAgainst = baseMetadata
|
||||
}
|
||||
if requirementErr := requirement.Validate(validateAgainst); requirementErr != nil {
|
||||
writeError(w, http.StatusConflict, "CommitFailedException", "Requirement failed: "+requirementErr.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if baseMetadata == nil {
|
||||
baseMetadata = newTableMetadata(tableUUID, location, nil, nil, nil, nil)
|
||||
if baseMetadata == nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to build current metadata")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
result, reqErr := s.finalizeCreateOnCommit(r.Context(), createOnCommitInput{
|
||||
bucketARN: bucketARN,
|
||||
markerBucket: bucketName,
|
||||
namespace: namespace,
|
||||
tableName: tableName,
|
||||
identityName: identityName,
|
||||
location: location,
|
||||
tableUUID: tableUUID,
|
||||
baseMetadata: baseMetadata,
|
||||
baseMetadataLoc: baseMetadataLocation,
|
||||
baseMetadataVer: baseMetadataVersion,
|
||||
updates: req.Updates,
|
||||
statisticsUpdates: statisticsUpdates,
|
||||
})
|
||||
if reqErr != nil {
|
||||
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: CommitTable GetTable error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
location := tableLocationFromMetadataLocation(getResp.MetadataLocation)
|
||||
if location == "" {
|
||||
location = fmt.Sprintf("s3://%s/%s/%s", bucketName, encodeNamespace(namespace), tableName)
|
||||
}
|
||||
tableUUID := uuid.Nil
|
||||
if getResp.Metadata != nil && getResp.Metadata.Iceberg != nil && getResp.Metadata.Iceberg.TableUUID != "" {
|
||||
if parsed, parseErr := uuid.Parse(getResp.Metadata.Iceberg.TableUUID); parseErr == nil {
|
||||
tableUUID = parsed
|
||||
}
|
||||
}
|
||||
if tableUUID == uuid.Nil {
|
||||
tableUUID = generatedLegacyUUID
|
||||
}
|
||||
|
||||
var currentMetadata table.Metadata
|
||||
if getResp.Metadata != nil && len(getResp.Metadata.FullMetadata) > 0 {
|
||||
currentMetadata, err = table.ParseMetadataBytes(getResp.Metadata.FullMetadata)
|
||||
if err != nil {
|
||||
glog.Errorf("Iceberg: Failed to parse current metadata for %s: %v", tableName, err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to parse current metadata")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
currentMetadata = newTableMetadata(tableUUID, location, nil, nil, nil, nil)
|
||||
}
|
||||
if currentMetadata == nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to build current metadata")
|
||||
return
|
||||
}
|
||||
|
||||
for _, requirement := range req.Requirements {
|
||||
if err := requirement.Validate(currentMetadata); err != nil {
|
||||
writeError(w, http.StatusConflict, "CommitFailedException", "Requirement failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
builder, err := table.MetadataBuilderFromBase(currentMetadata, getResp.MetadataLocation)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to create metadata builder: "+err.Error())
|
||||
return
|
||||
}
|
||||
for _, update := range req.Updates {
|
||||
if err := update.Apply(builder); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Failed to apply update: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
newMetadata, err := builder.Build()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Failed to build new metadata: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
metadataVersion := getResp.MetadataVersion + 1
|
||||
metadataFileName := fmt.Sprintf("v%d.metadata.json", metadataVersion)
|
||||
newMetadataLocation := fmt.Sprintf("%s/metadata/%s", strings.TrimSuffix(location, "/"), metadataFileName)
|
||||
|
||||
metadataBytes, err := json.Marshal(newMetadata)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to serialize metadata: "+err.Error())
|
||||
return
|
||||
}
|
||||
// iceberg-go does not currently support set/remove-statistics updates in MetadataBuilder.
|
||||
// Patch the encoded metadata JSON and parse it back to keep the response object consistent.
|
||||
metadataBytes, err = applyStatisticsUpdates(metadataBytes, statisticsUpdates)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Failed to apply statistics updates: "+err.Error())
|
||||
return
|
||||
}
|
||||
newMetadata, err = table.ParseMetadataBytes(metadataBytes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to parse committed metadata: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
metadataBucket, metadataPath, err := parseS3Location(location)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Invalid table location: "+err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.saveMetadataFile(r.Context(), metadataBucket, metadataPath, metadataFileName, metadataBytes); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save metadata file: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
updateReq := &s3tables.UpdateTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
VersionToken: getResp.VersionToken,
|
||||
Metadata: &s3tables.TableMetadata{
|
||||
Iceberg: &s3tables.IcebergMetadata{
|
||||
TableUUID: tableUUID.String(),
|
||||
},
|
||||
FullMetadata: metadataBytes,
|
||||
},
|
||||
MetadataVersion: metadataVersion,
|
||||
MetadataLocation: newMetadataLocation,
|
||||
}
|
||||
|
||||
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "UpdateTable", updateReq, nil, identityName)
|
||||
})
|
||||
if err == nil {
|
||||
result := CommitTableResponse{
|
||||
MetadataLocation: newMetadataLocation,
|
||||
Metadata: newMetadata,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
return
|
||||
}
|
||||
|
||||
if isS3TablesConflict(err) {
|
||||
if cleanupErr := s.deleteMetadataFile(r.Context(), metadataBucket, metadataPath, metadataFileName); cleanupErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to cleanup metadata file %s on conflict: %v", newMetadataLocation, cleanupErr)
|
||||
}
|
||||
if attempt < maxCommitAttempts {
|
||||
glog.V(1).Infof("Iceberg: CommitTable conflict for %s (attempt %d/%d), retrying", tableName, attempt, maxCommitAttempts)
|
||||
jitter := time.Duration(rand.Int64N(int64(25 * time.Millisecond)))
|
||||
time.Sleep(time.Duration(50*attempt)*time.Millisecond + jitter)
|
||||
continue
|
||||
}
|
||||
writeError(w, http.StatusConflict, "CommitFailedException", "Version token mismatch")
|
||||
return
|
||||
}
|
||||
|
||||
if cleanupErr := s.deleteMetadataFile(r.Context(), metadataBucket, metadataPath, metadataFileName); cleanupErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to cleanup metadata file %s after update failure: %v", newMetadataLocation, cleanupErr)
|
||||
}
|
||||
glog.Errorf("Iceberg: CommitTable UpdateTable error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to commit table update: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// handleConfig returns catalog configuration.
|
||||
func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
config := CatalogConfig{
|
||||
Defaults: map[string]string{},
|
||||
Overrides: map[string]string{},
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(config); err != nil {
|
||||
glog.Warningf("handleConfig: Failed to encode config: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleListNamespaces lists namespaces in a catalog.
|
||||
func (s *Server) handleListNamespaces(w http.ResponseWriter, r *http.Request) {
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
pageToken, pageSize, err := parsePagination(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Use S3 Tables manager to list namespaces
|
||||
var resp s3tables.ListNamespacesResponse
|
||||
req := &s3tables.ListNamespacesRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
ContinuationToken: pageToken,
|
||||
MaxNamespaces: pageSize,
|
||||
}
|
||||
|
||||
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "ListNamespaces", req, &resp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
glog.Infof("Iceberg: ListNamespaces error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Convert to Iceberg format
|
||||
namespaces := make([]Namespace, 0, len(resp.Namespaces))
|
||||
for _, ns := range resp.Namespaces {
|
||||
namespaces = append(namespaces, Namespace(ns.Namespace))
|
||||
}
|
||||
|
||||
result := ListNamespacesResponse{
|
||||
NextPageToken: resp.ContinuationToken,
|
||||
Namespaces: namespaces,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// handleCreateNamespace creates a new namespace.
|
||||
func (s *Server) handleCreateNamespace(w http.ResponseWriter, r *http.Request) {
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
var req CreateNamespaceRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Namespace) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
||||
return
|
||||
}
|
||||
|
||||
// Use S3 Tables manager to create namespace
|
||||
createReq := &s3tables.CreateNamespaceRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: req.Namespace,
|
||||
Properties: normalizeNamespaceProperties(req.Properties),
|
||||
}
|
||||
var createResp s3tables.CreateNamespaceResponse
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
glog.V(2).Infof("Iceberg: handleCreateNamespace calling Execute with identityName=%s", identityName)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "CreateNamespace", createReq, &createResp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "already exists") {
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", err.Error())
|
||||
return
|
||||
}
|
||||
glog.Errorf("Iceberg: CreateNamespace error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result := CreateNamespaceResponse{
|
||||
Namespace: Namespace(createResp.Namespace),
|
||||
Properties: normalizeNamespaceProperties(createResp.Properties),
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// handleGetNamespace gets namespace metadata.
|
||||
func (s *Server) handleGetNamespace(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
if len(namespace) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
// Use S3 Tables manager to get namespace
|
||||
getReq := &s3tables.GetNamespaceRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
}
|
||||
var getResp s3tables.GetNamespaceResponse
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "GetNamespace", getReq, &getResp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", fmt.Sprintf("Namespace does not exist: %v", namespace))
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: GetNamespace error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result := GetNamespaceResponse{
|
||||
Namespace: Namespace(getResp.Namespace),
|
||||
Properties: normalizeNamespaceProperties(getResp.Properties),
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// handleNamespaceExists checks if a namespace exists.
|
||||
func (s *Server) handleNamespaceExists(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
if len(namespace) == 0 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
getReq := &s3tables.GetNamespaceRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
}
|
||||
var getResp s3tables.GetNamespaceResponse
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "GetNamespace", getReq, &getResp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: NamespaceExists error: %v", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleDropNamespace deletes a namespace.
|
||||
func (s *Server) handleDropNamespace(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
if len(namespace) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
deleteReq := &s3tables.DeleteNamespaceRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
}
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "DeleteNamespace", deleteReq, nil, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", fmt.Sprintf("Namespace does not exist: %v", namespace))
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "not empty") {
|
||||
writeError(w, http.StatusConflict, "NamespaceNotEmptyException", "Namespace is not empty")
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: DropNamespace error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
var errTableNameRequired = errors.New("table name is required")
|
||||
|
||||
func validateCreateTableRequest(req CreateTableRequest) error {
|
||||
if req.Name == "" {
|
||||
return errTableNameRequired
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleListTables lists tables in a namespace.
|
||||
func (s *Server) handleListTables(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
if len(namespace) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
pageToken, pageSize, err := parsePagination(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
listReq := &s3tables.ListTablesRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
ContinuationToken: pageToken,
|
||||
MaxTables: pageSize,
|
||||
}
|
||||
var listResp s3tables.ListTablesResponse
|
||||
|
||||
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "ListTables", listReq, &listResp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", fmt.Sprintf("Namespace does not exist: %v", namespace))
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: ListTables error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Convert to Iceberg format
|
||||
identifiers := make([]TableIdentifier, 0, len(listResp.Tables))
|
||||
for _, t := range listResp.Tables {
|
||||
identifiers = append(identifiers, TableIdentifier{
|
||||
Namespace: namespace,
|
||||
Name: t.Name,
|
||||
})
|
||||
}
|
||||
|
||||
result := ListTablesResponse{
|
||||
NextPageToken: listResp.ContinuationToken,
|
||||
Identifiers: identifiers,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// handleCreateTable creates a new table.
|
||||
func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
if len(namespace) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateTableRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if err := validateCreateTableRequest(req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
|
||||
return
|
||||
}
|
||||
if req.StageCreate && !isStageCreateEnabled() {
|
||||
writeError(w, http.StatusNotImplemented, "NotImplementedException", "stage-create is disabled")
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
// Generate UUID for the new table
|
||||
tableUUID := uuid.New()
|
||||
tablePath := path.Join(encodeNamespace(namespace), req.Name)
|
||||
location := strings.TrimSuffix(req.Location, "/")
|
||||
if location == "" {
|
||||
if req.Properties != nil {
|
||||
if warehouse := strings.TrimSuffix(req.Properties["warehouse"], "/"); warehouse != "" {
|
||||
location = fmt.Sprintf("%s/%s", warehouse, tablePath)
|
||||
}
|
||||
}
|
||||
if location == "" {
|
||||
if warehouse := strings.TrimSuffix(os.Getenv("ICEBERG_WAREHOUSE"), "/"); warehouse != "" {
|
||||
location = fmt.Sprintf("%s/%s", warehouse, tablePath)
|
||||
}
|
||||
}
|
||||
if location == "" {
|
||||
location = fmt.Sprintf("s3://%s/%s", bucketName, tablePath)
|
||||
}
|
||||
} else {
|
||||
parsedBucket, parsedPath, err := parseS3Location(location)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid table location: "+err.Error())
|
||||
return
|
||||
}
|
||||
if parsedPath == "" {
|
||||
location = fmt.Sprintf("s3://%s/%s", parsedBucket, tablePath)
|
||||
}
|
||||
}
|
||||
|
||||
// Build proper Iceberg table metadata using iceberg-go types
|
||||
metadata := newTableMetadata(tableUUID, location, req.Schema, req.PartitionSpec, req.WriteOrder, req.Properties)
|
||||
if metadata == nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to build table metadata")
|
||||
return
|
||||
}
|
||||
|
||||
// Serialize metadata to JSON
|
||||
metadataBytes, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to serialize metadata: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tableName := req.Name
|
||||
metadataFileName := "v1.metadata.json" // Initial version is always 1
|
||||
metadataLocation := fmt.Sprintf("%s/metadata/%s", location, metadataFileName)
|
||||
metadataBucket, metadataPath, err := parseS3Location(location)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Invalid table location: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Stage-create persists metadata in the internal staged area and skips S3Tables registration.
|
||||
if req.StageCreate {
|
||||
stagedTablePath := stageCreateStagedTablePath(namespace, tableName, tableUUID)
|
||||
if err := s.saveMetadataFile(r.Context(), metadataBucket, stagedTablePath, metadataFileName, metadataBytes); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save staged metadata file: "+err.Error())
|
||||
return
|
||||
}
|
||||
stagedMetadataLocation := fmt.Sprintf("s3://%s/%s/metadata/%s", metadataBucket, stagedTablePath, metadataFileName)
|
||||
if markerErr := s.writeStageCreateMarker(r.Context(), bucketName, namespace, tableName, tableUUID, location, stagedMetadataLocation); markerErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to persist stage-create marker for %s.%s: %v", encodeNamespace(namespace), tableName, markerErr)
|
||||
}
|
||||
result := LoadTableResult{
|
||||
MetadataLocation: metadataLocation,
|
||||
Metadata: metadata,
|
||||
Config: make(iceberg.Properties),
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
return
|
||||
}
|
||||
if err := s.saveMetadataFile(r.Context(), metadataBucket, metadataPath, metadataFileName, metadataBytes); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save metadata file: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Use S3 Tables manager to create table
|
||||
createReq := &s3tables.CreateTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
Format: "ICEBERG",
|
||||
Metadata: &s3tables.TableMetadata{
|
||||
Iceberg: &s3tables.IcebergMetadata{
|
||||
TableUUID: tableUUID.String(),
|
||||
},
|
||||
FullMetadata: metadataBytes,
|
||||
},
|
||||
MetadataLocation: metadataLocation,
|
||||
MetadataVersion: 1,
|
||||
}
|
||||
var createResp s3tables.CreateTableResponse
|
||||
|
||||
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "CreateTable", createReq, &createResp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if tableErr, ok := err.(*s3tables.S3TablesError); ok && tableErr.Type == s3tables.ErrCodeTableAlreadyExists {
|
||||
getReq := &s3tables.GetTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}
|
||||
var getResp s3tables.GetTableResponse
|
||||
getErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", getReq, &getResp, identityName)
|
||||
})
|
||||
if getErr != nil {
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", err.Error())
|
||||
return
|
||||
}
|
||||
result := buildLoadTableResult(getResp, bucketName, namespace, tableName)
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "already exists") {
|
||||
getReq := &s3tables.GetTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}
|
||||
var getResp s3tables.GetTableResponse
|
||||
getErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", getReq, &getResp, identityName)
|
||||
})
|
||||
if getErr != nil {
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", err.Error())
|
||||
return
|
||||
}
|
||||
result := buildLoadTableResult(getResp, bucketName, namespace, tableName)
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: CreateTable error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Use returned location if available, otherwise fallback to local one
|
||||
finalLocation := createResp.MetadataLocation
|
||||
if finalLocation == "" {
|
||||
finalLocation = metadataLocation
|
||||
}
|
||||
if markerErr := s.deleteStageCreateMarkers(r.Context(), bucketName, namespace, tableName); markerErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to cleanup stage-create markers for %s.%s after create: %v", encodeNamespace(namespace), tableName, markerErr)
|
||||
}
|
||||
|
||||
result := LoadTableResult{
|
||||
MetadataLocation: finalLocation,
|
||||
Metadata: metadata,
|
||||
Config: make(iceberg.Properties),
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// handleLoadTable loads table metadata.
|
||||
func (s *Server) handleLoadTable(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
tableName := vars["table"]
|
||||
|
||||
if len(namespace) == 0 || tableName == "" {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace and table name are required")
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
getReq := &s3tables.GetTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}
|
||||
var getResp s3tables.GetTableResponse
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", getReq, &getResp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
writeError(w, http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName))
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: LoadTable error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result := buildLoadTableResult(getResp, bucketName, namespace, tableName)
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func buildLoadTableResult(getResp s3tables.GetTableResponse, bucketName string, namespace []string, tableName string) LoadTableResult {
|
||||
location := tableLocationFromMetadataLocation(getResp.MetadataLocation)
|
||||
if location == "" {
|
||||
location = fmt.Sprintf("s3://%s/%s/%s", bucketName, encodeNamespace(namespace), tableName)
|
||||
}
|
||||
tableUUID := uuid.Nil
|
||||
if getResp.Metadata != nil && getResp.Metadata.Iceberg != nil && getResp.Metadata.Iceberg.TableUUID != "" {
|
||||
if parsed, err := uuid.Parse(getResp.Metadata.Iceberg.TableUUID); err == nil {
|
||||
tableUUID = parsed
|
||||
}
|
||||
}
|
||||
// Use Nil UUID if not found in storage (legacy table)
|
||||
// Stability is guaranteed by not generating random UUIDs on read
|
||||
|
||||
var metadata table.Metadata
|
||||
if getResp.Metadata != nil && len(getResp.Metadata.FullMetadata) > 0 {
|
||||
var err error
|
||||
metadata, err = table.ParseMetadataBytes(getResp.Metadata.FullMetadata)
|
||||
if err != nil {
|
||||
glog.Warningf("Iceberg: Failed to parse persisted metadata for %s: %v", tableName, err)
|
||||
// Attempt to reconstruct from IcebergMetadata if available, otherwise synthetic
|
||||
// TODO: Extract schema/spec from getResp.Metadata.Iceberg if FullMetadata fails but partial info exists?
|
||||
// For now, fallback to empty metadata
|
||||
metadata = newTableMetadata(tableUUID, location, nil, nil, nil, nil)
|
||||
}
|
||||
} else {
|
||||
// No full metadata, create synthetic
|
||||
// TODO: If we had stored schema in IcebergMetadata, we would pass it here
|
||||
metadata = newTableMetadata(tableUUID, location, nil, nil, nil, nil)
|
||||
}
|
||||
|
||||
return LoadTableResult{
|
||||
MetadataLocation: getResp.MetadataLocation,
|
||||
Metadata: metadata,
|
||||
Config: make(iceberg.Properties),
|
||||
}
|
||||
}
|
||||
|
||||
// handleTableExists checks if a table exists.
|
||||
func (s *Server) handleTableExists(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
tableName := vars["table"]
|
||||
|
||||
if len(namespace) == 0 || tableName == "" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
getReq := &s3tables.GetTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}
|
||||
var getResp s3tables.GetTableResponse
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", getReq, &getResp, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleDropTable deletes a table.
|
||||
func (s *Server) handleDropTable(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
namespace := parseNamespace(vars["namespace"])
|
||||
tableName := vars["table"]
|
||||
|
||||
if len(namespace) == 0 || tableName == "" {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace and table name are required")
|
||||
return
|
||||
}
|
||||
|
||||
bucketName := getBucketFromPrefix(r)
|
||||
bucketARN := buildTableBucketARN(bucketName)
|
||||
|
||||
// Extract identity from context
|
||||
identityName := s3_constants.GetIdentityNameFromContext(r)
|
||||
|
||||
deleteReq := &s3tables.DeleteTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
return s.tablesManager.Execute(r.Context(), mgrClient, "DeleteTable", deleteReq, nil, identityName)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
writeError(w, http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName))
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: DropTable error: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// newTableMetadata creates a new table.Metadata object with the given parameters.
|
||||
// Uses iceberg-go's MetadataBuilder pattern for proper spec compliance.
|
||||
func newTableMetadata(
|
||||
tableUUID uuid.UUID,
|
||||
location string,
|
||||
schema *iceberg.Schema,
|
||||
partitionSpec *iceberg.PartitionSpec,
|
||||
sortOrder *table.SortOrder,
|
||||
props iceberg.Properties,
|
||||
) table.Metadata {
|
||||
// Add schema - use provided or create empty schema
|
||||
var s *iceberg.Schema
|
||||
if schema != nil {
|
||||
s = schema
|
||||
} else {
|
||||
s = iceberg.NewSchema(0)
|
||||
}
|
||||
|
||||
// Add partition spec
|
||||
var pSpec *iceberg.PartitionSpec
|
||||
if partitionSpec != nil {
|
||||
pSpec = partitionSpec
|
||||
} else {
|
||||
unpartitioned := iceberg.NewPartitionSpecID(0)
|
||||
pSpec = &unpartitioned
|
||||
}
|
||||
|
||||
// Add sort order
|
||||
var so table.SortOrder
|
||||
if sortOrder != nil {
|
||||
so = *sortOrder
|
||||
} else {
|
||||
so = table.UnsortedSortOrder
|
||||
}
|
||||
|
||||
// Create properties map if nil
|
||||
if props == nil {
|
||||
props = make(iceberg.Properties)
|
||||
}
|
||||
|
||||
// Create metadata directly using the constructor which ensures spec compliance for V2
|
||||
metadata, err := table.NewMetadataWithUUID(s, pSpec, so, location, props, tableUUID)
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to create metadata: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return metadata
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,103 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
func TestParseCommitUpdatesSeparatesStatistics(t *testing.T) {
|
||||
raw := []json.RawMessage{
|
||||
json.RawMessage(`{"action":"set-statistics","snapshot-id":10,"statistics-path":"s3://bucket/table/metadata/stats.puffin","file-size-in-bytes":100,"file-footer-size-in-bytes":20,"blob-metadata":[]}`),
|
||||
json.RawMessage(`{"action":"set-properties","updates":{"k":"v"}}`),
|
||||
}
|
||||
|
||||
updates, stats, err := parseCommitUpdates(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("parseCommitUpdates() error = %v", err)
|
||||
}
|
||||
if len(stats) != 1 {
|
||||
t.Fatalf("statistics updates = %d, want 1", len(stats))
|
||||
}
|
||||
if stats[0].set == nil || stats[0].set.SnapshotID != 10 {
|
||||
t.Fatalf("unexpected statistics update: %#v", stats[0])
|
||||
}
|
||||
if len(updates) != 1 {
|
||||
t.Fatalf("decoded updates = %d, want 1", len(updates))
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCommitUpdatesRejectsIncompleteSetStatistics(t *testing.T) {
|
||||
raw := []json.RawMessage{
|
||||
json.RawMessage(`{"action":"set-statistics","snapshot-id":10}`),
|
||||
}
|
||||
|
||||
_, _, err := parseCommitUpdates(raw)
|
||||
if err == nil {
|
||||
t.Fatalf("parseCommitUpdates() expected error")
|
||||
}
|
||||
if !errors.Is(err, ErrIncompleteSetStatistics) {
|
||||
t.Fatalf("parseCommitUpdates() error = %v, want ErrIncompleteSetStatistics", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyStatisticsUpdatesUpsertAndRemove(t *testing.T) {
|
||||
metadata := []byte(`{"format-version":2,"statistics":[{"snapshot-id":1,"statistics-path":"s3://bucket/stats-1.puffin","file-size-in-bytes":10,"file-footer-size-in-bytes":1,"blob-metadata":[]},{"snapshot-id":2,"statistics-path":"s3://bucket/stats-2.puffin","file-size-in-bytes":20,"file-footer-size-in-bytes":2,"blob-metadata":[]}]} `)
|
||||
|
||||
snapshotID := int64(2)
|
||||
setUpdates := []statisticsUpdate{
|
||||
{
|
||||
set: &statisticsFileForTest,
|
||||
},
|
||||
{
|
||||
remove: &snapshotID,
|
||||
},
|
||||
}
|
||||
|
||||
updated, err := applyStatisticsUpdates(metadata, setUpdates)
|
||||
if err != nil {
|
||||
t.Fatalf("applyStatisticsUpdates() error = %v", err)
|
||||
}
|
||||
|
||||
var decoded map[string]json.RawMessage
|
||||
if err := json.Unmarshal(updated, &decoded); err != nil {
|
||||
t.Fatalf("json.Unmarshal(updated) error = %v", err)
|
||||
}
|
||||
|
||||
var stats []map[string]any
|
||||
if err := json.Unmarshal(decoded["statistics"], &stats); err != nil {
|
||||
t.Fatalf("json.Unmarshal(statistics) error = %v", err)
|
||||
}
|
||||
if len(stats) != 1 {
|
||||
t.Fatalf("statistics length = %d, want 1", len(stats))
|
||||
}
|
||||
if got := int64(stats[0]["snapshot-id"].(float64)); got != 1 {
|
||||
t.Fatalf("remaining snapshot-id = %d, want 1", got)
|
||||
}
|
||||
if got := int64(stats[0]["file-size-in-bytes"].(float64)); got != 11 {
|
||||
t.Fatalf("remaining file-size-in-bytes = %d, want 11", got)
|
||||
}
|
||||
}
|
||||
|
||||
var statisticsFileForTest = table.StatisticsFile{
|
||||
SnapshotID: 1,
|
||||
StatisticsPath: "s3://bucket/stats-1.puffin",
|
||||
FileSizeInBytes: 11,
|
||||
FileFooterSizeInBytes: 2,
|
||||
BlobMetadata: []table.BlobMetadata{},
|
||||
}
|
||||
|
||||
func TestIsS3TablesConflict(t *testing.T) {
|
||||
if !isS3TablesConflict(s3tables.ErrVersionTokenMismatch) {
|
||||
t.Fatalf("expected ErrVersionTokenMismatch to be conflict")
|
||||
}
|
||||
if !isS3TablesConflict(&s3tables.S3TablesError{Type: s3tables.ErrCodeConflict, Message: "Version token mismatch"}) {
|
||||
t.Fatalf("expected S3Tables conflict error to be conflict")
|
||||
}
|
||||
if isS3TablesConflict(errors.New("other")) {
|
||||
t.Fatalf("unexpected conflict for non-conflict error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateCreateTableRequestRequiresName(t *testing.T) {
|
||||
err := validateCreateTableRequest(CreateTableRequest{})
|
||||
if !errors.Is(err, errTableNameRequired) {
|
||||
t.Fatalf("validateCreateTableRequest() error = %v, want errTableNameRequired", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCreateTableRequestAcceptsWithName(t *testing.T) {
|
||||
err := validateCreateTableRequest(CreateTableRequest{Name: "orders"})
|
||||
if err != nil {
|
||||
t.Fatalf("validateCreateTableRequest() error = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsStageCreateEnabledDefaultsToTrue(t *testing.T) {
|
||||
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "")
|
||||
if !isStageCreateEnabled() {
|
||||
t.Fatalf("isStageCreateEnabled() = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsStageCreateEnabledFalseValues(t *testing.T) {
|
||||
falseValues := []string{"0", "false", "FALSE", "no", "off"}
|
||||
for _, value := range falseValues {
|
||||
t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", value)
|
||||
if isStageCreateEnabled() {
|
||||
t.Fatalf("isStageCreateEnabled() = true for value %q, want false", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package iceberg
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeNamespacePropertiesNil(t *testing.T) {
|
||||
properties := normalizeNamespaceProperties(nil)
|
||||
if properties == nil {
|
||||
t.Fatalf("normalizeNamespaceProperties(nil) returned nil map")
|
||||
}
|
||||
if len(properties) != 0 {
|
||||
t.Fatalf("normalizeNamespaceProperties(nil) length = %d, want 0", len(properties))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeNamespacePropertiesReturnsInputWhenSet(t *testing.T) {
|
||||
input := map[string]string{
|
||||
"owner": "analytics",
|
||||
}
|
||||
|
||||
properties := normalizeNamespaceProperties(input)
|
||||
if properties["owner"] != "analytics" {
|
||||
t.Fatalf("normalized properties value = %q, want %q", properties["owner"], "analytics")
|
||||
}
|
||||
|
||||
input["owner"] = "updated"
|
||||
if properties["owner"] != "updated" {
|
||||
t.Fatalf("normalizeNamespaceProperties should reuse the input map when non-nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParsePaginationDefaultValues(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/v1/namespaces", nil)
|
||||
|
||||
pageToken, pageSize, err := parsePagination(req)
|
||||
if err != nil {
|
||||
t.Fatalf("parsePagination() error = %v", err)
|
||||
}
|
||||
if pageToken != "" {
|
||||
t.Fatalf("pageToken = %q, want empty", pageToken)
|
||||
}
|
||||
if pageSize != defaultListPageSize {
|
||||
t.Fatalf("pageSize = %d, want %d", pageSize, defaultListPageSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePaginationUsesCamelCaseParameters(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/v1/namespaces?pageToken=abc&pageSize=25", nil)
|
||||
|
||||
pageToken, pageSize, err := parsePagination(req)
|
||||
if err != nil {
|
||||
t.Fatalf("parsePagination() error = %v", err)
|
||||
}
|
||||
if pageToken != "abc" {
|
||||
t.Fatalf("pageToken = %q, want %q", pageToken, "abc")
|
||||
}
|
||||
if pageSize != 25 {
|
||||
t.Fatalf("pageSize = %d, want %d", pageSize, 25)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePaginationSupportsHyphenatedFallback(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/v1/namespaces?page-token=abc&page-size=17", nil)
|
||||
|
||||
pageToken, pageSize, err := parsePagination(req)
|
||||
if err != nil {
|
||||
t.Fatalf("parsePagination() error = %v", err)
|
||||
}
|
||||
if pageToken != "abc" {
|
||||
t.Fatalf("pageToken = %q, want %q", pageToken, "abc")
|
||||
}
|
||||
if pageSize != 17 {
|
||||
t.Fatalf("pageSize = %d, want %d", pageSize, 17)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePaginationRejectsInvalidPageSize(t *testing.T) {
|
||||
testCases := []string{
|
||||
"/v1/namespaces?pageSize=0",
|
||||
"/v1/namespaces?pageSize=-1",
|
||||
"/v1/namespaces?pageSize=foo",
|
||||
"/v1/namespaces?pageSize=1001",
|
||||
}
|
||||
|
||||
for _, rawURL := range testCases {
|
||||
t.Run(rawURL, func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", rawURL, nil)
|
||||
if _, _, err := parsePagination(req); err == nil {
|
||||
t.Fatalf("parsePagination() expected error for url %q", rawURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestHasAssertCreateRequirement(t *testing.T) {
|
||||
requirements := table.Requirements{table.AssertCreate()}
|
||||
if !hasAssertCreateRequirement(requirements) {
|
||||
t.Fatalf("hasAssertCreateRequirement() = false, want true")
|
||||
}
|
||||
|
||||
requirements = table.Requirements{table.AssertDefaultSortOrderID(0)}
|
||||
if hasAssertCreateRequirement(requirements) {
|
||||
t.Fatalf("hasAssertCreateRequirement() = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMetadataVersionFromLocation(t *testing.T) {
|
||||
testCases := []struct {
|
||||
location string
|
||||
version int
|
||||
}{
|
||||
{location: "s3://b/ns/t/metadata/v1.metadata.json", version: 1},
|
||||
{location: "s3://b/ns/t/metadata/v25.metadata.json", version: 25},
|
||||
{location: "v1.metadata.json", version: 1},
|
||||
{location: "s3://b/ns/t/metadata/v0.metadata.json", version: 0},
|
||||
{location: "s3://b/ns/t/metadata/v-1.metadata.json", version: 0},
|
||||
{location: "s3://b/ns/t/metadata/vABC.metadata.json", version: 0},
|
||||
{location: "s3://b/ns/t/metadata/current.json", version: 0},
|
||||
{location: "", version: 0},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.location, func(t *testing.T) {
|
||||
if got := parseMetadataVersionFromLocation(tc.location); got != tc.version {
|
||||
t.Errorf("parseMetadataVersionFromLocation(%q) = %d, want %d", tc.location, got, tc.version)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageCreateMarkerNamespaceKey(t *testing.T) {
|
||||
key := stageCreateMarkerNamespaceKey([]string{"a", "b"})
|
||||
if key == "a\x1fb" {
|
||||
t.Fatalf("stageCreateMarkerNamespaceKey() returned unescaped namespace key %q", key)
|
||||
}
|
||||
if !strings.Contains(key, "%1F") {
|
||||
t.Fatalf("stageCreateMarkerNamespaceKey() = %q, want escaped unit separator", key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageCreateMarkerDir(t *testing.T) {
|
||||
dir := stageCreateMarkerDir("warehouse", []string{"ns"}, "orders")
|
||||
if !strings.Contains(dir, stageCreateMarkerDirName) {
|
||||
t.Fatalf("stageCreateMarkerDir() = %q, want marker dir segment %q", dir, stageCreateMarkerDirName)
|
||||
}
|
||||
if !strings.HasSuffix(dir, "/orders") {
|
||||
t.Fatalf("stageCreateMarkerDir() = %q, want suffix /orders", dir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageCreateStagedTablePath(t *testing.T) {
|
||||
tableUUID := uuid.MustParse("11111111-2222-3333-4444-555555555555")
|
||||
stagedPath := stageCreateStagedTablePath([]string{"ns"}, "orders", tableUUID)
|
||||
if !strings.Contains(stagedPath, stageCreateMarkerDirName) {
|
||||
t.Fatalf("stageCreateStagedTablePath() = %q, want marker dir segment %q", stagedPath, stageCreateMarkerDirName)
|
||||
}
|
||||
if !strings.HasSuffix(stagedPath, "/"+tableUUID.String()) {
|
||||
t.Fatalf("stageCreateStagedTablePath() = %q, want UUID suffix %q", stagedPath, tableUUID.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// saveMetadataFile saves the Iceberg metadata JSON file to the filer.
|
||||
// It constructs the filer path from the S3 location components.
|
||||
func (s *Server) saveMetadataFile(ctx context.Context, bucketName, tablePath, metadataFileName string, content []byte) error {
|
||||
|
||||
// Create context with timeout for file operations
|
||||
opCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
bucketsPath := s3tables.TablesPath
|
||||
|
||||
ensureDir := func(parent, name, errorContext string) error {
|
||||
_, err := filer_pb.LookupEntry(opCtx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: parent,
|
||||
Name: name,
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if err != filer_pb.ErrNotFound {
|
||||
return fmt.Errorf("lookup %s failed: %w", errorContext, err)
|
||||
}
|
||||
|
||||
// If lookup fails with ErrNotFound, try to create the directory.
|
||||
resp, createErr := client.CreateEntry(opCtx, &filer_pb.CreateEntryRequest{
|
||||
Directory: parent,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0755 | os.ModeDir),
|
||||
},
|
||||
},
|
||||
})
|
||||
if createErr != nil {
|
||||
return fmt.Errorf("failed to create %s: %w", errorContext, createErr)
|
||||
}
|
||||
if resp.Error != "" && !strings.Contains(resp.Error, "exist") {
|
||||
return fmt.Errorf("failed to create %s: %s", errorContext, resp.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
bucketDir := path.Join(bucketsPath, bucketName)
|
||||
// 1. Ensure bucket directory exists: <bucketsPath>/<bucket>
|
||||
if err := ensureDir(bucketsPath, bucketName, "bucket directory"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. Ensure table path exists under the bucket directory
|
||||
tableDir := bucketDir
|
||||
if tablePath != "" {
|
||||
segments := strings.Split(tablePath, "/")
|
||||
for _, segment := range segments {
|
||||
if segment == "" {
|
||||
continue
|
||||
}
|
||||
if err := ensureDir(tableDir, segment, "table directory"); err != nil {
|
||||
return err
|
||||
}
|
||||
tableDir = path.Join(tableDir, segment)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Ensure metadata directory exists: <bucketsPath>/<bucket>/<tablePath>/metadata
|
||||
metadataDir := path.Join(tableDir, "metadata")
|
||||
if err := ensureDir(tableDir, "metadata", "metadata directory"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 4. Write the file
|
||||
resp, err := client.CreateEntry(opCtx, &filer_pb.CreateEntryRequest{
|
||||
Directory: metadataDir,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: metadataFileName,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0644),
|
||||
FileSize: uint64(len(content)),
|
||||
},
|
||||
Content: content,
|
||||
Extended: map[string][]byte{
|
||||
"Mime-Type": []byte("application/json"),
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write metadata file: %w", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return fmt.Errorf("failed to write metadata file: %s", resp.Error)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) deleteMetadataFile(ctx context.Context, bucketName, tablePath, metadataFileName string) error {
|
||||
opCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
metadataDir := path.Join(s3tables.TablesPath, bucketName)
|
||||
if tablePath != "" {
|
||||
metadataDir = path.Join(metadataDir, tablePath)
|
||||
}
|
||||
metadataDir = path.Join(metadataDir, "metadata")
|
||||
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return filer_pb.DoRemove(opCtx, client, metadataDir, metadataFileName, true, false, true, false, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) loadMetadataFile(ctx context.Context, bucketName, tablePath, metadataFileName string) ([]byte, error) {
|
||||
opCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
metadataDir := path.Join(s3tables.TablesPath, bucketName)
|
||||
if tablePath != "" {
|
||||
metadataDir = path.Join(metadataDir, tablePath)
|
||||
}
|
||||
metadataDir = path.Join(metadataDir, "metadata")
|
||||
|
||||
var content []byte
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := filer_pb.LookupEntry(opCtx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: metadataDir,
|
||||
Name: metadataFileName,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp == nil || resp.Entry == nil {
|
||||
return fmt.Errorf("lookup returned nil entry for %s/%s", metadataDir, metadataFileName)
|
||||
}
|
||||
content = append([]byte(nil), resp.Entry.Content...)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// FilerClient provides access to the filer for storage operations.
|
||||
type FilerClient interface {
|
||||
WithFilerClient(streamingMode bool, fn func(client filer_pb.SeaweedFilerClient) error) error
|
||||
}
|
||||
|
||||
type S3Authenticator interface {
|
||||
AuthenticateRequest(r *http.Request) (string, interface{}, s3err.ErrorCode)
|
||||
}
|
||||
|
||||
// Server implements the Iceberg REST Catalog API.
|
||||
type Server struct {
|
||||
filerClient FilerClient
|
||||
tablesManager *s3tables.Manager
|
||||
prefix string // optional prefix for routes
|
||||
authenticator S3Authenticator
|
||||
}
|
||||
|
||||
// NewServer creates a new Iceberg REST Catalog server.
|
||||
func NewServer(filerClient FilerClient, authenticator S3Authenticator) *Server {
|
||||
manager := s3tables.NewManager()
|
||||
return &Server{
|
||||
filerClient: filerClient,
|
||||
tablesManager: manager,
|
||||
prefix: "",
|
||||
authenticator: authenticator,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterRoutes registers Iceberg REST API routes on the provided router.
|
||||
func (s *Server) RegisterRoutes(router *mux.Router) {
|
||||
// Add middleware to log all requests/responses
|
||||
router.Use(loggingMiddleware)
|
||||
|
||||
// Configuration endpoint - no auth needed for config
|
||||
router.HandleFunc("/v1/config", s.handleConfig).Methods(http.MethodGet)
|
||||
|
||||
// Namespace endpoints - wrapped with Auth middleware
|
||||
router.HandleFunc("/v1/namespaces", s.Auth(s.handleListNamespaces)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/namespaces", s.Auth(s.handleCreateNamespace)).Methods(http.MethodPost)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}", s.Auth(s.handleGetNamespace)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}", s.Auth(s.handleNamespaceExists)).Methods(http.MethodHead)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}", s.Auth(s.handleDropNamespace)).Methods(http.MethodDelete)
|
||||
|
||||
// Table endpoints - wrapped with Auth middleware
|
||||
router.HandleFunc("/v1/namespaces/{namespace}/tables", s.Auth(s.handleListTables)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}/tables", s.Auth(s.handleCreateTable)).Methods(http.MethodPost)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}/tables/{table}", s.Auth(s.handleLoadTable)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}/tables/{table}", s.Auth(s.handleTableExists)).Methods(http.MethodHead)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}/tables/{table}", s.Auth(s.handleDropTable)).Methods(http.MethodDelete)
|
||||
router.HandleFunc("/v1/namespaces/{namespace}/tables/{table}", s.Auth(s.handleUpdateTable)).Methods(http.MethodPost)
|
||||
|
||||
// With prefix support - wrapped with Auth middleware
|
||||
router.HandleFunc("/v1/{prefix}/namespaces", s.Auth(s.handleListNamespaces)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces", s.Auth(s.handleCreateNamespace)).Methods(http.MethodPost)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}", s.Auth(s.handleGetNamespace)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}", s.Auth(s.handleNamespaceExists)).Methods(http.MethodHead)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}", s.Auth(s.handleDropNamespace)).Methods(http.MethodDelete)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}/tables", s.Auth(s.handleListTables)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}/tables", s.Auth(s.handleCreateTable)).Methods(http.MethodPost)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}/tables/{table}", s.Auth(s.handleLoadTable)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}/tables/{table}", s.Auth(s.handleTableExists)).Methods(http.MethodHead)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}/tables/{table}", s.Auth(s.handleDropTable)).Methods(http.MethodDelete)
|
||||
router.HandleFunc("/v1/{prefix}/namespaces/{namespace}/tables/{table}", s.Auth(s.handleUpdateTable)).Methods(http.MethodPost)
|
||||
|
||||
// Catch-all for debugging
|
||||
router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
glog.V(2).Infof("Catch-all route hit: %s %s", r.Method, r.RequestURI)
|
||||
writeError(w, http.StatusNotFound, "NotFound", "Path not found")
|
||||
})
|
||||
|
||||
glog.V(2).Infof("Registered Iceberg REST Catalog routes")
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
glog.V(2).Infof("Iceberg REST request: %s %s from %s", r.Method, r.RequestURI, r.RemoteAddr)
|
||||
|
||||
// Log all headers for debugging
|
||||
glog.V(2).Infof("Iceberg REST headers:")
|
||||
for name, values := range r.Header {
|
||||
for _, value := range values {
|
||||
// Redact sensitive headers
|
||||
if name == "Authorization" && len(value) > 20 {
|
||||
glog.V(2).Infof(" %s: %s...%s", name, value[:20], value[len(value)-10:])
|
||||
} else {
|
||||
glog.V(2).Infof(" %s: %s", name, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create a response writer that captures the status code
|
||||
wrapped := &responseWriter{ResponseWriter: w}
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
glog.V(2).Infof("Iceberg REST response: %s %s -> %d", r.Method, r.RequestURI, wrapped.statusCode)
|
||||
})
|
||||
}
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *Server) Auth(handler http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.authenticator == nil {
|
||||
writeError(w, http.StatusUnauthorized, "NotAuthorizedException", "Authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
identityName, identity, errCode := s.authenticator.AuthenticateRequest(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
apiErr := s3err.GetAPIError(errCode)
|
||||
errorType := "RESTException"
|
||||
switch apiErr.HTTPStatusCode {
|
||||
case http.StatusForbidden:
|
||||
errorType = "ForbiddenException"
|
||||
case http.StatusUnauthorized:
|
||||
errorType = "NotAuthorizedException"
|
||||
case http.StatusBadRequest:
|
||||
errorType = "BadRequestException"
|
||||
case http.StatusInternalServerError:
|
||||
errorType = "InternalServerError"
|
||||
}
|
||||
writeError(w, apiErr.HTTPStatusCode, errorType, apiErr.Description)
|
||||
return
|
||||
}
|
||||
|
||||
if identityName != "" || identity != nil {
|
||||
ctx := r.Context()
|
||||
if identityName != "" {
|
||||
ctx = s3_constants.SetIdentityNameInContext(ctx, identityName)
|
||||
}
|
||||
if identity != nil {
|
||||
ctx = s3_constants.SetIdentityInContext(ctx, identity)
|
||||
}
|
||||
r = r.WithContext(ctx)
|
||||
}
|
||||
|
||||
handler(w, r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
const (
|
||||
stageCreateMarkerDirName = ".iceberg_staged"
|
||||
// Keep staged markers long enough to avoid deleting in-progress create transactions.
|
||||
stageCreateMarkerTTL = 72 * time.Hour
|
||||
)
|
||||
|
||||
type stageCreateMarker struct {
|
||||
TableUUID string `json:"table_uuid"`
|
||||
Location string `json:"location"`
|
||||
StagedMetadataLocation string `json:"staged_metadata_location,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}
|
||||
|
||||
func stageCreateMarkerNamespaceKey(namespace []string) string {
|
||||
return url.PathEscape(encodeNamespace(namespace))
|
||||
}
|
||||
|
||||
func stageCreateMarkerDir(bucketName string, namespace []string, tableName string) string {
|
||||
return path.Join(s3tables.TablesPath, bucketName, stageCreateMarkerDirName, stageCreateMarkerNamespaceKey(namespace), tableName)
|
||||
}
|
||||
|
||||
func stageCreateStagedTablePath(namespace []string, tableName string, tableUUID uuid.UUID) string {
|
||||
return path.Join(stageCreateMarkerDirName, stageCreateMarkerNamespaceKey(namespace), tableName, tableUUID.String())
|
||||
}
|
||||
|
||||
func (s *Server) pruneExpiredStageCreateMarkers(ctx context.Context, bucketName string, namespace []string, tableName string) error {
|
||||
opCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
markerDir := stageCreateMarkerDir(bucketName, namespace, tableName)
|
||||
now := time.Now().UTC()
|
||||
|
||||
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
stream, err := client.ListEntries(opCtx, &filer_pb.ListEntriesRequest{
|
||||
Directory: markerDir,
|
||||
Limit: 1024,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || strings.Contains(strings.ToLower(err.Error()), "not found") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if recvErr != nil {
|
||||
return recvErr
|
||||
}
|
||||
if resp.Entry == nil || resp.Entry.IsDirectory || len(resp.Entry.Content) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var marker stageCreateMarker
|
||||
if err := json.Unmarshal(resp.Entry.Content, &marker); err != nil {
|
||||
continue
|
||||
}
|
||||
expiresAt, err := time.Parse(time.RFC3339Nano, marker.ExpiresAt)
|
||||
if err != nil || !expiresAt.Before(now) {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := filer_pb.DoRemove(opCtx, client, markerDir, resp.Entry.Name, true, false, true, false, nil); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) loadLatestStageCreateMarker(ctx context.Context, bucketName string, namespace []string, tableName string) (*stageCreateMarker, error) {
|
||||
opCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
markerDir := stageCreateMarkerDir(bucketName, namespace, tableName)
|
||||
now := time.Now().UTC()
|
||||
|
||||
var latestMarker *stageCreateMarker
|
||||
var latestCreatedAt time.Time
|
||||
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
stream, err := client.ListEntries(opCtx, &filer_pb.ListEntriesRequest{
|
||||
Directory: markerDir,
|
||||
Limit: 1024,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || strings.Contains(strings.ToLower(err.Error()), "not found") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if recvErr != nil {
|
||||
return recvErr
|
||||
}
|
||||
if resp.Entry == nil || resp.Entry.IsDirectory || len(resp.Entry.Content) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var marker stageCreateMarker
|
||||
if err := json.Unmarshal(resp.Entry.Content, &marker); err != nil {
|
||||
continue
|
||||
}
|
||||
expiresAt, err := time.Parse(time.RFC3339Nano, marker.ExpiresAt)
|
||||
if err != nil || !expiresAt.After(now) {
|
||||
continue
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, marker.CreatedAt)
|
||||
if err != nil {
|
||||
createdAt = time.Time{}
|
||||
}
|
||||
if latestMarker == nil || createdAt.After(latestCreatedAt) {
|
||||
candidate := marker
|
||||
latestMarker = &candidate
|
||||
latestCreatedAt = createdAt
|
||||
}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return latestMarker, nil
|
||||
}
|
||||
|
||||
func (s *Server) writeStageCreateMarker(ctx context.Context, bucketName string, namespace []string, tableName string, tableUUID uuid.UUID, location string, stagedMetadataLocation string) error {
|
||||
opCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
marker := stageCreateMarker{
|
||||
TableUUID: tableUUID.String(),
|
||||
Location: location,
|
||||
StagedMetadataLocation: stagedMetadataLocation,
|
||||
CreatedAt: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
ExpiresAt: time.Now().UTC().Add(stageCreateMarkerTTL).Format(time.RFC3339Nano),
|
||||
}
|
||||
content, err := json.Marshal(marker)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.pruneExpiredStageCreateMarkers(ctx, bucketName, namespace, tableName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
ensureDir := func(parent, name, errorContext string) error {
|
||||
_, lookupErr := filer_pb.LookupEntry(opCtx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: parent,
|
||||
Name: name,
|
||||
})
|
||||
if lookupErr == nil {
|
||||
return nil
|
||||
}
|
||||
if lookupErr != filer_pb.ErrNotFound {
|
||||
return fmt.Errorf("lookup %s failed: %w", errorContext, lookupErr)
|
||||
}
|
||||
|
||||
resp, createErr := client.CreateEntry(opCtx, &filer_pb.CreateEntryRequest{
|
||||
Directory: parent,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0755 | os.ModeDir),
|
||||
},
|
||||
},
|
||||
})
|
||||
if createErr != nil {
|
||||
return fmt.Errorf("failed to create %s: %w", errorContext, createErr)
|
||||
}
|
||||
if resp.Error != "" && !strings.Contains(resp.Error, "exist") {
|
||||
return fmt.Errorf("failed to create %s: %s", errorContext, resp.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
segments := []string{bucketName, stageCreateMarkerDirName, stageCreateMarkerNamespaceKey(namespace), tableName}
|
||||
currentDir := s3tables.TablesPath
|
||||
for _, segment := range segments {
|
||||
if segment == "" {
|
||||
continue
|
||||
}
|
||||
if err := ensureDir(currentDir, segment, "stage-create marker directory"); err != nil {
|
||||
return err
|
||||
}
|
||||
currentDir = path.Join(currentDir, segment)
|
||||
}
|
||||
|
||||
entryName := tableUUID.String() + ".json"
|
||||
resp, createErr := client.CreateEntry(opCtx, &filer_pb.CreateEntryRequest{
|
||||
Directory: currentDir,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: entryName,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0644),
|
||||
FileSize: uint64(len(content)),
|
||||
},
|
||||
Content: content,
|
||||
Extended: map[string][]byte{
|
||||
"Mime-Type": []byte("application/json"),
|
||||
},
|
||||
},
|
||||
})
|
||||
if createErr != nil {
|
||||
return createErr
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return errors.New(resp.Error)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) deleteStageCreateMarkers(ctx context.Context, bucketName string, namespace []string, tableName string) error {
|
||||
opCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
parentDir := path.Dir(stageCreateMarkerDir(bucketName, namespace, tableName))
|
||||
targetName := path.Base(stageCreateMarkerDir(bucketName, namespace, tableName))
|
||||
|
||||
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := filer_pb.DoRemove(opCtx, client, parentDir, targetName, true, true, true, false, nil)
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func isStageCreateEnabled() bool {
|
||||
value := strings.TrimSpace(strings.ToLower(os.Getenv("ICEBERG_ENABLE_STAGE_CREATE")))
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
switch value {
|
||||
case "0", "false", "no", "off":
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// parseNamespace parses the namespace from path parameter.
|
||||
// Iceberg uses unit separator (0x1F) for multi-level namespaces.
|
||||
// Note: mux already decodes URL-encoded path parameters, so we only split by unit separator.
|
||||
func parseNamespace(encoded string) []string {
|
||||
if encoded == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(encoded, "\x1F")
|
||||
// Filter empty parts
|
||||
result := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if p != "" {
|
||||
result = append(result, p)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// encodeNamespace encodes namespace parts for response.
|
||||
func encodeNamespace(parts []string) string {
|
||||
return strings.Join(parts, "\x1F")
|
||||
}
|
||||
|
||||
func parseS3Location(location string) (bucketName, tablePath string, err error) {
|
||||
if !strings.HasPrefix(location, "s3://") {
|
||||
return "", "", fmt.Errorf("unsupported location: %s", location)
|
||||
}
|
||||
trimmed := strings.TrimPrefix(location, "s3://")
|
||||
trimmed = strings.TrimSuffix(trimmed, "/")
|
||||
if trimmed == "" {
|
||||
return "", "", fmt.Errorf("invalid location: %s", location)
|
||||
}
|
||||
parts := strings.SplitN(trimmed, "/", 2)
|
||||
bucketName = parts[0]
|
||||
if bucketName == "" {
|
||||
return "", "", fmt.Errorf("invalid location bucket: %s", location)
|
||||
}
|
||||
if len(parts) == 2 {
|
||||
tablePath = parts[1]
|
||||
}
|
||||
return bucketName, tablePath, nil
|
||||
}
|
||||
|
||||
func tableLocationFromMetadataLocation(metadataLocation string) string {
|
||||
trimmed := strings.TrimSuffix(metadataLocation, "/")
|
||||
if idx := strings.LastIndex(trimmed, "/metadata/"); idx != -1 {
|
||||
return trimmed[:idx]
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
// writeJSON writes a JSON response.
|
||||
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if v != nil {
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
glog.Errorf("Iceberg: failed to encode response: %v", err)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
}
|
||||
|
||||
// writeError writes an Iceberg error response.
|
||||
func writeError(w http.ResponseWriter, status int, errType, message string) {
|
||||
resp := ErrorResponse{
|
||||
Error: ErrorModel{
|
||||
Message: message,
|
||||
Type: errType,
|
||||
Code: status,
|
||||
},
|
||||
}
|
||||
writeJSON(w, status, resp)
|
||||
}
|
||||
|
||||
// getBucketFromPrefix extracts table bucket name from prefix parameter.
|
||||
// For now, we use the prefix as the table bucket name.
|
||||
func getBucketFromPrefix(r *http.Request) string {
|
||||
vars := mux.Vars(r)
|
||||
if prefix := vars["prefix"]; prefix != "" {
|
||||
return prefix
|
||||
}
|
||||
if bucket := os.Getenv("S3TABLES_DEFAULT_BUCKET"); bucket != "" {
|
||||
return bucket
|
||||
}
|
||||
// Default bucket if no prefix - use "warehouse" for Iceberg
|
||||
return "warehouse"
|
||||
}
|
||||
|
||||
// buildTableBucketARN builds an ARN for a table bucket.
|
||||
func buildTableBucketARN(bucketName string) string {
|
||||
arn, _ := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3_constants.AccountAdminId, bucketName)
|
||||
return arn
|
||||
}
|
||||
|
||||
const (
|
||||
defaultListPageSize = 1000
|
||||
maxListPageSize = 1000
|
||||
)
|
||||
|
||||
func getPaginationQueryParam(r *http.Request, primary, fallback string) string {
|
||||
if v := strings.TrimSpace(r.URL.Query().Get(primary)); v != "" {
|
||||
return v
|
||||
}
|
||||
return strings.TrimSpace(r.URL.Query().Get(fallback))
|
||||
}
|
||||
|
||||
func parsePagination(r *http.Request) (pageToken string, pageSize int, err error) {
|
||||
pageToken = getPaginationQueryParam(r, "pageToken", "page-token")
|
||||
pageSize = defaultListPageSize
|
||||
|
||||
pageSizeValue := getPaginationQueryParam(r, "pageSize", "page-size")
|
||||
if pageSizeValue == "" {
|
||||
return pageToken, pageSize, nil
|
||||
}
|
||||
|
||||
parsedPageSize, parseErr := strconv.Atoi(pageSizeValue)
|
||||
if parseErr != nil || parsedPageSize <= 0 {
|
||||
return pageToken, 0, fmt.Errorf("invalid pageSize %q: must be a positive integer", pageSizeValue)
|
||||
}
|
||||
if parsedPageSize > maxListPageSize {
|
||||
return pageToken, 0, fmt.Errorf("invalid pageSize %q: must be <= %d", pageSizeValue, maxListPageSize)
|
||||
}
|
||||
|
||||
return pageToken, parsedPageSize, nil
|
||||
}
|
||||
|
||||
func normalizeNamespaceProperties(properties map[string]string) map[string]string {
|
||||
if properties == nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
return properties
|
||||
}
|
||||
@@ -381,15 +381,7 @@ func ExtractConditionValuesFromRequest(r *http.Request) map[string][]string {
|
||||
values := make(map[string][]string)
|
||||
|
||||
// AWS condition keys
|
||||
// Extract IP address without port for proper IP matching
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
// Log a warning if splitting fails
|
||||
glog.Warningf("Failed to parse IP address from RemoteAddr %q: %v", r.RemoteAddr, err)
|
||||
// If splitting fails, use the original RemoteAddr (might be just IP without port)
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
values["aws:SourceIp"] = []string{host}
|
||||
values["aws:SourceIp"] = []string{extractSourceIP(r)}
|
||||
values["aws:SecureTransport"] = []string{fmt.Sprintf("%t", r.TLS != nil)}
|
||||
// Use AWS standard condition key for current time
|
||||
values["aws:CurrentTime"] = []string{time.Now().Format(time.RFC3339)}
|
||||
@@ -445,6 +437,101 @@ func ExtractConditionValuesFromRequest(r *http.Request) map[string][]string {
|
||||
return values
|
||||
}
|
||||
|
||||
// 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.
|
||||
// When the service is exposed directly, clients can spoof aws:SourceIp unless a
|
||||
// reverse proxy overwrites these headers.
|
||||
|
||||
// isPrivateIP returns true if the given IP is considered a "trusted proxy"
|
||||
// address, such as loopback, link-local, or RFC1918 private ranges.
|
||||
// isPrivateIP returns true if the given IP is considered a "trusted proxy"
|
||||
// address, such as loopback, link-local, or private ranges.
|
||||
func isPrivateIP(ip net.IP) bool {
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
return ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate()
|
||||
}
|
||||
|
||||
func extractSourceIP(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
remoteAddr := strings.TrimSpace(r.RemoteAddr)
|
||||
if remoteAddr == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Fall back to unix socket markers or other non-IP placeholders.
|
||||
if remoteAddr == "@" {
|
||||
return remoteAddr
|
||||
}
|
||||
|
||||
host := remoteAddr
|
||||
if h, _, err := net.SplitHostPort(remoteAddr); err == nil {
|
||||
host = h
|
||||
}
|
||||
|
||||
remoteIP := net.ParseIP(host)
|
||||
if remoteIP == nil {
|
||||
// Do not return DNS names or unparseable values.
|
||||
return ""
|
||||
}
|
||||
|
||||
// Only trust forwarding headers when the connection appears to come from
|
||||
// a trusted proxy (e.g., private/loopback address).
|
||||
if isPrivateIP(remoteIP) {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
// Iterate right-to-left to find the first non-trusted (public) IP
|
||||
entries := strings.Split(xff, ",")
|
||||
for i := len(entries) - 1; i >= 0; i-- {
|
||||
candidate := strings.TrimSpace(entries[i])
|
||||
if candidate == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
ip := net.ParseIP(candidate)
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// If the IP is trusted/private, we treat it as another proxy in the chain and continue
|
||||
if isPrivateIP(ip) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Found a public/non-trusted IP, return it as the client IP
|
||||
return ip.String()
|
||||
}
|
||||
|
||||
// If we exhausted the list (all were private/trusted) or found no valid IPs,
|
||||
// fallback related logic could go here.
|
||||
// For now, if all are private, we continue to check X-Real-Ip or return RemoteIP?
|
||||
// The prompt implies we should prefer the extracted IP.
|
||||
// If all in XFF are private, likely the original client IS private (internal network).
|
||||
// The best guess for "original client" in a fully trusted chain is the left-most valid IP.
|
||||
for _, candidate := range entries {
|
||||
candidate = strings.TrimSpace(candidate)
|
||||
if ip := net.ParseIP(candidate); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if xRealIP := strings.TrimSpace(r.Header.Get("X-Real-Ip")); xRealIP != "" {
|
||||
if ip := net.ParseIP(xRealIP); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Default to the actual peer IP when no trusted proxy is detected or the
|
||||
// forwarding headers are absent/invalid.
|
||||
return remoteIP.String()
|
||||
}
|
||||
|
||||
// BuildResourceArn builds an ARN for the given bucket and object
|
||||
func BuildResourceArn(bucketName, objectName string) string {
|
||||
if objectName == "" {
|
||||
|
||||
@@ -458,6 +458,89 @@ func TestExtractConditionValuesFromRequest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractConditionValuesFromRequestSourceIPPrecedence(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
header map[string][]string
|
||||
remoteAddr string
|
||||
expectedIP string
|
||||
}{
|
||||
{
|
||||
name: "uses right-most public X-Forwarded-For entry",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"bad-ip, 203.0.113.10, 198.51.100.5"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "198.51.100.5",
|
||||
},
|
||||
{
|
||||
name: "falls back to X-Real-Ip when X-Forwarded-For has no valid ip",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"bad-ip"},
|
||||
"X-Real-Ip": {"198.51.100.7"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "198.51.100.7",
|
||||
},
|
||||
{
|
||||
name: "uses RemoteAddr ip when no forwarding headers",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "192.168.1.100",
|
||||
},
|
||||
{
|
||||
name: "keeps unix socket marker when RemoteAddr is not an ip",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "@",
|
||||
expectedIP: "@",
|
||||
},
|
||||
{
|
||||
name: "uses IPv6 X-Forwarded-For entry",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"2001:db8::8, 198.51.100.7"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "198.51.100.7",
|
||||
},
|
||||
{
|
||||
name: "ignores spoofed IP when real client is public",
|
||||
header: map[string][]string{
|
||||
"X-Forwarded-For": {"8.8.8.8, 203.0.113.10, 10.0.0.1"},
|
||||
},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
expectedIP: "203.0.113.10",
|
||||
},
|
||||
{
|
||||
name: "handles bracketed IPv6 remote address",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "[2001:db8::1]:12345",
|
||||
expectedIP: "2001:db8::1",
|
||||
},
|
||||
{
|
||||
name: "avoids returning DNS host names",
|
||||
header: map[string][]string{},
|
||||
remoteAddr: "example.com:9000",
|
||||
expectedIP: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := &http.Request{
|
||||
Method: "GET",
|
||||
URL: &url.URL{Path: "/"},
|
||||
Header: tt.header,
|
||||
RemoteAddr: tt.remoteAddr,
|
||||
}
|
||||
|
||||
values := ExtractConditionValuesFromRequest(req)
|
||||
if len(values["aws:SourceIp"]) != 1 || values["aws:SourceIp"][0] != tt.expectedIP {
|
||||
t.Errorf("Expected SourceIp %q, got %v", tt.expectedIP, values["aws:SourceIp"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyEvaluationWithConditions(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ const (
|
||||
ExtETagKey = "Seaweed-X-Amz-ETag"
|
||||
ExtLatestVersionIdKey = "Seaweed-X-Amz-Latest-Version-Id"
|
||||
ExtLatestVersionFileNameKey = "Seaweed-X-Amz-Latest-Version-File-Name"
|
||||
ExtS3ImplicitDir = "Seaweed-X-Amz-Implicit-Dir"
|
||||
ExtAllowEmptyFolders = "Seaweed-X-Amz-Allow-Empty-Folders"
|
||||
// Cached list metadata in .versions directory for single-scan efficiency
|
||||
ExtLatestVersionSizeKey = "Seaweed-X-Amz-Latest-Version-Size"
|
||||
ExtLatestVersionETagKey = "Seaweed-X-Amz-Latest-Version-ETag"
|
||||
|
||||
@@ -2,7 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -23,7 +22,7 @@ const (
|
||||
func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("DeleteObjectHandler %s %s", bucket, object)
|
||||
glog.Infof("DeleteObjectHandler %s %s", bucket, object)
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
@@ -125,7 +124,9 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
target := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object))
|
||||
// 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 {
|
||||
@@ -340,13 +341,9 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
} else {
|
||||
// Handle non-versioned delete (original logic)
|
||||
lastSeparator := strings.LastIndex(object.Key, "/")
|
||||
parentDirectoryPath, entryName, isDeleteData, isRecursive := "", object.Key, true, false
|
||||
if lastSeparator > 0 && lastSeparator+1 < len(object.Key) {
|
||||
entryName = object.Key[lastSeparator+1:]
|
||||
parentDirectoryPath = object.Key[:lastSeparator]
|
||||
}
|
||||
parentDirectoryPath = fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), parentDirectoryPath)
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object.Key)
|
||||
parentDirectoryPath, entryName := target.DirAndName()
|
||||
isDeleteData, isRecursive := true, false
|
||||
|
||||
err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
|
||||
if err == nil {
|
||||
|
||||
@@ -351,25 +351,8 @@ func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, m
|
||||
}
|
||||
|
||||
// Adjust nextMarker for CommonPrefixes to include trailing slash (AWS S3 compliance)
|
||||
if cursor.isTruncated && lastEntryWasCommonPrefix && lastCommonPrefixName != "" {
|
||||
// For CommonPrefixes, NextMarker should include the trailing slash
|
||||
if requestDir != "" {
|
||||
if prefix != "" {
|
||||
nextMarker = requestDir + "/" + prefix + "/" + lastCommonPrefixName + "/"
|
||||
} else {
|
||||
nextMarker = requestDir + "/" + lastCommonPrefixName + "/"
|
||||
}
|
||||
} else {
|
||||
nextMarker = lastCommonPrefixName + "/"
|
||||
}
|
||||
} else if cursor.isTruncated {
|
||||
if requestDir != "" {
|
||||
if prefix != "" {
|
||||
nextMarker = requestDir + "/" + prefix + "/" + nextMarker
|
||||
} else {
|
||||
nextMarker = requestDir + "/" + nextMarker
|
||||
}
|
||||
}
|
||||
if cursor.isTruncated {
|
||||
nextMarker = buildTruncatedNextMarker(requestDir, prefix, nextMarker, lastEntryWasCommonPrefix, lastCommonPrefixName)
|
||||
}
|
||||
|
||||
if cursor.isTruncated {
|
||||
@@ -480,6 +463,28 @@ func toParentAndDescendants(dirAndName string) (dir, name string) {
|
||||
return
|
||||
}
|
||||
|
||||
func buildTruncatedNextMarker(requestDir, prefix, nextMarker string, lastEntryWasCommonPrefix bool, lastCommonPrefixName string) string {
|
||||
if lastEntryWasCommonPrefix && lastCommonPrefixName != "" {
|
||||
// For CommonPrefixes, NextMarker should include the trailing slash
|
||||
if requestDir != "" {
|
||||
if prefix != "" {
|
||||
return requestDir + "/" + prefix + "/" + lastCommonPrefixName + "/"
|
||||
}
|
||||
return requestDir + "/" + lastCommonPrefixName + "/"
|
||||
}
|
||||
if prefix != "" {
|
||||
return prefix + "/" + lastCommonPrefixName + "/"
|
||||
}
|
||||
return lastCommonPrefixName + "/"
|
||||
}
|
||||
|
||||
if requestDir != "" {
|
||||
return requestDir + "/" + nextMarker
|
||||
}
|
||||
|
||||
return nextMarker
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, bucket string, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
|
||||
// invariants
|
||||
// prefix and marker should be under dir, marker may contain "/"
|
||||
|
||||
@@ -148,6 +148,26 @@ func Test_normalizePrefixMarker(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTruncatedNextMarker(t *testing.T) {
|
||||
t.Run("does not duplicate prefix segment in next continuation token", func(t *testing.T) {
|
||||
prefix := "export_2026-02-10_17-00-23"
|
||||
nextMarker := "export_2026-02-10_17-00-23/4156000e.jpg"
|
||||
|
||||
actual := buildTruncatedNextMarker("xemu", prefix, nextMarker, false, "")
|
||||
assert.Equal(t, "xemu/export_2026-02-10_17-00-23/4156000e.jpg", actual)
|
||||
})
|
||||
|
||||
t.Run("keeps common prefix marker trailing slash", func(t *testing.T) {
|
||||
actual := buildTruncatedNextMarker("xemu", "export_2026-02-10_17-00-23", "", true, "nested")
|
||||
assert.Equal(t, "xemu/export_2026-02-10_17-00-23/nested/", actual)
|
||||
})
|
||||
|
||||
t.Run("includes prefix for common prefix marker when request dir is empty", func(t *testing.T) {
|
||||
actual := buildTruncatedNextMarker("", "foo", "", true, "bar")
|
||||
assert.Equal(t, "foo/bar/", actual)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAllowUnorderedParameterValidation(t *testing.T) {
|
||||
// Test getListObjectsV1Args with allow-unordered parameter
|
||||
t.Run("getListObjectsV1Args with allow-unordered", func(t *testing.T) {
|
||||
|
||||
@@ -139,6 +139,8 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
fullDirPath = fullDirPath + "/" + dirName
|
||||
}
|
||||
|
||||
glog.Infof("PutObjectHandler: explicit directory marker %s/%s (contentType=%q, len=%d)",
|
||||
bucket, object, objectContentType, r.ContentLength)
|
||||
if err := s3a.mkdir(
|
||||
fullDirPath, entryName,
|
||||
func(entry *filer_pb.Entry) {
|
||||
|
||||
+98
-16
@@ -1,9 +1,11 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -424,6 +426,93 @@ func (s3a *S3ApiServer) handleCORSOriginValidation(w http.ResponseWriter, r *htt
|
||||
return true
|
||||
}
|
||||
|
||||
// UnifiedPostHandler handles authenticated POST requests to the root path
|
||||
// It inspects the Action parameter to dispatch to either STS or IAM handlers
|
||||
func (s3a *S3ApiServer) UnifiedPostHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// 1. Authenticate (preserves body)
|
||||
identity, errCode := s3a.iam.AuthSignatureOnly(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Parse Form to get Action
|
||||
// Save the body first so we can restore it for STS handler signature verification
|
||||
var bodyBytes []byte
|
||||
if r.Body != nil {
|
||||
// Limit body size to prevent DoS attacks
|
||||
r.Body = http.MaxBytesReader(w, r.Body, iamRequestBodyLimit)
|
||||
var err error
|
||||
bodyBytes, err = io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
glog.Errorf("failed to read request body: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
r.Body.Close()
|
||||
// Restore body for ParseForm
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
||||
}
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Restore body again for downstream handlers (STS needs it for signature verification)
|
||||
if bodyBytes != nil {
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
||||
}
|
||||
|
||||
// 3. Dispatch
|
||||
action := r.Form.Get("Action")
|
||||
if strings.HasPrefix(action, "AssumeRole") {
|
||||
// STS
|
||||
if s3a.stsHandlers == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrServiceUnavailable)
|
||||
return
|
||||
}
|
||||
s3a.stsHandlers.HandleSTSRequest(w, r)
|
||||
} else {
|
||||
// IAM
|
||||
// IAM API requests must be authenticated - reject nil identity
|
||||
if identity == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
|
||||
// Store identity in context
|
||||
// Always set identity in context when non-nil to ensure downstream handlers have access
|
||||
ctx := r.Context()
|
||||
if identity.Name != "" {
|
||||
ctx = SetIdentityNameInContext(ctx, identity.Name)
|
||||
}
|
||||
ctx = SetIdentityInContext(ctx, identity)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
targetUserName := r.Form.Get("UserName")
|
||||
|
||||
// Check permissions based on action type
|
||||
isSelfServiceAction := iamRequiresAdminForOthers(action)
|
||||
isActingOnSelf := targetUserName == "" || targetUserName == identity.Name
|
||||
|
||||
// Permission check is required for all actions except for self-service actions
|
||||
// performed on the user's own identity.
|
||||
if !(isSelfServiceAction && isActingOnSelf) {
|
||||
if !identity.isAdmin() {
|
||||
if s3a.iam.VerifyActionPermission(r, identity, Action("iam:"+action), "arn:aws:iam:::*", "") != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Call Limit middleware + DoActions
|
||||
handler, _ := s3a.cb.Limit(s3a.embeddedIam.DoActions, ACTION_WRITE)
|
||||
handler.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
|
||||
// API Router
|
||||
apiRouter := router.PathPrefix("/").Subrouter()
|
||||
@@ -685,38 +774,31 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
|
||||
// POST / (without specific query parameters)
|
||||
// Uses AuthIam for granular permission checking
|
||||
if s3a.embeddedIam != nil {
|
||||
// 2. Authenticated IAM requests
|
||||
|
||||
// 2. Authenticated IAM/STS Post requests
|
||||
// Only match if the request appears to be authenticated (AWS Signature)
|
||||
// AND is not an STS request (which should be handled by STS handlers)
|
||||
// We use a UnifiedPostHandler to dispatch based on Action (STS vs IAM)
|
||||
iamMatcher := func(r *http.Request, rm *mux.RouteMatch) bool {
|
||||
if getRequestAuthType(r) == authTypeAnonymous {
|
||||
return false
|
||||
}
|
||||
|
||||
// IMPORTANT: Do NOT call r.ParseForm() here!
|
||||
// ParseForm() consumes the request body, which breaks AWS Signature V4 verification
|
||||
// for IAM requests. The signature must be calculated on the original body.
|
||||
// Instead, check only the query string for the Action parameter.
|
||||
// IMPORTANT: We do NOT parse the body here.
|
||||
// UnifiedPostHandler will handle authentication and body parsing.
|
||||
// We only filter out requests that are explicitly targeted at STS via Query params
|
||||
// to avoid double-handling, although UnifiedPostHandler would handle them correctly anyway.
|
||||
|
||||
// For IAM requests, the Action is typically in the POST body, not query string
|
||||
// So we match all authenticated POST / requests and let AuthIam validate them
|
||||
// This is safe because:
|
||||
// 1. STS actions are excluded (handled by separate STS routes)
|
||||
// 2. S3 operations don't POST to / (they use /<bucket> or /<bucket>/<key>)
|
||||
// 3. IAM operations all POST to /
|
||||
|
||||
// Only exclude STS actions which might be in query string
|
||||
// Action in Query String is handled by explicit STS routes above
|
||||
action := r.URL.Query().Get("Action")
|
||||
if action == "AssumeRole" || action == "AssumeRoleWithWebIdentity" || action == "AssumeRoleWithLDAPIdentity" {
|
||||
return false
|
||||
}
|
||||
|
||||
// Match all other authenticated POST / requests (IAM operations)
|
||||
return true
|
||||
}
|
||||
|
||||
apiRouter.Methods(http.MethodPost).Path("/").MatcherFunc(iamMatcher).
|
||||
HandlerFunc(track(s3a.embeddedIam.AuthIam(s3a.cb.Limit(s3a.embeddedIam.DoActions, ACTION_WRITE)), "IAM"))
|
||||
HandlerFunc(track(s3a.UnifiedPostHandler, "IAM-Unified"))
|
||||
|
||||
glog.V(1).Infof("Embedded IAM API enabled on S3 port")
|
||||
}
|
||||
|
||||
+41
-64
@@ -226,16 +226,27 @@ func parseOptionalIntParam(r *http.Request, name string) (int, error) {
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func parseOptionalNamespace(r *http.Request, name string) []string {
|
||||
func parseOptionalNamespace(r *http.Request, name string) ([]string, error) {
|
||||
value := r.URL.Query().Get(name)
|
||||
if value == "" {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{value}); err != nil {
|
||||
glog.V(1).Infof("invalid namespace value for %s: %q: %v", name, value, err)
|
||||
return nil
|
||||
parts, err := s3tables.ParseNamespace(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid %s: %w", name, err)
|
||||
}
|
||||
return []string{value}
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
func parseRequiredNamespacePathParam(r *http.Request, name string) ([]string, error) {
|
||||
value, err := getDecodedPathParam(r, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == "" {
|
||||
return nil, fmt.Errorf("%s is required", name)
|
||||
}
|
||||
return s3tables.ParseNamespace(value)
|
||||
}
|
||||
|
||||
// parseTagKeys handles tag key parsing from query parameters.
|
||||
@@ -352,19 +363,13 @@ func buildGetNamespaceRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := getDecodedPathParam(r, "namespace")
|
||||
namespace, err := parseRequiredNamespacePathParam(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{namespace}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s3tables.GetNamespaceRequest{
|
||||
TableBucketARN: tableBucketARN,
|
||||
Namespace: []string{namespace},
|
||||
Namespace: namespace,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -373,19 +378,13 @@ func buildDeleteNamespaceRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := getDecodedPathParam(r, "namespace")
|
||||
namespace, err := parseRequiredNamespacePathParam(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{namespace}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s3tables.DeleteNamespaceRequest{
|
||||
TableBucketARN: tableBucketARN,
|
||||
Namespace: []string{namespace},
|
||||
Namespace: namespace,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -398,18 +397,12 @@ func buildCreateTableRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := getDecodedPathParam(r, "namespace")
|
||||
namespace, err := parseRequiredNamespacePathParam(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{namespace}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.TableBucketARN = tableBucketARN
|
||||
req.Namespace = []string{namespace}
|
||||
req.Namespace = namespace
|
||||
return &req, nil
|
||||
}
|
||||
|
||||
@@ -418,13 +411,17 @@ func buildListTablesRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := parseOptionalNamespace(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
maxTables, err := parseOptionalIntParam(r, "maxTables")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s3tables.ListTablesRequest{
|
||||
TableBucketARN: tableBucketARN,
|
||||
Namespace: parseOptionalNamespace(r, "namespace"),
|
||||
Namespace: namespace,
|
||||
Prefix: r.URL.Query().Get("prefix"),
|
||||
ContinuationToken: r.URL.Query().Get("continuationToken"),
|
||||
MaxTables: maxTables,
|
||||
@@ -439,7 +436,11 @@ func buildGetTableRequest(r *http.Request) (interface{}, error) {
|
||||
}
|
||||
if tableARN == "" {
|
||||
req.TableBucketARN = query.Get("tableBucketARN")
|
||||
req.Namespace = parseOptionalNamespace(r, "namespace")
|
||||
namespace, err := parseOptionalNamespace(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Namespace = namespace
|
||||
req.Name = query.Get("name")
|
||||
if req.TableBucketARN == "" || len(req.Namespace) == 0 || req.Name == "" {
|
||||
return nil, fmt.Errorf("either tableArn or (tableBucketARN, namespace, name) must be provided")
|
||||
@@ -453,16 +454,10 @@ func buildDeleteTableRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := getDecodedPathParam(r, "namespace")
|
||||
namespace, err := parseRequiredNamespacePathParam(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{namespace}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name, err := getDecodedPathParam(r, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -475,7 +470,7 @@ func buildDeleteTableRequest(r *http.Request) (interface{}, error) {
|
||||
}
|
||||
return &s3tables.DeleteTableRequest{
|
||||
TableBucketARN: tableBucketARN,
|
||||
Namespace: []string{namespace},
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
VersionToken: r.URL.Query().Get("versionToken"),
|
||||
}, nil
|
||||
@@ -490,16 +485,10 @@ func buildPutTablePolicyRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := getDecodedPathParam(r, "namespace")
|
||||
namespace, err := parseRequiredNamespacePathParam(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{namespace}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name, err := getDecodedPathParam(r, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -511,7 +500,7 @@ func buildPutTablePolicyRequest(r *http.Request) (interface{}, error) {
|
||||
return nil, err
|
||||
}
|
||||
req.TableBucketARN = tableBucketARN
|
||||
req.Namespace = []string{namespace}
|
||||
req.Namespace = namespace
|
||||
req.Name = name
|
||||
return &req, nil
|
||||
}
|
||||
@@ -521,16 +510,10 @@ func buildGetTablePolicyRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := getDecodedPathParam(r, "namespace")
|
||||
namespace, err := parseRequiredNamespacePathParam(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{namespace}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name, err := getDecodedPathParam(r, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -543,7 +526,7 @@ func buildGetTablePolicyRequest(r *http.Request) (interface{}, error) {
|
||||
}
|
||||
return &s3tables.GetTablePolicyRequest{
|
||||
TableBucketARN: tableBucketARN,
|
||||
Namespace: []string{namespace},
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}, nil
|
||||
}
|
||||
@@ -553,16 +536,10 @@ func buildDeleteTablePolicyRequest(r *http.Request) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
namespace, err := getDecodedPathParam(r, "namespace")
|
||||
namespace, err := parseRequiredNamespacePathParam(r, "namespace")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
if _, err := s3tables.ValidateNamespace([]string{namespace}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name, err := getDecodedPathParam(r, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -575,7 +552,7 @@ func buildDeleteTablePolicyRequest(r *http.Request) (interface{}, error) {
|
||||
}
|
||||
return &s3tables.DeleteTablePolicyRequest{
|
||||
TableBucketARN: tableBucketARN,
|
||||
Namespace: []string{namespace},
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
const testTableBucketARN = "arn:aws:s3tables:us-east-1:123456789012:bucket/test-bucket"
|
||||
|
||||
func TestBuildListTablesRequestRejectsInvalidNamespaceQuery(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
namespace string
|
||||
}{
|
||||
{name: "uppercase", namespace: "InvalidNamespace"},
|
||||
{name: "hyphen", namespace: "invalid-ns"},
|
||||
{name: "slash", namespace: "a/b"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/tables?namespace="+url.QueryEscape(tc.namespace), nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"tableBucketARN": testTableBucketARN})
|
||||
|
||||
_, err := buildListTablesRequest(req)
|
||||
if err == nil {
|
||||
t.Fatalf("expected invalid namespace query to return an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "invalid namespace") {
|
||||
t.Fatalf("expected invalid namespace error, got %q", err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildGetTableRequestRejectsInvalidNamespaceQuery(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
namespace string
|
||||
}{
|
||||
{name: "uppercase", namespace: "InvalidNamespace"},
|
||||
{name: "hyphen", namespace: "invalid-ns"},
|
||||
{name: "slash", namespace: "a/b"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/get-table?tableBucketARN="+url.QueryEscape(testTableBucketARN)+"&namespace="+url.QueryEscape(tc.namespace)+"&name=table1", nil)
|
||||
|
||||
_, err := buildGetTableRequest(req)
|
||||
if err == nil {
|
||||
t.Fatalf("expected invalid namespace query to return an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "invalid namespace") {
|
||||
t.Fatalf("expected invalid namespace error, got %q", err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleRestOperationReturnsBadRequestForInvalidNamespaceQuery(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
namespace string
|
||||
}{
|
||||
{name: "uppercase", namespace: "InvalidNamespace"},
|
||||
{name: "hyphen", namespace: "invalid-ns"},
|
||||
{name: "slash", namespace: "a/b"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/tables?namespace="+url.QueryEscape(tc.namespace), nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"tableBucketARN": testTableBucketARN})
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
st := &S3TablesApiServer{}
|
||||
st.handleRestOperation("ListTables", buildListTablesRequest).ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rr.Code)
|
||||
}
|
||||
|
||||
var body map[string]string
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("failed to decode error response: %v", err)
|
||||
}
|
||||
if got, want := body["__type"], s3tables.ErrCodeInvalidRequest; got != want {
|
||||
t.Fatalf("expected __type=%q, got %q", want, got)
|
||||
}
|
||||
if !strings.Contains(body["message"], "invalid namespace") {
|
||||
t.Fatalf("expected invalid namespace error message, got %q", body["message"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,7 @@ const (
|
||||
|
||||
ErrTooManyRequest
|
||||
ErrRequestBytesExceed
|
||||
ErrServiceUnavailable
|
||||
|
||||
OwnershipControlsNotFoundError
|
||||
ErrNoSuchTagSet
|
||||
@@ -512,6 +513,11 @@ var errorCodeResponse = map[ErrorCode]APIError{
|
||||
Description: "Simultaneous request bytes exceed limitations",
|
||||
HTTPStatusCode: http.StatusServiceUnavailable,
|
||||
},
|
||||
ErrServiceUnavailable: {
|
||||
Code: "ServiceUnavailable",
|
||||
Description: "Service Unavailable",
|
||||
HTTPStatusCode: http.StatusServiceUnavailable,
|
||||
},
|
||||
|
||||
OwnershipControlsNotFoundError: {
|
||||
Code: "OwnershipControlsNotFoundError",
|
||||
|
||||
@@ -147,6 +147,7 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
|
||||
Namespace: req.Namespace,
|
||||
CreatedAt: now,
|
||||
OwnerAccountID: bucketMetadata.OwnerAccountID,
|
||||
Properties: req.Properties,
|
||||
}
|
||||
|
||||
metadataBytes, err := json.Marshal(metadata)
|
||||
@@ -177,6 +178,7 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
|
||||
resp := &CreateNamespaceResponse{
|
||||
Namespace: req.Namespace,
|
||||
TableBucketARN: req.TableBucketARN,
|
||||
Properties: req.Properties,
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusOK, resp)
|
||||
@@ -265,6 +267,7 @@ func (h *S3TablesHandler) handleGetNamespace(w http.ResponseWriter, r *http.Requ
|
||||
Namespace: metadata.Namespace,
|
||||
CreatedAt: metadata.CreatedAt,
|
||||
OwnerAccountID: metadata.OwnerAccountID,
|
||||
Properties: metadata.Properties,
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusOK, resp)
|
||||
|
||||
@@ -408,7 +408,7 @@ func (h *S3TablesHandler) handleGetTable(w http.ResponseWriter, r *http.Request,
|
||||
resp := &GetTableResponse{
|
||||
Name: metadata.Name,
|
||||
TableARN: tableARN,
|
||||
Namespace: []string{metadata.Namespace},
|
||||
Namespace: expandNamespace(metadata.Namespace),
|
||||
Format: metadata.Format,
|
||||
CreatedAt: metadata.CreatedAt,
|
||||
ModifiedAt: metadata.ModifiedAt,
|
||||
@@ -683,7 +683,7 @@ func (h *S3TablesHandler) listTablesWithClient(r *http.Request, client filer_pb.
|
||||
tables = append(tables, TableSummary{
|
||||
Name: entry.Entry.Name,
|
||||
TableARN: tableARN,
|
||||
Namespace: []string{namespaceName},
|
||||
Namespace: expandNamespace(namespaceName),
|
||||
CreatedAt: metadata.CreatedAt,
|
||||
ModifiedAt: metadata.ModifiedAt,
|
||||
})
|
||||
@@ -929,7 +929,7 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
|
||||
if err := h.deleteDirectory(r.Context(), client, tablePath); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.deleteTableLocationMapping(r.Context(), client, metadata.MetadataLocation); err != nil {
|
||||
if err := h.deleteTableLocationMapping(r.Context(), client, metadata.MetadataLocation, tablePath); err != nil {
|
||||
glog.V(1).Infof("failed to delete table location mapping for %s: %v", metadata.MetadataLocation, err)
|
||||
}
|
||||
return nil
|
||||
@@ -1139,29 +1139,98 @@ func (h *S3TablesHandler) updateTableLocationMapping(ctx context.Context, client
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
tableBucketPath, ok := tableBucketPathFromTablePath(tablePath)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid table path for location mapping: %s", tablePath)
|
||||
}
|
||||
|
||||
if err := h.ensureDirectory(ctx, client, GetTableLocationMappingDir()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := h.ensureTableLocationMappingBucketDir(ctx, client, newTableLocationBucket); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// If the metadata location changed, delete the stale mapping for the old bucket
|
||||
// If the metadata location changed, remove this table's stale mapping entry from the old bucket.
|
||||
if oldMetadataLocation != "" && oldMetadataLocation != newMetadataLocation {
|
||||
oldTableLocationBucket, ok := parseTableLocationBucket(oldMetadataLocation)
|
||||
if ok && oldTableLocationBucket != newTableLocationBucket {
|
||||
oldMappingPath := GetTableLocationMappingPath(oldTableLocationBucket)
|
||||
if err := h.deleteEntryIfExists(ctx, client, oldMappingPath); err != nil {
|
||||
if err := h.removeTableLocationMappingEntry(ctx, client, oldTableLocationBucket, tablePath); err != nil {
|
||||
glog.V(1).Infof("failed to delete stale mapping for %s: %v", oldTableLocationBucket, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return h.upsertFile(ctx, client, GetTableLocationMappingPath(newTableLocationBucket), []byte(tablePath))
|
||||
return h.upsertFile(ctx, client, GetTableLocationMappingEntryPath(newTableLocationBucket, tablePath), []byte(tableBucketPath))
|
||||
}
|
||||
|
||||
func (h *S3TablesHandler) deleteTableLocationMapping(ctx context.Context, client filer_pb.SeaweedFilerClient, metadataLocation string) error {
|
||||
func (h *S3TablesHandler) deleteTableLocationMapping(ctx context.Context, client filer_pb.SeaweedFilerClient, metadataLocation, tablePath string) error {
|
||||
tableLocationBucket, ok := parseTableLocationBucket(metadataLocation)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return h.deleteEntryIfExists(ctx, client, GetTableLocationMappingPath(tableLocationBucket))
|
||||
return h.removeTableLocationMappingEntry(ctx, client, tableLocationBucket, tablePath)
|
||||
}
|
||||
|
||||
func (h *S3TablesHandler) ensureTableLocationMappingBucketDir(ctx context.Context, client filer_pb.SeaweedFilerClient, tableLocationBucket string) error {
|
||||
mappingDir := GetTableLocationMappingDir()
|
||||
bucketMappingPath := GetTableLocationMappingPath(tableLocationBucket)
|
||||
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: mappingDir,
|
||||
Name: tableLocationBucket,
|
||||
})
|
||||
if err == nil {
|
||||
if resp != nil && resp.Entry != nil && resp.Entry.IsDirectory {
|
||||
return nil
|
||||
}
|
||||
if removeErr := h.deleteEntryIfExists(ctx, client, bucketMappingPath); removeErr != nil && !errors.Is(removeErr, filer_pb.ErrNotFound) {
|
||||
return removeErr
|
||||
}
|
||||
} else if !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
return h.ensureDirectory(ctx, client, bucketMappingPath)
|
||||
}
|
||||
|
||||
func (h *S3TablesHandler) removeTableLocationMappingEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, tableLocationBucket, tablePath string) error {
|
||||
entryPath := GetTableLocationMappingEntryPath(tableLocationBucket, tablePath)
|
||||
if err := h.deleteEntryIfExists(ctx, client, entryPath); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
return h.removeTableLocationMappingBucketDirIfEmpty(ctx, client, tableLocationBucket)
|
||||
}
|
||||
|
||||
func (h *S3TablesHandler) removeTableLocationMappingBucketDirIfEmpty(ctx context.Context, client filer_pb.SeaweedFilerClient, tableLocationBucket string) error {
|
||||
bucketMappingPath := GetTableLocationMappingPath(tableLocationBucket)
|
||||
|
||||
stream, err := client.ListEntries(ctx, &filer_pb.ListEntriesRequest{
|
||||
Directory: bucketMappingPath,
|
||||
Limit: 1,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr == io.EOF {
|
||||
break
|
||||
}
|
||||
if recvErr != nil {
|
||||
return recvErr
|
||||
}
|
||||
if resp != nil && resp.Entry != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.deleteEntryIfExists(ctx, client, bucketMappingPath); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetTableLocationMappingEntryPathPerTable(t *testing.T) {
|
||||
tableLocationBucket := "shared-location--table-s3"
|
||||
tablePathA := GetTablePath("warehouse", "analytics", "orders")
|
||||
tablePathB := GetTablePath("warehouse", "analytics", "customers")
|
||||
|
||||
entryPathA := GetTableLocationMappingEntryPath(tableLocationBucket, tablePathA)
|
||||
entryPathARepeat := GetTableLocationMappingEntryPath(tableLocationBucket, tablePathA)
|
||||
entryPathB := GetTableLocationMappingEntryPath(tableLocationBucket, tablePathB)
|
||||
|
||||
if entryPathA != entryPathARepeat {
|
||||
t.Fatalf("mapping entry path should be deterministic: %q != %q", entryPathA, entryPathARepeat)
|
||||
}
|
||||
if entryPathA == entryPathB {
|
||||
t.Fatalf("mapping entry path should differ per table path: %q == %q", entryPathA, entryPathB)
|
||||
}
|
||||
|
||||
expectedPrefix := GetTableLocationMappingPath(tableLocationBucket) + "/"
|
||||
if !strings.HasPrefix(entryPathA, expectedPrefix) {
|
||||
t.Fatalf("mapping entry path %q should start with %q", entryPathA, expectedPrefix)
|
||||
}
|
||||
if strings.TrimPrefix(entryPathA, expectedPrefix) == "" {
|
||||
t.Fatalf("mapping entry name should not be empty: %q", entryPathA)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableBucketPathFromTablePath(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
tablePath string
|
||||
expected string
|
||||
ok bool
|
||||
}{
|
||||
{
|
||||
name: "valid table path",
|
||||
tablePath: GetTablePath("warehouse", "analytics", "orders"),
|
||||
expected: GetTableBucketPath("warehouse"),
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "valid table bucket root",
|
||||
tablePath: GetTableBucketPath("warehouse"),
|
||||
expected: GetTableBucketPath("warehouse"),
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "invalid non-tables path",
|
||||
tablePath: "/tmp/warehouse/analytics/orders",
|
||||
expected: "",
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "invalid empty bucket segment",
|
||||
tablePath: "/buckets/",
|
||||
expected: "",
|
||||
ok: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
actual, ok := tableBucketPathFromTablePath(tc.tablePath)
|
||||
if ok != tc.ok {
|
||||
t.Fatalf("tableBucketPathFromTablePath(%q) ok=%v, want %v", tc.tablePath, ok, tc.ok)
|
||||
}
|
||||
if actual != tc.expected {
|
||||
t.Fatalf("tableBucketPathFromTablePath(%q)=%q, want %q", tc.tablePath, actual, tc.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -77,19 +77,22 @@ type DeleteTableBucketPolicyRequest struct {
|
||||
// Namespace types
|
||||
|
||||
type Namespace struct {
|
||||
Namespace []string `json:"namespace"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
Namespace []string `json:"namespace"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
Properties map[string]string `json:"properties,omitempty"`
|
||||
}
|
||||
|
||||
type CreateNamespaceRequest struct {
|
||||
TableBucketARN string `json:"tableBucketARN"`
|
||||
Namespace []string `json:"namespace"`
|
||||
TableBucketARN string `json:"tableBucketARN"`
|
||||
Namespace []string `json:"namespace"`
|
||||
Properties map[string]string `json:"properties,omitempty"`
|
||||
}
|
||||
|
||||
type CreateNamespaceResponse struct {
|
||||
Namespace []string `json:"namespace"`
|
||||
TableBucketARN string `json:"tableBucketARN"`
|
||||
Namespace []string `json:"namespace"`
|
||||
TableBucketARN string `json:"tableBucketARN"`
|
||||
Properties map[string]string `json:"properties,omitempty"`
|
||||
}
|
||||
|
||||
type GetNamespaceRequest struct {
|
||||
@@ -98,9 +101,10 @@ type GetNamespaceRequest struct {
|
||||
}
|
||||
|
||||
type GetNamespaceResponse struct {
|
||||
Namespace []string `json:"namespace"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
Namespace []string `json:"namespace"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
Properties map[string]string `json:"properties,omitempty"`
|
||||
}
|
||||
|
||||
type ListNamespacesRequest struct {
|
||||
|
||||
@@ -2,6 +2,7 @@ package s3tables
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/url"
|
||||
@@ -15,7 +16,7 @@ import (
|
||||
|
||||
const (
|
||||
bucketNamePatternStr = `[a-z0-9-]+`
|
||||
tableNamespacePatternStr = `[a-z0-9_]+`
|
||||
tableNamespacePatternStr = `[a-z0-9_.]+`
|
||||
tableNamePatternStr = `[a-z0-9_]+`
|
||||
)
|
||||
|
||||
@@ -54,7 +55,6 @@ func ParseBucketNameFromARN(arn string) (string, error) {
|
||||
// parseTableFromARN extracts bucket name, namespace, and table name from ARN
|
||||
// ARN format: arn:aws:s3tables:{region}:{account}:bucket/{bucket-name}/table/{namespace}/{table-name}
|
||||
func parseTableFromARN(arn string) (bucketName, namespace, tableName string, err error) {
|
||||
// Updated regex to align with namespace validation (single-segment)
|
||||
matches := tableARNPattern.FindStringSubmatch(arn)
|
||||
if len(matches) != 4 {
|
||||
return "", "", "", fmt.Errorf("invalid table ARN: %s", arn)
|
||||
@@ -66,9 +66,7 @@ func parseTableFromARN(arn string) (bucketName, namespace, tableName string, err
|
||||
return "", "", "", fmt.Errorf("invalid bucket name in ARN: %v", err)
|
||||
}
|
||||
|
||||
// Namespace is already constrained by the regex; validate it directly.
|
||||
namespace = matches[2]
|
||||
_, err = validateNamespace([]string{namespace})
|
||||
namespace, err = validateNamespace([]string{matches[2]})
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("invalid namespace in ARN: %v", err)
|
||||
}
|
||||
@@ -121,6 +119,33 @@ func GetTableLocationMappingPath(tableLocationBucket string) string {
|
||||
return path.Join(GetTableLocationMappingDir(), tableLocationBucket)
|
||||
}
|
||||
|
||||
// GetTableLocationMappingEntryPath returns the filer path for a table-specific mapping entry.
|
||||
// Each table gets its own entry so multiple tables can share the same external table-location bucket.
|
||||
func GetTableLocationMappingEntryPath(tableLocationBucket, tablePath string) string {
|
||||
return path.Join(GetTableLocationMappingPath(tableLocationBucket), tableLocationMappingEntryName(tablePath))
|
||||
}
|
||||
|
||||
func tableLocationMappingEntryName(tablePath string) string {
|
||||
normalized := path.Clean("/" + strings.TrimSpace(strings.TrimPrefix(tablePath, "/")))
|
||||
sum := sha1.Sum([]byte(normalized))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func tableBucketPathFromTablePath(tablePath string) (string, bool) {
|
||||
normalized := path.Clean("/" + strings.TrimSpace(strings.TrimPrefix(tablePath, "/")))
|
||||
tablesPrefix := strings.TrimSuffix(TablesPath, "/") + "/"
|
||||
if !strings.HasPrefix(normalized, tablesPrefix) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
remaining := strings.TrimPrefix(normalized, tablesPrefix)
|
||||
bucketName, _, _ := strings.Cut(remaining, "/")
|
||||
if bucketName == "" {
|
||||
return "", false
|
||||
}
|
||||
return path.Join(TablesPath, bucketName), true
|
||||
}
|
||||
|
||||
// Metadata structures
|
||||
|
||||
type tableBucketMetadata struct {
|
||||
@@ -131,9 +156,10 @@ type tableBucketMetadata struct {
|
||||
|
||||
// namespaceMetadata stores metadata for a namespace
|
||||
type namespaceMetadata struct {
|
||||
Namespace []string `json:"namespace"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
Namespace []string `json:"namespace"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
Properties map[string]string `json:"properties,omitempty"`
|
||||
}
|
||||
|
||||
// tableMetadataInternal stores metadata for a table
|
||||
@@ -326,35 +352,27 @@ func splitPath(p string) (dir, name string) {
|
||||
return
|
||||
}
|
||||
|
||||
// validateNamespace validates that the namespace provided is supported (single-level)
|
||||
func validateNamespace(namespace []string) (string, error) {
|
||||
if len(namespace) == 0 {
|
||||
return "", fmt.Errorf("namespace is required")
|
||||
}
|
||||
if len(namespace) > 1 {
|
||||
return "", fmt.Errorf("multi-level namespaces are not supported")
|
||||
}
|
||||
name := namespace[0]
|
||||
func validateNamespacePart(name string) error {
|
||||
if len(name) < 1 || len(name) > 255 {
|
||||
return "", fmt.Errorf("namespace name must be between 1 and 255 characters")
|
||||
return fmt.Errorf("namespace name must be between 1 and 255 characters")
|
||||
}
|
||||
|
||||
// Prevent path traversal and multi-segment paths
|
||||
if name == "." || name == ".." {
|
||||
return "", fmt.Errorf("namespace name cannot be '.' or '..'")
|
||||
return fmt.Errorf("namespace name cannot be '.' or '..'")
|
||||
}
|
||||
if strings.Contains(name, "/") {
|
||||
return "", fmt.Errorf("namespace name cannot contain '/'")
|
||||
return fmt.Errorf("namespace name cannot contain '/'")
|
||||
}
|
||||
|
||||
// Must start and end with a letter or digit
|
||||
start := name[0]
|
||||
end := name[len(name)-1]
|
||||
if !((start >= 'a' && start <= 'z') || (start >= '0' && start <= '9')) {
|
||||
return "", fmt.Errorf("namespace name must start with a letter or digit")
|
||||
return fmt.Errorf("namespace name must start with a letter or digit")
|
||||
}
|
||||
if !((end >= 'a' && end <= 'z') || (end >= '0' && end <= '9')) {
|
||||
return "", fmt.Errorf("namespace name must end with a letter or digit")
|
||||
return fmt.Errorf("namespace name must end with a letter or digit")
|
||||
}
|
||||
|
||||
// Allowed characters: a-z, 0-9, _
|
||||
@@ -362,15 +380,46 @@ func validateNamespace(namespace []string) (string, error) {
|
||||
if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' {
|
||||
continue
|
||||
}
|
||||
return "", fmt.Errorf("invalid namespace name: only 'a-z', '0-9', and '_' are allowed")
|
||||
return fmt.Errorf("invalid namespace name: only 'a-z', '0-9', and '_' are allowed")
|
||||
}
|
||||
|
||||
// Reserved prefix
|
||||
if strings.HasPrefix(name, "aws") {
|
||||
return "", fmt.Errorf("namespace name cannot start with reserved prefix 'aws'")
|
||||
return fmt.Errorf("namespace name cannot start with reserved prefix 'aws'")
|
||||
}
|
||||
|
||||
return name, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeNamespace(namespace []string) ([]string, error) {
|
||||
if len(namespace) == 0 {
|
||||
return nil, fmt.Errorf("namespace is required")
|
||||
}
|
||||
|
||||
parts := namespace
|
||||
if len(namespace) == 1 {
|
||||
parts = strings.Split(namespace[0], ".")
|
||||
}
|
||||
|
||||
normalized := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if err := validateNamespacePart(part); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalized = append(normalized, part)
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
// validateNamespace validates namespace identifiers and returns an internal namespace key.
|
||||
// A single dotted namespace value is interpreted as multi-level namespace for compatibility
|
||||
// with path-style APIs, for example "analytics.daily" => ["analytics", "daily"].
|
||||
func validateNamespace(namespace []string) (string, error) {
|
||||
parts, err := normalizeNamespace(namespace)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return flattenNamespace(parts), nil
|
||||
}
|
||||
|
||||
// ValidateNamespace is a wrapper to validate namespace for other packages.
|
||||
@@ -378,6 +427,11 @@ func ValidateNamespace(namespace []string) (string, error) {
|
||||
return validateNamespace(namespace)
|
||||
}
|
||||
|
||||
// ParseNamespace parses a namespace string into namespace parts.
|
||||
func ParseNamespace(namespace string) ([]string, error) {
|
||||
return normalizeNamespace([]string{namespace})
|
||||
}
|
||||
|
||||
// validateTableName validates a table name
|
||||
func validateTableName(name string) (string, error) {
|
||||
if len(name) < 1 || len(name) > 255 {
|
||||
@@ -415,3 +469,14 @@ func flattenNamespace(namespace []string) string {
|
||||
}
|
||||
return strings.Join(namespace, ".")
|
||||
}
|
||||
|
||||
func expandNamespace(namespace string) []string {
|
||||
if namespace == "" {
|
||||
return nil
|
||||
}
|
||||
parts, err := ParseNamespace(namespace)
|
||||
if err != nil {
|
||||
return []string{namespace}
|
||||
}
|
||||
return parts
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateNamespaceSupportsMultiLevel(t *testing.T) {
|
||||
got, err := validateNamespace([]string{"analytics", "daily"})
|
||||
if err != nil {
|
||||
t.Fatalf("validateNamespace returned error: %v", err)
|
||||
}
|
||||
if got != "analytics.daily" {
|
||||
t.Fatalf("validateNamespace = %q, want %q", got, "analytics.daily")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateNamespaceSupportsDottedInput(t *testing.T) {
|
||||
got, err := validateNamespace([]string{"analytics.daily"})
|
||||
if err != nil {
|
||||
t.Fatalf("validateNamespace returned error: %v", err)
|
||||
}
|
||||
if got != "analytics.daily" {
|
||||
t.Fatalf("validateNamespace = %q, want %q", got, "analytics.daily")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateNamespaceRejectsEmptyDottedSegment(t *testing.T) {
|
||||
_, err := validateNamespace([]string{"analytics..daily"})
|
||||
if err == nil {
|
||||
t.Fatalf("expected validateNamespace to fail for empty dotted segment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseNamespace(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
namespace string
|
||||
want []string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "single level",
|
||||
namespace: "analytics",
|
||||
want: []string{"analytics"},
|
||||
},
|
||||
{
|
||||
name: "multi level dotted",
|
||||
namespace: "analytics.daily",
|
||||
want: []string{"analytics", "daily"},
|
||||
},
|
||||
{
|
||||
name: "invalid reserved prefix",
|
||||
namespace: "analytics.awsprod",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "invalid empty segment",
|
||||
namespace: "analytics..daily",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseNamespace(tt.namespace)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("ParseNamespace(%q) expected error", tt.namespace)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ParseNamespace(%q) unexpected error: %v", tt.namespace, err)
|
||||
}
|
||||
if len(got) != len(tt.want) {
|
||||
t.Fatalf("ParseNamespace(%q) = %v, want %v", tt.namespace, got, tt.want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Fatalf("ParseNamespace(%q) = %v, want %v", tt.namespace, got, tt.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTableFromARNWithMultiLevelNamespace(t *testing.T) {
|
||||
arn := "arn:aws:s3tables:us-east-1:123456789012:bucket/testbucket/table/analytics.daily/events"
|
||||
bucket, namespace, table, err := parseTableFromARN(arn)
|
||||
if err != nil {
|
||||
t.Fatalf("parseTableFromARN returned error: %v", err)
|
||||
}
|
||||
if bucket != "testbucket" {
|
||||
t.Fatalf("bucket = %q, want %q", bucket, "testbucket")
|
||||
}
|
||||
if namespace != "analytics.daily" {
|
||||
t.Fatalf("namespace = %q, want %q", namespace, "analytics.daily")
|
||||
}
|
||||
if table != "events" {
|
||||
t.Fatalf("table = %q, want %q", table, "events")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTableARNWithDottedNamespace(t *testing.T) {
|
||||
arn, err := BuildTableARN("us-east-1", "123456789012", "testbucket", "analytics.daily", "events")
|
||||
if err != nil {
|
||||
t.Fatalf("BuildTableARN returned error: %v", err)
|
||||
}
|
||||
if !strings.Contains(arn, "/table/analytics.daily/events") {
|
||||
t.Fatalf("BuildTableARN returned %q, missing normalized namespace/table path", arn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandNamespace(t *testing.T) {
|
||||
got := expandNamespace("analytics.daily")
|
||||
want := []string{"analytics", "daily"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("expandNamespace = %v, want %v", got, want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("expandNamespace = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNamespaceMetadataPropertiesRoundTrip(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
metadata namespaceMetadata
|
||||
}{
|
||||
{
|
||||
name: "with properties",
|
||||
metadata: namespaceMetadata{
|
||||
Namespace: []string{"analytics"},
|
||||
Properties: map[string]string{"owner": "finance"},
|
||||
OwnerAccountID: "123456789012",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "nil properties",
|
||||
metadata: namespaceMetadata{
|
||||
Namespace: []string{"analytics"},
|
||||
Properties: nil,
|
||||
OwnerAccountID: "123456789012",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "empty properties",
|
||||
metadata: namespaceMetadata{
|
||||
Namespace: []string{"analytics"},
|
||||
Properties: map[string]string{},
|
||||
OwnerAccountID: "123456789012",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
data, err := json.Marshal(tc.metadata)
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(metadata) returned error: %v", err)
|
||||
}
|
||||
|
||||
var decoded namespaceMetadata
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("json.Unmarshal(data) returned error: %v", err)
|
||||
}
|
||||
|
||||
// Due to `omitempty`, nil and empty maps are unmarshaled as nil.
|
||||
if len(tc.metadata.Properties) == 0 {
|
||||
if decoded.Properties != nil {
|
||||
t.Fatalf("expected nil properties for empty/nil input, got %v", decoded.Properties)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(decoded.Properties, tc.metadata.Properties) {
|
||||
t.Fatalf("decoded.Properties = %v, want %v", decoded.Properties, tc.metadata.Properties)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Minimal mock implementation of AuthenticateJWT needed for testing
|
||||
type mockIAMIntegration struct{}
|
||||
|
||||
func (m *mockIAMIntegration) AuthenticateJWT(ctx context.Context, r *http.Request) (*IAMIdentity, s3err.ErrorCode) {
|
||||
return &IAMIdentity{
|
||||
Name: "test-user",
|
||||
Account: &Account{
|
||||
Id: "test-account",
|
||||
DisplayName: "test-account",
|
||||
EmailAddress: "test@example.com",
|
||||
},
|
||||
Principal: "arn:aws:iam::test-account:user/test-user",
|
||||
SessionToken: "mock-session-token",
|
||||
}, s3err.ErrNone
|
||||
}
|
||||
func (m *mockIAMIntegration) AuthorizeAction(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
func (m *mockIAMIntegration) ValidateTrustPolicyForPrincipal(ctx context.Context, roleArn, principalArn string) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockIAMIntegration) ValidateSessionToken(ctx context.Context, token string) (*sts.SessionInfo, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestSTSAssumeRolePostBody(t *testing.T) {
|
||||
// Setup S3ApiServer with IAM enabled
|
||||
option := &S3ApiServerOption{
|
||||
DomainName: "localhost",
|
||||
EnableIam: true,
|
||||
Filers: []pb.ServerAddress{"localhost:8888"},
|
||||
}
|
||||
|
||||
// Create IAM instance that we can control
|
||||
// We need to bypass the file/store loading logic in NewIdentityAccessManagement
|
||||
// So we construct it manually similarly to how it's done for tests
|
||||
iam := &IdentityAccessManagement{
|
||||
identities: []*Identity{{Name: "test-user"}},
|
||||
isAuthEnabled: true,
|
||||
accessKeyIdent: make(map[string]*Identity),
|
||||
nameToIdentity: make(map[string]*Identity),
|
||||
iamIntegration: &mockIAMIntegration{},
|
||||
}
|
||||
|
||||
// Pre-populate an identity for testing
|
||||
ident := &Identity{
|
||||
Name: "test-user",
|
||||
Credentials: []*Credential{
|
||||
{AccessKey: "test", SecretKey: "test", Status: "Active"},
|
||||
},
|
||||
Actions: nil, // Admin
|
||||
IsStatic: true,
|
||||
}
|
||||
iam.identities[0] = ident
|
||||
iam.accessKeyIdent["test"] = ident
|
||||
iam.nameToIdentity["test-user"] = ident
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: option,
|
||||
iam: iam,
|
||||
embeddedIam: &EmbeddedIamApi{iam: iam, getS3ApiConfigurationFunc: func(cfg *iam_pb.S3ApiConfiguration) error { return nil }},
|
||||
stsHandlers: NewSTSHandlers(nil, iam), // STS service nil -> will return STSErrSTSNotReady (503)
|
||||
credentialManager: nil, // Not needed for this test as we pre-populated IAM
|
||||
cb: &CircuitBreaker{
|
||||
counters: make(map[string]*int64),
|
||||
limitations: make(map[string]int64),
|
||||
},
|
||||
}
|
||||
s3a.cb.s3a = s3a
|
||||
s3a.inFlightDataLimitCond = sync.NewCond(&sync.Mutex{})
|
||||
|
||||
// Create router and register routes
|
||||
router := mux.NewRouter()
|
||||
s3a.registerRouter(router)
|
||||
|
||||
// Test Case 1: STS Action in Query String (Should work - routed to STS)
|
||||
t.Run("ActionInQuery", func(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "/?Action=AssumeRole", nil)
|
||||
// We aren't signing requests, so we expect STSErrAccessDenied (403) from STS handler
|
||||
// due to invalid signature, OR STSErrSTSNotReady (503) if it gets past auth.
|
||||
// The key is it should NOT be 501 Not Implemented (which comes from IAM handler)
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
// If routed to STS, we expect 400 (Bad Request) - MissingParameter
|
||||
// because we didn't provide RoleArn/RoleSessionName etc.
|
||||
// Or 503 if it checks STS service readiness first.
|
||||
|
||||
// Let's see what we get. The STS handler checks parameters first.
|
||||
// "RoleArn is required" -> 400 Bad Request
|
||||
|
||||
assert.NotEqual(t, http.StatusNotImplemented, rr.Code, "Should not return 501 (IAM handler)")
|
||||
assert.Equal(t, http.StatusBadRequest, rr.Code, "Should return 400 (STS handler) for missing params")
|
||||
})
|
||||
|
||||
// Test Case 2: STS Action in Body (Should FAIL current implementation - routed to IAM)
|
||||
t.Run("ActionInBody", func(t *testing.T) {
|
||||
form := url.Values{}
|
||||
form.Add("Action", "AssumeRole")
|
||||
form.Add("RoleArn", "arn:aws:iam::123:role/test")
|
||||
form.Add("RoleSessionName", "session")
|
||||
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
// We need an Authorization header to trigger the IAM matcher
|
||||
// The matcher checks: getRequestAuthType(r) != authTypeAnonymous
|
||||
// So we provide a dummy auth header
|
||||
|
||||
req.Header.Set("Authorization", "Bearer test-token")
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
// CURRENT BEHAVIOR:
|
||||
// The Router does not match "/" for STS because Action is not in query.
|
||||
// The Router matches "/" for IAM because it has Authorization header.
|
||||
// IAM handler (AuthIam) calls DoActions.
|
||||
// DoActions switches on "AssumeRole" -> default -> Not Implemented (501).
|
||||
|
||||
// DESIRED BEHAVIOR (after fix):
|
||||
// Should be routed to UnifiedPostHandler (or similar), detected as STS action,
|
||||
// and routed to STS handler.
|
||||
// STS handler should return 403 Forbidden (Access Denied) or 400 Bad Request
|
||||
// because of signature mismatch (since we provided dummy auth).
|
||||
// It should NOT be 501.
|
||||
|
||||
// For verification of fix, we assert it IS 503 (STS Service Not Initialized).
|
||||
// This confirms it was routed to STS handler.
|
||||
if rr.Code != http.StatusServiceUnavailable {
|
||||
t.Logf("Unexpected status code: %d", rr.Code)
|
||||
t.Logf("Response body: %s", rr.Body.String())
|
||||
}
|
||||
// Confirm it routed to STS
|
||||
assert.Equal(t, http.StatusServiceUnavailable, rr.Code, "Fixed behavior: Should return 503 from STS handler (service not ready)")
|
||||
})
|
||||
|
||||
// Test Case 3: STS Action in Body with SigV4-style Authorization (Real-world scenario)
|
||||
// This test validates that requests with AWS SigV4 Authorization headers and POST body
|
||||
// parameters are correctly routed to the STS handler.
|
||||
t.Run("ActionInBodyWithSigV4Style", func(t *testing.T) {
|
||||
form := url.Values{}
|
||||
form.Add("Action", "AssumeRole")
|
||||
form.Add("RoleArn", "arn:aws:iam::123:role/test")
|
||||
form.Add("RoleSessionName", "session")
|
||||
|
||||
bodyContent := form.Encode()
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(bodyContent))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// Set AWS SigV4-style Authorization header
|
||||
// This simulates a real SigV4-signed request without needing perfect signature
|
||||
// The key is to validate that UnifiedPostHandler correctly routes based on Action
|
||||
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260212/us-east-1/sts/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=dummy")
|
||||
req.Header.Set("x-amz-date", "20260212T000000Z")
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
// With SigV4-style Authorization header, the request should:
|
||||
// 1. Be recognized as authenticated (not anonymous)
|
||||
// 2. Be routed to UnifiedPostHandler
|
||||
// 3. UnifiedPostHandler should parse Action=AssumeRole from body
|
||||
// 4. Route to STS handler (which returns 503 because stsService is nil)
|
||||
// OR return 403 if signature validation fails (which is acceptable)
|
||||
|
||||
// The key validation is that it should NOT return 501 (IAM handler's "Not Implemented")
|
||||
// This confirms the routing fix works for SigV4-signed requests with POST body params
|
||||
|
||||
if rr.Code != http.StatusServiceUnavailable && rr.Code != http.StatusForbidden {
|
||||
t.Logf("Unexpected status code: %d", rr.Code)
|
||||
t.Logf("Response body: %s", rr.Body.String())
|
||||
}
|
||||
|
||||
// Accept either 503 (routed to STS, service unavailable) or 403 (signature failed)
|
||||
// Both indicate correct routing to STS handler, not IAM handler
|
||||
assert.NotEqual(t, http.StatusNotImplemented, rr.Code, "Should not return 501 (IAM handler)")
|
||||
assert.Contains(t, []int{http.StatusServiceUnavailable, http.StatusForbidden}, rr.Code,
|
||||
"Should return 503 (STS unavailable) or 403 (auth failed), confirming STS routing")
|
||||
})
|
||||
}
|
||||
@@ -54,4 +54,3 @@ func TestCheckEcVolumeStatusCountOnlyDataShards(t *testing.T) {
|
||||
t.Fatalf("expected shardCount=3, got %d", shardCount)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,9 +99,9 @@ func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb
|
||||
switch m := req.GetMode(); m {
|
||||
case volume_server_pb.VolumeScrubMode_INDEX:
|
||||
// index scrubs do not verify individual EC shards
|
||||
files, serrs = v.CheckIndex()
|
||||
files, serrs = v.ScrubIndex()
|
||||
case volume_server_pb.VolumeScrubMode_LOCAL:
|
||||
files, shardInfos, serrs = scrubEcVolumeLocal(ctx, v)
|
||||
files, shardInfos, serrs = v.ScrubLocal()
|
||||
case volume_server_pb.VolumeScrubMode_FULL:
|
||||
files, shardInfos, serrs = scrubEcVolumeFull(ctx, v)
|
||||
default:
|
||||
@@ -129,10 +129,6 @@ func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func scrubEcVolumeLocal(ctx context.Context, v *erasure_coding.EcVolume) (int64, []*volume_server_pb.EcShardInfo, []error) {
|
||||
return 0, nil, []error{fmt.Errorf("scrubEcVolumeLocal(): not implemented, see https://github.com/seaweedfs/seaweedfs/issues/8018")}
|
||||
}
|
||||
|
||||
func scrubEcVolumeFull(ctx context.Context, v *erasure_coding.EcVolume) (int64, []*volume_server_pb.EcShardInfo, []error) {
|
||||
return 0, nil, []error{fmt.Errorf("scrubEcVolumeFull(): not implemented, see https://github.com/seaweedfs/seaweedfs/issues/8018")}
|
||||
}
|
||||
@@ -214,13 +214,13 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
sp.regularVolumesStats = RegularVolumesStats{}
|
||||
sp.ecVolumesStats = EcVolumesStats{}
|
||||
|
||||
var mu sync.Mutex
|
||||
var statsMu, writerMu sync.Mutex
|
||||
var progressTotal, progressDone uint64
|
||||
ewg := NewErrorWaitGroup(sp.maxParallelization)
|
||||
|
||||
updateProgress := func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
writerMu.Lock()
|
||||
defer writerMu.Unlock()
|
||||
|
||||
progressDone++
|
||||
sp.write("collecting file stats: %s \r", sp.uint64Pct(progressDone, progressTotal))
|
||||
@@ -230,13 +230,15 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
for _, ri := range dci.RackInfos {
|
||||
for _, dni := range ri.DataNodeInfos {
|
||||
for _, d := range dni.DiskInfos {
|
||||
mu.Lock()
|
||||
statsMu.Lock()
|
||||
progressTotal += uint64(len(d.VolumeInfos))
|
||||
progressTotal += uint64(len(d.EcShardInfos))
|
||||
mu.Unlock()
|
||||
statsMu.Unlock()
|
||||
|
||||
for _, v := range d.VolumeInfos {
|
||||
ewg.Add(func() error {
|
||||
defer updateProgress()
|
||||
|
||||
// Collect regular volume stats
|
||||
err := operation.WithVolumeServerClient(false, pb.NewServerAddressWithGrpcPort(dni.Id, int(dni.GrpcPort)), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
resp, reqErr := volumeServerClient.VolumeStatus(context.Background(), &volume_server_pb.VolumeStatusRequest{
|
||||
@@ -246,8 +248,8 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return reqErr
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
statsMu.Lock()
|
||||
defer statsMu.Unlock()
|
||||
if resp != nil {
|
||||
if _, ok := sp.regularVolumesStats[v.Id]; !ok {
|
||||
sp.regularVolumesStats[v.Id] = []*VolumeReplicaStats{}
|
||||
@@ -263,26 +265,24 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
updateProgress()
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
for _, eci := range d.EcShardInfos {
|
||||
ewg.Add(func() error {
|
||||
defer updateProgress()
|
||||
|
||||
// Collect EC shard stats
|
||||
|
||||
var err error
|
||||
|
||||
mu.Lock()
|
||||
statsMu.Lock()
|
||||
_, ok := sp.ecVolumesStats[eci.Id]
|
||||
mu.Unlock()
|
||||
statsMu.Unlock()
|
||||
if ok {
|
||||
// this EC volume has been already processed, likely on a different node
|
||||
return nil
|
||||
}
|
||||
|
||||
err = operation.WithVolumeServerClient(false, pb.NewServerAddressWithGrpcPort(dni.Id, int(dni.GrpcPort)), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
err := operation.WithVolumeServerClient(false, pb.NewServerAddressWithGrpcPort(dni.Id, int(dni.GrpcPort)), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
resp, reqErr := volumeServerClient.VolumeEcShardsInfo(context.Background(), &volume_server_pb.VolumeEcShardsInfoRequest{
|
||||
VolumeId: uint32(eci.Id),
|
||||
})
|
||||
@@ -290,8 +290,8 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return reqErr
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
statsMu.Lock()
|
||||
defer statsMu.Unlock()
|
||||
if resp != nil {
|
||||
sp.ecVolumesStats[eci.Id] = &EcVolumeStats{
|
||||
VolumeId: eci.Id,
|
||||
@@ -303,7 +303,6 @@ func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
updateProgress()
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
@@ -49,8 +49,7 @@ func (c *commandEcVolumeScrub) Do(args []string, commandEnv *CommandEnv, writer
|
||||
volScrubCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
nodesStr := volScrubCommand.String("node", "", "comma-separated list of volume server <host>:<port> (optional)")
|
||||
volumeIDsStr := volScrubCommand.String("volumeId", "", "comma-separated EC volume IDs to process (optional)")
|
||||
// TODO: switch default mode to LOCAL, once implemented.
|
||||
mode := volScrubCommand.String("mode", "index", "scrubbing mode (index/local/full)")
|
||||
mode := volScrubCommand.String("mode", "local", "scrubbing mode (index/local/full)")
|
||||
maxParallelization := volScrubCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
|
||||
|
||||
if err = volScrubCommand.Parse(args); err != nil {
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
@@ -39,7 +40,8 @@ func init() {
|
||||
}
|
||||
|
||||
const (
|
||||
readbufferSize = 16
|
||||
readbufferSize = 16
|
||||
jwtFilerTokenExpirationSeconds = 300
|
||||
)
|
||||
|
||||
type commandVolumeFsck struct {
|
||||
@@ -53,6 +55,7 @@ type commandVolumeFsck struct {
|
||||
forcePurging *bool
|
||||
findMissingChunksInFiler *bool
|
||||
verifyNeedle *bool
|
||||
filerSigningKey string
|
||||
}
|
||||
|
||||
func (c *commandVolumeFsck) Name() string {
|
||||
@@ -139,6 +142,8 @@ func (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.
|
||||
}
|
||||
defer os.RemoveAll(c.tempFolder)
|
||||
|
||||
c.filerSigningKey = util.GetViper().GetString("jwt.filer_signing.key")
|
||||
|
||||
// collect all volume id locations
|
||||
dataNodeVolumeIdToVInfo, err := c.collectVolumeIds()
|
||||
if err != nil {
|
||||
@@ -556,6 +561,12 @@ func (c *commandVolumeFsck) httpDelete(path util.FullPath) {
|
||||
Host: c.env.option.FilerAddress.ToHttpAddress(),
|
||||
Path: string(path),
|
||||
}
|
||||
|
||||
if c.filerSigningKey != "" {
|
||||
encodedJwt := security.GenJwtForFilerServer(security.SigningKey(c.filerSigningKey), jwtFilerTokenExpirationSeconds)
|
||||
req.Header.Set("Authorization", "BEARER "+string(encodedJwt))
|
||||
}
|
||||
|
||||
if *c.verbose {
|
||||
fmt.Fprintf(c.writer, "full HTTP delete request to be sent: %v\n", req)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Commands = append(Commands, &commandVolumeServerState{})
|
||||
}
|
||||
|
||||
type commandVolumeServerState struct {
|
||||
env *CommandEnv
|
||||
writer io.Writer
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) Name() string {
|
||||
return "volumeServer.state"
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) Help() string {
|
||||
return `query/update volume server state settings
|
||||
|
||||
volumeServer.state [-nodes <host:port>] [..state flags...]
|
||||
|
||||
This command display volume server state flags for the provided
|
||||
list of nodes; if empty, all nodes in the topology are queried.
|
||||
For example:
|
||||
|
||||
volumeServer.state --nodes 192.168.10.111:9000,192.168.10.112:9000
|
||||
|
||||
Additionally, if any flags are provided, these are applied
|
||||
to the selected node(s). The command will display the resulting
|
||||
state for each node *after* the state is updated. For exmaple...
|
||||
|
||||
volumeServer.state --nodes 192.168.10.111:9000 --maintenanceOn
|
||||
|
||||
...will set the specified volume server to maintenance mode.
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) HasTag(CommandTag) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) write(format string, a ...any) {
|
||||
format = strings.TrimRight(format, " ")
|
||||
if len(format) == 0 {
|
||||
format = "\n"
|
||||
}
|
||||
fmt.Fprintf(c.writer, format, a...)
|
||||
|
||||
last := format[len(format)-1:]
|
||||
if last != "\n" && last != "\r" {
|
||||
fmt.Fprint(c.writer, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) bool2Str(b bool) string {
|
||||
if b {
|
||||
return "yes"
|
||||
}
|
||||
return "no"
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
|
||||
vsStateCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
nodesStr := vsStateCommand.String("nodes", "", "comma-separated list of volume servers <host>:<port> (optional)")
|
||||
maintenanceOn := vsStateCommand.Bool("maintenanceOn", false, "enables maintenance mode on the server")
|
||||
maintenanceOff := vsStateCommand.Bool("maintenanceOff", false, "disables maintenance mode on the server")
|
||||
if err = vsStateCommand.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if *maintenanceOn && *maintenanceOff {
|
||||
return fmt.Errorf("--maintenanceOn and --maintenanceOff are mutually exclusive")
|
||||
}
|
||||
|
||||
volumeServerAddrs := []pb.ServerAddress{}
|
||||
if *nodesStr != "" {
|
||||
for _, addr := range strings.Split(*nodesStr, ",") {
|
||||
volumeServerAddrs = append(volumeServerAddrs, pb.ServerAddress(addr))
|
||||
}
|
||||
} else {
|
||||
dns, err := collectDataNodes(commandEnv, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dn := range dns {
|
||||
volumeServerAddrs = append(volumeServerAddrs, pb.ServerAddress(dn.Address))
|
||||
}
|
||||
}
|
||||
slices.Sort(volumeServerAddrs)
|
||||
if len(volumeServerAddrs) == 0 {
|
||||
return fmt.Errorf("no volume servers specified")
|
||||
}
|
||||
|
||||
c.env = commandEnv
|
||||
c.writer = writer
|
||||
|
||||
for _, addr := range volumeServerAddrs {
|
||||
state, err := c.getVolumeServerState(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load state from %v: %v", addr, err)
|
||||
}
|
||||
|
||||
stateOrig := &volume_server_pb.VolumeServerState{}
|
||||
proto.Merge(stateOrig, state)
|
||||
|
||||
// apply updates, if any
|
||||
switch {
|
||||
case *maintenanceOn:
|
||||
state.Maintenance = true
|
||||
case *maintenanceOff:
|
||||
state.Maintenance = false
|
||||
}
|
||||
|
||||
// update volume server state if settings changed
|
||||
if !proto.Equal(state, stateOrig) {
|
||||
state, err = c.setVolumeServerState(addr, state)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update state for %v: %v", addr, err)
|
||||
}
|
||||
}
|
||||
|
||||
c.write("%v\t -> Maintenance mode: %s\n", addr.String(), c.bool2Str(state.GetMaintenance()))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) getVolumeServerState(volumeServerAddress pb.ServerAddress) (*volume_server_pb.VolumeServerState, error) {
|
||||
var state *volume_server_pb.VolumeServerState
|
||||
|
||||
err := operation.WithVolumeServerClient(false, volumeServerAddress, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
res, err := volumeServerClient.GetState(context.Background(), &volume_server_pb.GetStateRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
state = res.GetState()
|
||||
return nil
|
||||
})
|
||||
|
||||
return state, err
|
||||
}
|
||||
|
||||
func (c *commandVolumeServerState) setVolumeServerState(volumeServerAddress pb.ServerAddress, state *volume_server_pb.VolumeServerState) (*volume_server_pb.VolumeServerState, error) {
|
||||
var stateAfter *volume_server_pb.VolumeServerState
|
||||
|
||||
err := operation.WithVolumeServerClient(false, volumeServerAddress, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
res, err := volumeServerClient.SetState(context.Background(), &volume_server_pb.SetStateRequest{
|
||||
State: state,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stateAfter = res.GetState()
|
||||
return nil
|
||||
})
|
||||
|
||||
return stateAfter, err
|
||||
}
|
||||
@@ -339,14 +339,3 @@ func (ev *EcVolume) WalkIndex(processNeedleFn func(key types.NeedleId, offset ty
|
||||
}
|
||||
return idx.WalkIndexFile(ev.ecxFile, 0, processNeedleFn)
|
||||
}
|
||||
|
||||
func (ev *EcVolume) CheckIndex() (int64, []error) {
|
||||
if ev.ecxFile == nil {
|
||||
return 0, []error{fmt.Errorf("no ECX file associated with EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
if ev.ecxFileSize == 0 {
|
||||
return 0, []error{fmt.Errorf("zero-size ECX file for EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
|
||||
return idx.CheckIndexFile(ev.ecxFile, ev.ecxFileSize, ev.Version)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// ScrubIndex verifies index integrity of an EC volume.
|
||||
func (ev *EcVolume) ScrubIndex() (int64, []error) {
|
||||
if ev.ecxFile == nil {
|
||||
return 0, []error{fmt.Errorf("no ECX file associated with EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
if ev.ecxFileSize == 0 {
|
||||
return 0, []error{fmt.Errorf("zero-size ECX file for EC volume %v", ev.VolumeId)}
|
||||
}
|
||||
|
||||
return idx.CheckIndexFile(ev.ecxFile, ev.ecxFileSize, ev.Version)
|
||||
}
|
||||
|
||||
// ScrubLocal checks the integrity of local shards for a EC volume. Notably, it cannot verify CRC on needles.
|
||||
// Returns a count of processed file entries, slice of found broken shards, and slice of found errors.
|
||||
func (ecv *EcVolume) ScrubLocal() (int64, []*volume_server_pb.EcShardInfo, []error) {
|
||||
// local scan means verifying indexes as well
|
||||
_, errs := ecv.ScrubIndex()
|
||||
|
||||
brokenShardsMap := map[ShardId]*EcVolumeShard{}
|
||||
var count int64
|
||||
|
||||
flagShardBroken := func(ecs *EcVolumeShard, errFmt string, a ...any) {
|
||||
// reads for EC chunks can hit the same shard multiple times, so dedupe upon read errors
|
||||
brokenShardsMap[ecs.ShardId] = ecs
|
||||
errs = append(errs, fmt.Errorf(errFmt, a...))
|
||||
}
|
||||
|
||||
err := idx.WalkIndexFile(ecv.ecxFile, 0, func(id types.NeedleId, offset types.Offset, size types.Size) error {
|
||||
count++
|
||||
if size.IsTombstone() {
|
||||
// nothing to do for tombstones...
|
||||
return nil
|
||||
}
|
||||
|
||||
var read int64
|
||||
locations := ecv.LocateEcShardNeedleInterval(ecv.Version, offset.ToActualOffset(), size)
|
||||
|
||||
for i, iv := range locations {
|
||||
sid, soffset := iv.ToShardIdAndOffset(ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize)
|
||||
ssize := int64(iv.Size.Raw())
|
||||
shard, found := ecv.FindEcVolumeShard(sid)
|
||||
if !found {
|
||||
// shard is not local :( skip it
|
||||
read += ssize
|
||||
continue
|
||||
}
|
||||
if soffset+int64(ssize) > shard.Size() {
|
||||
flagShardBroken(shard, "local shard %d for needle %d is too short (%d), cannot read chunk %d/%d", sid, id, shard.Size(), i+1, len(locations))
|
||||
continue
|
||||
}
|
||||
|
||||
buf := make([]byte, ssize)
|
||||
got, err := shard.ReadAt(buf, soffset)
|
||||
if err != nil {
|
||||
flagShardBroken(shard, "failed to read chunk %d/%d for needle %d from local shard %d at offset %d: %v", i+1, len(locations), id, sid, soffset, err)
|
||||
continue
|
||||
}
|
||||
if int64(got) != ssize {
|
||||
flagShardBroken(shard, "expected %d bytes for chunk %d/%d for needle %d from local shard %d, got %d", ssize, i+1, len(locations), id, sid, got)
|
||||
continue
|
||||
}
|
||||
read += int64(got)
|
||||
}
|
||||
|
||||
if got, want := read, needle.GetActualSize(size, ecv.Version); got != want {
|
||||
return fmt.Errorf("expected %d bytes for needle %d, got %d", want, id, got)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
// collect broken shard infos for reporting
|
||||
brokenShards := make([]*volume_server_pb.EcShardInfo, 0, len(brokenShardsMap))
|
||||
for _, s := range brokenShardsMap {
|
||||
brokenShards = append(brokenShards, s.ToEcShardInfo())
|
||||
}
|
||||
slices.SortFunc(brokenShards, func(a, b *volume_server_pb.EcShardInfo) int {
|
||||
if a.ShardId < b.ShardId {
|
||||
return -1
|
||||
}
|
||||
if a.ShardId > b.ShardId {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
return count, brokenShards, errs
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
func TestPositioning(t *testing.T) {
|
||||
|
||||
ecxFile, err := os.OpenFile("../idx/test_files/389.ecx", os.O_RDONLY, 0)
|
||||
ecxFile, err := os.OpenFile("./test_files/389.ecx", os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
t.Errorf("failed to open ecx file: %v", err)
|
||||
}
|
||||
|
||||
File renamed without changes.
@@ -50,13 +50,6 @@ func TestCheckIndexFile(t *testing.T) {
|
||||
fmt.Errorf("expected an index file of size 2540, got 2528"),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "healthy EC index",
|
||||
indexPath: "./test_files/389.ecx",
|
||||
version: needle.Version3,
|
||||
want: 485098,
|
||||
wantErrs: []error{},
|
||||
},
|
||||
{
|
||||
name: "healthy EC index with deleted files",
|
||||
indexPath: "./test_files/deleted_files.ecx",
|
||||
|
||||
@@ -132,15 +132,17 @@ func generateLevelDbFile(dbFileName string, indexFile *os.File) error {
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) Get(key NeedleId) (element *needle_map.NeedleValue, ok bool) {
|
||||
bytes := make([]byte, NeedleIdSize)
|
||||
if m.ldbTimeout > 0 {
|
||||
m.ldbAccessLock.RLock()
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
loadErr := reloadLdb(m)
|
||||
if loadErr != nil {
|
||||
if err := m.ensureLdbLoaded(); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
}
|
||||
return m.getFromDb(key)
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) getFromDb(key NeedleId) (element *needle_map.NeedleValue, ok bool) {
|
||||
bytes := make([]byte, NeedleIdSize)
|
||||
NeedleIdToBytes(bytes[0:NeedleIdSize], key)
|
||||
data, err := m.db.Get(bytes, nil)
|
||||
if err != nil || len(data) != OffsetSize+SizeSize {
|
||||
@@ -155,14 +157,12 @@ func (m *LevelDbNeedleMap) Put(key NeedleId, offset Offset, size Size) error {
|
||||
var oldSize Size
|
||||
var watermark uint64
|
||||
if m.ldbTimeout > 0 {
|
||||
m.ldbAccessLock.RLock()
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
loadErr := reloadLdb(m)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
if err := m.ensureLdbLoaded(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
}
|
||||
if oldNeedle, ok := m.Get(key); ok {
|
||||
if oldNeedle, ok := m.getFromDb(key); ok {
|
||||
oldSize = oldNeedle.Size
|
||||
}
|
||||
m.logPut(key, oldSize, size)
|
||||
@@ -222,14 +222,12 @@ func levelDbDelete(db *leveldb.DB, key NeedleId) error {
|
||||
func (m *LevelDbNeedleMap) Delete(key NeedleId, offset Offset) error {
|
||||
var watermark uint64
|
||||
if m.ldbTimeout > 0 {
|
||||
m.ldbAccessLock.RLock()
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
loadErr := reloadLdb(m)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
if err := m.ensureLdbLoaded(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.ldbAccessLock.RUnlock()
|
||||
}
|
||||
oldNeedle, found := m.Get(key)
|
||||
oldNeedle, found := m.getFromDb(key)
|
||||
if !found || oldNeedle.Size.IsDeleted() {
|
||||
return nil
|
||||
}
|
||||
@@ -400,6 +398,24 @@ func (m *LevelDbNeedleMap) DoOffsetLoading(v *Volume, indexFile *os.File, startF
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) ensureLdbLoaded() error {
|
||||
for {
|
||||
m.ldbAccessLock.RLock()
|
||||
if m.db != nil {
|
||||
return nil
|
||||
}
|
||||
m.ldbAccessLock.RUnlock()
|
||||
m.ldbAccessLock.Lock()
|
||||
if m.db == nil {
|
||||
if err := reloadLdb(m); err != nil {
|
||||
m.ldbAccessLock.Unlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
m.ldbAccessLock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func reloadLdb(m *LevelDbNeedleMap) (err error) {
|
||||
if m.db != nil {
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func TestLevelDbNeedleMap_Concurrency(t *testing.T) {
|
||||
dir, err := os.MkdirTemp("", "test_leveldb_concurrency")
|
||||
if err != nil {
|
||||
t.Fatalf("temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
prefix := "test"
|
||||
indexFile, err := os.Create(filepath.Join(dir, prefix+".idx"))
|
||||
if err != nil {
|
||||
t.Fatalf("create index file: %v", err)
|
||||
}
|
||||
dbFileName := filepath.Join(dir, prefix+".ldb")
|
||||
|
||||
// Create and initialize map
|
||||
m, err := NewLevelDbNeedleMap(dbFileName, indexFile, nil, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLevelDbNeedleMap: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
// Pre-populate some data
|
||||
key := types.NeedleId(1)
|
||||
if err := m.Put(key, types.ToOffset(100), types.Size(200)); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
// Force unload to start from nil state
|
||||
if err := unloadLdb(m); err != nil {
|
||||
t.Fatalf("unloadLdb: %v", err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
startCh := make(chan struct{})
|
||||
errCh := make(chan error, 100)
|
||||
|
||||
// Spawn multiple goroutines to trigger the race
|
||||
// Multiple readers will see m.db == nil and try to reload concurrently
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
<-startCh
|
||||
|
||||
// Try multiple times to increase chance of collision
|
||||
for j := 0; j < 2; j++ {
|
||||
_, ok := m.Get(key)
|
||||
if !ok {
|
||||
// Get failed, possibly due to race in reload.
|
||||
// But we also put data concurrently, so maybe it's missing if deleted?
|
||||
// In this test, we only Put, never Delete. So Key 1 should be there.
|
||||
// However, if DB reload fails, Get returns false!
|
||||
errCh <- fmt.Errorf("routine %d iter %d: Get returned false", id, j)
|
||||
}
|
||||
|
||||
// Also try Put concurrently
|
||||
err := m.Put(types.NeedleId(2+id), types.ToOffset(100), types.Size(200))
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("routine %d iter %d: Put failed: %v", id, j, err)
|
||||
}
|
||||
|
||||
// Manually unload occasionally to reset the state
|
||||
if j%2 == 0 {
|
||||
// This might fail if locked, but that's fine
|
||||
unloadLdb(m)
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
close(startCh)
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
|
||||
for e := range errCh {
|
||||
t.Errorf("Error encountered: %v", e)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,10 @@ type Offset struct {
|
||||
|
||||
type Size int32
|
||||
|
||||
func (s Size) IsTombstone() bool {
|
||||
return s == TombstoneFileSize
|
||||
}
|
||||
|
||||
// IsDeleted checks if the needle entry has been marked as deleted (tombstoned).
|
||||
// Use this when checking if an entry should exist in the needle map.
|
||||
// Returns true for negative sizes or TombstoneFileSize.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package util
|
||||
|
||||
import "strings"
|
||||
|
||||
// ExtractBucketPath returns the bucket path under basePath that contains target.
|
||||
// If requireChild is true, the target must include additional segments beyond the bucket itself.
|
||||
func ExtractBucketPath(basePath, target string, requireChild bool) (string, bool) {
|
||||
cleanBase := strings.TrimSuffix(basePath, "/")
|
||||
if cleanBase == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
prefix := cleanBase + "/"
|
||||
if !strings.HasPrefix(target, prefix) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
rest := strings.TrimPrefix(target, prefix)
|
||||
if rest == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
bucketName, _, found := strings.Cut(rest, "/")
|
||||
if bucketName == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
if requireChild && !found {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return prefix + bucketName, true
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package util
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestExtractBucketPath(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
base string
|
||||
target string
|
||||
requireChild bool
|
||||
expected string
|
||||
ok bool
|
||||
}{
|
||||
{
|
||||
name: "child paths return bucket",
|
||||
base: "/buckets",
|
||||
target: "/buckets/test/folder/file",
|
||||
requireChild: true,
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "bucket root without child fails when required",
|
||||
base: "/buckets",
|
||||
target: "/buckets/test",
|
||||
requireChild: true,
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "bucket root allowed when not required",
|
||||
base: "/buckets",
|
||||
target: "/buckets/test",
|
||||
requireChild: false,
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "path outside buckets fails",
|
||||
base: "/buckets",
|
||||
target: "/data/test/folder",
|
||||
requireChild: true,
|
||||
ok: false,
|
||||
},
|
||||
{
|
||||
name: "trailing slash on base is normalized",
|
||||
base: "/buckets/",
|
||||
target: "/buckets/test/sub",
|
||||
requireChild: true,
|
||||
expected: "/buckets/test",
|
||||
ok: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, ok := ExtractBucketPath(tt.base, tt.target, tt.requireChild)
|
||||
if ok != tt.ok {
|
||||
t.Fatalf("expected ok=%v, got %v", tt.ok, ok)
|
||||
}
|
||||
if got != tt.expected {
|
||||
t.Fatalf("expected path %q, got %q", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user