mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2ea089519 | ||
|
|
e655ce9057 | ||
|
|
d51dd99845 | ||
|
|
3e4306da55 | ||
|
|
88b91cccba | ||
|
|
fefac028ec | ||
|
|
0c9872f842 | ||
|
|
da1d7444b8 | ||
|
|
d15396fc4d | ||
|
|
39bdbc18db | ||
|
|
403d51631b | ||
|
|
52d91008ac |
No files matched your search
@@ -24,7 +24,7 @@ jobs:
|
||||
|
||||
# ── Pre-build the Rust binaries natively ────────────────────────────
|
||||
build-rust-binaries:
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
|
||||
@@ -66,7 +66,7 @@ jobs:
|
||||
|
||||
# ── Pre-build the Rust binaries natively ────────────────────────────
|
||||
build-rust-binaries:
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
# amd64 and arm64 without QEMU, turning a 5-hour emulated cargo build into
|
||||
# ~15 minutes of native compilation.
|
||||
build-rust-binaries:
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
|
||||
@@ -32,7 +32,7 @@ defaults:
|
||||
jobs:
|
||||
e2e:
|
||||
name: FUSE Mount
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
|
||||
@@ -28,7 +28,7 @@ permissions:
|
||||
jobs:
|
||||
ec-integration-tests:
|
||||
name: EC Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Set up Go 1.x
|
||||
|
||||
@@ -28,7 +28,7 @@ permissions:
|
||||
jobs:
|
||||
fuse-dlm-integration:
|
||||
name: FUSE DLM Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
|
||||
@@ -33,7 +33,7 @@ permissions:
|
||||
jobs:
|
||||
fuse-failover:
|
||||
name: FUSE Volume Server Failover
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
|
||||
steps:
|
||||
|
||||
@@ -26,7 +26,7 @@ permissions:
|
||||
jobs:
|
||||
fuse-integration:
|
||||
name: FUSE Integration Testing
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 50
|
||||
|
||||
steps:
|
||||
|
||||
@@ -34,7 +34,7 @@ permissions:
|
||||
jobs:
|
||||
fuse-p2p-integration:
|
||||
name: FUSE P2P Peer Chunk Sharing
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
|
||||
@@ -32,7 +32,7 @@ defaults:
|
||||
jobs:
|
||||
kms-provider-tests:
|
||||
name: KMS Provider Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
|
||||
s3-kms-e2e-tests:
|
||||
name: S3 KMS End-to-End Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
|
||||
@@ -30,7 +30,7 @@ permissions:
|
||||
jobs:
|
||||
master-cold-start-tests:
|
||||
name: Master Cold Start Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out code
|
||||
|
||||
@@ -37,7 +37,7 @@ env:
|
||||
jobs:
|
||||
metadata-subscribe-integration:
|
||||
name: Metadata Subscribe Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
|
||||
@@ -30,7 +30,7 @@ permissions:
|
||||
jobs:
|
||||
multi-master-failover-tests:
|
||||
name: Multi-Master Failover Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out code
|
||||
|
||||
@@ -27,7 +27,7 @@ permissions:
|
||||
jobs:
|
||||
pjdfstest:
|
||||
name: pjdfstest
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
|
||||
steps:
|
||||
|
||||
@@ -28,7 +28,7 @@ permissions:
|
||||
jobs:
|
||||
plugin-worker:
|
||||
name: "Plugin Worker: ${{ matrix.worker }}"
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
@@ -54,7 +54,7 @@ jobs:
|
||||
|
||||
build-test-binaries:
|
||||
name: Build Test Binaries
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -113,7 +113,7 @@ jobs:
|
||||
|
||||
rust-unit-tests:
|
||||
name: Rust Unit Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
@@ -213,7 +213,7 @@ jobs:
|
||||
|
||||
rust-integration-tests:
|
||||
name: Rust Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
needs: [build-test-binaries]
|
||||
|
||||
@@ -270,7 +270,7 @@ jobs:
|
||||
|
||||
rust-volume-go-tests:
|
||||
name: Go Tests with Rust Volume (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
needs: [build-test-binaries]
|
||||
env:
|
||||
|
||||
@@ -26,7 +26,7 @@ permissions:
|
||||
jobs:
|
||||
rust-worker-build:
|
||||
name: Rust Plugin Worker Build and Unit Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: cleanup
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
build-rust-volume-linux:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -37,9 +37,13 @@ jobs:
|
||||
if: matrix.cross
|
||||
run: |
|
||||
sudo dpkg --add-architecture arm64
|
||||
sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy main restricted universe multiverse" | sudo tee /etc/apt/sources.list.d/arm64.list
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy-updates main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
|
||||
# noble keeps apt sources in deb822 ubuntu.sources, not sources.list —
|
||||
# pin them to amd64 so apt does not probe arm64 indexes on
|
||||
# archive/security.ubuntu.com (they 404).
|
||||
sudo sed -i '/^Types: deb$/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
|
||||
for suite in noble noble-updates noble-security; do
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports $suite main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
|
||||
done
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gcc-aarch64-linux-gnu libssl-dev:arm64
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
|
||||
@@ -120,7 +124,7 @@ jobs:
|
||||
build-rust-worker-linux:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -146,9 +150,13 @@ jobs:
|
||||
if: matrix.cross
|
||||
run: |
|
||||
sudo dpkg --add-architecture arm64
|
||||
sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy main restricted universe multiverse" | sudo tee /etc/apt/sources.list.d/arm64.list
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy-updates main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
|
||||
# noble keeps apt sources in deb822 ubuntu.sources, not sources.list —
|
||||
# pin them to amd64 so apt does not probe arm64 indexes on
|
||||
# archive/security.ubuntu.com (they 404).
|
||||
sudo sed -i '/^Types: deb$/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
|
||||
for suite in noble noble-updates noble-security; do
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports $suite main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
|
||||
done
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gcc-aarch64-linux-gnu
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
|
||||
|
||||
@@ -30,7 +30,7 @@ permissions:
|
||||
jobs:
|
||||
s3-etag-acl-tests:
|
||||
name: S3 ETag + ACL Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out code
|
||||
|
||||
@@ -22,7 +22,7 @@ permissions:
|
||||
jobs:
|
||||
tests:
|
||||
name: S3 Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
|
||||
@@ -25,7 +25,7 @@ defaults:
|
||||
jobs:
|
||||
s3-filer-group-tests:
|
||||
name: S3 Filer Group Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
|
||||
@@ -26,7 +26,7 @@ defaults:
|
||||
jobs:
|
||||
s3-versioning-tests:
|
||||
name: S3 Versioning Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -97,7 +97,7 @@ jobs:
|
||||
|
||||
s3-versioning-compatibility:
|
||||
name: S3 Versioning Compatibility Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -146,7 +146,7 @@ jobs:
|
||||
|
||||
s3-cors-compatibility:
|
||||
name: S3 CORS Compatibility Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -195,7 +195,7 @@ jobs:
|
||||
|
||||
s3-retention-tests:
|
||||
name: S3 Retention Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -266,7 +266,7 @@ jobs:
|
||||
|
||||
s3-lifecycle-tests:
|
||||
name: S3 Lifecycle Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -339,7 +339,7 @@ jobs:
|
||||
|
||||
s3-checksum-tests:
|
||||
name: S3 Checksum Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -398,7 +398,7 @@ jobs:
|
||||
|
||||
s3-cors-tests:
|
||||
name: S3 CORS Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -469,7 +469,7 @@ jobs:
|
||||
|
||||
s3-retention-worm:
|
||||
name: S3 Retention WORM Integration Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -519,7 +519,7 @@ jobs:
|
||||
|
||||
s3-versioning-stress:
|
||||
name: S3 Versioning Stress Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 35
|
||||
|
||||
steps:
|
||||
@@ -588,7 +588,7 @@ jobs:
|
||||
s3-tagging-tests:
|
||||
# CI job for S3 object tagging tests
|
||||
name: S3 Tagging Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -644,7 +644,7 @@ jobs:
|
||||
|
||||
s3-remote-cache-tests:
|
||||
name: S3 Remote Cache Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
# Unit tests for IAM components
|
||||
iam-unit-tests:
|
||||
name: IAM Unit Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
# S3 IAM integration tests with SeaweedFS services
|
||||
s3-iam-integration-tests:
|
||||
name: S3 IAM Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 25
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -202,7 +202,7 @@ jobs:
|
||||
# Distributed IAM tests
|
||||
s3-iam-distributed-tests:
|
||||
name: S3 IAM Distributed Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
@@ -263,7 +263,7 @@ jobs:
|
||||
# Performance and stress tests
|
||||
s3-iam-performance-tests:
|
||||
name: S3 IAM Performance Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
# Dedicated job for Keycloak integration tests
|
||||
s3-keycloak-integration-tests:
|
||||
name: S3 Keycloak Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
|
||||
@@ -21,7 +21,7 @@ permissions:
|
||||
jobs:
|
||||
s3-versioning-regressions:
|
||||
name: S3 Versioning Regression Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
|
||||
s3-delete-regressions:
|
||||
name: S3 Delete Regression Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -114,7 +114,7 @@ jobs:
|
||||
|
||||
s3-distributed-lock-regressions:
|
||||
name: S3 Distributed Lock Regression Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
# Unit tests for policy components
|
||||
policy-unit-tests:
|
||||
name: S3 Policy Unit Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
# S3 Policy Variables Integration Tests
|
||||
s3-policy-variables-tests:
|
||||
name: S3 Policy Variables Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
@@ -192,7 +192,7 @@ jobs:
|
||||
# S3 Policy Enforcement Integration Tests
|
||||
s3-policy-enforcement-tests:
|
||||
name: S3 Policy Enforcement Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -317,7 +317,7 @@ jobs:
|
||||
# Trusted Proxy Detection Tests
|
||||
trusted-proxy-tests:
|
||||
name: Trusted Proxy Detection Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -405,7 +405,7 @@ jobs:
|
||||
# S3 Policy Shell Integration Tests
|
||||
s3-policy-shell-tests:
|
||||
name: S3 Policy Shell Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
|
||||
@@ -30,7 +30,7 @@ permissions:
|
||||
jobs:
|
||||
proxy-signature-tests:
|
||||
name: S3 Proxy Signature Verification Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
|
||||
@@ -24,7 +24,7 @@ permissions:
|
||||
jobs:
|
||||
s3-sdk-v2-routing-tests:
|
||||
name: S3 SDK V2 Routing Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out code
|
||||
|
||||
@@ -46,7 +46,7 @@ permissions:
|
||||
jobs:
|
||||
snowflake-s3compat-tests:
|
||||
name: Snowflake S3Compat API tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
WORK_DIR: /tmp/seaweedfs-snowflake-tests
|
||||
|
||||
@@ -20,7 +20,7 @@ permissions:
|
||||
jobs:
|
||||
s3-spark-issue-repro-tests:
|
||||
name: S3 Spark Issue Reproduction Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
|
||||
@@ -36,7 +36,7 @@ defaults:
|
||||
jobs:
|
||||
s3-sse-integration-tests:
|
||||
name: S3 SSE Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
|
||||
s3-sse-compatibility:
|
||||
name: S3 SSE Compatibility Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -160,7 +160,7 @@ jobs:
|
||||
|
||||
s3-sse-metadata-persistence:
|
||||
name: S3 SSE Metadata Persistence Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
@@ -210,7 +210,7 @@ jobs:
|
||||
|
||||
s3-sse-copy-operations:
|
||||
name: S3 SSE Copy Operations Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
@@ -260,7 +260,7 @@ jobs:
|
||||
|
||||
s3-sse-multipart:
|
||||
name: S3 SSE Multipart Upload Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
@@ -310,7 +310,7 @@ jobs:
|
||||
|
||||
s3-sse-performance:
|
||||
name: S3 SSE Performance Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 35
|
||||
# Only run performance tests on master branch pushes to avoid overloading PR testing
|
||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main')
|
||||
@@ -361,7 +361,7 @@ jobs:
|
||||
|
||||
s3-volume-encryption:
|
||||
name: S3 Volume Encryption Test
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
|
||||
@@ -23,7 +23,7 @@ permissions:
|
||||
jobs:
|
||||
s3-tables-tests:
|
||||
name: S3 Tables Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -88,7 +88,7 @@ jobs:
|
||||
|
||||
iceberg-catalog-tests:
|
||||
name: Iceberg Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -153,7 +153,7 @@ jobs:
|
||||
|
||||
trino-iceberg-catalog-tests:
|
||||
name: Trino Iceberg Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -227,7 +227,7 @@ jobs:
|
||||
|
||||
dremio-iceberg-catalog-tests:
|
||||
name: Dremio Iceberg Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -304,7 +304,7 @@ jobs:
|
||||
|
||||
doris-iceberg-catalog-tests:
|
||||
name: Doris Iceberg Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 35
|
||||
|
||||
steps:
|
||||
@@ -381,7 +381,7 @@ jobs:
|
||||
|
||||
clickhouse-iceberg-catalog-tests:
|
||||
name: ClickHouse Iceberg Catalog Integration Tests (${{ matrix.tag }})
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -470,7 +470,7 @@ jobs:
|
||||
|
||||
olake-iceberg-catalog-tests:
|
||||
name: OLake Iceberg Catalog Integration Tests (${{ matrix.tag }})
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -585,7 +585,7 @@ jobs:
|
||||
|
||||
polaris-integration-tests:
|
||||
name: Polaris Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -657,7 +657,7 @@ jobs:
|
||||
|
||||
spark-iceberg-catalog-tests:
|
||||
name: Spark Iceberg Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -731,7 +731,7 @@ jobs:
|
||||
|
||||
risingwave-catalog-tests:
|
||||
name: RisingWave Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -806,7 +806,7 @@ jobs:
|
||||
|
||||
sts-integration-tests:
|
||||
name: STS Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -905,7 +905,7 @@ jobs:
|
||||
|
||||
lakekeeper-integration-tests:
|
||||
name: Lakekeeper Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -969,7 +969,7 @@ jobs:
|
||||
|
||||
unity-catalog-integration-tests:
|
||||
name: Unity Catalog Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -1046,7 +1046,7 @@ jobs:
|
||||
|
||||
lancedb-namespace-tests:
|
||||
name: LanceDB Namespace Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -1120,7 +1120,7 @@ jobs:
|
||||
|
||||
table-lifecycle-tests:
|
||||
name: Table Lifecycle Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
|
||||
steps:
|
||||
@@ -1189,7 +1189,7 @@ jobs:
|
||||
|
||||
duckdb-lance-tests:
|
||||
name: DuckDB Lance Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
@@ -1268,7 +1268,7 @@ jobs:
|
||||
|
||||
spark-lance-namespace-tests:
|
||||
name: Spark Lance Namespace Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
|
||||
steps:
|
||||
@@ -1346,7 +1346,7 @@ jobs:
|
||||
|
||||
s3-tables-build-verification:
|
||||
name: S3 Tables Build Verification
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
@@ -1412,7 +1412,7 @@ jobs:
|
||||
|
||||
s3-tables-fmt-check:
|
||||
name: S3 Tables Format Check
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
@@ -1464,7 +1464,7 @@ jobs:
|
||||
|
||||
s3-tables-vet:
|
||||
name: S3 Tables Go Vet Check
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
|
||||
@@ -34,7 +34,7 @@ permissions:
|
||||
jobs:
|
||||
basic-s3-tests:
|
||||
name: Basic S3 tests (KV store)
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
@@ -387,7 +387,7 @@ jobs:
|
||||
|
||||
versioning-tests:
|
||||
name: S3 Versioning & Object Lock tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
@@ -558,7 +558,7 @@ jobs:
|
||||
|
||||
cors-tests:
|
||||
name: S3 CORS tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
@@ -684,7 +684,7 @@ jobs:
|
||||
|
||||
copy-tests:
|
||||
name: SeaweedFS Custom S3 Copy tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
@@ -787,7 +787,7 @@ jobs:
|
||||
|
||||
sql-store-tests:
|
||||
name: Basic S3 tests (SQL store)
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
|
||||
@@ -29,7 +29,7 @@ permissions:
|
||||
jobs:
|
||||
samba-integration:
|
||||
name: samba-integration
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
|
||||
@@ -29,7 +29,7 @@ env:
|
||||
jobs:
|
||||
sftp-integration:
|
||||
name: SFTP Integration Testing
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
|
||||
@@ -28,7 +28,7 @@ permissions:
|
||||
jobs:
|
||||
tls-rotation-tests:
|
||||
name: TLS Rotation Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Set up Go 1.x
|
||||
|
||||
@@ -24,7 +24,7 @@ defaults:
|
||||
jobs:
|
||||
tus-integration-tests:
|
||||
name: TUS Protocol Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
|
||||
@@ -28,7 +28,7 @@ permissions:
|
||||
jobs:
|
||||
vacuum-integration-tests:
|
||||
name: Vacuum Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Set up Go 1.x
|
||||
|
||||
@@ -35,7 +35,7 @@ env:
|
||||
jobs:
|
||||
build-weed:
|
||||
name: Build SeaweedFS Binary
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
@@ -68,7 +68,7 @@ jobs:
|
||||
|
||||
volume-server-integration-tests:
|
||||
name: Volume Server Integration Tests (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
needs: [build-weed]
|
||||
strategy:
|
||||
|
||||
Generated
+1
@@ -4601,6 +4601,7 @@ dependencies = [
|
||||
"futures",
|
||||
"hex",
|
||||
"http-body 1.0.1",
|
||||
"httpdate",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"image",
|
||||
|
||||
@@ -51,6 +51,7 @@ prost-types = "0.14"
|
||||
# HTTP server
|
||||
axum = { version = "0.8", features = ["multipart"] }
|
||||
http-body = "1"
|
||||
httpdate = "1"
|
||||
hyper = { version = "1", features = ["full"] }
|
||||
hyper-util = { version = "0.1", features = ["tokio", "service", "server-auto", "http1", "http2"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
||||
@@ -1120,6 +1120,10 @@ async fn get_or_head_handler_inner(
|
||||
};
|
||||
|
||||
let (etag, last_modified_str) = etag_and_last_modified(&n);
|
||||
// A Range whose If-Range no longer matches is ignored and the whole
|
||||
// content is sent, so a resumed download restarts instead of mixing
|
||||
// two versions.
|
||||
let range = range.filter(|_| if_range_matches(&headers, &etag, &last_modified_str));
|
||||
if let Some(resp) = not_modified_response(&n, &headers, &etag, &last_modified_str) {
|
||||
// A request that ends here was answered by the meta read alone.
|
||||
if let Some(io_errors) = strategy.io_errors() {
|
||||
@@ -1167,14 +1171,20 @@ async fn get_or_head_handler_inner(
|
||||
return head_from_meta_response(&info, response_headers);
|
||||
}
|
||||
ReadStrategy::RangeFromSource(info) => {
|
||||
return range_from_source_response(
|
||||
&state,
|
||||
range.as_deref().unwrap_or_default(),
|
||||
info,
|
||||
response_headers,
|
||||
track_download,
|
||||
)
|
||||
.await;
|
||||
return match range.as_deref() {
|
||||
Some(range) => {
|
||||
range_from_source_response(
|
||||
&state,
|
||||
range,
|
||||
info,
|
||||
response_headers,
|
||||
track_download,
|
||||
)
|
||||
.await
|
||||
}
|
||||
// If-Range dropped the range; serve the whole content.
|
||||
None => stream_response(&state, info, response_headers, track_download),
|
||||
};
|
||||
}
|
||||
ReadStrategy::Buffered => {}
|
||||
}
|
||||
@@ -1557,6 +1567,31 @@ fn not_modified_response(
|
||||
None
|
||||
}
|
||||
|
||||
/// If-Range (RFC 9110 13.1.5): an entity-tag by strong comparison, or a date
|
||||
/// equal to Last-Modified. The response etag here is always a strong tag.
|
||||
fn if_range_matches(headers: &HeaderMap, etag: &str, last_modified_str: &Option<String>) -> bool {
|
||||
let Some(raw) = headers.get(header::IF_RANGE) else {
|
||||
return true;
|
||||
};
|
||||
let Ok(if_range) = raw.to_str() else {
|
||||
return false;
|
||||
};
|
||||
let if_range = if_range.trim();
|
||||
if if_range.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if if_range.starts_with('"') || if_range.starts_with("W/") {
|
||||
return if_range == etag;
|
||||
}
|
||||
let Ok(date) = httpdate::parse_http_date(if_range) else {
|
||||
return false;
|
||||
};
|
||||
last_modified_str
|
||||
.as_deref()
|
||||
.and_then(|lm| httpdate::parse_http_date(lm).ok())
|
||||
.is_some_and(|lm| date == lm)
|
||||
}
|
||||
|
||||
/// Weak comparison against "*" or a comma-separated entity-tag list (RFC 9110 13.1.2).
|
||||
fn etag_list_matches(header: &str, etag: &str) -> bool {
|
||||
if header.trim() == "*" {
|
||||
@@ -5767,6 +5802,53 @@ mod tests {
|
||||
assert!(resp.headers().contains_key(header::LAST_MODIFIED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_if_range_matches() {
|
||||
let etag = "\"v2\"".to_string();
|
||||
let last_modified_str = Some("Sat, 24 Oct 2026 22:01:04 GMT".to_string());
|
||||
let cases: Vec<(Option<&str>, bool)> = vec![
|
||||
(None, true),
|
||||
(Some("\"v2\""), true),
|
||||
(Some("Sat, 24 Oct 2026 22:01:04 GMT"), true),
|
||||
(Some("Saturday, 24-Oct-26 22:01:04 GMT"), true),
|
||||
(Some("Sat Oct 24 22:01:04 2026"), true),
|
||||
(Some("\"v1\""), false),
|
||||
(Some("W/\"v2\""), false),
|
||||
(Some("Sat, 24 Oct 2026 22:01:03 GMT"), false),
|
||||
(Some("not a date"), false),
|
||||
];
|
||||
for (if_range, want) in cases {
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Some(v) = if_range {
|
||||
headers.insert(header::IF_RANGE, v.parse().unwrap());
|
||||
}
|
||||
assert_eq!(
|
||||
if_range_matches(&headers, &etag, &last_modified_str),
|
||||
want,
|
||||
"{if_range:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// A present value that is not valid UTF-8 fails the condition.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::IF_RANGE,
|
||||
header::HeaderValue::from_bytes(b"\"\xff\xfev2\"").unwrap(),
|
||||
);
|
||||
assert!(!if_range_matches(&headers, &etag, &last_modified_str));
|
||||
|
||||
// No Last-Modified on the representation: a date validator fails,
|
||||
// an entity-tag still applies.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::IF_RANGE, "\"v2\"".parse().unwrap());
|
||||
assert!(if_range_matches(&headers, &etag, &None));
|
||||
headers.insert(
|
||||
header::IF_RANGE,
|
||||
"Sat, 24 Oct 2026 22:01:04 GMT".parse().unwrap(),
|
||||
);
|
||||
assert!(!if_range_matches(&headers, &etag, &None));
|
||||
}
|
||||
|
||||
/// A GET whose needle read is parked must not hold the store lock: a
|
||||
/// writer, here a real append to the same volume, must get through.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
@@ -34,6 +34,7 @@ struct ListTablesResponse {
|
||||
pub struct NamespaceClient {
|
||||
base_url: String,
|
||||
http: reqwest::Client,
|
||||
api_key: Option<String>,
|
||||
}
|
||||
|
||||
/// A namespace call that has not answered by now is not going to. Without this
|
||||
@@ -41,12 +42,23 @@ pub struct NamespaceClient {
|
||||
/// slot open forever, and the sweep never finishes.
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_REDIRECT_HOPS: usize = 10;
|
||||
|
||||
impl NamespaceClient {
|
||||
pub fn new(base_url: impl Into<String>) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
// reqwest forwards custom headers on a follow, so only a same-origin
|
||||
// hop is allowed: anywhere else would carry x-api-key to a listener
|
||||
// the credential was never meant for.
|
||||
.redirect(reqwest::redirect::Policy::custom(|attempt| {
|
||||
if may_follow(attempt.previous(), attempt.url()) {
|
||||
attempt.follow()
|
||||
} else {
|
||||
attempt.stop()
|
||||
}
|
||||
}))
|
||||
.build()
|
||||
// The builder only fails on a bad TLS backend, which would break
|
||||
// every call anyway; a client with no timeouts is worse than a panic
|
||||
@@ -58,6 +70,32 @@ impl NamespaceClient {
|
||||
Self {
|
||||
base_url: base_url.into().trim_end_matches('/').to_string(),
|
||||
http,
|
||||
api_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The catalog accepts an S3 credential as `x-api-key`; where the worker
|
||||
/// already holds one for storage it authenticates the namespace calls too.
|
||||
pub fn with_fallback(mut self, fallback: &crate::dataset::FallbackOptions) -> Self {
|
||||
if let (Some(access), Some(secret)) = (
|
||||
fallback.get("aws_access_key_id"),
|
||||
fallback.get("aws_secret_access_key"),
|
||||
) {
|
||||
if !protected_transport(&self.base_url) {
|
||||
tracing::warn!(
|
||||
"catalog url {} exposes the x-api-key credential in cleartext",
|
||||
self.base_url
|
||||
);
|
||||
}
|
||||
self.api_key = Some(format!("{access}:{secret}"));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn authed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
||||
match &self.api_key {
|
||||
Some(key) => request.header("x-api-key", key),
|
||||
None => request,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,8 +103,7 @@ impl NamespaceClient {
|
||||
pub async fn list_all_tables(&self) -> Result<Vec<String>> {
|
||||
let url = format!("{}/v1/table", self.base_url);
|
||||
let response: ListTablesResponse = self
|
||||
.http
|
||||
.get(&url)
|
||||
.authed(self.http.get(&url))
|
||||
.send()
|
||||
.await
|
||||
.context("list tables")?
|
||||
@@ -80,8 +117,7 @@ impl NamespaceClient {
|
||||
pub async fn list_namespaces(&self, id: &[String]) -> Result<Vec<String>> {
|
||||
let url = format!("{}/v1/namespace/{}/list", self.base_url, encode_id(id));
|
||||
let response: ListNamespacesResponse = self
|
||||
.http
|
||||
.get(&url)
|
||||
.authed(self.http.get(&url))
|
||||
.send()
|
||||
.await
|
||||
.context("list namespaces")?
|
||||
@@ -98,8 +134,7 @@ impl NamespaceClient {
|
||||
let url = format!("{}/v1/table/{}/describe", self.base_url, encode_id(id));
|
||||
let body = serde_json::json!({ "id": id, "vend_credentials": true });
|
||||
let description: TableDescription = self
|
||||
.http
|
||||
.post(&url)
|
||||
.authed(self.http.post(&url))
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
@@ -111,6 +146,41 @@ impl NamespaceClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Without a hop bound a catalog that redirects to itself keeps the request
|
||||
/// alive until the call timeout, so the custom policy keeps the limit the
|
||||
/// default one had.
|
||||
fn may_follow(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
|
||||
previous.len() < MAX_REDIRECT_HOPS
|
||||
&& previous.last().is_some_and(|prev| same_origin(prev, next))
|
||||
}
|
||||
|
||||
/// A redirect stays within an origin when scheme, host, and port all match, so
|
||||
/// a catalog cannot bounce the api key onto a downgraded or foreign listener.
|
||||
fn same_origin(from: &reqwest::Url, to: &reqwest::Url) -> bool {
|
||||
from.scheme() == to.scheme()
|
||||
&& from.host_str() == to.host_str()
|
||||
&& from.port_or_known_default() == to.port_or_known_default()
|
||||
}
|
||||
|
||||
/// A catalog url protects the api key when the hop is TLS or never leaves the
|
||||
/// host; anything else sends it where the network can read it.
|
||||
fn protected_transport(base_url: &str) -> bool {
|
||||
let Ok(url) = reqwest::Url::parse(base_url) else {
|
||||
return false;
|
||||
};
|
||||
if url.scheme() == "https" {
|
||||
return true;
|
||||
}
|
||||
match url.host_str() {
|
||||
Some("localhost") => true,
|
||||
Some(host) => host
|
||||
.trim_matches(['[', ']'])
|
||||
.parse::<std::net::IpAddr>()
|
||||
.is_ok_and(|ip| ip.is_loopback()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_id(id: &[String]) -> String {
|
||||
if id.is_empty() {
|
||||
DELIMITER.to_string()
|
||||
@@ -127,3 +197,56 @@ pub fn parse_id(encoded: &str) -> Vec<String> {
|
||||
.map(|part| part.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{MAX_REDIRECT_HOPS, may_follow, protected_transport, same_origin};
|
||||
|
||||
#[test]
|
||||
fn may_follow_bounds_hops_within_the_origin() {
|
||||
let url = |u: &str| reqwest::Url::parse(u).unwrap();
|
||||
let first = [url("https://c.local/ns")];
|
||||
let next = url("https://c.local/other");
|
||||
assert!(may_follow(&first, &next));
|
||||
assert!(!may_follow(&[], &next));
|
||||
assert!(!may_follow(&first, &url("http://c.local/other")));
|
||||
let full: Vec<_> = (0..MAX_REDIRECT_HOPS)
|
||||
.map(|i| url(&format!("https://c.local/{i}")))
|
||||
.collect();
|
||||
assert!(!may_follow(&full, &next));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_origin_rejects_scheme_and_port_hops() {
|
||||
for (from, to, expected) in [
|
||||
("https://c.local/ns", "https://c.local/other", true),
|
||||
("http://c.local", "http://c.local:80/next", true),
|
||||
("https://c.local", "http://c.local/next", false),
|
||||
("https://c.local:8443", "https://c.local/next", false),
|
||||
("https://c.local", "https://other.local/next", false),
|
||||
] {
|
||||
let from = reqwest::Url::parse(from).unwrap();
|
||||
let to = reqwest::Url::parse(to).unwrap();
|
||||
assert_eq!(same_origin(&from, &to), expected, "{from} -> {to}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protected_transport_covers_tls_and_loopback() {
|
||||
for url in [
|
||||
"https://catalog.internal:8443",
|
||||
"http://127.0.0.1:8080",
|
||||
"http://localhost",
|
||||
"http://[::1]:8080",
|
||||
] {
|
||||
assert!(protected_transport(url), "{url} should be protected");
|
||||
}
|
||||
for url in [
|
||||
"http://catalog.internal",
|
||||
"http://127.0.0.1.evil.test",
|
||||
"not a url",
|
||||
] {
|
||||
assert!(!protected_transport(url), "{url} should warn");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,7 @@ impl CleanupVersionsHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ impl CompactHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ impl OptimizeIndicesHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ impl SortHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ impl PreviewProvider for LancePreview {
|
||||
}
|
||||
|
||||
async fn preview(&self, object_id: &[String], row_limit: usize) -> Result<Preview> {
|
||||
let client = NamespaceClient::new(self.namespace_url.clone());
|
||||
let client = NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback);
|
||||
let table = dataset::open(&client, object_id, &self.fallback).await?;
|
||||
|
||||
let total_rows = table.dataset.count_rows(None).await.unwrap_or(0) as i64;
|
||||
|
||||
@@ -244,7 +244,13 @@ func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
|
||||
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
|
||||
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatalf("build the namespace exists request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", env.accessKey+":"+env.secretKey)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
|
||||
}
|
||||
|
||||
@@ -53,7 +53,13 @@ def main():
|
||||
"aws_region": "us-east-1",
|
||||
}
|
||||
|
||||
ns = ln.connect("rest", {"uri": args.namespace_url})
|
||||
ns = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
)
|
||||
ns.create_namespace(ln.CreateNamespaceRequest(id=[args.bucket], mode="EXIST_OK"))
|
||||
ns.create_namespace(
|
||||
ln.CreateNamespaceRequest(id=[args.bucket, args.namespace], mode="EXIST_OK")
|
||||
|
||||
@@ -45,7 +45,15 @@ def seed_table(namespace_url, storage, bucket, namespace, table, rows):
|
||||
LanceDB reads through the catalog; the writing half is pylance, because the
|
||||
namespace records where a table lives and does not carry its data.
|
||||
"""
|
||||
ns = ln.connect("rest", {"uri": namespace_url})
|
||||
ns = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": namespace_url,
|
||||
"header.x-api-key": (
|
||||
f"{storage['aws_access_key_id']}:{storage['aws_secret_access_key']}"
|
||||
),
|
||||
},
|
||||
)
|
||||
ns.create_namespace(
|
||||
ln.CreateNamespaceRequest(id=[bucket], mode="EXIST_OK")
|
||||
)
|
||||
@@ -98,7 +106,12 @@ def main():
|
||||
|
||||
print(f"lancedb {lancedb.__version__} connecting to {args.namespace_url}")
|
||||
db = lancedb.connect_namespace(
|
||||
"rest", {"uri": args.namespace_url}, storage_options=storage
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
storage_options=storage,
|
||||
)
|
||||
|
||||
# 1. The catalog is browsable: the bucket is a namespace, and the table is
|
||||
@@ -190,7 +203,10 @@ def main():
|
||||
# declare-and-write - rather than a hang, a 404, or a half-made table.
|
||||
pushdown = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{"uri": args.namespace_url},
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
storage_options=storage,
|
||||
namespace_client_pushdown_operations=["CreateTable"],
|
||||
)
|
||||
|
||||
@@ -41,6 +41,7 @@ deployment uses whatever address the gateway answers on:
|
||||
spark.sql.catalog.lance org.lance.spark.LanceNamespaceSparkCatalog
|
||||
spark.sql.catalog.lance.impl rest
|
||||
spark.sql.catalog.lance.uri http://seaweed:9101
|
||||
spark.sql.catalog.lance.headers.x-api-key <access-key>:<secret-key>
|
||||
spark.sql.catalog.lance.storage.aws_endpoint http://seaweed:8333
|
||||
spark.sql.catalog.lance.storage.allow_http true
|
||||
spark.sql.catalog.lance.storage.aws_access_key_id …
|
||||
|
||||
@@ -46,6 +46,10 @@ def main():
|
||||
.config("spark.sql.catalog.lance", "org.lance.spark.LanceNamespaceSparkCatalog")
|
||||
.config("spark.sql.catalog.lance.impl", "rest")
|
||||
.config("spark.sql.catalog.lance.uri", args.namespace_url)
|
||||
.config(
|
||||
"spark.sql.catalog.lance.headers.x-api-key",
|
||||
f"{args.access_key}:{args.secret_key}",
|
||||
)
|
||||
.config("spark.sql.catalog.lance.storage.aws_endpoint", args.s3_endpoint)
|
||||
.config("spark.sql.catalog.lance.storage.allow_http", "true")
|
||||
.config("spark.sql.catalog.lance.storage.aws_access_key_id", args.access_key)
|
||||
|
||||
@@ -239,7 +239,13 @@ func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
|
||||
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
|
||||
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatalf("build the namespace exists request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", env.accessKey+":"+env.secretKey)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
|
||||
}
|
||||
|
||||
@@ -99,7 +99,8 @@ def connect(args):
|
||||
"uri": args.catalog_url,
|
||||
"warehouse": f"s3://{args.bucket}/",
|
||||
"prefix": args.bucket,
|
||||
"auth": {"type": "noop"},
|
||||
"oauth2-server-uri": f"{args.catalog_url}/v1/oauth/tokens",
|
||||
"credential": f"{args.access_key}:{args.secret_key}",
|
||||
"s3.endpoint": args.s3_endpoint,
|
||||
"s3.access-key-id": args.access_key,
|
||||
"s3.secret-access-key": args.secret_key,
|
||||
|
||||
@@ -83,7 +83,13 @@ def tally(dataset):
|
||||
|
||||
def resolve(args):
|
||||
"""Ask the namespace where the table lives, the way the worker does."""
|
||||
namespace = ln.connect("rest", {"uri": args.namespace_url})
|
||||
namespace = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
)
|
||||
table_id = [args.bucket, args.namespace, args.table]
|
||||
described = namespace.describe_table(ln.DescribeTableRequest(id=table_id))
|
||||
return namespace, table_id, described.location, storage_options(args, described)
|
||||
@@ -115,7 +121,13 @@ def main():
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.phase == "write":
|
||||
namespace = ln.connect("rest", {"uri": args.namespace_url})
|
||||
namespace = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
)
|
||||
for parent in ([args.bucket], [args.bucket, args.namespace]):
|
||||
namespace.create_namespace(ln.CreateNamespaceRequest(id=parent, mode="EXIST_OK"))
|
||||
table_id = [args.bucket, args.namespace, args.table]
|
||||
|
||||
@@ -111,6 +111,16 @@ func (cp *ConfigPersistence) ApplyMaintenanceConfigFromToml(v TomlConfig) error
|
||||
}
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.max_shard_transfers"; v.IsSet(k) {
|
||||
n := v.GetInt(k)
|
||||
if n < 0 {
|
||||
n = 0
|
||||
} else if n > math.MaxInt32 {
|
||||
n = math.MaxInt32
|
||||
}
|
||||
ecConf.MaxShardTransfers = &n
|
||||
ecChanged = true
|
||||
}
|
||||
|
||||
if !maintenanceChanged && !vacuumChanged && !balanceChanged && !ecChanged {
|
||||
return nil
|
||||
@@ -239,6 +249,7 @@ var pluginConfigSections = []pluginConfigSection{
|
||||
"replica_placement": stringValue,
|
||||
"strict_placement": boolValue,
|
||||
"free_slots_deadband": int64Value,
|
||||
"max_shard_transfers": int64Value,
|
||||
},
|
||||
// workers read collection_filter from the admin values, not the worker values
|
||||
adminKeys: map[string]func(v TomlConfig, key string) *plugin_pb.ConfigValue{
|
||||
|
||||
@@ -307,3 +307,97 @@ preferred_tags = ["fast,SSD"]
|
||||
t.Errorf("preferred_tags = %v, want [fast ssd]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMaintenanceConfigFromTomlMaxShardTransfers(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
fullness_ratio = 0.9
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply fullness: %v", err)
|
||||
}
|
||||
ec := erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers != nil {
|
||||
t.Fatalf("absent key persisted as %d, want unset", *ec.MaxShardTransfers)
|
||||
}
|
||||
if ec.FullnessRatio != 0.9 {
|
||||
t.Fatalf("fullness_ratio = %v, want 0.9", ec.FullnessRatio)
|
||||
}
|
||||
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = 0
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply 0: %v", err)
|
||||
}
|
||||
ec = erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 0 {
|
||||
t.Fatalf("0: got %v, want sequential 0", ec.MaxShardTransfers)
|
||||
}
|
||||
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = 4
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply 4: %v", err)
|
||||
}
|
||||
ec = erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 4 {
|
||||
t.Fatalf("4: got %v, want 4", ec.MaxShardTransfers)
|
||||
}
|
||||
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = -3
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply negative: %v", err)
|
||||
}
|
||||
ec = erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 0 {
|
||||
t.Fatalf("negative: got %v, want sequential 0", ec.MaxShardTransfers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyPluginConfigFromTomlMaxShardTransfers(t *testing.T) {
|
||||
s := newPluginServer(t)
|
||||
seed := &plugin_pb.PersistedJobTypeConfig{
|
||||
JobType: "erasure_coding",
|
||||
AdminRuntime: &plugin_pb.AdminRuntimeConfig{Enabled: true},
|
||||
}
|
||||
if err := s.GetPlugin().SaveJobTypeConfig(seed); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
|
||||
if err := s.ApplyPluginConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
replica_placement = "020"
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply placement: %v", err)
|
||||
}
|
||||
cfg, err := s.GetPlugin().LoadJobTypeConfig("erasure_coding")
|
||||
if err != nil || cfg == nil {
|
||||
t.Fatalf("load: %v %v", cfg, err)
|
||||
}
|
||||
if _, ok := cfg.WorkerConfigValues["max_shard_transfers"]; ok {
|
||||
t.Fatal("absent max_shard_transfers was written into worker config")
|
||||
}
|
||||
|
||||
if err := s.ApplyPluginConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = 0
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply 0: %v", err)
|
||||
}
|
||||
cfg, err = s.GetPlugin().LoadJobTypeConfig("erasure_coding")
|
||||
if err != nil || cfg == nil {
|
||||
t.Fatalf("load 0: %v %v", cfg, err)
|
||||
}
|
||||
got, ok := cfg.WorkerConfigValues["max_shard_transfers"]
|
||||
if !ok {
|
||||
t.Fatal("max_shard_transfers = 0 missing from worker config")
|
||||
}
|
||||
if got.GetInt64Value() != 0 {
|
||||
t.Fatalf("max_shard_transfers = %d, want 0", got.GetInt64Value())
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -50,9 +51,14 @@ func NewFileBrowserHandlers(adminServer *dash.AdminServer) *FileBrowserHandlers
|
||||
// ShowFileBrowser renders the file browser page
|
||||
func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Request) {
|
||||
// Get path from query parameter, default to root
|
||||
path := defaultQuery(r.URL.Query().Get("path"), "/")
|
||||
// Normalize Windows-style paths for consistency
|
||||
path = util.CleanWindowsPath(path)
|
||||
dirPath := path.Clean(util.CleanWindowsPath(defaultQuery(r.URL.Query().Get("path"), "/")))
|
||||
if !strings.HasPrefix(dirPath, "/") {
|
||||
dirPath = "/" + dirPath
|
||||
}
|
||||
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) && restrictedBrowserPath(dirPath) {
|
||||
http.Redirect(w, r, dash.P(r.Context(), "/admin?error=Insufficient permissions"), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
// Get pagination parameters
|
||||
lastFileName := r.URL.Query().Get("lastFileName")
|
||||
@@ -66,7 +72,7 @@ func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
// Get file browser data with cursor-based pagination
|
||||
browserData, err := h.adminServer.GetFileBrowser(path, "", lastFileName, pageSize)
|
||||
browserData, err := h.adminServer.GetFileBrowser(dirPath, "", lastFileName, pageSize)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get file browser data: "+err.Error())
|
||||
return
|
||||
@@ -356,14 +362,46 @@ func (h *FileBrowserHandlers) validateAndCleanFilePath(filePath string) (string,
|
||||
cleanPath = "/" + cleanPath
|
||||
}
|
||||
|
||||
// Prevent path traversal attacks
|
||||
if strings.Contains(cleanPath, "..") {
|
||||
// Reject parent-directory components; names merely containing ".." are valid
|
||||
if slices.Contains(strings.Split(cleanPath, "/"), "..") {
|
||||
return "", fmt.Errorf("path traversal not allowed")
|
||||
}
|
||||
|
||||
return cleanPath, nil
|
||||
}
|
||||
|
||||
// restrictedBrowserPath reports whether a cleaned path lies inside the filer's
|
||||
// /etc tree, which holds the credential store and cluster configuration.
|
||||
func restrictedBrowserPath(cleanPath string) bool {
|
||||
return cleanPath == strings.TrimSuffix(filer.DirectoryEtcRoot, "/") ||
|
||||
strings.HasPrefix(cleanPath, filer.DirectoryEtcRoot)
|
||||
}
|
||||
|
||||
// cleanReadPath validates the request's path parameter; read-only sessions are
|
||||
// denied the /etc tree so the file browser cannot serve stored credentials.
|
||||
func (h *FileBrowserHandlers) cleanReadPath(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
cleanPath, err := h.validateAndCleanFilePath(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return "", false
|
||||
}
|
||||
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) && restrictedBrowserPath(cleanPath) {
|
||||
writeJSONError(w, http.StatusForbidden, "Access to this path requires admin access")
|
||||
return "", false
|
||||
}
|
||||
return cleanPath, true
|
||||
}
|
||||
|
||||
// exportExcludedPrefixes lists the subtrees a metadata export skips; read-only
|
||||
// sessions also lose /etc so stored credentials stay out of the dump.
|
||||
func exportExcludedPrefixes(r *http.Request) []string {
|
||||
prefixes := []string{filer.SystemLogDir}
|
||||
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) {
|
||||
prefixes = append(prefixes, strings.TrimSuffix(filer.DirectoryEtcRoot, "/"))
|
||||
}
|
||||
return prefixes
|
||||
}
|
||||
|
||||
// fetchFileContent fetches file content via the filer gRPC service. It is
|
||||
// used for the "view as text" path, so the maxBytes cap matches the 1 MB
|
||||
// limit the caller already applies before invoking us.
|
||||
@@ -377,9 +415,8 @@ func (h *FileBrowserHandlers) fetchFileContent(filePath string, timeout time.Dur
|
||||
// gRPC service, so the admin file browser keeps working even when the filer
|
||||
// is started with -disableHttp=true.
|
||||
func (h *FileBrowserHandlers) DownloadFile(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
filePath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
inline := r.URL.Query().Get("inline") == "true"
|
||||
@@ -419,9 +456,8 @@ func (t *responseWriteTracker) Write(p []byte) (int, error) {
|
||||
|
||||
// ViewFile handles file viewing requests (for text files, images, etc.)
|
||||
func (h *FileBrowserHandlers) ViewFile(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
filePath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -524,9 +560,8 @@ func (h *FileBrowserHandlers) ViewFile(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// GetFileProperties handles file properties requests
|
||||
func (h *FileBrowserHandlers) GetFileProperties(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
filePath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -630,23 +665,18 @@ func (h *FileBrowserHandlers) GetFileProperties(w http.ResponseWriter, r *http.R
|
||||
// FullEntry stream — the format weed shell fs.meta.load reads. Directories are
|
||||
// walked recursively via the filer BFS metadata stream.
|
||||
func (h *FileBrowserHandlers) ExportMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
return
|
||||
}
|
||||
cleanPath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
cleanPath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
excludedPrefixes := exportExcludedPrefixes(r)
|
||||
|
||||
tracker := &responseWriteTracker{ResponseWriter: w}
|
||||
|
||||
err = h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
stream, err := client.TraverseBfsMetadata(r.Context(), &filer_pb.TraverseBfsMetadataRequest{
|
||||
Directory: cleanPath,
|
||||
ExcludedPrefixes: []string{filer.SystemLogDir},
|
||||
ExcludedPrefixes: excludedPrefixes,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -3,9 +3,12 @@ package handlers
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
)
|
||||
|
||||
func TestValidateAndCleanFilePath_AllowsControlChars(t *testing.T) {
|
||||
@@ -26,6 +29,9 @@ func TestValidateAndCleanFilePath_AllowsControlChars(t *testing.T) {
|
||||
{"relative/path.txt", "/relative/path.txt"},
|
||||
// Duplicate slashes should be collapsed by path.Clean.
|
||||
{"/a//b", "/a/b"},
|
||||
// ".." inside a file or directory name is not a parent component.
|
||||
{"/buckets/reports/report..csv", "/buckets/reports/report..csv"},
|
||||
{"/a../b", "/a../b"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := h.validateAndCleanFilePath(tc.in)
|
||||
@@ -46,6 +52,81 @@ func TestValidateAndCleanFilePath_RejectsEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAndCleanFilePath_RejectsParentComponents(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
for _, p := range []string{"../etc", "../../etc/iam", "..", "a/../../b"} {
|
||||
if _, err := h.validateAndCleanFilePath(p); err == nil {
|
||||
t.Errorf("validateAndCleanFilePath(%q): expected traversal rejection", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanReadPath_DeniesEtcForReadOnly(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
|
||||
denied := []string{"/etc", "/etc/iam", "/etc/iam/identities/root.json",
|
||||
"/etc/s3/kek.json", "/etc/../etc/iam/identity.json", "/a/../../etc/x"}
|
||||
for _, p := range denied {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/download?path="+p, nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "ro", dash.RoleReadOnly, "csrf"))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
if _, ok := h.cleanReadPath(w, req); ok {
|
||||
t.Errorf("path %q: expected denial for read-only session", p)
|
||||
continue
|
||||
}
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("path %q: expected 403, got %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanReadPath_AllowsEtcForAdminAndNorRole(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
|
||||
for _, role := range []string{"admin", ""} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/download?path=/etc/iam/identities/root.json", nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "u", role, "csrf"))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
if _, ok := h.cleanReadPath(w, req); !ok {
|
||||
t.Errorf("role %q: expected /etc path to be allowed, got %d", role, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanReadPath_AllowsReadOnlyOutsideEtc(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
|
||||
for _, p := range []string{"/buckets/foo/bar.txt", "/etcx/file", "/etcetera", "/"} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/download?path="+p, nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "ro", dash.RoleReadOnly, "csrf"))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
if _, ok := h.cleanReadPath(w, req); !ok {
|
||||
t.Errorf("path %q: expected allowed for read-only session, got %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportExcludedPrefixes_ReadOnlyDropsEtc(t *testing.T) {
|
||||
etcPrefix := strings.TrimSuffix(filer.DirectoryEtcRoot, "/")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/metadata/export?path=/", nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "ro", dash.RoleReadOnly, "csrf"))
|
||||
if got := exportExcludedPrefixes(req); !slices.Contains(got, etcPrefix) {
|
||||
t.Errorf("read-only export should exclude %q, got %v", etcPrefix, got)
|
||||
}
|
||||
|
||||
for _, role := range []string{"admin", ""} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/metadata/export?path=/", nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "u", role, "csrf"))
|
||||
if got := exportExcludedPrefixes(req); slices.Contains(got, etcPrefix) {
|
||||
t.Errorf("role %q: export should keep %q, got %v", role, etcPrefix, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListFolders_RejectsPathOutsideBuckets(t *testing.T) {
|
||||
h := &FileBrowserHandlers{adminServer: &dash.AdminServer{}}
|
||||
|
||||
@@ -62,4 +143,3 @@ func TestListFolders_RejectsPathOutsideBuckets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2272,6 +2272,105 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
return input;
|
||||
}
|
||||
|
||||
function shardTransferParallelOn(nativeValue) {
|
||||
if (nativeValue === null || nativeValue === undefined || nativeValue === '') {
|
||||
return true;
|
||||
}
|
||||
var n = parseInt(nativeValue, 10);
|
||||
if (Number.isNaN(n)) {
|
||||
return true;
|
||||
}
|
||||
return n !== 0;
|
||||
}
|
||||
|
||||
function shardTransferMaxText(nativeValue) {
|
||||
if (nativeValue === null || nativeValue === undefined || nativeValue === '') {
|
||||
return '';
|
||||
}
|
||||
var n = parseInt(nativeValue, 10);
|
||||
if (Number.isNaN(n) || n <= 0) {
|
||||
return '';
|
||||
}
|
||||
return String(n);
|
||||
}
|
||||
|
||||
// Presentation of the single persisted max_shard_transfers value.
|
||||
// Unchecked stores 0. Checked with an empty max omits the key.
|
||||
function renderShardTransferControls(scope, field, nativeValue) {
|
||||
var parallelOn = shardTransferParallelOn(nativeValue);
|
||||
var wrapper = document.createElement('div');
|
||||
wrapper.className = 'mb-3 plugin-field';
|
||||
wrapper.dataset.scope = scope;
|
||||
wrapper.dataset.fieldName = field.name;
|
||||
wrapper.dataset.fieldType = normalizeEnum(field.field_type);
|
||||
wrapper.dataset.widget = 'SHARD_TRANSFERS';
|
||||
|
||||
var checkWrap = document.createElement('div');
|
||||
checkWrap.className = 'form-check form-switch mb-2';
|
||||
var box = document.createElement('input');
|
||||
box.type = 'checkbox';
|
||||
box.className = 'form-check-input';
|
||||
box.id = toInputID(scope, field.name) + '-parallel';
|
||||
box.checked = parallelOn;
|
||||
var boxLabel = document.createElement('label');
|
||||
boxLabel.className = 'form-check-label';
|
||||
boxLabel.setAttribute('for', box.id);
|
||||
boxLabel.textContent = 'Parallel shard distribution';
|
||||
checkWrap.appendChild(box);
|
||||
checkWrap.appendChild(boxLabel);
|
||||
wrapper.appendChild(checkWrap);
|
||||
|
||||
var numberLabel = document.createElement('label');
|
||||
numberLabel.className = 'form-label';
|
||||
numberLabel.setAttribute('for', toInputID(scope, field.name));
|
||||
numberLabel.textContent = 'Max transfers';
|
||||
wrapper.appendChild(numberLabel);
|
||||
|
||||
var input = document.createElement('input');
|
||||
input.type = 'number';
|
||||
input.min = '1';
|
||||
input.step = '1';
|
||||
input.className = 'form-control';
|
||||
input.id = toInputID(scope, field.name);
|
||||
input.placeholder = 'no global cap';
|
||||
input.value = shardTransferMaxText(nativeValue);
|
||||
input.disabled = !parallelOn;
|
||||
wrapper.appendChild(input);
|
||||
|
||||
box.addEventListener('change', function() {
|
||||
input.disabled = !box.checked;
|
||||
});
|
||||
|
||||
var help = document.createElement('div');
|
||||
help.className = 'form-text';
|
||||
help.textContent = field.description || 'Unchecked sends shards sequentially. Checked with an empty max uses one in-flight copy per destination disk. A number is a global cap, still one copy per disk.';
|
||||
wrapper.appendChild(help);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function collectShardTransferValue(scope) {
|
||||
var box = document.getElementById(toInputID(scope, 'max_shard_transfers') + '-parallel');
|
||||
var input = document.getElementById(toInputID(scope, 'max_shard_transfers'));
|
||||
if (!box || !input) {
|
||||
return null;
|
||||
}
|
||||
if (!box.checked) {
|
||||
return { int64_value: '0' };
|
||||
}
|
||||
var raw = String(input.value || '').trim();
|
||||
if (raw === '') {
|
||||
return null;
|
||||
}
|
||||
if (!/^\d+$/.test(raw)) {
|
||||
throw new Error('Invalid int64 value for field Max transfers');
|
||||
}
|
||||
var n = parseInt(raw, 10);
|
||||
if (n <= 0) {
|
||||
return { int64_value: '0' };
|
||||
}
|
||||
return { int64_value: String(n) };
|
||||
}
|
||||
|
||||
function renderConfigForm(scope, rootID, form) {
|
||||
var root = document.getElementById(rootID);
|
||||
if (!root) {
|
||||
@@ -2321,6 +2420,11 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
var configValue = resolveFieldConfigValue(scope, field);
|
||||
var nativeValue = configValueToNative(configValue);
|
||||
|
||||
if (field.name === 'max_shard_transfers') {
|
||||
sectionBody.appendChild(renderShardTransferControls(scope, field, nativeValue));
|
||||
continue;
|
||||
}
|
||||
|
||||
var wrapper = document.createElement('div');
|
||||
wrapper.className = 'mb-3 plugin-field';
|
||||
wrapper.dataset.scope = scope;
|
||||
@@ -2440,6 +2544,14 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field.name === 'max_shard_transfers') {
|
||||
var shardCap = collectShardTransferValue(scope);
|
||||
if (shardCap !== null) {
|
||||
out[field.name] = shardCap;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
var wrapper = document.querySelector('.plugin-field[data-scope="' + scope + '"][data-field-name="' + field.name + '"]');
|
||||
if (wrapper && wrapper.classList.contains('plugin-field-hidden')) {
|
||||
continue;
|
||||
|
||||
@@ -104,7 +104,7 @@ func Plugin(page string, initialJob string, lane string) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"bi bi-arrow-repeat me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"bi bi-graph-up-arrow me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"bi bi-sliders me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"bi bi-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"bi bi-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"bi bi-list-check me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"bi bi-arrow-repeat me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"bi bi-graph-up-arrow me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"bi bi-sliders me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"bi bi-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"bi bi-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"bi bi-list-check me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
+18
-3
@@ -64,6 +64,7 @@ type FilerOptions struct {
|
||||
mastersString *string
|
||||
ip *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
portGrpc *int
|
||||
publicPort *int
|
||||
@@ -282,12 +283,17 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
}
|
||||
go stats_collect.StartMetricsServer(*f.metricsHttpIp, *f.metricsHttpPort)
|
||||
|
||||
// Embedded services keep their loopback companion listener only while
|
||||
// -ip.bind is unset and the bind address falls back to -ip. This must be
|
||||
// captured before startFiler fills *f.bindIp in place.
|
||||
filerBindIpUnset := *f.bindIp == ""
|
||||
filerAddress := pb.NewServerAddress(*f.ip, *f.port, *f.portGrpc).String()
|
||||
startDelay := time.Duration(2)
|
||||
if *filerStartS3 {
|
||||
filerS3Options.filer = &filerAddress
|
||||
filerS3Options.ip = f.ip
|
||||
if *filerS3Options.bindIp == "" {
|
||||
filerS3Options.listenOnLocalhost = &filerBindIpUnset
|
||||
filerS3Options.bindIp = f.bindIp
|
||||
}
|
||||
filerS3Options.localFilerSocket = f.localSocket
|
||||
@@ -320,6 +326,7 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
if *filerStartIam {
|
||||
filerIamOptions.filer = &filerAddress
|
||||
filerIamOptions.masters = f.mastersString
|
||||
filerIamOptions.listenOnLocalhost = &filerBindIpUnset
|
||||
go func(delay time.Duration) {
|
||||
time.Sleep(delay * time.Second)
|
||||
filerIamOptions.startIamServer()
|
||||
@@ -330,6 +337,7 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
if *filerStartSftp {
|
||||
filerSftpOptions.filer = &filerAddress
|
||||
if *filerSftpOptions.bindIp == "" {
|
||||
filerSftpOptions.listenOnLocalhost = &filerBindIpUnset
|
||||
filerSftpOptions.bindIp = f.bindIp
|
||||
}
|
||||
go func(delay time.Duration) {
|
||||
@@ -356,6 +364,13 @@ func (fo *FilerOptions) startFiler() {
|
||||
if *fo.portGrpc == 0 {
|
||||
*fo.portGrpc = 10000 + *fo.port
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset
|
||||
// and the bind address falls back to -ip. An explicit -ip.bind pins each
|
||||
// port to exactly that address.
|
||||
listenOnLocalhost := *fo.bindIp == ""
|
||||
if fo.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *fo.listenOnLocalhost
|
||||
}
|
||||
if *fo.bindIp == "" {
|
||||
*fo.bindIp = *fo.ip
|
||||
}
|
||||
@@ -433,7 +448,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
if *fo.publicPort != 0 {
|
||||
publicListeningAddress := util.JoinHostPort(*fo.bindIp, *fo.publicPort)
|
||||
glog.V(0).Infoln("Start Seaweed filer server", version.Version(), "public at", publicListeningAddress)
|
||||
publicListener, localPublicListener, e := util.NewIpAndLocalListeners(*fo.bindIp, *fo.publicPort, 0)
|
||||
publicListener, localPublicListener, e := util.NewIpAndLocalListeners(*fo.bindIp, *fo.publicPort, 0, listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer server public listener error on port %d:%v", *fo.publicPort, e)
|
||||
}
|
||||
@@ -459,7 +474,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
glog.V(0).Infof("Start Seaweed Filer %s at %s:%d", version.Version(), *fo.ip, *fo.port)
|
||||
filerListener, filerLocalListener, e := util.NewIpAndLocalListeners(
|
||||
*fo.bindIp, *fo.port,
|
||||
time.Duration(10)*time.Second,
|
||||
time.Duration(10)*time.Second, listenOnLocalhost,
|
||||
)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer listener error: %v", e)
|
||||
@@ -467,7 +482,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
|
||||
// starting grpc server
|
||||
grpcPort := *fo.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*fo.bindIp, grpcPort, 0)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*fo.bindIp, grpcPort, 0, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
|
||||
+16
-1
@@ -31,6 +31,8 @@ type IamOptions struct {
|
||||
filer *string
|
||||
masters *string
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
selfServiceRequiresGrant *bool
|
||||
}
|
||||
@@ -40,6 +42,7 @@ func init() {
|
||||
iamStandaloneOptions.filer = cmdIam.Flag.String("filer", "localhost:8888", "comma-separated filer server addresses for high availability")
|
||||
iamStandaloneOptions.masters = cmdIam.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
iamStandaloneOptions.ip = cmdIam.Flag.String("ip", util.DetectedHostAddress(), "iam server http listen ip address")
|
||||
iamStandaloneOptions.ipBind = cmdIam.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
iamStandaloneOptions.port = cmdIam.Flag.Int("port", 8111, "iam server http listen port")
|
||||
iamStandaloneOptions.selfServiceRequiresGrant = cmdIam.Flag.Bool("selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
}
|
||||
@@ -119,8 +122,20 @@ func (iamopt *IamOptions) startIamServer() bool {
|
||||
iamApiServer.Shutdown()
|
||||
})
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset and
|
||||
// the bind address falls back to -ip. An explicit -ip.bind pins the port to
|
||||
// exactly that address.
|
||||
bindIp := *iamopt.ip
|
||||
listenOnLocalhost := iamopt.ipBind == nil || *iamopt.ipBind == ""
|
||||
if iamopt.ipBind != nil && *iamopt.ipBind != "" {
|
||||
bindIp = *iamopt.ipBind
|
||||
}
|
||||
if iamopt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *iamopt.listenOnLocalhost
|
||||
}
|
||||
|
||||
listenAddress := fmt.Sprintf(":%d", *iamopt.port)
|
||||
iamApiListener, iamApiLocalListener, err := util.NewIpAndLocalListeners(*iamopt.ip, *iamopt.port, time.Duration(10)*time.Second)
|
||||
iamApiListener, iamApiLocalListener, err := util.NewIpAndLocalListeners(bindIp, *iamopt.port, time.Duration(10)*time.Second, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("IAM API Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
+10
-2
@@ -50,6 +50,7 @@ type MasterOptions struct {
|
||||
portGrpc *int
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
metaFolder *string
|
||||
peers *string
|
||||
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
|
||||
@@ -191,6 +192,13 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
if *masterOption.portGrpc == 0 {
|
||||
*masterOption.portGrpc = 10000 + *masterOption.port
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset
|
||||
// and the bind address falls back to -ip. An explicit -ip.bind pins each
|
||||
// port to exactly that address.
|
||||
listenOnLocalhost := *masterOption.ipBind == ""
|
||||
if masterOption.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *masterOption.listenOnLocalhost
|
||||
}
|
||||
if *masterOption.ipBind == "" {
|
||||
*masterOption.ipBind = *masterOption.ip
|
||||
}
|
||||
@@ -207,7 +215,7 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
ms := weed_server.NewMasterServer(r, masterOption.toMasterOption(masterWhiteList), masterPeers)
|
||||
listeningAddress := util.JoinHostPort(*masterOption.ipBind, *masterOption.port)
|
||||
glog.V(0).Infof("Start Seaweed Master %s at %s", version.Version(), listeningAddress)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOption.ipBind, *masterOption.port, 0)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOption.ipBind, *masterOption.port, 0, listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Master startup error: %v", e)
|
||||
}
|
||||
@@ -264,7 +272,7 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
}
|
||||
// starting grpc server
|
||||
grpcPort := *masterOption.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOption.ipBind, grpcPort, 0)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOption.ipBind, grpcPort, 0, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("master failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
|
||||
@@ -129,6 +129,10 @@ func startMasterFollower(masterOptions MasterOptions) {
|
||||
option := masterOptions.toMasterOption(nil)
|
||||
option.IsFollower = true
|
||||
|
||||
listenOnLocalhost := *masterOptions.ipBind == ""
|
||||
if masterOptions.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *masterOptions.listenOnLocalhost
|
||||
}
|
||||
if *masterOptions.ipBind == "" {
|
||||
*masterOptions.ipBind = *masterOptions.ip
|
||||
}
|
||||
@@ -137,14 +141,14 @@ func startMasterFollower(masterOptions MasterOptions) {
|
||||
ms := weed_server.NewMasterServer(r, option, masters)
|
||||
listeningAddress := util.JoinHostPort(*masterOptions.ipBind, *masterOptions.port)
|
||||
glog.V(0).Infof("Start Seaweed Master %s at %s", version.Version(), listeningAddress)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOptions.ipBind, *masterOptions.port, 0)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOptions.ipBind, *masterOptions.port, 0, listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Master startup error: %v", e)
|
||||
}
|
||||
|
||||
// starting grpc server
|
||||
grpcPort := *masterOptions.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOptions.ipBind, grpcPort, 0)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOptions.ipBind, grpcPort, 0, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("master failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
|
||||
+111
-65
@@ -821,10 +821,20 @@ func isPortAvailable(port int) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// isPortUsableOnIP reports whether port can be bound on ip. While mini also
|
||||
// opens a loopback listener, the port must additionally be free on every
|
||||
// interface so that listener cannot collide with a holder on another address.
|
||||
func isPortUsableOnIP(ip string, port int, listenOnLocalhost bool) bool {
|
||||
if !isPortOpenOnIP(ip, port) {
|
||||
return false
|
||||
}
|
||||
return !listenOnLocalhost || isPortAvailable(port)
|
||||
}
|
||||
|
||||
// findAvailablePortOnIP finds the next available port on a specific IP starting from the given port
|
||||
// It skips any ports that are in the reservedPorts map (for gRPC port collision avoidance)
|
||||
// It returns the first available port found within maxAttempts, or 0 if none found
|
||||
func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPorts map[int]bool) int {
|
||||
func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPorts map[int]bool, listenOnLocalhost bool) int {
|
||||
for i := 0; i < maxAttempts; i++ {
|
||||
port := startPort + i
|
||||
if port > 65535 {
|
||||
@@ -836,7 +846,7 @@ func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPo
|
||||
continue
|
||||
}
|
||||
// Check on both the specific IP and on all interfaces for maximum reliability
|
||||
if isPortOpenOnIP(ip, port) && isPortAvailable(port) {
|
||||
if isPortUsableOnIP(ip, port, listenOnLocalhost) {
|
||||
return port
|
||||
}
|
||||
}
|
||||
@@ -847,7 +857,7 @@ func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPo
|
||||
// ensurePortAvailableOnIP ensures a port pointer points to an available port on a specific IP
|
||||
// If the port is not available, it finds the next available port and updates the pointer
|
||||
// The reservedPorts map contains ports that should not be allocated (for gRPC collision avoidance)
|
||||
func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reservedPorts map[int]bool, flagName string) error {
|
||||
func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reservedPorts map[int]bool, flagName string, listenOnLocalhost bool) error {
|
||||
// Check if this port was explicitly specified by the user (from CLI or env, before the config file was applied)
|
||||
isExplicitPort := explicitFlags[flagName]
|
||||
|
||||
@@ -863,7 +873,7 @@ func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reserv
|
||||
return fmt.Errorf("port %d for %s (specified by flag %s) is reserved for gRPC calculation and cannot be used", original, serviceName, flagName)
|
||||
}
|
||||
glog.Warningf("Port %d for %s is reserved for gRPC calculation, finding alternative...", original, serviceName)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts, listenOnLocalhost)
|
||||
if newPort == 0 {
|
||||
glog.Errorf("Could not find available port for %s starting from %d, will use original %d and fail on binding", serviceName, original+1, original)
|
||||
} else {
|
||||
@@ -874,14 +884,14 @@ func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reserv
|
||||
}
|
||||
|
||||
// Check on both the specific IP and on all interfaces (0.0.0.0) for maximum reliability
|
||||
if !isPortOpenOnIP(ip, original) || !isPortAvailable(original) {
|
||||
if !isPortUsableOnIP(ip, original, listenOnLocalhost) {
|
||||
// If explicitly specified, fail immediately with the originally requested port
|
||||
if isExplicitPort {
|
||||
return fmt.Errorf("port %d for %s (specified by flag %s) is not available on %s and cannot be used", original, serviceName, flagName, ip)
|
||||
}
|
||||
// For default ports, try to find an alternative
|
||||
glog.Warningf("Port %d for %s is not available on %s, finding alternative port...", original, serviceName, ip)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts, listenOnLocalhost)
|
||||
if newPort == 0 {
|
||||
glog.Errorf("Could not find available port for %s starting from %d, will use original %d and fail on binding", serviceName, original+1, original)
|
||||
} else {
|
||||
@@ -897,53 +907,61 @@ func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reserv
|
||||
// ensureAllPortsAvailableOnIP ensures all mini service ports are available on a specific IP
|
||||
// Returns an error if an explicitly specified port is unavailable.
|
||||
// This should be called before starting any services
|
||||
func ensureAllPortsAvailableOnIP(bindIp string) error {
|
||||
func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
|
||||
portConfigs := []struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{
|
||||
{miniMasterOptions.port, "Master", "master.port", miniMasterOptions.portGrpc},
|
||||
{miniFilerOptions.port, "Filer", "filer.port", miniFilerOptions.portGrpc},
|
||||
{miniOptions.v.port, "Volume", "volume.port", miniOptions.v.portGrpc},
|
||||
{miniMasterOptions.port, "Master", "master.port", miniMasterOptions.portGrpc, listenOnLocalhost},
|
||||
{miniFilerOptions.port, "Filer", "filer.port", miniFilerOptions.portGrpc, listenOnLocalhost},
|
||||
{miniOptions.v.port, "Volume", "volume.port", miniOptions.v.portGrpc, listenOnLocalhost},
|
||||
}
|
||||
if *miniEnableS3 {
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniS3Options.port, "S3", "s3.port", miniS3Options.portGrpc})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniS3Options.port, "S3", "s3.port", miniS3Options.portGrpc, listenOnLocalhost})
|
||||
if miniS3Options.portIceberg != nil && *miniS3Options.portIceberg > 0 {
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniS3Options.portIceberg, "Iceberg", "s3.port.iceberg", nil})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniS3Options.portIceberg, "Iceberg", "s3.port.iceberg", nil, listenOnLocalhost})
|
||||
}
|
||||
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniS3Options.portLance, "Lance", "s3.port.lance", nil})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniS3Options.portLance, "Lance", "s3.port.lance", nil, listenOnLocalhost})
|
||||
}
|
||||
}
|
||||
// WebDAV and the Admin UI bind only -ip.bind; they never open a loopback
|
||||
// companion listener, so ports held elsewhere cannot collide with them.
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniWebDavOptions.port, "WebDAV", "webdav.port", nil},
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniWebDavOptions.port, "WebDAV", "webdav.port", nil, false},
|
||||
struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniAdminOptions.port, "Admin", "admin.port", miniAdminOptions.grpcPort})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniAdminOptions.port, "Admin", "admin.port", miniAdminOptions.grpcPort, false})
|
||||
|
||||
// First, reserve all gRPC ports that will be calculated to prevent HTTP port allocation from using them
|
||||
// This prevents collisions like: HTTP port moves to X, then gRPC port is calculated as Y where Y == X
|
||||
@@ -956,13 +974,20 @@ func ensureAllPortsAvailableOnIP(bindIp string) error {
|
||||
}
|
||||
}
|
||||
|
||||
applyMiniAdminCredentialFallback(&miniAdminOptions)
|
||||
adminBindIP := miniAdminEffectiveBindIP(bindIp)
|
||||
|
||||
// Check all HTTP ports sequentially to avoid race conditions
|
||||
// Each port check and allocation must complete before the next one starts
|
||||
// to prevent multiple goroutines from claiming the same available port
|
||||
// Also avoid allocating ports that are reserved for gRPC calculation
|
||||
for _, config := range portConfigs {
|
||||
checkIP := bindIp
|
||||
if config.name == "Admin" {
|
||||
checkIP = adminBindIP
|
||||
}
|
||||
original := *config.port
|
||||
if err := ensurePortAvailableOnIP(config.port, config.name, bindIp, reservedPorts, config.flagName); err != nil {
|
||||
if err := ensurePortAvailableOnIP(config.port, config.name, checkIP, reservedPorts, config.flagName, config.localhost); err != nil {
|
||||
return err
|
||||
}
|
||||
// If port was changed, update the reserved gRPC ports mapping
|
||||
@@ -975,7 +1000,7 @@ func ensureAllPortsAvailableOnIP(bindIp string) error {
|
||||
// Initialize all gRPC ports before services start
|
||||
// This ensures they won't be recalculated and cause conflicts
|
||||
// All gRPC port handling (calculation, validation, and assignment) is performed exclusively in initializeGrpcPortsOnIP
|
||||
allocatedPorts := initializeGrpcPortsOnIP(bindIp)
|
||||
allocatedPorts := initializeGrpcPortsOnIP(bindIp, listenOnLocalhost)
|
||||
|
||||
// Every other service binds within a moment of this check, but the admin
|
||||
// waits for all of them first. The admin gRPC port sits inside the Linux
|
||||
@@ -1054,7 +1079,7 @@ func listenMiniAdminWorker(bindIP string, port int) (net.Listener, error) {
|
||||
// This must be called after HTTP ports are finalized and before services start
|
||||
// Returns the set of ports allocated to mini services, for callers that must
|
||||
// keep optional listeners from stealing them.
|
||||
func initializeGrpcPortsOnIP(bindIp string) map[int]bool {
|
||||
func initializeGrpcPortsOnIP(bindIp string, listenOnLocalhost bool) map[int]bool {
|
||||
// Track all ports allocated (both HTTP and gRPC) to prevent collisions.
|
||||
// We must reserve HTTP ports so that gRPC fallback allocation never picks
|
||||
// a port already assigned to an HTTP service (which hasn't bound yet).
|
||||
@@ -1077,26 +1102,34 @@ func initializeGrpcPortsOnIP(bindIp string) map[int]bool {
|
||||
}
|
||||
|
||||
grpcConfigs := []struct {
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
ip string
|
||||
localhost bool
|
||||
}{
|
||||
{miniMasterOptions.port, miniMasterOptions.portGrpc, "Master"},
|
||||
{miniFilerOptions.port, miniFilerOptions.portGrpc, "Filer"},
|
||||
{miniOptions.v.port, miniOptions.v.portGrpc, "Volume"},
|
||||
{miniMasterOptions.port, miniMasterOptions.portGrpc, "Master", bindIp, listenOnLocalhost},
|
||||
{miniFilerOptions.port, miniFilerOptions.portGrpc, "Filer", bindIp, listenOnLocalhost},
|
||||
{miniOptions.v.port, miniOptions.v.portGrpc, "Volume", bindIp, listenOnLocalhost},
|
||||
}
|
||||
if *miniEnableS3 {
|
||||
grpcConfigs = append(grpcConfigs, struct {
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
}{miniS3Options.port, miniS3Options.portGrpc, "S3"})
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
ip string
|
||||
localhost bool
|
||||
}{miniS3Options.port, miniS3Options.portGrpc, "S3", bindIp, listenOnLocalhost})
|
||||
}
|
||||
// The Admin worker gRPC binds workerGrpcBindIp (loopback by default), not
|
||||
// -ip.bind, and never opens a companion listener.
|
||||
grpcConfigs = append(grpcConfigs, struct {
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
}{miniAdminOptions.port, miniAdminOptions.grpcPort, "Admin"})
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
ip string
|
||||
localhost bool
|
||||
}{miniAdminOptions.port, miniAdminOptions.grpcPort, "Admin", miniAdminOptions.workerGrpcBindIp, false})
|
||||
|
||||
for _, config := range grpcConfigs {
|
||||
if config.grpcPort == nil {
|
||||
@@ -1110,10 +1143,10 @@ func initializeGrpcPortsOnIP(bindIp string) map[int]bool {
|
||||
|
||||
// Verify the gRPC port is available (whether calculated or explicitly set)
|
||||
// Check on both specific IP and all interfaces, and check against already allocated ports
|
||||
if !isPortOpenOnIP(bindIp, *config.grpcPort) || !isPortAvailable(*config.grpcPort) || allocatedPorts[*config.grpcPort] {
|
||||
if !isPortUsableOnIP(config.ip, *config.grpcPort, config.localhost) || allocatedPorts[*config.grpcPort] {
|
||||
glog.Warningf("gRPC port %d for %s is not available, finding alternative...", *config.grpcPort, config.name)
|
||||
originalPort := *config.grpcPort
|
||||
newPort := findAvailablePortOnIP(bindIp, originalPort+1, 100, allocatedPorts)
|
||||
newPort := findAvailablePortOnIP(config.ip, originalPort+1, 100, allocatedPorts, config.localhost)
|
||||
if newPort == 0 {
|
||||
glog.Errorf("Could not find available gRPC port for %s starting from %d, will use %d and fail on binding", config.name, originalPort+1, originalPort)
|
||||
} else {
|
||||
@@ -1404,8 +1437,14 @@ func runMini(cmd *Command, args []string) bool {
|
||||
miniAdminOptions.workerGrpcBindIp = "127.0.0.1"
|
||||
}
|
||||
|
||||
// Services keep the loopback companion listener only while -ip.bind is
|
||||
// unset and the bind address falls back to -ip. While it is on, each
|
||||
// service port must be free on every interface, not just bindIp. This
|
||||
// must be captured before *miniBindIp is filled in below.
|
||||
listenOnLocalhost := *miniBindIp == "" && !util.IsLoopbackOrWildcardAddress(bindIp)
|
||||
|
||||
// Ensure all ports are available, find alternatives if needed
|
||||
if err := ensureAllPortsAvailableOnIP(bindIp); err != nil {
|
||||
if err := ensureAllPortsAvailableOnIP(bindIp, listenOnLocalhost); err != nil {
|
||||
glog.Errorf("Port allocation failed: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -1430,14 +1469,18 @@ func runMini(cmd *Command, args []string) bool {
|
||||
// ip address
|
||||
miniMasterOptions.ip = miniIp
|
||||
miniMasterOptions.ipBind = miniBindIp
|
||||
miniMasterOptions.listenOnLocalhost = &listenOnLocalhost
|
||||
miniFilerOptions.masters = pb.ServerAddresses(actualPeersForComponents).ToServiceDiscovery()
|
||||
miniFilerOptions.ip = miniIp
|
||||
miniFilerOptions.bindIp = miniBindIp
|
||||
miniFilerOptions.listenOnLocalhost = &listenOnLocalhost
|
||||
miniS3Options.ip = miniIp
|
||||
miniS3Options.bindIp = miniBindIp
|
||||
miniS3Options.listenOnLocalhost = &listenOnLocalhost
|
||||
miniWebDavOptions.ipBind = miniBindIp
|
||||
miniOptions.v.ip = miniIp
|
||||
miniOptions.v.bindIp = miniBindIp
|
||||
miniOptions.v.listenOnLocalhost = &listenOnLocalhost
|
||||
miniOptions.v.masters = pb.ServerAddresses(actualPeersForComponents).ToAddresses()
|
||||
miniOptions.v.idleConnectionTimeout = miniTimeout
|
||||
// Admin server binds to the same address as the other mini services.
|
||||
@@ -1776,6 +1819,14 @@ func miniAdminBindIP(requestedIP string, passwordConfigured, mtlsConfigured, all
|
||||
return "127.0.0.1"
|
||||
}
|
||||
|
||||
func miniAdminEffectiveBindIP(requestedIP string) string {
|
||||
hasMTLS := util.GetViper().GetString("https.admin.key") != "" &&
|
||||
util.GetViper().GetString("https.admin.ca") != ""
|
||||
allowInsecure := miniAdminOptions.allowInsecureBind != nil &&
|
||||
*miniAdminOptions.allowInsecureBind
|
||||
return miniAdminBindIP(requestedIP, *miniAdminOptions.adminPassword != "", hasMTLS, allowInsecure)
|
||||
}
|
||||
|
||||
// miniAdminWorkerAddress encodes the finalized HTTP and gRPC ports in the
|
||||
// server-address format understood by pb.ServerToGrpcAddress.
|
||||
func miniAdminWorkerAddress(bindIP string, httpPort, grpcPort int) string {
|
||||
@@ -1833,16 +1884,11 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
applyMiniAdminCredentialFallback(&miniAdminOptions)
|
||||
|
||||
requestedBindIP := getBindIp()
|
||||
bindIP := miniAdminEffectiveBindIP(requestedBindIP)
|
||||
hasMTLS := util.GetViper().GetString("https.admin.key") != "" &&
|
||||
util.GetViper().GetString("https.admin.ca") != ""
|
||||
allowInsecure := miniAdminOptions.allowInsecureBind != nil &&
|
||||
*miniAdminOptions.allowInsecureBind
|
||||
bindIP := miniAdminBindIP(
|
||||
requestedBindIP,
|
||||
*miniAdminOptions.adminPassword != "",
|
||||
hasMTLS,
|
||||
allowInsecure,
|
||||
)
|
||||
miniAdminOptions.ip = &bindIP
|
||||
if bindIP != requestedBindIP {
|
||||
glog.Warningf(
|
||||
|
||||
@@ -17,17 +17,20 @@ var (
|
||||
)
|
||||
|
||||
type MessageQueueAgentOptions struct {
|
||||
brokers []pb.ServerAddress
|
||||
brokersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
port *int
|
||||
brokers []pb.ServerAddress
|
||||
brokersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdMqAgent.Run = runMqAgent // break init cycle
|
||||
mqAgentOptions.brokersString = cmdMqAgent.Flag.String("broker", "localhost:17777", "comma-separated message queue brokers")
|
||||
mqAgentOptions.ip = cmdMqAgent.Flag.String("ip", "", "message queue agent host address")
|
||||
mqAgentOptions.ipBind = cmdMqAgent.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
mqAgentOptions.port = cmdMqAgent.Flag.Int("port", 16777, "message queue agent gRPC server port")
|
||||
}
|
||||
|
||||
@@ -60,8 +63,20 @@ func (mqAgentOpt *MessageQueueAgentOptions) startQueueAgent() bool {
|
||||
SeedBrokers: mqAgentOpt.brokers,
|
||||
}, grpcDialOption)
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset and
|
||||
// the bind address falls back to -ip. An explicit -ip.bind pins the port to
|
||||
// exactly that address.
|
||||
bindIp := *mqAgentOpt.ip
|
||||
listenOnLocalhost := mqAgentOpt.ipBind == nil || *mqAgentOpt.ipBind == ""
|
||||
if mqAgentOpt.ipBind != nil && *mqAgentOpt.ipBind != "" {
|
||||
bindIp = *mqAgentOpt.ipBind
|
||||
}
|
||||
if mqAgentOpt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *mqAgentOpt.listenOnLocalhost
|
||||
}
|
||||
|
||||
// start grpc listener
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners(*mqAgentOpt.ip, *mqAgentOpt.port, 0)
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners(bindIp, *mqAgentOpt.port, 0, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", *mqAgentOpt.port, err)
|
||||
}
|
||||
@@ -84,7 +99,7 @@ func (mqAgentOpt *MessageQueueAgentOptions) startQueueAgent() bool {
|
||||
}()
|
||||
}
|
||||
|
||||
glog.Infof("Start Seaweed Message Queue Agent on %s:%d", *mqAgentOpt.ip, *mqAgentOpt.port)
|
||||
glog.Infof("Start Seaweed Message Queue Agent on %s:%d", bindIp, *mqAgentOpt.port)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("MQ Agent failed to start: %v", err)
|
||||
}
|
||||
|
||||
+24
-14
@@ -18,18 +18,20 @@ var (
|
||||
)
|
||||
|
||||
type MessageQueueBrokerOptions struct {
|
||||
masters map[string]pb.ServerAddress
|
||||
mastersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
port *int
|
||||
dataCenter *string
|
||||
rack *string
|
||||
cpuprofile *string
|
||||
memprofile *string
|
||||
logFlushInterval *int
|
||||
debug *bool
|
||||
debugPort *int
|
||||
masters map[string]pb.ServerAddress
|
||||
mastersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
dataCenter *string
|
||||
rack *string
|
||||
cpuprofile *string
|
||||
memprofile *string
|
||||
logFlushInterval *int
|
||||
debug *bool
|
||||
debugPort *int
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -37,6 +39,7 @@ func init() {
|
||||
mqBrokerStandaloneOptions.mastersString = cmdMqBroker.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
mqBrokerStandaloneOptions.filerGroup = cmdMqBroker.Flag.String("filerGroup", "", "share metadata with other filers in the same filerGroup")
|
||||
mqBrokerStandaloneOptions.ip = cmdMqBroker.Flag.String("ip", util.DetectedHostAddress(), "broker host address")
|
||||
mqBrokerStandaloneOptions.ipBind = cmdMqBroker.Flag.String("ip.bind", "", "ip address to bind to. If empty, listen on all interfaces.")
|
||||
mqBrokerStandaloneOptions.port = cmdMqBroker.Flag.Int("port", 17777, "broker gRPC listen port")
|
||||
mqBrokerStandaloneOptions.dataCenter = cmdMqBroker.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
|
||||
mqBrokerStandaloneOptions.rack = cmdMqBroker.Flag.String("rack", "", "prefer to write to volumes in this rack")
|
||||
@@ -94,8 +97,15 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
glog.Fatalf("failed to create new message broker for queue server: %v", err)
|
||||
}
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset.
|
||||
// An explicit -ip.bind pins the port to exactly that address.
|
||||
listenOnLocalhost := *mqBrokerOpt.ipBind == ""
|
||||
if mqBrokerOpt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *mqBrokerOpt.listenOnLocalhost
|
||||
}
|
||||
|
||||
// start grpc listener
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners("", *mqBrokerOpt.port, 0)
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners(*mqBrokerOpt.ipBind, *mqBrokerOpt.port, 0, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", *mqBrokerOpt.port, err)
|
||||
}
|
||||
@@ -118,7 +128,7 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
}()
|
||||
}
|
||||
|
||||
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ip, *mqBrokerOpt.port)
|
||||
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ipBind, *mqBrokerOpt.port)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("Failed to serve MQ Broker: %v", err)
|
||||
}
|
||||
|
||||
+16
-9
@@ -46,6 +46,7 @@ type S3Options struct {
|
||||
filer *string
|
||||
ip *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
portHttps *int
|
||||
portGrpc *int
|
||||
@@ -359,6 +360,12 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
if *s3opt.portGrpc == 0 {
|
||||
*s3opt.portGrpc = 10000 + *s3opt.port
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset.
|
||||
// An explicit -ip.bind pins each port to exactly that address.
|
||||
listenOnLocalhost := *s3opt.bindIp == ""
|
||||
if s3opt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *s3opt.listenOnLocalhost
|
||||
}
|
||||
if *s3opt.bindIp == "" {
|
||||
*s3opt.bindIp = "0.0.0.0"
|
||||
}
|
||||
@@ -414,14 +421,14 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
// Start Iceberg REST Catalog server if enabled
|
||||
if *s3opt.portIceberg > 0 {
|
||||
if httpS := s3opt.startIcebergServer(s3ApiServer); httpS != nil {
|
||||
if httpS := s3opt.startIcebergServer(s3ApiServer, listenOnLocalhost); httpS != nil {
|
||||
httpServers = append(httpServers, httpS)
|
||||
}
|
||||
}
|
||||
|
||||
// Start Lance Namespace server if enabled
|
||||
if s3opt.portLance != nil && *s3opt.portLance > 0 {
|
||||
if httpS := s3opt.startLanceServer(s3ApiServer); httpS != nil {
|
||||
if httpS := s3opt.startLanceServer(s3ApiServer, listenOnLocalhost); httpS != nil {
|
||||
httpServers = append(httpServers, httpS)
|
||||
}
|
||||
}
|
||||
@@ -445,7 +452,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.port)
|
||||
s3ApiListener, s3ApiLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.port, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
*s3opt.bindIp, *s3opt.port, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
@@ -459,7 +466,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
// starting grpc server
|
||||
grpcPort := *s3opt.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*s3opt.bindIp, grpcPort, 0)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*s3opt.bindIp, grpcPort, 0, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("s3 failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
@@ -532,7 +539,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
} else {
|
||||
glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", version.Version(), *s3opt.portHttps)
|
||||
s3ApiListenerHttps, s3ApiLocalListenerHttps, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portHttps, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
*s3opt.bindIp, *s3opt.portHttps, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API HTTPS listener on %s:%d error: %v", *s3opt.bindIp, *s3opt.portHttps, err)
|
||||
}
|
||||
@@ -592,7 +599,7 @@ func (s3opt *S3Options) newShutdown(stopGrpc func(), s3ApiServer *s3api.S3ApiSer
|
||||
}
|
||||
|
||||
// startIcebergServer starts the Iceberg REST Catalog server on a separate port.
|
||||
func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) *http.Server {
|
||||
func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer, listenOnLocalhost bool) *http.Server {
|
||||
icebergRouter := mux.NewRouter().SkipClean(true)
|
||||
// warehouse/parent query values may legally contain ';', which Go's
|
||||
// url.ParseQuery would otherwise drop
|
||||
@@ -614,7 +621,7 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) *http
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portIceberg)
|
||||
icebergListener, icebergLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portIceberg, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
*s3opt.bindIp, *s3opt.portIceberg, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
if err != nil {
|
||||
// The catalog is auxiliary to the S3 gateway; a port conflict must not
|
||||
// take the whole server down.
|
||||
@@ -645,7 +652,7 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) *http
|
||||
// startLanceServer starts the Lance Namespace server on a separate port. It
|
||||
// shares the Iceberg catalog's credential role: one deployment vends table
|
||||
// credentials one way, whichever catalog the client speaks to.
|
||||
func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer) *http.Server {
|
||||
func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer, listenOnLocalhost bool) *http.Server {
|
||||
lanceRouter := mux.NewRouter().SkipClean(true)
|
||||
lanceRouter.Use(util_http.EscapeSemicolonsInQuery)
|
||||
|
||||
@@ -660,7 +667,7 @@ func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer) *http.S
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portLance)
|
||||
lanceListener, lanceLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portLance, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
*s3opt.bindIp, *s3opt.portLance, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Errorf("Lance Namespace listener on %s error: %v", listenAddress, err)
|
||||
return nil
|
||||
|
||||
@@ -42,14 +42,14 @@ func TestAuxListenerBindFailureIsNonFatal(t *testing.T) {
|
||||
}
|
||||
s3a := &s3api.S3ApiServer{}
|
||||
|
||||
if s := s3opt.startIcebergServer(s3a); s != nil {
|
||||
if s := s3opt.startIcebergServer(s3a, false); s != nil {
|
||||
s.Close()
|
||||
t.Error("startIcebergServer on an occupied port should return nil")
|
||||
}
|
||||
if s3opt.icebergBound.Load() {
|
||||
t.Error("icebergBound must stay false when the listener failed to bind")
|
||||
}
|
||||
if s := s3opt.startLanceServer(s3a); s != nil {
|
||||
if s := s3opt.startLanceServer(s3a, false); s != nil {
|
||||
s.Close()
|
||||
t.Error("startLanceServer on an occupied port should return nil")
|
||||
}
|
||||
|
||||
@@ -69,6 +69,9 @@
|
||||
# volume-slot deadband for shard placement: nodes whose free volume slots differ by at
|
||||
# most this much tie and fewer live shards wins; applied times data shards (0 = strict)
|
||||
# free_slots_deadband = 0
|
||||
# shard copy concurrency. Leave unset for one in-flight copy per destination disk.
|
||||
# 0 sends shards sequentially. A positive N is a global cap, still one per disk.
|
||||
# max_shard_transfers = 4
|
||||
# max retry attempts for a failed erasure coding job
|
||||
# retry_limit = 1
|
||||
# seconds to wait between retry attempts
|
||||
|
||||
@@ -63,6 +63,11 @@ copy_other = 1 # create n x 1 = n actual volumes
|
||||
threshold = 0.9 # create threshold
|
||||
reservation_timeout = "5m"# capacity reservation timeout before unreleased reservations expire
|
||||
disable = false # disables volume growth if true
|
||||
# allocation_deferral = "15s" # hold the first volume id allocation after a fresh
|
||||
# topology id is minted, giving a rebuilt master's
|
||||
# veteran volume servers time to report. The hold
|
||||
# lifts early once heartbeats stay clean for two
|
||||
# pulses. "0s" disables it (e.g. test setups).
|
||||
|
||||
# configuration flags for replication
|
||||
[master.replication]
|
||||
|
||||
+38
-1
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/grace"
|
||||
)
|
||||
|
||||
@@ -240,6 +241,17 @@ func init() {
|
||||
|
||||
}
|
||||
|
||||
// isServerFlagPassed checks if a specific flag was passed on the command line
|
||||
func isServerFlagPassed(name string) bool {
|
||||
found := false
|
||||
cmdServer.Flag.Visit(func(f *flag.Flag) {
|
||||
if f.Name == name {
|
||||
found = true
|
||||
}
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func runServer(cmd *Command, args []string) bool {
|
||||
|
||||
if *serverOptions.debug {
|
||||
@@ -293,6 +305,11 @@ func runServer(cmd *Command, args []string) bool {
|
||||
actualPeersForComponents = *masterOptions.peers
|
||||
}
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset and
|
||||
// the bind address falls back to -ip. Capture that here: serverBindIp is
|
||||
// repointed at serverIp below, after which the flag state is no longer
|
||||
// distinguishable.
|
||||
ipBindUnspecified := *serverBindIp == ""
|
||||
if *serverBindIp == "" {
|
||||
serverBindIp = serverIp
|
||||
}
|
||||
@@ -307,31 +324,51 @@ func runServer(cmd *Command, args []string) bool {
|
||||
// ip address
|
||||
masterOptions.ip = serverIp
|
||||
masterOptions.ipBind = serverBindIp
|
||||
masterOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
// Use actualPeersForComponents for volume/filer, not masterOptions.peers which might be "none"
|
||||
filerOptions.masters = pb.ServerAddresses(actualPeersForComponents).ToServiceDiscovery()
|
||||
filerOptions.ip = serverIp
|
||||
filerOptions.bindIp = serverBindIp
|
||||
filerOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
s3Options.ip = serverIp
|
||||
if *s3Options.bindIp == "" {
|
||||
s3Options.listenOnLocalhost = &ipBindUnspecified
|
||||
s3Options.bindIp = serverBindIp
|
||||
}
|
||||
if sftpOptions.bindIp == nil || *sftpOptions.bindIp == "" {
|
||||
sftpOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
sftpOptions.bindIp = serverBindIp
|
||||
}
|
||||
iamOptions.ip = serverBindIp
|
||||
iamOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
iamOptions.masters = &actualPeersForComponents
|
||||
webdavOptions.ipBind = serverBindIp
|
||||
serverOptions.v.ip = serverIp
|
||||
serverOptions.v.bindIp = serverBindIp
|
||||
serverOptions.v.listenOnLocalhost = &ipBindUnspecified
|
||||
serverOptions.v.masters = pb.ServerAddresses(actualPeersForComponents).ToAddresses()
|
||||
serverOptions.v.idleConnectionTimeout = serverTimeout
|
||||
serverOptions.v.dataCenter = serverDataCenter
|
||||
serverOptions.v.rack = serverRack
|
||||
mqBrokerOptions.ip = serverIp
|
||||
mqBrokerOptions.ipBind = serverBindIp
|
||||
mqBrokerOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
mqBrokerOptions.masters = filerOptions.masters.GetInstancesAsMap()
|
||||
mqBrokerOptions.filerGroup = filerOptions.filerGroup
|
||||
mqAgentServerOptions.ip = serverIp
|
||||
mqAgentServerOptions.brokers = pb.ServerAddresses(*mqAgentServerOptions.brokersString).ToAddresses()
|
||||
mqAgentServerOptions.ipBind = serverBindIp
|
||||
mqAgentServerOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
if isServerFlagPassed("mq.agent.brokers") {
|
||||
mqAgentServerOptions.brokers = pb.ServerAddresses(*mqAgentServerOptions.brokersString).ToAddresses()
|
||||
} else {
|
||||
// Default to the embedded broker's bind address: with an explicit
|
||||
// -ip.bind the broker does not listen on localhost.
|
||||
brokerHost := *serverBindIp
|
||||
if brokerHost == "0.0.0.0" || brokerHost == "::" || brokerHost == "[::]" {
|
||||
brokerHost = "localhost"
|
||||
}
|
||||
mqAgentServerOptions.brokers = []pb.ServerAddress{pb.NewServerAddress(brokerHost, *mqBrokerOptions.port, 0)}
|
||||
}
|
||||
|
||||
// serverOptions.v.pulseSeconds = pulseSeconds
|
||||
// masterOptions.pulseSeconds = pulseSeconds
|
||||
|
||||
@@ -25,6 +25,7 @@ var (
|
||||
type SftpOptions struct {
|
||||
filer *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
sshPrivateKey *string
|
||||
hostKeysFolder *string
|
||||
@@ -105,6 +106,12 @@ func (sftpOpt *SftpOptions) resolvePaths() {
|
||||
}
|
||||
|
||||
func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
// The loopback companion listener is only kept while -ip.bind is unset.
|
||||
// An explicit -ip.bind pins the port to exactly that address.
|
||||
listenOnLocalhost := *sftpOpt.bindIp == ""
|
||||
if sftpOpt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *sftpOpt.listenOnLocalhost
|
||||
}
|
||||
if *sftpOpt.bindIp == "" {
|
||||
*sftpOpt.bindIp = "0.0.0.0"
|
||||
}
|
||||
@@ -194,7 +201,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
|
||||
// Start the SFTP service on TCP
|
||||
listenAddress := fmt.Sprintf("%s:%d", *sftpOpt.bindIp, *sftpOpt.port)
|
||||
sftpListener, sftpLocalListener, err := util.NewIpAndLocalListeners(*sftpOpt.bindIp, *sftpOpt.port, time.Duration(10)*time.Second)
|
||||
sftpListener, sftpLocalListener, err := util.NewIpAndLocalListeners(*sftpOpt.bindIp, *sftpOpt.port, time.Duration(10)*time.Second, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("SFTP server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
+17
-9
@@ -45,6 +45,7 @@ type VolumeServerOptions struct {
|
||||
id *string
|
||||
publicUrl *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
mastersString *string
|
||||
mserverString *string // deprecated, for backward compatibility
|
||||
masters []pb.ServerAddress
|
||||
@@ -397,6 +398,13 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
*v.ip = util.DetectedHostAddress()
|
||||
glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset
|
||||
// and the bind address falls back to -ip. An explicit -ip.bind pins each
|
||||
// port to exactly that address.
|
||||
listenOnLocalhost := *v.bindIp == ""
|
||||
if v.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *v.listenOnLocalhost
|
||||
}
|
||||
if *v.bindIp == "" {
|
||||
*v.bindIp = *v.ip
|
||||
}
|
||||
@@ -485,19 +493,19 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
v.syncBatchOption(),
|
||||
)
|
||||
// starting grpc server
|
||||
grpcS := v.startGrpcService(volumeServer)
|
||||
grpcS := v.startGrpcService(volumeServer, listenOnLocalhost)
|
||||
|
||||
// starting public http server
|
||||
var publicHttpDown httpdown.Server
|
||||
if v.isSeparatedPublicPort() {
|
||||
publicHttpDown = v.startPublicHttpService(publicVolumeMux)
|
||||
publicHttpDown = v.startPublicHttpService(publicVolumeMux, listenOnLocalhost)
|
||||
if nil == publicHttpDown {
|
||||
glog.Fatalf("start public http service failed")
|
||||
}
|
||||
}
|
||||
|
||||
// starting the cluster http server
|
||||
clusterHttpServer, closeCert := v.startClusterHttpService(volumeMux)
|
||||
clusterHttpServer, closeCert := v.startClusterHttpService(volumeMux, listenOnLocalhost)
|
||||
|
||||
grace.OnReload(volumeServer.LoadNewVolumes)
|
||||
grace.OnReload(volumeServer.Reload)
|
||||
@@ -632,9 +640,9 @@ func (m multiHttpdownServer) Stop() error {
|
||||
return firstErr
|
||||
}
|
||||
|
||||
func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
|
||||
func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer, listenOnLocalhost bool) *grpc.Server {
|
||||
grpcPort := *v.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*v.bindIp, grpcPort, 0)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*v.bindIp, grpcPort, 0, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
@@ -653,10 +661,10 @@ func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerSe
|
||||
return grpcS
|
||||
}
|
||||
|
||||
func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
|
||||
func (v VolumeServerOptions) startPublicHttpService(handler http.Handler, listenOnLocalhost bool) httpdown.Server {
|
||||
publicListeningAddress := util.JoinHostPort(*v.bindIp, *v.publicPort)
|
||||
glog.V(0).Infoln("Start Seaweed volume server", version.Version(), "public at", publicListeningAddress)
|
||||
publicListener, publicLocalListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.publicPort, time.Duration(*v.idleConnectionTimeout)*time.Second)
|
||||
publicListener, publicLocalListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.publicPort, time.Duration(*v.idleConnectionTimeout)*time.Second, listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Volume server listener error:%v", e)
|
||||
}
|
||||
@@ -681,7 +689,7 @@ func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdo
|
||||
// for invoking the close func on every shutdown path — both the
|
||||
// SIGTERM/grace.OnInterrupt path and the shutdownCtx path used by
|
||||
// mini/integration tests.
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) (httpdown.Server, func()) {
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler, listenOnLocalhost bool) (httpdown.Server, func()) {
|
||||
var (
|
||||
certFile, keyFile string
|
||||
)
|
||||
@@ -692,7 +700,7 @@ func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) (http
|
||||
|
||||
listeningAddress := util.JoinHostPort(*v.bindIp, *v.port)
|
||||
glog.V(0).Infof("Start Seaweed volume server %s at %s", version.Version(), listeningAddress)
|
||||
listener, localListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.port, time.Duration(*v.idleConnectionTimeout)*time.Second)
|
||||
listener, localListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.port, time.Duration(*v.idleConnectionTimeout)*time.Second, listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Volume server listener error:%v", e)
|
||||
}
|
||||
|
||||
@@ -849,13 +849,14 @@ func staticOIDCProviderRecords(stsConfig *sts.STSConfig) map[string]*OIDCProvide
|
||||
continue
|
||||
}
|
||||
out[arn] = &OIDCProviderRecord{
|
||||
AccountID: stsConfig.AccountId,
|
||||
ARN: arn,
|
||||
URL: issuer,
|
||||
ClientIDs: extractClientIDs(pc.Config),
|
||||
Thumbprints: extractStringList(pc.Config, "thumbprints"),
|
||||
AllowedPrincipalTagKeys: extractStringList(pc.Config, "allowedPrincipalTagKeys"),
|
||||
PolicyClaim: extractString(pc.Config, "policyClaim"),
|
||||
AccountID: stsConfig.AccountId,
|
||||
ARN: arn,
|
||||
URL: issuer,
|
||||
ClientIDs: extractClientIDs(pc.Config),
|
||||
Thumbprints: extractStringList(pc.Config, "thumbprints"),
|
||||
AllowedPrincipalTagKeys: extractStringList(pc.Config, "allowedPrincipalTagKeys"),
|
||||
PolicyClaim: extractString(pc.Config, "policyClaim"),
|
||||
JTIReplayProtectionEnabled: extractBool(pc.Config, sts.ConfigFieldJTIReplayProtectionEnabled),
|
||||
// No CreatedAt: a config-file provider has no creation time the
|
||||
// server could report consistently across restarts.
|
||||
}
|
||||
@@ -1055,14 +1056,15 @@ func (m *IAMManager) oidcProviderStillReferenced(provider *oidc.OIDCProvider) bo
|
||||
// from, so a refresh rebuilds the provider only when that content changed.
|
||||
func oidcProviderFingerprint(rec *OIDCProviderRecord) string {
|
||||
key, _ := json.Marshal(struct {
|
||||
ARN string
|
||||
AccountID string
|
||||
URL string
|
||||
ClientIDs []string
|
||||
Thumbprints []string
|
||||
AllowedPrincipalTagKeys []string
|
||||
PolicyClaim string
|
||||
}{rec.ARN, rec.AccountID, rec.URL, rec.ClientIDs, rec.Thumbprints, rec.AllowedPrincipalTagKeys, rec.PolicyClaim})
|
||||
ARN string
|
||||
AccountID string
|
||||
URL string
|
||||
ClientIDs []string
|
||||
Thumbprints []string
|
||||
AllowedPrincipalTagKeys []string
|
||||
PolicyClaim string
|
||||
JTIReplayProtectionEnabled *bool
|
||||
}{rec.ARN, rec.AccountID, rec.URL, rec.ClientIDs, rec.Thumbprints, rec.AllowedPrincipalTagKeys, rec.PolicyClaim, rec.JTIReplayProtectionEnabled})
|
||||
sum := sha256.Sum256(key)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -1072,11 +1074,12 @@ func oidcProviderFingerprint(rec *OIDCProviderRecord) string {
|
||||
// record's name — so records that differ only in identity reuse one provider.
|
||||
func oidcProviderConfigFingerprint(rec *OIDCProviderRecord) string {
|
||||
key, _ := json.Marshal(&oidc.OIDCConfig{
|
||||
Issuer: rec.URL,
|
||||
ClientIDs: rec.ClientIDs,
|
||||
Thumbprints: rec.Thumbprints,
|
||||
AllowedPrincipalTagKeys: rec.AllowedPrincipalTagKeys,
|
||||
PolicyClaim: rec.PolicyClaim,
|
||||
Issuer: rec.URL,
|
||||
ClientIDs: rec.ClientIDs,
|
||||
Thumbprints: rec.Thumbprints,
|
||||
AllowedPrincipalTagKeys: rec.AllowedPrincipalTagKeys,
|
||||
PolicyClaim: rec.PolicyClaim,
|
||||
JTIReplayProtectionEnabled: rec.JTIReplayProtectionEnabled,
|
||||
})
|
||||
sum := sha256.Sum256(key)
|
||||
return hex.EncodeToString(sum[:])
|
||||
@@ -1096,6 +1099,10 @@ func buildOIDCProviderFromRecord(rec *OIDCProviderRecord) (*oidc.OIDCProvider, e
|
||||
AllowedPrincipalTagKeys: append([]string(nil), rec.AllowedPrincipalTagKeys...),
|
||||
PolicyClaim: rec.PolicyClaim,
|
||||
}
|
||||
if rec.JTIReplayProtectionEnabled != nil {
|
||||
enabled := *rec.JTIReplayProtectionEnabled
|
||||
cfg.JTIReplayProtectionEnabled = &enabled
|
||||
}
|
||||
provider := oidc.NewOIDCProvider(rec.ARN)
|
||||
if err := provider.Initialize(cfg); err != nil {
|
||||
return nil, err
|
||||
@@ -1171,6 +1178,18 @@ func extractString(cfg map[string]interface{}, key string) string {
|
||||
return s
|
||||
}
|
||||
|
||||
// extractBool reads a single bool field from the provider's static config
|
||||
// map; missing or non-bool values produce nil.
|
||||
func extractBool(cfg map[string]interface{}, key string) *bool {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
if b, ok := cfg[key].(bool); ok {
|
||||
return &b
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getFilerAddress returns the current filer address using the provider function
|
||||
func (m *IAMManager) getFilerAddress() string {
|
||||
if m.filerAddressProvider != nil {
|
||||
|
||||
@@ -649,3 +649,62 @@ func TestSameIssuerRecordsShareOneProvider(t *testing.T) {
|
||||
"a changed record kept the shared provider")
|
||||
assert.True(t, stsKnowsIssuerForAccount(t, mgr, persistTestAPIIssuer, "222222222222"))
|
||||
}
|
||||
|
||||
// The replay flag is part of what a provider is built from: two records that
|
||||
// differ only in it must not share a provider, and flipping it on a record
|
||||
// must rebuild.
|
||||
func TestOIDCProviderFingerprintsSeparateReplayFlag(t *testing.T) {
|
||||
disabled := false
|
||||
base := &OIDCProviderRecord{
|
||||
ARN: "arn:aws:iam::111111111111:oidc-provider/issuer.example", URL: "https://issuer.example",
|
||||
ClientIDs: []string{"aud"},
|
||||
}
|
||||
off := *base
|
||||
off.JTIReplayProtectionEnabled = &disabled
|
||||
|
||||
assert.NotEqual(t, oidcProviderConfigFingerprint(base), oidcProviderConfigFingerprint(&off),
|
||||
"records differing only in the replay flag share a config fingerprint")
|
||||
assert.NotEqual(t, oidcProviderFingerprint(base), oidcProviderFingerprint(&off),
|
||||
"a flipped replay flag does not rebuild the provider")
|
||||
}
|
||||
|
||||
// A config-file provider's jtiReplayProtectionEnabled rides the record into
|
||||
// the runtime build path, so a mirrored static provider keeps the flag the
|
||||
// provider factory would have applied.
|
||||
func TestStaticOIDCProviderRecordsCarryJTIReplayFlag(t *testing.T) {
|
||||
records := staticOIDCProviderRecords(&sts.STSConfig{
|
||||
AccountId: "111111111111",
|
||||
Providers: []*sts.ProviderConfig{
|
||||
{
|
||||
Name: "k8s", Type: sts.ProviderTypeOIDC, Enabled: true,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://k8s.example",
|
||||
"clientId": "sts.amazonaws.com",
|
||||
"jtiReplayProtectionEnabled": false,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "plain", Type: sts.ProviderTypeOIDC, Enabled: true,
|
||||
Config: map[string]interface{}{
|
||||
"issuer": "https://issuer.example",
|
||||
"clientId": "sts.amazonaws.com",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.Len(t, records, 2)
|
||||
|
||||
var flagged, plain *OIDCProviderRecord
|
||||
for _, rec := range records {
|
||||
if rec.URL == "https://k8s.example" {
|
||||
flagged = rec
|
||||
} else {
|
||||
plain = rec
|
||||
}
|
||||
}
|
||||
require.NotNil(t, flagged)
|
||||
require.NotNil(t, flagged.JTIReplayProtectionEnabled)
|
||||
assert.False(t, *flagged.JTIReplayProtectionEnabled)
|
||||
require.NotNil(t, plain)
|
||||
assert.Nil(t, plain.JTIReplayProtectionEnabled)
|
||||
}
|
||||
@@ -74,6 +74,10 @@ type OIDCProviderRecord struct {
|
||||
// derive their effective policies from this JWT claim.
|
||||
PolicyClaim string `json:"policyClaim,omitempty"`
|
||||
|
||||
// JTIReplayProtectionEnabled overrides the server default for this
|
||||
// provider; nil means replay protection is on.
|
||||
JTIReplayProtectionEnabled *bool `json:"jtiReplayProtectionEnabled,omitempty"`
|
||||
|
||||
// Tags is the AWS-style tag set attached to the IAM resource itself
|
||||
// (audit/inventory metadata, not propagated into sessions).
|
||||
Tags map[string]string `json:"tags,omitempty"`
|
||||
@@ -639,6 +643,10 @@ func copyOIDCProviderRecord(rec *OIDCProviderRecord) *OIDCProviderRecord {
|
||||
if rec.AllowedPrincipalTagKeys != nil {
|
||||
cp.AllowedPrincipalTagKeys = append([]string(nil), rec.AllowedPrincipalTagKeys...)
|
||||
}
|
||||
if rec.JTIReplayProtectionEnabled != nil {
|
||||
enabled := *rec.JTIReplayProtectionEnabled
|
||||
cp.JTIReplayProtectionEnabled = &enabled
|
||||
}
|
||||
if rec.Tags != nil {
|
||||
cp.Tags = make(map[string]string, len(rec.Tags))
|
||||
for k, v := range rec.Tags {
|
||||
|
||||
@@ -331,6 +331,8 @@ message OIDCProvider {
|
||||
// from it and the issuer URL.
|
||||
string account_id = 4;
|
||||
string arn = 5; // output only
|
||||
// unset means the server default (replay protection on)
|
||||
optional bool jti_replay_protection_enabled = 6;
|
||||
}
|
||||
|
||||
// PutOIDCProviderRequest creates the provider, or replaces the client IDs and
|
||||
@@ -340,6 +342,8 @@ message PutOIDCProviderRequest {
|
||||
repeated string client_ids = 2;
|
||||
repeated string thumbprints = 3;
|
||||
string account_id = 4;
|
||||
// unset keeps the stored value, or the server default on create
|
||||
optional bool jti_replay_protection_enabled = 5;
|
||||
}
|
||||
|
||||
message PutOIDCProviderResponse {
|
||||
|
||||
+39
-15
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v6.33.4
|
||||
// protoc v3.21.12
|
||||
// source: iam.proto
|
||||
|
||||
package iam_pb
|
||||
@@ -2687,10 +2687,12 @@ type OIDCProvider struct {
|
||||
Thumbprints []string `protobuf:"bytes,3,rep,name=thumbprints,proto3" json:"thumbprints,omitempty"`
|
||||
// account_id scopes the provider; empty means global. The ARN is derived
|
||||
// from it and the issuer URL.
|
||||
AccountId string `protobuf:"bytes,4,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"`
|
||||
Arn string `protobuf:"bytes,5,opt,name=arn,proto3" json:"arn,omitempty"` // output only
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
AccountId string `protobuf:"bytes,4,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"`
|
||||
Arn string `protobuf:"bytes,5,opt,name=arn,proto3" json:"arn,omitempty"` // output only
|
||||
// unset means the server default (replay protection on)
|
||||
JtiReplayProtectionEnabled *bool `protobuf:"varint,6,opt,name=jti_replay_protection_enabled,json=jtiReplayProtectionEnabled,proto3,oneof" json:"jti_replay_protection_enabled,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *OIDCProvider) Reset() {
|
||||
@@ -2758,16 +2760,25 @@ func (x *OIDCProvider) GetArn() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *OIDCProvider) GetJtiReplayProtectionEnabled() bool {
|
||||
if x != nil && x.JtiReplayProtectionEnabled != nil {
|
||||
return *x.JtiReplayProtectionEnabled
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// PutOIDCProviderRequest creates the provider, or replaces the client IDs and
|
||||
// thumbprints of an existing one.
|
||||
type PutOIDCProviderRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
IssuerUrl string `protobuf:"bytes,1,opt,name=issuer_url,json=issuerUrl,proto3" json:"issuer_url,omitempty"`
|
||||
ClientIds []string `protobuf:"bytes,2,rep,name=client_ids,json=clientIds,proto3" json:"client_ids,omitempty"`
|
||||
Thumbprints []string `protobuf:"bytes,3,rep,name=thumbprints,proto3" json:"thumbprints,omitempty"`
|
||||
AccountId string `protobuf:"bytes,4,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
IssuerUrl string `protobuf:"bytes,1,opt,name=issuer_url,json=issuerUrl,proto3" json:"issuer_url,omitempty"`
|
||||
ClientIds []string `protobuf:"bytes,2,rep,name=client_ids,json=clientIds,proto3" json:"client_ids,omitempty"`
|
||||
Thumbprints []string `protobuf:"bytes,3,rep,name=thumbprints,proto3" json:"thumbprints,omitempty"`
|
||||
AccountId string `protobuf:"bytes,4,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"`
|
||||
// unset keeps the stored value, or the server default on create
|
||||
JtiReplayProtectionEnabled *bool `protobuf:"varint,5,opt,name=jti_replay_protection_enabled,json=jtiReplayProtectionEnabled,proto3,oneof" json:"jti_replay_protection_enabled,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *PutOIDCProviderRequest) Reset() {
|
||||
@@ -2828,6 +2839,13 @@ func (x *PutOIDCProviderRequest) GetAccountId() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *PutOIDCProviderRequest) GetJtiReplayProtectionEnabled() bool {
|
||||
if x != nil && x.JtiReplayProtectionEnabled != nil {
|
||||
return *x.JtiReplayProtectionEnabled
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type PutOIDCProviderResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Arn string `protobuf:"bytes,1,opt,name=arn,proto3" json:"arn,omitempty"`
|
||||
@@ -4039,7 +4057,7 @@ const file_iam_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"access_key\x18\x01 \x01(\tR\taccessKey\"g\n" +
|
||||
"$GetServiceAccountByAccessKeyResponse\x12?\n" +
|
||||
"\x0fservice_account\x18\x01 \x01(\v2\x16.iam_pb.ServiceAccountR\x0eserviceAccount\"\x9f\x01\n" +
|
||||
"\x0fservice_account\x18\x01 \x01(\v2\x16.iam_pb.ServiceAccountR\x0eserviceAccount\"\x89\x02\n" +
|
||||
"\fOIDCProvider\x12\x1d\n" +
|
||||
"\n" +
|
||||
"issuer_url\x18\x01 \x01(\tR\tissuerUrl\x12\x1d\n" +
|
||||
@@ -4048,7 +4066,9 @@ const file_iam_proto_rawDesc = "" +
|
||||
"\vthumbprints\x18\x03 \x03(\tR\vthumbprints\x12\x1d\n" +
|
||||
"\n" +
|
||||
"account_id\x18\x04 \x01(\tR\taccountId\x12\x10\n" +
|
||||
"\x03arn\x18\x05 \x01(\tR\x03arn\"\x97\x01\n" +
|
||||
"\x03arn\x18\x05 \x01(\tR\x03arn\x12F\n" +
|
||||
"\x1djti_replay_protection_enabled\x18\x06 \x01(\bH\x00R\x1ajtiReplayProtectionEnabled\x88\x01\x01B \n" +
|
||||
"\x1e_jti_replay_protection_enabled\"\x81\x02\n" +
|
||||
"\x16PutOIDCProviderRequest\x12\x1d\n" +
|
||||
"\n" +
|
||||
"issuer_url\x18\x01 \x01(\tR\tissuerUrl\x12\x1d\n" +
|
||||
@@ -4056,7 +4076,9 @@ const file_iam_proto_rawDesc = "" +
|
||||
"client_ids\x18\x02 \x03(\tR\tclientIds\x12 \n" +
|
||||
"\vthumbprints\x18\x03 \x03(\tR\vthumbprints\x12\x1d\n" +
|
||||
"\n" +
|
||||
"account_id\x18\x04 \x01(\tR\taccountId\"+\n" +
|
||||
"account_id\x18\x04 \x01(\tR\taccountId\x12F\n" +
|
||||
"\x1djti_replay_protection_enabled\x18\x05 \x01(\bH\x00R\x1ajtiReplayProtectionEnabled\x88\x01\x01B \n" +
|
||||
"\x1e_jti_replay_protection_enabled\"+\n" +
|
||||
"\x17PutOIDCProviderResponse\x12\x10\n" +
|
||||
"\x03arn\x18\x01 \x01(\tR\x03arn\"V\n" +
|
||||
"\x16GetOIDCProviderRequest\x12\x1d\n" +
|
||||
@@ -4340,6 +4362,8 @@ func file_iam_proto_init() {
|
||||
if File_iam_proto != nil {
|
||||
return
|
||||
}
|
||||
file_iam_proto_msgTypes[56].OneofWrappers = []any{}
|
||||
file_iam_proto_msgTypes[57].OneofWrappers = []any{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
|
||||
@@ -382,6 +382,7 @@ message ErasureCodingTaskConfig {
|
||||
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
bool strict_placement = 7; // fail planning instead of relaxing placement constraints
|
||||
int32 free_slots_deadband = 8; // Place free-volume-slot deadband; |ΔfreeSlots| ≤ M×dataShards ranks by liveShards; 0 = strict
|
||||
optional int32 max_shard_transfers = 9; // unset = no global cap (one in-flight per dest disk); 0 = sequential; N>0 = global cap
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
|
||||
@@ -2974,14 +2974,15 @@ func (x *VacuumTaskConfig) GetMinIntervalSeconds() int32 {
|
||||
// ErasureCodingTaskConfig contains EC-specific configuration
|
||||
type ErasureCodingTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
FullnessRatio float64 `protobuf:"fixed64,1,opt,name=fullness_ratio,json=fullnessRatio,proto3" json:"fullness_ratio,omitempty"` // Minimum fullness ratio to trigger EC (0.0-1.0)
|
||||
QuietForSeconds int32 `protobuf:"varint,2,opt,name=quiet_for_seconds,json=quietForSeconds,proto3" json:"quiet_for_seconds,omitempty"` // Minimum quiet time before EC
|
||||
MinVolumeSizeMb int32 `protobuf:"varint,3,opt,name=min_volume_size_mb,json=minVolumeSizeMb,proto3" json:"min_volume_size_mb,omitempty"` // Minimum volume size for EC
|
||||
CollectionFilter string `protobuf:"bytes,4,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Only process volumes from specific collections
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Disk tags to prioritize for EC shard placement
|
||||
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
StrictPlacement bool `protobuf:"varint,7,opt,name=strict_placement,json=strictPlacement,proto3" json:"strict_placement,omitempty"` // fail planning instead of relaxing placement constraints
|
||||
FreeSlotsDeadband int32 `protobuf:"varint,8,opt,name=free_slots_deadband,json=freeSlotsDeadband,proto3" json:"free_slots_deadband,omitempty"` // Place free-volume-slot deadband; |ΔfreeSlots| ≤ M×dataShards ranks by liveShards; 0 = strict
|
||||
FullnessRatio float64 `protobuf:"fixed64,1,opt,name=fullness_ratio,json=fullnessRatio,proto3" json:"fullness_ratio,omitempty"` // Minimum fullness ratio to trigger EC (0.0-1.0)
|
||||
QuietForSeconds int32 `protobuf:"varint,2,opt,name=quiet_for_seconds,json=quietForSeconds,proto3" json:"quiet_for_seconds,omitempty"` // Minimum quiet time before EC
|
||||
MinVolumeSizeMb int32 `protobuf:"varint,3,opt,name=min_volume_size_mb,json=minVolumeSizeMb,proto3" json:"min_volume_size_mb,omitempty"` // Minimum volume size for EC
|
||||
CollectionFilter string `protobuf:"bytes,4,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Only process volumes from specific collections
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Disk tags to prioritize for EC shard placement
|
||||
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
StrictPlacement bool `protobuf:"varint,7,opt,name=strict_placement,json=strictPlacement,proto3" json:"strict_placement,omitempty"` // fail planning instead of relaxing placement constraints
|
||||
FreeSlotsDeadband int32 `protobuf:"varint,8,opt,name=free_slots_deadband,json=freeSlotsDeadband,proto3" json:"free_slots_deadband,omitempty"` // Place free-volume-slot deadband; |ΔfreeSlots| ≤ M×dataShards ranks by liveShards; 0 = strict
|
||||
MaxShardTransfers *int32 `protobuf:"varint,9,opt,name=max_shard_transfers,json=maxShardTransfers,proto3,oneof" json:"max_shard_transfers,omitempty"` // unset = no global cap (one in-flight per dest disk); 0 = sequential; N>0 = global cap
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3072,6 +3073,13 @@ func (x *ErasureCodingTaskConfig) GetFreeSlotsDeadband() int32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *ErasureCodingTaskConfig) GetMaxShardTransfers() int32 {
|
||||
if x != nil && x.MaxShardTransfers != nil {
|
||||
return *x.MaxShardTransfers
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
type BalanceTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -4301,7 +4309,7 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x10VacuumTaskConfig\x12+\n" +
|
||||
"\x11garbage_threshold\x18\x01 \x01(\x01R\x10garbageThreshold\x12/\n" +
|
||||
"\x14min_volume_age_hours\x18\x02 \x01(\x05R\x11minVolumeAgeHours\x120\n" +
|
||||
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\xf5\x02\n" +
|
||||
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\xc2\x03\n" +
|
||||
"\x17ErasureCodingTaskConfig\x12%\n" +
|
||||
"\x0efullness_ratio\x18\x01 \x01(\x01R\rfullnessRatio\x12*\n" +
|
||||
"\x11quiet_for_seconds\x18\x02 \x01(\x05R\x0fquietForSeconds\x12+\n" +
|
||||
@@ -4310,7 +4318,9 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\x12)\n" +
|
||||
"\x10strict_placement\x18\a \x01(\bR\x0fstrictPlacement\x12.\n" +
|
||||
"\x13free_slots_deadband\x18\b \x01(\x05R\x11freeSlotsDeadband\"\x9b\x01\n" +
|
||||
"\x13free_slots_deadband\x18\b \x01(\x05R\x11freeSlotsDeadband\x123\n" +
|
||||
"\x13max_shard_transfers\x18\t \x01(\x05H\x00R\x11maxShardTransfers\x88\x01\x01B\x16\n" +
|
||||
"\x14_max_shard_transfers\"\x9b\x01\n" +
|
||||
"\x11BalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\x12+\n" +
|
||||
@@ -4585,6 +4595,7 @@ func file_worker_proto_init() {
|
||||
(*TaskPolicy_ReplicationConfig)(nil),
|
||||
(*TaskPolicy_EcBalanceConfig)(nil),
|
||||
}
|
||||
file_worker_proto_msgTypes[31].OneofWrappers = []any{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
|
||||
@@ -2401,23 +2401,29 @@ func (s3a *S3ApiServer) setResponseHeaders(w http.ResponseWriter, r *http.Reques
|
||||
// Set custom headers from entry.Extended (user metadata)
|
||||
// Use direct map assignment to preserve original header casing (matches proxy behavior)
|
||||
if entry.Extended != nil {
|
||||
extAmzPrefixLower := strings.ToLower(s3_constants.ExtAmzPrefix)
|
||||
taggingPrefixLower := strings.ToLower(s3_constants.AmzObjectTaggingPrefix)
|
||||
for k, v := range entry.Extended {
|
||||
// Skip internal SeaweedFS headers
|
||||
if !strings.HasPrefix(k, "xattr-") && !s3_constants.IsSeaweedFSInternalHeader(k) {
|
||||
// Support backward compatibility: migrate old non-canonical format to canonical format
|
||||
// OLD: "x-amz-meta-foo" → NEW: "X-Amz-Meta-foo" (preserving suffix case)
|
||||
headerKey := k
|
||||
if len(k) >= 11 && strings.EqualFold(k[:11], "x-amz-meta-") {
|
||||
// Normalize to AWS S3 format: "X-Amz-Meta-" prefix with lowercase suffix
|
||||
// AWS S3 returns user metadata with the suffix in lowercase
|
||||
suffix := k[len("x-amz-meta-"):]
|
||||
headerKey = s3_constants.AmzUserMetaPrefix + strings.ToLower(suffix)
|
||||
if glog.V(4) && k != headerKey {
|
||||
glog.Infof("Normalizing user metadata header %q to %q in response", k, headerKey)
|
||||
}
|
||||
}
|
||||
w.Header()[headerKey] = []string{string(v)}
|
||||
// Skip internal SeaweedFS headers, and the stored tag/ACL/lock
|
||||
// metadata that belongs behind its own API (GetObjectTagging,
|
||||
// GetObjectAcl, GetObjectRetention) instead of every reader.
|
||||
lowerKey := strings.ToLower(k)
|
||||
if strings.HasPrefix(lowerKey, "xattr-") || strings.HasPrefix(lowerKey, extAmzPrefixLower) || strings.HasPrefix(lowerKey, taggingPrefixLower) || s3_constants.IsSeaweedFSInternalHeader(lowerKey) {
|
||||
continue
|
||||
}
|
||||
// Support backward compatibility: migrate old non-canonical format to canonical format
|
||||
// OLD: "x-amz-meta-foo" → NEW: "X-Amz-Meta-foo" (preserving suffix case)
|
||||
headerKey := k
|
||||
if len(k) >= 11 && strings.EqualFold(k[:11], "x-amz-meta-") {
|
||||
// Normalize to AWS S3 format: "X-Amz-Meta-" prefix with lowercase suffix
|
||||
// AWS S3 returns user metadata with the suffix in lowercase
|
||||
suffix := k[len("x-amz-meta-"):]
|
||||
headerKey = s3_constants.AmzUserMetaPrefix + strings.ToLower(suffix)
|
||||
if glog.V(4) && k != headerKey {
|
||||
glog.Infof("Normalizing user metadata header %q to %q in response", k, headerKey)
|
||||
}
|
||||
}
|
||||
w.Header()[headerKey] = []string{string(v)}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// GetObject/HeadObject must expose only response headers AWS defines: user
|
||||
// metadata, standard entity headers and x-amz-tagging-count. Tag values live
|
||||
// behind GetObjectTagging and ACL/owner/lock state behind its own APIs; the
|
||||
// generic Extended echo must not hand them to any caller that can read the
|
||||
// object.
|
||||
func TestSetResponseHeadersFiltersInternalExtendedKeys(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "object",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 100},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.AmzObjectTaggingPrefix + "project": []byte("alpha"),
|
||||
s3_constants.AmzObjectTaggingPrefix + "owner": []byte("y"),
|
||||
"x-amz-tagging-sneaky": []byte("z"),
|
||||
"seaweed-x-amz-acl": []byte("z"),
|
||||
s3_constants.ExtAmzAclKey: []byte(`[{"Permission":"FULL_CONTROL"}]`),
|
||||
s3_constants.ExtAmzOwnerKey: []byte("admin"),
|
||||
s3_constants.ExtVersionIdKey: []byte("version-1"),
|
||||
s3_constants.ExtObjectLockModeKey: []byte("COMPLIANCE"),
|
||||
s3_constants.ExtETagKey: []byte("d41d8cd98f00b204e9800998ecf8427e"),
|
||||
s3_constants.SeaweedFSWriteId: []byte("write-id"),
|
||||
"X-Amz-Meta-Foo": []byte("bar"),
|
||||
"Cache-Control": []byte("no-cache"),
|
||||
"xattr-user.note": []byte("n"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
w := httptest.NewRecorder()
|
||||
s3a.setResponseHeaders(w, httptest.NewRequest(method, "/bucket/object", nil), entry, 8)
|
||||
|
||||
for key := range w.Header() {
|
||||
lowerKey := strings.ToLower(key)
|
||||
if lowerKey == s3_constants.AmzTagCount {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(lowerKey, strings.ToLower(s3_constants.ExtAmzPrefix)) {
|
||||
t.Errorf("%s: internal header %q leaked into response", method, key)
|
||||
}
|
||||
if strings.HasPrefix(lowerKey, strings.ToLower(s3_constants.AmzObjectTaggingPrefix)) {
|
||||
t.Errorf("%s: object tag value %q leaked into response", method, key)
|
||||
}
|
||||
}
|
||||
if got := w.Header().Get(s3_constants.AmzTagCount); got != "2" {
|
||||
t.Errorf("%s: tag count = %q, want 2", method, got)
|
||||
}
|
||||
if got := w.Header()["X-Amz-Meta-foo"]; len(got) != 1 || got[0] != "bar" {
|
||||
t.Errorf("%s: user metadata dropped, X-Amz-Meta-foo = %v", method, got)
|
||||
}
|
||||
if got := w.Header().Get("Cache-Control"); got != "no-cache" {
|
||||
t.Errorf("%s: Cache-Control = %q", method, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ func TestGetAccountIDAdminActionKeepsAdminAccount(t *testing.T) {
|
||||
assert.Equal(t, s3_constants.AccountAdminId, h.getAccountID(req), "an admin identity keeps the admin account as principal")
|
||||
}
|
||||
|
||||
func TestDefaultAllowForOnlyAppliesToUnauthenticatedOrAnonymous(t *testing.T) {
|
||||
func TestDefaultAllowForOnlyAppliesWithoutResolvedIdentity(t *testing.T) {
|
||||
h := NewS3TablesHandler()
|
||||
h.SetDefaultAllow(true)
|
||||
|
||||
@@ -149,8 +149,8 @@ func TestDefaultAllowForOnlyAppliesToUnauthenticatedOrAnonymous(t *testing.T) {
|
||||
|
||||
anon := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
anon = anon.WithContext(s3_constants.SetIdentityInContext(anon.Context(),
|
||||
&testIdentity{Name: s3_constants.AccountAnonymousId}))
|
||||
assert.True(t, h.defaultAllowFor(anon), "anonymous requests keep the open default")
|
||||
&testIdentity{Name: s3_constants.AccountAnonymousId, Actions: []string{"Read:pub", "List:pub"}}))
|
||||
assert.False(t, h.defaultAllowFor(anon), "a resolved anonymous identity is scoped by its grant, not the open default")
|
||||
|
||||
authed := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
authed = authed.WithContext(s3_constants.SetIdentityInContext(authed.Context(),
|
||||
|
||||
@@ -49,7 +49,8 @@ func (h *S3TablesHandler) shouldUseIAM(r *http.Request, identityActions, identit
|
||||
}
|
||||
|
||||
// defaultAllowFor reports whether the open-by-default fallback applies: only for
|
||||
// trusted tooling or unauthenticated/anonymous access. An authenticated principal
|
||||
// trusted tooling or when no principal was resolved at all. A resolved identity
|
||||
// — the configured anonymous identity included — is scoped by its grant and
|
||||
// must pass an explicit check.
|
||||
func (h *S3TablesHandler) defaultAllowFor(r *http.Request) bool {
|
||||
if h.trusted {
|
||||
@@ -60,10 +61,7 @@ func (h *S3TablesHandler) defaultAllowFor(r *http.Request) bool {
|
||||
}
|
||||
// The Manager path forwards only the identity name, so a name alone (no
|
||||
// identity object) still counts as an authenticated principal.
|
||||
if s3_constants.GetIdentityFromContext(r) == nil && s3_constants.GetIdentityNameFromContext(r) == "" {
|
||||
return true
|
||||
}
|
||||
return isAnonymousIdentity(r)
|
||||
return s3_constants.GetIdentityFromContext(r) == nil && s3_constants.GetIdentityNameFromContext(r) == ""
|
||||
}
|
||||
|
||||
func isAnonymousIdentity(r *http.Request) bool {
|
||||
|
||||
@@ -313,8 +313,33 @@ func (t *responseBodyTracker) Write(p []byte) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
// ifRangeMatches reports whether an If-Range validator still names the
|
||||
// representation described by header (RFC 9110 13.1.5): an entity tag by
|
||||
// strong comparison, or a date equal to Last-Modified.
|
||||
func ifRangeMatches(ifRange string, header http.Header) bool {
|
||||
ifRange = strings.TrimSpace(ifRange)
|
||||
if ifRange == "" {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(ifRange, "\"") || strings.HasPrefix(ifRange, "W/") {
|
||||
etag := header.Get("ETag")
|
||||
return etag != "" && !strings.HasPrefix(etag, "W/") && ifRange == etag
|
||||
}
|
||||
date, err := http.ParseTime(ifRange)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
lastModified, err := http.ParseTime(header.Get("Last-Modified"))
|
||||
return err == nil && date.Equal(lastModified)
|
||||
}
|
||||
|
||||
func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64, mimeType string, prepareWriteFn func(offset int64, size int64) (filer.DoStreamContent, error)) error {
|
||||
rangeReq := r.Header.Get("Range")
|
||||
// A Range whose If-Range no longer matches is ignored and the whole content
|
||||
// is sent, so a resumed download restarts instead of mixing two versions.
|
||||
if rangeReq != "" && !ifRangeMatches(r.Header.Get("If-Range"), w.Header()) {
|
||||
rangeReq = ""
|
||||
}
|
||||
sink := &responseBodyTracker{ResponseWriter: w}
|
||||
bufferedWriter := writePool.Get().(*bufio.Writer)
|
||||
bufferedWriter.Reset(sink)
|
||||
|
||||
@@ -343,6 +343,48 @@ func TestProcessRangeRequestRanges(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessRangeRequestIfRange(t *testing.T) {
|
||||
data := []byte("0123456789")
|
||||
const etag = `"v2"`
|
||||
const lastModified = "Sat, 24 Oct 2026 22:01:04 GMT"
|
||||
tests := []struct {
|
||||
ifRange string
|
||||
wantCode int
|
||||
wantBody string
|
||||
}{
|
||||
{"", http.StatusPartialContent, "01"},
|
||||
{etag, http.StatusPartialContent, "01"},
|
||||
{lastModified, http.StatusPartialContent, "01"},
|
||||
{"Saturday, 24-Oct-26 22:01:04 GMT", http.StatusPartialContent, "01"},
|
||||
{"Sat Oct 24 22:01:04 2026", http.StatusPartialContent, "01"},
|
||||
{`"v1"`, http.StatusOK, "0123456789"},
|
||||
{`W/"v2"`, http.StatusOK, "0123456789"},
|
||||
{"Sat, 24 Oct 2026 22:01:03 GMT", http.StatusOK, "0123456789"},
|
||||
{"not a date", http.StatusOK, "0123456789"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/test.txt", nil)
|
||||
r.Header.Set("Range", "bytes=0-1")
|
||||
if tt.ifRange != "" {
|
||||
r.Header.Set("If-Range", tt.ifRange)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
w.Header().Set("ETag", etag)
|
||||
w.Header().Set("Last-Modified", lastModified)
|
||||
if err := ProcessRangeRequest(r, w, int64(len(data)), "text/plain", func(offset int64, size int64) (filer.DoStreamContent, error) {
|
||||
return func(writer io.Writer) error {
|
||||
_, err := writer.Write(data[offset : offset+size])
|
||||
return err
|
||||
}, nil
|
||||
}); err != nil {
|
||||
t.Errorf("If-Range %q: %v", tt.ifRange, err)
|
||||
}
|
||||
if w.Code != tt.wantCode || w.Body.String() != tt.wantBody {
|
||||
t.Errorf("If-Range %q: got %d %q, want %d %q", tt.ifRange, w.Code, w.Body.String(), tt.wantCode, tt.wantBody)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// /submit must reject at the limit its master was given, not at a hardcoded
|
||||
// 256MB: weed server hands -volume.fileSizeLimitMB down to the master, and an
|
||||
// upload the volume server would store must not be turned away here (#6748).
|
||||
|
||||
@@ -59,11 +59,12 @@ func (s *IamGrpcServer) requireRoleStore() (integration.RoleStore, error) {
|
||||
|
||||
func toPbOIDCProvider(rec *integration.OIDCProviderRecord) *iam_pb.OIDCProvider {
|
||||
return &iam_pb.OIDCProvider{
|
||||
IssuerUrl: rec.URL,
|
||||
ClientIds: rec.ClientIDs,
|
||||
Thumbprints: rec.Thumbprints,
|
||||
AccountId: rec.AccountID,
|
||||
Arn: rec.ARN,
|
||||
IssuerUrl: rec.URL,
|
||||
ClientIds: rec.ClientIDs,
|
||||
Thumbprints: rec.Thumbprints,
|
||||
AccountId: rec.AccountID,
|
||||
Arn: rec.ARN,
|
||||
JtiReplayProtectionEnabled: rec.JTIReplayProtectionEnabled,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +96,7 @@ func (s *IamGrpcServer) PutOIDCProvider(ctx context.Context, req *iam_pb.PutOIDC
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
rec.JTIReplayProtectionEnabled = req.JtiReplayProtectionEnabled
|
||||
// Put replaces what the request carries and keeps what it cannot. The
|
||||
// store's atomic update decides which against the record as it is when
|
||||
// written, so a delete racing the put is not merged back from a stale read.
|
||||
@@ -109,6 +111,9 @@ func (s *IamGrpcServer) PutOIDCProvider(ctx context.Context, req *iam_pb.PutOIDC
|
||||
next.Tags = existing.Tags
|
||||
next.AllowedPrincipalTagKeys = existing.AllowedPrincipalTagKeys
|
||||
next.PolicyClaim = existing.PolicyClaim
|
||||
if next.JTIReplayProtectionEnabled == nil {
|
||||
next.JTIReplayProtectionEnabled = existing.JTIReplayProtectionEnabled
|
||||
}
|
||||
}
|
||||
return &next, nil
|
||||
})
|
||||
|
||||
@@ -497,3 +497,40 @@ func TestIamGrpc_DeleteOIDCProviderDoesNotDeleteAProviderReplacedMeanwhile(t *te
|
||||
require.NoError(t, err, "the replacement record was deleted")
|
||||
assert.Equal(t, []string{"new"}, rec.ClientIDs)
|
||||
}
|
||||
|
||||
// The flag rides PutOIDCProvider into the record, is reported back by Get, and
|
||||
// a Put that does not carry it keeps the stored value.
|
||||
func TestIamGrpc_PutOIDCProviderJTIReplayProtectionFlag(t *testing.T) {
|
||||
s, ctx, providers, _ := newSTSTestServer(t)
|
||||
disabled, enabled := false, true
|
||||
|
||||
put, err := s.PutOIDCProvider(ctx, &iam_pb.PutOIDCProviderRequest{
|
||||
IssuerUrl: "https://oidc.example", ClientIds: []string{"aud"},
|
||||
JtiReplayProtectionEnabled: &disabled,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
got, err := s.GetOIDCProvider(ctx, &iam_pb.GetOIDCProviderRequest{IssuerUrl: "https://oidc.example"})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.Provider.JtiReplayProtectionEnabled)
|
||||
assert.False(t, *got.Provider.JtiReplayProtectionEnabled)
|
||||
|
||||
_, err = s.PutOIDCProvider(ctx, &iam_pb.PutOIDCProviderRequest{
|
||||
IssuerUrl: "https://oidc.example", ClientIds: []string{"aud2"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
rec, err := providers.GetProviderByARN(context.Background(), "", put.Arn)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, rec.JTIReplayProtectionEnabled)
|
||||
assert.False(t, *rec.JTIReplayProtectionEnabled)
|
||||
|
||||
_, err = s.PutOIDCProvider(ctx, &iam_pb.PutOIDCProviderRequest{
|
||||
IssuerUrl: "https://oidc.example", ClientIds: []string{"aud"},
|
||||
JtiReplayProtectionEnabled: &enabled,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
rec, err = providers.GetProviderByARN(context.Background(), "", put.Arn)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, rec.JTIReplayProtectionEnabled)
|
||||
assert.True(t, *rec.JTIReplayProtectionEnabled)
|
||||
}
|
||||
@@ -103,6 +103,55 @@ func announceVolume(message *master_pb.VolumeLocation, vid uint32, isRemote, isR
|
||||
}
|
||||
}
|
||||
|
||||
// reportsPriorClusterState tells whether a heartbeat could come from a server
|
||||
// still carrying cluster state from before this leader's term: it holds a
|
||||
// volume or shard id above the bound this master has issued, has seen a
|
||||
// higher volume id bound, or last synced with a different topology id.
|
||||
// Echoes of this term's own allocations stay under the bound and do not count.
|
||||
func reportsPriorClusterState(heartbeat *master_pb.Heartbeat, topologyId string, bound needle.VolumeId) bool {
|
||||
if needle.VolumeId(heartbeat.MaxVolumeIdSeen) > bound ||
|
||||
(heartbeat.LastSeenTopologyId != "" && heartbeat.LastSeenTopologyId != topologyId) {
|
||||
return true
|
||||
}
|
||||
unissued := func(id uint32) bool { return needle.VolumeId(id) > bound }
|
||||
for _, v := range heartbeat.Volumes {
|
||||
if unissued(v.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, v := range heartbeat.NewVolumes {
|
||||
if unissued(v.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, v := range heartbeat.ChangedVolumes {
|
||||
if unissued(v.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, v := range heartbeat.DeletedVolumes {
|
||||
if unissued(v.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, s := range heartbeat.EcShards {
|
||||
if unissued(s.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, s := range heartbeat.NewEcShards {
|
||||
if unissued(s.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, s := range heartbeat.DeletedEcShards {
|
||||
if unissued(s.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {
|
||||
var dn *topology.DataNode
|
||||
|
||||
@@ -182,6 +231,9 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
|
||||
continue
|
||||
}
|
||||
|
||||
if (dn == nil && heartbeat.Ip != "") || reportsPriorClusterState(heartbeat, ms.Topo.GetTopologyId(), ms.Topo.GetMaxVolumeId()) {
|
||||
ms.Topo.NoteAllocationEvidence()
|
||||
}
|
||||
ms.Topo.Sequence.SetMax(heartbeat.MaxFileKey)
|
||||
ms.Topo.UpAdjustMaxVolumeId(needle.VolumeId(heartbeat.MaxVolumeIdSeen))
|
||||
if len(heartbeat.Volumes) > 0 {
|
||||
|
||||
@@ -199,27 +199,15 @@ func (ms *MasterServer) Assign(ctx context.Context, req *master_pb.AssignRequest
|
||||
if dn == nil {
|
||||
continue
|
||||
}
|
||||
var replicas []*master_pb.Location
|
||||
for _, r := range dnList.Rest() {
|
||||
replicas = append(replicas, &master_pb.Location{
|
||||
Url: r.Url(),
|
||||
PublicUrl: r.PublicUrl,
|
||||
GrpcPort: uint32(r.GrpcPort),
|
||||
DataCenter: r.GetDataCenterId(),
|
||||
})
|
||||
return assignResponse(fid, count, dnList, ms.guard), nil
|
||||
}
|
||||
// The last in-loop pick can predate the growth it triggered concluding:
|
||||
// growth registers its volumes before clearing the pending flag, so pick
|
||||
// once more before shedding.
|
||||
if fid, count, dnList, _, err := ms.Topo.PickForWrite(req.Count, option, vl, req.ExpectedDataSize); err == nil {
|
||||
if dnList.Head() != nil {
|
||||
return assignResponse(fid, count, dnList, ms.guard), nil
|
||||
}
|
||||
return &master_pb.AssignResponse{
|
||||
Fid: fid,
|
||||
Location: &master_pb.Location{
|
||||
Url: dn.Url(),
|
||||
PublicUrl: dn.PublicUrl,
|
||||
GrpcPort: uint32(dn.GrpcPort),
|
||||
DataCenter: dn.GetDataCenterId(),
|
||||
},
|
||||
Count: count,
|
||||
Auth: string(security.GenJwtForVolumeServer(ms.guard.SigningKey(), ms.guard.ExpiresAfterSec(), fid)),
|
||||
Replicas: replicas,
|
||||
}, nil
|
||||
}
|
||||
// The initiator timed out with its growth still pending: shed retryably
|
||||
// rather than failing the write that growth is about to satisfy.
|
||||
@@ -235,6 +223,31 @@ func (ms *MasterServer) Assign(ctx context.Context, req *master_pb.AssignRequest
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func assignResponse(fid string, count uint64, dnList *topology.VolumeLocationList, guard *security.Guard) *master_pb.AssignResponse {
|
||||
var replicas []*master_pb.Location
|
||||
for _, r := range dnList.Rest() {
|
||||
replicas = append(replicas, &master_pb.Location{
|
||||
Url: r.Url(),
|
||||
PublicUrl: r.PublicUrl,
|
||||
GrpcPort: uint32(r.GrpcPort),
|
||||
DataCenter: r.GetDataCenterId(),
|
||||
})
|
||||
}
|
||||
dn := dnList.Head()
|
||||
return &master_pb.AssignResponse{
|
||||
Fid: fid,
|
||||
Location: &master_pb.Location{
|
||||
Url: dn.Url(),
|
||||
PublicUrl: dn.PublicUrl,
|
||||
GrpcPort: uint32(dn.GrpcPort),
|
||||
DataCenter: dn.GetDataCenterId(),
|
||||
},
|
||||
Count: count,
|
||||
Auth: string(security.GenJwtForVolumeServer(guard.SigningKey(), guard.ExpiresAfterSec(), fid)),
|
||||
Replicas: replicas,
|
||||
}
|
||||
}
|
||||
|
||||
// describeDiskLayout names the disk layout an assign targets. The empty disk
|
||||
// type is the legacy unlabeled layout on servers that were never started with
|
||||
// -disk; naming it "hdd" sends operators looking for servers that were never
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestReportsPriorClusterState(t *testing.T) {
|
||||
topoId := "topo-1"
|
||||
|
||||
// a quiet heartbeat from a synced server is not evidence
|
||||
assert.False(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
LastSeenTopologyId: topoId,
|
||||
}, topoId, 5))
|
||||
|
||||
// echoes of volume ids this master issued are not evidence
|
||||
assert.False(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
MaxVolumeIdSeen: 5,
|
||||
NewVolumes: []*master_pb.VolumeShortInformationMessage{{Id: 5}},
|
||||
ChangedVolumes: []*master_pb.VolumeInformationMessage{{Id: 3}},
|
||||
LastSeenTopologyId: topoId,
|
||||
}, topoId, 5))
|
||||
|
||||
// ids above the issued bound come from before this term
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
MaxVolumeIdSeen: 6,
|
||||
}, topoId, 5))
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
Volumes: []*master_pb.VolumeInformationMessage{{Id: 6}},
|
||||
}, topoId, 5))
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
NewVolumes: []*master_pb.VolumeShortInformationMessage{{Id: 6}},
|
||||
}, topoId, 5))
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
DeletedVolumes: []*master_pb.VolumeShortInformationMessage{{Id: 6}},
|
||||
}, topoId, 5))
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
EcShards: []*master_pb.VolumeEcShardInformationMessage{{Id: 42}},
|
||||
}, topoId, 5))
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
NewEcShards: []*master_pb.VolumeEcShardInformationMessage{{Id: 42}},
|
||||
}, topoId, 5))
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
DeletedEcShards: []*master_pb.VolumeEcShardInformationMessage{{Id: 42}},
|
||||
}, topoId, 5))
|
||||
|
||||
// a heartbeat last synced under another topology id is prior state
|
||||
assert.True(t, reportsPriorClusterState(&master_pb.Heartbeat{
|
||||
LastSeenTopologyId: "topo-0",
|
||||
}, topoId, 5))
|
||||
}
|
||||
@@ -175,6 +175,13 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
|
||||
ms.Topo.SetGrowthFreezeConfig(
|
||||
v.GetBool("master.volume_growth.freeze_on_topology_mismatch"),
|
||||
v.GetDuration("master.volume_growth.state_loss_recovery_wait"))
|
||||
if str := strings.TrimSpace(v.GetString("master.volume_growth.allocation_deferral")); str != "" {
|
||||
if d, err := time.ParseDuration(str); err != nil {
|
||||
glog.Warningf("invalid master.volume_growth.allocation_deferral %q: %v", str, err)
|
||||
} else {
|
||||
ms.Topo.SetAllocationDeferral(d)
|
||||
}
|
||||
}
|
||||
ms.Topo.QuarantineVolumeFn = func(dn *topology.DataNode, vid needle.VolumeId, readOnly bool) error {
|
||||
err := operation.WithVolumeServerClient(false, dn.ServerAddress(), ms.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
@@ -261,6 +261,16 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// The last in-loop pick can predate the growth it triggered concluding:
|
||||
// growth registers its volumes before clearing the pending flag, so pick
|
||||
// once more before shedding.
|
||||
if fid, count, dnList, _, err := ms.Topo.PickForWrite(requestedCount, option, vl, expectedDataSize); err == nil {
|
||||
if dn := dnList.Head(); dn != nil {
|
||||
ms.maybeAddJwtAuthorization(w, fid, true)
|
||||
writeJsonQuiet(w, r, http.StatusOK, operation.AssignResult{Fid: fid, Url: dn.Url(), PublicUrl: dn.PublicUrl, Count: count})
|
||||
return
|
||||
}
|
||||
}
|
||||
// See Assign: initiator that timed out with growth still pending stays retryable.
|
||||
if initiatedGrow && vl.HasGrowRequest() && ms.Topo.AvailableSpaceFor(option) > 0 {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
|
||||
@@ -65,7 +65,7 @@ func EnsureTopologyId(topo *topology.Topology, checkLeaderFn func() bool, persis
|
||||
} else {
|
||||
glog.V(0).Infof("TopologyId generated: %s", topologyId)
|
||||
}
|
||||
topo.DeferAllocation(topo.WarmupDuration())
|
||||
topo.DeferAllocation(topo.AllocationDeferralDuration())
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,66 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// ShardDistributionOptions controls DistributeEcShards concurrency.
|
||||
// MaxShardTransfers:
|
||||
// - nil / unset: no global cap; one in-flight per (destNode, disk_id), or
|
||||
// per destNode (host:port, not rack) when any target leaves disk choice
|
||||
// to the receiver (disk_id 0)
|
||||
// - N<=0: historical sequential nested loops
|
||||
// - N>0: global cap of N, still at most one in-flight per key
|
||||
type ShardDistributionOptions struct {
|
||||
MaxShardTransfers *int
|
||||
send shardSender
|
||||
}
|
||||
|
||||
type shardSender func(ctx context.Context, volumeID uint32, collection string, dialOption grpc.DialOption, destServer string, diskID uint32, filePath, shardType string) error
|
||||
|
||||
type shardJob struct {
|
||||
destNode string
|
||||
shardType string
|
||||
filePath string
|
||||
diskID uint32
|
||||
hasDisk bool
|
||||
}
|
||||
|
||||
func shardSenderOrDefault(opts *ShardDistributionOptions) shardSender {
|
||||
if opts != nil && opts.send != nil {
|
||||
return opts.send
|
||||
}
|
||||
return sendShardFileToDestination
|
||||
}
|
||||
|
||||
func shardTransferCap(opts *ShardDistributionOptions) (sequential bool, capN int) {
|
||||
if opts == nil || opts.MaxShardTransfers == nil {
|
||||
return false, 0
|
||||
}
|
||||
n := *opts.MaxShardTransfers
|
||||
if n <= 0 {
|
||||
return true, 0
|
||||
}
|
||||
return false, n
|
||||
}
|
||||
|
||||
func lookupShardDisk(shardDisks map[string]map[string]uint32, destNode, shardType string) (uint32, bool) {
|
||||
if byShard, ok := shardDisks[destNode]; ok {
|
||||
if id, exists := byShard[shardType]; exists {
|
||||
return id, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func shardTransferKey(j shardJob) string {
|
||||
if j.hasDisk {
|
||||
return fmt.Sprintf("%s#%d", j.destNode, j.diskID)
|
||||
}
|
||||
return j.destNode
|
||||
}
|
||||
|
||||
func ensureLogger(logger logger) logger {
|
||||
if logger == nil {
|
||||
return &glogFallbackLogger{}
|
||||
@@ -98,7 +155,8 @@ func (g *glogFallbackLogger) Error(msg string, args ...interface{}) {
|
||||
|
||||
// DistributeEcShards distributes locally generated EC shards to destination servers.
|
||||
// Returns the shard assignment map used for mounting.
|
||||
func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb.TaskTarget, shardFiles map[string]string, dialOption grpc.DialOption, logger logger) (map[string][]string, error) {
|
||||
// opts nil is the default: one in-flight per dest disk/node, no global cap.
|
||||
func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb.TaskTarget, shardFiles map[string]string, dialOption grpc.DialOption, logger logger, opts *ShardDistributionOptions) (map[string][]string, error) {
|
||||
if len(targets) == 0 {
|
||||
return nil, fmt.Errorf("no targets specified for EC shard distribution")
|
||||
}
|
||||
@@ -173,6 +231,22 @@ func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb
|
||||
return nil, fmt.Errorf("no shard assignments found from planning phase")
|
||||
}
|
||||
|
||||
send := shardSenderOrDefault(opts)
|
||||
sequential, capN := shardTransferCap(opts)
|
||||
if sequential {
|
||||
if err := distributeEcShardsSequential(volumeID, collection, shardAssignment, shardFiles, shardDisks, dialOption, log, send); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if err := distributeEcShardsParallel(volumeID, collection, shardAssignment, shardFiles, shardDisks, dialOption, log, send, capN); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Successfully distributed EC shards to %d destinations", len(shardAssignment))
|
||||
return shardAssignment, nil
|
||||
}
|
||||
|
||||
func distributeEcShardsSequential(volumeID uint32, collection string, shardAssignment map[string][]string, shardFiles map[string]string, shardDisks map[string]map[string]uint32, dialOption grpc.DialOption, log logger, send shardSender) error {
|
||||
ctx := context.Background()
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": destNode,
|
||||
@@ -184,7 +258,7 @@ func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb
|
||||
for _, shardType := range assignedShards {
|
||||
filePath, exists := shardFiles[shardType]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("shard file %s not found for destination %s", shardType, destNode)
|
||||
return fmt.Errorf("shard file %s not found for destination %s", shardType, destNode)
|
||||
}
|
||||
|
||||
if info, err := os.Stat(filePath); err == nil {
|
||||
@@ -198,12 +272,9 @@ func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb
|
||||
}).Info("Starting shard file transfer")
|
||||
}
|
||||
|
||||
diskID := uint32(0)
|
||||
if byShard, ok := shardDisks[destNode]; ok {
|
||||
diskID = byShard[shardType]
|
||||
}
|
||||
if err := sendShardFileToDestination(volumeID, collection, dialOption, destNode, diskID, filePath, shardType); err != nil {
|
||||
return nil, fmt.Errorf("failed to send %s to %s: %w", shardType, destNode, err)
|
||||
diskID, _ := lookupShardDisk(shardDisks, destNode, shardType)
|
||||
if err := send(ctx, volumeID, collection, dialOption, destNode, diskID, filePath, shardType); err != nil {
|
||||
return fmt.Errorf("failed to send %s to %s: %w", shardType, destNode, err)
|
||||
}
|
||||
|
||||
withFields(log, map[string]interface{}{
|
||||
@@ -219,9 +290,139 @@ func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb
|
||||
"total_mb": float64(transferredBytes) / (1024 * 1024),
|
||||
}).Info("All shards distributed to destination server")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Successfully distributed EC shards to %d destinations", len(shardAssignment))
|
||||
return shardAssignment, nil
|
||||
func collectShardJobs(shardAssignment map[string][]string, shardFiles map[string]string, shardDisks map[string]map[string]uint32, log logger) (map[string][]shardJob, error) {
|
||||
// disk_id 0 leaves placement to the receiver's auto-select, which can land
|
||||
// on a disk another queued stream is pinned to — serialize every transfer
|
||||
// to that server under one key.
|
||||
autoPlacement := make(map[string]bool)
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
for _, shardType := range assignedShards {
|
||||
if diskID, ok := lookupShardDisk(shardDisks, destNode, shardType); ok && diskID == 0 {
|
||||
autoPlacement[destNode] = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
byKey := make(map[string][]shardJob)
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": destNode,
|
||||
"assigned_shards": len(assignedShards),
|
||||
"shard_types": assignedShards,
|
||||
}).Info("Starting shard distribution to destination server")
|
||||
|
||||
for _, shardType := range assignedShards {
|
||||
filePath, exists := shardFiles[shardType]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("shard file %s not found for destination %s", shardType, destNode)
|
||||
}
|
||||
diskID, hasDisk := lookupShardDisk(shardDisks, destNode, shardType)
|
||||
job := shardJob{
|
||||
destNode: destNode,
|
||||
shardType: shardType,
|
||||
filePath: filePath,
|
||||
diskID: diskID,
|
||||
hasDisk: hasDisk,
|
||||
}
|
||||
key := shardTransferKey(job)
|
||||
if autoPlacement[destNode] {
|
||||
key = destNode
|
||||
}
|
||||
byKey[key] = append(byKey[key], job)
|
||||
}
|
||||
}
|
||||
return byKey, nil
|
||||
}
|
||||
|
||||
func distributeEcShardsParallel(volumeID uint32, collection string, shardAssignment map[string][]string, shardFiles map[string]string, shardDisks map[string]map[string]uint32, dialOption grpc.DialOption, log logger, send shardSender, capN int) error {
|
||||
byKey, err := collectShardJobs(shardAssignment, shardFiles, shardDisks, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
g, ctx := errgroup.WithContext(context.Background())
|
||||
var sem chan struct{}
|
||||
if capN > 0 {
|
||||
sem = make(chan struct{}, capN)
|
||||
}
|
||||
|
||||
for _, jobs := range byKey {
|
||||
jobs := jobs
|
||||
g.Go(func() error {
|
||||
for _, job := range jobs {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if sem != nil {
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-sem
|
||||
return err
|
||||
}
|
||||
}
|
||||
err := transferOneShard(ctx, volumeID, collection, dialOption, log, send, job)
|
||||
if err != nil {
|
||||
// Hold the slot so another key cannot start a send in the
|
||||
// window before errgroup cancels ctx.
|
||||
return err
|
||||
}
|
||||
if sem != nil {
|
||||
<-sem
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
if err := g.Wait(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
var transferredBytes int64
|
||||
for _, shardType := range assignedShards {
|
||||
if filePath, ok := shardFiles[shardType]; ok {
|
||||
if info, statErr := os.Stat(filePath); statErr == nil {
|
||||
transferredBytes += info.Size()
|
||||
}
|
||||
}
|
||||
}
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": destNode,
|
||||
"shards_transferred": len(assignedShards),
|
||||
"total_bytes": transferredBytes,
|
||||
"total_mb": float64(transferredBytes) / (1024 * 1024),
|
||||
}).Info("All shards distributed to destination server")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func transferOneShard(ctx context.Context, volumeID uint32, collection string, dialOption grpc.DialOption, log logger, send shardSender, job shardJob) error {
|
||||
if info, err := os.Stat(job.filePath); err == nil {
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": job.destNode,
|
||||
"shard_type": job.shardType,
|
||||
"file_path": job.filePath,
|
||||
"size_bytes": info.Size(),
|
||||
"size_kb": float64(info.Size()) / 1024,
|
||||
}).Info("Starting shard file transfer")
|
||||
}
|
||||
if err := send(ctx, volumeID, collection, dialOption, job.destNode, job.diskID, job.filePath, job.shardType); err != nil {
|
||||
return fmt.Errorf("failed to send %s to %s: %w", job.shardType, job.destNode, err)
|
||||
}
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": job.destNode,
|
||||
"shard_type": job.shardType,
|
||||
}).Info("Shard file transfer completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// MountEcShards mounts EC shards on destination servers using an assignment map.
|
||||
@@ -300,7 +501,10 @@ func MountEcShards(volumeID uint32, collection string, shardAssignment map[strin
|
||||
}
|
||||
|
||||
// diskID=0 leaves disk placement to the server's auto-select.
|
||||
func sendShardFileToDestination(volumeID uint32, collection string, dialOption grpc.DialOption, destServer string, diskID uint32, filePath, shardType string) error {
|
||||
func sendShardFileToDestination(ctx context.Context, volumeID uint32, collection string, dialOption grpc.DialOption, destServer string, diskID uint32, filePath, shardType string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return operation.WithVolumeServerClient(false, pb.ServerAddress(destServer), dialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
file, err := os.Open(filePath)
|
||||
@@ -335,7 +539,7 @@ func sendShardFileToDestination(volumeID uint32, collection string, dialOption g
|
||||
return fmt.Errorf("unknown shard type: %s", shardType)
|
||||
}
|
||||
|
||||
stream, err := client.ReceiveFile(context.Background())
|
||||
stream, err := client.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create receive stream: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
func intPtr(n int) *int { return &n }
|
||||
|
||||
func writeShardFiles(t *testing.T, names ...string) map[string]string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
files := make(map[string]string, len(names))
|
||||
for _, name := range names {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(name), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files[name] = p
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
func shardTarget(node string, disk uint32, shards ...uint32) *worker_pb.TaskTarget {
|
||||
return &worker_pb.TaskTarget{Node: node, DiskId: disk, ShardIds: shards}
|
||||
}
|
||||
|
||||
type flightRecorder struct {
|
||||
mu sync.Mutex
|
||||
inFlight int
|
||||
maxFlight int
|
||||
keyFlight map[string]int
|
||||
keyMax int
|
||||
attempts []string
|
||||
sent []string
|
||||
failOn string
|
||||
failFirst bool
|
||||
enter chan struct{}
|
||||
goAhead chan struct{}
|
||||
noGate atomic.Bool
|
||||
}
|
||||
|
||||
func newFlightRecorder() *flightRecorder {
|
||||
return &flightRecorder{
|
||||
keyFlight: make(map[string]int),
|
||||
enter: make(chan struct{}, 32),
|
||||
goAhead: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *flightRecorder) release() {
|
||||
r.noGate.Store(true)
|
||||
close(r.goAhead)
|
||||
}
|
||||
|
||||
func (r *flightRecorder) send(ctx context.Context, _ uint32, _ string, _ grpc.DialOption, destServer string, diskID uint32, _ string, shardType string) error {
|
||||
id := destServer + "/" + shardType
|
||||
key := shardTransferKey(shardJob{destNode: destServer, diskID: diskID, hasDisk: true})
|
||||
|
||||
r.mu.Lock()
|
||||
r.inFlight++
|
||||
if r.inFlight > r.maxFlight {
|
||||
r.maxFlight = r.inFlight
|
||||
}
|
||||
r.keyFlight[key]++
|
||||
if r.keyFlight[key] > r.keyMax {
|
||||
r.keyMax = r.keyFlight[key]
|
||||
}
|
||||
r.attempts = append(r.attempts, id)
|
||||
r.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
r.mu.Lock()
|
||||
r.keyFlight[key]--
|
||||
r.inFlight--
|
||||
r.mu.Unlock()
|
||||
}()
|
||||
|
||||
if r.failOn == id || r.failFirst {
|
||||
r.failFirst = false
|
||||
return errors.New("mock send failed")
|
||||
}
|
||||
if !r.noGate.Load() {
|
||||
select {
|
||||
case r.enter <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
select {
|
||||
case <-r.goAhead:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.sent = append(r.sent, id)
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitEnters(t *testing.T, rec *flightRecorder, n int) {
|
||||
t.Helper()
|
||||
deadline := time.After(2 * time.Second)
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case <-rec.enter:
|
||||
case <-deadline:
|
||||
t.Fatalf("timed out waiting for %d in-flight sends (got %d)", n, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertNoExtraEnter(t *testing.T, rec *flightRecorder, wait time.Duration) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-rec.enter:
|
||||
t.Fatal("unexpected extra in-flight send")
|
||||
case <-time.After(wait):
|
||||
}
|
||||
}
|
||||
|
||||
func runDistribute(t *testing.T, targets []*worker_pb.TaskTarget, files map[string]string, rec *flightRecorder, max *int) (map[string][]string, error) {
|
||||
t.Helper()
|
||||
opts := &ShardDistributionOptions{
|
||||
MaxShardTransfers: max,
|
||||
send: rec.send,
|
||||
}
|
||||
return DistributeEcShards(1, "col", targets, files, nil, nil, opts)
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsZeroIsSequential(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02", "ec03")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0),
|
||||
shardTarget("full-01:8080", 1, 1),
|
||||
shardTarget("full-02:8080", 0, 2),
|
||||
shardTarget("full-02:8080", 1, 3),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, intPtr(0))
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 1)
|
||||
assertNoExtraEnter(t, rec, 40*time.Millisecond)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 1 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("max in-flight=%d, want 1 for max_shard_transfers=0", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if rec.maxFlight != 1 {
|
||||
t.Fatalf("max in-flight=%d after release, want 1", rec.maxFlight)
|
||||
}
|
||||
if rec.keyMax != 1 {
|
||||
t.Fatalf("per-key in-flight=%d, want 1", rec.keyMax)
|
||||
}
|
||||
if len(rec.sent) != 4 {
|
||||
t.Fatalf("sent %d shards, want 4: %v", len(rec.sent), rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsNoCapParallelByKey(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02", "ec03")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 1, 0),
|
||||
shardTarget("full-01:8080", 2, 1),
|
||||
shardTarget("full-02:8080", 0, 2),
|
||||
shardTarget("full-02:8081", 0, 3), // same rack host, different destNode
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 4)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 4 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("no cap: max in-flight=%d, want 4 (one per dest disk/node)", rec.maxFlight)
|
||||
}
|
||||
if rec.keyMax != 1 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("per-key in-flight=%d, want 1", rec.keyMax)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if len(rec.sent) != 4 {
|
||||
t.Fatalf("sent %d, want 4: %v", len(rec.sent), rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsSameDiskQueued(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0, 1),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 1)
|
||||
assertNoExtraEnter(t, rec, 40*time.Millisecond)
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if rec.maxFlight != 1 {
|
||||
t.Fatalf("same disk: max in-flight=%d, want 1", rec.maxFlight)
|
||||
}
|
||||
if rec.sent[0] != "full-01:8080/ec00" || rec.sent[1] != "full-01:8080/ec01" {
|
||||
t.Fatalf("same-disk order %v, want ec00 then ec01", rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsAutoDiskSerializesServer(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0), // disk picked by the receiver
|
||||
shardTarget("full-01:8080", 1, 1),
|
||||
shardTarget("full-02:8080", 1, 2),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 2)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 2 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("auto-placement server must serialize: in-flight=%d, want 2 (one per server)", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if len(rec.sent) != 3 {
|
||||
t.Fatalf("sent %d, want 3", len(rec.sent))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsTwoDisksTwoStreams(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 1, 0),
|
||||
shardTarget("full-01:8080", 2, 1),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 2)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 2 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("two disks on one VS: in-flight=%d, want 2", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsCapNeverExceedsN(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02", "ec03")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 1, 0),
|
||||
shardTarget("full-01:8080", 2, 1),
|
||||
shardTarget("full-02:8080", 1, 2),
|
||||
shardTarget("full-02:8080", 2, 3),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, intPtr(2))
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 2)
|
||||
assertNoExtraEnter(t, rec, 40*time.Millisecond)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 2 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("cap 2: in-flight=%d, want 2", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if rec.maxFlight > 2 {
|
||||
t.Fatalf("cap 2: max in-flight=%d", rec.maxFlight)
|
||||
}
|
||||
if rec.keyMax != 1 {
|
||||
t.Fatalf("per-key in-flight=%d, want 1 under cap", rec.keyMax)
|
||||
}
|
||||
if len(rec.sent) != 4 {
|
||||
t.Fatalf("sent %d, want 4", len(rec.sent))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsErrorAbortSameKey(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0, 1, 2),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
rec.noGate.Store(true)
|
||||
rec.failOn = "full-01:8080/ec01"
|
||||
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected send error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "failed to send ec01 to full-01:8080") {
|
||||
t.Fatalf("error wrap: %v", err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if got := strings.Join(rec.attempts, ","); got != "full-01:8080/ec00,full-01:8080/ec01" {
|
||||
t.Fatalf("attempts %v, want ec00 then ec01 (ec02 aborted)", rec.attempts)
|
||||
}
|
||||
if len(rec.sent) != 1 || rec.sent[0] != "full-01:8080/ec00" {
|
||||
t.Fatalf("successful sends %v, want only ec00", rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsErrorAbortCancelsOtherKeys(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0),
|
||||
shardTarget("full-02:8080", 0, 1),
|
||||
shardTarget("full-03:8080", 0, 2),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
rec.noGate.Store(true)
|
||||
rec.failFirst = true
|
||||
|
||||
_, err := runDistribute(t, targets, files, rec, intPtr(1))
|
||||
if err == nil {
|
||||
t.Fatal("expected send error")
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if len(rec.attempts) != 1 {
|
||||
t.Fatalf("cap=1 abort: attempts %v, want only the failing send", rec.attempts)
|
||||
}
|
||||
if len(rec.sent) != 0 {
|
||||
t.Fatalf("successful sends %v, want none", rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsMissingFile(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 1),
|
||||
}
|
||||
for _, max := range []*int{intPtr(0), nil} {
|
||||
_, err := DistributeEcShards(1, "col", targets, files, nil, nil, &ShardDistributionOptions{
|
||||
MaxShardTransfers: max,
|
||||
send: func(context.Context, uint32, string, grpc.DialOption, string, uint32, string, string) error {
|
||||
t.Fatal("send should not run for missing file")
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "shard file ec01 not found") {
|
||||
t.Fatalf("missing file error (max=%v): %v", max, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShardTransferKeyUsesDestNodeNotRack(t *testing.T) {
|
||||
a := shardTransferKey(shardJob{destNode: "full-01:8080", diskID: 0, hasDisk: true})
|
||||
b := shardTransferKey(shardJob{destNode: "full-01:8081", diskID: 0, hasDisk: true})
|
||||
if a == b {
|
||||
t.Fatalf("host:port keys collided: %s", a)
|
||||
}
|
||||
noDisk := shardTransferKey(shardJob{destNode: "full-01:8080", hasDisk: false})
|
||||
if noDisk != "full-01:8080" {
|
||||
t.Fatalf("no disk id key=%q, want destNode", noDisk)
|
||||
}
|
||||
if fmt.Sprint(a) == noDisk {
|
||||
t.Fatalf("disk 0 key should differ from destNode-only when hasDisk")
|
||||
}
|
||||
}
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user