mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7519f68ff1 | ||
|
|
2d41f4ca8b | ||
|
|
d7854ce88e | ||
|
|
8acf21e4d1 | ||
|
|
a99c8214bb | ||
|
|
2d41d37150 | ||
|
|
2b8349f9e9 | ||
|
|
7b4df8b9e2 | ||
|
|
ee56d1a5cd | ||
|
|
71de73bcd4 | ||
|
|
20934cc854 | ||
|
|
21af729cb4 | ||
|
|
1e70bd3fc6 | ||
|
|
4e421400e4 | ||
|
|
56c51e7f50 | ||
|
|
71c33cc1e2 | ||
|
|
d1665750e1 | ||
|
|
0566fbd552 | ||
|
|
d4e39b499b | ||
|
|
adfd731bb8 | ||
|
|
917a87928c | ||
|
|
8fa769f29a | ||
|
|
7c635c4508 | ||
|
|
fbdcec1cba | ||
|
|
0accff0e4a | ||
|
|
9021225591 | ||
|
|
5b42287c22 | ||
|
|
3392493f0a | ||
|
|
d82b3a8d6a | ||
|
|
39e9294907 | ||
|
|
3825035f07 | ||
|
|
83b7ea5e7b | ||
|
|
eae8f33db5 | ||
|
|
2c2b2d4d3e | ||
|
|
cd15ae1395 | ||
|
|
3f6410fdc3 | ||
|
|
87fdea5330 | ||
|
|
303c2be38d | ||
|
|
9b9fdb5b76 | ||
|
|
7e4691f2dc | ||
|
|
391f543ff2 | ||
|
|
afcc491517 | ||
|
|
a5d0e4a735 | ||
|
|
a17dca7009 | ||
|
|
024b59fb31 | ||
|
|
5af7d12f04 | ||
|
|
4385b86bf1 | ||
|
|
c00aa90990 |
No files matched your search
@@ -1,49 +0,0 @@
|
||||
name: EC Integration Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/admin/**'
|
||||
- 'weed/worker/**'
|
||||
- 'test/erasure_coding/admin_dockertest/**'
|
||||
- '.github/workflows/ec-integration.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/admin/**'
|
||||
- 'weed/worker/**'
|
||||
- 'test/erasure_coding/admin_dockertest/**'
|
||||
- '.github/workflows/ec-integration.yml'
|
||||
|
||||
jobs:
|
||||
ec-integration-test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build weed binary
|
||||
run: |
|
||||
cd weed
|
||||
go build -o ../weed_bin
|
||||
|
||||
- name: Run EC integration tests
|
||||
run: |
|
||||
cd test/erasure_coding/admin_dockertest
|
||||
go test -v -timeout 15m ec_integration_test.go
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ec-test-logs
|
||||
path: test/erasure_coding/admin_dockertest/tmp/logs/
|
||||
retention-days: 7
|
||||
@@ -0,0 +1,120 @@
|
||||
name: "Samba on FUSE Integration"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master, main ]
|
||||
paths:
|
||||
- 'weed/mount/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/cluster/**'
|
||||
- 'test/samba/**'
|
||||
- '.github/workflows/samba-integration.yml'
|
||||
pull_request:
|
||||
branches: [ master, main ]
|
||||
paths:
|
||||
- 'weed/mount/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/cluster/**'
|
||||
- 'test/samba/**'
|
||||
- '.github/workflows/samba-integration.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: samba-integration/${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
samba-integration:
|
||||
name: samba-integration
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Start local Docker registry
|
||||
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
driver-opts: network=host
|
||||
|
||||
- name: Build weed race binary
|
||||
run: |
|
||||
cd docker
|
||||
make binary_race
|
||||
|
||||
- name: Build SeaweedFS e2e image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: docker
|
||||
file: docker/Dockerfile.e2e
|
||||
tags: localhost:5000/chrislusf/seaweedfs:e2e
|
||||
push: true
|
||||
cache-from: type=gha,scope=samba-e2e
|
||||
cache-to: type=gha,mode=max,scope=samba-e2e
|
||||
|
||||
- name: Tag e2e image for docker compose
|
||||
run: |
|
||||
docker pull localhost:5000/chrislusf/seaweedfs:e2e
|
||||
docker tag localhost:5000/chrislusf/seaweedfs:e2e chrislusf/seaweedfs:e2e
|
||||
|
||||
- name: Build samba image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: test/samba
|
||||
build-contexts: |
|
||||
chrislusf/seaweedfs:e2e=docker-image://localhost:5000/chrislusf/seaweedfs:e2e
|
||||
tags: localhost:5000/chrislusf/seaweedfs:samba
|
||||
push: true
|
||||
cache-from: type=gha,scope=samba-harness
|
||||
cache-to: type=gha,mode=max,scope=samba-harness
|
||||
|
||||
- name: Tag samba image for docker compose
|
||||
run: |
|
||||
docker pull localhost:5000/chrislusf/seaweedfs:samba
|
||||
docker tag localhost:5000/chrislusf/seaweedfs:samba chrislusf/seaweedfs:samba
|
||||
|
||||
- name: Start SeaweedFS cluster and Samba
|
||||
run: |
|
||||
docker compose -f test/samba/docker-compose.yml up --wait
|
||||
|
||||
- name: Run Samba test battery
|
||||
run: |
|
||||
set -o pipefail
|
||||
docker compose -f test/samba/docker-compose.yml exec -T samba \
|
||||
/run_inside_container.sh 2>&1 | tee /tmp/samba-output.log
|
||||
|
||||
- name: Collect logs
|
||||
if: always()
|
||||
run: |
|
||||
mkdir -p /tmp/samba-docker-logs
|
||||
for svc in master volume filer samba; do
|
||||
docker compose -f test/samba/docker-compose.yml logs "$svc" \
|
||||
> "/tmp/samba-docker-logs/${svc}.log" 2>&1 || true
|
||||
done
|
||||
|
||||
- name: Tear down
|
||||
if: always()
|
||||
run: |
|
||||
docker compose -f test/samba/docker-compose.yml down -v
|
||||
|
||||
- name: Upload logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: samba-integration-results
|
||||
path: |
|
||||
/tmp/samba-output.log
|
||||
/tmp/samba-docker-logs/
|
||||
retention-days: 7
|
||||
@@ -42,6 +42,10 @@ RUN if [ -f "/prebuilt/weed-volume-${TARGETARCH}" ]; then \
|
||||
echo "Skipping Rust build for $TARGETARCH (unsupported)" && \
|
||||
touch /weed-volume; \
|
||||
fi
|
||||
# Pre-built binaries arrive via GitHub Actions artifacts, which drop the
|
||||
# executable bit, so the copied file is 0644 and exec fails with "Permission
|
||||
# denied". Restore it (no-op for the empty placeholder, which stays size 0).
|
||||
RUN chmod 0755 /weed-volume
|
||||
|
||||
FROM alpine AS final
|
||||
LABEL author="Chris Lu"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.27"
|
||||
appVersion: "4.28"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.27.0
|
||||
version: 4.28.0
|
||||
@@ -137,6 +137,9 @@ spec:
|
||||
- "/bin/sh"
|
||||
- "-ec"
|
||||
- |
|
||||
{{- if $volume.rust }}
|
||||
exec /usr/bin/weed-volume \
|
||||
{{- else }}
|
||||
exec /usr/bin/weed \
|
||||
{{- if $volume.logs }}
|
||||
-logdir=/logs \
|
||||
@@ -149,6 +152,7 @@ spec:
|
||||
-v={{ $.Values.global.seaweedfs.loggingLevel }} \
|
||||
{{- end }}
|
||||
volume \
|
||||
{{- end }}
|
||||
-port={{ $volume.port }} \
|
||||
{{- if $volume.metricsPort }}
|
||||
-metricsPort={{ $volume.metricsPort }} \
|
||||
@@ -180,7 +184,7 @@ spec:
|
||||
{{- if $volume.imagesFixOrientation }}
|
||||
-images.fix.orientation \
|
||||
{{- end }}
|
||||
{{- if $volume.pulseSeconds }}
|
||||
{{- if and $volume.pulseSeconds (not $volume.rust) }}
|
||||
-pulseSeconds={{ $volume.pulseSeconds }} \
|
||||
{{- end }}
|
||||
{{- if $volume.index }}
|
||||
|
||||
@@ -305,6 +305,11 @@ volume:
|
||||
enabled: true
|
||||
imageOverride: null
|
||||
restartPolicy: null
|
||||
# Run the Rust volume server (/usr/bin/weed-volume) instead of the Go one.
|
||||
# Requires an image that ships the Rust binary (amd64/arm64). The Go-only
|
||||
# log flags (-logtostderr/-logdir/-v) and -pulseSeconds are dropped; set log
|
||||
# level via the RUST_LOG env var in extraEnvironmentVars if needed.
|
||||
rust: false
|
||||
port: 8080
|
||||
grpcPort: 18080
|
||||
metricsPort: 9327
|
||||
|
||||
@@ -22,6 +22,9 @@ service SeaweedFiler {
|
||||
rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {
|
||||
}
|
||||
|
||||
rpc FinalizeVersionedWrite (FinalizeVersionedWriteRequest) returns (FinalizeVersionedWriteResponse) {
|
||||
}
|
||||
|
||||
rpc TouchAccessTime (TouchAccessTimeRequest) returns (TouchAccessTimeResponse) {
|
||||
}
|
||||
|
||||
@@ -222,6 +225,29 @@ message CreateEntryRequest {
|
||||
bool is_from_other_cluster = 4;
|
||||
repeated int32 signatures = 5;
|
||||
bool skip_check_parent_directory = 6;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the write, under the filer's per-path lock. The caller must route the
|
||||
// key's writes to this entry's owner filer for the check to be authoritative.
|
||||
WriteCondition condition = 7;
|
||||
}
|
||||
|
||||
// WriteCondition is a single precondition the filer evaluates against the
|
||||
// existing entry before writing. The client reduces request semantics (e.g.
|
||||
// RFC 7232 precedence) to one primitive; the filer just compares. A failed
|
||||
// condition returns FilerError PRECONDITION_FAILED.
|
||||
message WriteCondition {
|
||||
enum Kind {
|
||||
NONE = 0; // unconditional
|
||||
IF_NOT_EXISTS = 1; // fail if the entry exists (If-None-Match: *)
|
||||
IF_EXISTS = 2; // fail if the entry is absent (If-Match: *)
|
||||
IF_ETAG_MATCH = 3; // fail if absent or etag != expected (If-Match: <etag>)
|
||||
IF_ETAG_NOT_MATCH = 4; // fail if present and etag == expected (If-None-Match: <etag>)
|
||||
IF_UNMODIFIED_SINCE = 5; // fail if present and mtime > unix_time
|
||||
IF_MODIFIED_SINCE = 6; // fail if present and mtime <= unix_time
|
||||
}
|
||||
Kind kind = 1;
|
||||
string etag = 2; // expected ETag for IF_ETAG_* kinds
|
||||
int64 unix_time = 3; // bound (unix seconds) for IF_*_SINCE kinds
|
||||
}
|
||||
|
||||
// Structured error codes for filer entry operations.
|
||||
@@ -233,6 +259,7 @@ enum FilerError {
|
||||
EXISTING_IS_DIRECTORY = 3; // cannot overwrite directory with file
|
||||
EXISTING_IS_FILE = 4; // cannot overwrite file with directory
|
||||
ENTRY_ALREADY_EXISTS = 5; // O_EXCL and entry already exists
|
||||
PRECONDITION_FAILED = 6; // WriteCondition not satisfied
|
||||
}
|
||||
|
||||
message CreateEntryResponse {
|
||||
@@ -252,6 +279,40 @@ message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
}
|
||||
|
||||
// FinalizeVersionedWrite atomically finalizes an S3 versioned write on the
|
||||
// object's owner filer, after the caller has created the new version file: under
|
||||
// one exclusive lock on lock_key (the object path — the same key all of this
|
||||
// object's writes serialize on, regardless of versioning state) it evaluates the
|
||||
// precondition against the current latest, stamps the previously-latest version
|
||||
// as noncurrent (before the pointer flip, so the lifecycle router observes it),
|
||||
// then merges the latest-pointer / cached metadata into the .versions directory
|
||||
// entry. The caller routes the object's writes to this owner so the whole
|
||||
// sequence shares one local lock — no distributed lock. Key names are passed in
|
||||
// so the filer stays free of S3 semantics; the new version's file name is read
|
||||
// from set_extended[prior_latest_key].
|
||||
message FinalizeVersionedWriteRequest {
|
||||
string lock_key = 13; // object path; the per-path lock all of this object's writes share
|
||||
string delete_path = 14; // optional entry to delete under the lock first (suspended delete: the null version)
|
||||
string versions_dir = 1; // full path of <object>/.versions
|
||||
map<string, bytes> set_extended = 3; // merge into the .versions directory entry
|
||||
repeated string delete_extended = 4; // remove from the .versions directory entry
|
||||
string prior_latest_key = 5; // .versions entry key holding the latest file name (prior value = demote target)
|
||||
string noncurrent_since_key = 6; // key to stamp on the demoted previous version
|
||||
int64 noncurrent_since_ns = 7; // stamp value; <=0 skips the demote stamp
|
||||
bool is_from_other_cluster = 8;
|
||||
repeated int32 signatures = 9;
|
||||
// Optional precondition, evaluated against the current latest version
|
||||
// (derived from the .versions directory entry's cached metadata) before
|
||||
// anything is written, so the check and the write are atomic on this owner.
|
||||
WriteCondition condition = 10;
|
||||
string latest_etag_key = 11; // .versions entry key holding the latest version's ETag
|
||||
string latest_delete_marker_key = 12; // .versions entry key; "true" means the latest is a delete marker
|
||||
}
|
||||
message FinalizeVersionedWriteResponse {
|
||||
string error = 1;
|
||||
FilerError error_code = 2;
|
||||
}
|
||||
|
||||
message TouchAccessTimeRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
@@ -280,11 +341,16 @@ message DeleteEntryRequest {
|
||||
bool is_from_other_cluster = 7;
|
||||
repeated int32 signatures = 8;
|
||||
int64 if_not_modified_after = 9;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the delete, under the filer's per-path lock. Only honored for a
|
||||
// non-recursive single-entry delete routed to the entry's owner filer.
|
||||
WriteCondition condition = 10;
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
string error = 1;
|
||||
SubscribeMetadataResponse metadata_event = 2;
|
||||
FilerError error_code = 3; // machine-readable error code (e.g. PRECONDITION_FAILED)
|
||||
}
|
||||
|
||||
message AtomicRenameEntryRequest {
|
||||
@@ -421,6 +487,7 @@ message SubscribeMetadataRequest {
|
||||
repeated string directories = 10; // exact directory to watch
|
||||
bool client_supports_batching = 11; // client can unpack SubscribeMetadataResponse.events
|
||||
bool client_supports_metadata_chunks = 12; // client can read log file chunks from volume servers
|
||||
bool client_supports_idle_heartbeat = 13; // server may send empty responses carrying the current time while the client is caught up
|
||||
}
|
||||
message SubscribeMetadataResponse {
|
||||
string directory = 1;
|
||||
|
||||
@@ -3643,6 +3643,67 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_empty_volume() {
|
||||
// Mirror of Go's TestScrubVolumeData "zero-size volume without index"
|
||||
// case (weed/storage/volume_checking_test.go): a freshly created /
|
||||
// pre-allocated volume has a superblock-only .dat and a zero-size .idx,
|
||||
// and must scrub clean instead of being flagged as corrupt.
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
|
||||
// .dat holds only the superblock; .idx is empty.
|
||||
assert_eq!(v.dat_file_size().unwrap(), SUPER_BLOCK_SIZE as u64);
|
||||
|
||||
let (files_checked, broken) = v.scrub().unwrap();
|
||||
assert_eq!(files_checked, 0);
|
||||
assert!(
|
||||
broken.is_empty(),
|
||||
"empty volume should scrub clean, got {:?}",
|
||||
broken
|
||||
);
|
||||
|
||||
// The index-only mode must agree.
|
||||
let (idx_checked, idx_broken) = v.scrub_index().unwrap();
|
||||
assert_eq!(idx_checked, 0);
|
||||
assert!(
|
||||
idx_broken.is_empty(),
|
||||
"empty volume should scrub_index clean, got {:?}",
|
||||
idx_broken
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_healthy_volume() {
|
||||
// Mirror of Go's TestScrubVolumeData "healthy volume" case: a volume
|
||||
// with live needles scrubs clean and the .dat size accounting matches.
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
for i in 1..=5 {
|
||||
let data = format!("needle data {}", i);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let (files_checked, broken) = v.scrub().unwrap();
|
||||
assert_eq!(files_checked, 5);
|
||||
assert!(
|
||||
broken.is_empty(),
|
||||
"healthy volume should scrub clean, got {:?}",
|
||||
broken
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_volume_multiple_needles() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/shell"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// TestMultiDiskECBalanceNoShardLoss is the end-to-end regression for issue 9593.
|
||||
// It runs a real cluster of multi-disk volume servers (3 servers x 4 disks),
|
||||
// EC-encodes a volume, then runs ec.balance, asserting hard invariants the older
|
||||
// integration tests only logged:
|
||||
//
|
||||
// - after encode the full set of 14 EC shards exists,
|
||||
// - ec.balance never loses a shard (still 14 distinct shards afterwards),
|
||||
// - shards end up spread across more than one disk per node, and
|
||||
// - cluster.status counts physical disks (not one per node) and matches the
|
||||
// real on-disk distribution.
|
||||
func TestMultiDiskECBalanceNoShardLoss(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping multi-disk EC integration test in short mode")
|
||||
}
|
||||
|
||||
testDir := t.TempDir()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startMultiDiskCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForServer("127.0.0.1:9334", 30*time.Second))
|
||||
for i := 0; i < 3; i++ {
|
||||
require.NoError(t, waitForServer(fmt.Sprintf("127.0.0.1:809%d", i), 30*time.Second))
|
||||
}
|
||||
t.Log("waiting for multi-disk volume servers to register...")
|
||||
time.Sleep(10 * time.Second)
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&shell.ShellOptions{
|
||||
Masters: stringPtr("127.0.0.1:9334"),
|
||||
GrpcDialOption: grpc.WithInsecure(),
|
||||
FilerGroup: stringPtr("default"),
|
||||
})
|
||||
connectToMasterAndSync(ctx, t, commandEnv)
|
||||
|
||||
// Upload enough small files that the volume holds real data to encode.
|
||||
var volumeId needle.VolumeId
|
||||
for retry := 0; retry < 5; retry++ {
|
||||
volumeId, err = uploadTestDataToMaster([]byte(strings.Repeat("multidisk-ec-9593 ", 64)), "127.0.0.1:9334")
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
require.NoError(t, err, "failed to upload test data")
|
||||
for i := 0; i < 40; i++ {
|
||||
if _, e := uploadTestDataToMaster([]byte(strings.Repeat("filler ", 128)), "127.0.0.1:9334"); e != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
t.Logf("using volume %d", volumeId)
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Populate every server's disks with volumes so the encode can see and target
|
||||
// each physical disk. The master only enumerates disks that already hold a
|
||||
// volume or EC shard — an empty disk leaves no trace in the topology (heartbeats
|
||||
// aggregate capacity per disk type, not per physical disk). ec.encode therefore
|
||||
// spreads a volume's shards only across the disks the master already knows hold
|
||||
// data on each node; if a node's data sits on a single disk, all its shards land
|
||||
// there and ec.balance cannot redistribute them (it has no within-node
|
||||
// cross-disk move). So spreading must be set up before encoding.
|
||||
//
|
||||
// volume.grow only tops up toward a writable target and stops on the first
|
||||
// allocation error, so a single -count grow can create far fewer volumes than
|
||||
// asked and leave a node on one disk. Grow repeatedly on the nodes that have not
|
||||
// spread yet (the volume server places each new volume on its least-loaded disk)
|
||||
// until the master's topology shows every node holding volumes on at least two
|
||||
// physical disks. This makes the multi-disk layout — and thus the post-encode
|
||||
// disk spread — deterministic instead of racing volume-growth and heartbeat.
|
||||
require.Eventually(t, func() bool {
|
||||
spread := nodeVolumeDiskCounts(t, commandEnv)
|
||||
if len(spread) == 3 && allAtLeast(spread, 2) {
|
||||
return true
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
server := fmt.Sprintf("127.0.0.1:809%d", i)
|
||||
if spread[server] < 2 {
|
||||
captureCommandOutput(t, shell.Commands[findCommandIndex("volume.grow")],
|
||||
[]string{"-collection", "test", "-dataNode", server, "-count", "4"}, commandEnv)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, 60*time.Second, 2*time.Second,
|
||||
"volumes never spread across >=2 disks on all 3 nodes")
|
||||
|
||||
locked, unlock := tryLockWithTimeout(t, commandEnv, 15*time.Second)
|
||||
require.True(t, locked, "could not acquire shell lock")
|
||||
defer unlock()
|
||||
|
||||
// EC-encode the volume.
|
||||
out, err := captureCommandOutput(t, shell.Commands[findCommandIndex("ec.encode")],
|
||||
[]string{"-volumeId", fmt.Sprintf("%d", volumeId), "-collection", "test", "-force"}, commandEnv)
|
||||
t.Logf("ec.encode output:\n%s", out)
|
||||
require.NoError(t, err, "ec.encode failed")
|
||||
|
||||
// All 14 shards must exist after encoding.
|
||||
require.Eventually(t, func() bool {
|
||||
return len(collectDistinctShardIDs(testDir, uint32(volumeId))) == erasureShardCount
|
||||
}, 30*time.Second, time.Second, "expected all %d EC shards after encode, got %v",
|
||||
erasureShardCount, collectDistinctShardIDs(testDir, uint32(volumeId)))
|
||||
|
||||
beforeBalance := collectDistinctShardIDs(testDir, uint32(volumeId))
|
||||
t.Logf("after encode: %d distinct shards on %d disks", len(beforeBalance), disksWithShards(testDir, uint32(volumeId)))
|
||||
|
||||
// Run ec.balance.
|
||||
out, err = captureCommandOutput(t, shell.Commands[findCommandIndex("ec.balance")],
|
||||
[]string{"-collection", "test", "-force"}, commandEnv)
|
||||
t.Logf("ec.balance output:\n%s", out)
|
||||
require.NoError(t, err, "ec.balance failed")
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// The core regression: ec.balance must not lose any shard.
|
||||
afterBalance := collectDistinctShardIDs(testDir, uint32(volumeId))
|
||||
require.Equal(t, erasureShardCount, len(afterBalance),
|
||||
"ec.balance lost shards on multi-disk nodes: had %v, now %v", sortedKeysOf(beforeBalance), sortedKeysOf(afterBalance))
|
||||
|
||||
// Shards must be spread across more than one physical disk per node overall.
|
||||
usedDisks := disksWithShards(testDir, uint32(volumeId))
|
||||
assert.Greater(t, usedDisks, 3, "EC shards should span more than one disk per node (got %d disks across 3 nodes)", usedDisks)
|
||||
|
||||
// cluster.status must count physical disks, not collapse to one per node: it
|
||||
// must report at least the disks actually holding this volume's shards (which
|
||||
// is already >3 across the 3 nodes). Before the fix it reported 3 (node count).
|
||||
require.Eventually(t, func() bool {
|
||||
n, ok := clusterStatusDiskCount(t, commandEnv)
|
||||
return ok && n >= usedDisks
|
||||
}, 30*time.Second, 2*time.Second, "cluster.status never reported the >=%d physical disks holding shards (multi-disk count)", usedDisks)
|
||||
|
||||
n, _ := clusterStatusDiskCount(t, commandEnv)
|
||||
t.Logf("cluster.status reports %d physical disks (>= %d holding this volume's shards)", n, usedDisks)
|
||||
}
|
||||
|
||||
const erasureShardCount = 14 // 10 data + 4 parity
|
||||
|
||||
// collectDistinctShardIDs returns the set of EC shard ids present for a volume
|
||||
// across every disk of every server in the multi-disk test layout.
|
||||
func collectDistinctShardIDs(testDir string, volumeId uint32) map[int]bool {
|
||||
ids := map[int]bool{}
|
||||
for server := 0; server < 3; server++ {
|
||||
for disk := 0; disk < 4; disk++ {
|
||||
diskDir := filepath.Join(testDir, fmt.Sprintf("server%d_disk%d", server, disk))
|
||||
files, err := listECShardFiles(diskDir, volumeId)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, f := range files {
|
||||
i := strings.LastIndex(f, ".ec")
|
||||
if i < 0 {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(f[i+3:]); err == nil && n >= 0 && n < erasureShardCount {
|
||||
ids[n] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// disksWithShards counts how many physical disks hold at least one shard.
|
||||
func disksWithShards(testDir string, volumeId uint32) int {
|
||||
n := 0
|
||||
for _, disks := range countShardsPerDisk(testDir, volumeId) {
|
||||
for _, c := range disks {
|
||||
if c > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// nodeVolumeDiskCounts returns, per volume server id, how many distinct physical
|
||||
// disks hold at least one volume according to the master's topology. The master
|
||||
// only enumerates disks that already hold a volume or EC shard (heartbeats
|
||||
// aggregate capacity per disk type, not per physical disk), so this reports the
|
||||
// disks ec.encode can actually spread a volume's shards across on each node.
|
||||
func nodeVolumeDiskCounts(t *testing.T, commandEnv *shell.CommandEnv) map[string]int {
|
||||
t.Helper()
|
||||
var resp *master_pb.VolumeListResponse
|
||||
err := commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
|
||||
var e error
|
||||
resp, e = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
return e
|
||||
})
|
||||
counts := map[string]int{}
|
||||
if err != nil || resp.GetTopologyInfo() == nil {
|
||||
return counts
|
||||
}
|
||||
for _, dc := range resp.GetTopologyInfo().GetDataCenterInfos() {
|
||||
for _, r := range dc.GetRackInfos() {
|
||||
for _, dn := range r.GetDataNodeInfos() {
|
||||
disks := map[uint32]bool{}
|
||||
for _, di := range dn.GetDiskInfos() {
|
||||
for _, vi := range di.GetVolumeInfos() {
|
||||
disks[vi.GetDiskId()] = true
|
||||
}
|
||||
}
|
||||
counts[dn.Id] = len(disks)
|
||||
}
|
||||
}
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
func allAtLeast(counts map[string]int, min int) bool {
|
||||
for _, c := range counts {
|
||||
if c < min {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var diskCountRe = regexp.MustCompile(`(\d+)\s+disks?`)
|
||||
|
||||
// clusterStatusDiskCount runs cluster.status and parses the reported disk count.
|
||||
func clusterStatusDiskCount(t *testing.T, commandEnv *shell.CommandEnv) (int, bool) {
|
||||
t.Helper()
|
||||
out, err := captureCommandOutput(t, shell.Commands[findCommandIndex("cluster.status")], []string{}, commandEnv)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
m := diskCountRe.FindStringSubmatch(out)
|
||||
if m == nil {
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.Atoi(m[1])
|
||||
return n, err == nil
|
||||
}
|
||||
|
||||
func sortedKeysOf(m map[int]bool) []int {
|
||||
out := make([]int, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
for i := 1; i < len(out); i++ {
|
||||
for j := i; j > 0 && out[j-1] > out[j]; j-- {
|
||||
out[j-1], out[j] = out[j], out[j-1]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -207,8 +207,10 @@ func buildVolumeListResponse(t *testing.T, spec topologySpec, volumeID uint32) *
|
||||
t.Helper()
|
||||
|
||||
volumeSizeLimitMB := uint64(100)
|
||||
volumeSize := uint64(90) * 1024 * 1024
|
||||
volumeModifiedAt := time.Now().Add(-10 * time.Minute).Unix()
|
||||
// Exceed the default fullness (0.95) and quiet (1h) thresholds so volumes are
|
||||
// EC-eligible.
|
||||
volumeSize := uint64(96) * 1024 * 1024
|
||||
volumeModifiedAt := time.Now().Add(-2 * time.Hour).Unix()
|
||||
|
||||
diskTypes := spec.diskTypes
|
||||
if len(diskTypes) == 0 {
|
||||
|
||||
@@ -29,9 +29,11 @@ func TestErasureCodingDetectionLargeTopology(t *testing.T) {
|
||||
}
|
||||
|
||||
nodesPerRack := serverCount / rackCount
|
||||
eligibleSize := uint64(90) * 1024 * 1024
|
||||
// Eligible volumes must exceed the default fullness (0.95) and quiet (1h)
|
||||
// thresholds; ineligible ones fall below the fullness threshold.
|
||||
eligibleSize := uint64(96) * 1024 * 1024
|
||||
ineligibleSize := uint64(10) * 1024 * 1024
|
||||
modifiedAt := time.Now().Add(-10 * time.Minute).Unix()
|
||||
modifiedAt := time.Now().Add(-2 * time.Hour).Unix()
|
||||
|
||||
volumeID := uint32(1)
|
||||
dataCenters := make([]*master_pb.DataCenterInfo, 0, 1)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
FROM chrislusf/seaweedfs:e2e
|
||||
|
||||
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y \
|
||||
--no-install-recommends \
|
||||
--no-install-suggests \
|
||||
samba \
|
||||
smbclient \
|
||||
python3-minimal \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY smb.conf.template /smb.conf.template
|
||||
COPY smb_tests.sh /smb_tests.sh
|
||||
COPY lock_tests.sh /lock_tests.sh
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
COPY run_inside_container.sh /run_inside_container.sh
|
||||
RUN chmod +x /smb_tests.sh /lock_tests.sh /entrypoint.sh /run_inside_container.sh
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
@@ -0,0 +1,96 @@
|
||||
# Samba on FUSE integration test
|
||||
|
||||
Exports a SeaweedFS FUSE mount over SMB with Samba's `smbd` and drives it with
|
||||
`smbclient`, verifying that SMB file operations work correctly on top of the
|
||||
mount and that data stays consistent across both protocols.
|
||||
|
||||
## What it checks
|
||||
|
||||
The functional battery in `smb_tests.sh` covers:
|
||||
|
||||
- connecting to the share and listing the root
|
||||
- 1 MiB upload/download round-trip with content verification
|
||||
- subdirectory creation and writes into it
|
||||
- file rename
|
||||
- 64 MiB upload/download (exercises SeaweedFS chunk splitting)
|
||||
- recursive upload of a directory tree
|
||||
- cross-protocol consistency: files written over SMB appear on the FUSE mount
|
||||
with identical content, and files written directly on the FUSE mount are
|
||||
readable over SMB
|
||||
- deleting files and directory trees
|
||||
|
||||
The locking / concurrency battery in `lock_tests.sh` covers the harder cases a
|
||||
network-filesystem backend has to get right:
|
||||
|
||||
- **POSIX `fcntl` byte-range locking** on the FUSE mount: a held exclusive lock
|
||||
denies a conflicting lock, allows a non-overlapping range, and is reacquirable
|
||||
after release (exercises the mount's `SetLk`/`GetLk`)
|
||||
- **Distributed locking** (`-dlm`): a file held open for writing on one mount
|
||||
blocks a writer on a second mount until it is released
|
||||
- **Distributed-lock integrity**: concurrent writers to the same file from two
|
||||
mounts leave exactly one intact payload, never a torn mix
|
||||
- **Concurrency**: parallel writers to distinct files all succeed
|
||||
|
||||
Both FUSE mounts are started with `-dlm` (distributed lock manager). The second
|
||||
mount (`/mnt/seaweedfs2`) exists only to contend with the smbd-backed mount in
|
||||
the distributed-locking tests; both see the same filer path, so `.../share` is
|
||||
the same data on each.
|
||||
|
||||
> Note on DLM semantics: `-dlm` coordinates *write access* (one mount writes a
|
||||
> file at a time) and guarantees writes are not torn. It does not guarantee
|
||||
> which concurrent writer wins or instant cross-mount read convergence — the
|
||||
> holder's buffered data is flushed on close, asynchronously to lock release.
|
||||
> When a holder closes the file, a writer on another mount acquires the freed
|
||||
> lock within ~1s and completes.
|
||||
|
||||
## Layout
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| `smb_tests.sh` | SMB functional battery. Shared by both runners. |
|
||||
| `lock_tests.sh` | SMB locking / concurrency battery. Shared by both runners. |
|
||||
| `smb.conf.template` | Samba config; placeholders are filled in at run time. |
|
||||
| `run.sh` | Local runner: `weed mini` + two `-dlm` mounts + `smbd` + both batteries, all as the current user on unprivileged ports. |
|
||||
| `entrypoint.sh` | Container entrypoint: starts two `-dlm` FUSE mounts and runs `smbd`. |
|
||||
| `run_inside_container.sh` | Runs both batteries inside the container against the local `smbd`. |
|
||||
| `Dockerfile` | Adds Samba to the `chrislusf/seaweedfs:e2e` image. |
|
||||
| `docker-compose.yml` | master + volume + filer + samba services. |
|
||||
|
||||
## Running locally
|
||||
|
||||
Requirements: `weed` on `$PATH`, `fusermount3`, and Samba's `smbd` /
|
||||
`smbclient` / `smbpasswd` (Debian/Ubuntu: `apt-get install samba smbclient`).
|
||||
|
||||
```sh
|
||||
test/samba/run.sh
|
||||
```
|
||||
|
||||
No `sudo` is needed: `smbd` runs as the current user on port 4450 and all state
|
||||
lives under a temp work dir that is cleaned up on exit.
|
||||
|
||||
## Running with Docker
|
||||
|
||||
Mirrors the CI job. Requires `/dev/fuse` and `SYS_ADMIN` (provided in the
|
||||
compose file).
|
||||
|
||||
```sh
|
||||
# build the base e2e image first (from the repo's docker/ dir)
|
||||
docker compose -f test/samba/docker-compose.yml up --wait
|
||||
docker compose -f test/samba/docker-compose.yml exec -T samba /run_inside_container.sh
|
||||
docker compose -f test/samba/docker-compose.yml down -v
|
||||
```
|
||||
|
||||
## CI
|
||||
|
||||
`.github/workflows/samba-integration.yml` runs on changes to `weed/mount/**`,
|
||||
`weed/filer/**`, or `test/samba/**`. It builds the e2e image, builds the Samba
|
||||
harness image on top, brings up the cluster, runs the battery, and uploads
|
||||
server logs as artifacts.
|
||||
|
||||
## Notes
|
||||
|
||||
- The share disables Samba's DOS-attribute / xattr mapping and oplocks. The
|
||||
SeaweedFS FUSE mount does not implement that surface, and leaving it on
|
||||
produces `NT_STATUS_NOT_SUPPORTED` errors unrelated to data integrity.
|
||||
- The share path is a subdirectory of the mount (`.../share`) so the runner can
|
||||
verify SMB-side operations directly on the FUSE side.
|
||||
@@ -0,0 +1,60 @@
|
||||
services:
|
||||
master:
|
||||
image: chrislusf/seaweedfs:e2e
|
||||
command: "-v=4 master -ip=master -ip.bind=0.0.0.0 -raftBootstrap"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "--fail", "-I", "http://localhost:9333/cluster/healthz"]
|
||||
interval: 2s
|
||||
timeout: 10s
|
||||
retries: 30
|
||||
start_period: 10s
|
||||
|
||||
volume:
|
||||
image: chrislusf/seaweedfs:e2e
|
||||
command: "-v=4 volume -master=master:9333 -ip=volume -ip.bind=0.0.0.0 -preStopSeconds=1"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "--fail", "-I", "http://localhost:8080/healthz"]
|
||||
interval: 2s
|
||||
timeout: 10s
|
||||
retries: 15
|
||||
start_period: 5s
|
||||
depends_on:
|
||||
master:
|
||||
condition: service_healthy
|
||||
|
||||
filer:
|
||||
image: chrislusf/seaweedfs:e2e
|
||||
command: "-v=4 filer -master=master:9333 -ip=filer -ip.bind=0.0.0.0"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "--fail", "-I", "http://localhost:8888/healthz"]
|
||||
interval: 2s
|
||||
timeout: 10s
|
||||
retries: 15
|
||||
start_period: 5s
|
||||
depends_on:
|
||||
volume:
|
||||
condition: service_healthy
|
||||
|
||||
samba:
|
||||
image: chrislusf/seaweedfs:samba
|
||||
build:
|
||||
context: .
|
||||
environment:
|
||||
FILER: filer:8888
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
devices:
|
||||
- /dev/fuse
|
||||
security_opt:
|
||||
- apparmor:unconfined
|
||||
healthcheck:
|
||||
test:
|
||||
- "CMD-SHELL"
|
||||
- "mountpoint -q /mnt/seaweedfs && mountpoint -q /mnt/seaweedfs2 && smbclient -L 127.0.0.1 -p 445 -U smbtest%smbtest -m SMB3 >/dev/null 2>&1"
|
||||
interval: 3s
|
||||
timeout: 10s
|
||||
retries: 20
|
||||
start_period: 15s
|
||||
depends_on:
|
||||
filer:
|
||||
condition: service_healthy
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Entrypoint for the samba test container.
|
||||
#
|
||||
# Mounts SeaweedFS over FUSE twice, both with distributed locking (-dlm) so the
|
||||
# locking tests can exercise cross-mount write coordination:
|
||||
# - MOUNT_DIR (/mnt/seaweedfs) is exported over SMB by smbd
|
||||
# - MOUNT2_DIR (/mnt/seaweedfs2) is a second, independent mount of the same
|
||||
# filer used to contend with the SMB writer
|
||||
#
|
||||
# Both mounts see the same filer path, so .../share is the same data on each.
|
||||
# smbd runs in the foreground (as root, which owns the mounts), so the share
|
||||
# uses "force user = root".
|
||||
set -euo pipefail
|
||||
|
||||
FILER="${FILER:-filer:8888}"
|
||||
MOUNT_DIR="${MOUNT_DIR:-/mnt/seaweedfs}"
|
||||
MOUNT2_DIR="${MOUNT2_DIR:-/mnt/seaweedfs2}"
|
||||
SHARE_DIR="${MOUNT_DIR}/share"
|
||||
STATE_DIR="${STATE_DIR:-/var/lib/samba-test}"
|
||||
SMB_PORT="${SMB_PORT:-445}"
|
||||
SMB_USER="${SMB_USER:-smbtest}"
|
||||
SMB_PASS="${SMB_PASS:-smbtest}"
|
||||
|
||||
mkdir -p "${MOUNT_DIR}" "${MOUNT2_DIR}" \
|
||||
"${STATE_DIR}/private" "${STATE_DIR}/state" "${STATE_DIR}/cache" \
|
||||
"${STATE_DIR}/lock" "${STATE_DIR}/pid" "${STATE_DIR}/ncalrpc"
|
||||
|
||||
# mount_seaweedfs <mountpoint> <logfile> — mount with -dlm and wait for it.
|
||||
mount_seaweedfs() {
|
||||
local dir="$1" log="$2"
|
||||
echo "==> Mounting SeaweedFS (${FILER}) at ${dir} with -dlm"
|
||||
weed -v=1 mount \
|
||||
-filer="${FILER}" \
|
||||
-dir="${dir}" \
|
||||
-filer.path=/ \
|
||||
-dirAutoCreate \
|
||||
-allowOthers \
|
||||
-dlm \
|
||||
>"${log}" 2>&1 &
|
||||
local pid=$!
|
||||
for _ in $(seq 1 120); do
|
||||
if mountpoint -q "${dir}"; then
|
||||
return 0
|
||||
fi
|
||||
if ! kill -0 "${pid}" 2>/dev/null; then
|
||||
echo "weed mount (${dir}) exited early; log tail:" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "FUSE mount ${dir} did not come up" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
}
|
||||
|
||||
mount_seaweedfs "${MOUNT_DIR}" /var/log/weed-mount.log
|
||||
mount_seaweedfs "${MOUNT2_DIR}" /var/log/weed-mount2.log
|
||||
|
||||
mkdir -p "${SHARE_DIR}"
|
||||
chmod 0777 "${SHARE_DIR}"
|
||||
|
||||
# --- configure and start smbd ----------------------------------------------
|
||||
echo "==> Configuring Samba share on port ${SMB_PORT}"
|
||||
sed -e "s#@SHARE_PATH@#${SHARE_DIR}#g" \
|
||||
-e "s#@STATE_DIR@#${STATE_DIR}#g" \
|
||||
-e "s#@SMB_PORT@#${SMB_PORT}#g" \
|
||||
-e "s#@FORCE_USER@#root#g" \
|
||||
/smb.conf.template >/etc/samba/smb.conf
|
||||
|
||||
id -u "${SMB_USER}" >/dev/null 2>&1 || useradd -M -s /usr/sbin/nologin "${SMB_USER}"
|
||||
printf '%s\n%s\n' "${SMB_PASS}" "${SMB_PASS}" | smbpasswd -a -s "${SMB_USER}"
|
||||
|
||||
echo "==> Starting smbd"
|
||||
exec smbd -F --no-process-group -s /etc/samba/smb.conf
|
||||
Executable
+218
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Locking / concurrency test battery for Samba on a SeaweedFS FUSE mount.
|
||||
#
|
||||
# Covers the challenges a network-filesystem backend has to get right:
|
||||
# 1. POSIX fcntl byte-range locking on the FUSE mount (SetLk/GetLk)
|
||||
# 2. Distributed locking (-dlm): a write held open on one mount blocks a
|
||||
# writer on another mount until it is released
|
||||
# 3. Distributed locking integrity: concurrent writers to the same file from
|
||||
# two mounts produce intact (non-torn) data
|
||||
# 4. Concurrent writers to distinct files all succeed
|
||||
#
|
||||
# Required env:
|
||||
# SMB_USER, SMB_PASS samba credentials
|
||||
# MOUNT_SHARE dir on the smbd-backed FUSE mount (mount 1)
|
||||
# MOUNT2_SHARE dir on the second FUSE mount (mount 2)
|
||||
# Optional env:
|
||||
# SMB_HOST (127.0.0.1), SMB_SHARE (seaweedfs), SMB_PORT (445)
|
||||
set -uo pipefail
|
||||
|
||||
SMB_HOST="${SMB_HOST:-127.0.0.1}"
|
||||
SMB_SHARE="${SMB_SHARE:-seaweedfs}"
|
||||
SMB_PORT="${SMB_PORT:-445}"
|
||||
SMB_USER="${SMB_USER:?SMB_USER is required}"
|
||||
SMB_PASS="${SMB_PASS:?SMB_PASS is required}"
|
||||
MOUNT_SHARE="${MOUNT_SHARE:?MOUNT_SHARE is required}"
|
||||
MOUNT2_SHARE="${MOUNT2_SHARE:?MOUNT2_SHARE is required}"
|
||||
|
||||
WORK="$(mktemp -d /tmp/samba-locktest.XXXXXX)"
|
||||
trap 'rm -rf "${WORK}"' EXIT
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
pass() { printf ' [PASS] %s\n' "$1"; PASS=$((PASS + 1)); }
|
||||
fail() { printf ' [FAIL] %s\n' "$1"; FAIL=$((FAIL + 1)); }
|
||||
|
||||
smb() {
|
||||
smbclient "//${SMB_HOST}/${SMB_SHARE}" -p "${SMB_PORT}" \
|
||||
-U "${SMB_USER}%${SMB_PASS}" -m SMB3 -c "$1"
|
||||
}
|
||||
md5() { md5sum "$1" | awk '{print $1}'; }
|
||||
|
||||
# 1. POSIX fcntl byte-range locking on the FUSE mount ------------------------
|
||||
# Exercises the mount's SetLk/GetLk via two processes contending over fcntl
|
||||
# (F_SETLK) byte-range locks. python3's fcntl.lockf issues real POSIX locks.
|
||||
echo "==> 1. POSIX fcntl byte-range locking (FUSE mount SetLk/GetLk)"
|
||||
lockfile="${MOUNT_SHARE}/fcntl_lock.dat"
|
||||
: >"${lockfile}"
|
||||
fcntl_out="$(python3 - "${lockfile}" <<'PY'
|
||||
import fcntl, os, sys
|
||||
|
||||
path = sys.argv[1]
|
||||
parent_to_child_r, parent_to_child_w = os.pipe() # release signal
|
||||
child_to_parent_r, child_to_parent_w = os.pipe() # locked signal
|
||||
|
||||
pid = os.fork()
|
||||
if pid == 0: # child: hold an exclusive lock on [0,100)
|
||||
fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX, 100, 0, 0)
|
||||
os.write(child_to_parent_w, b"L")
|
||||
os.read(parent_to_child_r, 1) # wait until parent says release
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 0, 0)
|
||||
os.close(fd)
|
||||
os._exit(0)
|
||||
|
||||
# parent
|
||||
os.read(child_to_parent_r, 1) # wait until child holds the lock
|
||||
fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
results = []
|
||||
|
||||
# a. a conflicting exclusive lock must be denied while the child holds it
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 100, 0, 0)
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 0, 0)
|
||||
results.append(("conflicting exclusive lock denied while held", False))
|
||||
except OSError:
|
||||
results.append(("conflicting exclusive lock denied while held", True))
|
||||
|
||||
# b. a non-overlapping range must be grantable
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 100, 200, 0)
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 200, 0)
|
||||
results.append(("non-overlapping range lock granted", True))
|
||||
except OSError:
|
||||
results.append(("non-overlapping range lock granted", False))
|
||||
|
||||
# c. after the holder releases, the lock must be acquirable
|
||||
os.write(parent_to_child_w, b"R")
|
||||
os.waitpid(pid, 0)
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 100, 0, 0)
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 0, 0)
|
||||
results.append(("lock acquirable after holder releases", True))
|
||||
except OSError:
|
||||
results.append(("lock acquirable after holder releases", False))
|
||||
|
||||
for name, ok in results:
|
||||
print((" [PASS] " if ok else " [FAIL] ") + name)
|
||||
sys.exit(0 if all(ok for _, ok in results) else 1)
|
||||
PY
|
||||
)"
|
||||
echo "${fcntl_out}"
|
||||
PASS=$((PASS + $(grep -c '\[PASS\]' <<<"${fcntl_out}")))
|
||||
FAIL=$((FAIL + $(grep -c '\[FAIL\]' <<<"${fcntl_out}")))
|
||||
|
||||
# 2. Distributed lock blocks a cross-mount writer, then hands it off ----------
|
||||
# mount 2 holds a file open for writing (holding the DLM lock on its path).
|
||||
# An SMB put of the same file goes through mount 1 and must (a) block while
|
||||
# mount 2 holds it and (b) succeed once mount 2 releases, leaving the SMB
|
||||
# writer's payload on disk. smbclient gets a long client timeout (-t) so we are
|
||||
# testing the lock handoff itself, not smbclient's own ~20s default timeout.
|
||||
echo "==> 2. distributed lock: cross-mount write coordination"
|
||||
dlmfile="dlm_coord.bin"
|
||||
newdata="${WORK}/dlm_new.bin"
|
||||
head -c 4096 /dev/urandom >"${newdata}"
|
||||
|
||||
# Hold the file open for writing on mount 2 via fd 9 -> holds the DLM lock.
|
||||
exec 9>"${MOUNT2_SHARE}/${dlmfile}"
|
||||
printf 'held-by-mount2' >&9
|
||||
|
||||
# Start the SMB write; record its real exit code when it returns. The subshell
|
||||
# must NOT inherit fd 9 (9>&-): otherwise the SMB writer keeps the file open and
|
||||
# waits on a DLM lock held by its own inherited descriptor, deadlocking the
|
||||
# handoff this test is meant to exercise.
|
||||
rm -f "${WORK}/dlm_put.rc"
|
||||
(
|
||||
smbclient "//${SMB_HOST}/${SMB_SHARE}" -p "${SMB_PORT}" \
|
||||
-U "${SMB_USER}%${SMB_PASS}" -m SMB3 -t 120 \
|
||||
-c "put ${newdata} ${dlmfile}" >/dev/null 2>&1
|
||||
echo "$?" >"${WORK}/dlm_put.rc"
|
||||
) 9>&- &
|
||||
smb_bg=$!
|
||||
|
||||
sleep 4
|
||||
if [[ ! -f "${WORK}/dlm_put.rc" ]]; then
|
||||
pass "SMB write blocks while another mount holds the file open"
|
||||
else
|
||||
fail "SMB write returned early instead of blocking (rc=$(cat "${WORK}/dlm_put.rc"))"
|
||||
fi
|
||||
|
||||
# Release mount 2's DLM lock; the blocked SMB write must now complete.
|
||||
exec 9>&-
|
||||
|
||||
# Wait (bounded) for the SMB put to finish so a stuck handoff fails the test
|
||||
# instead of hanging the suite.
|
||||
put_rc="timeout"
|
||||
for _ in $(seq 1 20); do
|
||||
if [[ -f "${WORK}/dlm_put.rc" ]]; then
|
||||
put_rc="$(cat "${WORK}/dlm_put.rc")"
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
kill "${smb_bg}" 2>/dev/null
|
||||
wait "${smb_bg}" 2>/dev/null
|
||||
|
||||
if [[ "${put_rc}" == "0" ]]; then
|
||||
pass "blocked SMB write succeeds after the other mount releases"
|
||||
else
|
||||
fail "blocked SMB write succeeds after the other mount releases (rc=${put_rc})"
|
||||
fi
|
||||
|
||||
# A correct handoff leaves the SMB writer's payload on disk: mount 1 acquired
|
||||
# the lock and wrote after mount 2 released.
|
||||
got="${WORK}/dlm_got.bin"
|
||||
if smb "get ${dlmfile} ${got}" >/dev/null 2>&1 && [[ "$(md5 "${got}")" == "$(md5 "${newdata}")" ]]; then
|
||||
pass "post-release content is the SMB writer's payload (correct handoff)"
|
||||
else
|
||||
fail "post-release content is the SMB writer's payload (correct handoff)"
|
||||
fi
|
||||
|
||||
# 3. Distributed lock integrity: concurrent writers, same file ---------------
|
||||
# An SMB writer (mount 1) and a direct writer (mount 2) race on one file. DLM
|
||||
# serializes them, so the result must be exactly one of the two payloads.
|
||||
echo "==> 3. distributed lock: concurrent writers produce intact data"
|
||||
racefile="dlm_race.bin"
|
||||
payloadA="${WORK}/dlm_raceA.bin"
|
||||
head -c 1048576 /dev/urandom >"${payloadA}"
|
||||
payloadB="direct-write-from-mount2-payload"
|
||||
(smb "put ${payloadA} ${racefile}" >/dev/null 2>&1) &
|
||||
(printf '%s' "${payloadB}" >"${MOUNT2_SHARE}/${racefile}") &
|
||||
wait
|
||||
racegot="${WORK}/dlm_race_got.bin"
|
||||
if smb "get ${racefile} ${racegot}" >/dev/null 2>&1 &&
|
||||
{ [[ "$(md5 "${racegot}")" == "$(md5 "${payloadA}")" ]] || [[ "$(cat "${racegot}")" == "${payloadB}" ]]; }; then
|
||||
pass "concurrent same-file writers leave one intact payload"
|
||||
else
|
||||
fail "concurrent same-file writers leave one intact payload"
|
||||
fi
|
||||
|
||||
# 4. Concurrent writers to distinct files ------------------------------------
|
||||
echo "==> 4. concurrent writers to distinct files"
|
||||
n=6
|
||||
declare -a srcs=()
|
||||
for i in $(seq 1 "${n}"); do
|
||||
s="${WORK}/cc_${i}.bin"
|
||||
head -c 1048576 /dev/urandom >"${s}"
|
||||
srcs+=("${s}")
|
||||
(smb "put ${s} concurrent_${i}.bin" >/dev/null 2>&1) &
|
||||
done
|
||||
wait
|
||||
all_ok=true
|
||||
for i in $(seq 1 "${n}"); do
|
||||
g="${WORK}/cc_got_${i}.bin"
|
||||
if ! smb "get concurrent_${i}.bin ${g}" >/dev/null 2>&1 ||
|
||||
[[ "$(md5 "${srcs[$((i - 1))]}")" != "$(md5 "${g}")" ]]; then
|
||||
all_ok=false
|
||||
fi
|
||||
done
|
||||
if ${all_ok}; then
|
||||
pass "${n} concurrent distinct-file writes all intact"
|
||||
else
|
||||
fail "${n} concurrent distinct-file writes all intact"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "==> Summary: ${PASS} passed, ${FAIL} failed"
|
||||
[[ "${FAIL}" -eq 0 ]]
|
||||
Executable
+203
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Run the SMB (Samba) integration test against a SeaweedFS FUSE mount.
|
||||
#
|
||||
# Pipeline:
|
||||
# 1. start a self-contained "weed mini" (master + volume + filer in one)
|
||||
# 2. mount the filesystem with "weed mount"
|
||||
# 3. export a subdirectory of the mount over SMB with smbd
|
||||
# 4. drive the share with smbclient (test/samba/smb_tests.sh)
|
||||
#
|
||||
# Everything runs as the current user on unprivileged ports, so no sudo is
|
||||
# required. State lives under a temp work dir and is removed on exit.
|
||||
#
|
||||
# Requirements: weed in $PATH, fusermount3, and Samba's smbd / smbclient /
|
||||
# smbpasswd (Debian/Ubuntu: apt-get install samba smbclient).
|
||||
#
|
||||
# Usage:
|
||||
# test/samba/run.sh
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
WEED_BIN="${WEED_BIN:-weed}"
|
||||
WORK_DIR="${WORK_DIR:-$(mktemp -d /tmp/seaweedfs-samba.XXXXXX)}"
|
||||
MOUNT_DIR="${MOUNT_DIR:-${WORK_DIR}/mnt}"
|
||||
MOUNT2_DIR="${MOUNT2_DIR:-${WORK_DIR}/mnt2}"
|
||||
DATA_DIR="${DATA_DIR:-${WORK_DIR}/data}"
|
||||
LOG_DIR="${LOG_DIR:-${WORK_DIR}/logs}"
|
||||
STATE_DIR="${WORK_DIR}/samba"
|
||||
SHARE_DIR="${MOUNT_DIR}/share"
|
||||
SHARE_DIR2="${MOUNT2_DIR}/share"
|
||||
|
||||
FILER_PORT="${FILER_PORT:-28888}"
|
||||
FILER_ADDR="127.0.0.1:${FILER_PORT}"
|
||||
SMB_PORT="${SMB_PORT:-4450}"
|
||||
SMB_SHARE="seaweedfs"
|
||||
SMB_USER="${SMB_USER:-$(id -un)}"
|
||||
SMB_PASS="${SMB_PASS:-seaweedfs}"
|
||||
|
||||
SMBD_BIN="$(command -v smbd || echo /usr/sbin/smbd)"
|
||||
SMBPASSWD_BIN="$(command -v smbpasswd || echo /usr/bin/smbpasswd)"
|
||||
|
||||
CI_LOG_DIR="/tmp/seaweedfs-samba-logs"
|
||||
|
||||
mini_pid=""
|
||||
mount_pid=""
|
||||
mount2_pid=""
|
||||
smbd_pid=""
|
||||
|
||||
unmount_dir() {
|
||||
local dir="$1"
|
||||
if mountpoint -q "${dir}" 2>/dev/null; then
|
||||
fusermount3 -u "${dir}" 2>/dev/null ||
|
||||
fusermount -u "${dir}" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
set +e
|
||||
if [[ -n "${smbd_pid}" ]] && kill -0 "${smbd_pid}" 2>/dev/null; then
|
||||
kill -TERM "${smbd_pid}" 2>/dev/null || true
|
||||
wait "${smbd_pid}" 2>/dev/null || true
|
||||
fi
|
||||
for p in "${mount_pid}" "${mount2_pid}"; do
|
||||
if [[ -n "${p}" ]] && kill -0 "${p}" 2>/dev/null; then
|
||||
kill -TERM "${p}" 2>/dev/null || true
|
||||
wait "${p}" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
unmount_dir "${MOUNT_DIR}"
|
||||
unmount_dir "${MOUNT2_DIR}"
|
||||
if [[ -n "${mini_pid}" ]] && kill -0 "${mini_pid}" 2>/dev/null; then
|
||||
kill -TERM "${mini_pid}" 2>/dev/null || true
|
||||
wait "${mini_pid}" 2>/dev/null || true
|
||||
fi
|
||||
# Copy logs to a fixed path for CI artifact upload.
|
||||
mkdir -p "${CI_LOG_DIR}"
|
||||
cp "${LOG_DIR}"/*.log "${LOG_DIR}"/*.out "${STATE_DIR}/smbd.log" "${CI_LOG_DIR}/" 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
mkdir -p "${MOUNT_DIR}" "${MOUNT2_DIR}" "${DATA_DIR}" "${LOG_DIR}" \
|
||||
"${STATE_DIR}/private" "${STATE_DIR}/state" "${STATE_DIR}/cache" \
|
||||
"${STATE_DIR}/lock" "${STATE_DIR}/pid" "${STATE_DIR}/ncalrpc"
|
||||
|
||||
# --- 1. weed mini -----------------------------------------------------------
|
||||
echo "==> Starting weed mini on ${FILER_ADDR}"
|
||||
"${WEED_BIN}" mini \
|
||||
-dir="${DATA_DIR}" \
|
||||
-ip=127.0.0.1 \
|
||||
-filer.port="${FILER_PORT}" \
|
||||
-s3=false \
|
||||
-webdav=false \
|
||||
-admin.ui=false \
|
||||
>"${LOG_DIR}/mini.log" 2>&1 &
|
||||
mini_pid=$!
|
||||
|
||||
for i in $(seq 1 60); do
|
||||
if (echo >"/dev/tcp/127.0.0.1/${FILER_PORT}") 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
if ! kill -0 "${mini_pid}" 2>/dev/null; then
|
||||
echo "weed mini exited early; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/mini.log" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
if ! (echo >"/dev/tcp/127.0.0.1/${FILER_PORT}") 2>/dev/null; then
|
||||
echo "weed mini filer did not become reachable within 30s; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/mini.log" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- 2. weed mount (two mounts, both with -dlm) -----------------------------
|
||||
# mount_with_dlm <mountpoint> <logfile> <pid-var-name>
|
||||
mount_with_dlm() {
|
||||
local dir="$1" log="$2" pidvar="$3" pid
|
||||
echo "==> Mounting SeaweedFS at ${dir} with -dlm"
|
||||
"${WEED_BIN}" mount \
|
||||
-filer="${FILER_ADDR}" \
|
||||
-dir="${dir}" \
|
||||
-filer.path=/ \
|
||||
-dirAutoCreate \
|
||||
-dlm \
|
||||
>"${log}" 2>&1 &
|
||||
pid=$!
|
||||
printf -v "${pidvar}" '%s' "${pid}"
|
||||
for _ in $(seq 1 60); do
|
||||
if mountpoint -q "${dir}"; then
|
||||
return 0
|
||||
fi
|
||||
if ! kill -0 "${pid}" 2>/dev/null; then
|
||||
echo "weed mount (${dir}) exited early; log tail:" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "FUSE mount ${dir} did not come up within 30s" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
}
|
||||
|
||||
mount_with_dlm "${MOUNT_DIR}" "${LOG_DIR}/mount.log" mount_pid
|
||||
mount_with_dlm "${MOUNT2_DIR}" "${LOG_DIR}/mount2.log" mount2_pid
|
||||
|
||||
mkdir -p "${SHARE_DIR}"
|
||||
|
||||
# --- 3. smbd ----------------------------------------------------------------
|
||||
echo "==> Generating smb.conf and starting smbd on port ${SMB_PORT}"
|
||||
SMB_CONF="${STATE_DIR}/smb.conf"
|
||||
sed -e "s#@SHARE_PATH@#${SHARE_DIR}#g" \
|
||||
-e "s#@STATE_DIR@#${STATE_DIR}#g" \
|
||||
-e "s#@SMB_PORT@#${SMB_PORT}#g" \
|
||||
-e "s#@FORCE_USER@#${SMB_USER}#g" \
|
||||
"${SCRIPT_DIR}/smb.conf.template" >"${SMB_CONF}"
|
||||
|
||||
printf '%s\n%s\n' "${SMB_PASS}" "${SMB_PASS}" |
|
||||
"${SMBPASSWD_BIN}" -c "${SMB_CONF}" -a -s "${SMB_USER}"
|
||||
|
||||
"${SMBD_BIN}" -F --no-process-group -s "${SMB_CONF}" >"${LOG_DIR}/smbd.out" 2>&1 &
|
||||
smbd_pid=$!
|
||||
|
||||
for i in $(seq 1 60); do
|
||||
if (echo >"/dev/tcp/127.0.0.1/${SMB_PORT}") 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
if ! kill -0 "${smbd_pid}" 2>/dev/null; then
|
||||
echo "smbd exited early; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/smbd.out" "${STATE_DIR}/smbd.log" 2>/dev/null >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
if ! (echo >"/dev/tcp/127.0.0.1/${SMB_PORT}") 2>/dev/null; then
|
||||
echo "smbd did not become reachable within 30s; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/smbd.out" "${STATE_DIR}/smbd.log" 2>/dev/null >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- 4. run the test batteries ---------------------------------------------
|
||||
rc=0
|
||||
|
||||
echo "==> Running SMB functional test battery"
|
||||
SMB_HOST=127.0.0.1 \
|
||||
SMB_SHARE="${SMB_SHARE}" \
|
||||
SMB_PORT="${SMB_PORT}" \
|
||||
SMB_USER="${SMB_USER}" \
|
||||
SMB_PASS="${SMB_PASS}" \
|
||||
SHARE_FS_PATH="${SHARE_DIR}" \
|
||||
"${SCRIPT_DIR}/smb_tests.sh" || rc=1
|
||||
|
||||
echo "==> Running SMB locking / concurrency test battery"
|
||||
SMB_HOST=127.0.0.1 \
|
||||
SMB_SHARE="${SMB_SHARE}" \
|
||||
SMB_PORT="${SMB_PORT}" \
|
||||
SMB_USER="${SMB_USER}" \
|
||||
SMB_PASS="${SMB_PASS}" \
|
||||
MOUNT_SHARE="${SHARE_DIR}" \
|
||||
MOUNT2_SHARE="${SHARE_DIR2}" \
|
||||
"${SCRIPT_DIR}/lock_tests.sh" || rc=1
|
||||
|
||||
exit "${rc}"
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Runs the SMB test batteries inside the samba container against the local smbd,
|
||||
# which serves /mnt/seaweedfs/share over a SeaweedFS FUSE mount. A second FUSE
|
||||
# mount (/mnt/seaweedfs2) backs the distributed-locking tests.
|
||||
# Invoked via: docker compose exec samba /run_inside_container.sh
|
||||
set -euo pipefail
|
||||
|
||||
export SMB_HOST=127.0.0.1
|
||||
export SMB_SHARE=seaweedfs
|
||||
export SMB_PORT="${SMB_PORT:-445}"
|
||||
export SMB_USER="${SMB_USER:-smbtest}"
|
||||
export SMB_PASS="${SMB_PASS:-smbtest}"
|
||||
export SHARE_FS_PATH="${SHARE_FS_PATH:-/mnt/seaweedfs/share}"
|
||||
export MOUNT_SHARE="${MOUNT_SHARE:-/mnt/seaweedfs/share}"
|
||||
export MOUNT2_SHARE="${MOUNT2_SHARE:-/mnt/seaweedfs2/share}"
|
||||
|
||||
rc=0
|
||||
echo "############ SMB functional tests ############"
|
||||
/smb_tests.sh || rc=1
|
||||
echo
|
||||
echo "############ SMB locking / concurrency tests ############"
|
||||
/lock_tests.sh || rc=1
|
||||
exit "${rc}"
|
||||
@@ -0,0 +1,52 @@
|
||||
[global]
|
||||
server role = standalone server
|
||||
workgroup = WORKGROUP
|
||||
server string = SeaweedFS FUSE Samba test
|
||||
security = user
|
||||
server min protocol = SMB2
|
||||
smb ports = @SMB_PORT@
|
||||
bind interfaces only = yes
|
||||
interfaces = lo 127.0.0.1
|
||||
|
||||
# Self-contained state so smbd can run rootless and leaves nothing behind
|
||||
# outside the test work directory.
|
||||
private dir = @STATE_DIR@/private
|
||||
state directory = @STATE_DIR@/state
|
||||
cache directory = @STATE_DIR@/cache
|
||||
lock directory = @STATE_DIR@/lock
|
||||
pid directory = @STATE_DIR@/pid
|
||||
ncalrpc dir = @STATE_DIR@/ncalrpc
|
||||
log file = @STATE_DIR@/smbd.log
|
||||
log level = 1
|
||||
usershare max shares = 0
|
||||
|
||||
# No printing subsystem in a file-server test.
|
||||
load printers = no
|
||||
printing = bsd
|
||||
printcap name = /dev/null
|
||||
disable spoolss = yes
|
||||
|
||||
# The SeaweedFS FUSE mount does not implement the full xattr / DOS-attribute
|
||||
# surface Samba uses by default. Disabling these avoids spurious
|
||||
# NT_STATUS_NOT_SUPPORTED / EOPNOTSUPP errors unrelated to data integrity.
|
||||
ea support = no
|
||||
store dos attributes = no
|
||||
map archive = no
|
||||
map hidden = no
|
||||
map system = no
|
||||
map readonly = no
|
||||
|
||||
# A network-filesystem backend should not advertise local oplocks/leases.
|
||||
oplocks = no
|
||||
level2 oplocks = no
|
||||
kernel oplocks = no
|
||||
posix locking = no
|
||||
|
||||
[seaweedfs]
|
||||
path = @SHARE_PATH@
|
||||
comment = SeaweedFS share backed by a FUSE mount
|
||||
browseable = yes
|
||||
read only = no
|
||||
create mask = 0644
|
||||
directory mask = 0755
|
||||
force user = @FORCE_USER@
|
||||
Executable
+172
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# SMB protocol test battery against a Samba share backed by a SeaweedFS FUSE
|
||||
# mount. Driven both by the local runner (test/samba/run.sh) and by the Docker
|
||||
# harness (run_inside_container.sh).
|
||||
#
|
||||
# Required env:
|
||||
# SMB_USER samba username
|
||||
# SMB_PASS samba password
|
||||
# Optional env:
|
||||
# SMB_HOST samba host (default 127.0.0.1)
|
||||
# SMB_SHARE share name (default seaweedfs)
|
||||
# SMB_PORT smbd port (default 445)
|
||||
# SHARE_FS_PATH directory on the FUSE mount that backs the share. When set,
|
||||
# the suite also checks cross-protocol consistency: data written
|
||||
# over SMB is visible on the FUSE mount, and vice versa.
|
||||
set -uo pipefail
|
||||
|
||||
SMB_HOST="${SMB_HOST:-127.0.0.1}"
|
||||
SMB_SHARE="${SMB_SHARE:-seaweedfs}"
|
||||
SMB_PORT="${SMB_PORT:-445}"
|
||||
SMB_USER="${SMB_USER:?SMB_USER is required}"
|
||||
SMB_PASS="${SMB_PASS:?SMB_PASS is required}"
|
||||
SHARE_FS_PATH="${SHARE_FS_PATH:-}"
|
||||
|
||||
WORK="$(mktemp -d /tmp/samba-smbtest.XXXXXX)"
|
||||
trap 'rm -rf "${WORK}"' EXIT
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
pass() { printf ' [PASS] %s\n' "$1"; PASS=$((PASS + 1)); }
|
||||
fail() { printf ' [FAIL] %s\n' "$1"; FAIL=$((FAIL + 1)); }
|
||||
|
||||
# Run one or more smbclient commands (separated by ';') against the share.
|
||||
smb() {
|
||||
smbclient "//${SMB_HOST}/${SMB_SHARE}" -p "${SMB_PORT}" \
|
||||
-U "${SMB_USER}%${SMB_PASS}" -m SMB3 -c "$1"
|
||||
}
|
||||
|
||||
md5() { md5sum "$1" | awk '{print $1}'; }
|
||||
|
||||
echo "==> Target //${SMB_HOST}/${SMB_SHARE} (port ${SMB_PORT}) as ${SMB_USER}"
|
||||
[[ -n "${SHARE_FS_PATH}" ]] && echo "==> Cross-protocol checks against ${SHARE_FS_PATH}"
|
||||
|
||||
# 1. Connectivity ------------------------------------------------------------
|
||||
echo "==> 1. connectivity"
|
||||
if smb "ls" >/dev/null 2>&1; then
|
||||
pass "connect and list share root"
|
||||
else
|
||||
fail "connect and list share root"
|
||||
fi
|
||||
|
||||
# 2. Upload / download round-trip -------------------------------------------
|
||||
echo "==> 2. upload / download round-trip"
|
||||
src="${WORK}/src.bin"
|
||||
head -c 1048576 /dev/urandom >"${src}" # 1 MiB
|
||||
if smb "put ${src} roundtrip.bin" >/dev/null 2>&1; then
|
||||
pass "put 1 MiB file"
|
||||
else
|
||||
fail "put 1 MiB file"
|
||||
fi
|
||||
got="${WORK}/got.bin"
|
||||
if smb "get roundtrip.bin ${got}" >/dev/null 2>&1 && [[ "$(md5 "${src}")" == "$(md5 "${got}")" ]]; then
|
||||
pass "get returns identical content"
|
||||
else
|
||||
fail "get returns identical content"
|
||||
fi
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
if [[ -f "${SHARE_FS_PATH}/roundtrip.bin" ]] && [[ "$(md5 "${SHARE_FS_PATH}/roundtrip.bin")" == "$(md5 "${src}")" ]]; then
|
||||
pass "SMB-written file visible on FUSE mount with identical content"
|
||||
else
|
||||
fail "SMB-written file visible on FUSE mount with identical content"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Directory operations ----------------------------------------------------
|
||||
echo "==> 3. directory operations"
|
||||
if smb "mkdir docs; cd docs; put ${src} nested.bin; ls" >/dev/null 2>&1; then
|
||||
pass "mkdir + put into subdirectory"
|
||||
else
|
||||
fail "mkdir + put into subdirectory"
|
||||
fi
|
||||
if [[ -z "${SHARE_FS_PATH}" || -f "${SHARE_FS_PATH}/docs/nested.bin" ]]; then
|
||||
pass "nested file present"
|
||||
else
|
||||
fail "nested file present"
|
||||
fi
|
||||
|
||||
# 4. Rename ------------------------------------------------------------------
|
||||
echo "==> 4. rename"
|
||||
if smb "rename roundtrip.bin renamed.bin" >/dev/null 2>&1; then
|
||||
pass "rename file"
|
||||
else
|
||||
fail "rename file"
|
||||
fi
|
||||
renback="${WORK}/renamed.bin"
|
||||
if smb "get renamed.bin ${renback}" >/dev/null 2>&1 && [[ "$(md5 "${renback}")" == "$(md5 "${src}")" ]]; then
|
||||
pass "renamed file readable with original content"
|
||||
else
|
||||
fail "renamed file readable with original content"
|
||||
fi
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
if [[ -f "${SHARE_FS_PATH}/renamed.bin" && ! -e "${SHARE_FS_PATH}/roundtrip.bin" ]]; then
|
||||
pass "rename reflected on FUSE mount"
|
||||
else
|
||||
fail "rename reflected on FUSE mount"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 5. Large file (exercises SeaweedFS chunking) -------------------------------
|
||||
echo "==> 5. large file (SeaweedFS chunking)"
|
||||
big="${WORK}/big.bin"
|
||||
head -c 67108864 /dev/urandom >"${big}" # 64 MiB
|
||||
bigback="${WORK}/big.back"
|
||||
if smb "put ${big} big.bin" >/dev/null 2>&1 &&
|
||||
smb "get big.bin ${bigback}" >/dev/null 2>&1 &&
|
||||
[[ "$(md5 "${big}")" == "$(md5 "${bigback}")" ]]; then
|
||||
pass "64 MiB put/get round-trip"
|
||||
else
|
||||
fail "64 MiB put/get round-trip"
|
||||
fi
|
||||
|
||||
# 6. Recursive upload --------------------------------------------------------
|
||||
echo "==> 6. recursive upload"
|
||||
tree="${WORK}/tree"
|
||||
mkdir -p "${tree}/a/b"
|
||||
echo one >"${tree}/f1.txt"
|
||||
echo two >"${tree}/a/f2.txt"
|
||||
echo three >"${tree}/a/b/f3.txt"
|
||||
if (cd "${WORK}" && smb "recurse ON; prompt OFF; mput tree" >/dev/null 2>&1) &&
|
||||
{ [[ -z "${SHARE_FS_PATH}" ]] || [[ -f "${SHARE_FS_PATH}/tree/a/b/f3.txt" ]]; }; then
|
||||
pass "recursive mput"
|
||||
else
|
||||
fail "recursive mput"
|
||||
fi
|
||||
|
||||
# 7. Cross-protocol read (FUSE writes, SMB reads) ----------------------------
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
echo "==> 7. cross-protocol read (FUSE write -> SMB read)"
|
||||
echo "written-via-fuse" >"${SHARE_FS_PATH}/from_fuse.txt"
|
||||
cpb="${WORK}/from_fuse.back"
|
||||
if smb "get from_fuse.txt ${cpb}" >/dev/null 2>&1 && grep -q written-via-fuse "${cpb}"; then
|
||||
pass "FUSE-written file readable over SMB"
|
||||
else
|
||||
fail "FUSE-written file readable over SMB"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 8. Delete ------------------------------------------------------------------
|
||||
echo "==> 8. delete"
|
||||
smb "del renamed.bin" >/dev/null 2>&1
|
||||
smb "del big.bin" >/dev/null 2>&1
|
||||
smb "deltree docs" >/dev/null 2>&1
|
||||
smb "deltree tree" >/dev/null 2>&1
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
if [[ ! -e "${SHARE_FS_PATH}/renamed.bin" && ! -e "${SHARE_FS_PATH}/big.bin" &&
|
||||
! -e "${SHARE_FS_PATH}/docs" && ! -e "${SHARE_FS_PATH}/tree" ]]; then
|
||||
pass "delete files and directory trees"
|
||||
else
|
||||
fail "delete files and directory trees"
|
||||
fi
|
||||
else
|
||||
if ! smb "get renamed.bin /dev/null" >/dev/null 2>&1; then
|
||||
pass "deleted file no longer retrievable"
|
||||
else
|
||||
fail "deleted file no longer retrievable"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "==> Summary: ${PASS} passed, ${FAIL} failed"
|
||||
[[ "${FAIL}" -eq 0 ]]
|
||||
@@ -2,6 +2,8 @@ package volume_server_http_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -44,6 +46,17 @@ func TestReplicatedUploadSucceedsImmediatelyAfterAllocate(t *testing.T) {
|
||||
fid := framework.NewFileID(volumeID, 881001, 0x0B0C0D0E)
|
||||
payload := []byte("replicated-upload-after-allocate")
|
||||
|
||||
// The master only learns about replica locations through volume-server
|
||||
// heartbeats, which lag behind the direct AllocateVolume gRPC calls above.
|
||||
// In production a client obtains its fid from the master assign flow, which
|
||||
// guarantees the master already knows every replica; this test crafts the
|
||||
// fid by hand, so the replicated write would otherwise look up the master
|
||||
// before the second replica is registered and fail with a 500. Wait until
|
||||
// the master reports both replicas before uploading.
|
||||
if !waitForMasterReplicaCount(t, client, clusterHarness.MasterURL(), volumeID, 2, 10*time.Second) {
|
||||
t.Fatalf("master did not report 2 replica locations for volume %d within deadline", volumeID)
|
||||
}
|
||||
|
||||
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, payload)
|
||||
_ = framework.ReadAllAndClose(t, uploadResp)
|
||||
if uploadResp.StatusCode != http.StatusCreated {
|
||||
@@ -61,3 +74,29 @@ func TestReplicatedUploadSucceedsImmediatelyAfterAllocate(t *testing.T) {
|
||||
t.Fatalf("replica body mismatch: got %q want %q", string(replicaBody), string(payload))
|
||||
}
|
||||
}
|
||||
|
||||
// waitForMasterReplicaCount polls the master volume lookup until it reports at
|
||||
// least want locations for volumeID, or the timeout elapses.
|
||||
func waitForMasterReplicaCount(t testing.TB, client *http.Client, masterURL string, volumeID uint32, want int, timeout time.Duration) bool {
|
||||
t.Helper()
|
||||
|
||||
lookupURL := fmt.Sprintf("%s/dir/lookup?volumeId=%d", masterURL, volumeID)
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, lookupURL))
|
||||
body := framework.ReadAllAndClose(t, resp)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var result struct {
|
||||
Locations []struct {
|
||||
Url string `json:"url"`
|
||||
} `json:"locations"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err == nil && len(result.Locations) >= want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/plugin"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
@@ -735,8 +734,8 @@ func (s *AdminServer) parseOrBuildClusterContext(raw json.RawMessage) (*plugin_p
|
||||
if len(contextMessage.MasterGrpcAddresses) == 0 {
|
||||
contextMessage.MasterGrpcAddresses = append(contextMessage.MasterGrpcAddresses, fallback.MasterGrpcAddresses...)
|
||||
}
|
||||
if len(contextMessage.FilerGrpcAddresses) == 0 {
|
||||
contextMessage.FilerGrpcAddresses = append(contextMessage.FilerGrpcAddresses, fallback.FilerGrpcAddresses...)
|
||||
if len(contextMessage.FilerAddresses) == 0 {
|
||||
contextMessage.FilerAddresses = append(contextMessage.FilerAddresses, fallback.FilerAddresses...)
|
||||
}
|
||||
if len(contextMessage.VolumeGrpcAddresses) == 0 {
|
||||
contextMessage.VolumeGrpcAddresses = append(contextMessage.VolumeGrpcAddresses, fallback.VolumeGrpcAddresses...)
|
||||
@@ -755,7 +754,7 @@ func (s *AdminServer) parseOrBuildClusterContext(raw json.RawMessage) (*plugin_p
|
||||
func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterContext {
|
||||
clusterContext := &plugin_pb.ClusterContext{
|
||||
MasterGrpcAddresses: make([]string, 0),
|
||||
FilerGrpcAddresses: make([]string, 0),
|
||||
FilerAddresses: make([]string, 0),
|
||||
VolumeGrpcAddresses: make([]string, 0),
|
||||
S3GrpcAddresses: make([]string, 0),
|
||||
Metadata: map[string]string{
|
||||
@@ -768,20 +767,20 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
|
||||
clusterContext.MasterGrpcAddresses = append(clusterContext.MasterGrpcAddresses, masterAddress)
|
||||
}
|
||||
|
||||
// Master returns filers in dual-port form (host:httpPort.grpcPort);
|
||||
// workers dial these directly, so collapse to host:grpcPort first.
|
||||
// Master returns filers in pb.ServerAddress form (host:httpPort.grpcPort).
|
||||
// Forward that verbatim; each worker converts to a gRPC or HTTP address as
|
||||
// it needs (dialing wants gRPC, the admin shell wants the ServerAddress).
|
||||
filerSeen := map[string]struct{}{}
|
||||
for _, filer := range s.GetAllFilers() {
|
||||
filer = strings.TrimSpace(filer)
|
||||
if filer == "" {
|
||||
continue
|
||||
}
|
||||
grpcAddr := pb.ServerAddress(filer).ToGrpcAddress()
|
||||
if _, exists := filerSeen[grpcAddr]; exists {
|
||||
if _, exists := filerSeen[filer]; exists {
|
||||
continue
|
||||
}
|
||||
filerSeen[grpcAddr] = struct{}{}
|
||||
clusterContext.FilerGrpcAddresses = append(clusterContext.FilerGrpcAddresses, grpcAddr)
|
||||
filerSeen[filer] = struct{}{}
|
||||
clusterContext.FilerAddresses = append(clusterContext.FilerAddresses, filer)
|
||||
}
|
||||
|
||||
volumeSeen := map[string]struct{}{}
|
||||
@@ -829,7 +828,7 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
|
||||
}
|
||||
|
||||
sort.Strings(clusterContext.MasterGrpcAddresses)
|
||||
sort.Strings(clusterContext.FilerGrpcAddresses)
|
||||
sort.Strings(clusterContext.FilerAddresses)
|
||||
sort.Strings(clusterContext.VolumeGrpcAddresses)
|
||||
sort.Strings(clusterContext.S3GrpcAddresses)
|
||||
|
||||
|
||||
@@ -26,6 +26,10 @@ type MaintenanceIntegration struct {
|
||||
// Active topology for task detection and target selection
|
||||
activeTopology *topology.ActiveTopology
|
||||
|
||||
// Master's default replication, refreshed by the scanner each cycle and
|
||||
// passed to detectors as the replica-placement fallback (matches the shell).
|
||||
defaultReplicaPlacement string
|
||||
|
||||
// Type conversion maps
|
||||
taskTypeMap map[types.TaskType]MaintenanceTaskType
|
||||
revTaskTypeMap map[MaintenanceTaskType]types.TaskType
|
||||
@@ -219,9 +223,10 @@ func (s *MaintenanceIntegration) ScanWithTaskDetectors(volumeMetrics []*types.Vo
|
||||
|
||||
// Create cluster info
|
||||
clusterInfo := &types.ClusterInfo{
|
||||
TotalVolumes: len(filteredMetrics),
|
||||
LastUpdated: time.Now(),
|
||||
ActiveTopology: s.activeTopology, // Provide ActiveTopology for destination planning
|
||||
TotalVolumes: len(filteredMetrics),
|
||||
LastUpdated: time.Now(),
|
||||
ActiveTopology: s.activeTopology, // Provide ActiveTopology for destination planning
|
||||
DefaultReplicaPlacement: s.defaultReplicaPlacement,
|
||||
}
|
||||
|
||||
// Run detection for each registered task type
|
||||
@@ -271,6 +276,12 @@ func (s *MaintenanceIntegration) ScanWithTaskDetectors(volumeMetrics []*types.Vo
|
||||
return allResults, nil
|
||||
}
|
||||
|
||||
// SetDefaultReplicaPlacement records the master's default replication so detectors
|
||||
// can use it as the replica-placement fallback (matching the shell).
|
||||
func (s *MaintenanceIntegration) SetDefaultReplicaPlacement(replicaPlacement string) {
|
||||
s.defaultReplicaPlacement = replicaPlacement
|
||||
}
|
||||
|
||||
// UpdateTopologyInfo updates the volume shard tracker with topology information for empty servers
|
||||
func (s *MaintenanceIntegration) UpdateTopologyInfo(topologyInfo *master_pb.TopologyInfo) error {
|
||||
// Log topology details before update for diagnostics
|
||||
|
||||
@@ -51,6 +51,10 @@ func (ms *MaintenanceScanner) ScanForMaintenanceTasks() ([]*TaskDetectionResult,
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh the master's default replication so detectors can use it as the
|
||||
// replica-placement fallback (matches the shell ec.balance default).
|
||||
ms.integration.SetDefaultReplicaPlacement(ms.getDefaultReplicaPlacement())
|
||||
|
||||
// Use task detection system with complete cluster information
|
||||
results, err := ms.integration.ScanWithTaskDetectors(taskMetrics)
|
||||
if err != nil {
|
||||
@@ -67,6 +71,26 @@ func (ms *MaintenanceScanner) ScanForMaintenanceTasks() ([]*TaskDetectionResult,
|
||||
return []*TaskDetectionResult{}, nil
|
||||
}
|
||||
|
||||
// getDefaultReplicaPlacement reads the master's configured default replication,
|
||||
// used by detectors as the replica-placement fallback. Returns "" on error so
|
||||
// detectors fall back to even spread rather than failing the scan.
|
||||
func (ms *MaintenanceScanner) getDefaultReplicaPlacement() string {
|
||||
var replicaPlacement string
|
||||
err := ms.adminClient.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.GetMasterConfiguration(context.Background(), &master_pb.GetMasterConfigurationRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
replicaPlacement = resp.DefaultReplication
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(1).Infof("could not fetch master default replication: %v", err)
|
||||
return ""
|
||||
}
|
||||
return replicaPlacement
|
||||
}
|
||||
|
||||
// getVolumeHealthMetrics collects health information for all volumes.
|
||||
// Returns metrics in task-system format directly (no intermediate copy) and
|
||||
// the topology info for updating the active topology.
|
||||
|
||||
@@ -113,7 +113,7 @@ func cloneClusterContext(in *plugin_pb.ClusterContext) *plugin_pb.ClusterContext
|
||||
}
|
||||
out := &plugin_pb.ClusterContext{
|
||||
MasterGrpcAddresses: in.MasterGrpcAddresses,
|
||||
FilerGrpcAddresses: in.FilerGrpcAddresses,
|
||||
FilerAddresses: in.FilerAddresses,
|
||||
VolumeGrpcAddresses: in.VolumeGrpcAddresses,
|
||||
S3GrpcAddresses: in.S3GrpcAddresses,
|
||||
}
|
||||
|
||||
@@ -54,6 +54,70 @@ func (at *ActiveTopology) GetEffectiveAvailableCapacityDetailed(nodeID string, d
|
||||
return at.getEffectiveAvailableCapacityUnsafe(disk)
|
||||
}
|
||||
|
||||
// GetEffectiveAvailableEcShardSlots returns a disk's free EC shard slots,
|
||||
// accounting for in-flight task reservations at shard granularity. Unlike the
|
||||
// volume-slot views (GetDisksWithEffectiveCapacity / GetEffectiveAvailableCapacity),
|
||||
// this does not truncate sub-volume shard reservations: it subtracts the full
|
||||
// reservation impact (volume slots converted to shard slots, plus the raw shard
|
||||
// slots) so a reservation that is not a whole multiple of ShardsPerVolumeSlot is
|
||||
// not lost. It does NOT subtract the EC shards already persisted on the disk;
|
||||
// callers that track those (from EcShardInfos) subtract them separately.
|
||||
//
|
||||
// shardsPerVolume is the number of EC shards of the target collection that fit in
|
||||
// one volume slot (i.e. its data-shard count): a 4+2 volume's shards are ~1/4 of a
|
||||
// volume each, so one volume slot holds 4 of them, not the default
|
||||
// ShardsPerVolumeSlot. Pass <= 0 to use the default. Using the target ratio keeps
|
||||
// Place from over-filling a disk for low-data-shard layouts.
|
||||
func (at *ActiveTopology) GetEffectiveAvailableEcShardSlots(nodeID string, diskID uint32, shardsPerVolume int) int {
|
||||
if shardsPerVolume <= 0 {
|
||||
shardsPerVolume = ShardsPerVolumeSlot
|
||||
}
|
||||
|
||||
at.mutex.RLock()
|
||||
defer at.mutex.RUnlock()
|
||||
|
||||
diskKey := fmt.Sprintf("%s:%d", nodeID, diskID)
|
||||
disk, exists := at.disks[diskKey]
|
||||
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
info := disk.DiskInfo.DiskInfo
|
||||
base := info.MaxVolumeCount - info.VolumeCount
|
||||
if base <= 0 && info.MaxVolumeCount == 0 && info.VolumeCount == 0 &&
|
||||
len(info.VolumeInfos) == 0 && len(info.EcShardInfos) == 0 {
|
||||
// Freshly started empty servers can report max=0 before publishing concrete
|
||||
// limits; keep one provisional slot so EC placement still sees the disk,
|
||||
// mirroring getEffectiveAvailableCapacityUnsafe.
|
||||
base = 1
|
||||
}
|
||||
if base < 0 {
|
||||
base = 0
|
||||
}
|
||||
// calculateTaskStorageImpact reports consumption as positive, so subtract it.
|
||||
// Volume-slot reservations scale by the target ratio; the sub-volume shard-slot
|
||||
// remainder is in default units and subtracted as-is (a small approximation).
|
||||
impact := at.getEffectiveCapacityUnsafe(disk)
|
||||
// impact.ShardSlots is recorded in default ShardsPerVolumeSlot units; convert it
|
||||
// to the target ratio's shard slots before subtracting (identity when
|
||||
// shardsPerVolume == ShardsPerVolumeSlot). Round a positive reservation up so a
|
||||
// sub-slot reservation (e.g. 1 default slot against a 4-shard target) is not
|
||||
// truncated to zero and wrongly counted as free.
|
||||
scaledShardImpact := int64(impact.ShardSlots) * int64(shardsPerVolume)
|
||||
if scaledShardImpact > 0 {
|
||||
scaledShardImpact = (scaledShardImpact + int64(ShardsPerVolumeSlot) - 1) / int64(ShardsPerVolumeSlot)
|
||||
} else {
|
||||
scaledShardImpact /= int64(ShardsPerVolumeSlot)
|
||||
}
|
||||
free := base*int64(shardsPerVolume) -
|
||||
int64(impact.VolumeSlots)*int64(shardsPerVolume) -
|
||||
scaledShardImpact
|
||||
if free < 0 {
|
||||
free = 0
|
||||
}
|
||||
return int(free)
|
||||
}
|
||||
|
||||
// GetEffectiveCapacityImpact returns the StorageSlotChange impact for a disk
|
||||
// This shows the net impact from all pending and assigned tasks
|
||||
func (at *ActiveTopology) GetEffectiveCapacityImpact(nodeID string, diskID uint32) StorageSlotChange {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package topology
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
// TestCountTopologyResources_multiDiskPerNode covers the case where the master
|
||||
// keys DiskInfos by disk type, so several same-type physical disks on a node
|
||||
// collapse into a single DiskInfo entry. Counting len(DiskInfos) under-reports
|
||||
// the physical disk count and disagrees with the per-disk activeDisk map that
|
||||
// the rest of the admin topology builds via SplitByPhysicalDisk.
|
||||
func TestCountTopologyResources_multiDiskPerNode(t *testing.T) {
|
||||
makeNode := func(id string) *master_pb.DataNodeInfo {
|
||||
var ecShardInfos []*master_pb.VolumeEcShardInformationMessage
|
||||
for diskId := uint32(0); diskId < 6; diskId++ {
|
||||
ecShardInfos = append(ecShardInfos, &master_pb.VolumeEcShardInformationMessage{
|
||||
Id: diskId + 1,
|
||||
DiskId: diskId,
|
||||
EcIndexBits: 1,
|
||||
})
|
||||
}
|
||||
return &master_pb.DataNodeInfo{
|
||||
Id: id,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {Type: "", MaxVolumeCount: 60, EcShardInfos: ecShardInfos},
|
||||
},
|
||||
}
|
||||
}
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "multi_disk_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
makeNode("node1"), makeNode("node2"), makeNode("node3"),
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}
|
||||
|
||||
dcCount, nodeCount, diskCount := CountTopologyResources(topo)
|
||||
if dcCount != 1 {
|
||||
t.Errorf("dcCount = %d, want 1", dcCount)
|
||||
}
|
||||
if nodeCount != 3 {
|
||||
t.Errorf("nodeCount = %d, want 3", nodeCount)
|
||||
}
|
||||
if diskCount != 18 {
|
||||
t.Errorf("diskCount = %d, want 18 (6 physical disks x 3 nodes)", diskCount)
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,12 @@ func CountTopologyResources(topologyInfo *master_pb.TopologyInfo) (dcCount, node
|
||||
for _, rack := range dc.RackInfos {
|
||||
nodeCount += len(rack.DataNodeInfos)
|
||||
for _, node := range rack.DataNodeInfos {
|
||||
diskCount += len(node.DiskInfos)
|
||||
// DiskInfos is keyed by disk type, so same-type physical disks
|
||||
// collapse into one entry. Count physical disks so the number
|
||||
// matches the per-disk activeDisk map.
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
diskCount += len(diskInfo.SplitByPhysicalDisk())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+103
-21
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -11,7 +12,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -20,6 +20,14 @@ type LockClient struct {
|
||||
maxLockDuration time.Duration
|
||||
sleepDuration time.Duration
|
||||
seedFiler pb.ServerAddress
|
||||
|
||||
// ring is an optional client-side view of the filer lock hash ring. When
|
||||
// populated, a new lock starts at the key's primary filer instead of the
|
||||
// seed filer, avoiding the seed->primary forward hop. A stale view stays
|
||||
// correct: the filer forwards to the real primary as a fallback.
|
||||
ringMu sync.RWMutex
|
||||
ring *lock_manager.HashRing
|
||||
ringVersion int64
|
||||
}
|
||||
|
||||
func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *LockClient {
|
||||
@@ -31,12 +39,56 @@ func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *
|
||||
}
|
||||
}
|
||||
|
||||
// SetRing updates the client-side view of the filer lock ring. It mirrors the
|
||||
// master's LockRingUpdate broadcasts so the client computes the same primary
|
||||
// the filers do. Updates older than the current version are ignored to tolerate
|
||||
// reordered broadcasts; version 0 is always accepted (bootstrap).
|
||||
func (lc *LockClient) SetRing(servers []pb.ServerAddress, version int64) {
|
||||
lc.ringMu.Lock()
|
||||
defer lc.ringMu.Unlock()
|
||||
if version != 0 && version < lc.ringVersion {
|
||||
return
|
||||
}
|
||||
lc.ringVersion = version
|
||||
if lc.ring == nil {
|
||||
lc.ring = lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
|
||||
}
|
||||
lc.ring.SetServers(servers)
|
||||
}
|
||||
|
||||
// hostForKey returns the filer that should own key per the current ring view,
|
||||
// falling back to the seed filer when no view has been received yet.
|
||||
func (lc *LockClient) hostForKey(key string) pb.ServerAddress {
|
||||
lc.ringMu.RLock()
|
||||
defer lc.ringMu.RUnlock()
|
||||
if lc.ring == nil {
|
||||
return lc.seedFiler
|
||||
}
|
||||
if primary := lc.ring.GetPrimary(key); primary != "" {
|
||||
return primary
|
||||
}
|
||||
return lc.seedFiler
|
||||
}
|
||||
|
||||
// PrimaryForKey returns the filer that owns key per the current ring view, or
|
||||
// "" when no ring view has been received yet. Callers use it to route a key's
|
||||
// operations to a single owner so that owner's local lock serializes them.
|
||||
func (lc *LockClient) PrimaryForKey(key string) pb.ServerAddress {
|
||||
lc.ringMu.RLock()
|
||||
defer lc.ringMu.RUnlock()
|
||||
if lc.ring == nil {
|
||||
return ""
|
||||
}
|
||||
return lc.ring.GetPrimary(key)
|
||||
}
|
||||
|
||||
type LiveLock struct {
|
||||
key string
|
||||
renewToken string
|
||||
expireAtNs int64
|
||||
hostFiler pb.ServerAddress
|
||||
cancelCh chan struct{}
|
||||
renewalDone chan struct{} // closed when the renewal goroutine exits; nil if there is none
|
||||
grpcDialOption grpc.DialOption
|
||||
isLocked int32 // 0 = unlocked, 1 = locked; use atomic operations
|
||||
self string
|
||||
@@ -51,7 +103,7 @@ type LiveLock struct {
|
||||
func (lc *LockClient) NewShortLivedLock(key string, owner string) (lock *LiveLock) {
|
||||
lock = &LiveLock{
|
||||
key: key,
|
||||
hostFiler: lc.seedFiler,
|
||||
hostFiler: lc.hostForKey(key),
|
||||
cancelCh: make(chan struct{}),
|
||||
expireAtNs: time.Now().Add(5 * time.Second).UnixNano(),
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
@@ -72,7 +124,7 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
}
|
||||
lock := &LiveLock{
|
||||
key: key,
|
||||
hostFiler: lc.seedFiler,
|
||||
hostFiler: lc.hostForKey(key),
|
||||
cancelCh: make(chan struct{}),
|
||||
expireAtNs: time.Now().Add(lockTTL).UnixNano(),
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
@@ -83,7 +135,9 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
// Block until acquired
|
||||
lock.retryUntilLocked(lockTTL)
|
||||
// Start renewal goroutine using a ticker for interruptible sleep
|
||||
lock.renewalDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(lock.renewalDone)
|
||||
renewInterval := lockTTL / 2
|
||||
ticker := time.NewTicker(renewInterval)
|
||||
defer ticker.Stop()
|
||||
@@ -108,7 +162,7 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerChange func(newLockOwner string), lockTTL time.Duration) (lock *LiveLock) {
|
||||
lock = &LiveLock{
|
||||
key: key,
|
||||
hostFiler: lc.seedFiler,
|
||||
hostFiler: lc.hostForKey(key),
|
||||
cancelCh: make(chan struct{}),
|
||||
expireAtNs: time.Now().Add(lockTTL).UnixNano(),
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
@@ -119,7 +173,9 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
if lock.lockTTL == 0 {
|
||||
lock.lockTTL = lock_manager.LiveLockTTL
|
||||
}
|
||||
lock.renewalDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(lock.renewalDone)
|
||||
renewInterval := lock.lockTTL / 2
|
||||
isLocked := false
|
||||
lockOwner := ""
|
||||
@@ -149,30 +205,39 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
onLockOwnerChange(lock.LockOwner())
|
||||
lockOwner = lock.LockOwner()
|
||||
}
|
||||
// Sleep until the next attempt, but wake immediately on Stop() so
|
||||
// the goroutine exits and closes renewalDone before Stop()'s bounded
|
||||
// wait elapses. An uninterruptible sleep here (up to 5*renewInterval
|
||||
// when unlocked) can outlast that wait and break the shutdown
|
||||
// synchronization.
|
||||
sleepFor := renewInterval
|
||||
if !isLocked {
|
||||
sleepFor = 5 * renewInterval
|
||||
}
|
||||
timer := time.NewTimer(sleepFor)
|
||||
select {
|
||||
case <-lock.cancelCh:
|
||||
timer.Stop()
|
||||
return
|
||||
default:
|
||||
if isLocked {
|
||||
time.Sleep(renewInterval)
|
||||
} else {
|
||||
time.Sleep(5 * renewInterval)
|
||||
}
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
// retryUntilLocked blocks until the lock is acquired, polling at the steady
|
||||
// short cadence that AttemptToLock already enforces on contention (~1s). It
|
||||
// deliberately avoids util.RetryUntil's exponential backoff (which grows to
|
||||
// several seconds): when a holder on another mount releases the lock, the
|
||||
// waiter must pick it up promptly, otherwise cross-mount write handoff stalls
|
||||
// long enough to time out clients.
|
||||
func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) {
|
||||
util.RetryUntil("create lock:"+lock.key, func() error {
|
||||
return lock.AttemptToLock(lockDuration)
|
||||
}, func(err error) (shouldContinue bool) {
|
||||
if err != nil {
|
||||
glog.Warningf("create lock %s: %s", lock.key, err)
|
||||
for lock.renewToken == "" {
|
||||
if err := lock.AttemptToLock(lockDuration); err != nil {
|
||||
glog.V(1).Infof("create lock %s: %v", lock.key, err)
|
||||
}
|
||||
return lock.renewToken == ""
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
|
||||
@@ -226,10 +291,27 @@ func (lock *LiveLock) Stop() error {
|
||||
close(lock.cancelCh)
|
||||
}
|
||||
|
||||
// Wait a brief moment for the goroutine to see the closed channel
|
||||
// This reduces the race condition window where the goroutine might
|
||||
// attempt one more lock operation after we've released the lock
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
// Wait for the renewal goroutine to fully exit before unlocking. A renewal
|
||||
// in flight when we close cancelCh rotates renewToken on the server; if we
|
||||
// then unlock with the token we read here, the unlock fails with a token
|
||||
// mismatch and the lock lingers until its TTL expires — blocking other
|
||||
// mounts waiting on the same file. Waiting for the goroutine to return also
|
||||
// makes the renewToken read below race-free (channel close = happens-before).
|
||||
if lock.renewalDone != nil {
|
||||
select {
|
||||
case <-lock.renewalDone:
|
||||
case <-time.After(lock.lockTTL + 2*time.Second):
|
||||
// The renewal goroutine is wedged, almost certainly in a stuck
|
||||
// renewal RPC. Do not unlock here: the renewToken may be rotated
|
||||
// when that RPC finally returns, so an unlock sent now could race
|
||||
// it, be rejected on a stale token, and leave the lock lingering
|
||||
// anyway. cancelCh is closed, so the goroutine stops renewing once
|
||||
// its in-flight call returns and the lock then expires within its
|
||||
// TTL on its own.
|
||||
glog.Warningf("lock %s: renewal goroutine still running at shutdown; letting lock expire via TTL", lock.key)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Also release the lock if held
|
||||
// Note: We intentionally don't clear renewToken here because
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
// The gateway must resolve a lock key to the same primary the filers do,
|
||||
// otherwise it dials the wrong filer and the lock still gets forwarded. Both
|
||||
// sides use the same HashRing over the same server set, so for every key the
|
||||
// client's hostForKey must equal the filer ring's GetPrimary.
|
||||
func TestLockClientHostMatchesFilerRing(t *testing.T) {
|
||||
servers := []pb.ServerAddress{
|
||||
"filer-a:8888", "filer-b:8888", "filer-c:8888", "filer-d:8888",
|
||||
}
|
||||
|
||||
filerRing := lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
|
||||
filerRing.SetServers(servers)
|
||||
|
||||
lc := NewLockClient(nil, "seed:8888")
|
||||
lc.SetRing(servers, 1)
|
||||
|
||||
for _, key := range []string{
|
||||
"s3.object.write:/buckets/b/obj-0",
|
||||
"s3.object.write:/buckets/b/obj-1",
|
||||
"s3.object.write:/buckets/b/obj-2",
|
||||
"s3.object.write:/buckets/gosbench-0/w0obj-kilo-0877",
|
||||
"some/other/key",
|
||||
} {
|
||||
if got, want := lc.hostForKey(key), filerRing.GetPrimary(key); got != want {
|
||||
t.Errorf("key %q: client host %q != filer primary %q", key, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Without a ring view, the client falls back to the seed filer (which the filer
|
||||
// forwards from), preserving the pre-optimization behavior.
|
||||
func TestLockClientHostFallsBackToSeed(t *testing.T) {
|
||||
lc := NewLockClient(nil, "seed:8888")
|
||||
if got := lc.hostForKey("any-key"); got != "seed:8888" {
|
||||
t.Errorf("expected seed fallback, got %q", got)
|
||||
}
|
||||
|
||||
// An empty ring (no members yet) also falls back to the seed.
|
||||
lc.SetRing(nil, 1)
|
||||
if got := lc.hostForKey("any-key"); got != "seed:8888" {
|
||||
t.Errorf("expected seed fallback on empty ring, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A stale (older-version) update must not regress a newer ring view, while
|
||||
// version 0 always applies as a bootstrap.
|
||||
func TestLockClientSetRingVersionGuard(t *testing.T) {
|
||||
lc := NewLockClient(nil, "seed:8888")
|
||||
|
||||
newer := []pb.ServerAddress{"filer-a:8888", "filer-b:8888"}
|
||||
lc.SetRing(newer, 10)
|
||||
primaryAt10 := lc.hostForKey("k")
|
||||
|
||||
// Older version is ignored.
|
||||
lc.SetRing([]pb.ServerAddress{"filer-z:8888"}, 5)
|
||||
if got := lc.hostForKey("k"); got != primaryAt10 {
|
||||
t.Errorf("stale update applied: host changed to %q", got)
|
||||
}
|
||||
|
||||
// version 0 is always accepted.
|
||||
lc.SetRing([]pb.ServerAddress{"filer-z:8888"}, 0)
|
||||
if got := lc.hostForKey("k"); got != "filer-z:8888" {
|
||||
t.Errorf("bootstrap update not applied, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -439,6 +439,13 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
StartTsNs: sourceFilerOffsetTsNs,
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
// While the source has only read activity it emits no metadata events, so
|
||||
// the watermark above never advances and sync_offset would look stuck.
|
||||
// The idle heartbeat moves the gauge to the source's current time once we
|
||||
// are caught up, so now-sync_offset reflects real lag and stays alertable.
|
||||
OnIdleHeartbeat: func(tsNs int64) {
|
||||
statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(tsNs))
|
||||
},
|
||||
}
|
||||
|
||||
return pb.FollowMetadata(sourceFiler, sourceGrpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
|
||||
@@ -2,6 +2,7 @@ package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
@@ -9,12 +10,15 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -27,6 +31,7 @@ var cmdFix = &Command{
|
||||
Short: "run weed tool fix on files or whole folders to recreate index file(s) if corrupted",
|
||||
Long: `Fix runs the SeaweedFS fix command on local dat files ( or remote files) or whole folders to re-create the index .idx file. If fixing remote files, you need to synchronize master.toml to the same directory on the current node as on the master node.
|
||||
You Need to stop the volume server when running this command.
|
||||
Use -ecx to rebuild a lost EC index (.ecx) — and the .vif when missing — from the local .ec## shards.
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -36,6 +41,9 @@ var (
|
||||
fixIncludeDeleted = cmdFix.Flag.Bool("includeDeleted", true, "include deleted entries in the index file")
|
||||
fixIgnoreError = cmdFix.Flag.Bool("ignoreError", false, "an optional, if true will be processed despite errors")
|
||||
fixRemoteFile = cmdFix.Flag.Bool("remoteFile", false, "an optional, if true will not try to load the local .dat file, but only the remote file")
|
||||
fixGenerateEcx = cmdFix.Flag.Bool("ecx", false, "regenerate a lost EC index (.ecx) — and the .vif when missing — from the local .ec## shards (missing shards are reconstructed from parity when enough survive). Run with the volume server stopped.")
|
||||
fixEcDataShards = cmdFix.Flag.Int("ecDataShards", 0, "EC data shard count for -ecx (0 = read from .vif, otherwise default 10)")
|
||||
fixEcParityShards = cmdFix.Flag.Int("ecParityShards", 0, "EC parity shard count for -ecx (0 = read from .vif, infer from shard count, otherwise default 4)")
|
||||
)
|
||||
|
||||
type VolumeFileScanner4Fix struct {
|
||||
@@ -130,6 +138,45 @@ func runFix(cmd *Command, args []string) bool {
|
||||
}
|
||||
doFixOneVolume(basePath, baseFileName, collection, volumeId, *fixIncludeDeleted)
|
||||
}
|
||||
|
||||
if *fixGenerateEcx {
|
||||
if !fixEcxFromShardsInDir(basePath, files) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// fixEcxFromShardsInDir finds EC volumes in files (identified by their .ec00
|
||||
// data shard) and regenerates the .ecx (and .vif when missing) for each,
|
||||
// honoring the -collection and -volumeId filters.
|
||||
func fixEcxFromShardsInDir(basePath string, files []fs.DirEntry) bool {
|
||||
const shard0Ext = ".ec00"
|
||||
for _, file := range files {
|
||||
if !strings.HasSuffix(file.Name(), shard0Ext) {
|
||||
continue
|
||||
}
|
||||
if *fixVolumeCollection != "" {
|
||||
if !strings.HasPrefix(file.Name(), *fixVolumeCollection+"_") {
|
||||
continue
|
||||
}
|
||||
}
|
||||
baseFileName := file.Name()[:len(file.Name())-len(shard0Ext)]
|
||||
collection, volumeIdStr := "", baseFileName
|
||||
if sepIndex := strings.LastIndex(baseFileName, "_"); sepIndex > 0 {
|
||||
collection = baseFileName[:sepIndex]
|
||||
volumeIdStr = baseFileName[sepIndex+1:]
|
||||
}
|
||||
volumeId, parseErr := strconv.ParseInt(volumeIdStr, 10, 64)
|
||||
if parseErr != nil {
|
||||
fmt.Printf("Failed to parse volume id from %s: %v\n", baseFileName, parseErr)
|
||||
return false
|
||||
}
|
||||
if *fixVolumeId != 0 && *fixVolumeId != volumeId {
|
||||
continue
|
||||
}
|
||||
doFixEcxFromShards(basePath, baseFileName, collection, volumeId)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -202,3 +249,252 @@ func doFixOneVolume(basepath string, baseFileName string, collection string, vol
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doFixEcxFromShards rebuilds the sealed EC index (.ecx) for one EC volume
|
||||
// directly from its local shards when both the .ecx and the original .dat are
|
||||
// gone but the shards survive. When some data shards are missing but at least
|
||||
// dataShards shards survive in total, the missing shards are first reconstructed
|
||||
// from the survivors via Reed-Solomon. It then de-stripes the data shards into a
|
||||
// temporary .dat, scans the needles, and writes a fresh ascending-sorted .ecx
|
||||
// that matches what WriteSortedFileFromIdx emits at encode time (live entries
|
||||
// only). When the .vif is also missing it is regenerated from the inferred EC
|
||||
// ratio and the .dat size discovered during the scan.
|
||||
func doFixEcxFromShards(basePath, baseFileName, collection string, volumeId int64) {
|
||||
base := path.Join(basePath, baseFileName)
|
||||
|
||||
fail := func(err error) {
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
} else {
|
||||
glog.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
ecxName := base + ".ecx"
|
||||
if info, err := os.Stat(ecxName); err == nil && info.Size() > 0 {
|
||||
glog.Infof("volume %d: %s already exists (%d bytes), skipping; remove it first to force regeneration", volumeId, ecxName, info.Size())
|
||||
return
|
||||
}
|
||||
|
||||
// Discover which shards are present and their common size. Reed-Solomon
|
||||
// requires every shard to be the same size.
|
||||
present := make([]bool, erasure_coding.MaxShardCount)
|
||||
presentCount := 0
|
||||
maxPresentIdx := -1
|
||||
var shardSize int64
|
||||
for i := 0; i < erasure_coding.MaxShardCount; i++ {
|
||||
info, statErr := os.Stat(base + erasure_coding.ToExt(i))
|
||||
if statErr != nil || info.Size() == 0 {
|
||||
continue
|
||||
}
|
||||
if shardSize == 0 {
|
||||
shardSize = info.Size()
|
||||
} else if info.Size() != shardSize {
|
||||
fail(fmt.Errorf("volume %d: shard %s size %d does not match %d", volumeId, base+erasure_coding.ToExt(i), info.Size(), shardSize))
|
||||
return
|
||||
}
|
||||
present[i] = true
|
||||
presentCount++
|
||||
maxPresentIdx = i
|
||||
}
|
||||
if presentCount == 0 {
|
||||
fail(fmt.Errorf("volume %d: no EC shards found under %s", volumeId, base))
|
||||
return
|
||||
}
|
||||
|
||||
// Resolve the EC ratio and the original .dat size.
|
||||
// Priority: explicit flags > existing .vif > defaults (10+4).
|
||||
vifName := base + ".vif"
|
||||
vifExists := util.FileExists(vifName)
|
||||
dataShards := erasure_coding.DataShardsCount
|
||||
parityShards := erasure_coding.ParityShardsCount
|
||||
var datFileSize int64
|
||||
if vifExists {
|
||||
// MaybeLoadVolumeInfo returns a non-nil error when the .vif exists but
|
||||
// cannot be read or unmarshalled; fail loudly rather than silently
|
||||
// falling back to defaults (which would be wrong for a custom ratio).
|
||||
if vi, _, found, loadErr := volume_info.MaybeLoadVolumeInfo(vifName); loadErr != nil {
|
||||
fail(fmt.Errorf("volume %d: read %s: %w", volumeId, vifName, loadErr))
|
||||
return
|
||||
} else if found && vi != nil {
|
||||
if cfg := vi.GetEcShardConfig(); cfg != nil && cfg.GetDataShards() > 0 {
|
||||
dataShards = int(cfg.GetDataShards())
|
||||
parityShards = int(cfg.GetParityShards())
|
||||
}
|
||||
datFileSize = vi.GetDatFileSize()
|
||||
}
|
||||
}
|
||||
if *fixEcDataShards > 0 {
|
||||
dataShards = *fixEcDataShards
|
||||
}
|
||||
if *fixEcParityShards > 0 {
|
||||
parityShards = *fixEcParityShards
|
||||
}
|
||||
// Ensure the configured total covers every shard index actually present
|
||||
// (a custom-ratio volume with more than the default 14 shards and no .vif).
|
||||
// This never lowers parity below the default, so the common 10+4 case stays
|
||||
// correct for any subset of missing shards.
|
||||
if maxPresentIdx+1 > dataShards+parityShards {
|
||||
parityShards = maxPresentIdx + 1 - dataShards
|
||||
}
|
||||
if dataShards <= 0 || parityShards <= 0 || dataShards+parityShards > erasure_coding.MaxShardCount {
|
||||
fail(fmt.Errorf("volume %d: cannot determine EC ratio (data=%d parity=%d); set -ecDataShards/-ecParityShards", volumeId, dataShards, parityShards))
|
||||
return
|
||||
}
|
||||
|
||||
// Need at least dataShards shards (any data+parity mix) to recover anything.
|
||||
if presentCount < dataShards {
|
||||
fail(fmt.Errorf("volume %d: only %d shards present, need at least %d (data shards) to recover", volumeId, presentCount, dataShards))
|
||||
return
|
||||
}
|
||||
|
||||
// If any data shard is missing, reconstruct the missing shards from the
|
||||
// survivors via Reed-Solomon before de-striping. This writes the rebuilt
|
||||
// shard files back to disk, fully repairing the volume locally.
|
||||
dataComplete := true
|
||||
for i := 0; i < dataShards; i++ {
|
||||
if !present[i] {
|
||||
dataComplete = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !dataComplete {
|
||||
ctx := &erasure_coding.ECContext{DataShards: dataShards, ParityShards: parityShards}
|
||||
glog.Infof("volume %d: %d/%d shards present; reconstructing missing shards (%s) before index rebuild", volumeId, presentCount, dataShards+parityShards, ctx.String())
|
||||
if _, err := erasure_coding.RebuildEcFilesWithContext(base, ctx); err != nil {
|
||||
fail(fmt.Errorf("volume %d: reconstruct missing shards from %d survivors: %w", volumeId, presentCount, err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Collect the data shards (now all present).
|
||||
shardFileNames := make([]string, dataShards)
|
||||
for i := 0; i < dataShards; i++ {
|
||||
shardPath := base + erasure_coding.ToExt(i)
|
||||
if !util.FileExists(shardPath) {
|
||||
fail(fmt.Errorf("volume %d: data shard %s still missing after reconstruction", volumeId, shardPath))
|
||||
return
|
||||
}
|
||||
shardFileNames[i] = shardPath
|
||||
}
|
||||
|
||||
// Without a recorded original size, reconstruct the fully padded layout; the
|
||||
// scan below detects the trailing zero padding and recovers the true size.
|
||||
reconstructSize := datFileSize
|
||||
if reconstructSize <= 0 {
|
||||
reconstructSize = int64(dataShards) * shardSize
|
||||
glog.V(0).Infof("volume %d: no .dat size in .vif; reconstructing padded .dat (%d bytes) from %d data shards", volumeId, reconstructSize, dataShards)
|
||||
}
|
||||
|
||||
// De-stripe the data shards into a temporary .dat next to the shards.
|
||||
tmpBase := base + ".ecxrecover"
|
||||
tmpDat := tmpBase + ".dat"
|
||||
if err := erasure_coding.WriteDatFile(tmpBase, reconstructSize, shardFileNames); err != nil {
|
||||
os.Remove(tmpDat)
|
||||
fail(fmt.Errorf("volume %d: reconstruct .dat from data shards: %w", volumeId, err))
|
||||
return
|
||||
}
|
||||
defer os.Remove(tmpDat)
|
||||
|
||||
realDatSize, version, err := writeEcxFromDat(tmpDat, ecxName)
|
||||
if err != nil {
|
||||
os.Remove(ecxName)
|
||||
fail(fmt.Errorf("volume %d: build .ecx from reconstructed .dat: %w", volumeId, err))
|
||||
return
|
||||
}
|
||||
glog.Infof("volume %d: wrote %s from %d data shards", volumeId, ecxName, dataShards)
|
||||
|
||||
// Regenerate the .vif when missing so the volume can mount and future
|
||||
// rebuilds know the EC ratio and original .dat size.
|
||||
if !vifExists {
|
||||
size := datFileSize
|
||||
if size <= 0 {
|
||||
size = realDatSize
|
||||
}
|
||||
volumeInfo := &volume_server_pb.VolumeInfo{
|
||||
Version: uint32(version),
|
||||
DatFileSize: size,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(dataShards),
|
||||
ParityShards: uint32(parityShards),
|
||||
},
|
||||
}
|
||||
if err := volume_info.SaveVolumeInfo(vifName, volumeInfo); err != nil {
|
||||
fail(fmt.Errorf("volume %d: write %s: %w", volumeId, vifName, err))
|
||||
return
|
||||
}
|
||||
glog.Infof("volume %d: wrote %s (version %d, datFileSize %d, ec %d+%d)", volumeId, vifName, version, size, dataShards, parityShards)
|
||||
}
|
||||
}
|
||||
|
||||
// writeEcxFromDat scans a (reconstructed) .dat and writes an ascending-sorted
|
||||
// .ecx containing only live needles — the same on-disk shape
|
||||
// WriteSortedFileFromIdx produces when an EC volume is first encoded. It returns
|
||||
// the physical .dat size (the offset where the EC zero padding begins) and the
|
||||
// volume version read from the superblock.
|
||||
func writeEcxFromDat(datPath, ecxPath string) (datFileSize int64, version needle.Version, err error) {
|
||||
f, err := os.OpenFile(datPath, os.O_RDONLY, 0644)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("open %s: %w", datPath, err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(f)
|
||||
defer datBackend.Close()
|
||||
|
||||
superBlock, err := super_block.ReadSuperBlock(datBackend)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("read superblock: %w", err)
|
||||
}
|
||||
version = superBlock.Version
|
||||
|
||||
fileSize, _, err := datBackend.GetStat()
|
||||
if err != nil {
|
||||
return 0, version, fmt.Errorf("stat %s: %w", datPath, err)
|
||||
}
|
||||
|
||||
nm := needle_map.NewMemDb()
|
||||
defer nm.Close()
|
||||
|
||||
offset := int64(superBlock.BlockSize())
|
||||
for offset < fileSize {
|
||||
n, _, rest, readErr := needle.ReadNeedleHeader(datBackend, version, offset)
|
||||
if readErr != nil {
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
return 0, version, fmt.Errorf("read needle header at offset %d: %w", offset, readErr)
|
||||
}
|
||||
// EC encoding zero-pads the tail of the last block row. An all-zero
|
||||
// header marks the start of that padding, i.e. the end of real needles.
|
||||
if n.Cookie == 0 && n.Id == 0 && n.Size == 0 {
|
||||
break
|
||||
}
|
||||
if n.Size.IsValid() {
|
||||
if pe := nm.Set(n.Id, types.ToOffset(offset), n.Size); pe != nil {
|
||||
return 0, version, fmt.Errorf("set needle %d: %w", n.Id, pe)
|
||||
}
|
||||
} else {
|
||||
// Deleted/invalid: drop it so the .ecx carries only live entries,
|
||||
// matching the encode-time WriteSortedFileFromIdx behavior.
|
||||
if pe := nm.Delete(n.Id); pe != nil {
|
||||
return 0, version, fmt.Errorf("delete needle %d: %w", n.Id, pe)
|
||||
}
|
||||
}
|
||||
offset += types.NeedleHeaderSize + rest
|
||||
}
|
||||
datFileSize = offset
|
||||
|
||||
ecxFile, err := os.OpenFile(ecxPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return 0, version, fmt.Errorf("open %s: %w", ecxPath, err)
|
||||
}
|
||||
defer ecxFile.Close()
|
||||
|
||||
if err := nm.AscendingVisit(func(value needle_map.NeedleValue) error {
|
||||
_, writeErr := ecxFile.Write(value.ToBytes())
|
||||
return writeErr
|
||||
}); err != nil {
|
||||
return 0, version, fmt.Errorf("write %s: %w", ecxPath, err)
|
||||
}
|
||||
|
||||
return datFileSize, version, nil
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
)
|
||||
|
||||
// buildAndEncodeTestEcVolume writes a small volume (.dat + .idx), EC-encodes it
|
||||
// into .ec00..ec13, and produces the canonical sorted .ecx. It returns the base
|
||||
// path, the canonical .ecx bytes, and the original .dat size. A couple of
|
||||
// needles are deleted so the .ecx must exclude them (live entries only).
|
||||
func buildAndEncodeTestEcVolume(t *testing.T, dir, baseName string) (base string, canonicalEcx []byte, origDatSize int64) {
|
||||
t.Helper()
|
||||
base = filepath.Join(dir, baseName)
|
||||
version := needle.GetCurrentVersion()
|
||||
|
||||
df, err := os.OpenFile(base+".dat", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(df)
|
||||
sb := super_block.SuperBlock{
|
||||
Version: version,
|
||||
ReplicaPlacement: &super_block.ReplicaPlacement{},
|
||||
Ttl: &needle.TTL{},
|
||||
}
|
||||
if _, err := datBackend.WriteAt(sb.Bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
nm := needle_map.NewMemDb()
|
||||
for i := uint64(1); i <= 12; i++ {
|
||||
n := new(needle.Needle)
|
||||
n.Id = types.Uint64ToNeedleId(i)
|
||||
n.Data = make([]byte, 200+int(i))
|
||||
rand.Read(n.Data)
|
||||
n.Checksum = needle.NewCRC(n.Data)
|
||||
offset, _, _, err := n.Append(datBackend, version)
|
||||
if err != nil {
|
||||
t.Fatalf("append needle %d: %v", i, err)
|
||||
}
|
||||
// Store n.Size (the on-disk header size), exactly what the volume
|
||||
// server records in its .idx (volume_write.go: nm.Put(..., n.Size)).
|
||||
if err := nm.Set(n.Id, types.ToOffset(int64(offset)), n.Size); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Delete ids 3 and 8: append an empty needle (delete record) and drop them
|
||||
// from the index, exactly as the encode-time .ecx would reflect.
|
||||
for _, id := range []uint64{3, 8} {
|
||||
n := new(needle.Needle)
|
||||
n.Id = types.Uint64ToNeedleId(id)
|
||||
if _, _, _, err := n.Append(datBackend, version); err != nil {
|
||||
t.Fatalf("append delete record %d: %v", id, err)
|
||||
}
|
||||
if err := nm.Delete(types.Uint64ToNeedleId(id)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := datBackend.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datInfo, err := df.Stat()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
origDatSize = datInfo.Size()
|
||||
datBackend.Close()
|
||||
|
||||
idxFile, err := os.OpenFile(base+".idx", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nm.AscendingVisit(func(v needle_map.NeedleValue) error {
|
||||
_, e := idxFile.Write(v.ToBytes())
|
||||
return e
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
idxFile.Close()
|
||||
nm.Close()
|
||||
|
||||
if err := erasure_coding.WriteEcFiles(base); err != nil {
|
||||
t.Fatalf("WriteEcFiles: %v", err)
|
||||
}
|
||||
if err := erasure_coding.WriteSortedFileFromIdx(base, ".ecx"); err != nil {
|
||||
t.Fatalf("WriteSortedFileFromIdx: %v", err)
|
||||
}
|
||||
canonicalEcx, err = os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(canonicalEcx) == 0 {
|
||||
t.Fatal("canonical .ecx is empty")
|
||||
}
|
||||
return base, canonicalEcx, origDatSize
|
||||
}
|
||||
|
||||
// TestFixEcxFromShards verifies the .ecx and .vif are rebuilt purely from the
|
||||
// data shards when every index/metadata file has been lost.
|
||||
func TestFixEcxFromShards(t *testing.T) {
|
||||
oldData, oldParity := *fixEcDataShards, *fixEcParityShards
|
||||
*fixEcDataShards, *fixEcParityShards = 0, 0
|
||||
*fixIgnoreError = true
|
||||
t.Cleanup(func() {
|
||||
*fixIgnoreError = false
|
||||
*fixEcDataShards, *fixEcParityShards = oldData, oldParity
|
||||
})
|
||||
|
||||
dir := t.TempDir()
|
||||
const volumeId = 7
|
||||
base, canonical, origDatSize := buildAndEncodeTestEcVolume(t, dir, "7")
|
||||
|
||||
// Disaster: keep only the shards.
|
||||
for _, ext := range []string{".ecx", ".ecj", ".idx", ".dat", ".vif"} {
|
||||
if err := os.Remove(base + ext); err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("remove %s: %v", base+ext, err)
|
||||
}
|
||||
}
|
||||
|
||||
doFixEcxFromShards(dir, "7", "", volumeId)
|
||||
|
||||
recovered, err := os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("recovered .ecx not written: %v", err)
|
||||
}
|
||||
if !bytes.Equal(canonical, recovered) {
|
||||
t.Fatalf(".ecx mismatch: canonical %d bytes, recovered %d bytes", len(canonical), len(recovered))
|
||||
}
|
||||
|
||||
// The reconstructed temporary .dat must not be left behind.
|
||||
if _, err := os.Stat(base + ".ecxrecover.dat"); !os.IsNotExist(err) {
|
||||
t.Fatalf("temporary reconstructed .dat was not cleaned up")
|
||||
}
|
||||
|
||||
// .vif must be regenerated with the default ratio and the original .dat size.
|
||||
vi, _, found, err := volume_info.MaybeLoadVolumeInfo(base + ".vif")
|
||||
if err != nil || !found {
|
||||
t.Fatalf(".vif not regenerated: found=%v err=%v", found, err)
|
||||
}
|
||||
if got := int(vi.GetEcShardConfig().GetDataShards()); got != erasure_coding.DataShardsCount {
|
||||
t.Fatalf("data shards = %d, want %d", got, erasure_coding.DataShardsCount)
|
||||
}
|
||||
if got := int(vi.GetEcShardConfig().GetParityShards()); got != erasure_coding.ParityShardsCount {
|
||||
t.Fatalf("parity shards = %d, want %d", got, erasure_coding.ParityShardsCount)
|
||||
}
|
||||
if vi.GetDatFileSize() != origDatSize {
|
||||
t.Fatalf("dat size = %d, want %d", vi.GetDatFileSize(), origDatSize)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFixEcxFromShardsWithVif verifies that when the .vif survives (recording
|
||||
// the exact .dat size and EC ratio) the .ecx is rebuilt from it and the .vif is
|
||||
// left untouched.
|
||||
func TestFixEcxFromShardsWithVif(t *testing.T) {
|
||||
oldData, oldParity := *fixEcDataShards, *fixEcParityShards
|
||||
*fixEcDataShards, *fixEcParityShards = 0, 0
|
||||
*fixIgnoreError = true
|
||||
t.Cleanup(func() {
|
||||
*fixIgnoreError = false
|
||||
*fixEcDataShards, *fixEcParityShards = oldData, oldParity
|
||||
})
|
||||
|
||||
dir := t.TempDir()
|
||||
const volumeId = 9
|
||||
base, canonical, origDatSize := buildAndEncodeTestEcVolume(t, dir, "9")
|
||||
|
||||
// Write a .vif as the volume server would after encoding.
|
||||
if err := volume_info.SaveVolumeInfo(base+".vif", &volume_server_pb.VolumeInfo{
|
||||
Version: uint32(needle.GetCurrentVersion()),
|
||||
DatFileSize: origDatSize,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(erasure_coding.DataShardsCount),
|
||||
ParityShards: uint32(erasure_coding.ParityShardsCount),
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vifBefore, err := os.ReadFile(base + ".vif")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Lose the index but keep the surviving .vif and shards.
|
||||
for _, ext := range []string{".ecx", ".ecj", ".idx", ".dat"} {
|
||||
if err := os.Remove(base + ext); err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("remove %s: %v", base+ext, err)
|
||||
}
|
||||
}
|
||||
|
||||
doFixEcxFromShards(dir, "9", "", volumeId)
|
||||
|
||||
recovered, err := os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("recovered .ecx not written: %v", err)
|
||||
}
|
||||
if !bytes.Equal(canonical, recovered) {
|
||||
t.Fatalf(".ecx mismatch: canonical %d bytes, recovered %d bytes", len(canonical), len(recovered))
|
||||
}
|
||||
|
||||
// An existing .vif must be left untouched.
|
||||
vifAfter, err := os.ReadFile(base + ".vif")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(vifBefore, vifAfter) {
|
||||
t.Fatalf("existing .vif was modified")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFixEcxFromShardsMissingShards verifies that when some shards (including a
|
||||
// couple of data shards) are lost but at least dataShards survive, the missing
|
||||
// shards are reconstructed from parity and the .ecx is still rebuilt correctly.
|
||||
func TestFixEcxFromShardsMissingShards(t *testing.T) {
|
||||
oldData, oldParity := *fixEcDataShards, *fixEcParityShards
|
||||
*fixEcDataShards, *fixEcParityShards = 0, 0
|
||||
*fixIgnoreError = true
|
||||
t.Cleanup(func() {
|
||||
*fixIgnoreError = false
|
||||
*fixEcDataShards, *fixEcParityShards = oldData, oldParity
|
||||
})
|
||||
|
||||
dir := t.TempDir()
|
||||
const volumeId = 11
|
||||
base, canonical, origDatSize := buildAndEncodeTestEcVolume(t, dir, "11")
|
||||
|
||||
// Lose every index/metadata file plus three shards (two data: .ec02, .ec05;
|
||||
// one parity: .ec11), keeping 11 of 14 — enough to reconstruct. The highest
|
||||
// shard (.ec13) is kept so the default 10+4 ratio is inferred without a .vif.
|
||||
for _, ext := range []string{".ecx", ".ecj", ".idx", ".dat", ".vif",
|
||||
erasure_coding.ToExt(2), erasure_coding.ToExt(5), erasure_coding.ToExt(11)} {
|
||||
if err := os.Remove(base + ext); err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("remove %s: %v", base+ext, err)
|
||||
}
|
||||
}
|
||||
|
||||
doFixEcxFromShards(dir, "11", "", volumeId)
|
||||
|
||||
recovered, err := os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("recovered .ecx not written: %v", err)
|
||||
}
|
||||
if !bytes.Equal(canonical, recovered) {
|
||||
t.Fatalf(".ecx mismatch: canonical %d bytes, recovered %d bytes", len(canonical), len(recovered))
|
||||
}
|
||||
|
||||
// The missing shards must have been reconstructed on disk.
|
||||
for _, idx := range []int{2, 5, 11} {
|
||||
if info, err := os.Stat(base + erasure_coding.ToExt(idx)); err != nil || info.Size() == 0 {
|
||||
t.Fatalf("missing shard %d was not reconstructed: err=%v", idx, err)
|
||||
}
|
||||
}
|
||||
|
||||
vi, _, found, err := volume_info.MaybeLoadVolumeInfo(base + ".vif")
|
||||
if err != nil || !found {
|
||||
t.Fatalf(".vif not regenerated: found=%v err=%v", found, err)
|
||||
}
|
||||
if vi.GetDatFileSize() != origDatSize {
|
||||
t.Fatalf("dat size = %d, want %d", vi.GetDatFileSize(), origDatSize)
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@ func (store *MysqlStore) GetName() string {
|
||||
}
|
||||
|
||||
func (store *MysqlStore) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"dsn"),
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
|
||||
@@ -33,6 +33,8 @@ func (store *MysqlStore2) GetName() string {
|
||||
}
|
||||
|
||||
func (store *MysqlStore2) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"createTable"),
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
|
||||
@@ -28,6 +28,8 @@ func (store *PostgresStore) GetName() string {
|
||||
}
|
||||
|
||||
func (store *PostgresStore) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
configuration.GetBool(prefix+"enableUpsert"),
|
||||
|
||||
@@ -33,6 +33,8 @@ func (store *PostgresStore2) GetName() string {
|
||||
}
|
||||
|
||||
func (store *PostgresStore2) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"createTable"),
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
|
||||
@@ -127,7 +127,7 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
// collect names before name, add them to X
|
||||
namesToX, err := nl.NodeRangeBeforeExclusive(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// delete skiplist reference to old node
|
||||
if _, err := nl.skipList.DeleteByKey(prevNodeReference.Key); err != nil {
|
||||
@@ -136,32 +136,32 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
// add namesToY and name to a new X
|
||||
namesToX = append(namesToX, name)
|
||||
if err := nl.ItemAdd([]byte(namesToX[0]), 0, namesToX...); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// remove names less than name from current Y
|
||||
if err := nl.NodeDeleteBeforeExclusive(prevNodeReference, name); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
// point skip list to current Y
|
||||
if err := nl.ItemAdd(lookupKey, prevNodeReference.ElementPointer); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
// collect names after name, add them to Y
|
||||
namesToY, err := nl.NodeRangeAfterExclusive(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// add namesToY and name to a new Y
|
||||
namesToY = append(namesToY, name)
|
||||
if err := nl.ItemAdd(lookupKey, 0, namesToY...); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// remove names after name from current X
|
||||
if err := nl.NodeDeleteAfterExclusive(prevNodeReference, name); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ service SeaweedFiler {
|
||||
rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {
|
||||
}
|
||||
|
||||
rpc FinalizeVersionedWrite (FinalizeVersionedWriteRequest) returns (FinalizeVersionedWriteResponse) {
|
||||
}
|
||||
|
||||
rpc TouchAccessTime (TouchAccessTimeRequest) returns (TouchAccessTimeResponse) {
|
||||
}
|
||||
|
||||
@@ -222,6 +225,29 @@ message CreateEntryRequest {
|
||||
bool is_from_other_cluster = 4;
|
||||
repeated int32 signatures = 5;
|
||||
bool skip_check_parent_directory = 6;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the write, under the filer's per-path lock. The caller must route the
|
||||
// key's writes to this entry's owner filer for the check to be authoritative.
|
||||
WriteCondition condition = 7;
|
||||
}
|
||||
|
||||
// WriteCondition is a single precondition the filer evaluates against the
|
||||
// existing entry before writing. The client reduces request semantics (e.g.
|
||||
// RFC 7232 precedence) to one primitive; the filer just compares. A failed
|
||||
// condition returns FilerError PRECONDITION_FAILED.
|
||||
message WriteCondition {
|
||||
enum Kind {
|
||||
NONE = 0; // unconditional
|
||||
IF_NOT_EXISTS = 1; // fail if the entry exists (If-None-Match: *)
|
||||
IF_EXISTS = 2; // fail if the entry is absent (If-Match: *)
|
||||
IF_ETAG_MATCH = 3; // fail if absent or etag != expected (If-Match: <etag>)
|
||||
IF_ETAG_NOT_MATCH = 4; // fail if present and etag == expected (If-None-Match: <etag>)
|
||||
IF_UNMODIFIED_SINCE = 5; // fail if present and mtime > unix_time
|
||||
IF_MODIFIED_SINCE = 6; // fail if present and mtime <= unix_time
|
||||
}
|
||||
Kind kind = 1;
|
||||
string etag = 2; // expected ETag for IF_ETAG_* kinds
|
||||
int64 unix_time = 3; // bound (unix seconds) for IF_*_SINCE kinds
|
||||
}
|
||||
|
||||
// Structured error codes for filer entry operations.
|
||||
@@ -233,6 +259,7 @@ enum FilerError {
|
||||
EXISTING_IS_DIRECTORY = 3; // cannot overwrite directory with file
|
||||
EXISTING_IS_FILE = 4; // cannot overwrite file with directory
|
||||
ENTRY_ALREADY_EXISTS = 5; // O_EXCL and entry already exists
|
||||
PRECONDITION_FAILED = 6; // WriteCondition not satisfied
|
||||
}
|
||||
|
||||
message CreateEntryResponse {
|
||||
@@ -252,6 +279,40 @@ message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
}
|
||||
|
||||
// FinalizeVersionedWrite atomically finalizes an S3 versioned write on the
|
||||
// object's owner filer, after the caller has created the new version file: under
|
||||
// one exclusive lock on lock_key (the object path — the same key all of this
|
||||
// object's writes serialize on, regardless of versioning state) it evaluates the
|
||||
// precondition against the current latest, stamps the previously-latest version
|
||||
// as noncurrent (before the pointer flip, so the lifecycle router observes it),
|
||||
// then merges the latest-pointer / cached metadata into the .versions directory
|
||||
// entry. The caller routes the object's writes to this owner so the whole
|
||||
// sequence shares one local lock — no distributed lock. Key names are passed in
|
||||
// so the filer stays free of S3 semantics; the new version's file name is read
|
||||
// from set_extended[prior_latest_key].
|
||||
message FinalizeVersionedWriteRequest {
|
||||
string lock_key = 13; // object path; the per-path lock all of this object's writes share
|
||||
string delete_path = 14; // optional entry to delete under the lock first (suspended delete: the null version)
|
||||
string versions_dir = 1; // full path of <object>/.versions
|
||||
map<string, bytes> set_extended = 3; // merge into the .versions directory entry
|
||||
repeated string delete_extended = 4; // remove from the .versions directory entry
|
||||
string prior_latest_key = 5; // .versions entry key holding the latest file name (prior value = demote target)
|
||||
string noncurrent_since_key = 6; // key to stamp on the demoted previous version
|
||||
int64 noncurrent_since_ns = 7; // stamp value; <=0 skips the demote stamp
|
||||
bool is_from_other_cluster = 8;
|
||||
repeated int32 signatures = 9;
|
||||
// Optional precondition, evaluated against the current latest version
|
||||
// (derived from the .versions directory entry's cached metadata) before
|
||||
// anything is written, so the check and the write are atomic on this owner.
|
||||
WriteCondition condition = 10;
|
||||
string latest_etag_key = 11; // .versions entry key holding the latest version's ETag
|
||||
string latest_delete_marker_key = 12; // .versions entry key; "true" means the latest is a delete marker
|
||||
}
|
||||
message FinalizeVersionedWriteResponse {
|
||||
string error = 1;
|
||||
FilerError error_code = 2;
|
||||
}
|
||||
|
||||
message TouchAccessTimeRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
@@ -280,11 +341,16 @@ message DeleteEntryRequest {
|
||||
bool is_from_other_cluster = 7;
|
||||
repeated int32 signatures = 8;
|
||||
int64 if_not_modified_after = 9;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the delete, under the filer's per-path lock. Only honored for a
|
||||
// non-recursive single-entry delete routed to the entry's owner filer.
|
||||
WriteCondition condition = 10;
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
string error = 1;
|
||||
SubscribeMetadataResponse metadata_event = 2;
|
||||
FilerError error_code = 3; // machine-readable error code (e.g. PRECONDITION_FAILED)
|
||||
}
|
||||
|
||||
message AtomicRenameEntryRequest {
|
||||
@@ -421,6 +487,7 @@ message SubscribeMetadataRequest {
|
||||
repeated string directories = 10; // exact directory to watch
|
||||
bool client_supports_batching = 11; // client can unpack SubscribeMetadataResponse.events
|
||||
bool client_supports_metadata_chunks = 12; // client can read log file chunks from volume servers
|
||||
bool client_supports_idle_heartbeat = 13; // server may send empty responses carrying the current time while the client is caught up
|
||||
}
|
||||
message SubscribeMetadataResponse {
|
||||
string directory = 1;
|
||||
|
||||
+847
-416
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v7.34.1
|
||||
// - protoc v6.33.4
|
||||
// source: filer.proto
|
||||
|
||||
package filer_pb
|
||||
@@ -23,6 +23,7 @@ const (
|
||||
SeaweedFiler_ListEntries_FullMethodName = "/filer_pb.SeaweedFiler/ListEntries"
|
||||
SeaweedFiler_CreateEntry_FullMethodName = "/filer_pb.SeaweedFiler/CreateEntry"
|
||||
SeaweedFiler_UpdateEntry_FullMethodName = "/filer_pb.SeaweedFiler/UpdateEntry"
|
||||
SeaweedFiler_FinalizeVersionedWrite_FullMethodName = "/filer_pb.SeaweedFiler/FinalizeVersionedWrite"
|
||||
SeaweedFiler_TouchAccessTime_FullMethodName = "/filer_pb.SeaweedFiler/TouchAccessTime"
|
||||
SeaweedFiler_AppendToEntry_FullMethodName = "/filer_pb.SeaweedFiler/AppendToEntry"
|
||||
SeaweedFiler_DeleteEntry_FullMethodName = "/filer_pb.SeaweedFiler/DeleteEntry"
|
||||
@@ -59,6 +60,7 @@ type SeaweedFilerClient interface {
|
||||
ListEntries(ctx context.Context, in *ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ListEntriesResponse], error)
|
||||
CreateEntry(ctx context.Context, in *CreateEntryRequest, opts ...grpc.CallOption) (*CreateEntryResponse, error)
|
||||
UpdateEntry(ctx context.Context, in *UpdateEntryRequest, opts ...grpc.CallOption) (*UpdateEntryResponse, error)
|
||||
FinalizeVersionedWrite(ctx context.Context, in *FinalizeVersionedWriteRequest, opts ...grpc.CallOption) (*FinalizeVersionedWriteResponse, error)
|
||||
TouchAccessTime(ctx context.Context, in *TouchAccessTimeRequest, opts ...grpc.CallOption) (*TouchAccessTimeResponse, error)
|
||||
AppendToEntry(ctx context.Context, in *AppendToEntryRequest, opts ...grpc.CallOption) (*AppendToEntryResponse, error)
|
||||
DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error)
|
||||
@@ -147,6 +149,16 @@ func (c *seaweedFilerClient) UpdateEntry(ctx context.Context, in *UpdateEntryReq
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) FinalizeVersionedWrite(ctx context.Context, in *FinalizeVersionedWriteRequest, opts ...grpc.CallOption) (*FinalizeVersionedWriteResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(FinalizeVersionedWriteResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_FinalizeVersionedWrite_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) TouchAccessTime(ctx context.Context, in *TouchAccessTimeRequest, opts ...grpc.CallOption) (*TouchAccessTimeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(TouchAccessTimeResponse)
|
||||
@@ -454,6 +466,7 @@ type SeaweedFilerServer interface {
|
||||
ListEntries(*ListEntriesRequest, grpc.ServerStreamingServer[ListEntriesResponse]) error
|
||||
CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error)
|
||||
UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error)
|
||||
FinalizeVersionedWrite(context.Context, *FinalizeVersionedWriteRequest) (*FinalizeVersionedWriteResponse, error)
|
||||
TouchAccessTime(context.Context, *TouchAccessTimeRequest) (*TouchAccessTimeResponse, error)
|
||||
AppendToEntry(context.Context, *AppendToEntryRequest) (*AppendToEntryResponse, error)
|
||||
DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error)
|
||||
@@ -505,6 +518,9 @@ func (UnimplementedSeaweedFilerServer) CreateEntry(context.Context, *CreateEntry
|
||||
func (UnimplementedSeaweedFilerServer) UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method UpdateEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) FinalizeVersionedWrite(context.Context, *FinalizeVersionedWriteRequest) (*FinalizeVersionedWriteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method FinalizeVersionedWrite not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) TouchAccessTime(context.Context, *TouchAccessTimeRequest) (*TouchAccessTimeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method TouchAccessTime not implemented")
|
||||
}
|
||||
@@ -669,6 +685,24 @@ func _SeaweedFiler_UpdateEntry_Handler(srv interface{}, ctx context.Context, dec
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_FinalizeVersionedWrite_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(FinalizeVersionedWriteRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).FinalizeVersionedWrite(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_FinalizeVersionedWrite_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).FinalizeVersionedWrite(ctx, req.(*FinalizeVersionedWriteRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_TouchAccessTime_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(TouchAccessTimeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -1117,6 +1151,10 @@ var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "UpdateEntry",
|
||||
Handler: _SeaweedFiler_UpdateEntry_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "FinalizeVersionedWrite",
|
||||
Handler: _SeaweedFiler_FinalizeVersionedWrite_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "TouchAccessTime",
|
||||
Handler: _SeaweedFiler_TouchAccessTime_Handler,
|
||||
|
||||
@@ -38,6 +38,12 @@ type MetadataFollowOption struct {
|
||||
// the server sends log file chunk fids instead of streaming events,
|
||||
// and the client reads directly from volume servers.
|
||||
LogFileReaderFn LogFileReaderFn
|
||||
// OnIdleHeartbeat, when non-nil, opts in to idle heartbeats: while the
|
||||
// subscriber is caught up the server periodically sends an empty response
|
||||
// carrying the current time, and this is called with that timestamp. It is
|
||||
// a freshness signal only and does not advance StartTsNs, so the resume
|
||||
// checkpoint stays on the last real event.
|
||||
OnIdleHeartbeat func(tsNs int64)
|
||||
}
|
||||
|
||||
type ProcessMetadataFunc func(resp *filer_pb.SubscribeMetadataResponse) error
|
||||
@@ -77,6 +83,7 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
UntilNs: option.StopTsNs,
|
||||
ClientSupportsBatching: true,
|
||||
ClientSupportsMetadataChunks: option.LogFileReaderFn != nil,
|
||||
ClientSupportsIdleHeartbeat: option.OnIdleHeartbeat != nil,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("subscribe: %w", err)
|
||||
@@ -138,6 +145,17 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
pendingRefs = nil
|
||||
}
|
||||
|
||||
// Idle heartbeat: the source is caught up and has no new events, so
|
||||
// it sends an empty response carrying the current time. Surface it as
|
||||
// a freshness signal but leave option.StartTsNs untouched so a restart
|
||||
// still resumes from the last real event.
|
||||
if resp.EventNotification == nil && len(resp.Events) == 0 && resp.TsNs > 0 {
|
||||
if option.OnIdleHeartbeat != nil {
|
||||
option.OnIdleHeartbeat(resp.TsNs)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Process the first event (always present in top-level fields)
|
||||
if resp.EventNotification != nil {
|
||||
if err := processEventFn(resp); err != nil {
|
||||
|
||||
@@ -348,7 +348,9 @@ message JobResult {
|
||||
|
||||
message ClusterContext {
|
||||
repeated string master_grpc_addresses = 1;
|
||||
repeated string filer_grpc_addresses = 2;
|
||||
// Filers in pb.ServerAddress form (host:httpPort.grpcPort). Consumers
|
||||
// convert to a gRPC or HTTP address as needed; see weed/pb/server_address.go.
|
||||
repeated string filer_addresses = 2;
|
||||
repeated string volume_grpc_addresses = 3;
|
||||
map<string, string> metadata = 4;
|
||||
repeated string s3_grpc_addresses = 5;
|
||||
|
||||
@@ -3564,10 +3564,12 @@ func (x *JobResult) GetSummary() string {
|
||||
type ClusterContext struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
MasterGrpcAddresses []string `protobuf:"bytes,1,rep,name=master_grpc_addresses,json=masterGrpcAddresses,proto3" json:"master_grpc_addresses,omitempty"`
|
||||
FilerGrpcAddresses []string `protobuf:"bytes,2,rep,name=filer_grpc_addresses,json=filerGrpcAddresses,proto3" json:"filer_grpc_addresses,omitempty"`
|
||||
VolumeGrpcAddresses []string `protobuf:"bytes,3,rep,name=volume_grpc_addresses,json=volumeGrpcAddresses,proto3" json:"volume_grpc_addresses,omitempty"`
|
||||
Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
S3GrpcAddresses []string `protobuf:"bytes,5,rep,name=s3_grpc_addresses,json=s3GrpcAddresses,proto3" json:"s3_grpc_addresses,omitempty"`
|
||||
// Filers in pb.ServerAddress form (host:httpPort.grpcPort). Consumers
|
||||
// convert to a gRPC or HTTP address as needed; see weed/pb/server_address.go.
|
||||
FilerAddresses []string `protobuf:"bytes,2,rep,name=filer_addresses,json=filerAddresses,proto3" json:"filer_addresses,omitempty"`
|
||||
VolumeGrpcAddresses []string `protobuf:"bytes,3,rep,name=volume_grpc_addresses,json=volumeGrpcAddresses,proto3" json:"volume_grpc_addresses,omitempty"`
|
||||
Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
S3GrpcAddresses []string `protobuf:"bytes,5,rep,name=s3_grpc_addresses,json=s3GrpcAddresses,proto3" json:"s3_grpc_addresses,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3609,9 +3611,9 @@ func (x *ClusterContext) GetMasterGrpcAddresses() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ClusterContext) GetFilerGrpcAddresses() []string {
|
||||
func (x *ClusterContext) GetFilerAddresses() []string {
|
||||
if x != nil {
|
||||
return x.FilerGrpcAddresses
|
||||
return x.FilerAddresses
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -4273,10 +4275,10 @@ const file_plugin_proto_rawDesc = "" +
|
||||
"\asummary\x18\x02 \x01(\tR\asummary\x1aT\n" +
|
||||
"\x11OutputValuesEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12)\n" +
|
||||
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"\xd5\x02\n" +
|
||||
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"\xcc\x02\n" +
|
||||
"\x0eClusterContext\x122\n" +
|
||||
"\x15master_grpc_addresses\x18\x01 \x03(\tR\x13masterGrpcAddresses\x120\n" +
|
||||
"\x14filer_grpc_addresses\x18\x02 \x03(\tR\x12filerGrpcAddresses\x122\n" +
|
||||
"\x15master_grpc_addresses\x18\x01 \x03(\tR\x13masterGrpcAddresses\x12'\n" +
|
||||
"\x0ffiler_addresses\x18\x02 \x03(\tR\x0efilerAddresses\x122\n" +
|
||||
"\x15volume_grpc_addresses\x18\x03 \x03(\tR\x13volumeGrpcAddresses\x12@\n" +
|
||||
"\bmetadata\x18\x04 \x03(\v2$.plugin.ClusterContext.MetadataEntryR\bmetadata\x12*\n" +
|
||||
"\x11s3_grpc_addresses\x18\x05 \x03(\tR\x0fs3GrpcAddresses\x1a;\n" +
|
||||
|
||||
@@ -374,6 +374,7 @@ message ErasureCodingTaskConfig {
|
||||
int32 min_volume_size_mb = 3; // Minimum volume size for EC
|
||||
string collection_filter = 4; // Only process volumes from specific collections
|
||||
repeated string preferred_tags = 5; // Disk tags to prioritize for EC shard placement
|
||||
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
@@ -413,6 +414,7 @@ message EcBalanceTaskConfig {
|
||||
string collection_filter = 3; // Collection filter
|
||||
string disk_type = 4; // Disk type filter
|
||||
repeated string preferred_tags = 5; // Preferred disk tags for placement
|
||||
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
}
|
||||
|
||||
// ========== Task Persistence Messages ==========
|
||||
|
||||
@@ -2960,6 +2960,7 @@ type ErasureCodingTaskConfig struct {
|
||||
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
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3029,6 +3030,13 @@ func (x *ErasureCodingTaskConfig) GetPreferredTags() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ErasureCodingTaskConfig) GetReplicaPlacement() string {
|
||||
if x != nil {
|
||||
return x.ReplicaPlacement
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
type BalanceTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -3297,6 +3305,7 @@ type EcBalanceTaskConfig struct {
|
||||
CollectionFilter string `protobuf:"bytes,3,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Collection filter
|
||||
DiskType string `protobuf:"bytes,4,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"` // Disk type filter
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Preferred disk tags for 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
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3366,6 +3375,13 @@ func (x *EcBalanceTaskConfig) GetPreferredTags() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *EcBalanceTaskConfig) GetReplicaPlacement() string {
|
||||
if x != nil {
|
||||
return x.ReplicaPlacement
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// MaintenanceTaskData represents complete task state for persistence
|
||||
type MaintenanceTaskData struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -4210,13 +4226,14 @@ 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\"\xed\x01\n" +
|
||||
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\x9a\x02\n" +
|
||||
"\x17ErasureCodingTaskConfig\x12%\n" +
|
||||
"\x0efullness_ratio\x18\x01 \x01(\x01R\rfullnessRatio\x12*\n" +
|
||||
"\x11quiet_for_seconds\x18\x02 \x01(\x05R\x0fquietForSeconds\x12+\n" +
|
||||
"\x12min_volume_size_mb\x18\x03 \x01(\x05R\x0fminVolumeSizeMb\x12+\n" +
|
||||
"\x11collection_filter\x18\x04 \x01(\tR\x10collectionFilter\x12%\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\"n\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"n\n" +
|
||||
"\x11BalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\"I\n" +
|
||||
@@ -4238,13 +4255,14 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x0esource_disk_id\x18\x05 \x01(\rR\fsourceDiskId\x12\x1f\n" +
|
||||
"\vtarget_node\x18\x06 \x01(\tR\n" +
|
||||
"targetNode\x12$\n" +
|
||||
"\x0etarget_disk_id\x18\a \x01(\rR\ftargetDiskId\"\xe1\x01\n" +
|
||||
"\x0etarget_disk_id\x18\a \x01(\rR\ftargetDiskId\"\x8e\x02\n" +
|
||||
"\x13EcBalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\x12+\n" +
|
||||
"\x11collection_filter\x18\x03 \x01(\tR\x10collectionFilter\x12\x1b\n" +
|
||||
"\tdisk_type\x18\x04 \x01(\tR\bdiskType\x12%\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\"\xae\a\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"\xae\a\n" +
|
||||
"\x13MaintenanceTaskData\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
|
||||
"\x04type\x18\x02 \x01(\tR\x04type\x12\x1a\n" +
|
||||
|
||||
@@ -19,9 +19,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
adminScriptJobType = "admin_script"
|
||||
maxAdminScriptOutputBytes = 16 * 1024
|
||||
defaultAdminScriptRunMins = 17
|
||||
adminScriptJobType = "admin_script"
|
||||
maxAdminScriptOutputBytes = 16 * 1024
|
||||
defaultAdminScriptRunMins = 17
|
||||
adminScriptDetectTickMinutes = 17
|
||||
)
|
||||
|
||||
@@ -546,13 +546,31 @@ func (h *AdminScriptHandler) buildAdminScriptCommandEnv(
|
||||
ctx context.Context,
|
||||
clusterContext *plugin_pb.ClusterContext,
|
||||
) (*shell.CommandEnv, context.CancelFunc, error) {
|
||||
options, err := h.buildAdminScriptShellOptions(clusterContext)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&options)
|
||||
commandEnv.ForceNoLock()
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
go commandEnv.MasterClient.KeepConnectedToMaster(ctx)
|
||||
|
||||
return commandEnv, cancel, nil
|
||||
}
|
||||
|
||||
// buildAdminScriptShellOptions maps a cluster context onto shell.ShellOptions.
|
||||
// It is split out from buildAdminScriptCommandEnv so the address handling is
|
||||
// testable without standing up a master client.
|
||||
func (h *AdminScriptHandler) buildAdminScriptShellOptions(clusterContext *plugin_pb.ClusterContext) (shell.ShellOptions, error) {
|
||||
if clusterContext == nil {
|
||||
return nil, nil, fmt.Errorf("cluster context is required")
|
||||
return shell.ShellOptions{}, fmt.Errorf("cluster context is required")
|
||||
}
|
||||
|
||||
masters := normalizeAddressList(clusterContext.MasterGrpcAddresses)
|
||||
if len(masters) == 0 {
|
||||
return nil, nil, fmt.Errorf("missing master addresses for admin script")
|
||||
return shell.ShellOptions{}, fmt.Errorf("missing master addresses for admin script")
|
||||
}
|
||||
|
||||
filerGroup := ""
|
||||
@@ -564,20 +582,17 @@ func (h *AdminScriptHandler) buildAdminScriptCommandEnv(
|
||||
Directory: "/",
|
||||
}
|
||||
|
||||
filers := normalizeAddressList(clusterContext.FilerGrpcAddresses)
|
||||
// FilerAddresses are pb.ServerAddress strings (host:httpPort.grpcPort).
|
||||
// ShellOptions.FilerAddress is itself a ServerAddress; shell commands derive
|
||||
// the gRPC or HTTP port from it as needed, so store it verbatim.
|
||||
filers := normalizeAddressList(clusterContext.FilerAddresses)
|
||||
if len(filers) > 0 {
|
||||
options.FilerAddress = pb.ServerAddress(filers[0])
|
||||
} else {
|
||||
glog.V(1).Infof("admin script worker missing filer address; filer-dependent commands may fail")
|
||||
}
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&options)
|
||||
commandEnv.ForceNoLock()
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
go commandEnv.MasterClient.KeepConnectedToMaster(ctx)
|
||||
|
||||
return commandEnv, cancel, nil
|
||||
return options, nil
|
||||
}
|
||||
|
||||
func normalizeAddressList(addresses []string) []string {
|
||||
|
||||
@@ -10,6 +10,36 @@ import (
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func TestAdminScriptFilerAddressKeepsGrpcPortOffConvention(t *testing.T) {
|
||||
// FilerAddresses arrive as pb.ServerAddress (host:httpPort.grpcPort). The
|
||||
// shell derives the gRPC port from FilerAddress via ToGrpcAddress(); it must
|
||||
// land on the real gRPC port even when that port is off the httpPort+10000
|
||||
// convention, not double the offset into a non-existent filer:28890.
|
||||
h := NewAdminScriptHandler(nil)
|
||||
options, err := h.buildAdminScriptShellOptions(&plugin_pb.ClusterContext{
|
||||
MasterGrpcAddresses: []string{"master:19333"},
|
||||
FilerAddresses: []string{"filer:8888.18890"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("buildAdminScriptShellOptions returned err = %v", err)
|
||||
}
|
||||
if grpc := options.FilerAddress.ToGrpcAddress(); grpc != "filer:18890" {
|
||||
t.Fatalf("filer gRPC address = %q, want filer:18890 (not filer:28890)", grpc)
|
||||
}
|
||||
if http := options.FilerAddress.ToHttpAddress(); http != "filer:8888" {
|
||||
t.Fatalf("filer HTTP address = %q, want filer:8888", http)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminScriptShellOptionsRequireMasters(t *testing.T) {
|
||||
h := NewAdminScriptHandler(nil)
|
||||
if _, err := h.buildAdminScriptShellOptions(&plugin_pb.ClusterContext{
|
||||
FilerAddresses: []string{"filer:8888.18890"},
|
||||
}); err == nil {
|
||||
t.Fatalf("expected error when master addresses are missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminScriptDescriptorDefaults(t *testing.T) {
|
||||
descriptor := NewAdminScriptHandler(nil).Descriptor()
|
||||
if descriptor == nil {
|
||||
|
||||
@@ -59,6 +59,38 @@ func CollectVolumeMetricsFromMasters(
|
||||
// FetchVolumeList dials the given master address (trying both the address as
|
||||
// given and the gRPC port variant) and returns the master's volume list. Used
|
||||
// by detection helpers that already know which master address to talk to.
|
||||
// FetchDefaultReplicaPlacement returns the master's configured default replication
|
||||
// (GetMasterConfiguration), used by detectors as the replica-placement fallback so
|
||||
// the plugin path matches the shell. Returns "" if it cannot be fetched, so callers
|
||||
// fall back to even spread rather than failing detection.
|
||||
func FetchDefaultReplicaPlacement(ctx context.Context, masterAddresses []string, grpcDialOption grpc.DialOption) string {
|
||||
if grpcDialOption == nil {
|
||||
return ""
|
||||
}
|
||||
for _, address := range masterAddresses {
|
||||
for _, candidate := range MasterAddressCandidates(address) {
|
||||
if ctx.Err() != nil {
|
||||
return ""
|
||||
}
|
||||
dialCtx, cancelDial := context.WithTimeout(ctx, 5*time.Second)
|
||||
conn, err := pb.GrpcDial(dialCtx, candidate, false, grpcDialOption)
|
||||
cancelDial()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
client := master_pb.NewSeaweedClient(conn)
|
||||
callCtx, cancelCall := context.WithTimeout(ctx, 10*time.Second)
|
||||
resp, callErr := client.GetMasterConfiguration(callCtx, &master_pb.GetMasterConfigurationRequest{})
|
||||
cancelCall()
|
||||
_ = conn.Close()
|
||||
if callErr == nil {
|
||||
return resp.DefaultReplication
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func FetchVolumeList(ctx context.Context, address string, grpcDialOption grpc.DialOption) (*master_pb.VolumeListResponse, error) {
|
||||
var lastErr error
|
||||
for _, candidate := range MasterAddressCandidates(address) {
|
||||
|
||||
@@ -242,9 +242,11 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string,
|
||||
}
|
||||
|
||||
transferStatus := &ChunkTransferStatus{
|
||||
ChunkFileId: sourceChunk.GetFileIdString(),
|
||||
Path: path,
|
||||
Status: "downloading",
|
||||
ChunkTransferSnapshot: ChunkTransferSnapshot{
|
||||
ChunkFileId: sourceChunk.GetFileIdString(),
|
||||
Path: path,
|
||||
Status: "downloading",
|
||||
},
|
||||
}
|
||||
fs.activeTransfers.Store(sourceChunk.GetFileIdString(), transferStatus)
|
||||
defer fs.activeTransfers.Delete(sourceChunk.GetFileIdString())
|
||||
|
||||
@@ -22,12 +22,9 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// ChunkTransferStatus tracks the progress of a single chunk being replicated.
|
||||
// Fields are guarded by mu: ChunkFileId and Path are immutable after creation,
|
||||
// while BytesReceived, Status, and LastErr are updated by fetchAndWrite and
|
||||
// read by ActiveTransfers.
|
||||
type ChunkTransferStatus struct {
|
||||
mu sync.RWMutex
|
||||
// ChunkTransferSnapshot is a lock-free, copyable view of a chunk transfer's
|
||||
// progress, returned by ActiveTransfers.
|
||||
type ChunkTransferSnapshot struct {
|
||||
ChunkFileId string
|
||||
Path string
|
||||
BytesReceived int64
|
||||
@@ -35,6 +32,15 @@ type ChunkTransferStatus struct {
|
||||
LastErr string
|
||||
}
|
||||
|
||||
// ChunkTransferStatus tracks the progress of a single chunk being replicated.
|
||||
// Fields are guarded by mu: ChunkFileId and Path are immutable after creation,
|
||||
// while BytesReceived, Status, and LastErr are updated by fetchAndWrite and
|
||||
// read by ActiveTransfers.
|
||||
type ChunkTransferStatus struct {
|
||||
mu sync.RWMutex
|
||||
ChunkTransferSnapshot
|
||||
}
|
||||
|
||||
type FilerSink struct {
|
||||
filerSource *source.FilerSource
|
||||
grpcAddress string
|
||||
@@ -134,18 +140,12 @@ func (fs *FilerSink) SetChunkConcurrency(concurrency int) {
|
||||
}
|
||||
|
||||
// ActiveTransfers returns an immutable snapshot of all in-progress chunk transfers.
|
||||
func (fs *FilerSink) ActiveTransfers() []ChunkTransferStatus {
|
||||
var transfers []ChunkTransferStatus
|
||||
func (fs *FilerSink) ActiveTransfers() []ChunkTransferSnapshot {
|
||||
var transfers []ChunkTransferSnapshot
|
||||
fs.activeTransfers.Range(func(key, value any) bool {
|
||||
t := value.(*ChunkTransferStatus)
|
||||
t.mu.RLock()
|
||||
transfers = append(transfers, ChunkTransferStatus{
|
||||
ChunkFileId: t.ChunkFileId,
|
||||
Path: t.Path,
|
||||
BytesReceived: t.BytesReceived,
|
||||
Status: t.Status,
|
||||
LastErr: t.LastErr,
|
||||
})
|
||||
transfers = append(transfers, t.ChunkTransferSnapshot)
|
||||
t.mu.RUnlock()
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -68,6 +68,11 @@ type IdentityAccessManagement struct {
|
||||
// IAM Integration for advanced features
|
||||
iamIntegration IAMIntegration
|
||||
|
||||
// Serializes resyncs of the policy set into the advanced IAM manager so that
|
||||
// concurrent policy updates can't apply stale views out of order. See
|
||||
// resyncIAMManagerPolicies.
|
||||
iamManagerSyncMu sync.Mutex
|
||||
|
||||
// Bucket policy engine for evaluating bucket policies
|
||||
policyEngine *BucketPolicyEngine
|
||||
|
||||
@@ -1859,6 +1864,28 @@ func (iam *IdentityAccessManagement) syncRuntimePoliciesToIAMManager(ctx context
|
||||
return manager.SyncRuntimePolicies(ctx, policies)
|
||||
}
|
||||
|
||||
// resyncIAMManagerPolicies pushes the current policy set into the advanced IAM
|
||||
// manager's engine. SyncRuntimePolicies treats its argument as the full desired
|
||||
// state, so callers must not pass snapshots captured earlier: two updates that
|
||||
// mutate iam.policies in order could otherwise apply their snapshots in the
|
||||
// opposite order and resurrect a deleted policy or drop a new one. Instead this
|
||||
// serializes on iamManagerSyncMu and reads iam.policies fresh, so whatever the
|
||||
// map holds when the last caller runs becomes the manager's state. Call it after
|
||||
// the iam.policies mutation has been committed (lock released).
|
||||
func (iam *IdentityAccessManagement) resyncIAMManagerPolicies() {
|
||||
if iam == nil {
|
||||
return
|
||||
}
|
||||
iam.iamManagerSyncMu.Lock()
|
||||
defer iam.iamManagerSyncMu.Unlock()
|
||||
iam.m.RLock()
|
||||
policies := iam.collectPoliciesLocked()
|
||||
iam.m.RUnlock()
|
||||
if err := iam.syncRuntimePoliciesToIAMManager(context.Background(), policies); err != nil {
|
||||
glog.Warningf("Failed to sync runtime policies to IAM Manager: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// PruneBucketFromConfiguration removes any identity actions scoped to the given
|
||||
// bucket (e.g. "Read:bucket", "Write:bucket/prefix") from the persisted S3 IAM
|
||||
// configuration. Wildcarded resources and global actions are preserved because
|
||||
@@ -1953,15 +1980,16 @@ func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromCredentialManager
|
||||
glog.Errorf("Failed to hydrate runtime IAM policies: %v", err)
|
||||
return err
|
||||
}
|
||||
if err := iam.syncRuntimePoliciesToIAMManager(context.Background(), s3ApiConfiguration.Policies); err != nil {
|
||||
glog.Errorf("Failed to sync runtime IAM policies to advanced IAM manager: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Install the loaded config into iam.policies first, then resync the advanced
|
||||
// IAM manager from that committed map. Syncing before the load would leave a
|
||||
// window where the manager holds policies the map doesn't, which a concurrent
|
||||
// resync (e.g. SetIAMIntegration or a runtime PutPolicy) would then clobber.
|
||||
if err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {
|
||||
glog.Errorf("Failed to load S3 API configuration: %v", err)
|
||||
return err
|
||||
}
|
||||
iam.resyncIAMManagerPolicies()
|
||||
|
||||
glog.V(1).Infof("Successfully loaded S3 API configuration from credential manager")
|
||||
return nil
|
||||
@@ -2010,8 +2038,14 @@ func (iam *IdentityAccessManagement) initializeKMSFromJSON(configContent []byte)
|
||||
// isAuthEnabled themselves via EnableAuthEnforcement / updateAuthenticationState.
|
||||
func (iam *IdentityAccessManagement) SetIAMIntegration(integration *S3IAMIntegration) {
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
iam.iamIntegration = integration
|
||||
iam.m.Unlock()
|
||||
// Config loaded before the integration was attached skipped the policy sync
|
||||
// (syncRuntimePoliciesToIAMManager no-ops while iamIntegration is nil), so
|
||||
// flush the policies already in memory into the manager's engine now. This
|
||||
// covers either startup ordering: if the load won the race the policies are
|
||||
// here to push; if SetIAMIntegration won, the load's own resync runs next.
|
||||
iam.resyncIAMManagerPolicies()
|
||||
}
|
||||
|
||||
// EnableAuthEnforcement turns on the auth-required mode unconditionally. Use
|
||||
@@ -2351,7 +2385,6 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity
|
||||
// PutPolicy adds or updates a policy
|
||||
func (iam *IdentityAccessManagement) PutPolicy(name string, content string) error {
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
if iam.policies == nil {
|
||||
iam.policies = make(map[string]*iam_pb.Policy)
|
||||
}
|
||||
@@ -2362,6 +2395,12 @@ func (iam *IdentityAccessManagement) PutPolicy(name string, content string) erro
|
||||
if err := iam.iamPolicyEngine.SetBucketPolicy(name, content); err != nil {
|
||||
glog.Warningf("IAM policy %q is stored but could not be compiled for cache: %v", name, err)
|
||||
}
|
||||
iam.m.Unlock()
|
||||
// Also sync to the advanced IAM Manager's policy engine so that the
|
||||
// authorizeWithIAM path (used when identity has policy_names) sees the update.
|
||||
// Done after releasing iam.m so the per-request auth RLock path isn't blocked
|
||||
// by the policy recompile.
|
||||
iam.resyncIAMManagerPolicies()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2378,14 +2417,26 @@ func (iam *IdentityAccessManagement) GetPolicy(name string) (*iam_pb.Policy, err
|
||||
// DeletePolicy removes a policy
|
||||
func (iam *IdentityAccessManagement) DeletePolicy(name string) error {
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
delete(iam.policies, name)
|
||||
if iam.iamPolicyEngine != nil {
|
||||
_ = iam.iamPolicyEngine.DeleteBucketPolicy(name)
|
||||
}
|
||||
iam.m.Unlock()
|
||||
// Also sync the removal to the advanced IAM Manager's policy engine.
|
||||
iam.resyncIAMManagerPolicies()
|
||||
return nil
|
||||
}
|
||||
|
||||
// collectPoliciesLocked returns all policies as a slice for SyncRuntimePolicies.
|
||||
// Caller must hold iam.m (read or write).
|
||||
func (iam *IdentityAccessManagement) collectPoliciesLocked() []*iam_pb.Policy {
|
||||
policies := make([]*iam_pb.Policy, 0, len(iam.policies))
|
||||
for _, p := range iam.policies {
|
||||
policies = append(policies, p)
|
||||
}
|
||||
return policies
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) PutGroup(group *iam_pb.Group) error {
|
||||
if group == nil {
|
||||
return fmt.Errorf("put group failed: nil group")
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newTestIAMManager(t *testing.T) *integration.IAMManager {
|
||||
t.Helper()
|
||||
mgr := integration.NewIAMManager()
|
||||
require.NoError(t, mgr.Initialize(&integration.IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test",
|
||||
SigningKey: []byte("test-signing-key-32-characters!!"),
|
||||
AccountId: "111122223333",
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Allow", StoreType: "memory"},
|
||||
Roles: &integration.RoleStoreConfig{StoreType: "memory"},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
return mgr
|
||||
}
|
||||
|
||||
func TestPutPolicy_SyncsToIAMManager(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::backup/*"},
|
||||
},
|
||||
})
|
||||
|
||||
require.NoError(t, iam.PutPolicy("BackupAll", string(policyDoc)))
|
||||
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::backup/file.txt",
|
||||
PolicyNames: []string{"BackupAll"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, allowed, "PutPolicy should sync to IAM Manager policy engine")
|
||||
}
|
||||
|
||||
func TestDeletePolicy_SyncsToIAMManager(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::backup/*"},
|
||||
},
|
||||
})
|
||||
|
||||
require.NoError(t, iam.PutPolicy("BackupAll", string(policyDoc)))
|
||||
require.NoError(t, iam.DeletePolicy("BackupAll"))
|
||||
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::backup/file.txt",
|
||||
PolicyNames: []string{"BackupAll"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed, "DeletePolicy should remove from IAM Manager policy engine")
|
||||
}
|
||||
|
||||
// TestSetIAMIntegration_FlushesLoadedPolicies reproduces the startup race: a
|
||||
// policy is loaded into the IAM cache before the integration is attached (so the
|
||||
// sync was skipped), then SetIAMIntegration must flush it into the manager's
|
||||
// engine. Without the flush, policy_names identities get AccessDenied until an
|
||||
// external IAM change triggers a reload.
|
||||
func TestSetIAMIntegration_FlushesLoadedPolicies(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::backup/*"},
|
||||
},
|
||||
})
|
||||
|
||||
// Integration not attached yet, so this only lands in the legacy engine.
|
||||
require.NoError(t, iam.PutPolicy("BackupAll", string(policyDoc)))
|
||||
|
||||
mgr := newTestIAMManager(t)
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::backup/file.txt",
|
||||
PolicyNames: []string{"BackupAll"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, allowed, "SetIAMIntegration should flush already-loaded policies into the IAM Manager")
|
||||
}
|
||||
|
||||
// TestResyncIAMManager_ReflectsCurrentPolicies pins the property that prevents
|
||||
// the stale-snapshot race: SyncRuntimePolicies replaces the full desired set, so
|
||||
// the resync must derive that set from the live iam.policies map at apply time,
|
||||
// not from a view captured earlier. Here the map is mutated out from under an
|
||||
// already-synced policy, and the next resync must converge the manager onto the
|
||||
// new map rather than reinstating the old state.
|
||||
func TestResyncIAMManager_ReflectsCurrentPolicies(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
doc := func(name string) string {
|
||||
b, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::" + name + "/*"},
|
||||
},
|
||||
})
|
||||
return string(b)
|
||||
}
|
||||
allows := func(name string) bool {
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::" + name + "/file.txt",
|
||||
PolicyNames: []string{name},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return allowed
|
||||
}
|
||||
|
||||
require.NoError(t, iam.PutPolicy("alpha", doc("alpha")))
|
||||
require.True(t, allows("alpha"))
|
||||
|
||||
// Swap the map contents without going through PutPolicy/DeletePolicy, then
|
||||
// resync. A snapshot-based sync would push a pre-swap view; the fresh-read
|
||||
// resync must mirror the current map: alpha gone, beta present.
|
||||
iam.m.Lock()
|
||||
delete(iam.policies, "alpha")
|
||||
iam.policies["beta"] = &iam_pb.Policy{Name: "beta", Content: doc("beta")}
|
||||
iam.m.Unlock()
|
||||
iam.resyncIAMManagerPolicies()
|
||||
|
||||
require.False(t, allows("alpha"), "resync should drop a policy no longer in the map")
|
||||
require.True(t, allows("beta"), "resync should add a policy newly in the map")
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
@@ -553,9 +554,28 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
uploadDirectory := s3a.genUploadsFolder(*input.Bucket) + "/" + *input.UploadId
|
||||
entryName, dirName := s3a.getEntryNameAndDir(input)
|
||||
var completionState *multipartCompletionState
|
||||
finalizeCode := s3a.withObjectWriteLock(*input.Bucket, *input.Key, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, *input.Bucket, *input.Key)
|
||||
}, func() s3err.ErrorCode {
|
||||
// Route the completion to the object's owner and skip the distributed lock
|
||||
// when it can carry its own precondition. A non-versioned completion is a
|
||||
// single CreateEntry; a versioning-enabled completion is a unique version
|
||||
// file plus an atomic latest-pointer flip (FinalizeVersionedWrite). Both
|
||||
// evaluate the precondition under the per-path lock, so the lock wrapper is
|
||||
// only kept for paths that can't route: object-lock, suspended versioning,
|
||||
// unsupported preconditions, or before a ring view arrives. Assembly and the
|
||||
// idempotency replay below are read-only and safe outside any lock.
|
||||
mpuCond, mpuCondOk := buildWriteCondition(r)
|
||||
var nvOwner pb.ServerAddress
|
||||
var versionedOwner pb.ServerAddress
|
||||
if mpuCondOk {
|
||||
if vs, vErr := s3a.getVersioningState(*input.Bucket); vErr == nil {
|
||||
switch vs {
|
||||
case "":
|
||||
nvOwner, _ = s3a.routedObjectOwner(*input.Bucket, *input.Key)
|
||||
case s3_constants.VersioningEnabled:
|
||||
versionedOwner = s3a.objectWriteOwner(*input.Bucket, *input.Key)
|
||||
}
|
||||
}
|
||||
}
|
||||
finalizeBody := func() s3err.ErrorCode {
|
||||
var prepCode s3err.ErrorCode
|
||||
completionState, output, prepCode = s3a.prepareMultipartCompletionState(r, input, uploadDirectory, entryName, dirName, completedPartNumbers, completedPartMap, maxPartNo)
|
||||
if prepCode != s3err.ErrNone || output != nil {
|
||||
@@ -649,9 +669,20 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
versionEntryForCache.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
|
||||
}
|
||||
|
||||
// Update the .versions directory metadata to indicate this is the latest version
|
||||
// Pass entry to cache its metadata for single-scan list efficiency
|
||||
if err := s3a.updateLatestVersionInDirectory(*input.Bucket, *input.Key, versionId, versionFileName, versionEntryForCache); err != nil {
|
||||
// Update the .versions directory metadata to indicate this is the
|
||||
// latest version. When the owner is known (computed above as
|
||||
// versionedOwner) the pointer flip is routed: it serializes on the
|
||||
// object key against routed versioned writes and evaluates the
|
||||
// precondition atomically, so the completion takes no distributed lock.
|
||||
// Fall back to the lock-based update when the owner is unknown.
|
||||
if versionedOwner != "" {
|
||||
if code := s3a.routedVersionedFinalize(versionedOwner, *input.Bucket, *input.Key, versionId, versionFileName, versionEntryForCache, mpuCond, ""); code != s3err.ErrNone {
|
||||
if rollbackErr := s3a.rollbackMultipartVersion(versionDir, versionFileName); rollbackErr != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to rollback version %s for %s/%s after routed finalize error: %v", versionId, *input.Bucket, *input.Key, rollbackErr)
|
||||
}
|
||||
return code
|
||||
}
|
||||
} else if err := s3a.updateLatestVersionInDirectory(*input.Bucket, *input.Key, versionId, versionFileName, versionEntryForCache); err != nil {
|
||||
if rollbackErr := s3a.rollbackMultipartVersion(versionDir, versionFileName); rollbackErr != nil {
|
||||
glog.Errorf("completeMultipartUpload: failed to rollback version %s for %s/%s after latest pointer update error: %v", versionId, *input.Bucket, *input.Key, rollbackErr)
|
||||
}
|
||||
@@ -739,7 +770,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
}
|
||||
|
||||
// For non-versioned buckets, create main object file
|
||||
if err := s3a.mkFile(dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
|
||||
nvModifier := func(entry *filer_pb.Entry) {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
@@ -787,7 +818,14 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
if completionState.entityWithTtl {
|
||||
entry.Extended[s3_constants.SeaweedFSExpiresS3] = []byte("true")
|
||||
}
|
||||
}); err != nil {
|
||||
}
|
||||
if nvOwner != "" {
|
||||
// Routed path: the owner evaluates the precondition and writes under
|
||||
// its local lock, so the lock wrapper below is skipped.
|
||||
if code := s3a.mkFileRouted(nvOwner, dirName, entryName, completionState.finalParts, mpuCond, nvModifier); code != s3err.ErrNone {
|
||||
return code
|
||||
}
|
||||
} else if err := s3a.mkFile(dirName, entryName, completionState.finalParts, nvModifier); err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s/%s error: %v", dirName, entryName, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
@@ -802,7 +840,17 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
ChecksumValue: completionState.checksumValue,
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
var finalizeCode s3err.ErrorCode
|
||||
if nvOwner != "" || versionedOwner != "" {
|
||||
// Routed completion: no distributed lock, no gateway precondition here —
|
||||
// the routed write carries the condition.
|
||||
finalizeCode = finalizeBody()
|
||||
} else {
|
||||
finalizeCode = s3a.withObjectWriteLock(*input.Bucket, *input.Key, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, *input.Bucket, *input.Key)
|
||||
}, finalizeBody)
|
||||
}
|
||||
if finalizeCode != s3err.ErrNone {
|
||||
return nil, finalizeCode
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
@@ -248,24 +249,65 @@ type contextKey string
|
||||
const (
|
||||
contextKeyIdentityName contextKey = "s3-identity-name"
|
||||
contextKeyIdentityObject contextKey = "s3-identity-object"
|
||||
contextKeyIdentityHolder contextKey = "s3-identity-holder"
|
||||
)
|
||||
|
||||
// identityHolder is a mutable container for the authenticated identity name,
|
||||
// stored by pointer in the request context. Authentication runs as an inner
|
||||
// handler that records the identity with r.WithContext, which returns a request
|
||||
// copy; that copy's new context values are invisible to outer middleware (e.g.
|
||||
// the audit logger) holding an earlier copy of the request. A pointer to a
|
||||
// holder installed before authentication is shared across all copies, so the
|
||||
// name written by the inner handler is readable by the outer middleware.
|
||||
type identityHolder struct {
|
||||
name atomic.Pointer[string]
|
||||
}
|
||||
|
||||
// EnsureIdentityHolder attaches a mutable identity holder to the request context
|
||||
// if one is not already present, returning the (possibly new) request. Install
|
||||
// it before authentication so the authenticated requester remains recoverable
|
||||
// from the original request, e.g. when emitting an audit entry for a handler
|
||||
// that does not log the requester itself.
|
||||
func EnsureIdentityHolder(r *http.Request) *http.Request {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
if h, ok := r.Context().Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
return r
|
||||
}
|
||||
return r.WithContext(context.WithValue(r.Context(), contextKeyIdentityHolder, &identityHolder{}))
|
||||
}
|
||||
|
||||
// SetIdentityNameInContext stores the authenticated identity name in the request context
|
||||
// This is the secure way to propagate identity - headers can be spoofed, context cannot
|
||||
func SetIdentityNameInContext(ctx context.Context, identityName string) context.Context {
|
||||
if identityName != "" {
|
||||
return context.WithValue(ctx, contextKeyIdentityName, identityName)
|
||||
if identityName == "" {
|
||||
return ctx
|
||||
}
|
||||
return ctx
|
||||
// Also record into the mutable holder (if installed) so the name survives the
|
||||
// request-context copy and stays visible to outer middleware such as the
|
||||
// audit logger.
|
||||
if h, ok := ctx.Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
h.name.Store(&identityName)
|
||||
}
|
||||
return context.WithValue(ctx, contextKeyIdentityName, identityName)
|
||||
}
|
||||
|
||||
// GetIdentityNameFromContext retrieves the authenticated identity name from the request context
|
||||
// Returns empty string if no identity is set (unauthenticated request)
|
||||
// This is the secure way to retrieve identity - never read from headers directly
|
||||
func GetIdentityNameFromContext(r *http.Request) string {
|
||||
if name, ok := r.Context().Value(contextKeyIdentityName).(string); ok {
|
||||
// Prefer the per-request context value; fall back to the mutable holder for
|
||||
// callers (e.g. the audit middleware) that hold a copy of the request taken
|
||||
// before authentication set the identity.
|
||||
if name, ok := r.Context().Value(contextKeyIdentityName).(string); ok && name != "" {
|
||||
return name
|
||||
}
|
||||
if h, ok := r.Context().Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
if name := h.name.Load(); name != nil {
|
||||
return *name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package s3_constants
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -129,3 +131,55 @@ func TestRemoveDuplicateSlashes(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentityHolderPropagation reproduces the audit-log middleware chain: an
|
||||
// outer handler installs the holder, an inner handler authenticates and records
|
||||
// the identity on a request copy, and the outer handler must still recover the
|
||||
// requester from its own (earlier) copy of the request.
|
||||
func TestIdentityHolderPropagation(t *testing.T) {
|
||||
outer := httptest.NewRequest(http.MethodGet, "/bucket/object", nil)
|
||||
|
||||
// Before the holder is installed there is no identity to recover.
|
||||
if got := GetIdentityNameFromContext(outer); got != "" {
|
||||
t.Fatalf("unauthenticated request reports requester %q, want empty", got)
|
||||
}
|
||||
|
||||
outer = EnsureIdentityHolder(outer)
|
||||
|
||||
// The inner handler sets the identity on a copy, mirroring how auth wraps
|
||||
// the request with r.WithContext before invoking the next handler.
|
||||
innerCtx := SetIdentityNameInContext(outer.Context(), "admin")
|
||||
inner := outer.WithContext(innerCtx)
|
||||
|
||||
if got := GetIdentityNameFromContext(inner); got != "admin" {
|
||||
t.Errorf("inner request requester = %q, want admin", got)
|
||||
}
|
||||
if got := GetIdentityNameFromContext(outer); got != "admin" {
|
||||
t.Errorf("outer request requester = %q, want admin (must propagate via holder)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureIdentityHolderIdempotent(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/bucket/object", nil)
|
||||
|
||||
first := EnsureIdentityHolder(req)
|
||||
if first == req {
|
||||
t.Fatal("EnsureIdentityHolder should return a new request when no holder is present")
|
||||
}
|
||||
|
||||
again := EnsureIdentityHolder(first)
|
||||
if again != first {
|
||||
t.Error("EnsureIdentityHolder should be idempotent when a holder is already present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetIdentityNameFromContextWithoutHolder(t *testing.T) {
|
||||
// Without a holder, the per-request context value is still honored so paths
|
||||
// that set identity without installing a holder keep working.
|
||||
req := httptest.NewRequest(http.MethodGet, "/bucket/object", nil)
|
||||
req = req.WithContext(SetIdentityNameInContext(req.Context(), "admin"))
|
||||
|
||||
if got := GetIdentityNameFromContext(req); got != "admin" {
|
||||
t.Errorf("requester = %q, want admin", got)
|
||||
}
|
||||
}
|
||||
@@ -69,9 +69,14 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
}
|
||||
return retryLater("TRANSPORT_ERROR: versioning lookup: " + vErr.Error()), nil
|
||||
}
|
||||
// Route the pointer flip to the object's owner so it serializes on the
|
||||
// object key against routed versioned/suspended writes (it would otherwise
|
||||
// flip the latest pointer off that lock). Falls back to the lock path when
|
||||
// the owner is unknown.
|
||||
markerOwner := s3a.objectWriteOwner(req.Bucket, req.ObjectPath)
|
||||
switch state {
|
||||
case s3_constants.VersioningEnabled:
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath); err != nil {
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath, markerOwner, nil, ""); err != nil {
|
||||
return retryLater("TRANSPORT_ERROR: createDeleteMarker: " + err.Error()), nil
|
||||
}
|
||||
return done(), nil
|
||||
@@ -82,7 +87,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
return retryLater("TRANSPORT_ERROR: deleteNullVersion: " + err.Error()), nil
|
||||
}
|
||||
}
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath); err != nil {
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath, markerOwner, nil, ""); err != nil {
|
||||
return retryLater("TRANSPORT_ERROR: createDeleteMarker: " + err.Error()), nil
|
||||
}
|
||||
return done(), nil
|
||||
|
||||
@@ -324,7 +324,7 @@ func removeDuplicateSlashes(object string) string {
|
||||
// hasChildren("bucket", "empty-dir") where no children exist → false
|
||||
//
|
||||
// Performance: ~1-5ms per call (one gRPC LIST request with Limit=1)
|
||||
func (s3a *S3ApiServer) hasChildren(bucket, prefix string) bool {
|
||||
func (s3a *S3ApiServer) hasChildren(ctx context.Context, bucket, prefix string) bool {
|
||||
// Clean up prefix: remove leading slashes
|
||||
cleanPrefix := strings.TrimPrefix(prefix, "/")
|
||||
|
||||
@@ -332,35 +332,20 @@ func (s3a *S3ApiServer) hasChildren(bucket, prefix string) bool {
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
fullPath := bucketDir + "/" + cleanPrefix
|
||||
|
||||
// Try to list one child object in the directory
|
||||
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
request := &filer_pb.ListEntriesRequest{
|
||||
Directory: fullPath,
|
||||
Limit: 1,
|
||||
InclusiveStartFrom: true,
|
||||
}
|
||||
|
||||
stream, err := client.ListEntries(context.Background(), request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if we got at least one entry
|
||||
_, err = stream.Recv()
|
||||
if err == io.EOF {
|
||||
return io.EOF // No children
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// List one child object. filer_pb.List cancels the underlying ListEntries
|
||||
// stream when it returns, so gRPC's per-stream client goroutine is not leaked.
|
||||
// The caller's request context is propagated so the probe is cancelled if the
|
||||
// client disconnects.
|
||||
found := false
|
||||
err := filer_pb.List(ctx, s3a, fullPath, "", func(*filer_pb.Entry, bool) error {
|
||||
found = true
|
||||
return nil
|
||||
})
|
||||
}, "", true, 1)
|
||||
|
||||
// If we got an entry (not EOF), then it has children
|
||||
if err == nil {
|
||||
return true
|
||||
return found
|
||||
}
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, filer_pb.ErrNotFound) {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return false
|
||||
}
|
||||
glog.V(1).Infof("hasChildren: list entries failed for %s/%s: %v", bucket, cleanPrefix, err)
|
||||
@@ -2337,7 +2322,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
if isZeroByteFile {
|
||||
// Check if it has children (making it an implicit directory)
|
||||
if s3a.hasChildren(bucket, object) {
|
||||
if s3a.hasChildren(r.Context(), bucket, object) {
|
||||
// This is an implicit directory with children
|
||||
// Return 404 to force clients (like s3fs) to use LIST-based discovery
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
@@ -182,7 +183,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
updatedEntry.Attributes.Mtime = t.Unix()
|
||||
|
||||
dstVersionId, etag, currentErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, updatedEntry)
|
||||
dstVersionId, etag, currentErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, updatedEntry, "", nil)
|
||||
if currentErr != nil {
|
||||
return filerErrorToS3Error(currentErr)
|
||||
}
|
||||
@@ -337,16 +338,49 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
var dstVersionId string
|
||||
var etag string
|
||||
|
||||
finalizeCode := s3a.withObjectWriteLock(dstBucket, dstObject, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, dstBucket, dstObject)
|
||||
}, func() s3err.ErrorCode {
|
||||
var finalizeErr error
|
||||
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry)
|
||||
if finalizeErr != nil {
|
||||
return filerErrorToS3Error(finalizeErr)
|
||||
// Fast path: route the finalize to the destination's owner filer and skip the
|
||||
// distributed lock. A non-versioned destination is a single CreateEntry; a
|
||||
// versioning-enabled destination is a unique version file plus an atomic
|
||||
// latest-pointer update on the .versions owner (FinalizeVersionedWrite).
|
||||
// Suspended versioning (multi-version IsLatest rewrite) keeps the lock path.
|
||||
var finalizeCode s3err.ErrorCode
|
||||
routed := false
|
||||
if cond, condOk := buildWriteCondition(r); condOk {
|
||||
switch dstVersioningState {
|
||||
case "":
|
||||
if owner, ownerOk := s3a.routedObjectOwner(dstBucket, dstObject); ownerOk {
|
||||
if code, e, handled := s3a.routedCopyFinalize(owner, dstBucket, dstObject, dstEntry, cond); handled {
|
||||
finalizeCode, etag, routed = code, e, true
|
||||
}
|
||||
}
|
||||
case s3_constants.VersioningEnabled:
|
||||
if owner := s3a.objectWriteOwner(dstBucket, s3_constants.NormalizeObjectKey(dstObject)); owner != "" {
|
||||
var finalizeErr error
|
||||
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry, owner, cond)
|
||||
switch {
|
||||
case finalizeErr == nil:
|
||||
finalizeCode = s3err.ErrNone
|
||||
case errors.Is(finalizeErr, errVersionedPreconditionFailed):
|
||||
finalizeCode = s3err.ErrPreconditionFailed
|
||||
default:
|
||||
finalizeCode = filerErrorToS3Error(finalizeErr)
|
||||
}
|
||||
routed = true
|
||||
}
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
if !routed {
|
||||
finalizeCode = s3a.withObjectWriteLock(dstBucket, dstObject, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, dstBucket, dstObject)
|
||||
}, func() s3err.ErrorCode {
|
||||
var finalizeErr error
|
||||
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry, "", nil)
|
||||
if finalizeErr != nil {
|
||||
return filerErrorToS3Error(finalizeErr)
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
if finalizeCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, finalizeCode)
|
||||
return
|
||||
@@ -412,7 +446,58 @@ func copyEntryToTarget(dst, src *filer_pb.Entry) {
|
||||
dst.WormEnforcedAtTsNs = src.WormEnforcedAtTsNs
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersioningState string, dstEntry *filer_pb.Entry) (versionId string, etag string, err error) {
|
||||
// routedCopyFinalize writes a non-versioned copy destination as a single
|
||||
// CreateEntry routed to the destination key's owner filer, building the same
|
||||
// entry that finalizeCopyDestination's default branch produces via mkFile. It
|
||||
// returns handled=false to fall back to the lock path on a transport error or an
|
||||
// unmapped in-band error.
|
||||
func (s3a *S3ApiServer) routedCopyFinalize(owner pb.ServerAddress, dstBucket, dstObject string, dstEntry *filer_pb.Entry, cond *filer_pb.WriteCondition) (errCode s3err.ErrorCode, etag string, handled bool) {
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(dstObject)
|
||||
dstPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), normalizedObject))
|
||||
dstDir, dstName := dstPath.DirAndName()
|
||||
|
||||
if dstEntry.Attributes == nil {
|
||||
dstEntry.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
if dstEntry.Extended == nil {
|
||||
dstEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
etag = copyEntryETag(dstPath, dstEntry)
|
||||
cleanupVersioningMetadata(dstEntry.Extended)
|
||||
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
// Build the destination entry exactly as mkFile + copyEntryToTarget would.
|
||||
entry := &filer_pb.Entry{Name: dstName, Chunks: dstEntry.Chunks}
|
||||
copyEntryToTarget(entry, dstEntry)
|
||||
|
||||
resp, err := s3a.createEntryOnFiler(owner, &filer_pb.CreateEntryRequest{
|
||||
Directory: dstDir,
|
||||
Entry: entry,
|
||||
Condition: cond,
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("CopyObjectHandler: routed finalize to %s failed for %s/%s, falling back to lock: %v", owner, dstBucket, dstObject, err)
|
||||
return s3err.ErrNone, "", false
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
if code, mapped := filerErrorCodeToS3Error(resp.ErrorCode); mapped {
|
||||
return code, "", true
|
||||
}
|
||||
glog.Warningf("CopyObjectHandler: routed finalize to %s returned code %v for %s/%s, falling back to lock", owner, resp.ErrorCode, dstBucket, dstObject)
|
||||
return s3err.ErrNone, "", false
|
||||
case resp.Error != "":
|
||||
glog.Warningf("CopyObjectHandler: routed finalize to %s returned %q for %s/%s, falling back to lock", owner, resp.Error, dstBucket, dstObject)
|
||||
return s3err.ErrNone, "", false
|
||||
default:
|
||||
return s3err.ErrNone, etag, true
|
||||
}
|
||||
}
|
||||
|
||||
// finalizeCopyDestination writes the copy destination. When routedOwner is set
|
||||
// (versioning-enabled destination routed off the distributed lock), the latest-
|
||||
// pointer update goes through FinalizeVersionedWrite on that owner, which also
|
||||
// evaluates cond; otherwise it uses the lock-based updateLatestVersionInDirectory.
|
||||
func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersioningState string, dstEntry *filer_pb.Entry, routedOwner pb.ServerAddress, cond *filer_pb.WriteCondition) (versionId string, etag string, err error) {
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(dstObject)
|
||||
dstPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), normalizedObject))
|
||||
dstDir, dstName := dstPath.DirAndName()
|
||||
@@ -444,6 +529,18 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
if routedOwner != "" {
|
||||
// Routed: precondition + demote + pointer flip run atomically on the
|
||||
// .versions owner. Roll back the version file if it does not succeed.
|
||||
if code := s3a.routedVersionedFinalize(routedOwner, dstBucket, normalizedObject, versionId, versionFileName, dstEntry, cond, ""); code != s3err.ErrNone {
|
||||
if rollbackErr := s3a.rollbackCopyVersion(bucketDir, versionObjectPath); rollbackErr != nil {
|
||||
glog.Errorf("CopyObjectHandler: failed to rollback version %s for %s/%s after routed finalize error: %v", versionId, dstBucket, normalizedObject, rollbackErr)
|
||||
}
|
||||
return "", "", finalizeCodeToError(code)
|
||||
}
|
||||
return versionId, etag, nil
|
||||
}
|
||||
|
||||
if err = s3a.updateLatestVersionInDirectory(dstBucket, normalizedObject, versionId, versionFileName, dstEntry); err != nil {
|
||||
if rollbackErr := s3a.rollbackCopyVersion(bucketDir, versionObjectPath); rollbackErr != nil {
|
||||
glog.Errorf("CopyObjectHandler: failed to rollback version %s for %s/%s after latest pointer update error: %v", versionId, dstBucket, normalizedObject, rollbackErr)
|
||||
@@ -627,6 +724,17 @@ type CopyPartResult struct {
|
||||
ETag string `xml:"ETag"`
|
||||
}
|
||||
|
||||
// copyPartLocation returns the destination directory and filename for a
|
||||
// server-side copy part under the destination bucket's .uploads folder. Copy
|
||||
// parts carry a fixed "copy" suffix (rather than the random suffix
|
||||
// genPartUploadPath mints for client uploads) so re-copying a part replaces
|
||||
// its predecessor in place.
|
||||
func (s3a *S3ApiServer) copyPartLocation(dstBucket, uploadID string, partID int) (uploadDir, partName string) {
|
||||
uploadDir = s3a.genUploadsFolder(dstBucket) + "/" + uploadID
|
||||
partName = fmt.Sprintf("%04d_%s.part", partID, "copy")
|
||||
return
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Request) {
|
||||
t := time.Now().UTC().Truncate(time.Millisecond)
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingRESTMPUapi.html
|
||||
@@ -845,6 +953,15 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
Extended: make(map[string][]byte),
|
||||
}
|
||||
|
||||
// The copied part lives under the destination bucket's .uploads folder.
|
||||
// Assign destination volumes against that real filer path so they land in
|
||||
// the destination bucket's collection. r.URL.Path is the S3 request URI
|
||||
// (e.g. /bucket/key), not a filer path, so passing it would skip the
|
||||
// filer's bucket-to-collection mapping and route the copied bytes to the
|
||||
// default collection.
|
||||
uploadDir, partName := s3a.copyPartLocation(dstBucket, uploadID, partID)
|
||||
dstPartPath := uploadDir + "/" + partName
|
||||
|
||||
// Handle zero-size files or empty ranges
|
||||
if entry.Attributes.FileSize == 0 || endOffset < startOffset {
|
||||
// For zero-size files or invalid ranges, create an empty part with size 0
|
||||
@@ -852,7 +969,7 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
dstEntry.Chunks = nil
|
||||
} else {
|
||||
// Copy chunks that overlap with the range
|
||||
dstChunks, err := s3a.copyChunksForRange(entry, startOffset, endOffset, r.URL.Path)
|
||||
dstChunks, err := s3a.copyChunksForRange(entry, startOffset, endOffset, dstPartPath)
|
||||
if err != nil {
|
||||
glog.Errorf("CopyObjectPartHandler copy chunks error: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -862,9 +979,6 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
// Save the part entry to the multipart uploads folder
|
||||
uploadDir := s3a.genUploadsFolder(dstBucket) + "/" + uploadID
|
||||
partName := fmt.Sprintf("%04d_%s.part", partID, "copy")
|
||||
|
||||
// Check if part exists and remove it first (allow re-copying same part)
|
||||
if exists, _ := s3a.exists(uploadDir, partName, false); exists {
|
||||
if err := s3a.rm(uploadDir, partName, false, false); err != nil {
|
||||
@@ -1279,10 +1393,9 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e
|
||||
|
||||
// validateConditionalCopyHeaders validates the conditional copy headers against the source entry
|
||||
func (s3a *S3ApiServer) validateConditionalCopyHeaders(r *http.Request, entry *filer_pb.Entry) s3err.ErrorCode {
|
||||
// Calculate ETag for the source entry
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", r.URL.Path, entry.Name))
|
||||
// Calculate ETag for the source entry. ETagEntry derives the tag from the
|
||||
// chunks/Md5/remote-etag only, so no path is needed here.
|
||||
filerEntry := &filer.Entry{
|
||||
FullPath: srcPath,
|
||||
Attr: filer.Attr{
|
||||
FileSize: entry.Attributes.FileSize,
|
||||
Mtime: time.Unix(entry.Attributes.Mtime, 0),
|
||||
@@ -2276,7 +2389,10 @@ func (s3a *S3ApiServer) copyCrossEncryptionChunk(chunk *filer_pb.FileChunk, sour
|
||||
|
||||
// copyChunksWithSSEC handles SSE-C aware copying with smart fast/slow path selection
|
||||
// Returns chunks and destination metadata that should be applied to the destination entry
|
||||
func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Request) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
// dstPath is the destination object's filer path, so volume assignment targets
|
||||
// the destination bucket's collection. The caller must not pass r.URL.Path (the
|
||||
// S3 request URI), which would route copied chunks to the default collection.
|
||||
func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Request, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
|
||||
// Parse SSE-C headers
|
||||
copySourceKey, err := ParseSSECCopySourceHeaders(r)
|
||||
@@ -2304,7 +2420,7 @@ func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Reques
|
||||
|
||||
if isMultipartSSEC {
|
||||
glog.V(2).Infof("Detected multipart SSE-C object with %d encrypted chunks for copy", sseCChunks)
|
||||
return s3a.copyMultipartSSECChunks(entry, copySourceKey, destKey, r.URL.Path)
|
||||
return s3a.copyMultipartSSECChunks(entry, copySourceKey, destKey, dstPath)
|
||||
}
|
||||
|
||||
// Single-part SSE-C object: use original logic
|
||||
@@ -2320,13 +2436,13 @@ func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Reques
|
||||
case SSECCopyStrategyDirect:
|
||||
// FAST PATH: Direct chunk copy
|
||||
glog.V(2).Infof("Using fast path: direct chunk copy for %s", r.URL.Path)
|
||||
chunks, err := s3a.copyChunks(entry, r.URL.Path)
|
||||
chunks, err := s3a.copyChunks(entry, dstPath)
|
||||
return chunks, nil, err
|
||||
|
||||
case SSECCopyStrategyDecryptEncrypt:
|
||||
// SLOW PATH: Decrypt and re-encrypt
|
||||
glog.V(2).Infof("Using slow path: decrypt/re-encrypt for %s", r.URL.Path)
|
||||
chunks, destIV, err := s3a.copyChunksWithReencryption(entry, copySourceKey, destKey, r.URL.Path)
|
||||
chunks, destIV, err := s3a.copyChunksWithReencryption(entry, copySourceKey, destKey, dstPath)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// TestCopyDestinationPathResolvesBucketCollection guards against server-side
|
||||
// copies routing data into the default collection.
|
||||
//
|
||||
// The filer maps a write to a bucket's collection only when the AssignVolume
|
||||
// Path sits under its buckets folder (/buckets/<bucket>/...). UploadPartCopy
|
||||
// and SSE-C CopyObject used to assign destination volumes against r.URL.Path,
|
||||
// the S3 request URI (e.g. /bucket/key), which never has that prefix; the
|
||||
// copied bytes therefore landed in the default collection instead of the
|
||||
// destination bucket's. The handlers must assign against the real filer path
|
||||
// of the destination.
|
||||
func TestCopyDestinationPathResolvesBucketCollection(t *testing.T) {
|
||||
const bucket = "docker-registry"
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
f := &filer.Filer{DirBucketsPath: "/buckets"}
|
||||
|
||||
// The S3 request URI is not a filer path: the filer cannot derive the
|
||||
// destination bucket from it. This is the shape that caused the leak.
|
||||
if got := f.DetectBucket(util.FullPath("/" + bucket + "/blobs/data")); got != "" {
|
||||
t.Fatalf("S3 request URI unexpectedly mapped to collection %q; the test no longer reproduces the bug", got)
|
||||
}
|
||||
|
||||
// UploadPartCopy assigns against the destination part path under .uploads.
|
||||
uploadDir, partName := s3a.copyPartLocation(bucket, "uploadid", 1)
|
||||
partPath := uploadDir + "/" + partName
|
||||
if got := f.DetectBucket(util.FullPath(partPath)); got != bucket {
|
||||
t.Fatalf("UploadPartCopy dst path %q resolved to collection %q, want %q", partPath, got, bucket)
|
||||
}
|
||||
|
||||
// CopyObject (including the SSE-C paths) assigns against the destination
|
||||
// object path.
|
||||
objPath := fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), "blobs/data")
|
||||
if got := f.DetectBucket(util.FullPath(objPath)); got != bucket {
|
||||
t.Fatalf("CopyObject dst path %q resolved to collection %q, want %q", objPath, got, bucket)
|
||||
}
|
||||
}
|
||||
@@ -397,7 +397,7 @@ func (s3a *S3ApiServer) copyObjectPartViaReencryption(
|
||||
filePath := s3a.genPartUploadPath(dstBucket, uploadID, partID)
|
||||
// Copy-part is an MPU part write under .uploads/<id>/<n>; lifecycle
|
||||
// TTL only applies to the eventual completed object. Pass 0.
|
||||
tag, code, putSSE := s3a.putToFiler(cloned, filePath, srcReader, dstBucket, "", partID, 0, nil)
|
||||
tag, code, putSSE := s3a.putToFiler(cloned, filePath, srcReader, dstBucket, "", partID, 0, nil, false)
|
||||
if code != s3err.ErrNone {
|
||||
return "", SSEResponseMetadata{}, code
|
||||
}
|
||||
@@ -407,8 +407,7 @@ func (s3a *S3ApiServer) copyObjectPartViaReencryption(
|
||||
// writeEmptyCopyPart writes a 0-byte part entry for an empty UploadPartCopy
|
||||
// range, mirroring the legacy fast path's handling of endOffset < startOffset.
|
||||
func (s3a *S3ApiServer) writeEmptyCopyPart(dstBucket, uploadID string, partID int) (string, s3err.ErrorCode) {
|
||||
uploadDir := s3a.genUploadsFolder(dstBucket) + "/" + uploadID
|
||||
partName := fmt.Sprintf("%04d_%s.part", partID, "copy")
|
||||
uploadDir, partName := s3a.copyPartLocation(dstBucket, uploadID, partID)
|
||||
if exists, _ := s3a.exists(uploadDir, partName, false); exists {
|
||||
if err := s3a.rm(uploadDir, partName, false, false); err != nil {
|
||||
return "", s3err.ErrInternalError
|
||||
|
||||
@@ -45,7 +45,7 @@ func (s3a *S3ApiServer) executeUnifiedCopyStrategy(entry *filer_pb.Entry, r *htt
|
||||
return chunks, nil, err
|
||||
|
||||
case CopyStrategyKeyRotation:
|
||||
return s3a.executeKeyRotation(entry, r, state)
|
||||
return s3a.executeKeyRotation(entry, r, state, dstBucket, dstPath)
|
||||
|
||||
case CopyStrategyEncrypt:
|
||||
return s3a.executeEncryptCopy(entry, r, state, dstBucket, dstPath)
|
||||
@@ -90,13 +90,13 @@ func (s3a *S3ApiServer) mapCopyErrorToS3Error(err error) s3err.ErrorCode {
|
||||
}
|
||||
|
||||
// executeKeyRotation handles key rotation for same-object copies
|
||||
func (s3a *S3ApiServer) executeKeyRotation(entry *filer_pb.Entry, r *http.Request, state *EncryptionState) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
func (s3a *S3ApiServer) executeKeyRotation(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
// For key rotation, we only need to update metadata, not re-copy chunks
|
||||
// This is a significant optimization for same-object key changes
|
||||
|
||||
if state.SrcSSEC && state.DstSSEC {
|
||||
// SSE-C key rotation - need to handle new key/IV, use reencrypt logic
|
||||
return s3a.executeReencryptCopy(entry, r, state, "", "")
|
||||
return s3a.executeReencryptCopy(entry, r, state, dstBucket, dstPath)
|
||||
}
|
||||
|
||||
if state.SrcSSEKMS && state.DstSSEKMS {
|
||||
@@ -105,14 +105,14 @@ func (s3a *S3ApiServer) executeKeyRotation(entry *filer_pb.Entry, r *http.Reques
|
||||
}
|
||||
|
||||
// Fallback to reencrypt if we can't do metadata-only rotation
|
||||
return s3a.executeReencryptCopy(entry, r, state, "", "")
|
||||
return s3a.executeReencryptCopy(entry, r, state, dstBucket, dstPath)
|
||||
}
|
||||
|
||||
// executeEncryptCopy handles plain → encrypted copies
|
||||
func (s3a *S3ApiServer) executeEncryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
if state.DstSSEC {
|
||||
// Use existing SSE-C copy logic
|
||||
return s3a.copyChunksWithSSEC(entry, r)
|
||||
return s3a.copyChunksWithSSEC(entry, r, dstPath)
|
||||
}
|
||||
|
||||
if state.DstSSEKMS {
|
||||
@@ -145,7 +145,7 @@ func (s3a *S3ApiServer) executeDecryptCopy(entry *filer_pb.Entry, r *http.Reques
|
||||
func (s3a *S3ApiServer) executeReencryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
// Use chunk-by-chunk approach for all cross-encryption scenarios (consistent behavior)
|
||||
if state.SrcSSEC && state.DstSSEC {
|
||||
return s3a.copyChunksWithSSEC(entry, r)
|
||||
return s3a.copyChunksWithSSEC(entry, r, dstPath)
|
||||
}
|
||||
|
||||
if state.SrcSSEKMS && state.DstSSEKMS {
|
||||
|
||||
@@ -133,7 +133,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
return result, s3err.ErrNone
|
||||
|
||||
case versioningState == s3_constants.VersioningEnabled:
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object, "", nil, "")
|
||||
if err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to create delete marker for %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
@@ -152,7 +152,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
glog.Errorf("deleteVersionedObject: failed to delete null version for %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object, "", nil, "")
|
||||
if err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to create delete marker for suspended versioning %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
@@ -214,33 +214,104 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
|
||||
var deleteResult deleteMutationResult
|
||||
deleteCode := s3a.withObjectWriteLock(bucket, object, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, object, versionId, versioningState, r.Header.Get(s3_constants.IfMatch), s3err.ErrPreconditionFailed)
|
||||
}, func() s3err.ErrorCode {
|
||||
if versioningConfigured {
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, object, versionId, versioningState)
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
var deleteCode s3err.ErrorCode
|
||||
|
||||
// Fast path: route an unversioned object delete to its owner filer, which
|
||||
// serializes it and evaluates the If-Match precondition under the per-path
|
||||
// lock, avoiding the distributed lock. Falls back below for versioned /
|
||||
// object-lock buckets, unsupported conditions, or an unreachable owner.
|
||||
deleteHandled := false
|
||||
if !versioningConfigured {
|
||||
if cond, condOk := buildDeleteCondition(r); condOk {
|
||||
if owner, ownerOk := s3a.routedObjectOwner(bucket, object); ownerOk {
|
||||
resp, err := s3a.deleteEntryOnFiler(owner, bucket, object, cond)
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("DeleteObjectHandler: routed delete to %s failed for %s/%s, falling back to lock: %v", owner, bucket, object, err)
|
||||
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
deleteCode, deleteHandled = s3err.ErrPreconditionFailed, true
|
||||
case resp.Error != "":
|
||||
// Fall back to the lock path, which carries extra handling the
|
||||
// raw DeleteEntry lacks (e.g. demoting a directory marker that
|
||||
// still has children instead of failing on a non-empty folder).
|
||||
glog.Warningf("DeleteObjectHandler: routed delete to %s returned %q for %s/%s, falling back to lock", owner, resp.Error, bucket, object)
|
||||
default:
|
||||
deleteCode, deleteHandled = s3err.ErrNone, true
|
||||
}
|
||||
}
|
||||
deleteResult = result
|
||||
}
|
||||
}
|
||||
|
||||
// Fast path: a versioning-enabled delete (no specific version) creates a
|
||||
// delete marker — a unique marker file plus an atomic latest-pointer flip. We
|
||||
// route it to the .versions owner, off the distributed lock. Suspended
|
||||
// versioning (multi-step) and version-specific deletes keep the lock path.
|
||||
if !deleteHandled && versionId == "" && versioningState == s3_constants.VersioningEnabled {
|
||||
if cond, condOk := buildDeleteCondition(r); condOk {
|
||||
if owner := s3a.objectWriteOwner(bucket, s3_constants.NormalizeObjectKey(object)); owner != "" {
|
||||
vid, err := s3a.createDeleteMarker(bucket, object, owner, cond, "")
|
||||
switch {
|
||||
case err == nil:
|
||||
deleteResult = deleteMutationResult{versionId: vid, deleteMarker: true}
|
||||
deleteCode, deleteHandled = s3err.ErrNone, true
|
||||
case errors.Is(err, errVersionedPreconditionFailed):
|
||||
deleteCode, deleteHandled = s3err.ErrPreconditionFailed, true
|
||||
default:
|
||||
glog.Warningf("DeleteObjectHandler: routed delete marker for %s/%s failed, falling back to lock: %v", bucket, object, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fast path: a suspended-versioning delete (no specific version) removes the
|
||||
// null version (the main object entry) and adds a delete marker — the op does
|
||||
// both atomically under the object-key lock, so it serializes with the (also
|
||||
// routed) suspended PUT. Routed only without If-Match: that condition targets
|
||||
// the main object, not the .versions pointer the op evaluates, so a
|
||||
// conditional suspended delete stays on the lock path.
|
||||
if !deleteHandled && versionId == "" && versioningState == s3_constants.VersioningSuspended {
|
||||
if cond, condOk := buildDeleteCondition(r); condOk && cond.Kind == filer_pb.WriteCondition_NONE {
|
||||
if owner := s3a.objectWriteOwner(bucket, s3_constants.NormalizeObjectKey(object)); owner != "" {
|
||||
nullPath := s3a.toFilerPath(bucket, s3_constants.NormalizeObjectKey(object))
|
||||
vid, err := s3a.createDeleteMarker(bucket, object, owner, cond, nullPath)
|
||||
if err == nil {
|
||||
deleteResult = deleteMutationResult{versionId: vid, deleteMarker: true}
|
||||
deleteCode, deleteHandled = s3err.ErrNone, true
|
||||
} else {
|
||||
glog.Warningf("DeleteObjectHandler: routed suspended delete for %s/%s failed, falling back to lock: %v", bucket, object, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !deleteHandled {
|
||||
deleteCode = s3a.withObjectWriteLock(bucket, object, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, object, versionId, versioningState, r.Header.Get(s3_constants.IfMatch), s3err.ErrPreconditionFailed)
|
||||
}, func() s3err.ErrorCode {
|
||||
if versioningConfigured {
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, object, versionId, versioningState)
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
deleteResult = result
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteObjectHandler: object lock check failed for %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s3a.deleteUnversionedObjectWithClient(client, bucket, object, false)
|
||||
}); err != nil {
|
||||
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteObjectHandler: object lock check failed for %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s3a.deleteUnversionedObjectWithClient(client, bucket, object, false)
|
||||
}); err != nil {
|
||||
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
return s3err.ErrNone
|
||||
})
|
||||
})
|
||||
}
|
||||
if deleteCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, deleteCode)
|
||||
return
|
||||
|
||||
@@ -109,7 +109,7 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
|
||||
// Adjust marker if it ends with delimiter to skip all entries with that prefix
|
||||
marker = adjustMarkerForDelimiter(marker, delimiter)
|
||||
|
||||
response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
|
||||
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
|
||||
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -173,7 +173,7 @@ func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Requ
|
||||
// Adjust marker if it ends with delimiter to skip all entries with that prefix
|
||||
marker = adjustMarkerForDelimiter(marker, delimiter)
|
||||
|
||||
response, err := s3a.listFilerEntries(bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
|
||||
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
|
||||
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -232,7 +232,7 @@ func sanitizeV1MarkerEcho(response *ListBucketResult, marker string, encodingTyp
|
||||
}
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
|
||||
func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
|
||||
// convert full path prefix into directory name and prefix for entry name
|
||||
requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
|
||||
bucketPrefix := s3a.bucketPrefix(bucket)
|
||||
@@ -307,7 +307,7 @@ func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, m
|
||||
if normalizedPrefix != "" {
|
||||
relativePath := strings.TrimPrefix(fmt.Sprintf("%s/%s", dir, entry.Name), bucketPrefix)
|
||||
relativePath = strings.TrimPrefix(relativePath, "/")
|
||||
if normalizedPrefix == relativePath && !s3a.hasChildren(bucket, relativePath) && !entry.IsDirectoryKeyObject() {
|
||||
if normalizedPrefix == relativePath && !s3a.hasChildren(ctx, bucket, relativePath) && !entry.IsDirectoryKeyObject() {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -677,22 +677,41 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
|
||||
}
|
||||
|
||||
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
|
||||
// A trailing-slash prefix (e.g. "logs/") names one directory and asks
|
||||
// whether it exists, so a real but empty directory must be reported for
|
||||
// that probe.
|
||||
explicitDirProbe := cursor.prefixEndsOnDelimiter
|
||||
if cursor.prefixEndsOnDelimiter {
|
||||
cursor.prefixEndsOnDelimiter = false
|
||||
if entry.IsDirectoryKeyObject() {
|
||||
eachEntryFn(dir, entry)
|
||||
}
|
||||
} else if entry.IsDirectoryKeyObject() {
|
||||
}
|
||||
isKeyObject := entry.IsDirectoryKeyObject()
|
||||
if isKeyObject {
|
||||
// Directory key objects (created via PutObject with trailing "/")
|
||||
// must appear as regular keys in recursive listing mode.
|
||||
eachEntryFn(dir, entry)
|
||||
}
|
||||
// Recurse into subdirectory to list any children
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, bucket, eachEntryFn)
|
||||
// Recurse into subdirectory to list any children, noting whether the
|
||||
// subtree produced any entries.
|
||||
childEmitted := false
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, bucket, func(d string, e *filer_pb.Entry) {
|
||||
childEmitted = true
|
||||
eachEntryFn(d, e)
|
||||
})
|
||||
if subErr != nil {
|
||||
err = fmt.Errorf("doListFilerEntries2: %w", subErr)
|
||||
return
|
||||
}
|
||||
// A real but empty directory (created out of band via mount, mkdir or
|
||||
// the filer API, so it carries no MIME) is otherwise invisible to S3
|
||||
// clients that detect directories by listing it under its own "<dir>/"
|
||||
// prefix. Surface it as a directory marker for that explicit probe,
|
||||
// identical to a directory created via PutObject with a trailing "/", so
|
||||
// tools like hadoop-aws can find it. Plain listings are left untouched, so
|
||||
// empty directories left behind by deleted objects are not shown as keys.
|
||||
if explicitDirProbe && !isKeyObject && !childEmitted && !cursor.isTruncated && entry.Attributes != nil {
|
||||
entry.Attributes.Mime = s3_constants.FolderMimeType
|
||||
eachEntryFn(dir, entry)
|
||||
}
|
||||
// println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
|
||||
nextMarker = entry.Name + "/" + subNextMarker
|
||||
if cursor.isTruncated {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -61,3 +62,122 @@ func TestDirectoryListedAsCommonPrefix(t *testing.T) {
|
||||
"Directory should be passed to callback for CommonPrefix processing with delimiter=/")
|
||||
assert.Empty(t, seenFiles, "No files should be seen, only the directory")
|
||||
}
|
||||
|
||||
// TestEmptyDirectorySurfacedAsMarker reproduces the hadoop-aws / Spark case where a
|
||||
// real but empty directory (created via mount, mkdir or the filer API, so it has no
|
||||
// MIME) must be visible to S3 clients that detect directories by listing under the
|
||||
// "<dir>/" prefix. Such a directory is surfaced as a directory marker, identical to
|
||||
// one created via PutObject with a trailing "/".
|
||||
func TestEmptyDirectorySurfacedAsMarker(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{BucketsPath: "/buckets"},
|
||||
}
|
||||
|
||||
emptyDir := &filer_pb.Entry{
|
||||
Name: "logs",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mime: ""},
|
||||
}
|
||||
client := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {emptyDir},
|
||||
"/buckets/test/logs": {}, // empty directory has no children
|
||||
},
|
||||
}
|
||||
|
||||
// Mirrors the getFileStatus probe: prefix "logs/" with delimiter "/".
|
||||
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
|
||||
var seen []*filer_pb.Entry
|
||||
_, err := s3a.doListFilerEntries(client, "/buckets/test", "logs", cursor, "", "/", false, "test",
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
seen = append(seen, entry)
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, seen, 1, "empty directory must be surfaced under the logs/ prefix") {
|
||||
assert.True(t, seen[0].IsDirectoryKeyObject(),
|
||||
"empty directory must be marked as a directory key object so it lists as logs/")
|
||||
assert.Equal(t, s3_constants.FolderMimeType, seen[0].Attributes.Mime)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNonEmptyDirectoryGetsNoPhantomMarker ensures the empty-directory fix does not add
|
||||
// a spurious marker for directories that already have children; the children represent
|
||||
// the directory.
|
||||
func TestNonEmptyDirectoryGetsNoPhantomMarker(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{BucketsPath: "/buckets"},
|
||||
}
|
||||
|
||||
dir := &filer_pb.Entry{
|
||||
Name: "data",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mime: ""},
|
||||
}
|
||||
child := &filer_pb.Entry{
|
||||
Name: "a.txt",
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
}
|
||||
client := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {dir},
|
||||
"/buckets/test/data": {child},
|
||||
},
|
||||
}
|
||||
|
||||
// Recursive listing under the "data/" prefix.
|
||||
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
|
||||
var seen []string
|
||||
_, err := s3a.doListFilerEntries(client, "/buckets/test", "data", cursor, "", "", false, "test",
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
seen = append(seen, entry.Name)
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{"a.txt"}, seen, "non-empty directory must be represented by its child only")
|
||||
}
|
||||
|
||||
// TestEmptyDirectoryHiddenInFlatListing ensures the marker is only surfaced for an
|
||||
// explicit "<dir>/" probe, not in a plain (no prefix, no delimiter) listing. An empty
|
||||
// directory left behind by deleted objects (e.g. after lifecycle expiration) must not
|
||||
// appear as a phantom key, matching AWS S3.
|
||||
func TestEmptyDirectoryHiddenInFlatListing(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{BucketsPath: "/buckets"},
|
||||
}
|
||||
|
||||
emptyDir := &filer_pb.Entry{
|
||||
Name: "expire1",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mime: ""},
|
||||
}
|
||||
keepDir := &filer_pb.Entry{
|
||||
Name: "keep2",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mime: ""},
|
||||
}
|
||||
keepObj := &filer_pb.Entry{
|
||||
Name: "foo",
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
}
|
||||
client := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {emptyDir, keepDir},
|
||||
"/buckets/test/expire1": {},
|
||||
"/buckets/test/keep2": {keepObj},
|
||||
},
|
||||
}
|
||||
|
||||
// Plain flat listing: no prefix, no delimiter.
|
||||
cursor := &ListingCursor{maxKeys: 1000}
|
||||
var seen []string
|
||||
_, err := s3a.doListFilerEntries(client, "/buckets/test", "", cursor, "", "", false, "test",
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
seen = append(seen, entry.Name)
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{"foo"}, seen, "flat listing must hide the empty directory and return only real objects")
|
||||
}
|
||||
@@ -457,7 +457,7 @@ func (s3a *S3ApiServer) PutObjectPartHandler(w http.ResponseWriter, r *http.Requ
|
||||
// transient .uploads/<id>/<n> path, and a part write would otherwise
|
||||
// start the TTL clock before CompleteMultipartUpload ever assembled
|
||||
// the object.
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, "", partID, 0, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, "", partID, 0, nil, false)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("PutObjectPart: putToFiler failed with error code %v for bucket=%s, object=%s, partNumber=%d",
|
||||
errCode, bucket, object, partID)
|
||||
|
||||
@@ -135,7 +135,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
// fields and boundaries inflates ContentLength relative to the
|
||||
// object body, which would mis-evaluate any size-filtered rule.
|
||||
ttlSec := s3a.lifecycleTTLForObjectWrite(bucket, object, fileSize)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, fileBody, bucket, object, 1, ttlSec, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, fileBody, bucket, object, 1, ttlSec, nil, false)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
|
||||
@@ -297,7 +297,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
ttlSec := s3a.lifecycleTTLForObjectWrite(bucket, object, r.ContentLength)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, object, 1, ttlSec, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, object, 1, ttlSec, nil, false)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -359,7 +359,12 @@ func (s3a *S3ApiServer) withObjectWriteLock(bucket, object string, preconditionF
|
||||
// pass 0 because their own keys aren't the user-visible object the rule
|
||||
// targets and a part write would otherwise bind a TTL clock starting
|
||||
// before CompleteMultipartUpload.
|
||||
func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader io.Reader, bucket string, object string, partNumber int, lifecycleTTLSec int32, afterCreate func(entry *filer_pb.Entry) s3err.ErrorCode) (etag string, code s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
|
||||
// uniqueVersionPath marks writes whose target path never collides (an S3 object
|
||||
// version file under <object>/.versions/<versionId>). For those, putToFiler
|
||||
// skips the object write lock and the gateway precondition: the afterCreate hook
|
||||
// finalizes the version atomically on the .versions owner (precondition + demote
|
||||
// + pointer flip) and rolls back the file if that fails.
|
||||
func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader io.Reader, bucket string, object string, partNumber int, lifecycleTTLSec int32, afterCreate func(entry *filer_pb.Entry) s3err.ErrorCode, uniqueVersionPath bool) (etag string, code s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
|
||||
// NEW OPTIMIZATION: Write directly to volume servers, bypassing filer proxy
|
||||
// This eliminates the filer proxy overhead for PUT operations
|
||||
// Note: filePath is now passed directly instead of URL (no parsing needed)
|
||||
@@ -802,7 +807,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
}
|
||||
return s3a.checkConditionalHeaders(r, bucket, object)
|
||||
}
|
||||
createCode := s3a.withObjectWriteLock(bucket, object, preconditionFn, func() s3err.ErrorCode {
|
||||
createUnderLock := func() s3err.ErrorCode {
|
||||
createErr = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
req := &filer_pb.CreateEntryRequest{
|
||||
Directory: path.Dir(filePath),
|
||||
@@ -831,7 +836,52 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
}
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
|
||||
// Fast path: route the create to the object key's owner filer, which
|
||||
// serializes it with its local per-path lock and evaluates the precondition,
|
||||
// avoiding the distributed lock. Restricted to the safe subset by
|
||||
// routedObjectWrite; falls back to the lock for everything else and if the
|
||||
// owner is unreachable.
|
||||
var createCode s3err.ErrorCode
|
||||
routed := false
|
||||
if uniqueVersionPath {
|
||||
// The version-file path never collides, so no object write lock is needed.
|
||||
// createUnderLock creates the file and runs afterCreate, which finalizes
|
||||
// the version (precondition + demote + pointer flip) atomically on the
|
||||
// .versions owner and rolls back the file on failure.
|
||||
createCode, routed = createUnderLock(), true
|
||||
}
|
||||
if !routed {
|
||||
if owner, cond, ok := s3a.routedObjectWrite(r, bucket, object, afterCreate != nil); ok {
|
||||
req := &filer_pb.CreateEntryRequest{
|
||||
Directory: path.Dir(filePath),
|
||||
Entry: entry,
|
||||
Condition: cond,
|
||||
}
|
||||
resp, err := s3a.createEntryOnFiler(owner, req)
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("putToFiler: routed create to %s failed for %s, falling back to lock: %v", owner, filePath, err)
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
// Map known filer error codes to the same S3 errors the lock path
|
||||
// would produce; fall back for any code this does not recognize.
|
||||
if code, mapped := filerErrorCodeToS3Error(resp.ErrorCode); mapped {
|
||||
createCode, routed = code, true
|
||||
} else {
|
||||
glog.Warningf("putToFiler: routed create to %s returned code %v for %s, falling back to lock", owner, resp.ErrorCode, filePath)
|
||||
}
|
||||
case resp.Error != "":
|
||||
// In-band error without a code: fall back so the lock path maps it.
|
||||
glog.Warningf("putToFiler: routed create to %s returned %q for %s, falling back to lock", owner, resp.Error, filePath)
|
||||
default:
|
||||
entryCreated, createCode, routed = true, s3err.ErrNone, true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !routed {
|
||||
createCode = s3a.withObjectWriteLock(bucket, object, preconditionFn, createUnderLock)
|
||||
}
|
||||
if createCode != s3err.ErrNone {
|
||||
if createErr != nil {
|
||||
glog.Errorf("putToFiler: failed to create entry for %s: %v", filePath, createErr)
|
||||
@@ -1280,18 +1330,22 @@ func (s3a *S3ApiServer) putSuspendedVersioningObject(r *http.Request, bucket, ob
|
||||
// it runs while withObjectWriteLock is still held in putToFiler.
|
||||
// Doing it after putToFiler returns would race a concurrent PUT
|
||||
// promoting a newer latest, which we'd then incorrectly wipe.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, func(_ *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject); err != nil {
|
||||
// Best-effort: a stale IsLatest flag is recoverable on the
|
||||
// next list-versions resync, so don't fail the PUT.
|
||||
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
// The null version is written to the main object path, so this is a
|
||||
// single-entry object write — route it on the object key like a normal PUT
|
||||
// (no afterCreate, so putToFiler can take the route-by-key path and skip the
|
||||
// distributed lock). The IsLatest flag rewrite over existing versions is
|
||||
// best-effort bookkeeping, so it runs after the write rather than inside the
|
||||
// atomic boundary.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, nil, false)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("putSuspendedVersioningObject: failed to upload object: %v", errCode)
|
||||
return "", errCode, SSEResponseMetadata{}
|
||||
}
|
||||
if err := s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject); err != nil {
|
||||
// Best-effort: a stale IsLatest flag is recoverable on the next
|
||||
// list-versions resync, so don't fail the PUT.
|
||||
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("putSuspendedVersioningObject: successfully created null version for %s/%s", bucket, object)
|
||||
|
||||
@@ -1453,13 +1507,13 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
|
||||
// Versioned bucket: resolver returns 0 by construction. Pass 0
|
||||
// directly — versioned objects sit on regular volumes and the
|
||||
// lifecycle worker handles their expiration.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, versionFilePath, body, bucket, normalizedObject, 1, 0, func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateLatestVersionInDirectory(bucket, normalizedObject, versionId, versionFileName, versionEntry); err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
//
|
||||
// The version file lives at a unique <object>/.versions/<versionId> path, so
|
||||
// when the .versions owner is known the finalize (precondition + demote +
|
||||
// pointer flip) routes there to run atomically under one local lock, and
|
||||
// putToFiler skips the object write lock. Otherwise it stays on the lock path.
|
||||
finalize, routedVersioned := s3a.versionedAfterCreate(r, bucket, normalizedObject, versionId, versionFileName)
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, versionFilePath, body, bucket, normalizedObject, 1, 0, finalize, routedVersioned)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("putVersionedObject: failed to upload version: %v", errCode)
|
||||
return "", "", errCode, SSEResponseMetadata{}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// routedObjectOwner returns the filer that owns this object's metadata for
|
||||
// route-by-key on a single-entry object write, or ok=false when the write must
|
||||
// keep the distributed lock. Only versioning-*enabled* buckets are excluded:
|
||||
// their writes go to <obj>/.versions and flip the latest pointer (the versioned
|
||||
// finalize path handles those). Suspended and unversioned writes both go to the
|
||||
// main object path, so they route here. Object-lock buckets stay on the lock
|
||||
// path. On any lookup error it falls back to be safe.
|
||||
func (s3a *S3ApiServer) routedObjectOwner(bucket, object string) (pb.ServerAddress, bool) {
|
||||
if object == "" {
|
||||
return "", false
|
||||
}
|
||||
if enabled, err := s3a.isVersioningEnabled(bucket); err != nil || enabled {
|
||||
return "", false
|
||||
}
|
||||
// objectWriteOwner already excludes object-lock buckets (they stay fully on
|
||||
// the distributed lock), returning "" for them.
|
||||
owner := s3a.objectWriteOwner(bucket, object)
|
||||
if owner == "" {
|
||||
return "", false
|
||||
}
|
||||
return owner, true
|
||||
}
|
||||
|
||||
// routedObjectWrite decides whether an object PUT can take the route-by-key
|
||||
// fast path: the metadata write goes straight to the key's owner filer, which
|
||||
// serializes it with its local per-path lock and evaluates the precondition,
|
||||
// instead of acquiring a distributed lock. It returns the owner filer and the
|
||||
// reduced precondition, or ok=false to fall back to withObjectWriteLock.
|
||||
//
|
||||
// The fast path additionally requires no post-create hook and a precondition
|
||||
// that reduces to one primitive.
|
||||
func (s3a *S3ApiServer) routedObjectWrite(r *http.Request, bucket, object string, hasAfterCreate bool) (owner pb.ServerAddress, cond *filer_pb.WriteCondition, ok bool) {
|
||||
if hasAfterCreate {
|
||||
return "", nil, false
|
||||
}
|
||||
cond, condOk := buildWriteCondition(r)
|
||||
if !condOk {
|
||||
return "", nil, false
|
||||
}
|
||||
owner, ok = s3a.routedObjectOwner(bucket, object)
|
||||
if !ok {
|
||||
return "", nil, false
|
||||
}
|
||||
return owner, cond, true
|
||||
}
|
||||
|
||||
// buildWriteCondition reduces the request's conditional headers to a single
|
||||
// WriteCondition primitive the filer can evaluate. It only handles the
|
||||
// unambiguous single-condition cases; anything else (header combinations,
|
||||
// time-based conditions, ETag lists, weak ETags) returns ok=false so the caller
|
||||
// keeps the existing gateway-side evaluation under the distributed lock.
|
||||
func buildWriteCondition(r *http.Request) (*filer_pb.WriteCondition, bool) {
|
||||
headers, errCode := parseConditionalHeaders(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
return nil, false
|
||||
}
|
||||
if !headers.isSet {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}, true
|
||||
}
|
||||
// Time-based conditions are rare on writes; let the lock path handle them.
|
||||
if !headers.ifModifiedSince.IsZero() || !headers.ifUnmodifiedSince.IsZero() {
|
||||
return nil, false
|
||||
}
|
||||
hasMatch := headers.ifMatch != ""
|
||||
hasNoneMatch := headers.ifNoneMatch != ""
|
||||
switch {
|
||||
case hasMatch && !hasNoneMatch:
|
||||
if headers.ifMatch == "*" {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, true
|
||||
}
|
||||
if etag, single := singleStrongETag(headers.ifMatch); single {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: etag}, true
|
||||
}
|
||||
return nil, false
|
||||
case hasNoneMatch && !hasMatch:
|
||||
if headers.ifNoneMatch == "*" {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}, true
|
||||
}
|
||||
if etag, single := singleStrongETag(headers.ifNoneMatch); single {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: etag}, true
|
||||
}
|
||||
return nil, false
|
||||
default:
|
||||
// Both If-Match and If-None-Match present — leave to the lock path.
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// singleStrongETag returns the normalized ETag when the header carries exactly
|
||||
// one strong ETag, and false for ETag lists or weak ("W/") ETags, which the
|
||||
// fast path does not replicate.
|
||||
func singleStrongETag(v string) (string, bool) {
|
||||
v = strings.TrimSpace(v)
|
||||
if strings.Contains(v, ",") {
|
||||
return "", false
|
||||
}
|
||||
if strings.HasPrefix(v, "W/") || strings.HasPrefix(v, "w/") {
|
||||
return "", false
|
||||
}
|
||||
return strings.Trim(v, `"`), true
|
||||
}
|
||||
|
||||
// mkFileRouted builds a file entry the way filer_pb.MkFile does, applies fn, and
|
||||
// routes the CreateEntry (with an optional precondition) to the given owner filer
|
||||
// so its local per-path lock serializes the write. Used by callers that build an
|
||||
// object via a modifier (e.g. multipart completion) but want the routed,
|
||||
// distributed-lock-free write path.
|
||||
func (s3a *S3ApiServer) mkFileRouted(owner pb.ServerAddress, dir, name string, chunks []*filer_pb.FileChunk, cond *filer_pb.WriteCondition, fn func(*filer_pb.Entry)) s3err.ErrorCode {
|
||||
now := time.Now().Unix()
|
||||
entry := &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
Crtime: now,
|
||||
FileMode: uint32(0770),
|
||||
Uid: filer_pb.OS_UID,
|
||||
Gid: filer_pb.OS_GID,
|
||||
},
|
||||
Chunks: chunks,
|
||||
}
|
||||
if fn != nil {
|
||||
fn(entry)
|
||||
}
|
||||
resp, err := s3a.createEntryOnFiler(owner, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: entry,
|
||||
Condition: cond,
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Errorf("mkFileRouted: %s/%s on %s: %v", dir, name, owner, err)
|
||||
return s3err.ErrInternalError
|
||||
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
return s3err.ErrPreconditionFailed
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
if code, ok := filerErrorCodeToS3Error(resp.ErrorCode); ok {
|
||||
return code
|
||||
}
|
||||
glog.Errorf("mkFileRouted: %s/%s unexpected code %v", dir, name, resp.ErrorCode)
|
||||
return s3err.ErrInternalError
|
||||
case resp.Error != "":
|
||||
glog.Errorf("mkFileRouted: %s/%s: %s", dir, name, resp.Error)
|
||||
return s3err.ErrInternalError
|
||||
default:
|
||||
return s3err.ErrNone
|
||||
}
|
||||
}
|
||||
|
||||
// createEntryOnFiler sends a CreateEntry directly to the given owner filer so
|
||||
// its local per-path lock serializes the write. The raw response is returned so
|
||||
// the caller can distinguish PRECONDITION_FAILED from other outcomes.
|
||||
func (s3a *S3ApiServer) createEntryOnFiler(owner pb.ServerAddress, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
var resp *filer_pb.CreateEntryResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.CreateEntry(context.Background(), req)
|
||||
return e
|
||||
})
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// filerErrorCodeToS3Error maps a routed response's machine-readable FilerError
|
||||
// to the same S3 error the lock path produces via filerErrorToS3Error, so the
|
||||
// fast path keeps identical semantics. ok is false for codes it does not map,
|
||||
// signalling the caller to fall back to the lock path for exact behavior.
|
||||
func filerErrorCodeToS3Error(code filer_pb.FilerError) (s3err.ErrorCode, bool) {
|
||||
switch code {
|
||||
case filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
return s3err.ErrPreconditionFailed, true
|
||||
case filer_pb.FilerError_ENTRY_NAME_TOO_LONG:
|
||||
return s3err.ErrKeyTooLongError, true
|
||||
case filer_pb.FilerError_PARENT_IS_FILE, filer_pb.FilerError_EXISTING_IS_FILE:
|
||||
return s3err.ErrExistingObjectIsFile, true
|
||||
case filer_pb.FilerError_EXISTING_IS_DIRECTORY:
|
||||
return s3err.ErrExistingObjectIsDirectory, true
|
||||
default:
|
||||
return s3err.ErrNone, false
|
||||
}
|
||||
}
|
||||
|
||||
// buildDeleteCondition reduces a DeleteObject's If-Match header to a primitive.
|
||||
// DeleteObject only honors If-Match (matching checkDeleteIfMatch), so other
|
||||
// conditional headers are ignored here as they are on the existing path.
|
||||
func buildDeleteCondition(r *http.Request) (*filer_pb.WriteCondition, bool) {
|
||||
ifMatch := strings.TrimSpace(r.Header.Get(s3_constants.IfMatch))
|
||||
switch {
|
||||
case ifMatch == "":
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}, true
|
||||
case ifMatch == "*":
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, true
|
||||
default:
|
||||
if etag, single := singleStrongETag(ifMatch); single {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: etag}, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// deleteEntryOnFiler sends a non-recursive DeleteEntry for the object directly
|
||||
// to its owner filer, which serializes it and evaluates the precondition under
|
||||
// the per-path lock. Flags mirror the unversioned delete path (doDeleteEntry).
|
||||
func (s3a *S3ApiServer) deleteEntryOnFiler(owner pb.ServerAddress, bucket, object string, cond *filer_pb.WriteCondition) (*filer_pb.DeleteEntryResponse, error) {
|
||||
dir, name := util.NewFullPath(s3a.bucketDir(bucket), object).DirAndName()
|
||||
var resp *filer_pb.DeleteEntryResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.DeleteEntry(context.Background(), &filer_pb.DeleteEntryRequest{
|
||||
Directory: dir,
|
||||
Name: name,
|
||||
IsDeleteData: true,
|
||||
IsRecursive: false,
|
||||
IgnoreRecursiveError: true,
|
||||
Condition: cond,
|
||||
})
|
||||
return e
|
||||
})
|
||||
return resp, err
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
func reqWith(headers map[string]string) *http.Request {
|
||||
r, _ := http.NewRequest(http.MethodPut, "/b/o", nil)
|
||||
for k, v := range headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestBuildWriteCondition(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
headers map[string]string
|
||||
wantOk bool
|
||||
want filer_pb.WriteCondition_Kind
|
||||
wantTag string
|
||||
}{
|
||||
{"none", nil, true, filer_pb.WriteCondition_NONE, ""},
|
||||
{"ifnonematch-star", map[string]string{s3_constants.IfNoneMatch: "*"}, true, filer_pb.WriteCondition_IF_NOT_EXISTS, ""},
|
||||
{"ifmatch-star", map[string]string{s3_constants.IfMatch: "*"}, true, filer_pb.WriteCondition_IF_EXISTS, ""},
|
||||
{"ifmatch-etag", map[string]string{s3_constants.IfMatch: `"abc"`}, true, filer_pb.WriteCondition_IF_ETAG_MATCH, "abc"},
|
||||
{"ifnonematch-etag", map[string]string{s3_constants.IfNoneMatch: `"abc"`}, true, filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, "abc"},
|
||||
// Cases that must fall back to the lock path:
|
||||
{"both", map[string]string{s3_constants.IfMatch: "*", s3_constants.IfNoneMatch: "*"}, false, 0, ""},
|
||||
{"etag-list", map[string]string{s3_constants.IfMatch: `"a","b"`}, false, 0, ""},
|
||||
{"weak-etag", map[string]string{s3_constants.IfMatch: `W/"abc"`}, false, 0, ""},
|
||||
{"time-based", map[string]string{s3_constants.IfUnmodifiedSince: "Wed, 21 Oct 2015 07:28:00 GMT"}, false, 0, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
cond, ok := buildWriteCondition(reqWith(tc.headers))
|
||||
if ok != tc.wantOk {
|
||||
t.Errorf("%s: ok=%v want %v", tc.name, ok, tc.wantOk)
|
||||
continue
|
||||
}
|
||||
if ok {
|
||||
if cond.Kind != tc.want {
|
||||
t.Errorf("%s: kind=%v want %v", tc.name, cond.Kind, tc.want)
|
||||
}
|
||||
if cond.Etag != tc.wantTag {
|
||||
t.Errorf("%s: etag=%q want %q", tc.name, cond.Etag, tc.wantTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDeleteCondition(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ifMatch string
|
||||
wantOk bool
|
||||
want filer_pb.WriteCondition_Kind
|
||||
wantTag string
|
||||
}{
|
||||
{"none", "", true, filer_pb.WriteCondition_NONE, ""},
|
||||
{"star", "*", true, filer_pb.WriteCondition_IF_EXISTS, ""},
|
||||
{"etag", `"abc"`, true, filer_pb.WriteCondition_IF_ETAG_MATCH, "abc"},
|
||||
{"list", `"a","b"`, false, 0, ""},
|
||||
{"weak", `W/"abc"`, false, 0, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
h := map[string]string{}
|
||||
if tc.ifMatch != "" {
|
||||
h[s3_constants.IfMatch] = tc.ifMatch
|
||||
}
|
||||
cond, ok := buildDeleteCondition(reqWith(h))
|
||||
if ok != tc.wantOk {
|
||||
t.Errorf("%s: ok=%v want %v", tc.name, ok, tc.wantOk)
|
||||
continue
|
||||
}
|
||||
if ok && (cond.Kind != tc.want || cond.Etag != tc.wantTag) {
|
||||
t.Errorf("%s: got kind=%v etag=%q want kind=%v etag=%q", tc.name, cond.Kind, cond.Etag, tc.want, tc.wantTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// errVersionedPreconditionFailed is returned by versioned finalize helpers whose
|
||||
// contract is (…, error) when the routed FinalizeVersionedWrite reports a failed
|
||||
// precondition, so callers can surface it as 412 rather than a generic 500.
|
||||
var errVersionedPreconditionFailed = errors.New("versioned write precondition failed")
|
||||
|
||||
// finalizeCodeToError adapts a routedVersionedFinalize result to an error: nil on
|
||||
// success, the precondition sentinel on 412, else a generic error.
|
||||
func finalizeCodeToError(code s3err.ErrorCode) error {
|
||||
switch code {
|
||||
case s3err.ErrNone:
|
||||
return nil
|
||||
case s3err.ErrPreconditionFailed:
|
||||
return errVersionedPreconditionFailed
|
||||
default:
|
||||
return fmt.Errorf("versioned finalize failed: code %v", code)
|
||||
}
|
||||
}
|
||||
|
||||
// objectWriteOwner returns the filer that owns all of an object's writes, or ""
|
||||
// when no ring view is available. It hashes the object key with the same prefix
|
||||
// the non-versioned path uses (routedObjectOwner), so normal, suspended, and
|
||||
// versioned writes to the same object all resolve to one owner and serialize on
|
||||
// the same lock — regardless of versioning state. The whole object subtree
|
||||
// (object, .versions dir, version files) belongs to this owner.
|
||||
func (s3a *S3ApiServer) objectWriteOwner(bucket, object string) pb.ServerAddress {
|
||||
if s3a.objectWriteLockClient == nil {
|
||||
return ""
|
||||
}
|
||||
// Object-lock (WORM) buckets keep ALL of their writes on the distributed
|
||||
// lock. Retention enforcement is a gateway-side check that the per-path-locked
|
||||
// filer ops don't perform, so routing only some of such a bucket's writes
|
||||
// would split serialization between the entry lock and the distributed lock
|
||||
// (they don't serialize against each other). Excluding the bucket entirely
|
||||
// keeps it internally consistent.
|
||||
if locked, err := s3a.isObjectLockEnabled(bucket); err != nil || locked {
|
||||
return ""
|
||||
}
|
||||
return s3a.objectWriteLockClient.PrimaryForKey("s3.object.write:" + s3a.toFilerPath(bucket, object))
|
||||
}
|
||||
|
||||
// versionedPointerExtended computes the Extended keys to set and to clear on the
|
||||
// .versions directory entry for a new latest version, mirroring
|
||||
// setCachedListMetadata (clear cached fields, then set id/filename + cached
|
||||
// size/mtime/etag/owner/delete-marker). The filer applies deletes before sets.
|
||||
func versionedPointerExtended(versionId, versionFileName string, versionEntry *filer_pb.Entry) (set map[string][]byte, del []string) {
|
||||
set = map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(versionId),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte(versionFileName),
|
||||
}
|
||||
if versionEntry.Attributes != nil {
|
||||
set[s3_constants.ExtLatestVersionSizeKey] = []byte(strconv.FormatUint(versionEntry.Attributes.FileSize, 10))
|
||||
set[s3_constants.ExtLatestVersionMtimeKey] = []byte(strconv.FormatInt(versionEntry.Attributes.Mtime, 10))
|
||||
}
|
||||
isDeleteMarker := []byte("false")
|
||||
if versionEntry.Extended != nil {
|
||||
if v, ok := versionEntry.Extended[s3_constants.ExtETagKey]; ok {
|
||||
set[s3_constants.ExtLatestVersionETagKey] = v
|
||||
}
|
||||
if v, ok := versionEntry.Extended[s3_constants.ExtAmzOwnerKey]; ok {
|
||||
set[s3_constants.ExtLatestVersionOwnerKey] = v
|
||||
}
|
||||
if v, ok := versionEntry.Extended[s3_constants.ExtDeleteMarkerKey]; ok {
|
||||
isDeleteMarker = v
|
||||
}
|
||||
}
|
||||
set[s3_constants.ExtLatestVersionIsDeleteMarker] = isDeleteMarker
|
||||
del = []string{
|
||||
s3_constants.ExtLatestVersionSizeKey,
|
||||
s3_constants.ExtLatestVersionMtimeKey,
|
||||
s3_constants.ExtLatestVersionETagKey,
|
||||
s3_constants.ExtLatestVersionOwnerKey,
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker,
|
||||
}
|
||||
return set, del
|
||||
}
|
||||
|
||||
// routedVersionedFinalize finalizes a versioned write by routing the precondition
|
||||
// check, the demote of the previous latest, and the pointer flip to the owner of
|
||||
// the object's .versions directory, where they run atomically under one local
|
||||
// lock. The caller (putToFiler with uniqueVersionPath) has already created the
|
||||
// version file and skips the object write lock and gateway precondition. A
|
||||
// transport/in-band error maps to InternalError (the client retries); there is
|
||||
// no silent non-atomic fallback.
|
||||
func (s3a *S3ApiServer) routedVersionedFinalize(owner pb.ServerAddress, bucket, object, versionId, versionFileName string, versionEntry *filer_pb.Entry, cond *filer_pb.WriteCondition, deletePath string) s3err.ErrorCode {
|
||||
set, del := versionedPointerExtended(versionId, versionFileName, versionEntry)
|
||||
req := &filer_pb.FinalizeVersionedWriteRequest{
|
||||
LockKey: s3a.toFilerPath(bucket, object),
|
||||
DeletePath: deletePath,
|
||||
VersionsDir: s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder),
|
||||
SetExtended: set,
|
||||
DeleteExtended: del,
|
||||
PriorLatestKey: s3_constants.ExtLatestVersionFileNameKey,
|
||||
NoncurrentSinceKey: s3_constants.ExtNoncurrentSinceNsKey,
|
||||
NoncurrentSinceNs: time.Now().UnixNano(),
|
||||
Condition: cond,
|
||||
LatestEtagKey: s3_constants.ExtLatestVersionETagKey,
|
||||
LatestDeleteMarkerKey: s3_constants.ExtLatestVersionIsDeleteMarker,
|
||||
}
|
||||
var resp *filer_pb.FinalizeVersionedWriteResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.FinalizeVersionedWrite(context.Background(), req)
|
||||
return e
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Errorf("routedVersionedFinalize: %s/%s on %s: %v", bucket, object, owner, err)
|
||||
return s3err.ErrInternalError
|
||||
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
return s3err.ErrPreconditionFailed
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
if code, ok := filerErrorCodeToS3Error(resp.ErrorCode); ok {
|
||||
return code
|
||||
}
|
||||
glog.Errorf("routedVersionedFinalize: %s/%s unexpected code %v", bucket, object, resp.ErrorCode)
|
||||
return s3err.ErrInternalError
|
||||
case resp.Error != "":
|
||||
glog.Errorf("routedVersionedFinalize: %s/%s: %s", bucket, object, resp.Error)
|
||||
return s3err.ErrInternalError
|
||||
default:
|
||||
return s3err.ErrNone
|
||||
}
|
||||
}
|
||||
|
||||
// versionedAfterCreate returns the putToFiler afterCreate hook for a versioned
|
||||
// write: the routed atomic finalize when the .versions owner is known and the
|
||||
// precondition reduces to a single primitive, otherwise the existing lock-based
|
||||
// updateLatestVersionInDirectory path. The bool reports whether the routed path
|
||||
// was selected, which the caller passes as putToFiler's uniqueVersionPath.
|
||||
func (s3a *S3ApiServer) versionedAfterCreate(r *http.Request, bucket, object, versionId, versionFileName string) (func(*filer_pb.Entry) s3err.ErrorCode, bool) {
|
||||
owner := s3a.objectWriteOwner(bucket, object)
|
||||
cond, condOk := buildWriteCondition(r)
|
||||
if owner != "" && condOk {
|
||||
return func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
|
||||
return s3a.routedVersionedFinalize(owner, bucket, object, versionId, versionFileName, versionEntry, cond, "")
|
||||
}, true
|
||||
}
|
||||
return func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateLatestVersionInDirectory(bucket, object, versionId, versionFileName, versionEntry); err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
return s3err.ErrNone
|
||||
}, false
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
s3_constants "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
@@ -191,7 +192,13 @@ type ObjectVersion struct {
|
||||
}
|
||||
|
||||
// createDeleteMarker creates a delete marker for versioned delete operations
|
||||
func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, error) {
|
||||
// createDeleteMarker writes a delete-marker version and makes it the latest.
|
||||
// When routedOwner is set, the latest-pointer update (and the optional cond) run
|
||||
// atomically via FinalizeVersionedWrite on that owner, off the distributed lock;
|
||||
// otherwise it uses the lock-based updateLatestVersionInDirectory. A failed
|
||||
// routed finalize rolls back the marker file and returns
|
||||
// errVersionedPreconditionFailed for a precondition miss.
|
||||
func (s3a *S3ApiServer) createDeleteMarker(bucket, object string, routedOwner pb.ServerAddress, cond *filer_pb.WriteCondition, deleteNullPath string) (string, error) {
|
||||
// Clean up the object path first
|
||||
cleanObject := strings.TrimPrefix(object, "/")
|
||||
|
||||
@@ -242,6 +249,19 @@ func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, error
|
||||
},
|
||||
Extended: deleteMarkerExtended,
|
||||
}
|
||||
if routedOwner != "" {
|
||||
// Routed: precondition + demote + pointer flip run atomically on the
|
||||
// .versions owner. Roll back the marker file if it does not succeed.
|
||||
if code := s3a.routedVersionedFinalize(routedOwner, bucket, cleanObject, versionId, versionFileName, deleteMarkerEntry, cond, deleteNullPath); code != s3err.ErrNone {
|
||||
if rbErr := s3a.rmObject(versionsDir, versionFileName, true, false); rbErr != nil {
|
||||
glog.Errorf("createDeleteMarker: rollback %s/%s: %v", versionsDir, versionFileName, rbErr)
|
||||
}
|
||||
return "", finalizeCodeToError(code)
|
||||
}
|
||||
glog.V(2).Infof("createDeleteMarker: routed delete marker %s for %s/%s", versionId, bucket, object)
|
||||
return versionId, nil
|
||||
}
|
||||
|
||||
err = s3a.updateLatestVersionInDirectory(bucket, cleanObject, versionId, versionFileName, deleteMarkerEntry)
|
||||
if err != nil {
|
||||
glog.Errorf("createDeleteMarker: failed to update latest version in directory: %v", err)
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
@@ -95,6 +96,11 @@ type S3ApiServer struct {
|
||||
stsHandlers *STSHandlers // STS HTTP handlers for AssumeRoleWithWebIdentity
|
||||
cipher bool // encrypt data on volume servers
|
||||
newObjectWriteLock func(bucket, object string) objectWriteLock
|
||||
// objectWriteLockClient holds the lock-ring view used to route an object's
|
||||
// metadata writes to its owner filer (route-by-key), so that owner's local
|
||||
// per-path lock serializes them without acquiring a distributed lock. Nil
|
||||
// when no filers are configured.
|
||||
objectWriteLockClient *cluster.LockClient
|
||||
// Shared ReaderCache used by the S3 GET streaming path. It lives for the
|
||||
// lifetime of the server so that concurrent and repeat reads share a
|
||||
// single in-flight download per chunk, and so that no per-request
|
||||
@@ -152,6 +158,8 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
// Uses the battle-tested vidMap with filer-based lookups
|
||||
// Supports multiple filer addresses with automatic failover for high availability
|
||||
var filerClient *wdclient.FilerClient
|
||||
var masterClient *wdclient.MasterClient
|
||||
var objectWriteLockClient *cluster.LockClient
|
||||
if len(option.Masters) > 0 {
|
||||
// Enable filer discovery via master
|
||||
masterMap := make(map[string]pb.ServerAddress)
|
||||
@@ -162,7 +170,22 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
if clientHost == "0.0.0.0" || clientHost == "" {
|
||||
clientHost = util.DetectedHostAddress()
|
||||
}
|
||||
masterClient := wdclient.NewMasterClient(option.GrpcDialOption, option.FilerGroup, cluster.S3Type, pb.ServerAddress(util.JoinHostPort(clientHost, option.GrpcPort)), "", "", *pb.NewServiceDiscoveryFromMap(masterMap))
|
||||
masterClient = wdclient.NewMasterClient(option.GrpcDialOption, option.FilerGroup, cluster.S3Type, pb.ServerAddress(util.JoinHostPort(clientHost, option.GrpcPort)), "", "", *pb.NewServiceDiscoveryFromMap(masterMap))
|
||||
// Build the object-write lock client and subscribe to the master's
|
||||
// lock-ring updates BEFORE starting the master loop, so the initial
|
||||
// LockRingUpdate sent on connect isn't dropped (the master only delivers
|
||||
// it once per connect). The masterClient already filters updates to this
|
||||
// server's filer group.
|
||||
if len(option.Filers) > 0 {
|
||||
objectWriteLockClient = cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
masterClient.SetOnLockRingUpdateFn(func(update *master_pb.LockRingUpdate) {
|
||||
servers := make([]pb.ServerAddress, 0, len(update.Servers))
|
||||
for _, s := range update.Servers {
|
||||
servers = append(servers, pb.ServerAddress(s))
|
||||
}
|
||||
objectWriteLockClient.SetRing(servers, update.Version)
|
||||
})
|
||||
}
|
||||
// Start the master client connection loop - required for GetMaster() to work
|
||||
go masterClient.KeepConnectedToMaster(context.Background())
|
||||
|
||||
@@ -263,7 +286,12 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
}
|
||||
|
||||
if len(option.Filers) > 0 {
|
||||
objectWriteLockClient := cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
// Reuse the lock client built in the masters block (already subscribed to
|
||||
// ring updates); create a plain one when no masters are configured.
|
||||
if objectWriteLockClient == nil {
|
||||
objectWriteLockClient = cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
}
|
||||
s3ApiServer.objectWriteLockClient = objectWriteLockClient
|
||||
s3ApiServer.newObjectWriteLock = func(bucket, object string) objectWriteLock {
|
||||
lockKey := fmt.Sprintf("s3.object.write:%s", s3ApiServer.toFilerPath(bucket, object))
|
||||
owner := fmt.Sprintf("s3api-%d", s3ApiServer.randomClientId)
|
||||
@@ -323,6 +351,13 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
// IAM config file. Without one, EnableIam is the implicit mini default
|
||||
// and we must keep the "no credentials = allow all" startup behavior so
|
||||
// `docker run seaweedfs` works out of the box (fixes #9557).
|
||||
//
|
||||
// SetIAMIntegration also flushes the policies already loaded from the
|
||||
// credential store into this manager's engine. The earlier config
|
||||
// loads (the synchronous one in NewIdentityAccessManagementWithStore
|
||||
// and the async goroutine) may have run before iamIntegration was set,
|
||||
// in which case their syncRuntimePoliciesToIAMManager call was a no-op
|
||||
// and identities relying on policy_names would get AccessDenied.
|
||||
iam.SetIAMIntegration(s3iam)
|
||||
if option.IamConfig != "" {
|
||||
iam.EnableAuthEnforcement()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
@@ -86,6 +87,33 @@ func TestGetAccessLogRemoteIP(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetAccessLogRequesterFromFallback reproduces the fallback audit path for
|
||||
// GET/HEAD/IAM operations: authentication records the requester on a request
|
||||
// copy the track() middleware never sees, yet the fallback audit entry (built
|
||||
// from the original request) must still report the authenticated user.
|
||||
func TestGetAccessLogRequesterFromFallback(t *testing.T) {
|
||||
// track() installs the holder before authentication runs.
|
||||
outer := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
|
||||
|
||||
// auth records the identity on a copy and hands that copy to the handler;
|
||||
// the copy itself is discarded once the handler returns.
|
||||
_ = outer.WithContext(s3_constants.SetIdentityNameInContext(outer.Context(), "admin"))
|
||||
|
||||
// The handler returned without logging, so track() builds the fallback entry
|
||||
// from the original request.
|
||||
log := GetAccessLog(outer, http.StatusOK, ErrNone)
|
||||
|
||||
assert.Equal(t, "admin", log.Requester, "fallback audit entry must report the authenticated requester")
|
||||
}
|
||||
|
||||
func TestGetAccessLogRequesterAnonymous(t *testing.T) {
|
||||
req := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
|
||||
|
||||
log := GetAccessLog(req, http.StatusOK, ErrNone)
|
||||
|
||||
assert.Empty(t, log.Requester, "anonymous request must not report a requester")
|
||||
}
|
||||
|
||||
func TestAuditTrackingFlag(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/bucket/object", nil)
|
||||
assert.False(t, AuditAlreadyLogged(req), "untracked request reports not logged")
|
||||
|
||||
@@ -25,6 +25,10 @@ func track(f http.HandlerFunc, action string) http.HandlerFunc {
|
||||
// PostLog directly mark it; we emit a fallback entry afterward for
|
||||
// handlers (e.g. successful GET/HEAD object) that don't.
|
||||
r = s3err.EnsureAuditTracking(r)
|
||||
// Attach a mutable identity holder before authentication so the fallback
|
||||
// entry can report the requester even though auth records it on a
|
||||
// request copy this middleware never sees.
|
||||
r = s3_constants.EnsureIdentityHolder(r)
|
||||
start := time.Now()
|
||||
f(recorder, r)
|
||||
if recorder.Status == http.StatusForbidden {
|
||||
|
||||
@@ -7,15 +7,16 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
@@ -186,6 +187,32 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
newEntry.TtlSec = 0
|
||||
}
|
||||
|
||||
// Serialize concurrent mutations to the same path on this filer so the
|
||||
// read (existence/condition) and the write are atomic. Callers route a
|
||||
// key's writes to this owner filer, making this local lock sufficient.
|
||||
fullpath := util.NewFullPath(req.Directory, req.Entry.Name)
|
||||
pathLock := fs.entryLockTable.AcquireLock("CreateEntry", fullpath, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(fullpath, pathLock)
|
||||
|
||||
// Evaluate the optional precondition against the current entry while the
|
||||
// path lock is held, so the check and the write are atomic on this filer.
|
||||
if req.Condition != nil && req.Condition.Kind != filer_pb.WriteCondition_NONE {
|
||||
current, findErr := fs.filer.FindEntry(ctx, fullpath)
|
||||
if findErr != nil && findErr != filer_pb.ErrNotFound {
|
||||
return &filer_pb.CreateEntryResponse{}, fmt.Errorf("CreateEntry condition check %s: %w", fullpath, findErr)
|
||||
}
|
||||
if findErr == filer_pb.ErrNotFound {
|
||||
current = nil
|
||||
}
|
||||
if !writeConditionSatisfied(req.Condition, current) {
|
||||
glog.V(3).InfofCtx(ctx, "CreateEntry %s: precondition %v failed", fullpath, req.Condition.Kind)
|
||||
return &filer_pb.CreateEntryResponse{
|
||||
Error: "precondition failed",
|
||||
ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
||||
createErr := fs.filer.CreateEntry(ctx, newEntry, req.OExcl, req.IsFromOtherCluster, req.Signatures, req.SkipCheckParentDirectory, so.MaxFileNameLength)
|
||||
|
||||
@@ -212,6 +239,170 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
return
|
||||
}
|
||||
|
||||
// writeConditionSatisfied reports whether the precondition holds against the
|
||||
// current entry (nil if absent). The caller reduces request semantics to one
|
||||
// primitive; each kind is a single comparison evaluated under the path lock.
|
||||
func writeConditionSatisfied(cond *filer_pb.WriteCondition, current *filer.Entry) bool {
|
||||
exists := current != nil
|
||||
switch cond.Kind {
|
||||
case filer_pb.WriteCondition_IF_NOT_EXISTS:
|
||||
return !exists
|
||||
case filer_pb.WriteCondition_IF_EXISTS:
|
||||
return exists
|
||||
case filer_pb.WriteCondition_IF_ETAG_MATCH:
|
||||
return exists && storedEntryETag(current) == normalizeETag(cond.Etag)
|
||||
case filer_pb.WriteCondition_IF_ETAG_NOT_MATCH:
|
||||
return !exists || storedEntryETag(current) != normalizeETag(cond.Etag)
|
||||
case filer_pb.WriteCondition_IF_UNMODIFIED_SINCE:
|
||||
return !exists || current.Attr.Mtime.Unix() <= cond.UnixTime
|
||||
case filer_pb.WriteCondition_IF_MODIFIED_SINCE:
|
||||
return !exists || current.Attr.Mtime.Unix() > cond.UnixTime
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// storedEntryETag mirrors the S3 gateway's ETag precedence (the stored
|
||||
// Seaweed ETag extended attribute, then the chunk/Md5 fallback) so conditional
|
||||
// comparisons match what the gateway computes, without coupling the filer to
|
||||
// S3 request handling.
|
||||
func storedEntryETag(entry *filer.Entry) string {
|
||||
if v, ok := entry.Extended[s3_constants.ExtETagKey]; ok && len(v) > 0 {
|
||||
return normalizeETag(string(v))
|
||||
}
|
||||
return normalizeETag(filer.ETagEntry(entry))
|
||||
}
|
||||
|
||||
func normalizeETag(etag string) string {
|
||||
return strings.Trim(etag, `"`)
|
||||
}
|
||||
|
||||
// versionedConditionSatisfied evaluates a precondition against the current
|
||||
// latest version, derived from the .versions directory entry's cached metadata
|
||||
// (whether a latest exists and isn't a delete marker, and its ETag). It mirrors
|
||||
// writeConditionSatisfied but reads the cached pointer fields instead of a plain
|
||||
// object entry.
|
||||
func versionedConditionSatisfied(req *filer_pb.FinalizeVersionedWriteRequest, versionsEntry *filer.Entry) bool {
|
||||
exists := false
|
||||
etag := ""
|
||||
if versionsEntry != nil && versionsEntry.Extended != nil {
|
||||
latestFile := string(versionsEntry.Extended[req.PriorLatestKey])
|
||||
isDeleteMarker := req.LatestDeleteMarkerKey != "" && string(versionsEntry.Extended[req.LatestDeleteMarkerKey]) == "true"
|
||||
exists = latestFile != "" && !isDeleteMarker
|
||||
if req.LatestEtagKey != "" {
|
||||
etag = normalizeETag(string(versionsEntry.Extended[req.LatestEtagKey]))
|
||||
}
|
||||
}
|
||||
want := normalizeETag(req.Condition.Etag)
|
||||
switch req.Condition.Kind {
|
||||
case filer_pb.WriteCondition_IF_NOT_EXISTS:
|
||||
return !exists
|
||||
case filer_pb.WriteCondition_IF_EXISTS:
|
||||
return exists
|
||||
case filer_pb.WriteCondition_IF_ETAG_MATCH:
|
||||
return exists && etag == want
|
||||
case filer_pb.WriteCondition_IF_ETAG_NOT_MATCH:
|
||||
return !exists || etag != want
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// FinalizeVersionedWrite performs an S3 versioned-write finalize atomically on
|
||||
// the owner of the object's .versions directory: it creates the new version
|
||||
// file, stamps the previous latest as noncurrent (before the pointer flip so the
|
||||
// lifecycle router observes it), then merges the latest-pointer / cached
|
||||
// metadata into the .versions directory entry. A single exclusive lock on the
|
||||
// .versions directory serializes the whole sequence against concurrent versioned
|
||||
// writes to the same object, replacing the distributed lock. Key names come from
|
||||
// the caller so the filer carries no S3 versioning semantics.
|
||||
func (fs *FilerServer) FinalizeVersionedWrite(ctx context.Context, req *filer_pb.FinalizeVersionedWriteRequest) (*filer_pb.FinalizeVersionedWriteResponse, error) {
|
||||
resp := &filer_pb.FinalizeVersionedWriteResponse{}
|
||||
versionsDir := util.FullPath(req.VersionsDir)
|
||||
|
||||
// Serialize on the object key — the same lock all of this object's writes
|
||||
// (normal, suspended, versioned) share — not the .versions directory, so a
|
||||
// versioned write and a non-versioned write to the same object can't run on
|
||||
// different owners during a versioning-state change. Fall back to the
|
||||
// .versions directory for older callers that don't set lock_key.
|
||||
lockKey := util.FullPath(req.LockKey)
|
||||
if lockKey == "" {
|
||||
lockKey = versionsDir
|
||||
}
|
||||
lock := fs.entryLockTable.AcquireLock("FinalizeVersionedWrite", lockKey, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(lockKey, lock)
|
||||
|
||||
// The caller already created the new version file under this .versions
|
||||
// directory, so it exists; read the directory entry that holds the pointer.
|
||||
versionsEntry, err := fs.filer.FindEntry(ctx, versionsDir)
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// 1. Evaluate the optional precondition against the current latest version
|
||||
// (the .versions directory's cached pointer metadata) before the flip, so the
|
||||
// check and the flip are atomic under this lock.
|
||||
if req.Condition != nil && req.Condition.Kind != filer_pb.WriteCondition_NONE {
|
||||
if !versionedConditionSatisfied(req, versionsEntry) {
|
||||
glog.V(3).InfofCtx(ctx, "FinalizeVersionedWrite %s: precondition %v failed", versionsDir, req.Condition.Kind)
|
||||
resp.Error = "precondition failed"
|
||||
resp.ErrorCode = filer_pb.FilerError_PRECONDITION_FAILED
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: delete an entry under the same lock first (suspended delete
|
||||
// removes the "null" version at the main object path before adding the
|
||||
// marker). Not-found is fine (idempotent).
|
||||
if req.DeletePath != "" {
|
||||
if derr := fs.filer.DeleteEntryMetaAndData(ctx, util.FullPath(req.DeletePath), false, false, true, req.IsFromOtherCluster, req.Signatures, 0); derr != nil && derr != filer_pb.ErrNotFound {
|
||||
resp.Error = derr.Error()
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Stamp the previously-latest version as noncurrent BEFORE the pointer
|
||||
// flip (so the lifecycle router observes it). Best-effort.
|
||||
newFileName := string(req.SetExtended[req.PriorLatestKey])
|
||||
if req.NoncurrentSinceNs > 0 && req.PriorLatestKey != "" && req.NoncurrentSinceKey != "" {
|
||||
prior := string(versionsEntry.Extended[req.PriorLatestKey])
|
||||
if prior != "" && prior != newFileName {
|
||||
demotedPath := util.NewFullPath(req.VersionsDir, prior)
|
||||
if demoted, derr := fs.filer.FindEntry(ctx, demotedPath); derr == nil {
|
||||
if demoted.Extended == nil {
|
||||
demoted.Extended = make(map[string][]byte)
|
||||
}
|
||||
demoted.Extended[req.NoncurrentSinceKey] = []byte(strconv.FormatInt(req.NoncurrentSinceNs, 10))
|
||||
if uerr := fs.filer.UpdateEntry(ctx, demoted, demoted); uerr != nil {
|
||||
glog.Warningf("FinalizeVersionedWrite: demote stamp %s: %v", demotedPath, uerr)
|
||||
}
|
||||
} else {
|
||||
glog.V(2).InfofCtx(ctx, "FinalizeVersionedWrite: demote target %s not found: %v", demotedPath, derr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Flip the latest pointer: merge the requested Extended keys into the
|
||||
// .versions directory entry and write it back (emits the meta-log event the
|
||||
// lifecycle router consumes).
|
||||
if versionsEntry.Extended == nil {
|
||||
versionsEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
for _, k := range req.DeleteExtended {
|
||||
delete(versionsEntry.Extended, k)
|
||||
}
|
||||
for k, v := range req.SetExtended {
|
||||
versionsEntry.Extended[k] = v
|
||||
}
|
||||
if err := fs.filer.CreateEntry(ctx, versionsEntry, false, req.IsFromOtherCluster, req.Signatures, true, fs.filer.MaxFilenameLength); err != nil {
|
||||
resp.Error = err.Error()
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
|
||||
|
||||
glog.V(4).InfofCtx(ctx, "UpdateEntry %v", req)
|
||||
@@ -328,9 +519,11 @@ func (fs *FilerServer) AppendToEntry(ctx context.Context, req *filer_pb.AppendTo
|
||||
glog.V(4).InfofCtx(ctx, "AppendToEntry %v", req)
|
||||
fullpath := util.NewFullPath(req.Directory, req.EntryName)
|
||||
|
||||
lockClient := cluster.NewLockClient(fs.grpcDialOption, fs.option.Host)
|
||||
lock := lockClient.NewShortLivedLock(string(fullpath), string(fs.option.Host))
|
||||
defer lock.StopShortLivedLock()
|
||||
// Serialize the read-modify-write against concurrent mutations to the same
|
||||
// path on this filer. The append must route to this entry's owner filer for
|
||||
// this local lock to be authoritative.
|
||||
pathLock := fs.entryLockTable.AcquireLock("AppendToEntry", fullpath, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(fullpath, pathLock)
|
||||
|
||||
var offset int64 = 0
|
||||
entry, err := fs.filer.FindEntry(ctx, fullpath)
|
||||
@@ -375,9 +568,35 @@ func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntr
|
||||
|
||||
glog.V(4).InfofCtx(ctx, "DeleteEntry %v", req)
|
||||
|
||||
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
||||
err = fs.filer.DeleteEntryMetaAndData(ctx, util.JoinPath(req.Directory, req.Name), req.IsRecursive, req.IgnoreRecursiveError, req.IsDeleteData, req.IsFromOtherCluster, req.Signatures, req.IfNotModifiedAfter)
|
||||
fullpath := util.JoinPath(req.Directory, req.Name)
|
||||
resp = &filer_pb.DeleteEntryResponse{}
|
||||
|
||||
// A single-entry delete serializes against concurrent mutations to the same
|
||||
// path so a conditional delete's check and the removal are atomic. Recursive
|
||||
// deletes span many paths and keep the prior unlocked behavior.
|
||||
if !req.IsRecursive {
|
||||
pathLock := fs.entryLockTable.AcquireLock("DeleteEntry", fullpath, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(fullpath, pathLock)
|
||||
|
||||
if req.Condition != nil && req.Condition.Kind != filer_pb.WriteCondition_NONE {
|
||||
current, findErr := fs.filer.FindEntry(ctx, fullpath)
|
||||
if findErr != nil && findErr != filer_pb.ErrNotFound {
|
||||
return &filer_pb.DeleteEntryResponse{}, fmt.Errorf("DeleteEntry condition check %s: %w", fullpath, findErr)
|
||||
}
|
||||
if findErr == filer_pb.ErrNotFound {
|
||||
current = nil
|
||||
}
|
||||
if !writeConditionSatisfied(req.Condition, current) {
|
||||
glog.V(3).InfofCtx(ctx, "DeleteEntry %s: precondition %v failed", fullpath, req.Condition.Kind)
|
||||
resp.Error = "precondition failed"
|
||||
resp.ErrorCode = filer_pb.FilerError_PRECONDITION_FAILED
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
||||
err = fs.filer.DeleteEntryMetaAndData(ctx, fullpath, req.IsRecursive, req.IgnoreRecursiveError, req.IsDeleteData, req.IsFromOtherCluster, req.Signatures, req.IfNotModifiedAfter)
|
||||
if err != nil && err != filer_pb.ErrNotFound {
|
||||
resp.Error = err.Error()
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func entryWithETag(etag string, mtime time.Time) *filer.Entry {
|
||||
return &filer.Entry{
|
||||
FullPath: "/test/obj",
|
||||
Attr: filer.Attr{Mtime: mtime},
|
||||
Extended: map[string][]byte{s3_constants.ExtETagKey: []byte(etag)},
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteConditionSatisfied(t *testing.T) {
|
||||
base := time.Unix(1700000000, 0)
|
||||
present := entryWithETag("abc", base)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
cond *filer_pb.WriteCondition
|
||||
cur *filer.Entry
|
||||
want bool
|
||||
}{
|
||||
{"none-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}, nil, true},
|
||||
{"ifnotexists-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}, nil, true},
|
||||
{"ifnotexists-present", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}, present, false},
|
||||
{"ifexists-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, nil, false},
|
||||
{"ifexists-present", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, present, true},
|
||||
{"etagmatch-hit", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: `"abc"`}, present, true},
|
||||
{"etagmatch-miss", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: `"zzz"`}, present, false},
|
||||
{"etagmatch-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: `"abc"`}, nil, false},
|
||||
{"etagnotmatch-hit", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: `"abc"`}, present, false},
|
||||
{"etagnotmatch-miss", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: `"zzz"`}, present, true},
|
||||
{"etagnotmatch-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: `"abc"`}, nil, true},
|
||||
{"unmodsince-ok", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_UNMODIFIED_SINCE, UnixTime: base.Unix()}, present, true},
|
||||
{"unmodsince-fail", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_UNMODIFIED_SINCE, UnixTime: base.Unix() - 1}, present, false},
|
||||
{"modsince-ok", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_MODIFIED_SINCE, UnixTime: base.Unix() - 1}, present, true},
|
||||
{"modsince-fail", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_MODIFIED_SINCE, UnixTime: base.Unix()}, present, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := writeConditionSatisfied(tc.cond, tc.cur); got != tc.want {
|
||||
t.Errorf("%s: got %v want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// storedEntryETag prefers the stored Seaweed ETag attribute and falls back to
|
||||
// the Md5-derived ETag, matching the S3 gateway.
|
||||
func TestStoredEntryETag(t *testing.T) {
|
||||
withExt := entryWithETag("explicit", time.Unix(0, 0))
|
||||
if got := storedEntryETag(withExt); got != "explicit" {
|
||||
t.Errorf("extended etag: got %q", got)
|
||||
}
|
||||
md5Only := &filer.Entry{Attr: filer.Attr{Md5: []byte{0xab, 0xcd}}}
|
||||
if got := storedEntryETag(md5Only); got != "abcd" {
|
||||
t.Errorf("md5 fallback: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The CreateEntry handler enforces the precondition atomically: a matching
|
||||
// If-Match overwrites, a non-matching one returns PRECONDITION_FAILED.
|
||||
func TestCreateEntryConditionEnforced(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
store.entries["/test/obj"] = &filer.Entry{
|
||||
FullPath: "/test/obj",
|
||||
Attr: filer.Attr{Inode: 1, Mtime: time.Unix(1700000000, 0)},
|
||||
Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("abc")},
|
||||
}
|
||||
f := newRenameTestFiler(store)
|
||||
f.DirBucketsPath = "/buckets"
|
||||
fs := &FilerServer{filer: f, option: &FilerOption{}, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
|
||||
req := func(etag string) *filer_pb.CreateEntryRequest {
|
||||
return &filer_pb.CreateEntryRequest{
|
||||
Directory: "/test",
|
||||
SkipCheckParentDirectory: true,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "obj",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1700000001, FileMode: 0644, Inode: 2},
|
||||
},
|
||||
Condition: &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: etag},
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := fs.CreateEntry(context.Background(), req(`"zzz"`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.ErrorCode != filer_pb.FilerError_PRECONDITION_FAILED {
|
||||
t.Fatalf("mismatched etag: want PRECONDITION_FAILED, got %v (%q)", resp.ErrorCode, resp.Error)
|
||||
}
|
||||
|
||||
resp, err = fs.CreateEntry(context.Background(), req(`"abc"`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
t.Fatalf("matching etag should overwrite, got error %q", resp.Error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Concurrent OExcl creates for the same path must yield exactly one winner. The
|
||||
// filer's CreateEntry is a FindEntry-then-Insert; without the per-path lock both
|
||||
// racers observe "not found" and both insert. The exclusive entry lock makes the
|
||||
// check-then-act atomic so the losers see ErrEntryAlreadyExists.
|
||||
func TestCreateEntryOExclSerialized(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
store.findDelay = 5 * time.Millisecond
|
||||
f := newRenameTestFiler(store)
|
||||
f.DirBucketsPath = "/buckets"
|
||||
|
||||
fs := &FilerServer{
|
||||
filer: f,
|
||||
option: &FilerOption{},
|
||||
entryLockTable: util.NewLockTable[util.FullPath](),
|
||||
}
|
||||
|
||||
const racers = 8
|
||||
var success int32
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i := 0; i < racers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
resp, err := fs.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
||||
Directory: "/test",
|
||||
OExcl: true,
|
||||
SkipCheckParentDirectory: true,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "obj",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000, FileMode: 0644, Inode: 1},
|
||||
},
|
||||
})
|
||||
if err == nil && resp.Error == "" {
|
||||
atomic.AddInt32(&success, 1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
if success != 1 {
|
||||
t.Fatalf("expected exactly 1 OExcl winner, got %d", success)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ type renameTestStore struct {
|
||||
findCalls map[string]int
|
||||
commitErr error
|
||||
deleteErr error
|
||||
findDelay time.Duration // optional: widen check-then-act windows in tests
|
||||
}
|
||||
|
||||
func newRenameTestStore() *renameTestStore {
|
||||
@@ -69,6 +70,9 @@ func (s *renameTestStore) UpdateEntry(_ context.Context, entry *filer.Entry) err
|
||||
}
|
||||
|
||||
func (s *renameTestStore) FindEntry(_ context.Context, p util.FullPath) (*filer.Entry, error) {
|
||||
if s.findDelay > 0 {
|
||||
time.Sleep(s.findDelay)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.findCalls[string(p)]++
|
||||
|
||||
@@ -22,6 +22,12 @@ import (
|
||||
const (
|
||||
// MaxUnsyncedEvents send empty notification with timestamp when certain amount of events have been filtered
|
||||
MaxUnsyncedEvents = 1e3
|
||||
|
||||
// idleHeartbeatInterval bounds how often a caught-up subscriber that asked
|
||||
// for idle heartbeats is reminded that the source is alive and has nothing
|
||||
// newer. It keeps freshness signals such as filer.sync's sync_offset metric
|
||||
// from looking stuck during read-only periods on the source.
|
||||
idleHeartbeatInterval = 5 * time.Second
|
||||
)
|
||||
|
||||
// metadataStreamSender is satisfied by both gRPC stream types and pipelinedSender.
|
||||
@@ -186,7 +192,16 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
|
||||
|
||||
eachEventNotificationFn := fs.eachEventNotificationFn(req, sender, clientName)
|
||||
|
||||
eachLogEntryFn := eachLogEntryFn(eachEventNotificationFn)
|
||||
// lastSeenTsNs tracks how far the subscriber has read so idle heartbeats are
|
||||
// only emitted once it is caught up to the buffer head. It is read and
|
||||
// written from this single goroutine, so no synchronization is needed.
|
||||
var lastSeenTsNs int64
|
||||
var lastHeartbeatNs int64
|
||||
baseEachLogEntryFn := eachLogEntryFn(eachEventNotificationFn)
|
||||
eachLogEntryFn := func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
lastSeenTsNs = logEntry.TsNs
|
||||
return baseEachLogEntryFn(logEntry)
|
||||
}
|
||||
|
||||
var processedTsNs int64
|
||||
var readPersistedLogErr error
|
||||
@@ -248,7 +263,11 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
|
||||
return false
|
||||
default:
|
||||
}
|
||||
return fs.hasClient(req.ClientId, req.ClientEpoch)
|
||||
if !fs.hasClient(req.ClientId, req.ClientEpoch) {
|
||||
return false
|
||||
}
|
||||
lastHeartbeatNs = fs.maybeSendIdleHeartbeat(req, sender, fs.filer.MetaAggregator.MetaLogBuffer, lastReadTime.Time.UnixNano(), lastSeenTsNs, lastHeartbeatNs)
|
||||
return true
|
||||
}, eachLogEntryFn)
|
||||
if readInMemoryLogErr != nil {
|
||||
if errors.Is(readInMemoryLogErr, log_buffer.ResumeFromDiskError) {
|
||||
@@ -314,7 +333,16 @@ func (fs *FilerServer) SubscribeLocalMetadata(req *filer_pb.SubscribeMetadataReq
|
||||
|
||||
eachEventNotificationFn := fs.eachEventNotificationFn(req, sender, clientName)
|
||||
|
||||
eachLogEntryFn := eachLogEntryFn(eachEventNotificationFn)
|
||||
// lastSeenTsNs tracks how far the subscriber has read so idle heartbeats are
|
||||
// only emitted once it is caught up to the buffer head. It is read and
|
||||
// written from this single goroutine, so no synchronization is needed.
|
||||
var lastSeenTsNs int64
|
||||
var lastHeartbeatNs int64
|
||||
baseEachLogEntryFn := eachLogEntryFn(eachEventNotificationFn)
|
||||
eachLogEntryFn := func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
lastSeenTsNs = logEntry.TsNs
|
||||
return baseEachLogEntryFn(logEntry)
|
||||
}
|
||||
|
||||
var processedTsNs int64
|
||||
var readPersistedLogErr error
|
||||
@@ -400,7 +428,11 @@ func (fs *FilerServer) SubscribeLocalMetadata(req *filer_pb.SubscribeMetadataReq
|
||||
return false
|
||||
default:
|
||||
}
|
||||
return fs.hasClient(req.ClientId, req.ClientEpoch)
|
||||
if !fs.hasClient(req.ClientId, req.ClientEpoch) {
|
||||
return false
|
||||
}
|
||||
lastHeartbeatNs = fs.maybeSendIdleHeartbeat(req, sender, fs.filer.LocalMetaLogBuffer, lastReadTime.Time.UnixNano(), lastSeenTsNs, lastHeartbeatNs)
|
||||
return true
|
||||
}, eachLogEntryFn)
|
||||
if readInMemoryLogErr != nil {
|
||||
if readInMemoryLogErr == log_buffer.ResumeFromDiskError {
|
||||
@@ -474,6 +506,45 @@ func eachLogEntryFn(eachEventNotificationFn func(dirPath string, eventNotificati
|
||||
}
|
||||
}
|
||||
|
||||
// maybeSendIdleHeartbeat emits an empty response carrying the current time when
|
||||
// the subscriber has consumed everything up to the buffer head. The client uses
|
||||
// it to advance freshness signals (e.g. filer.sync's sync_offset) without moving
|
||||
// its resume checkpoint, so a restart still re-reads from the last real event.
|
||||
//
|
||||
// The catch-up floor is the max of two read-progress markers:
|
||||
// - readPositionTsNs: how far the read cursor has advanced. It starts at
|
||||
// SinceNs and also covers metadata-chunks mode, where persisted entries are
|
||||
// replayed as log file refs rather than through eachLogEntryFn.
|
||||
// - lastSeenTsNs: the timestamp of the most recent entry streamed in this
|
||||
// call. It advances live while reading the in-memory backlog, before the
|
||||
// read cursor returned by LoopProcessLogData has been updated.
|
||||
//
|
||||
// While the buffer head is past that floor the subscriber is still behind (e.g.
|
||||
// replaying a backlog) and no heartbeat is sent. Returns the (possibly advanced)
|
||||
// lastHeartbeatNs.
|
||||
func (fs *FilerServer) maybeSendIdleHeartbeat(req *filer_pb.SubscribeMetadataRequest, sender metadataStreamSender, logBuffer *log_buffer.LogBuffer, readPositionTsNs, lastSeenTsNs, lastHeartbeatNs int64) int64 {
|
||||
if !req.ClientSupportsIdleHeartbeat {
|
||||
return lastHeartbeatNs
|
||||
}
|
||||
floorTsNs := lastSeenTsNs
|
||||
if readPositionTsNs > floorTsNs {
|
||||
floorTsNs = readPositionTsNs
|
||||
}
|
||||
if logBuffer.LastTsNs.Load() > floorTsNs {
|
||||
// the buffer holds data the subscriber has not reached yet
|
||||
return lastHeartbeatNs
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
if now-lastHeartbeatNs < int64(idleHeartbeatInterval) {
|
||||
return lastHeartbeatNs
|
||||
}
|
||||
if err := sender.Send(&filer_pb.SubscribeMetadataResponse{TsNs: now}); err != nil {
|
||||
glog.V(0).Infof("=> idle heartbeat to %s: %v", req.ClientName, err)
|
||||
return lastHeartbeatNs
|
||||
}
|
||||
return now
|
||||
}
|
||||
|
||||
// sendLogFileRefs collects persisted log file chunk references and sends them
|
||||
// to the client so it can read the data directly from volume servers.
|
||||
// This does zero volume server I/O — it only lists filer store directory entries.
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
// slowStream simulates a gRPC stream with configurable per-Send latency.
|
||||
@@ -32,9 +33,13 @@ func (s *slowStream) Send(msg *filer_pb.SubscribeMetadataResponse) error {
|
||||
|
||||
type collectingStream struct {
|
||||
messages []*filer_pb.SubscribeMetadataResponse
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *collectingStream) Send(msg *filer_pb.SubscribeMetadataResponse) error {
|
||||
if s.err != nil {
|
||||
return s.err
|
||||
}
|
||||
s.messages = append(s.messages, msg)
|
||||
return nil
|
||||
}
|
||||
@@ -409,3 +414,85 @@ func TestPipelinedSingleVsParallelStreams(t *testing.T) {
|
||||
t.Logf("Speedup: %.1fx (%d parallel pipelined streams vs 1)", parallelRate/singleRate, numDirs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeSendIdleHeartbeat(t *testing.T) {
|
||||
lb := log_buffer.NewLogBuffer("test", time.Minute, nil, nil, nil)
|
||||
defer lb.ShutdownLogBuffer()
|
||||
|
||||
fs := &FilerServer{}
|
||||
const recentEvent = int64(1_000_000)
|
||||
|
||||
t.Run("not opted in", func(t *testing.T) {
|
||||
lb.LastTsNs.Store(recentEvent)
|
||||
s := &collectingStream{}
|
||||
req := &filer_pb.SubscribeMetadataRequest{ClientSupportsIdleHeartbeat: false}
|
||||
got := fs.maybeSendIdleHeartbeat(req, s, lb, recentEvent, recentEvent, 0)
|
||||
if got != 0 || len(s.messages) != 0 {
|
||||
t.Fatalf("expected no heartbeat, got lastHeartbeat=%d msgs=%d", got, len(s.messages))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("behind buffer head", func(t *testing.T) {
|
||||
lb.LastTsNs.Store(recentEvent)
|
||||
s := &collectingStream{}
|
||||
req := &filer_pb.SubscribeMetadataRequest{ClientSupportsIdleHeartbeat: true}
|
||||
// startTs and lastSeen both below the buffer head: still replaying.
|
||||
got := fs.maybeSendIdleHeartbeat(req, s, lb, 0, recentEvent-1, 0)
|
||||
if got != 0 || len(s.messages) != 0 {
|
||||
t.Fatalf("expected no heartbeat while behind, got lastHeartbeat=%d msgs=%d", got, len(s.messages))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("caught up via lastSeen", func(t *testing.T) {
|
||||
lb.LastTsNs.Store(recentEvent)
|
||||
s := &collectingStream{}
|
||||
req := &filer_pb.SubscribeMetadataRequest{ClientSupportsIdleHeartbeat: true}
|
||||
got := fs.maybeSendIdleHeartbeat(req, s, lb, 0, recentEvent, 0)
|
||||
if len(s.messages) != 1 {
|
||||
t.Fatalf("expected one heartbeat, got %d", len(s.messages))
|
||||
}
|
||||
hb := s.messages[0]
|
||||
if hb.EventNotification != nil || len(hb.Events) != 0 || hb.TsNs <= 0 {
|
||||
t.Fatalf("heartbeat should be an empty timestamped response, got %+v", hb)
|
||||
}
|
||||
if got != hb.TsNs {
|
||||
t.Fatalf("expected returned lastHeartbeat %d to equal sent ts %d", got, hb.TsNs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("caught up via read position floor", func(t *testing.T) {
|
||||
// The read cursor has advanced past the buffer head while lastSeen stayed
|
||||
// 0. This is the idle-source case (subscribed from "now", read nothing) and
|
||||
// also metadata-chunks mode, where persisted entries replay as log file
|
||||
// refs and never reach eachLogEntryFn.
|
||||
lb.LastTsNs.Store(recentEvent)
|
||||
s := &collectingStream{}
|
||||
req := &filer_pb.SubscribeMetadataRequest{ClientSupportsIdleHeartbeat: true}
|
||||
readPosition := time.Now().UnixNano()
|
||||
got := fs.maybeSendIdleHeartbeat(req, s, lb, readPosition, 0, 0)
|
||||
if len(s.messages) != 1 || got <= 0 {
|
||||
t.Fatalf("expected heartbeat for caught-up subscriber, got msgs=%d lastHeartbeat=%d", len(s.messages), got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("throttled within interval", func(t *testing.T) {
|
||||
lb.LastTsNs.Store(recentEvent)
|
||||
s := &collectingStream{}
|
||||
req := &filer_pb.SubscribeMetadataRequest{ClientSupportsIdleHeartbeat: true}
|
||||
justSent := time.Now().UnixNano()
|
||||
got := fs.maybeSendIdleHeartbeat(req, s, lb, 0, recentEvent, justSent)
|
||||
if got != justSent || len(s.messages) != 0 {
|
||||
t.Fatalf("expected throttled (no send), got lastHeartbeat=%d msgs=%d", got, len(s.messages))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("send error keeps prior heartbeat time", func(t *testing.T) {
|
||||
lb.LastTsNs.Store(recentEvent)
|
||||
s := &collectingStream{err: fmt.Errorf("broken stream")}
|
||||
req := &filer_pb.SubscribeMetadataRequest{ClientSupportsIdleHeartbeat: true}
|
||||
got := fs.maybeSendIdleHeartbeat(req, s, lb, 0, recentEvent, 0)
|
||||
if got != 0 {
|
||||
t.Fatalf("expected lastHeartbeat unchanged on send error, got %d", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func newFinalizeTestServer(store *renameTestStore) *FilerServer {
|
||||
f := newRenameTestFiler(store)
|
||||
f.DirBucketsPath = "/buckets"
|
||||
return &FilerServer{filer: f, option: &FilerOption{}, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
}
|
||||
|
||||
func seedVersions(store *renameTestStore, latestFile, latestEtag string) {
|
||||
store.entries["/buckets/b/obj/.versions"] = &filer.Entry{
|
||||
FullPath: "/buckets/b/obj/.versions",
|
||||
Attr: filer.Attr{Inode: 10, Mode: 0755 | (1 << 31)},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte(latestFile),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(latestEtag),
|
||||
},
|
||||
}
|
||||
store.entries["/buckets/b/obj/.versions/"+latestFile] = &filer.Entry{
|
||||
FullPath: util.FullPath("/buckets/b/obj/.versions/" + latestFile),
|
||||
Attr: filer.Attr{Inode: 11},
|
||||
Extended: map[string][]byte{},
|
||||
}
|
||||
}
|
||||
|
||||
func finalizeReq(cond *filer_pb.WriteCondition) *filer_pb.FinalizeVersionedWriteRequest {
|
||||
return &filer_pb.FinalizeVersionedWriteRequest{
|
||||
VersionsDir: "/buckets/b/obj/.versions",
|
||||
SetExtended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v2.ver"),
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("vid2"),
|
||||
},
|
||||
DeleteExtended: []string{s3_constants.ExtLatestVersionETagKey},
|
||||
PriorLatestKey: s3_constants.ExtLatestVersionFileNameKey,
|
||||
NoncurrentSinceKey: s3_constants.ExtNoncurrentSinceNsKey,
|
||||
NoncurrentSinceNs: 77777,
|
||||
Condition: cond,
|
||||
LatestEtagKey: s3_constants.ExtLatestVersionETagKey,
|
||||
LatestDeleteMarkerKey: s3_constants.ExtLatestVersionIsDeleteMarker,
|
||||
}
|
||||
}
|
||||
|
||||
// The finalize flips the latest pointer and stamps the previously-latest version
|
||||
// noncurrent, atomically under the .versions lock.
|
||||
func TestFinalizeVersionedWriteFlipAndDemote(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
seedVersions(store, "v1.ver", "etag1")
|
||||
fs := newFinalizeTestServer(store)
|
||||
|
||||
resp, err := fs.FinalizeVersionedWrite(context.Background(), finalizeReq(&filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
t.Fatalf("unexpected resp error: %s", resp.Error)
|
||||
}
|
||||
|
||||
if got := string(store.entries["/buckets/b/obj/.versions"].Extended[s3_constants.ExtLatestVersionFileNameKey]); got != "v2.ver" {
|
||||
t.Errorf("latest pointer not flipped: %q", got)
|
||||
}
|
||||
if got := string(store.entries["/buckets/b/obj/.versions/v1.ver"].Extended[s3_constants.ExtNoncurrentSinceNsKey]); got != "77777" {
|
||||
t.Errorf("previous latest not demoted: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A failing precondition is reported and nothing is flipped or demoted.
|
||||
func TestFinalizeVersionedWritePreconditionFailed(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
seedVersions(store, "v1.ver", "etag1")
|
||||
fs := newFinalizeTestServer(store)
|
||||
|
||||
// IF_NOT_EXISTS against an existing latest must fail.
|
||||
resp, err := fs.FinalizeVersionedWrite(context.Background(), finalizeReq(&filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.ErrorCode != filer_pb.FilerError_PRECONDITION_FAILED {
|
||||
t.Fatalf("want PRECONDITION_FAILED, got %v (%q)", resp.ErrorCode, resp.Error)
|
||||
}
|
||||
if got := string(store.entries["/buckets/b/obj/.versions"].Extended[s3_constants.ExtLatestVersionFileNameKey]); got != "v1.ver" {
|
||||
t.Errorf("pointer should be unchanged on precondition failure, got %q", got)
|
||||
}
|
||||
if _, stamped := store.entries["/buckets/b/obj/.versions/v1.ver"].Extended[s3_constants.ExtNoncurrentSinceNsKey]; stamped {
|
||||
t.Errorf("previous latest should not be demoted on precondition failure")
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,13 @@ type FilerServer struct {
|
||||
// mountPeerRegistry backs the MountRegister / MountList RPCs for peer
|
||||
// chunk sharing (tier 1). Always populated.
|
||||
mountPeerRegistry *filer.MountPeerRegistry
|
||||
|
||||
// entryLockTable serializes mutations to the same entry path on this filer.
|
||||
// It is the local serialization point for read-modify-write operations
|
||||
// (conditional create, append) once writers for a key are routed to this
|
||||
// node, replacing the distributed lock for that purpose. Idle keys are
|
||||
// evicted automatically, so the table stays bounded.
|
||||
entryLockTable *util.LockTable[util.FullPath]
|
||||
}
|
||||
|
||||
func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption) (fs *FilerServer, err error) {
|
||||
@@ -162,6 +169,7 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption)
|
||||
inFlightDataLimitCond: sync.NewCond(new(sync.Mutex)),
|
||||
recentCopyRequests: make(map[string]recentCopyRequest),
|
||||
CredentialManager: option.CredentialManager,
|
||||
entryLockTable: util.NewLockTable[util.FullPath](),
|
||||
}
|
||||
fs.mountPeerRegistry = filer.NewMountPeerRegistry()
|
||||
go fs.runMountPeerRegistrySweeper()
|
||||
|
||||
@@ -393,7 +393,13 @@ func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServ
|
||||
}
|
||||
|
||||
func (ms *MasterServer) initialLockRingUpdate(clientType string, filerGroup string) *master_pb.KeepConnectedResponse {
|
||||
if clientType != cluster.FilerType || ms.LockRingManager == nil {
|
||||
if ms.LockRingManager == nil {
|
||||
return nil
|
||||
}
|
||||
// Filers are ring members; S3 gateways are lock clients that need the same
|
||||
// view to dial a key's primary directly. Both get the initial snapshot;
|
||||
// later membership changes already broadcast to every connected client.
|
||||
if clientType != cluster.FilerType && clientType != cluster.S3Type {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -170,10 +170,17 @@ func (ms *MasterServer) isKnownPingTarget(ctx context.Context, target string, ta
|
||||
case cluster.FilerType, cluster.BrokerType, cluster.S3Type:
|
||||
return ms.Cluster.IsKnownNode(targetType, addr)
|
||||
case cluster.VolumeServerType:
|
||||
if ms.Topo == nil {
|
||||
return false
|
||||
if ms.Topo != nil && ms.Topo.LookupDataNodeByAddress(addr) != nil {
|
||||
return true
|
||||
}
|
||||
return ms.Topo.LookupDataNodeByAddress(addr) != nil
|
||||
// Only the leader receives volume-server heartbeats, so a follower's
|
||||
// topology is empty. Fall back to the volume-server set the master
|
||||
// learns over its own MasterClient subscription to the leader, the
|
||||
// same source the filer gate trusts.
|
||||
if ms.MasterClient != nil {
|
||||
return ms.MasterClient.HasVolumeServer(addr)
|
||||
}
|
||||
return false
|
||||
case cluster.MasterType:
|
||||
if ms.option != nil && ms.option.Master.Equals(addr) {
|
||||
return true
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/sequence"
|
||||
"github.com/seaweedfs/seaweedfs/weed/topology"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
func TestMasterIsKnownPingTarget(t *testing.T) {
|
||||
@@ -62,6 +64,36 @@ func TestMasterIsKnownPingTarget(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// On a follower master the topology is empty because only the leader receives
|
||||
// volume-server heartbeats. The gate must then fall back to the volume-server
|
||||
// set learned over the MasterClient subscription instead of rejecting every
|
||||
// volume-server target. The positive MasterClient.HasVolumeServer lookup is
|
||||
// covered by wdclient.TestHasVolumeServer; here we lock in that an empty
|
||||
// topology no longer short-circuits to false and that the fallback is
|
||||
// nil-safe.
|
||||
func TestMasterIsKnownPingTargetFollowerEmptyTopology(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
vs := "10.0.0.10:8080.18080"
|
||||
|
||||
// No topology and no MasterClient: nothing to consult, so reject.
|
||||
bare := &MasterServer{option: &MasterOption{Master: pb.ServerAddress("10.0.0.1:9333")}}
|
||||
if bare.isKnownPingTarget(ctx, vs, cluster.VolumeServerType) {
|
||||
t.Fatalf("volume server must be unknown without topology or MasterClient")
|
||||
}
|
||||
|
||||
// Empty topology plus a MasterClient that has not learned this volume
|
||||
// server yet: still reject, but exercise the MasterClient fallback path.
|
||||
mc := wdclient.NewMasterClient(grpc.EmptyDialOption{}, "", cluster.MasterType, "", "", "", pb.ServerDiscovery{})
|
||||
follower := &MasterServer{
|
||||
option: &MasterOption{Master: pb.ServerAddress("10.0.0.1:9333")},
|
||||
Topo: topology.NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false),
|
||||
MasterClient: mc,
|
||||
}
|
||||
if follower.isKnownPingTarget(ctx, vs, cluster.VolumeServerType) {
|
||||
t.Fatalf("volume server must be unknown until the MasterClient learns it")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeServerIsKnownPingTarget(t *testing.T) {
|
||||
seed := pb.ServerAddress("10.0.0.1:9333")
|
||||
vs := &VolumeServer{
|
||||
|
||||
@@ -327,7 +327,13 @@ func (sp *ClusterStatusPrinter) printClusterInfo() {
|
||||
for _, ri := range dci.RackInfos {
|
||||
for _, dni := range ri.DataNodeInfos {
|
||||
nodes++
|
||||
disks += len(dni.DiskInfos)
|
||||
// The master keys DiskInfos by disk type, so multiple
|
||||
// same-type physical disks on one node collapse into a single
|
||||
// entry. Count physical disks via SplitByPhysicalDisk so a node
|
||||
// with N disks of one type reports N, not 1.
|
||||
for _, di := range dni.DiskInfos {
|
||||
disks += len(di.SplitByPhysicalDisk())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,65 @@ func TestPrintClusterInfo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrintClusterInfo_multiDiskPerNode covers a node whose several physical
|
||||
// disks of the same type collapse into a single DiskInfo on the wire (keyed by
|
||||
// disk type), so counting len(DiskInfos) under-reports the physical disk count.
|
||||
// Three nodes with six disks each must report 18 disks, not 3.
|
||||
func TestPrintClusterInfo_multiDiskPerNode(t *testing.T) {
|
||||
makeNode := func(id string) *master_pb.DataNodeInfo {
|
||||
var ecShardInfos []*master_pb.VolumeEcShardInformationMessage
|
||||
// One EC volume per physical disk, each carrying its own DiskId 0..5.
|
||||
for diskId := uint32(0); diskId < 6; diskId++ {
|
||||
ecShardInfos = append(ecShardInfos, &master_pb.VolumeEcShardInformationMessage{
|
||||
Id: diskId + 1,
|
||||
DiskId: diskId,
|
||||
EcIndexBits: 1, // a single shard present
|
||||
})
|
||||
}
|
||||
return &master_pb.DataNodeInfo{
|
||||
Id: id,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {
|
||||
Type: "",
|
||||
MaxVolumeCount: 60,
|
||||
EcShardInfos: ecShardInfos,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "multi_disk_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
makeNode("node1"), makeNode("node2"), makeNode("node3"),
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
sp := &ClusterStatusPrinter{
|
||||
writer: &buf,
|
||||
humanize: true,
|
||||
topology: topo,
|
||||
}
|
||||
sp.printClusterInfo()
|
||||
got := buf.String()
|
||||
want := `cluster:
|
||||
id: multi_disk_topo
|
||||
status: unlocked
|
||||
nodes: 3
|
||||
topology: 1 DC, 18 disks on 1 rack
|
||||
|
||||
`
|
||||
if got != want {
|
||||
t.Errorf("multi-disk cluster info:\ngot:\n%s\nwant:\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintVolumeInfo(t *testing.T) {
|
||||
testCases := []struct {
|
||||
topology *master_pb.TopologyInfo
|
||||
|
||||
+180
-905
File diff suppressed because it is too large.
Load diff
@@ -1,377 +0,0 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func TestPickRackForShardType_AntiAffinityRacks(t *testing.T) {
|
||||
// Setup topology with 3 racks, each with 1 node, enough free slots
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
buildRackWithEcShards("rack0", "node0:8080", 100, nil),
|
||||
buildRackWithEcShards("rack1", "node1:8080", 100, nil),
|
||||
buildRackWithEcShards("rack2", "node2:8080", 100, nil),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
racks := ecb.racks()
|
||||
rackToShardCount := make(map[string]int)
|
||||
shardsPerRack := make(map[string][]erasure_coding.ShardId)
|
||||
maxPerRack := 2
|
||||
|
||||
// Case 1: Avoid rack0
|
||||
antiAffinityRacks := map[string]bool{"rack0": true}
|
||||
|
||||
// Try multiple times to ensure randomness doesn't accidentally pass
|
||||
for i := 0; i < 20; i++ {
|
||||
picked, err := ecb.pickRackForShardType(racks, shardsPerRack, maxPerRack, rackToShardCount, antiAffinityRacks)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if picked == "rack0" {
|
||||
t.Errorf("picked avoided rack rack0")
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2: Fallback - avoid all racks
|
||||
avoidAll := map[string]bool{"rack0": true, "rack1": true, "rack2": true}
|
||||
picked, err := ecb.pickRackForShardType(racks, shardsPerRack, maxPerRack, rackToShardCount, avoidAll)
|
||||
if err != nil {
|
||||
t.Fatalf("fallback failed: %v", err)
|
||||
}
|
||||
if picked == "" {
|
||||
t.Errorf("expected some rack to be picked in fallback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPickRackForShardType_EdgeCases(t *testing.T) {
|
||||
t.Run("NoFreeSlots", func(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
buildRackWithEcShards("rack0", "node0:8080", 0, nil), // maxVolumes=0
|
||||
buildRackWithEcShards("rack1", "node1:8080", 0, nil),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
racks := ecb.racks()
|
||||
_, err := ecb.pickRackForShardType(racks, make(map[string][]erasure_coding.ShardId), 2, make(map[string]int), nil)
|
||||
if err == nil {
|
||||
t.Error("expected error when no free slots, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("AllRacksAtMaxCapacity", func(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
buildRackWithEcShards("rack0", "node0:8080", 100, nil),
|
||||
buildRackWithEcShards("rack1", "node1:8080", 100, nil),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
racks := ecb.racks()
|
||||
shardsPerRack := map[string][]erasure_coding.ShardId{
|
||||
"rack0": {0, 1}, // 2 shards
|
||||
"rack1": {2, 3}, // 2 shards
|
||||
}
|
||||
maxPerRack := 2
|
||||
|
||||
_, err := ecb.pickRackForShardType(racks, shardsPerRack, maxPerRack, make(map[string]int), nil)
|
||||
if err == nil {
|
||||
t.Error("expected error when all racks at max capacity, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ReplicaPlacementLimit", func(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
buildRackWithEcShards("rack0", "node0:8080", 100, nil),
|
||||
buildRackWithEcShards("rack1", "node1:8080", 100, nil),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("012") // DiffRackCount = 1
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
replicaPlacement: rp,
|
||||
}
|
||||
|
||||
racks := ecb.racks()
|
||||
rackToShardCount := map[string]int{
|
||||
"rack0": 1, // At limit
|
||||
"rack1": 0,
|
||||
}
|
||||
|
||||
picked, err := ecb.pickRackForShardType(racks, make(map[string][]erasure_coding.ShardId), 5, rackToShardCount, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if picked != "rack1" {
|
||||
t.Errorf("expected rack1 (not at limit), got %v", picked)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PreferFewerShards", func(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
buildRackWithEcShards("rack0", "node0:8080", 100, nil),
|
||||
buildRackWithEcShards("rack1", "node1:8080", 100, nil),
|
||||
buildRackWithEcShards("rack2", "node2:8080", 100, nil),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
racks := ecb.racks()
|
||||
shardsPerRack := map[string][]erasure_coding.ShardId{
|
||||
"rack0": {0, 1}, // 2 shards
|
||||
"rack1": {2}, // 1 shard
|
||||
"rack2": {}, // 0 shards
|
||||
}
|
||||
|
||||
// Should pick rack2 (fewest shards)
|
||||
picked, err := ecb.pickRackForShardType(racks, shardsPerRack, 5, make(map[string]int), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if picked != "rack2" {
|
||||
t.Errorf("expected rack2 (fewest shards), got %v", picked)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPickNodeForShardType_AntiAffinityNodes(t *testing.T) {
|
||||
// Setup topology with 1 rack, 3 nodes
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
{
|
||||
Id: "rack0",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
buildDataNode("node0:8080", 100),
|
||||
buildDataNode("node1:8080", 100),
|
||||
buildDataNode("node2:8080", 100),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
nodeToShardCount := make(map[string]int)
|
||||
shardsPerNode := make(map[string][]erasure_coding.ShardId)
|
||||
maxPerNode := 2
|
||||
|
||||
// Case 1: Avoid node0
|
||||
antiAffinityNodes := map[string]bool{"node0:8080": true}
|
||||
|
||||
for i := 0; i < 20; i++ {
|
||||
picked, err := ecb.pickNodeForShardType(ecNodes, shardsPerNode, maxPerNode, nodeToShardCount, antiAffinityNodes)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if picked.info.Id == "node0:8080" {
|
||||
t.Errorf("picked avoided node node0")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPickNodeForShardType_EdgeCases(t *testing.T) {
|
||||
t.Run("NoFreeSlots", func(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
{
|
||||
Id: "rack0",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
buildDataNode("node0:8080", 0), // No capacity
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
_, err := ecb.pickNodeForShardType(ecNodes, make(map[string][]erasure_coding.ShardId), 2, make(map[string]int), nil)
|
||||
if err == nil {
|
||||
t.Error("expected error when no free slots, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ReplicaPlacementSameRackLimit", func(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "test_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
{
|
||||
Id: "rack0",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
buildDataNode("node0:8080", 100),
|
||||
buildDataNode("node1:8080", 100),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ecNodes, _ := collectEcVolumeServersByDc(topo, "", types.HardDriveType)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("021") // SameRackCount = 1
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: ecNodes,
|
||||
diskType: types.HardDriveType,
|
||||
replicaPlacement: rp,
|
||||
}
|
||||
|
||||
nodeToShardCount := map[string]int{
|
||||
"node0:8080": 3, // Exceeds SameRackCount + 1
|
||||
"node1:8080": 0,
|
||||
}
|
||||
|
||||
picked, err := ecb.pickNodeForShardType(ecNodes, make(map[string][]erasure_coding.ShardId), 5, nodeToShardCount, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if picked.info.Id != "node1:8080" {
|
||||
t.Errorf("expected node1 (not at limit), got %v", picked.info.Id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestShardsByType(t *testing.T) {
|
||||
vid := needle.VolumeId(123)
|
||||
|
||||
// Create mock nodes with shards
|
||||
nodes := []*EcNode{
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
string(types.HardDriveType): {
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
|
||||
{
|
||||
Id: uint32(vid),
|
||||
EcIndexBits: uint32((1 << 0) | (1 << 1) | (1 << 10) | (1 << 11)), // data: 0,1 parity: 10,11
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
rack: "rack1",
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("Standard10Plus4", func(t *testing.T) {
|
||||
dataPerRack, parityPerRack := shardsByTypePerRack(vid, nodes, types.HardDriveType, 10)
|
||||
|
||||
if len(dataPerRack["rack1"]) != 2 {
|
||||
t.Errorf("expected 2 data shards, got %d", len(dataPerRack["rack1"]))
|
||||
}
|
||||
if len(parityPerRack["rack1"]) != 2 {
|
||||
t.Errorf("expected 2 parity shards, got %d", len(parityPerRack["rack1"]))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("NodeGrouping", func(t *testing.T) {
|
||||
dataPerNode, parityPerNode := shardsByTypePerNode(vid, nodes, types.HardDriveType, 10)
|
||||
|
||||
if len(dataPerNode["node1"]) != 2 {
|
||||
t.Errorf("expected 2 data shards on node1, got %d", len(dataPerNode["node1"]))
|
||||
}
|
||||
if len(parityPerNode["node1"]) != 2 {
|
||||
t.Errorf("expected 2 parity shards on node1, got %d", len(parityPerNode["node1"]))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func buildDataNode(nodeId string, maxVolumes int64) *master_pb.DataNodeInfo {
|
||||
return &master_pb.DataNodeInfo{
|
||||
Id: nodeId,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
string(types.HardDriveType): {
|
||||
Type: string(types.HardDriveType),
|
||||
MaxVolumeCount: maxVolumes,
|
||||
VolumeCount: 0,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -405,9 +405,19 @@ func collectEcNodeShardsInfo(topoInfo *master_pb.TopologyInfo, vid needle.Volume
|
||||
res := make(map[pb.ServerAddress]*erasure_coding.ShardsInfo)
|
||||
eachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
if diskInfo, found := dn.DiskInfos[string(diskType)]; found {
|
||||
// A node may report several EcShardInfos for one volume — one per
|
||||
// physical disk holding shards of it (multi-disk nodes). Union them
|
||||
// rather than overwriting, or only the last disk's shards survive and
|
||||
// the node looks like it is missing shards it actually has.
|
||||
for _, v := range diskInfo.EcShardInfos {
|
||||
if v.Id == uint32(vid) {
|
||||
res[pb.NewServerAddressFromDataNode(dn)] = erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(v)
|
||||
addr := pb.NewServerAddressFromDataNode(dn)
|
||||
si := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(v)
|
||||
if existing, ok := res[addr]; ok {
|
||||
existing.Add(si)
|
||||
} else {
|
||||
res[addr] = si
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_replica"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -295,7 +296,7 @@ func doEcEncode(commandEnv *CommandEnv, writer io.Writer, volumeIdToCollection m
|
||||
collection := volumeIdToCollection[vid]
|
||||
|
||||
// Sync missing entries between replicas, then select the best one
|
||||
bestLoc, selectErr := syncAndSelectBestReplica(commandEnv.option.GrpcDialOption, vid, collection, filteredLocations[vid], "", writer)
|
||||
bestLoc, selectErr := volume_replica.SyncAndSelectBestReplica(commandEnv.option.GrpcDialOption, vid, collection, filteredLocations[vid], "", writer)
|
||||
if selectErr != nil {
|
||||
return fmt.Errorf("failed to sync and select replica for volume %d: %v", vid, selectErr)
|
||||
}
|
||||
@@ -340,36 +341,58 @@ func doEcEncode(commandEnv *CommandEnv, writer io.Writer, volumeIdToCollection m
|
||||
}
|
||||
|
||||
func verifyEcShardsBeforeDelete(commandEnv *CommandEnv, volumeIds []needle.VolumeId, diskType types.DiskType) error {
|
||||
topoInfo, _, err := collectTopologyInfo(commandEnv, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch topology for shard verification: %w", err)
|
||||
}
|
||||
// Shard relocations from the preceding EC balance reach the master via
|
||||
// volume-server heartbeats, so freshly distributed shards may not all be
|
||||
// visible in the master topology immediately. Poll a few times before
|
||||
// concluding the shard set is incomplete, so a heartbeat-propagation lag is
|
||||
// not mistaken for missing data (which would abort the encode). Genuine loss
|
||||
// still fails after the retries are exhausted.
|
||||
const maxAttempts = 10
|
||||
const retryInterval = 2 * time.Second
|
||||
|
||||
for _, vid := range volumeIds {
|
||||
nodeShards := collectEcNodeShardsInfo(topoInfo, vid, diskType)
|
||||
|
||||
var union erasure_coding.ShardBits
|
||||
for _, info := range nodeShards {
|
||||
union = erasure_coding.ShardBits(uint32(union) | info.Bitmap())
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < maxAttempts; attempt++ {
|
||||
topoInfo, _, err := collectTopologyInfo(commandEnv, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch topology for shard verification: %w", err)
|
||||
}
|
||||
|
||||
totalShards := erasure_coding.TotalShardsCount
|
||||
if err := erasure_coding.RequireFullShardSet(uint32(vid), union, totalShards); err != nil {
|
||||
summary := make([]string, 0, len(nodeShards))
|
||||
for node, info := range nodeShards {
|
||||
summary = append(summary, fmt.Sprintf("%s=%s", node, info.String()))
|
||||
lastErr = nil
|
||||
for _, vid := range volumeIds {
|
||||
nodeShards := collectEcNodeShardsInfo(topoInfo, vid, diskType)
|
||||
|
||||
var union erasure_coding.ShardBits
|
||||
for _, info := range nodeShards {
|
||||
union = erasure_coding.ShardBits(uint32(union) | info.Bitmap())
|
||||
}
|
||||
sort.Strings(summary)
|
||||
glog.Errorf("EC shard verification failed for volume %d on diskType %q: %v; observed: %v",
|
||||
vid, diskType.ReadableString(), err, summary)
|
||||
return fmt.Errorf("volume %d: %w (observed: %v)", vid, err, summary)
|
||||
|
||||
totalShards := erasure_coding.TotalShardsCount
|
||||
if err := erasure_coding.RequireFullShardSet(uint32(vid), union, totalShards); err != nil {
|
||||
summary := make([]string, 0, len(nodeShards))
|
||||
for node, info := range nodeShards {
|
||||
summary = append(summary, fmt.Sprintf("%s=%s", node, info.String()))
|
||||
}
|
||||
sort.Strings(summary)
|
||||
lastErr = fmt.Errorf("volume %d: %w (observed: %v)", vid, err, summary)
|
||||
break
|
||||
}
|
||||
|
||||
glog.V(0).Infof("EC shard verification ok for volume %d on diskType %q: %d/%d shards present across %d nodes",
|
||||
vid, diskType.ReadableString(), union.Count(), totalShards, len(nodeShards))
|
||||
}
|
||||
|
||||
glog.V(0).Infof("EC shard verification ok for volume %d on diskType %q: %d/%d shards present across %d nodes",
|
||||
vid, diskType.ReadableString(), union.Count(), totalShards, len(nodeShards))
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
if attempt < maxAttempts-1 {
|
||||
glog.V(0).Infof("EC shard verification incomplete (attempt %d/%d), waiting for shard locations to propagate: %v",
|
||||
attempt+1, maxAttempts, lastErr)
|
||||
time.Sleep(retryInterval)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
glog.Errorf("EC shard verification failed after %d attempts: %v", maxAttempts, lastErr)
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// doDeleteVolumesWithLocations deletes volumes using pre-collected location information
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestCommandEcBalanceSmall(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balance([]string{"c1"})
|
||||
}
|
||||
|
||||
func TestCommandEcBalanceNothingToMove(t *testing.T) {
|
||||
@@ -36,7 +36,7 @@ func TestCommandEcBalanceNothingToMove(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balance([]string{"c1"})
|
||||
}
|
||||
|
||||
func TestCommandEcBalanceAddNewServers(t *testing.T) {
|
||||
@@ -55,7 +55,7 @@ func TestCommandEcBalanceAddNewServers(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balance([]string{"c1"})
|
||||
}
|
||||
|
||||
func TestCommandEcBalanceAddNewRacks(t *testing.T) {
|
||||
@@ -74,7 +74,7 @@ func TestCommandEcBalanceAddNewRacks(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balance([]string{"c1"})
|
||||
}
|
||||
|
||||
func TestCommandEcBalanceVolumeEvenButRackUneven(t *testing.T) {
|
||||
@@ -118,8 +118,7 @@ func TestCommandEcBalanceVolumeEvenButRackUneven(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balanceEcRacks()
|
||||
ecb.balance([]string{"c1"})
|
||||
}
|
||||
|
||||
func newEcNode(dc string, rack string, dataNodeId string, freeEcSlot int) *EcNode {
|
||||
@@ -158,7 +157,7 @@ func TestCommandEcBalanceEvenDataAndParityDistribution(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balance([]string{"c1"})
|
||||
|
||||
// After balancing (dry-run), verify the PLANNED distribution by checking what moves were proposed
|
||||
// The ecb.ecNodes state is updated during dry-run to track planned moves
|
||||
@@ -262,7 +261,7 @@ func TestCommandEcBalanceMultipleVolumesEvenDistribution(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balance([]string{"c1"})
|
||||
|
||||
// Check both volumes
|
||||
for _, vid := range []needle.VolumeId{1, 2} {
|
||||
@@ -316,8 +315,7 @@ func TestCommandEcBalanceAllNodesShareAllVolumes(t *testing.T) {
|
||||
diskType: types.HardDriveType,
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("c1")
|
||||
ecb.balanceEcRacks()
|
||||
ecb.balance([]string{"c1"})
|
||||
|
||||
// Count total shards per node after balancing
|
||||
for _, node := range ecb.ecNodes {
|
||||
@@ -342,7 +340,11 @@ func TestCommandEcBalanceIssue8793Topology(t *testing.T) {
|
||||
// Simulate 22 EC volumes across 14 nodes (each volume has 14 shards, 1 per node).
|
||||
// Give nodes 0-3 an extra volume each (vol 23-26, all 14 shards) to create imbalance.
|
||||
// Before balancing: nodes 0-3 have 22+14=36 shards each, nodes 4-13 have 22 shards each.
|
||||
// Total = 4*36 + 10*22 = 144+220 = 364. Average = ceil(364/14) = 26.
|
||||
// Total = 4*36 + 10*22 = 144+220 = 364. Capacities are heterogeneous (max 80 vs
|
||||
// 33), so the utilization-based global phase balances by fullness, not count:
|
||||
// 364 shards over 9*80+5*33=885 slots is ~41% full, so large nodes settle near
|
||||
// 33 shards and small nodes near 14 (all ~41% full) rather than ~26 each, which
|
||||
// would drive the small nodes to ~79%.
|
||||
|
||||
type nodeSpec struct {
|
||||
id string
|
||||
@@ -396,11 +398,19 @@ func TestCommandEcBalanceIssue8793Topology(t *testing.T) {
|
||||
t.Logf("BEFORE node %s (max %d): %d shards", node.info.Id, node.freeEcSlot+count, count)
|
||||
}
|
||||
|
||||
ecb.balanceEcVolumes("cldata")
|
||||
ecb.balanceEcRacks()
|
||||
ecb.balance([]string{"cldata"})
|
||||
|
||||
// Verify even FULLNESS (shards/capacity), not even count: with heterogeneous
|
||||
// capacities the utilization-based global phase fills nodes proportionally, so
|
||||
// large nodes hold more shards than small ones while every node ends near the
|
||||
// overall fullness. (An even-count result would over-fill the small nodes.)
|
||||
capacityByID := make(map[string]int, len(nodes))
|
||||
for _, ns := range nodes {
|
||||
capacityByID[ns.id] = ns.maxSlot
|
||||
}
|
||||
|
||||
// Verify: no node should exceed the average
|
||||
totalShards := 0
|
||||
totalCapacity := 0
|
||||
shardCounts := make(map[string]int)
|
||||
for _, node := range ecb.ecNodes {
|
||||
count := 0
|
||||
@@ -411,14 +421,22 @@ func TestCommandEcBalanceIssue8793Topology(t *testing.T) {
|
||||
}
|
||||
shardCounts[node.info.Id] = count
|
||||
totalShards += count
|
||||
totalCapacity += capacityByID[node.info.Id]
|
||||
}
|
||||
avg := ceilDivide(totalShards, len(ecNodes))
|
||||
overallFullness := float64(totalShards) / float64(totalCapacity)
|
||||
|
||||
// Tolerance well below the gap a count-even result would show (small nodes
|
||||
// would sit ~38 points above overall), but above integer-rounding skew.
|
||||
const tolerance = 0.05
|
||||
for _, node := range ecb.ecNodes {
|
||||
count := shardCounts[node.info.Id]
|
||||
t.Logf("AFTER node %s: %d shards (avg %d)", node.info.Id, count, avg)
|
||||
if count > avg {
|
||||
t.Errorf("node %s has %d shards, expected at most %d (avg)", node.info.Id, count, avg)
|
||||
capacity := capacityByID[node.info.Id]
|
||||
fullness := float64(count) / float64(capacity)
|
||||
t.Logf("AFTER node %s: %d/%d shards (%.0f%% full, overall %.0f%%)",
|
||||
node.info.Id, count, capacity, fullness*100, overallFullness*100)
|
||||
if diff := fullness - overallFullness; diff > tolerance || diff < -tolerance {
|
||||
t.Errorf("node %s fullness %.1f%% deviates from overall %.1f%% by more than %.0f points",
|
||||
node.info.Id, fullness*100, overallFullness*100, tolerance*100)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/server/constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_replica"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -521,7 +522,7 @@ func (vcd *volumeCheckDisk) doVolumeCheckDisk(minuend, subtrahend *needle_map.Me
|
||||
return nil
|
||||
}
|
||||
if doCutoffOfLastNeedle {
|
||||
if needleMeta, err := readNeedleMeta(vcd.grpcDialOption(), pb.NewServerAddressFromDataNode(source.location.dataNode), source.info.Id, minuendValue); err == nil {
|
||||
if needleMeta, err := volume_replica.ReadNeedleMeta(vcd.grpcDialOption(), pb.NewServerAddressFromDataNode(source.location.dataNode), source.info.Id, minuendValue); err == nil {
|
||||
// needles older than the cutoff time are not missing yet
|
||||
if needleMeta.AppendAtNs > cutoffFromAtNs {
|
||||
return nil
|
||||
|
||||
@@ -136,7 +136,10 @@ func (c *commandVolumeServerEvacuate) evacuateNormalVolumes(commandEnv *CommandE
|
||||
}
|
||||
}
|
||||
volumeReplicas, _ := collectVolumeReplicaLocations(c.topologyInfo)
|
||||
for _, vol := range diskInfo.VolumeInfos {
|
||||
// A successful move calls adjustAfterMove, which removes the volume from
|
||||
// this disk's VolumeInfos in place. Iterate over a snapshot so removals
|
||||
// don't leave nil holes in the slice we are ranging over.
|
||||
for _, vol := range slices.Clone(diskInfo.VolumeInfos) {
|
||||
hasMoved, err := moveAwayOneNormalVolume(commandEnv, volumeReplicas, vol, thisNode, otherNodes, applyChange)
|
||||
if err != nil {
|
||||
fmt.Fprintf(writer, "move away volume %d from %s: %v\n", vol.Id, volumeServer, err)
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_replica"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -221,7 +222,7 @@ func (c *commandVolumeTierMove) doVolumeTierMove(commandEnv *CommandEnv, writer
|
||||
// Sync replicas and select the best one (with highest file count) for multi-replica volumes
|
||||
// This addresses data inconsistency risk in multi-replica volumes (issue #7797)
|
||||
// by syncing missing entries between replicas before moving
|
||||
sourceLoc, selectErr := syncAndSelectBestReplica(
|
||||
sourceLoc, selectErr := volume_replica.SyncAndSelectBestReplica(
|
||||
commandEnv.option.GrpcDialOption, vid, collection, locations, dst.dataNode.Id, writer)
|
||||
if selectErr != nil {
|
||||
fmt.Fprintf(writer, "failed to sync and select source replica for volume %d: %v\n", vid, selectErr)
|
||||
|
||||
@@ -179,23 +179,6 @@ func handleHelpRequest(c command, args []string, writer io.Writer) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func readNeedleMeta(grpcDialOption grpc.DialOption, volumeServer pb.ServerAddress, volumeId uint32, needleValue needle_map.NeedleValue) (resp *volume_server_pb.ReadNeedleMetaResponse, err error) {
|
||||
err = operation.WithVolumeServerClient(false, volumeServer, grpcDialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
if resp, err = client.ReadNeedleMeta(context.Background(), &volume_server_pb.ReadNeedleMetaRequest{
|
||||
VolumeId: volumeId,
|
||||
NeedleId: uint64(needleValue.Key),
|
||||
Offset: needleValue.Offset.ToActualOffset(),
|
||||
Size: int32(needleValue.Size),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func readNeedleStatus(grpcDialOption grpc.DialOption, sourceVolumeServer pb.ServerAddress, volumeId uint32, needleValue needle_map.NeedleValue) (resp *volume_server_pb.VolumeNeedleStatusResponse, err error) {
|
||||
err = operation.WithVolumeServerClient(false, sourceVolumeServer, grpcDialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
|
||||
@@ -172,7 +172,7 @@ func iterateEcjFile(baseFileName string, processNeedleFn func(key types.NeedleId
|
||||
|
||||
}
|
||||
|
||||
// WriteDatFile generates .dat from .ec00 ~ .ec09 files
|
||||
// WriteDatFile generates .dat from EC shard files (e.g., .ec00 ~ .ec09 for 10+4)
|
||||
func WriteDatFile(baseFileName string, datFileSize int64, shardFileNames []string) error {
|
||||
|
||||
datFile, openErr := os.OpenFile(baseFileName+".dat", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
@@ -181,25 +181,28 @@ func WriteDatFile(baseFileName string, datFileSize int64, shardFileNames []strin
|
||||
}
|
||||
defer datFile.Close()
|
||||
|
||||
inputFiles := make([]*os.File, DataShardsCount)
|
||||
// Use the actual number of data shards passed in rather than the global
|
||||
// constant, so the de-striping matches the caller's shard set.
|
||||
dataShards := len(shardFileNames)
|
||||
inputFiles := make([]*os.File, dataShards)
|
||||
|
||||
defer func() {
|
||||
for shardId := 0; shardId < DataShardsCount; shardId++ {
|
||||
for shardId := 0; shardId < dataShards; shardId++ {
|
||||
if inputFiles[shardId] != nil {
|
||||
inputFiles[shardId].Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for shardId := 0; shardId < DataShardsCount; shardId++ {
|
||||
for shardId := 0; shardId < dataShards; shardId++ {
|
||||
inputFiles[shardId], openErr = os.OpenFile(shardFileNames[shardId], os.O_RDONLY, 0)
|
||||
if openErr != nil {
|
||||
return openErr
|
||||
}
|
||||
}
|
||||
|
||||
for datFileSize >= DataShardsCount*ErasureCodingLargeBlockSize {
|
||||
for shardId := 0; shardId < DataShardsCount; shardId++ {
|
||||
for datFileSize >= int64(dataShards)*ErasureCodingLargeBlockSize {
|
||||
for shardId := 0; shardId < dataShards; shardId++ {
|
||||
w, err := io.CopyN(datFile, inputFiles[shardId], ErasureCodingLargeBlockSize)
|
||||
if w != ErasureCodingLargeBlockSize {
|
||||
return fmt.Errorf("copy %s large block on shardId %d: %v", baseFileName, shardId, err)
|
||||
@@ -209,7 +212,7 @@ func WriteDatFile(baseFileName string, datFileSize int64, shardFileNames []strin
|
||||
}
|
||||
|
||||
for datFileSize > 0 {
|
||||
for shardId := 0; shardId < DataShardsCount; shardId++ {
|
||||
for shardId := 0; shardId < dataShards; shardId++ {
|
||||
toRead := min(datFileSize, ErasureCodingSmallBlockSize)
|
||||
w, err := io.CopyN(datFile, inputFiles[shardId], toRead)
|
||||
if w != toRead {
|
||||
|
||||
@@ -2,6 +2,7 @@ package erasure_coding
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"iter"
|
||||
"math/bits"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -40,6 +41,20 @@ func (sb ShardBits) Count() int {
|
||||
return bits.OnesCount32(uint32(sb))
|
||||
}
|
||||
|
||||
// All iterates the shard ids present in the bitmap, in ascending order. It walks
|
||||
// only the set bits (trailing-zero scan), so cost scales with the number of
|
||||
// shards present rather than the full id range. Prefer this over scanning
|
||||
// 0..MaxShardCount and calling Has on each id.
|
||||
func (sb ShardBits) All() iter.Seq[ShardId] {
|
||||
return func(yield func(ShardId) bool) {
|
||||
for b := uint32(sb); b != 0; b &= b - 1 {
|
||||
if !yield(ShardId(bits.TrailingZeros32(b))) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ShardsInfo encapsulates information for EC shards with memory-efficient storage
|
||||
type ShardsInfo struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user