Compare commits

..
Author SHA1 Message Date
chrislu f98f347807 s3/filer: add singleflight deduplication for remote object caching
- Add singleflight.Group to FilerServer to deduplicate concurrent cache operations
- Wrap CacheRemoteObjectToLocalCluster with singleflight to ensure only one
  caching operation runs per object when multiple clients request the same file
- Add early-return check for already-cached objects
- S3 API calls filer gRPC with timeout and graceful fallback on error
- Clear negative bucket cache when bucket is created via weed shell
- Add integration tests for remote cache with singleflight deduplication

This benefits all clients (S3, HTTP, Hadoop) accessing remote-mounted objects
by preventing redundant cache operations and improving concurrent access performance.

Fixes: https://github.com/seaweedfs/seaweedfs/discussions/7599
2025-12-16 11:39:02 -08:00
118 changed files with 898 additions and 8697 deletions

No files matched your search

@@ -224,4 +224,3 @@ jobs:
echo "✓ Successfully copied ${{ matrix.variant }} to Docker Hub"
@@ -83,4 +83,3 @@ jobs:
path: test/s3/filer_group/weed-test*.log
retention-days: 3
-1
View File
@@ -91,4 +91,3 @@ jobs:
echo "| readonly | /public | Read-only |" >> $GITHUB_STEP_SUMMARY
-1
View File
@@ -130,4 +130,3 @@ coverage.out
/test/s3/remote_cache/test-remote-data
test/s3/remote_cache/remote-server.pid
test/s3/remote_cache/primary-server.pid
/test/erasure_coding/filerldb2
+1 -1
View File
@@ -71,7 +71,7 @@ require (
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/seaweedfs/goexif v1.0.3
github.com/seaweedfs/raft v1.1.6
github.com/seaweedfs/raft v1.1.3
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
+2 -2
View File
@@ -1618,8 +1618,8 @@ github.com/seaweedfs/cockroachdb-parser v0.0.0-20251021184156-909763b17138 h1:bX
github.com/seaweedfs/cockroachdb-parser v0.0.0-20251021184156-909763b17138/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/seaweedfs/raft v1.1.6 h1:e83Xn0boscPnuSiBllUPeWRVS6JKrqJPYBozgFyBiC0=
github.com/seaweedfs/raft v1.1.6/go.mod h1:9cYlEBA+djJbnf/5tWsCybtbL7ICYpi+Uxcg3MxjuNs=
github.com/seaweedfs/raft v1.1.3 h1:5B6hgneQ7IuU4Ceom/f6QUt8pEeqjcsRo+IxlyPZCws=
github.com/seaweedfs/raft v1.1.3/go.mod h1:9cYlEBA+djJbnf/5tWsCybtbL7ICYpi+Uxcg3MxjuNs=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
@@ -203,9 +203,6 @@ spec:
- name: client-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/client/
- name: admin-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/admin/
{{- end }}
{{ tpl .Values.admin.extraVolumeMounts . | nindent 12 | trim }}
ports:
@@ -301,9 +298,6 @@ spec:
- name: client-cert
secret:
secretName: {{ template "seaweedfs.name" . }}-client-cert
- name: admin-cert
secret:
secretName: {{ template "seaweedfs.name" . }}-admin-cert
{{- end }}
{{ tpl .Values.admin.extraVolumes . | indent 8 | trim }}
{{- if .Values.admin.nodeSelector }}
@@ -1,43 +0,0 @@
{{- if and .Values.global.enableSecurity (not .Values.certificates.externalCertificates.enabled)}}
apiVersion: cert-manager.io/v1{{ if .Values.global.certificates.alphacrds }}alpha1{{ end }}
kind: Certificate
metadata:
name: {{ template "seaweedfs.name" . }}-admin-cert
namespace: {{ .Release.Namespace }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: admin
{{- if .Values.admin.annotations }}
annotations:
{{- toYaml .Values.admin.annotations | nindent 4 }}
{{- end }}
spec:
secretName: {{ template "seaweedfs.name" . }}-admin-cert
issuerRef:
name: {{ template "seaweedfs.name" . }}-ca-issuer
kind: Issuer
commonName: {{ .Values.certificates.commonName }}
subject:
organizations:
- "SeaweedFS CA"
dnsNames:
- '*.{{ template "seaweedfs.name" . }}-admin'
- '*.{{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}'
- '*.{{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}.svc'
- '*.{{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.ipAddresses }}
ipAddresses:
{{- range .Values.certificates.ipAddresses }}
- {{ . }}
{{- end }}
{{- end }}
privateKey:
algorithm: {{ .Values.certificates.keyAlgorithm }}
size: {{ .Values.certificates.keySize }}
duration: {{ .Values.certificates.duration }}
renewBefore: {{ .Values.certificates.renewBefore }}
{{- end }}
@@ -1,43 +0,0 @@
{{- if and .Values.global.enableSecurity (not .Values.certificates.externalCertificates.enabled)}}
apiVersion: cert-manager.io/v1{{ if .Values.global.certificates.alphacrds }}alpha1{{ end }}
kind: Certificate
metadata:
name: {{ template "seaweedfs.name" . }}-worker-cert
namespace: {{ .Release.Namespace }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: worker
{{- if .Values.worker.annotations }}
annotations:
{{- toYaml .Values.worker.annotations | nindent 4 }}
{{- end }}
spec:
secretName: {{ template "seaweedfs.name" . }}-worker-cert
issuerRef:
name: {{ template "seaweedfs.name" . }}-ca-issuer
kind: Issuer
commonName: {{ .Values.certificates.commonName }}
subject:
organizations:
- "SeaweedFS CA"
dnsNames:
- '*.{{ template "seaweedfs.name" . }}-worker'
- '*.{{ template "seaweedfs.name" . }}-worker.{{ .Release.Namespace }}'
- '*.{{ template "seaweedfs.name" . }}-worker.{{ .Release.Namespace }}.svc'
- '*.{{ template "seaweedfs.name" . }}-worker.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.ipAddresses }}
ipAddresses:
{{- range .Values.certificates.ipAddresses }}
- {{ . }}
{{- end }}
{{- end }}
privateKey:
algorithm: {{ .Values.certificates.keyAlgorithm }}
size: {{ .Values.certificates.keySize }}
duration: {{ .Values.certificates.duration }}
renewBefore: {{ .Values.certificates.renewBefore }}
{{- end }}
@@ -65,14 +65,6 @@ data:
cert = "/usr/local/share/ca-certificates/filer/tls.crt"
key = "/usr/local/share/ca-certificates/filer/tls.key"
[grpc.admin]
cert = "/usr/local/share/ca-certificates/admin/tls.crt"
key = "/usr/local/share/ca-certificates/admin/tls.key"
[grpc.worker]
cert = "/usr/local/share/ca-certificates/worker/tls.crt"
key = "/usr/local/share/ca-certificates/worker/tls.key"
# use this for any place needs a grpc client
# i.e., "weed backup|benchmark|filer.copy|filer.replicate|mount|s3|upload"
[grpc.client]
@@ -171,9 +171,6 @@ spec:
- name: client-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/client/
- name: worker-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/worker/
{{- end }}
{{ tpl .Values.worker.extraVolumeMounts . | nindent 12 | trim }}
ports:
@@ -265,9 +262,6 @@ spec:
- name: client-cert
secret:
secretName: {{ template "seaweedfs.name" . }}-client-cert
- name: worker-cert
secret:
secretName: {{ template "seaweedfs.name" . }}-worker-cert
{{- end }}
{{ tpl .Values.worker.extraVolumes . | indent 8 | trim }}
{{- if .Values.worker.nodeSelector }}
-187
View File
@@ -1,187 +0,0 @@
# Makefile for EC integration testing
# Usage:
# make start - Start the test cluster (master + 6 volume servers + filer)
# make stop - Stop the test cluster
# make populate - Populate test data (~300MB across 7 volumes)
# make shell - Open weed shell connected to the test cluster
# make clean - Stop cluster and remove all test data
# make setup - Start cluster and populate data (one command)
#
# Requirements: curl, jq
WEED_BINARY := $(shell pwd)/../../weed/weed
TEST_DIR := /tmp/ec_manual_test
# Use non-standard ports to avoid conflicts with existing SeaweedFS servers
MASTER_PORT := 29333
FILER_PORT := 28888
VOLUME_BASE_PORT := 28080
NUM_VOLUME_SERVERS := 6
VOLUME_SIZE_LIMIT_MB := 30
MAX_VOLUMES_PER_SERVER := 10
# Build weed binary if it doesn't exist
$(WEED_BINARY):
cd ../../weed && go build -o weed .
.PHONY: build
build: $(WEED_BINARY)
.PHONY: start
start: build
@echo "=== Starting SeaweedFS test cluster ==="
@mkdir -p $(TEST_DIR)/master $(TEST_DIR)/filer
@for i in $$(seq 0 $$(($(NUM_VOLUME_SERVERS)-1))); do mkdir -p $(TEST_DIR)/volume$$i; done
@# Create security.toml with JWT disabled
@echo "# Disable JWT for testing" > $(TEST_DIR)/security.toml
@echo '[jwt.signing]' >> $(TEST_DIR)/security.toml
@echo 'key = ""' >> $(TEST_DIR)/security.toml
@echo 'expires_after_seconds = 0' >> $(TEST_DIR)/security.toml
@echo '' >> $(TEST_DIR)/security.toml
@echo '[jwt.signing.read]' >> $(TEST_DIR)/security.toml
@echo 'key = ""' >> $(TEST_DIR)/security.toml
@echo 'expires_after_seconds = 0' >> $(TEST_DIR)/security.toml
@# Create filer.toml with leveldb2
@echo '[leveldb2]' > $(TEST_DIR)/filer.toml
@echo 'enabled = true' >> $(TEST_DIR)/filer.toml
@echo 'dir = "$(TEST_DIR)/filer/filerldb2"' >> $(TEST_DIR)/filer.toml
@# Start master
@echo "Starting master on port $(MASTER_PORT)..."
@cd $(TEST_DIR) && $(WEED_BINARY) master \
-port=$(MASTER_PORT) \
-mdir=$(TEST_DIR)/master \
-volumeSizeLimitMB=$(VOLUME_SIZE_LIMIT_MB) \
-ip=127.0.0.1 \
> $(TEST_DIR)/master/master.log 2>&1 & echo $$! > $(TEST_DIR)/master.pid
@sleep 3
@# Start volume servers (run from TEST_DIR to find security.toml)
@for i in $$(seq 0 $$(($(NUM_VOLUME_SERVERS)-1))); do \
port=$$(($(VOLUME_BASE_PORT) + $$i)); \
echo "Starting volume server $$i on port $$port (rack$$i)..."; \
cd $(TEST_DIR) && $(WEED_BINARY) volume \
-port=$$port \
-dir=$(TEST_DIR)/volume$$i \
-max=$(MAX_VOLUMES_PER_SERVER) \
-master=127.0.0.1:$(MASTER_PORT) \
-ip=127.0.0.1 \
-dataCenter=dc1 \
-rack=rack$$i \
> $(TEST_DIR)/volume$$i/volume.log 2>&1 & echo $$! > $(TEST_DIR)/volume$$i.pid; \
done
@sleep 3
@# Start filer (run from TEST_DIR to find security.toml)
@echo "Starting filer on port $(FILER_PORT)..."
@cd $(TEST_DIR) && $(WEED_BINARY) filer \
-port=$(FILER_PORT) \
-master=127.0.0.1:$(MASTER_PORT) \
-ip=127.0.0.1 \
> $(TEST_DIR)/filer/filer.log 2>&1 & echo $$! > $(TEST_DIR)/filer.pid
@sleep 3
@echo ""
@echo "=== Cluster started ==="
@echo "Master: http://127.0.0.1:$(MASTER_PORT)"
@echo "Filer: http://127.0.0.1:$(FILER_PORT)"
@echo "Volume servers: http://127.0.0.1:$(VOLUME_BASE_PORT) - http://127.0.0.1:$$(($(VOLUME_BASE_PORT) + $(NUM_VOLUME_SERVERS) - 1))"
@echo ""
@echo "Run 'make shell' to open weed shell"
@echo "Run 'make populate' to add test data"
.PHONY: stop
stop:
@echo "=== Stopping SeaweedFS test cluster ==="
@# Stop filer by PID
@-[ -f $(TEST_DIR)/filer.pid ] && kill $$(cat $(TEST_DIR)/filer.pid) 2>/dev/null && rm -f $(TEST_DIR)/filer.pid || true
@# Stop volume servers by PID
@for i in $$(seq 0 $$(($(NUM_VOLUME_SERVERS)-1))); do \
[ -f $(TEST_DIR)/volume$$i.pid ] && kill $$(cat $(TEST_DIR)/volume$$i.pid) 2>/dev/null && rm -f $(TEST_DIR)/volume$$i.pid || true; \
done
@# Stop master by PID
@-[ -f $(TEST_DIR)/master.pid ] && kill $$(cat $(TEST_DIR)/master.pid) 2>/dev/null && rm -f $(TEST_DIR)/master.pid || true
@# Fallback: use pkill with specific patterns to ensure cleanup
@-pkill -f "weed filer.*-master=127.0.0.1:$(MASTER_PORT)" 2>/dev/null || true
@-pkill -f "weed volume.*-dir=$(TEST_DIR)/volume" 2>/dev/null || true
@-pkill -f "weed master.*-mdir=$(TEST_DIR)/master" 2>/dev/null || true
@echo "Cluster stopped."
.PHONY: clean
clean: stop
@echo "Removing test data..."
@rm -rf $(TEST_DIR)
@echo "Clean complete."
.PHONY: populate
populate:
@echo "=== Populating test data (~300MB) ==="
@# Create a 500KB test file template using mktemp for isolation
@tmpfile=$$(mktemp) && \
dd if=/dev/urandom bs=1024 count=500 of=$$tmpfile 2>/dev/null && \
uploaded=0; \
for i in $$(seq 1 600); do \
response=$$(curl -s "http://127.0.0.1:$(MASTER_PORT)/dir/assign?collection=ectest&replication=000"); \
fid=$$(echo $$response | jq -r '.fid'); \
url=$$(echo $$response | jq -r '.url'); \
if [ "$$fid" != "null" ] && [ -n "$$fid" ]; then \
curl -s -F "file=@$$tmpfile;filename=file_$$i.bin" "http://$$url/$$fid" > /dev/null; \
uploaded=$$((uploaded + 1)); \
fi; \
if [ $$((i % 100)) -eq 0 ]; then \
echo "Uploaded $$uploaded files..."; \
fi; \
done; \
rm -f $$tmpfile; \
echo ""; \
echo "=== Data population complete ==="; \
echo "Uploaded $$uploaded files (~$$((uploaded * 500 / 1024))MB)"
@echo ""
@echo "Volume status:"
@curl -s "http://127.0.0.1:$(MASTER_PORT)/vol/status" | jq -r \
'.Volumes.DataCenters.dc1 | to_entries[] | .key as $$rack | .value | to_entries[] | select(.value != null) | .key as $$server | .value[] | select(.Collection == "ectest") | " Volume \(.Id): \(.FileCount) files, \((.Size/1048576*10|floor)/10)MB - \($$rack)"' 2>/dev/null || true
.PHONY: shell
shell: build
@echo "Opening weed shell..."
@echo "Commands to try:"
@echo " lock"
@echo " volume.list"
@echo " ec.encode -collection=ectest -quietFor=1s -force"
@echo " ec.balance -collection=ectest"
@echo " unlock"
@echo ""
@$(WEED_BINARY) shell -master=127.0.0.1:$(MASTER_PORT) -filer=127.0.0.1:$(FILER_PORT)
.PHONY: setup
setup: clean start
@sleep 2
@$(MAKE) populate
.PHONY: status
status:
@echo "=== Cluster Status ==="
@curl -s "http://127.0.0.1:$(MASTER_PORT)/vol/status" | jq -r \
'.Volumes.DataCenters.dc1 | to_entries[] | .key as $$rack | .value | to_entries[] | select(.value != null) | .key as $$server | .value[] | select(.Collection == "ectest") | "Volume \(.Id): \(.FileCount) files, \((.Size/1048576*10|floor)/10)MB - \($$rack) (\($$server))"' 2>/dev/null | sort -t: -k1 -n || echo "Cluster not running"
@echo ""
@echo "=== EC Shards ==="
@for i in $$(seq 0 $$(($(NUM_VOLUME_SERVERS)-1))); do \
count=$$(ls $(TEST_DIR)/volume$$i/*.ec[0-9]* 2>/dev/null | wc -l | tr -d ' '); \
if [ "$$count" != "0" ]; then \
echo " volume$$i (port $$(($(VOLUME_BASE_PORT) + $$i))): $$count EC shard files"; \
fi; \
done
.PHONY: help
help:
@echo "EC Integration Test Makefile"
@echo ""
@echo "Targets:"
@echo " make start - Start test cluster (master + 6 volume servers + filer)"
@echo " make stop - Stop test cluster"
@echo " make populate - Populate ~300MB of test data"
@echo " make shell - Open weed shell"
@echo " make setup - Clean, start, and populate (all-in-one)"
@echo " make status - Show cluster and EC shard status"
@echo " make clean - Stop cluster and remove all test data"
@echo " make help - Show this help"
@echo ""
@echo "Quick start:"
@echo " make setup # Start cluster and populate data"
@echo " make shell # Open shell to run EC commands"
-37
View File
@@ -78,43 +78,6 @@ go test -v -run TestECEncodingMasterTimingRaceCondition
go test -v -short
```
## Manual Testing with Makefile
A Makefile is provided for manual EC testing.
**Requirements:** `curl`, `jq` (command-line JSON processor)
```bash
# Quick start: start cluster and populate data
make setup
# Open weed shell to run EC commands
make shell
# Individual targets
make start # Start test cluster (master + 6 volume servers + filer)
make stop # Stop test cluster
make populate # Populate ~300MB of test data
make status # Show cluster and EC shard status
make clean # Stop cluster and remove all test data
make help # Show all targets
```
### EC Rebalance Limited Slots (Unit Test)
The "no free ec shard slots" issue is tested with a **unit test** that works directly on
topology data structures without requiring a running cluster.
**Location**: `weed/shell/ec_rebalance_slots_test.go`
Tests included:
- `TestECRebalanceWithLimitedSlots`: Tests a topology with 6 servers, 7 EC volumes (98 shards)
- `TestECRebalanceZeroFreeSlots`: Reproduces the exact 0 free slots scenario
**Known Issue**: When volume servers are at capacity (`volumeCount == maxVolumeCount`),
the rebalance step fails with "no free ec shard slots" instead of recognizing that
moving shards frees slots on source servers.
## Test Results
**With the fix**: Shows "Collecting volume locations for N volumes before EC encoding..." message
+1 -260
View File
@@ -15,10 +15,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/shell"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
@@ -388,7 +386,7 @@ func startSeaweedFSCluster(ctx context.Context, dataDir string) (*TestCluster, e
// Find weed binary
weedBinary := findWeedBinary()
if weedBinary == "" {
return nil, fmt.Errorf("weed binary not found - build with 'go build' or 'make' first")
return nil, fmt.Errorf("weed binary not found")
}
cluster := &TestCluster{}
@@ -397,11 +395,6 @@ func startSeaweedFSCluster(ctx context.Context, dataDir string) (*TestCluster, e
masterDir := filepath.Join(dataDir, "master")
os.MkdirAll(masterDir, 0755)
// Create an empty security.toml to disable JWT authentication in tests
// This prevents the test from picking up ~/.seaweedfs/security.toml
securityToml := filepath.Join(dataDir, "security.toml")
os.WriteFile(securityToml, []byte("# Empty security config for testing\n"), 0644)
// Start master server
masterCmd := exec.CommandContext(ctx, weedBinary, "master",
"-port", "9333",
@@ -410,7 +403,6 @@ func startSeaweedFSCluster(ctx context.Context, dataDir string) (*TestCluster, e
"-ip", "127.0.0.1",
"-peers", "none", // Faster startup when no multiple masters needed
)
masterCmd.Dir = dataDir // Run from test dir so it picks up our security.toml
masterLogFile, err := os.Create(filepath.Join(masterDir, "master.log"))
if err != nil {
@@ -443,7 +435,6 @@ func startSeaweedFSCluster(ctx context.Context, dataDir string) (*TestCluster, e
"-dataCenter", "dc1",
"-rack", rack,
)
volumeCmd.Dir = dataDir // Run from test dir so it picks up our security.toml
volumeLogFile, err := os.Create(filepath.Join(volumeDir, "volume.log"))
if err != nil {
@@ -478,10 +469,6 @@ func findWeedBinary() string {
for _, candidate := range candidates {
if _, err := os.Stat(candidate); err == nil {
// Convert to absolute path so it works when command's Dir is changed
if absPath, err := filepath.Abs(candidate); err == nil {
return absPath
}
return candidate
}
}
@@ -2187,249 +2174,3 @@ func countShardsPerRack(testDir string, volumeId uint32) map[string]int {
return rackDistribution
}
// TestECEncodeReplicatedVolumeSync tests that ec.encode properly syncs missing entries
// between replicas before encoding. This addresses issue #7797.
func TestECEncodeReplicatedVolumeSync(t *testing.T) {
if testing.Short() {
t.Skip("Skipping replicated volume sync integration test in short mode")
}
// Create temporary directory for test data
testDir, err := os.MkdirTemp("", "seaweedfs_ec_replica_sync_test_")
require.NoError(t, err)
defer os.RemoveAll(testDir)
// Start SeaweedFS cluster
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
cluster, err := startSeaweedFSCluster(ctx, testDir)
require.NoError(t, err)
defer cluster.Stop()
// Wait for servers to be ready
require.NoError(t, waitForServer("127.0.0.1:9333", 30*time.Second))
for i := 0; i < 6; i++ {
require.NoError(t, waitForServer(fmt.Sprintf("127.0.0.1:%d", 8080+i), 30*time.Second))
}
// Create command environment
options := &shell.ShellOptions{
Masters: stringPtr("127.0.0.1:9333"),
GrpcDialOption: grpc.WithInsecure(),
FilerGroup: stringPtr("default"),
}
commandEnv := shell.NewCommandEnv(options)
// Connect to master with longer timeout
ctx2, cancel2 := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel2()
go commandEnv.MasterClient.KeepConnectedToMaster(ctx2)
commandEnv.MasterClient.WaitUntilConnected(ctx2)
// Wait for volume servers to register with master
time.Sleep(5 * time.Second)
// Test: Create replicated volume and verify sync behavior with consistent replicas
t.Run("sync_replicated_volume_consistent", func(t *testing.T) {
const testCollection = "replicated_consistent"
const testReplication = "010" // 2 copies on different servers on the same rack
// Retry a few times as volume servers may still be registering
var volumeId needle.VolumeId
var uploadErr error
for retry := 0; retry < 5; retry++ {
volumeId, uploadErr = uploadTestDataWithReplication(t, "127.0.0.1:9333", testCollection, testReplication)
if uploadErr == nil {
break
}
t.Logf("Upload attempt %d failed: %v, retrying...", retry+1, uploadErr)
time.Sleep(3 * time.Second)
}
if uploadErr != nil {
t.Skipf("Could not create replicated volume: %v", uploadErr)
return
}
t.Logf("Created replicated volume %d with collection %s, replication %s", volumeId, testCollection, testReplication)
// Acquire lock
locked, unlock := tryLockWithTimeout(t, commandEnv, 30*time.Second)
if !locked {
t.Skip("Could not acquire lock within timeout")
}
defer unlock()
// Execute EC encoding with the same collection
ecEncodeCmd := shell.Commands[findCommandIndex("ec.encode")]
args := []string{
"-volumeId", fmt.Sprintf("%d", volumeId),
"-collection", testCollection,
"-force",
}
outputStr, encodeErr := captureCommandOutput(t, ecEncodeCmd, args, commandEnv)
t.Logf("EC encode output:\n%s", outputStr)
// For consistent replicas, should see "all X replicas are consistent"
assert.Contains(t, outputStr, "replicas are consistent", "Should detect replicas are consistent")
if encodeErr != nil {
t.Logf("EC encoding result: %v", encodeErr)
} else {
t.Log("EC encoding completed successfully")
}
})
// Test: Create divergent replicas and verify sync/union code is exercised
t.Run("sync_replicated_volume_divergent", func(t *testing.T) {
const testCollection = "replicated_divergent"
const testReplication = "010" // 2 copies on different servers on the same rack
// Create replicated volume with initial data
var volumeId needle.VolumeId
var uploadErr error
for retry := 0; retry < 5; retry++ {
volumeId, uploadErr = uploadTestDataWithReplication(t, "127.0.0.1:9333", testCollection, testReplication)
if uploadErr == nil {
break
}
t.Logf("Upload attempt %d failed: %v, retrying...", retry+1, uploadErr)
time.Sleep(3 * time.Second)
}
if uploadErr != nil {
t.Skipf("Could not create replicated volume: %v", uploadErr)
return
}
t.Logf("Created replicated volume %d with collection %s, replication %s", volumeId, testCollection, testReplication)
// Get volume locations to identify the two replicas
locations, found := commandEnv.MasterClient.GetLocationsClone(uint32(volumeId))
if !found || len(locations) < 2 {
t.Skipf("Could not get 2 replica locations for volume %d (got %d)", volumeId, len(locations))
return
}
t.Logf("Volume %d has replicas at: %v and %v", volumeId, locations[0].Url, locations[1].Url)
// Write an extra entry to ONLY one replica to create divergence
// We'll use the WriteNeedleBlob gRPC call to inject data directly
extraNeedleId := uint64(999999) // Use a high needle ID unlikely to conflict
extraData := []byte("extra data written to only one replica to create divergence")
err := injectNeedleToOneReplica(grpc.WithInsecure(), volumeId, locations[0], extraNeedleId, extraData)
if err != nil {
t.Logf("Could not inject divergent needle (may not be supported): %v", err)
// Fall back to testing consistent path
} else {
t.Logf("Injected extra needle %d to replica %s to create divergence", extraNeedleId, locations[0].Url)
}
// Acquire lock
locked, unlock := tryLockWithTimeout(t, commandEnv, 30*time.Second)
if !locked {
t.Skip("Could not acquire lock within timeout")
}
defer unlock()
// Execute EC encoding - should detect divergence and build union
ecEncodeCmd := shell.Commands[findCommandIndex("ec.encode")]
args := []string{
"-volumeId", fmt.Sprintf("%d", volumeId),
"-collection", testCollection,
"-force",
}
outputStr, encodeErr := captureCommandOutput(t, ecEncodeCmd, args, commandEnv)
t.Logf("EC encode output:\n%s", outputStr)
// Check if divergence was detected
if strings.Contains(outputStr, "building union") {
t.Log("SUCCESS: Divergent replicas detected - sync/union code was exercised")
assert.Contains(t, outputStr, "selected", "Should show which replica was selected as best")
// The "copied" message only appears if the best replica is missing entries from other replicas
// In our case, we injected into what becomes the best replica (higher file count),
// so copying may not be needed. The key is that "building union" was triggered.
if strings.Contains(outputStr, "copied") {
t.Log("Entries were copied between replicas")
} else {
t.Log("Best replica already had all entries (injected entry was on best replica)")
}
} else if strings.Contains(outputStr, "replicas are consistent") {
t.Log("Replicas were consistent (injection may not have worked)")
} else {
t.Log("Single replica or sync not triggered")
}
if encodeErr != nil {
t.Logf("EC encoding result: %v", encodeErr)
} else {
t.Log("EC encoding completed successfully")
}
})
}
// injectNeedleToOneReplica writes a needle directly to one replica to create divergence
func injectNeedleToOneReplica(grpcDialOption grpc.DialOption, vid needle.VolumeId, location wdclient.Location, needleId uint64, data []byte) error {
return operation.WithVolumeServerClient(false, location.ServerAddress(), grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
_, err := client.WriteNeedleBlob(context.Background(), &volume_server_pb.WriteNeedleBlobRequest{
VolumeId: uint32(vid),
NeedleId: needleId,
Size: int32(len(data)),
NeedleBlob: data,
})
return err
})
}
// uploadTestDataWithReplication uploads test data and returns the volume ID
// using the specified collection and replication level. All files are uploaded to the same volume.
func uploadTestDataWithReplication(t *testing.T, masterAddr string, collection string, replication string) (needle.VolumeId, error) {
const numFiles = 20 // Reduced count since we're uploading to same volume
// Assign multiple file IDs from the same volume
assignResult, err := operation.Assign(context.Background(), func(ctx context.Context) pb.ServerAddress {
return pb.ServerAddress(masterAddr)
}, grpc.WithInsecure(), &operation.VolumeAssignRequest{
Count: uint64(numFiles),
Collection: collection,
Replication: replication,
})
if err != nil {
return 0, fmt.Errorf("failed to assign volume: %v", err)
}
// Parse volume ID from file ID
fid, err := needle.ParseFileIdFromString(assignResult.Fid)
if err != nil {
return 0, fmt.Errorf("failed to parse file ID: %v", err)
}
volumeId := fid.VolumeId
// Create uploader for upload
uploader, err := operation.NewUploader()
if err != nil {
return 0, fmt.Errorf("failed to create uploader: %v", err)
}
// Upload test data to the same volume using the assigned file IDs
// The first FID is assignResult.Fid, subsequent ones increment the needle key
baseNeedleKey := uint64(fid.Key)
for i := 0; i < numFiles; i++ {
data := []byte(fmt.Sprintf("test data for replicated volume sync test - entry %d - padding to make it larger %s",
i, strings.Repeat("x", 1000)))
// Construct FID for this file (same volume, incrementing needle key)
currentFid := fmt.Sprintf("%d,%x%08x", volumeId, baseNeedleKey+uint64(i), fid.Cookie)
uploadUrl := fmt.Sprintf("http://%s/%s", assignResult.Url, currentFid)
_, _, uploadErr := uploader.Upload(context.Background(), bytes.NewReader(data), &operation.UploadOption{
UploadUrl: uploadUrl,
Filename: fmt.Sprintf("file%d.txt", i),
})
if uploadErr != nil {
t.Logf("Upload %d failed: %v", i, uploadErr)
}
}
return volumeId, nil
}
+1 -2
View File
@@ -172,8 +172,7 @@ services:
- -master=seaweedfs-master:9333
- -ip=seaweedfs-mq-broker
- -port=17777
- -debug
- -debug.port=18777
- -port.pprof=18777
depends_on:
seaweedfs-filer:
condition: service_healthy
@@ -181,8 +181,7 @@ services:
- -ip=seaweedfs-mq-broker
- -port=17777
- -logFlushInterval=0
- -debug
- -debug.port=18777
- -port.pprof=18777
depends_on:
seaweedfs-filer:
condition: service_healthy
-1
View File
@@ -25,4 +25,3 @@ test-resume: build-weed
clean:
rm -f ../../weed/weed
-1
View File
@@ -47,4 +47,3 @@ go test -v -timeout 5m ./test/metadata_subscribe/...
- Tests create temporary directories that are cleaned up after completion
- Tests use ports 9333 (master), 8080 (volume), 8888 (filer)
-1
View File
@@ -90,4 +90,3 @@ These tests use **AWS SDK v2 for Go**, which has the same ETag validation behavi
- [GitHub Issue #7768](https://github.com/seaweedfs/seaweedfs/issues/7768)
- [AWS S3 ETag Documentation](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Object.html)
-1
View File
@@ -17,4 +17,3 @@
}
}
+1 -1
View File
@@ -5,4 +5,4 @@
"secret_key": "some_secret_key1",
"region": "us-east-1",
"filer_group": "testgroup"
}
}
+6 -7
View File
@@ -558,14 +558,13 @@ func TestS3IAMPresignedURLIntegration(t *testing.T) {
adminClient, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
require.NoError(t, err)
// Use unique bucket name to avoid conflicts with other tests
bucketName := framework.GenerateUniqueBucketName("test-iam-presigned")
err = framework.CreateBucket(adminClient, bucketName)
// Use static bucket name but with cleanup to handle conflicts
err = framework.CreateBucketWithCleanup(adminClient, testBucket)
require.NoError(t, err)
// Put test object
_, err = adminClient.PutObject(&s3.PutObjectInput{
Bucket: aws.String(bucketName),
Bucket: aws.String(testBucket),
Key: aws.String(testObjectKey),
Body: strings.NewReader(testObjectData),
})
@@ -587,7 +586,7 @@ func TestS3IAMPresignedURLIntegration(t *testing.T) {
// Test direct object access with JWT Bearer token (recommended approach)
_, err := adminClient.GetObject(&s3.GetObjectInput{
Bucket: aws.String(bucketName),
Bucket: aws.String(testBucket),
Key: aws.String(testObjectKey),
})
require.NoError(t, err, "Direct object access with JWT Bearer token works correctly")
@@ -598,13 +597,13 @@ func TestS3IAMPresignedURLIntegration(t *testing.T) {
// Cleanup
_, err = adminClient.DeleteObject(&s3.DeleteObjectInput{
Bucket: aws.String(bucketName),
Bucket: aws.String(testBucket),
Key: aws.String(testObjectKey),
})
require.NoError(t, err)
_, err = adminClient.DeleteBucket(&s3.DeleteBucketInput{
Bucket: aws.String(bucketName),
Bucket: aws.String(testBucket),
})
require.NoError(t, err)
}
+16 -18
View File
@@ -2,10 +2,8 @@
# Tests the remote object caching functionality with singleflight deduplication
# Uses two SeaweedFS instances: primary (with caching) and secondary (as remote storage)
.PHONY: all help build-weed check-deps start-remote stop-remote start-primary stop-primary \
setup-remote test test-with-server clean logs logs-primary logs-remote health
all: test-with-server
.PHONY: help build-weed check-deps start-remote stop-remote start-primary stop-primary \
setup-remote test test-with-server clean logs
# Configuration
WEED_BINARY := ../../../weed/weed_binary
@@ -60,13 +58,13 @@ build-weed:
@echo "Building SeaweedFS binary..."
@cd ../../../weed && go build -o weed_binary .
@chmod +x $(WEED_BINARY)
@echo "SeaweedFS binary built"
@echo "✅ SeaweedFS binary built"
check-deps: build-weed
@echo "Checking dependencies..."
@command -v go >/dev/null 2>&1 || (echo "Go is required" && exit 1)
@test -f $(WEED_BINARY) || (echo "SeaweedFS binary not found" && exit 1)
@echo "All dependencies available"
@echo "✅ All dependencies available"
# Start remote SeaweedFS (acts as the "remote" S3 storage)
start-remote: check-deps
@@ -90,12 +88,12 @@ start-remote: check-deps
@echo "Waiting for remote SeaweedFS to start..."
@for i in $$(seq 1 60); do \
if curl -s http://localhost:$(REMOTE_S3_PORT) >/dev/null 2>&1; then \
echo "Remote SeaweedFS started on port $(REMOTE_S3_PORT)"; \
echo "✅ Remote SeaweedFS started on port $(REMOTE_S3_PORT)"; \
exit 0; \
fi; \
sleep 1; \
done; \
echo "ERROR: Remote SeaweedFS failed to start"; \
echo "❌ Remote SeaweedFS failed to start"; \
cat remote-weed.log; \
exit 1
@@ -107,7 +105,7 @@ stop-remote:
kill -KILL $$(cat remote-server.pid) 2>/dev/null || true; \
rm -f remote-server.pid; \
fi
@echo "Remote SeaweedFS stopped"
@echo "✅ Remote SeaweedFS stopped"
# Start primary SeaweedFS (the one being tested)
start-primary: check-deps
@@ -131,12 +129,12 @@ start-primary: check-deps
@echo "Waiting for primary SeaweedFS to start..."
@for i in $$(seq 1 60); do \
if curl -s http://localhost:$(PRIMARY_S3_PORT) >/dev/null 2>&1; then \
echo "Primary SeaweedFS started on port $(PRIMARY_S3_PORT)"; \
echo "✅ Primary SeaweedFS started on port $(PRIMARY_S3_PORT)"; \
exit 0; \
fi; \
sleep 1; \
done; \
echo "ERROR: Primary SeaweedFS failed to start"; \
echo "❌ Primary SeaweedFS failed to start"; \
cat primary-weed.log; \
exit 1
@@ -148,7 +146,7 @@ stop-primary:
kill -KILL $$(cat primary-server.pid) 2>/dev/null || true; \
rm -f primary-server.pid; \
fi
@echo "Primary SeaweedFS stopped"
@echo "✅ Primary SeaweedFS stopped"
# Create bucket on remote and configure remote storage mount on primary
setup-remote:
@@ -161,13 +159,13 @@ setup-remote:
@echo "Mounting remote bucket on primary..."
@printf 'remote.mount -dir=/buckets/remotemounted -remote=seaweedremote/$(REMOTE_BUCKET) -nonempty\nexit\n' | $(WEED_BINARY) shell -master=localhost:$(PRIMARY_MASTER_PORT) 2>&1 || echo "remote.mount done"
@sleep 1
@echo "Remote storage configured"
@echo "✅ Remote storage configured"
# Run tests
test: check-deps
@echo "Running remote cache tests..."
@go test -v -timeout=$(TEST_TIMEOUT) -run "$(TEST_PATTERN)" .
@echo "Tests completed"
@echo "✅ Tests completed"
# Full test workflow
test-with-server: start-remote start-primary
@@ -177,7 +175,7 @@ test-with-server: start-remote start-primary
@echo "Running remote cache tests..."
@$(MAKE) test || (echo "Tests failed" && tail -50 primary-weed.log && $(MAKE) stop-primary stop-remote && exit 1)
@$(MAKE) stop-primary stop-remote
@echo "All tests passed"
@echo "✅ All tests passed"
# Show logs
logs:
@@ -201,10 +199,10 @@ clean:
@rm -rf $(PRIMARY_DIR) $(REMOTE_DIR)
@rm -f remote_cache.test
@go clean -testcache
@echo "Cleanup completed"
@echo "✅ Cleanup completed"
# Health check
health:
@echo "Checking server status..."
@curl -s http://localhost:$(PRIMARY_S3_PORT) >/dev/null 2>&1 && echo "Primary S3 ($(PRIMARY_S3_PORT)): UP" || echo "Primary S3 ($(PRIMARY_S3_PORT)): DOWN"
@curl -s http://localhost:$(REMOTE_S3_PORT) >/dev/null 2>&1 && echo "Remote S3 ($(REMOTE_S3_PORT)): UP" || echo "Remote S3 ($(REMOTE_S3_PORT)): DOWN"
@curl -s http://localhost:$(PRIMARY_S3_PORT) >/dev/null 2>&1 && echo "✅ Primary S3 ($(PRIMARY_S3_PORT)): UP" || echo "❌ Primary S3 ($(PRIMARY_S3_PORT)): DOWN"
@curl -s http://localhost:$(REMOTE_S3_PORT) >/dev/null 2>&1 && echo "✅ Remote S3 ($(REMOTE_S3_PORT)): UP" || echo "❌ Remote S3 ($(REMOTE_S3_PORT)): DOWN"
+1 -3
View File
@@ -13,7 +13,7 @@ This tests the full remote caching workflow including singleflight deduplication
## Architecture
```text
```
┌─────────────────────────────────────────────────────────────────┐
│ Test Client │
│ │
@@ -78,7 +78,6 @@ make clean
## Configuration
### Primary SeaweedFS (Being Tested)
| Service | Port |
|---------|------|
| S3 API | 8333 |
@@ -87,7 +86,6 @@ make clean
| Volume | 8080 |
### Remote SeaweedFS (Remote Storage)
| Service | Port |
|---------|------|
| S3 API | 8334 |
+20 -31
View File
@@ -45,15 +45,11 @@ const (
)
var (
primaryClient *s3.S3
primaryClientOnce sync.Once
primaryClient *s3.S3
)
func getPrimaryClient() *s3.S3 {
primaryClientOnce.Do(func() {
primaryClient = createS3Client(primaryEndpoint)
})
return primaryClient
func init() {
primaryClient = createS3Client(primaryEndpoint)
}
func createS3Client(endpoint string) *s3.S3 {
@@ -86,20 +82,19 @@ func skipIfNotRunning(t *testing.T) {
}
// runWeedShell executes a weed shell command
func runWeedShell(t *testing.T, command string) (string, error) {
func runWeedShell(t *testing.T, command string) string {
cmd := exec.Command(weedBinary, "shell", "-master=localhost:"+primaryMasterPort)
cmd.Stdin = strings.NewReader(command + "\nexit\n")
output, err := cmd.CombinedOutput()
if err != nil {
t.Logf("weed shell command '%s' failed: %v, output: %s", command, err, string(output))
return string(output), err
t.Logf("weed shell command '%s' output: %s", command, string(output))
}
return string(output), nil
return string(output)
}
// uploadToPrimary uploads an object to the primary SeaweedFS (local write)
func uploadToPrimary(t *testing.T, key string, data []byte) {
_, err := getPrimaryClient().PutObject(&s3.PutObjectInput{
_, err := primaryClient.PutObject(&s3.PutObjectInput{
Bucket: aws.String(testBucket),
Key: aws.String(key),
Body: bytes.NewReader(data),
@@ -109,7 +104,7 @@ func uploadToPrimary(t *testing.T, key string, data []byte) {
// getFromPrimary gets an object from primary SeaweedFS
func getFromPrimary(t *testing.T, key string) []byte {
resp, err := getPrimaryClient().GetObject(&s3.GetObjectInput{
resp, err := primaryClient.GetObject(&s3.GetObjectInput{
Bucket: aws.String(testBucket),
Key: aws.String(key),
})
@@ -124,10 +119,7 @@ func getFromPrimary(t *testing.T, key string) []byte {
// syncToRemote syncs local data to remote storage
func syncToRemote(t *testing.T) {
t.Log("Syncing to remote storage...")
output, err := runWeedShell(t, "remote.cache.uncache -dir=/buckets/"+testBucket+" -include=*")
if err != nil {
t.Logf("syncToRemote warning: %v", err)
}
output := runWeedShell(t, "remote.cache.uncache -dir=/buckets/"+testBucket+" -include=*")
t.Log(output)
time.Sleep(1 * time.Second)
}
@@ -135,10 +127,7 @@ func syncToRemote(t *testing.T) {
// uncacheLocal purges the local cache, forcing data to be fetched from remote
func uncacheLocal(t *testing.T, pattern string) {
t.Logf("Purging local cache for pattern: %s", pattern)
output, err := runWeedShell(t, fmt.Sprintf("remote.uncache -dir=/buckets/%s -include=%s", testBucket, pattern))
if err != nil {
t.Logf("uncacheLocal warning: %v", err)
}
output := runWeedShell(t, fmt.Sprintf("remote.uncache -dir=/buckets/%s -include=%s", testBucket, pattern))
t.Log(output)
time.Sleep(500 * time.Millisecond)
}
@@ -183,7 +172,7 @@ func TestRemoteCacheBasic(t *testing.T) {
assert.Equal(t, testData, result, "data mismatch on cached read")
t.Logf("Second read (from cache) took %v", secondReadDuration)
t.Log("Basic caching test passed")
t.Log("✅ Basic caching test passed")
}
// TestRemoteCacheConcurrent tests that concurrent reads of the same
@@ -224,7 +213,7 @@ func TestRemoteCacheConcurrent(t *testing.T) {
wg.Add(1)
go func(idx int) {
defer wg.Done()
resp, err := getPrimaryClient().GetObject(&s3.GetObjectInput{
resp, err := primaryClient.GetObject(&s3.GetObjectInput{
Bucket: aws.String(testBucket),
Key: aws.String(testKey),
})
@@ -263,7 +252,7 @@ func TestRemoteCacheConcurrent(t *testing.T) {
assert.Equal(t, int32(numRequests), successCount.Load(), "some requests failed")
assert.Equal(t, int32(0), errorCount.Load(), "no requests should fail")
t.Log("Concurrent caching test passed")
t.Log("✅ Concurrent caching test passed")
}
// TestRemoteCacheLargeObject tests caching of larger objects
@@ -299,7 +288,7 @@ func TestRemoteCacheLargeObject(t *testing.T) {
assert.Equal(t, testData, result, "data mismatch")
t.Logf("Large object cached in %v", duration)
t.Log("Large object caching test passed")
t.Log("✅ Large object caching test passed")
}
// TestRemoteCacheRangeRequest tests that range requests work after caching
@@ -316,7 +305,7 @@ func TestRemoteCacheRangeRequest(t *testing.T) {
// Range request should work and trigger caching
t.Log("Testing range request (bytes 10-19)...")
resp, err := getPrimaryClient().GetObject(&s3.GetObjectInput{
resp, err := primaryClient.GetObject(&s3.GetObjectInput{
Bucket: aws.String(testBucket),
Key: aws.String(testKey),
Range: aws.String("bytes=10-19"),
@@ -331,7 +320,7 @@ func TestRemoteCacheRangeRequest(t *testing.T) {
assert.Equal(t, expected, rangeData, "range data mismatch")
t.Logf("Range request returned: %s", string(rangeData))
t.Log("Range request test passed")
t.Log("✅ Range request test passed")
}
// TestRemoteCacheNotFound tests that non-existent objects return proper errors
@@ -340,7 +329,7 @@ func TestRemoteCacheNotFound(t *testing.T) {
testKey := fmt.Sprintf("non-existent-object-%d", time.Now().UnixNano())
_, err := getPrimaryClient().GetObject(&s3.GetObjectInput{
_, err := primaryClient.GetObject(&s3.GetObjectInput{
Bucket: aws.String(testBucket),
Key: aws.String(testKey),
})
@@ -348,17 +337,17 @@ func TestRemoteCacheNotFound(t *testing.T) {
assert.Error(t, err, "should get error for non-existent object")
t.Logf("Got expected error: %v", err)
t.Log("Not found test passed")
t.Log("✅ Not found test passed")
}
// TestMain sets up and tears down the test environment
func TestMain(m *testing.M) {
if !isServerRunning(primaryEndpoint) {
fmt.Println("WARNING: Primary SeaweedFS not running at", primaryEndpoint)
fmt.Println("⚠️ Primary SeaweedFS not running at", primaryEndpoint)
fmt.Println(" Run 'make test-with-server' to start servers automatically")
}
if !isServerRunning(remoteEndpoint) {
fmt.Println("WARNING: Remote SeaweedFS not running at", remoteEndpoint)
fmt.Println("⚠️ Remote SeaweedFS not running at", remoteEndpoint)
fmt.Println(" Run 'make test-with-server' to start servers automatically")
}
@@ -1,521 +0,0 @@
package s3api
import (
"bytes"
"context"
"crypto/md5"
"fmt"
"strings"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestMultipartUploadVersioningListETag tests that multipart uploaded objects
// in versioned buckets have correct ETags when listed.
// This covers a bug where synthetic entries for versioned objects didn't include
// proper ETag handling for multipart uploads (ETags with format "<md5>-<parts>").
func TestMultipartUploadVersioningListETag(t *testing.T) {
client := getS3Client(t)
bucketName := getNewBucketName()
// Create bucket
createBucket(t, client, bucketName)
defer deleteBucket(t, client, bucketName)
// Enable versioning
_, err := client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucketName),
VersioningConfiguration: &types.VersioningConfiguration{
Status: types.BucketVersioningStatusEnabled,
},
})
require.NoError(t, err, "Failed to enable versioning")
// Create multipart upload
objectKey := "multipart-test-object"
createResp, err := client.CreateMultipartUpload(context.TODO(), &s3.CreateMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
require.NoError(t, err, "Failed to create multipart upload")
uploadId := *createResp.UploadId
// Upload 2 parts (minimum 5MB per part except last)
partSize := 5 * 1024 * 1024 // 5MB
part1Data := bytes.Repeat([]byte("a"), partSize)
part2Data := bytes.Repeat([]byte("b"), partSize)
// Calculate MD5 for each part
part1MD5 := md5.Sum(part1Data)
part2MD5 := md5.Sum(part2Data)
// Upload part 1
uploadPart1Resp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: aws.String(uploadId),
PartNumber: aws.Int32(1),
Body: bytes.NewReader(part1Data),
})
require.NoError(t, err, "Failed to upload part 1")
// Upload part 2
uploadPart2Resp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: aws.String(uploadId),
PartNumber: aws.Int32(2),
Body: bytes.NewReader(part2Data),
})
require.NoError(t, err, "Failed to upload part 2")
// Complete multipart upload
completeResp, err := client.CompleteMultipartUpload(context.TODO(), &s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: aws.String(uploadId),
MultipartUpload: &types.CompletedMultipartUpload{
Parts: []types.CompletedPart{
{
ETag: uploadPart1Resp.ETag,
PartNumber: aws.Int32(1),
},
{
ETag: uploadPart2Resp.ETag,
PartNumber: aws.Int32(2),
},
},
},
})
require.NoError(t, err, "Failed to complete multipart upload")
// Verify the ETag from CompleteMultipartUpload has the multipart format (md5-parts)
completeETag := strings.Trim(*completeResp.ETag, "\"")
assert.Contains(t, completeETag, "-", "Multipart ETag should contain '-' (format: md5-parts)")
assert.True(t, strings.HasSuffix(completeETag, "-2"), "Multipart ETag should end with '-2' for 2 parts")
t.Logf("CompleteMultipartUpload ETag: %s", completeETag)
t.Logf("Part 1 MD5: %x", part1MD5)
t.Logf("Part 2 MD5: %x", part2MD5)
// HeadObject should return the same ETag
headResp, err := client.HeadObject(context.TODO(), &s3.HeadObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
require.NoError(t, err, "Failed to head object")
headETag := strings.Trim(*headResp.ETag, "\"")
assert.Equal(t, completeETag, headETag, "HeadObject ETag should match CompleteMultipartUpload ETag")
// ListObjectsV2 should return the same ETag
listResp, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list objects")
require.Len(t, listResp.Contents, 1, "Should have exactly one object")
listETag := strings.Trim(*listResp.Contents[0].ETag, "\"")
assert.Equal(t, completeETag, listETag, "ListObjectsV2 ETag should match CompleteMultipartUpload ETag")
assert.NotEmpty(t, listETag, "ListObjectsV2 ETag should not be empty")
t.Logf("ListObjectsV2 ETag: %s", listETag)
// ListObjectVersions should also return the correct ETag
versionsResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list object versions")
require.Len(t, versionsResp.Versions, 1, "Should have exactly one version")
versionETag := strings.Trim(*versionsResp.Versions[0].ETag, "\"")
assert.Equal(t, completeETag, versionETag, "ListObjectVersions ETag should match CompleteMultipartUpload ETag")
assert.NotEmpty(t, versionETag, "ListObjectVersions ETag should not be empty")
t.Logf("ListObjectVersions ETag: %s", versionETag)
}
// TestMultipartUploadMultipleVersionsListETag tests that multiple versions
// of multipart uploaded objects all have correct ETags when listed.
func TestMultipartUploadMultipleVersionsListETag(t *testing.T) {
client := getS3Client(t)
bucketName := getNewBucketName()
// Create bucket
createBucket(t, client, bucketName)
defer deleteBucket(t, client, bucketName)
// Enable versioning
_, err := client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucketName),
VersioningConfiguration: &types.VersioningConfiguration{
Status: types.BucketVersioningStatusEnabled,
},
})
require.NoError(t, err, "Failed to enable versioning")
objectKey := "multipart-multi-version-object"
partSize := 5 * 1024 * 1024 // 5MB
var expectedETags []string
// Create 3 versions using multipart upload
for version := 1; version <= 3; version++ {
// Create multipart upload
createResp, err := client.CreateMultipartUpload(context.TODO(), &s3.CreateMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
require.NoError(t, err, "Failed to create multipart upload for version %d", version)
uploadId := *createResp.UploadId
// Create unique data for each version
partData := bytes.Repeat([]byte(fmt.Sprintf("%d", version)), partSize)
// Upload single part (still results in multipart ETag format)
uploadPartResp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: aws.String(uploadId),
PartNumber: aws.Int32(1),
Body: bytes.NewReader(partData),
})
require.NoError(t, err, "Failed to upload part for version %d", version)
// Complete multipart upload
completeResp, err := client.CompleteMultipartUpload(context.TODO(), &s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: aws.String(uploadId),
MultipartUpload: &types.CompletedMultipartUpload{
Parts: []types.CompletedPart{
{
ETag: uploadPartResp.ETag,
PartNumber: aws.Int32(1),
},
},
},
})
require.NoError(t, err, "Failed to complete multipart upload for version %d", version)
etag := strings.Trim(*completeResp.ETag, "\"")
expectedETags = append(expectedETags, etag)
t.Logf("Version %d ETag: %s", version, etag)
}
// ListObjectVersions should return all versions with correct ETags
versionsResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list object versions")
require.Len(t, versionsResp.Versions, 3, "Should have exactly 3 versions")
// Collect ETags from the listing
var listedETags []string
for _, v := range versionsResp.Versions {
etag := strings.Trim(*v.ETag, "\"")
listedETags = append(listedETags, etag)
assert.NotEmpty(t, etag, "Version ETag should not be empty")
assert.Contains(t, etag, "-", "Multipart ETag should contain '-'")
}
t.Logf("Expected ETags: %v", expectedETags)
t.Logf("Listed ETags: %v", listedETags)
// Verify all expected ETags are present (order may differ due to version ordering)
assert.ElementsMatch(t, expectedETags, listedETags, "Listed ETags should match all expected ETags")
// Regular ListObjectsV2 should return only the latest version with correct ETag
listResp, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list objects")
require.Len(t, listResp.Contents, 1, "Should have exactly one object in regular listing")
listETag := strings.Trim(*listResp.Contents[0].ETag, "\"")
// The latest version (version 3) should be the one shown
assert.Equal(t, expectedETags[2], listETag, "ListObjectsV2 should show latest version's ETag")
}
// TestMixedSingleAndMultipartVersionsListETag tests that a mix of
// single-part and multipart uploaded versions all have correct ETags.
func TestMixedSingleAndMultipartVersionsListETag(t *testing.T) {
client := getS3Client(t)
bucketName := getNewBucketName()
// Create bucket
createBucket(t, client, bucketName)
defer deleteBucket(t, client, bucketName)
// Enable versioning
_, err := client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucketName),
VersioningConfiguration: &types.VersioningConfiguration{
Status: types.BucketVersioningStatusEnabled,
},
})
require.NoError(t, err, "Failed to enable versioning")
objectKey := "mixed-upload-versions"
// Version 1: Regular PutObject (single-part, pure MD5 ETag)
content1 := []byte("This is version 1 content - single part upload")
putResp1, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
Body: bytes.NewReader(content1),
})
require.NoError(t, err, "Failed to put version 1")
etag1 := strings.Trim(*putResp1.ETag, "\"")
assert.NotContains(t, etag1, "-", "Single-part ETag should not contain '-'")
t.Logf("Version 1 (PutObject) ETag: %s", etag1)
// Version 2: Multipart upload
partSize := 5 * 1024 * 1024
partData := bytes.Repeat([]byte("x"), partSize)
createResp, err := client.CreateMultipartUpload(context.TODO(), &s3.CreateMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
require.NoError(t, err, "Failed to create multipart upload")
uploadPartResp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: createResp.UploadId,
PartNumber: aws.Int32(1),
Body: bytes.NewReader(partData),
})
require.NoError(t, err, "Failed to upload part")
completeResp, err := client.CompleteMultipartUpload(context.TODO(), &s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: createResp.UploadId,
MultipartUpload: &types.CompletedMultipartUpload{
Parts: []types.CompletedPart{
{
ETag: uploadPartResp.ETag,
PartNumber: aws.Int32(1),
},
},
},
})
require.NoError(t, err, "Failed to complete multipart upload")
etag2 := strings.Trim(*completeResp.ETag, "\"")
assert.Contains(t, etag2, "-", "Multipart ETag should contain '-'")
t.Logf("Version 2 (Multipart) ETag: %s", etag2)
// Version 3: Another regular PutObject
content3 := []byte("This is version 3 content - another single part upload")
putResp3, err := client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
Body: bytes.NewReader(content3),
})
require.NoError(t, err, "Failed to put version 3")
etag3 := strings.Trim(*putResp3.ETag, "\"")
assert.NotContains(t, etag3, "-", "Single-part ETag should not contain '-'")
t.Logf("Version 3 (PutObject) ETag: %s", etag3)
// ListObjectVersions should return all 3 versions with correct ETags
versionsResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list object versions")
require.Len(t, versionsResp.Versions, 3, "Should have exactly 3 versions")
var listedETags []string
for _, v := range versionsResp.Versions {
etag := strings.Trim(*v.ETag, "\"")
assert.NotEmpty(t, etag, "Version ETag should not be empty")
listedETags = append(listedETags, etag)
t.Logf("Listed version %s ETag: %s, IsLatest: %v", *v.VersionId, etag, *v.IsLatest)
}
// Verify all ETags were found
assert.ElementsMatch(t, []string{etag1, etag2, etag3}, listedETags, "Listed ETags should match all expected ETags")
// Regular ListObjectsV2 should return only the latest (version 3)
listResp, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list objects")
require.Len(t, listResp.Contents, 1, "Should have exactly one object")
listETag := strings.Trim(*listResp.Contents[0].ETag, "\"")
assert.Equal(t, etag3, listETag, "ListObjectsV2 should show latest version's ETag (version 3)")
}
// TestMultipartUploadDeleteMarkerListBehavior tests that delete markers work correctly
// with multipart uploaded objects in versioned buckets.
func TestMultipartUploadDeleteMarkerListBehavior(t *testing.T) {
client := getS3Client(t)
bucketName := getNewBucketName()
// Create bucket
createBucket(t, client, bucketName)
defer deleteBucket(t, client, bucketName)
// Enable versioning
_, err := client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucketName),
VersioningConfiguration: &types.VersioningConfiguration{
Status: types.BucketVersioningStatusEnabled,
},
})
require.NoError(t, err, "Failed to enable versioning")
objectKey := "multipart-delete-marker-test"
partSize := 5 * 1024 * 1024 // 5MB
// Create multipart upload
createResp, err := client.CreateMultipartUpload(context.TODO(), &s3.CreateMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
require.NoError(t, err, "Failed to create multipart upload")
// Upload 2 parts
part1Data := bytes.Repeat([]byte("a"), partSize)
part2Data := bytes.Repeat([]byte("b"), partSize)
uploadPart1Resp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: createResp.UploadId,
PartNumber: aws.Int32(1),
Body: bytes.NewReader(part1Data),
})
require.NoError(t, err, "Failed to upload part 1")
uploadPart2Resp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: createResp.UploadId,
PartNumber: aws.Int32(2),
Body: bytes.NewReader(part2Data),
})
require.NoError(t, err, "Failed to upload part 2")
// Complete multipart upload
completeResp, err := client.CompleteMultipartUpload(context.TODO(), &s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: createResp.UploadId,
MultipartUpload: &types.CompletedMultipartUpload{
Parts: []types.CompletedPart{
{ETag: uploadPart1Resp.ETag, PartNumber: aws.Int32(1)},
{ETag: uploadPart2Resp.ETag, PartNumber: aws.Int32(2)},
},
},
})
require.NoError(t, err, "Failed to complete multipart upload")
multipartETag := strings.Trim(*completeResp.ETag, "\"")
multipartVersionId := *completeResp.VersionId
t.Logf("Multipart upload completed: ETag=%s, VersionId=%s", multipartETag, multipartVersionId)
// Verify object is visible in ListObjectsV2
listBeforeDelete, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list objects before delete")
require.Len(t, listBeforeDelete.Contents, 1, "Object should be visible before delete")
assert.Equal(t, multipartETag, strings.Trim(*listBeforeDelete.Contents[0].ETag, "\""),
"Listed ETag should match multipart ETag before delete")
// Delete object (creates delete marker)
deleteResp, err := client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
require.NoError(t, err, "Failed to delete object")
require.NotNil(t, deleteResp.DeleteMarker, "Should create delete marker")
assert.True(t, *deleteResp.DeleteMarker, "DeleteMarker should be true")
require.NotNil(t, deleteResp.VersionId, "Delete marker should have version ID")
deleteMarkerVersionId := *deleteResp.VersionId
t.Logf("Delete marker created: VersionId=%s", deleteMarkerVersionId)
// ListObjectsV2 should NOT show the object anymore
listAfterDelete, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list objects after delete")
assert.Empty(t, listAfterDelete.Contents, "Object should NOT be visible after delete marker")
// ListObjectVersions should show both the original version AND the delete marker
versionsResp, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list object versions")
// Should have 1 version (the multipart object)
require.Len(t, versionsResp.Versions, 1, "Should have exactly 1 version (the multipart object)")
version := versionsResp.Versions[0]
assert.Equal(t, multipartVersionId, *version.VersionId, "Version ID should match")
assert.Equal(t, multipartETag, strings.Trim(*version.ETag, "\""), "Version ETag should match multipart ETag")
assert.False(t, *version.IsLatest, "Multipart version should NOT be latest (delete marker is latest)")
// Should have 1 delete marker
require.Len(t, versionsResp.DeleteMarkers, 1, "Should have exactly 1 delete marker")
deleteMarker := versionsResp.DeleteMarkers[0]
assert.Equal(t, deleteMarkerVersionId, *deleteMarker.VersionId, "Delete marker version ID should match")
assert.True(t, *deleteMarker.IsLatest, "Delete marker should be latest")
t.Logf("ListObjectVersions: 1 version (ETag=%s), 1 delete marker", multipartETag)
// Access the specific version by version ID - should still work
getResp, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
VersionId: aws.String(multipartVersionId),
})
require.NoError(t, err, "Should be able to get object by version ID after delete marker")
defer getResp.Body.Close()
assert.Equal(t, multipartETag, strings.Trim(*getResp.ETag, "\""),
"GetObject with version ID should return correct ETag")
assert.Equal(t, int64(partSize*2), *getResp.ContentLength,
"GetObject with version ID should return correct size")
t.Logf("Successfully retrieved version %s after delete marker", multipartVersionId)
// Delete the delete marker to "undelete" the object
_, err = client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
VersionId: aws.String(deleteMarkerVersionId),
})
require.NoError(t, err, "Failed to delete the delete marker")
// ListObjectsV2 should show the object again
listAfterUndelete, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
Prefix: aws.String(objectKey),
})
require.NoError(t, err, "Failed to list objects after undelete")
require.Len(t, listAfterUndelete.Contents, 1, "Object should be visible again after removing delete marker")
assert.Equal(t, multipartETag, strings.Trim(*listAfterUndelete.Contents[0].ETag, "\""),
"Undeleted object should have correct multipart ETag")
t.Logf("Object restored after delete marker removal, ETag=%s", multipartETag)
}
-1
View File
@@ -90,4 +90,3 @@ To debug test failures:
```
-1
View File
@@ -35,4 +35,3 @@
]
+11 -43
View File
@@ -117,7 +117,7 @@ func (s *WorkerGrpcServer) Stop() error {
s.connMutex.Lock()
for _, conn := range s.connections {
conn.cancel()
s.safeCloseOutgoingChannel(conn, "Stop")
close(conn.outgoing)
}
s.connections = make(map[string]*WorkerConnection)
s.connMutex.Unlock()
@@ -182,27 +182,15 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
}
conn.capabilities = capabilities
// Register connection - clean up old connection if worker is reconnecting
// Register connection
s.connMutex.Lock()
if oldConn, exists := s.connections[workerID]; exists {
glog.Infof("Worker %s reconnected, cleaning up old connection", workerID)
// Cancel old connection to stop its goroutines
oldConn.cancel()
// Don't close oldConn.outgoing here as it may cause panic in handleOutgoingMessages
// Let the goroutine exit naturally when it detects context cancellation
}
s.connections[workerID] = conn
s.connMutex.Unlock()
// Register worker with maintenance manager
s.registerWorkerWithManager(conn)
// IMPORTANT: Start outgoing message handler BEFORE sending registration response
// This ensures the handler is ready to process messages and prevents race conditions
// where the worker might send requests before we're ready to respond
go s.handleOutgoingMessages(conn)
// Send registration response (after handler is started)
// Send registration response
regResponse := &worker_pb.AdminMessage{
Timestamp: time.Now().Unix(),
Message: &worker_pb.AdminMessage_RegistrationResponse{
@@ -215,11 +203,13 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
select {
case conn.outgoing <- regResponse:
glog.V(1).Infof("Registration response sent to worker %s", workerID)
case <-time.After(5 * time.Second):
glog.Errorf("Failed to send registration response to worker %s", workerID)
}
// Start outgoing message handler
go s.handleOutgoingMessages(conn)
// Handle incoming messages
for {
select {
@@ -245,9 +235,7 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
return err
}
s.connMutex.Lock()
conn.lastSeen = time.Now()
s.connMutex.Unlock()
s.handleWorkerMessage(conn, msg)
}
}
@@ -452,36 +440,16 @@ func (s *WorkerGrpcServer) handleTaskLogResponse(conn *WorkerConnection, respons
s.logRequestsMutex.Unlock()
}
// safeCloseOutgoingChannel safely closes the outgoing channel for a worker connection.
func (s *WorkerGrpcServer) safeCloseOutgoingChannel(conn *WorkerConnection, source string) {
defer func() {
if r := recover(); r != nil {
glog.V(1).Infof("%s: recovered from panic closing outgoing channel for worker %s: %v", source, conn.workerID, r)
}
}()
close(conn.outgoing)
}
// unregisterWorker removes a worker connection
func (s *WorkerGrpcServer) unregisterWorker(workerID string) {
s.connMutex.Lock()
conn, exists := s.connections[workerID]
if !exists {
s.connMutex.Unlock()
glog.V(2).Infof("unregisterWorker: worker %s not found in connections map (already unregistered)", workerID)
return
if conn, exists := s.connections[workerID]; exists {
conn.cancel()
close(conn.outgoing)
delete(s.connections, workerID)
}
// Remove from map first to prevent duplicate cleanup attempts
delete(s.connections, workerID)
s.connMutex.Unlock()
// Cancel context to signal goroutines to stop
conn.cancel()
// Safely close the outgoing channel with recover to handle potential double-close
s.safeCloseOutgoingChannel(conn, "unregisterWorker")
glog.V(1).Infof("Unregistered worker %s", workerID)
}
@@ -511,7 +479,7 @@ func (s *WorkerGrpcServer) cleanupStaleConnections() {
if conn.lastSeen.Before(cutoff) {
glog.Warningf("Cleaning up stale worker connection: %s", workerID)
conn.cancel()
s.safeCloseOutgoingChannel(conn, "cleanupStaleConnections")
close(conn.outgoing)
delete(s.connections, workerID)
}
}
@@ -266,26 +266,7 @@ func (s *MaintenanceIntegration) ScanWithTaskDetectors(volumeMetrics []*types.Vo
// 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
if topologyInfo != nil {
dcCount, nodeCount, diskCount := topology.CountTopologyResources(topologyInfo)
glog.V(2).Infof("UpdateTopologyInfo: received topology with %d datacenters, %d nodes, %d disks",
dcCount, nodeCount, diskCount)
} else {
glog.Warningf("UpdateTopologyInfo: received nil topologyInfo")
}
err := s.activeTopology.UpdateTopology(topologyInfo)
if err != nil {
glog.Errorf("UpdateTopologyInfo: topology update failed: %v", err)
} else {
// Log success with current disk count
currentDiskCount := s.activeTopology.GetDiskCount()
glog.V(1).Infof("UpdateTopologyInfo: topology update successful, active topology now has %d disks", currentDiskCount)
}
return err
return s.activeTopology.UpdateTopology(topologyInfo)
}
// convertToExistingFormat converts task results to existing system format using dynamic mapping
@@ -137,7 +137,6 @@ func (mm *MaintenanceManager) Start() error {
// Start background processes
go mm.scanLoop()
go mm.cleanupLoop()
go mm.topologyStatusLoop() // Periodic diagnostic logging
glog.Infof("Maintenance manager started with scan interval %ds", mm.config.ScanIntervalSeconds)
return nil
@@ -256,54 +255,6 @@ func (mm *MaintenanceManager) cleanupLoop() {
}
}
// topologyStatusLoop periodically logs topology status for diagnostics
func (mm *MaintenanceManager) topologyStatusLoop() {
// Log topology status every 5 minutes for diagnostic purposes
statusInterval := 5 * time.Minute
ticker := time.NewTicker(statusInterval)
defer ticker.Stop()
for mm.running {
select {
case <-mm.stopChan:
return
case <-ticker.C:
mm.logTopologyStatus()
}
}
}
// logTopologyStatus logs current topology and worker status for diagnostics
func (mm *MaintenanceManager) logTopologyStatus() {
if mm.scanner == nil || mm.scanner.integration == nil {
glog.V(2).Infof("Topology status: scanner/integration not available")
return
}
activeTopology := mm.scanner.integration.GetActiveTopology()
if activeTopology == nil {
glog.V(1).Infof("Topology status: ActiveTopology is nil")
return
}
diskCount := activeTopology.GetDiskCount()
nodeCount := len(activeTopology.GetAllNodes())
// Get queue stats
stats := mm.queue.GetStats()
workerCount := len(mm.queue.GetWorkers())
mm.mutex.RLock()
errorCount := mm.errorCount
mm.mutex.RUnlock()
glog.V(0).Infof("Topology status: %d nodes, %d disks, %d workers, %d pending tasks, %d running tasks, errors: %d",
nodeCount, diskCount, workerCount,
stats.TasksByStatus[TaskStatusPending],
stats.TasksByStatus[TaskStatusInProgress]+stats.TasksByStatus[TaskStatusAssigned],
errorCount)
}
// performScan executes a maintenance scan with error handling and backoff
func (mm *MaintenanceManager) performScan() {
defer func() {
@@ -8,53 +8,11 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
// CountTopologyResources counts datacenters, nodes, and disks in topology info
func CountTopologyResources(topologyInfo *master_pb.TopologyInfo) (dcCount, nodeCount, diskCount int) {
if topologyInfo == nil {
return 0, 0, 0
}
dcCount = len(topologyInfo.DataCenterInfos)
for _, dc := range topologyInfo.DataCenterInfos {
for _, rack := range dc.RackInfos {
nodeCount += len(rack.DataNodeInfos)
for _, node := range rack.DataNodeInfos {
diskCount += len(node.DiskInfos)
}
}
}
return
}
// UpdateTopology updates the topology information from master
func (at *ActiveTopology) UpdateTopology(topologyInfo *master_pb.TopologyInfo) error {
at.mutex.Lock()
defer at.mutex.Unlock()
// Validate topology updates to prevent clearing disk maps with invalid data
if topologyInfo == nil {
glog.Warningf("UpdateTopology received nil topologyInfo, preserving last-known-good topology")
return fmt.Errorf("rejected invalid topology update: nil topologyInfo")
}
if len(topologyInfo.DataCenterInfos) == 0 {
glog.Warningf("UpdateTopology received empty DataCenterInfos, preserving last-known-good topology (had %d nodes, %d disks)",
len(at.nodes), len(at.disks))
return fmt.Errorf("rejected invalid topology update: empty DataCenterInfos (had %d nodes, %d disks)", len(at.nodes), len(at.disks))
}
// Count incoming topology for validation logging
dcCount, incomingNodes, incomingDisks := CountTopologyResources(topologyInfo)
// Reject updates that would wipe out a valid topology with an empty one (e.g. during master restart)
if incomingNodes == 0 && len(at.nodes) > 0 {
glog.Warningf("UpdateTopology received topology with 0 nodes, preserving last-known-good topology (had %d nodes, %d disks)",
len(at.nodes), len(at.disks))
return fmt.Errorf("rejected invalid topology update: 0 nodes (had %d nodes, %d disks)", len(at.nodes), len(at.disks))
}
glog.V(2).Infof("UpdateTopology: validating update with %d datacenters, %d nodes, %d disks (current: %d nodes, %d disks)",
dcCount, incomingNodes, incomingDisks, len(at.nodes), len(at.disks))
at.topologyInfo = topologyInfo
at.lastUpdated = time.Now()
@@ -184,21 +142,8 @@ func (at *ActiveTopology) GetNodeDisks(nodeID string) []*DiskInfo {
return disks
}
// GetDiskCount returns the total number of disks in the active topology
func (at *ActiveTopology) GetDiskCount() int {
at.mutex.RLock()
defer at.mutex.RUnlock()
return len(at.disks)
}
// rebuildIndexes rebuilds the volume and EC shard indexes for O(1) lookups
func (at *ActiveTopology) rebuildIndexes() {
// Nil-safety guard: return early if topology is not valid
if at.topologyInfo == nil || at.topologyInfo.DataCenterInfos == nil {
glog.V(1).Infof("rebuildIndexes: skipping rebuild due to nil topology or DataCenterInfos")
return
}
// Clear existing indexes
at.volumeIndex = make(map[uint32][]string)
at.ecShardIndex = make(map[uint32][]string)
+1 -1
View File
@@ -127,7 +127,7 @@ templ S3Buckets(data dash.S3BucketsData) {
for _, bucket := range data.Buckets {
<tr>
<td>
<a href={templ.SafeURL(fmt.Sprintf("/files?path=/buckets/%s", bucket.Name))}
<a href={templ.SafeURL(fmt.Sprintf("/s3/buckets/%s", bucket.Name))}
class="text-decoration-none">
<i class="fas fa-cube me-2"></i>
{bucket.Name}
+2 -2
View File
@@ -83,9 +83,9 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 templ.SafeURL
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("/s3/buckets/%s", bucket.Name)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 130, Col: 123}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 130, Col: 114}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
+6 -20
View File
@@ -3,7 +3,6 @@ package cluster
import (
"context"
"fmt"
"strings"
"sync/atomic"
"time"
@@ -42,7 +41,6 @@ type LiveLock struct {
self string
lc *LockClient
owner string
renewInterval time.Duration
}
// NewShortLivedLock creates a lock with a 5-second duration
@@ -61,7 +59,7 @@ func (lc *LockClient) NewShortLivedLock(key string, owner string) (lock *LiveLoc
}
// StartLongLivedLock starts a goroutine to lock the key and returns immediately.
func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerChange func(newLockOwner string), renewInterval time.Duration) (lock *LiveLock) {
func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerChange func(newLockOwner string)) (lock *LiveLock) {
lock = &LiveLock{
key: key,
hostFiler: lc.seedFiler,
@@ -70,10 +68,6 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
grpcDialOption: lc.grpcDialOption,
self: owner,
lc: lc,
renewInterval: renewInterval,
}
if lock.renewInterval == 0 {
lock.renewInterval = lock_manager.RenewInterval
}
go func() {
isLocked := false
@@ -108,11 +102,7 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
case <-lock.cancelCh:
return
default:
if isLocked {
time.Sleep(5 * lock.renewInterval)
} else {
time.Sleep(lock.renewInterval)
}
time.Sleep(lock_manager.RenewInterval)
}
}
}()
@@ -139,11 +129,7 @@ func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
return err
}
if errorMessage != "" {
if strings.Contains(errorMessage, "lock already owned") {
glog.V(3).Infof("LOCK: doLock returned error message for key=%s: %s", lock.key, errorMessage)
} else {
glog.V(2).Infof("LOCK: doLock returned error message for key=%s: %s", lock.key, errorMessage)
}
glog.V(1).Infof("LOCK: doLock returned error message for key=%s: %s", lock.key, errorMessage)
time.Sleep(time.Second)
return fmt.Errorf("%v", errorMessage)
}
@@ -220,7 +206,7 @@ func (lock *LiveLock) doLock(lockDuration time.Duration) (errorMessage string, e
errorMessage = resp.Error
if resp.LockHostMovedTo != "" && resp.LockHostMovedTo != string(previousHostFiler) {
// Only log if the host actually changed
glog.V(2).Infof("LOCK: Host changed from %s to %s for key=%s", previousHostFiler, resp.LockHostMovedTo, lock.key)
glog.V(1).Infof("LOCK: Host changed from %s to %s for key=%s", previousHostFiler, resp.LockHostMovedTo, lock.key)
lock.hostFiler = pb.ServerAddress(resp.LockHostMovedTo)
lock.lc.seedFiler = lock.hostFiler
} else if resp.LockHostMovedTo != "" {
@@ -228,12 +214,12 @@ func (lock *LiveLock) doLock(lockDuration time.Duration) (errorMessage string, e
}
if resp.LockOwner != "" && resp.LockOwner != previousOwner {
// Only log if the owner actually changed
glog.V(2).Infof("LOCK: Owner changed from %s to %s for key=%s", previousOwner, resp.LockOwner, lock.key)
glog.V(1).Infof("LOCK: Owner changed from %s to %s for key=%s", previousOwner, resp.LockOwner, lock.key)
lock.owner = resp.LockOwner
} else if resp.LockOwner != "" {
lock.owner = resp.LockOwner
} else if previousOwner != "" {
glog.V(2).Infof("LOCK: Owner cleared for key=%s", lock.key)
glog.V(1).Infof("LOCK: Owner cleared for key=%s", lock.key)
lock.owner = ""
}
}
-7
View File
@@ -53,8 +53,6 @@ type SyncOptions struct {
bDoDeleteFiles *bool
clientId int32
clientEpoch atomic.Int32
debug *bool
debugPort *int
}
const (
@@ -110,8 +108,6 @@ func init() {
syncOptions.metricsHttpPort = cmdFilerSynchronize.Flag.Int("metricsPort", 0, "metrics listen port")
syncOptions.aDoDeleteFiles = cmdFilerSynchronize.Flag.Bool("a.doDeleteFiles", true, "delete and update files when synchronizing on filer A")
syncOptions.bDoDeleteFiles = cmdFilerSynchronize.Flag.Bool("b.doDeleteFiles", true, "delete and update files when synchronizing on filer B")
syncOptions.debug = cmdFilerSynchronize.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
syncOptions.debugPort = cmdFilerSynchronize.Flag.Int("debug.port", 6060, "http port for debugging")
syncOptions.clientId = util.RandomInt32()
}
@@ -134,9 +130,6 @@ var cmdFilerSynchronize = &Command{
}
func runFilerSynchronize(cmd *Command, args []string) bool {
if *syncOptions.debug {
grace.StartDebugServer(*syncOptions.debugPort)
}
util.LoadSecurityConfiguration()
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
-7
View File
@@ -69,8 +69,6 @@ type MasterOptions struct {
raftBootstrap *bool
telemetryUrl *string
telemetryEnabled *bool
debug *bool
debugPort *int
}
func init() {
@@ -100,8 +98,6 @@ func init() {
m.raftBootstrap = cmdMaster.Flag.Bool("raftBootstrap", false, "Whether to bootstrap the Raft cluster")
m.telemetryUrl = cmdMaster.Flag.String("telemetry.url", "https://telemetry.seaweedfs.com/api/collect", "telemetry server URL to send usage statistics")
m.telemetryEnabled = cmdMaster.Flag.Bool("telemetry", false, "enable telemetry reporting")
m.debug = cmdMaster.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
m.debugPort = cmdMaster.Flag.Int("debug.port", 6060, "http port for debugging")
}
var cmdMaster = &Command{
@@ -125,9 +121,6 @@ var (
)
func runMaster(cmd *Command, args []string) bool {
if *m.debug {
grace.StartDebugServer(*m.debugPort)
}
util.LoadSecurityConfiguration()
util.LoadConfiguration("master", false)
-3
View File
@@ -41,9 +41,6 @@ func init() {
mf.metricsAddress = aws.String("")
mf.metricsIntervalSec = aws.Int(0)
mf.raftResumeState = aws.Bool(false)
mf.maxParallelVacuumPerServer = aws.Int(1)
mf.telemetryUrl = aws.String("https://telemetry.seaweedfs.com/api/collect")
mf.telemetryEnabled = aws.Bool(false)
}
var cmdMasterFollower = &Command{
+2 -2
View File
@@ -68,8 +68,8 @@ func init() {
mountOptions.diskType = cmdMount.Flag.String("disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
mountOptions.ttlSec = cmdMount.Flag.Int("ttl", 0, "file ttl in seconds")
mountOptions.chunkSizeLimitMB = cmdMount.Flag.Int("chunkSizeLimitMB", 2, "local write buffer size, also chunk large files")
mountOptions.concurrentWriters = cmdMount.Flag.Int("concurrentWriters", 128, "limit concurrent goroutine writers")
mountOptions.concurrentReaders = cmdMount.Flag.Int("concurrentReaders", 128, "limit concurrent chunk fetches for read operations")
mountOptions.concurrentWriters = cmdMount.Flag.Int("concurrentWriters", 32, "limit concurrent goroutine writers")
mountOptions.concurrentReaders = cmdMount.Flag.Int("concurrentReaders", 16, "limit concurrent chunk fetches for read operations")
mountOptions.cacheDirForRead = cmdMount.Flag.String("cacheDir", os.TempDir(), "local cache directory for file chunks and meta data")
mountOptions.cacheSizeMBForRead = cmdMount.Flag.Int64("cacheCapacityMB", 128, "file chunk read cache capacity in MB")
mountOptions.cacheDirForWrite = cmdMount.Flag.String("cacheDirWrite", "", "buffer writes mostly for large files")
+20 -8
View File
@@ -1,15 +1,20 @@
package command
import (
"fmt"
"net/http"
_ "net/http/pprof"
"google.golang.org/grpc/reflection"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/broker"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
)
var (
@@ -22,13 +27,12 @@ type MessageQueueBrokerOptions struct {
filerGroup *string
ip *string
port *int
pprofPort *int
dataCenter *string
rack *string
cpuprofile *string
memprofile *string
logFlushInterval *int
debug *bool
debugPort *int
}
func init() {
@@ -37,13 +41,12 @@ func init() {
mqBrokerStandaloneOptions.filerGroup = cmdMqBroker.Flag.String("filerGroup", "", "share metadata with other filers in the same filerGroup")
mqBrokerStandaloneOptions.ip = cmdMqBroker.Flag.String("ip", util.DetectedHostAddress(), "broker host address")
mqBrokerStandaloneOptions.port = cmdMqBroker.Flag.Int("port", 17777, "broker gRPC listen port")
mqBrokerStandaloneOptions.pprofPort = cmdMqBroker.Flag.Int("port.pprof", 0, "HTTP profiling port (0 to disable)")
mqBrokerStandaloneOptions.dataCenter = cmdMqBroker.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
mqBrokerStandaloneOptions.rack = cmdMqBroker.Flag.String("rack", "", "prefer to write to volumes in this rack")
mqBrokerStandaloneOptions.cpuprofile = cmdMqBroker.Flag.String("cpuprofile", "", "cpu profile output file")
mqBrokerStandaloneOptions.memprofile = cmdMqBroker.Flag.String("memprofile", "", "memory profile output file")
mqBrokerStandaloneOptions.logFlushInterval = cmdMqBroker.Flag.Int("logFlushInterval", 5, "log buffer flush interval in seconds")
mqBrokerStandaloneOptions.debug = cmdMqBroker.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
mqBrokerStandaloneOptions.debugPort = cmdMqBroker.Flag.Int("debug.port", 6060, "http port for debugging")
}
var cmdMqBroker = &Command{
@@ -58,9 +61,6 @@ var cmdMqBroker = &Command{
}
func runMqBroker(cmd *Command, args []string) bool {
if *mqBrokerStandaloneOptions.debug {
grace.StartDebugServer(*mqBrokerStandaloneOptions.debugPort)
}
util.LoadSecurityConfiguration()
@@ -115,6 +115,18 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
}()
}
// Start HTTP profiling server if enabled
if mqBrokerOpt.pprofPort != nil && *mqBrokerOpt.pprofPort > 0 {
go func() {
pprofAddr := fmt.Sprintf(":%d", *mqBrokerOpt.pprofPort)
glog.V(0).Infof("MQ Broker pprof server listening on %s", pprofAddr)
glog.V(0).Infof("Access profiling at: http://localhost:%d/debug/pprof/", *mqBrokerOpt.pprofPort)
if err := http.ListenAndServe(pprofAddr, nil); err != nil {
glog.Errorf("pprof server error: %v", err)
}
}()
}
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ip, *mqBrokerOpt.port)
grpcS.Serve(grpcL)
+1 -17
View File
@@ -26,7 +26,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/security"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
"github.com/seaweedfs/seaweedfs/weed/util/version"
)
@@ -60,8 +59,6 @@ type S3Options struct {
concurrentUploadLimitMB *int
concurrentFileUploadLimit *int
enableIam *bool
debug *bool
debugPort *int
}
func init() {
@@ -91,8 +88,6 @@ func init() {
s3StandaloneOptions.concurrentUploadLimitMB = cmdS3.Flag.Int("concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
s3StandaloneOptions.concurrentFileUploadLimit = cmdS3.Flag.Int("concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
s3StandaloneOptions.enableIam = cmdS3.Flag.Bool("iam", true, "enable embedded IAM API on the same port")
s3StandaloneOptions.debug = cmdS3.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
s3StandaloneOptions.debugPort = cmdS3.Flag.Int("debug.port", 6060, "http port for debugging")
}
var cmdS3 = &Command{
@@ -187,9 +182,6 @@ var cmdS3 = &Command{
}
func runS3(cmd *Command, args []string) bool {
if *s3StandaloneOptions.debug {
grace.StartDebugServer(*s3StandaloneOptions.debugPort)
}
util.LoadSecurityConfiguration()
@@ -349,11 +341,6 @@ func (s3opt *S3Options) startS3Server() bool {
go grpcS.Serve(grpcL)
if *s3opt.tlsPrivateKey != "" {
// Check for port conflict when both HTTP and HTTPS are enabled on the same port
if *s3opt.portHttps > 0 && *s3opt.portHttps == *s3opt.port {
glog.Fatalf("S3 API Server error: -s3.port.https (%d) cannot be the same as -s3.port (%d)", *s3opt.portHttps, *s3opt.port)
}
pemfileOptions := pemfile.Options{
CertFile: *s3opt.tlsCertificate,
KeyFile: *s3opt.tlsPrivateKey,
@@ -401,11 +388,8 @@ func (s3opt *S3Options) startS3Server() bool {
}
} else {
glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", version.Version(), *s3opt.portHttps)
s3ApiListenerHttps, s3ApiLocalListenerHttps, err := util.NewIpAndLocalListeners(
s3ApiListenerHttps, s3ApiLocalListenerHttps, _ := util.NewIpAndLocalListeners(
*s3opt.bindIp, *s3opt.portHttps, time.Duration(*s3opt.idleTimeout)*time.Second)
if err != nil {
glog.Fatalf("S3 API HTTPS listener on %s:%d error: %v", *s3opt.bindIp, *s3opt.portHttps, err)
}
if s3ApiLocalListenerHttps != nil {
go func() {
if err = newHttpServer(router, tlsConfig).ServeTLS(s3ApiLocalListenerHttps, "", ""); err != nil {
-7
View File
@@ -72,8 +72,6 @@ type VolumeServerOptions struct {
hasSlowRead *bool
readBufferSizeMB *int
ldbTimeout *int64
debug *bool
debugPort *int
}
func init() {
@@ -112,8 +110,6 @@ func init() {
v.inflightDownloadDataTimeout = cmdVolume.Flag.Duration("inflightDownloadDataTimeout", 60*time.Second, "inflight download data wait timeout of volume servers")
v.hasSlowRead = cmdVolume.Flag.Bool("hasSlowRead", true, "<experimental> if true, this prevents slow reads from blocking other requests, but large file read P99 latency will increase.")
v.readBufferSizeMB = cmdVolume.Flag.Int("readBufferSizeMB", 4, "<experimental> larger values can optimize query performance but will increase some memory usage,Use with hasSlowRead normally.")
v.debug = cmdVolume.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
v.debugPort = cmdVolume.Flag.Int("debug.port", 6060, "http port for debugging")
}
var cmdVolume = &Command{
@@ -133,9 +129,6 @@ var (
)
func runVolume(cmd *Command, args []string) bool {
if *v.debug {
grace.StartDebugServer(*v.debugPort)
}
util.LoadSecurityConfiguration()
@@ -205,4 +205,3 @@ func (q *CleanupQueue) OldestAge() time.Duration {
}
@@ -369,4 +369,3 @@ func TestCleanupQueue_Concurrent(t *testing.T) {
}
+4 -12
View File
@@ -25,20 +25,12 @@ func MapRemoteStorageLocationPathToFullPath(localMountedDir util.FullPath, remot
return localMountedDir.Child(remoteLocationPath[len(remoteMountedLocation.Path):])
}
// CacheRemoteObjectToLocalCluster caches a remote object to the local cluster.
// It returns the updated entry with local chunk locations.
// Parameters remoteConf and remoteLocation are kept for backward compatibility but are not used.
func CacheRemoteObjectToLocalCluster(filerClient filer_pb.FilerClient, remoteConf *remote_pb.RemoteConf, remoteLocation *remote_pb.RemoteStorageLocation, parent util.FullPath, entry *filer_pb.Entry) (*filer_pb.Entry, error) {
var cachedEntry *filer_pb.Entry
err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, cacheErr := client.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
func CacheRemoteObjectToLocalCluster(filerClient filer_pb.FilerClient, remoteConf *remote_pb.RemoteConf, remoteLocation *remote_pb.RemoteStorageLocation, parent util.FullPath, entry *filer_pb.Entry) error {
return filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
Directory: string(parent),
Name: entry.Name,
})
if cacheErr == nil && resp != nil {
cachedEntry = resp.Entry
}
return cacheErr
return err
})
return cachedEntry, err
}
-1
View File
@@ -124,4 +124,3 @@ func MaskAccessKey(accessKeyId string) string {
return accessKeyId
}
-1
View File
@@ -133,4 +133,3 @@ func TestMaskAccessKey(t *testing.T) {
}
}
+1 -7
View File
@@ -9,7 +9,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func (fh *FileHandle) lockForRead(startOffset int64, size int) {
@@ -163,12 +162,7 @@ func (fh *FileHandle) downloadRemoteEntry(entry *LockedEntry) error {
fh.SetEntry(resp.Entry)
// Only update cache if the parent directory is cached
if fh.wfs.metaCache.IsDirectoryCached(util.FullPath(dir)) {
if err := fh.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, resp.Entry)); err != nil {
return fmt.Errorf("update meta cache for %s: %w", fileFullPath, err)
}
}
fh.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, resp.Entry))
return nil
})
-6
View File
@@ -187,9 +187,3 @@ func (mc *MetaCache) Debug() {
debuggable.Debug(os.Stderr)
}
}
// IsDirectoryCached returns true if the directory has been fully cached
// (i.e., all entries have been loaded via EnsureVisited or ReadDir).
func (mc *MetaCache) IsDirectoryCached(dirPath util.FullPath) bool {
return mc.isCachedFn(dirPath)
}
+6 -38
View File
@@ -2,6 +2,7 @@ package mount
import (
"context"
"errors"
"math/rand/v2"
"os"
"path"
@@ -250,7 +251,7 @@ func (wfs *WFS) maybeReadEntry(inode uint64) (path util.FullPath, fh *FileHandle
func (wfs *WFS) maybeLoadEntry(fullpath util.FullPath) (*filer_pb.Entry, fuse.Status) {
// glog.V(3).Infof("read entry cache miss %s", fullpath)
_, name := fullpath.DirAndName()
dir, name := fullpath.DirAndName()
// return a valid entry for the mount root
if string(fullpath) == wfs.option.FilerMountRootPath {
@@ -267,46 +268,13 @@ func (wfs *WFS) maybeLoadEntry(fullpath util.FullPath) (*filer_pb.Entry, fuse.St
}, fuse.OK
}
entry, status := wfs.lookupEntry(fullpath)
if status != fuse.OK {
return nil, status
}
return entry.ToProtoEntry(), fuse.OK
}
// lookupEntry looks up an entry by path, checking the local cache first.
// If the directory is cached, it trusts the cache. Otherwise, it fetches
// directly from the filer without caching the entire directory.
// This avoids the performance issue of listing millions of files just to open one.
func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, fuse.Status) {
dir, _ := fullpath.DirAndName()
// Try to find the entry in the local cache first.
// read from async meta cache
meta_cache.EnsureVisited(wfs.metaCache, wfs, util.FullPath(dir))
cachedEntry, cacheErr := wfs.metaCache.FindEntry(context.Background(), fullpath)
if cacheErr != nil && cacheErr != filer_pb.ErrNotFound {
glog.Errorf("lookupEntry: cache lookup for %s failed: %v", fullpath, cacheErr)
return nil, fuse.EIO
}
if cachedEntry != nil {
glog.V(4).Infof("lookupEntry cache hit %s", fullpath)
return cachedEntry, fuse.OK
}
// If the directory is cached but entry not found, file doesn't exist.
// No need to query the filer again.
if wfs.metaCache.IsDirectoryCached(util.FullPath(dir)) {
glog.V(4).Infof("lookupEntry cache miss (dir cached) %s", fullpath)
if errors.Is(cacheErr, filer_pb.ErrNotFound) {
return nil, fuse.ENOENT
}
// Directory not cached - fetch directly from filer without caching the entire directory.
glog.V(4).Infof("lookupEntry fetching from filer %s", fullpath)
entry, err := filer_pb.GetEntry(context.Background(), wfs, fullpath)
if err != nil {
glog.V(1).Infof("lookupEntry GetEntry %s: %v", fullpath, err)
return nil, fuse.ENOENT
}
return filer.FromPbEntry(dir, entry), fuse.OK
return cachedEntry.ToProtoEntry(), fuse.OK
}
func (wfs *WFS) LookupFn() wdclient.LookupFileIdFunctionType {
+1 -2
View File
@@ -42,8 +42,7 @@ func (wfs *WFS) GetAttr(cancel <-chan struct{}, input *fuse.GetAttrIn, out *fuse
func (wfs *WFS) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
// Check quota including uncommitted writes for real-time enforcement
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
+28 -4
View File
@@ -1,10 +1,14 @@
package mount
import (
"context"
"github.com/hanwen/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// Lookup is called by the kernel when the VFS wants to know
@@ -25,10 +29,30 @@ func (wfs *WFS) Lookup(cancel <-chan struct{}, header *fuse.InHeader, name strin
fullFilePath := dirPath.Child(name)
// Use shared lookup logic that checks cache first, then filer if needed
localEntry, status := wfs.lookupEntry(fullFilePath)
if status != fuse.OK {
return status
visitErr := meta_cache.EnsureVisited(wfs.metaCache, wfs, dirPath)
if visitErr != nil {
glog.Errorf("dir Lookup %s: %v", dirPath, visitErr)
return fuse.EIO
}
localEntry, cacheErr := wfs.metaCache.FindEntry(context.Background(), fullFilePath)
if cacheErr == filer_pb.ErrNotFound {
return fuse.ENOENT
}
if localEntry == nil {
// glog.V(3).Infof("dir Lookup cache miss %s", fullFilePath)
entry, err := filer_pb.GetEntry(context.Background(), wfs, fullFilePath)
if err != nil {
glog.V(1).Infof("dir GetEntry %s: %v", fullFilePath, err)
return fuse.ENOENT
}
localEntry = filer.FromPbEntry(string(dirPath), entry)
} else {
glog.V(4).Infof("dir Lookup cache hit %s", fullFilePath)
}
if localEntry == nil {
return fuse.ENOENT
}
inode := wfs.inodeToPath.Lookup(fullFilePath, localEntry.Crtime.Unix(), localEntry.IsDirectory(), len(localEntry.HardLinkId) > 0, localEntry.Inode, true)
+3 -7
View File
@@ -23,7 +23,7 @@ import (
* */
func (wfs *WFS) Mkdir(cancel <-chan struct{}, in *fuse.MkdirIn, name string, out *fuse.EntryOut) (code fuse.Status) {
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
@@ -68,12 +68,8 @@ func (wfs *WFS) Mkdir(cancel <-chan struct{}, in *fuse.MkdirIn, name string, out
return err
}
// Only cache the entry if the parent directory is already cached.
// This avoids polluting the cache with partial directory data.
if wfs.metaCache.IsDirectoryCached(dirFullPath) {
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("local mkdir dir %s: %w", entryFullPath, err)
}
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("local mkdir dir %s: %v", entryFullPath, err)
}
return nil
+3 -7
View File
@@ -37,7 +37,7 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
*/
func (wfs *WFS) Mknod(cancel <-chan struct{}, in *fuse.MknodIn, name string, out *fuse.EntryOut) (code fuse.Status) {
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
@@ -88,12 +88,8 @@ func (wfs *WFS) Mknod(cancel <-chan struct{}, in *fuse.MknodIn, name string, out
return err
}
// Only cache the entry if the parent directory is already cached.
// This avoids polluting the cache with partial directory data.
if wfs.metaCache.IsDirectoryCached(dirFullPath) {
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("local mknod %s: %w", entryFullPath, err)
}
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("local mknod %s: %v", entryFullPath, err)
}
return nil
+3 -10
View File
@@ -100,9 +100,7 @@ func (wfs *WFS) doFlush(fh *FileHandle, uid, gid uint32) fuse.Status {
// send the data to the OS
glog.V(4).Infof("doFlush %s fh %d", fileFullPath, fh.fh)
// Check quota including uncommitted writes for real-time enforcement
isOverQuota := wfs.IsOverQuotaWithUncommitted()
if !isOverQuota {
if !wfs.IsOverQuota {
if err := fh.dirtyPages.FlushData(); err != nil {
glog.Errorf("%v doFlush: %v", fileFullPath, err)
return fuse.EIO
@@ -113,7 +111,7 @@ func (wfs *WFS) doFlush(fh *FileHandle, uid, gid uint32) fuse.Status {
return fuse.OK
}
if isOverQuota {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
@@ -166,12 +164,7 @@ func (wfs *WFS) doFlush(fh *FileHandle, uid, gid uint32) fuse.Status {
return fmt.Errorf("fh flush create %s: %v", fileFullPath, err)
}
// Only update cache if the parent directory is cached
if wfs.metaCache.IsDirectoryCached(util.FullPath(dir)) {
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("update meta cache for %s: %w", fileFullPath, err)
}
}
wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
return nil
})
+2 -12
View File
@@ -36,8 +36,7 @@ import (
*/
func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (written uint32, code fuse.Status) {
// Check quota including uncommitted writes for real-time enforcement
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return 0, fuse.Status(syscall.ENOSPC)
}
@@ -60,16 +59,7 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
entry.Content = nil
offset := int64(in.Offset)
oldFileSize := int64(entry.Attributes.FileSize)
newFileSize := max(offset+int64(len(data)), oldFileSize)
entry.Attributes.FileSize = uint64(newFileSize)
// Track uncommitted bytes for real-time quota enforcement.
// Only count the new bytes being added beyond the current file size.
if newFileSize > oldFileSize {
wfs.AddUncommittedBytes(newFileSize - oldFileSize)
}
entry.Attributes.FileSize = uint64(max(offset+int64(len(data)), int64(entry.Attributes.FileSize)))
// glog.V(4).Infof("%v write [%d,%d) %d", fh.f.fullpath(), req.Offset, req.Offset+int64(len(req.Data)), len(req.Data))
fh.dirtyPages.AddPage(offset, data, fh.dirtyPages.writerPattern.IsSequentialMode(), tsNs)
+3 -15
View File
@@ -2,7 +2,6 @@ package mount
import (
"context"
"fmt"
"syscall"
"time"
@@ -11,7 +10,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
/*
@@ -27,7 +25,7 @@ When creating a link:
/** Create a hard link to a file */
func (wfs *WFS) Link(cancel <-chan struct{}, in *fuse.LinkIn, name string, out *fuse.EntryOut) (code fuse.Status) {
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
@@ -93,23 +91,13 @@ func (wfs *WFS) Link(cancel <-chan struct{}, in *fuse.LinkIn, name string, out *
if err := filer_pb.UpdateEntry(context.Background(), client, updateOldEntryRequest); err != nil {
return err
}
// Only update cache if the directory is cached
if wfs.metaCache.IsDirectoryCached(util.FullPath(updateOldEntryRequest.Directory)) {
if err := wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(updateOldEntryRequest.Directory, updateOldEntryRequest.Entry)); err != nil {
return fmt.Errorf("update meta cache for %s: %w", oldEntryPath, err)
}
}
wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(updateOldEntryRequest.Directory, updateOldEntryRequest.Entry))
if err := filer_pb.CreateEntry(context.Background(), client, request); err != nil {
return err
}
// Only cache the entry if the parent directory is already cached.
if wfs.metaCache.IsDirectoryCached(newParentPath) {
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("insert meta cache for %s: %w", newParentPath.Child(name), err)
}
}
wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
return nil
})
+3 -5
View File
@@ -146,11 +146,9 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
return err
}
// Only update cache if the parent directory is cached
if wfs.metaCache.IsDirectoryCached(util.FullPath(dir)) {
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("update meta cache for %s: %w", fileFullPath, err)
}
// Update meta cache
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("update meta cache for %s: %w", fileFullPath, err)
}
glog.V(3).Infof("flushed metadata for %s with %d chunks", fileFullPath, len(entry.GetChunks()))
+27 -123
View File
@@ -3,148 +3,52 @@ package mount
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"time"
)
const (
// Default quota check interval
defaultQuotaCheckInterval = 61 * time.Second
// Faster check interval when approaching quota (within 10%)
fastQuotaCheckInterval = 5 * time.Second
// Threshold for switching to fast check (90% of quota)
quotaWarningThreshold = 0.9
)
// uncommittedBytes tracks bytes written locally but not yet reflected in filer statistics.
// This is used for real-time quota enforcement between periodic checks.
var uncommittedBytes int64
// AddUncommittedBytes adds bytes to the uncommitted write counter.
// Called when data is written to the mount.
func (wfs *WFS) AddUncommittedBytes(bytes int64) {
if wfs.option.Quota > 0 {
atomic.AddInt64(&uncommittedBytes, bytes)
}
}
// SubtractUncommittedBytes subtracts bytes from the uncommitted counter.
// Called when data is flushed to filer or on quota refresh.
func (wfs *WFS) SubtractUncommittedBytes(bytes int64) {
if wfs.option.Quota > 0 {
current := atomic.AddInt64(&uncommittedBytes, -bytes)
// Don't let it go negative
if current < 0 {
atomic.StoreInt64(&uncommittedBytes, 0)
}
}
}
// ResetUncommittedBytes resets the counter after a quota check syncs with filer.
func (wfs *WFS) ResetUncommittedBytes() {
atomic.StoreInt64(&uncommittedBytes, 0)
}
// GetUncommittedBytes returns the current uncommitted byte count.
func (wfs *WFS) GetUncommittedBytes() int64 {
return atomic.LoadInt64(&uncommittedBytes)
}
// IsOverQuotaWithUncommitted checks if quota is exceeded including uncommitted writes.
// This provides real-time quota enforcement between periodic checks.
func (wfs *WFS) IsOverQuotaWithUncommitted() bool {
if wfs.option.Quota <= 0 {
return false
}
if wfs.IsOverQuota {
return true
}
// Check if uncommitted writes would exceed quota
uncommitted := atomic.LoadInt64(&uncommittedBytes)
usedSize := int64(wfs.stats.UsedSize)
return (usedSize + uncommitted) > wfs.option.Quota
}
func (wfs *WFS) loopCheckQuota() {
// Skip quota checking if no quota is set
if wfs.option.Quota <= 0 {
return
}
// Check quota immediately on mount, don't wait for first interval
wfs.checkQuotaOnce()
for {
// Adaptive interval: check more frequently when approaching quota
interval := wfs.getQuotaCheckInterval()
time.Sleep(interval)
time.Sleep(61 * time.Second)
if wfs.option.Quota <= 0 {
continue
}
wfs.checkQuotaOnce()
}
}
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
// getQuotaCheckInterval returns the check interval based on current usage.
// Returns a shorter interval when approaching quota limit.
func (wfs *WFS) getQuotaCheckInterval() time.Duration {
if wfs.option.Quota <= 0 {
return defaultQuotaCheckInterval
}
request := &filer_pb.StatisticsRequest{
Collection: wfs.option.Collection,
Replication: wfs.option.Replication,
Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
DiskType: string(wfs.option.DiskType),
}
usedSize := int64(wfs.stats.UsedSize)
uncommitted := atomic.LoadInt64(&uncommittedBytes)
totalUsed := usedSize + uncommitted
resp, err := client.Statistics(context.Background(), request)
if err != nil {
glog.V(0).Infof("reading quota usage %v: %v", request, err)
return err
}
glog.V(4).Infof("read quota usage: %+v", resp)
// If we're at 90% or more of quota, check more frequently
if float64(totalUsed) >= float64(wfs.option.Quota)*quotaWarningThreshold {
return fastQuotaCheckInterval
}
return defaultQuotaCheckInterval
}
isOverQuota := int64(resp.UsedSize) > wfs.option.Quota
if isOverQuota && !wfs.IsOverQuota {
glog.Warningf("Quota Exceeded! quota:%d used:%d", wfs.option.Quota, resp.UsedSize)
} else if !isOverQuota && wfs.IsOverQuota {
glog.Warningf("Within quota limit! quota:%d used:%d", wfs.option.Quota, resp.UsedSize)
}
wfs.IsOverQuota = isOverQuota
func (wfs *WFS) checkQuotaOnce() {
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return nil
})
request := &filer_pb.StatisticsRequest{
Collection: wfs.option.Collection,
Replication: wfs.option.Replication,
Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
DiskType: string(wfs.option.DiskType),
}
resp, err := client.Statistics(context.Background(), request)
if err != nil {
glog.V(0).Infof("reading quota usage %v: %v", request, err)
return err
glog.Warningf("read quota usage: %v", err)
}
glog.V(4).Infof("read quota usage: %+v", resp)
// Update the stats cache with latest filer data
wfs.stats.UsedSize = resp.UsedSize
wfs.stats.TotalSize = resp.TotalSize
// Reset uncommitted counter since we now have fresh data from filer
wfs.ResetUncommittedBytes()
isOverQuota := int64(resp.UsedSize) > wfs.option.Quota
if isOverQuota && !wfs.IsOverQuota {
glog.Warningf("Quota Exceeded! quota:%d used:%d", wfs.option.Quota, resp.UsedSize)
} else if !isOverQuota && wfs.IsOverQuota {
glog.Warningf("Within quota limit! quota:%d used:%d", wfs.option.Quota, resp.UsedSize)
}
wfs.IsOverQuota = isOverQuota
return nil
})
if err != nil {
glog.Warningf("read quota usage: %v", err)
}
}
-218
View File
@@ -1,218 +0,0 @@
package mount
import (
"sync/atomic"
"testing"
)
func TestUncommittedBytesTracking(t *testing.T) {
// Reset the global counter
atomic.StoreInt64(&uncommittedBytes, 0)
wfs := &WFS{
option: &Option{
Quota: 100 * 1024 * 1024, // 100MB
},
}
// Test AddUncommittedBytes
wfs.AddUncommittedBytes(1024)
if got := wfs.GetUncommittedBytes(); got != 1024 {
t.Errorf("AddUncommittedBytes: got %d, want 1024", got)
}
// Test accumulation
wfs.AddUncommittedBytes(2048)
if got := wfs.GetUncommittedBytes(); got != 3072 {
t.Errorf("AddUncommittedBytes accumulation: got %d, want 3072", got)
}
// Test SubtractUncommittedBytes
wfs.SubtractUncommittedBytes(1024)
if got := wfs.GetUncommittedBytes(); got != 2048 {
t.Errorf("SubtractUncommittedBytes: got %d, want 2048", got)
}
// Test ResetUncommittedBytes
wfs.ResetUncommittedBytes()
if got := wfs.GetUncommittedBytes(); got != 0 {
t.Errorf("ResetUncommittedBytes: got %d, want 0", got)
}
}
func TestUncommittedBytesDoesNotGoNegative(t *testing.T) {
atomic.StoreInt64(&uncommittedBytes, 0)
wfs := &WFS{
option: &Option{
Quota: 100 * 1024 * 1024,
},
}
wfs.AddUncommittedBytes(100)
wfs.SubtractUncommittedBytes(200) // Try to subtract more than available
if got := wfs.GetUncommittedBytes(); got < 0 {
t.Errorf("uncommittedBytes went negative: got %d", got)
}
}
func TestIsOverQuotaWithUncommitted(t *testing.T) {
atomic.StoreInt64(&uncommittedBytes, 0)
tests := []struct {
name string
quota int64
usedSize uint64
uncommitted int64
isOverQuota bool
want bool
}{
{
name: "no quota set",
quota: 0,
usedSize: 1000,
uncommitted: 1000,
isOverQuota: false,
want: false,
},
{
name: "under quota",
quota: 1000,
usedSize: 400,
uncommitted: 400,
isOverQuota: false,
want: false,
},
{
name: "over quota with uncommitted",
quota: 1000,
usedSize: 600,
uncommitted: 500,
isOverQuota: false,
want: true,
},
{
name: "already over quota flag set",
quota: 1000,
usedSize: 500,
uncommitted: 0,
isOverQuota: true,
want: true,
},
{
name: "exactly at quota",
quota: 1000,
usedSize: 500,
uncommitted: 500,
isOverQuota: false,
want: false,
},
{
name: "one byte over quota",
quota: 1000,
usedSize: 500,
uncommitted: 501,
isOverQuota: false,
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
atomic.StoreInt64(&uncommittedBytes, tt.uncommitted)
wfs := &WFS{
option: &Option{
Quota: tt.quota,
},
IsOverQuota: tt.isOverQuota,
}
wfs.stats.UsedSize = tt.usedSize
got := wfs.IsOverQuotaWithUncommitted()
if got != tt.want {
t.Errorf("IsOverQuotaWithUncommitted() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetQuotaCheckInterval(t *testing.T) {
atomic.StoreInt64(&uncommittedBytes, 0)
tests := []struct {
name string
quota int64
usedSize uint64
uncommitted int64
wantFast bool
}{
{
name: "no quota",
quota: 0,
usedSize: 0,
uncommitted: 0,
wantFast: false,
},
{
name: "under 90% threshold",
quota: 1000,
usedSize: 800,
uncommitted: 0,
wantFast: false,
},
{
name: "at 90% threshold",
quota: 1000,
usedSize: 900,
uncommitted: 0,
wantFast: true,
},
{
name: "over 90% with uncommitted",
quota: 1000,
usedSize: 500,
uncommitted: 410,
wantFast: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
atomic.StoreInt64(&uncommittedBytes, tt.uncommitted)
wfs := &WFS{
option: &Option{
Quota: tt.quota,
},
}
wfs.stats.UsedSize = tt.usedSize
got := wfs.getQuotaCheckInterval()
if tt.wantFast && got != fastQuotaCheckInterval {
t.Errorf("getQuotaCheckInterval() = %v, want fast interval %v", got, fastQuotaCheckInterval)
}
if !tt.wantFast && got != defaultQuotaCheckInterval {
t.Errorf("getQuotaCheckInterval() = %v, want default interval %v", got, defaultQuotaCheckInterval)
}
})
}
}
func TestNoQuotaTrackingWhenDisabled(t *testing.T) {
atomic.StoreInt64(&uncommittedBytes, 0)
wfs := &WFS{
option: &Option{
Quota: 0, // No quota
},
}
// Should not track when quota is disabled
wfs.AddUncommittedBytes(1000)
if got := wfs.GetUncommittedBytes(); got != 0 {
t.Errorf("Should not track uncommitted bytes when quota disabled: got %d", got)
}
}
+1 -1
View File
@@ -132,7 +132,7 @@ const (
)
func (wfs *WFS) Rename(cancel <-chan struct{}, in *fuse.RenameIn, oldName string, newName string) (code fuse.Status) {
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
+2 -7
View File
@@ -17,7 +17,7 @@ import (
/** Create a symbolic link */
func (wfs *WFS) Symlink(cancel <-chan struct{}, header *fuse.InHeader, target string, name string, out *fuse.EntryOut) (code fuse.Status) {
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
if s := checkName(name); s != fuse.OK {
@@ -57,12 +57,7 @@ func (wfs *WFS) Symlink(cancel <-chan struct{}, header *fuse.InHeader, target st
return fmt.Errorf("symlink %s: %v", entryFullPath, err)
}
// Only cache the entry if the parent directory is already cached.
if wfs.metaCache.IsDirectoryCached(dirPath) {
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
return fmt.Errorf("insert meta cache for symlink %s: %w", entryFullPath, err)
}
}
wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
return nil
})
+1 -1
View File
@@ -83,7 +83,7 @@ func (wfs *WFS) SetXAttr(cancel <-chan struct{}, input *fuse.SetXAttrIn, attr st
return fuse.Status(syscall.ENOTSUP)
}
if wfs.IsOverQuotaWithUncommitted() {
if wfs.IsOverQuota {
return fuse.Status(syscall.ENOSPC)
}
+1 -2
View File
@@ -12,7 +12,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
@@ -143,7 +142,7 @@ func NewMessageBroker(option *MessageQueueBrokerOption, grpcDialOption grpc.Dial
mqBroker.lockAsBalancer = lockClient.StartLongLivedLock(pub_balancer.LockBrokerBalancer, string(self), func(newLockOwner string) {
glog.V(0).Infof("broker %s found balanacer %s", self, newLockOwner)
newBrokerBalancerCh <- newLockOwner
}, lock_manager.RenewInterval)
})
mqBroker.KeepConnectedToBrokerBalancer(newBrokerBalancerCh)
}()
@@ -12,7 +12,6 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"github.com/seaweedfs/seaweedfs/weed/glog"
@@ -181,7 +180,6 @@ func (cr *CoordinatorRegistry) startLeaderElection() {
GatewayLeaderLockKey,
cr.gatewayAddress,
cr.onLeadershipChange,
lock_manager.RenewInterval,
)
// Wait for shutdown
+5 -43
View File
@@ -19,9 +19,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
@@ -35,11 +33,6 @@ const (
// gRPC keepalive settings - must be consistent between client and server
GrpcKeepAliveTime = 60 * time.Second // ping interval when no activity
GrpcKeepAliveTimeout = 20 * time.Second // ping timeout
// Connection recycling for Docker Swarm environments
// Forces connections to be recycled periodically to handle DNS changes
GrpcMaxConnectionAge = 5 * time.Minute // max time a connection may exist
GrpcMaxConnectionAgeGrace = 30 * time.Second // grace period for RPCs to complete
)
var (
@@ -63,10 +56,9 @@ func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
var options []grpc.ServerOption
options = append(options,
grpc.KeepaliveParams(keepalive.ServerParameters{
Time: GrpcKeepAliveTime, // server pings client if no activity for this long
Timeout: GrpcKeepAliveTimeout, // ping timeout
MaxConnectionAge: GrpcMaxConnectionAge, // max connection age for Docker Swarm DNS refresh
MaxConnectionAgeGrace: GrpcMaxConnectionAgeGrace, // grace period for in-flight RPCs
Time: GrpcKeepAliveTime, // server pings client if no activity for this long
Timeout: GrpcKeepAliveTimeout, // ping timeout
// MaxConnectionAge: 10 * time.Hour,
}),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: GrpcKeepAliveTime, // min time a client should wait before sending a ping
@@ -120,11 +112,9 @@ func getOrCreateConnection(address string, waitForReady bool, opts ...grpc.DialO
existingConnection, found := grpcClients[address]
if found {
glog.V(3).Infof("gRPC cache hit for %s (version %d)", address, existingConnection.version)
return existingConnection, nil
}
glog.V(2).Infof("Creating new gRPC connection to %s", address)
ctx := context.Background()
grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
if err != nil {
@@ -137,7 +127,6 @@ func getOrCreateConnection(address string, waitForReady bool, opts ...grpc.DialO
0,
}
grpcClients[address] = vgc
glog.V(2).Infof("New gRPC connection established to %s (version %d)", address, vgc.version)
return vgc, nil
}
@@ -174,33 +163,6 @@ func requestIDUnaryInterceptor() grpc.UnaryServerInterceptor {
}
}
// shouldInvalidateConnection checks if an error indicates the cached connection should be invalidated
func shouldInvalidateConnection(err error) bool {
if err == nil {
return false
}
// Check gRPC status codes first (more reliable)
if s, ok := status.FromError(err); ok {
code := s.Code()
switch code {
case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded, codes.Aborted, codes.Internal:
return true
}
}
// Fall back to string matching for transport-level errors not captured by gRPC codes
errStr := err.Error()
errLower := strings.ToLower(errStr)
return strings.Contains(errLower, "transport") ||
strings.Contains(errLower, "connection closed") ||
strings.Contains(errLower, "dns") ||
strings.Contains(errLower, "connection refused") ||
strings.Contains(errLower, "no route to host") ||
strings.Contains(errLower, "network is unreachable") ||
strings.Contains(errLower, "connection reset")
}
// WithGrpcClient In streamingMode, always use a fresh connection. Otherwise, try to reuse an existing connection.
func WithGrpcClient(streamingMode bool, signature int32, fn func(*grpc.ClientConn) error, address string, waitForReady bool, opts ...grpc.DialOption) error {
@@ -211,11 +173,11 @@ func WithGrpcClient(streamingMode bool, signature int32, fn func(*grpc.ClientCon
}
executionErr := fn(vgc.ClientConn)
if executionErr != nil {
if shouldInvalidateConnection(executionErr) {
if strings.Contains(executionErr.Error(), "transport") ||
strings.Contains(executionErr.Error(), "connection closed") {
grpcClientsLock.Lock()
if t, ok := grpcClients[address]; ok {
if t.version == vgc.version {
glog.V(1).Infof("Removing cached gRPC connection to %s due to error: %v", address, executionErr)
vgc.Close()
delete(grpcClients, address)
}
-11
View File
@@ -51,8 +51,6 @@ service Seaweed {
}
rpc RaftRemoveServer (RaftRemoveServerRequest) returns (RaftRemoveServerResponse) {
}
rpc RaftLeadershipTransfer (RaftLeadershipTransferRequest) returns (RaftLeadershipTransferResponse) {
}
rpc VolumeGrow (VolumeGrowRequest) returns (VolumeGrowResponse) {
}
}
@@ -445,14 +443,5 @@ message RaftListClusterServersResponse {
repeated ClusterServers cluster_servers = 1;
}
message RaftLeadershipTransferRequest {
string target_id = 1; // Optional: target server ID. If empty, transfers to any eligible follower
string target_address = 2; // Optional: target server address. Required if target_id is specified
}
message RaftLeadershipTransferResponse {
string previous_leader = 1;
string new_leader = 2;
}
message VolumeGrowResponse {
}
+67 -183
View File
@@ -3690,110 +3690,6 @@ func (x *RaftListClusterServersResponse) GetClusterServers() []*RaftListClusterS
return nil
}
type RaftLeadershipTransferRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
TargetId string `protobuf:"bytes,1,opt,name=target_id,json=targetId,proto3" json:"target_id,omitempty"` // Optional: target server ID. If empty, transfers to any eligible follower
TargetAddress string `protobuf:"bytes,2,opt,name=target_address,json=targetAddress,proto3" json:"target_address,omitempty"` // Optional: target server address. Required if target_id is specified
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RaftLeadershipTransferRequest) Reset() {
*x = RaftLeadershipTransferRequest{}
mi := &file_master_proto_msgTypes[58]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RaftLeadershipTransferRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RaftLeadershipTransferRequest) ProtoMessage() {}
func (x *RaftLeadershipTransferRequest) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[58]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RaftLeadershipTransferRequest.ProtoReflect.Descriptor instead.
func (*RaftLeadershipTransferRequest) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{58}
}
func (x *RaftLeadershipTransferRequest) GetTargetId() string {
if x != nil {
return x.TargetId
}
return ""
}
func (x *RaftLeadershipTransferRequest) GetTargetAddress() string {
if x != nil {
return x.TargetAddress
}
return ""
}
type RaftLeadershipTransferResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
PreviousLeader string `protobuf:"bytes,1,opt,name=previous_leader,json=previousLeader,proto3" json:"previous_leader,omitempty"`
NewLeader string `protobuf:"bytes,2,opt,name=new_leader,json=newLeader,proto3" json:"new_leader,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RaftLeadershipTransferResponse) Reset() {
*x = RaftLeadershipTransferResponse{}
mi := &file_master_proto_msgTypes[59]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RaftLeadershipTransferResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RaftLeadershipTransferResponse) ProtoMessage() {}
func (x *RaftLeadershipTransferResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[59]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RaftLeadershipTransferResponse.ProtoReflect.Descriptor instead.
func (*RaftLeadershipTransferResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{59}
}
func (x *RaftLeadershipTransferResponse) GetPreviousLeader() string {
if x != nil {
return x.PreviousLeader
}
return ""
}
func (x *RaftLeadershipTransferResponse) GetNewLeader() string {
if x != nil {
return x.NewLeader
}
return ""
}
type VolumeGrowResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -3802,7 +3698,7 @@ type VolumeGrowResponse struct {
func (x *VolumeGrowResponse) Reset() {
*x = VolumeGrowResponse{}
mi := &file_master_proto_msgTypes[60]
mi := &file_master_proto_msgTypes[58]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3814,7 +3710,7 @@ func (x *VolumeGrowResponse) String() string {
func (*VolumeGrowResponse) ProtoMessage() {}
func (x *VolumeGrowResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[60]
mi := &file_master_proto_msgTypes[58]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3827,7 +3723,7 @@ func (x *VolumeGrowResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use VolumeGrowResponse.ProtoReflect.Descriptor instead.
func (*VolumeGrowResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{60}
return file_master_proto_rawDescGZIP(), []int{58}
}
type SuperBlockExtra_ErasureCoding struct {
@@ -3841,7 +3737,7 @@ type SuperBlockExtra_ErasureCoding struct {
func (x *SuperBlockExtra_ErasureCoding) Reset() {
*x = SuperBlockExtra_ErasureCoding{}
mi := &file_master_proto_msgTypes[63]
mi := &file_master_proto_msgTypes[61]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3853,7 +3749,7 @@ func (x *SuperBlockExtra_ErasureCoding) String() string {
func (*SuperBlockExtra_ErasureCoding) ProtoMessage() {}
func (x *SuperBlockExtra_ErasureCoding) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[63]
mi := &file_master_proto_msgTypes[61]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3902,7 +3798,7 @@ type LookupVolumeResponse_VolumeIdLocation struct {
func (x *LookupVolumeResponse_VolumeIdLocation) Reset() {
*x = LookupVolumeResponse_VolumeIdLocation{}
mi := &file_master_proto_msgTypes[64]
mi := &file_master_proto_msgTypes[62]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3914,7 +3810,7 @@ func (x *LookupVolumeResponse_VolumeIdLocation) String() string {
func (*LookupVolumeResponse_VolumeIdLocation) ProtoMessage() {}
func (x *LookupVolumeResponse_VolumeIdLocation) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[64]
mi := &file_master_proto_msgTypes[62]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3968,7 +3864,7 @@ type LookupEcVolumeResponse_EcShardIdLocation struct {
func (x *LookupEcVolumeResponse_EcShardIdLocation) Reset() {
*x = LookupEcVolumeResponse_EcShardIdLocation{}
mi := &file_master_proto_msgTypes[69]
mi := &file_master_proto_msgTypes[67]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3980,7 +3876,7 @@ func (x *LookupEcVolumeResponse_EcShardIdLocation) String() string {
func (*LookupEcVolumeResponse_EcShardIdLocation) ProtoMessage() {}
func (x *LookupEcVolumeResponse_EcShardIdLocation) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[69]
mi := &file_master_proto_msgTypes[67]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4023,7 +3919,7 @@ type ListClusterNodesResponse_ClusterNode struct {
func (x *ListClusterNodesResponse_ClusterNode) Reset() {
*x = ListClusterNodesResponse_ClusterNode{}
mi := &file_master_proto_msgTypes[70]
mi := &file_master_proto_msgTypes[68]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4035,7 +3931,7 @@ func (x *ListClusterNodesResponse_ClusterNode) String() string {
func (*ListClusterNodesResponse_ClusterNode) ProtoMessage() {}
func (x *ListClusterNodesResponse_ClusterNode) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[70]
mi := &file_master_proto_msgTypes[68]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4098,7 +3994,7 @@ type RaftListClusterServersResponse_ClusterServers struct {
func (x *RaftListClusterServersResponse_ClusterServers) Reset() {
*x = RaftListClusterServersResponse_ClusterServers{}
mi := &file_master_proto_msgTypes[71]
mi := &file_master_proto_msgTypes[69]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4110,7 +4006,7 @@ func (x *RaftListClusterServersResponse_ClusterServers) String() string {
func (*RaftListClusterServersResponse_ClusterServers) ProtoMessage() {}
func (x *RaftListClusterServersResponse_ClusterServers) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[71]
mi := &file_master_proto_msgTypes[69]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4509,15 +4405,8 @@ const file_master_proto_rawDesc = "" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x18\n" +
"\aaddress\x18\x02 \x01(\tR\aaddress\x12\x1a\n" +
"\bsuffrage\x18\x03 \x01(\tR\bsuffrage\x12\x1a\n" +
"\bisLeader\x18\x04 \x01(\bR\bisLeader\"c\n" +
"\x1dRaftLeadershipTransferRequest\x12\x1b\n" +
"\ttarget_id\x18\x01 \x01(\tR\btargetId\x12%\n" +
"\x0etarget_address\x18\x02 \x01(\tR\rtargetAddress\"h\n" +
"\x1eRaftLeadershipTransferResponse\x12'\n" +
"\x0fprevious_leader\x18\x01 \x01(\tR\x0epreviousLeader\x12\x1d\n" +
"\n" +
"new_leader\x18\x02 \x01(\tR\tnewLeader\"\x14\n" +
"\x12VolumeGrowResponse2\xc6\x10\n" +
"\bisLeader\x18\x04 \x01(\bR\bisLeader\"\x14\n" +
"\x12VolumeGrowResponse2\xd5\x0f\n" +
"\aSeaweed\x12I\n" +
"\rSendHeartbeat\x12\x14.master_pb.Heartbeat\x1a\x1c.master_pb.HeartbeatResponse\"\x00(\x010\x01\x12X\n" +
"\rKeepConnected\x12\x1f.master_pb.KeepConnectedRequest\x1a .master_pb.KeepConnectedResponse\"\x00(\x010\x01\x12Q\n" +
@@ -4542,8 +4431,7 @@ const file_master_proto_rawDesc = "" +
"\x04Ping\x12\x16.master_pb.PingRequest\x1a\x17.master_pb.PingResponse\"\x00\x12o\n" +
"\x16RaftListClusterServers\x12(.master_pb.RaftListClusterServersRequest\x1a).master_pb.RaftListClusterServersResponse\"\x00\x12T\n" +
"\rRaftAddServer\x12\x1f.master_pb.RaftAddServerRequest\x1a .master_pb.RaftAddServerResponse\"\x00\x12]\n" +
"\x10RaftRemoveServer\x12\".master_pb.RaftRemoveServerRequest\x1a#.master_pb.RaftRemoveServerResponse\"\x00\x12o\n" +
"\x16RaftLeadershipTransfer\x12(.master_pb.RaftLeadershipTransferRequest\x1a).master_pb.RaftLeadershipTransferResponse\"\x00\x12K\n" +
"\x10RaftRemoveServer\x12\".master_pb.RaftRemoveServerRequest\x1a#.master_pb.RaftRemoveServerResponse\"\x00\x12K\n" +
"\n" +
"VolumeGrow\x12\x1c.master_pb.VolumeGrowRequest\x1a\x1d.master_pb.VolumeGrowResponse\"\x00B2Z0github.com/seaweedfs/seaweedfs/weed/pb/master_pbb\x06proto3"
@@ -4559,7 +4447,7 @@ func file_master_proto_rawDescGZIP() []byte {
return file_master_proto_rawDescData
}
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 72)
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 70)
var file_master_proto_goTypes = []any{
(*Heartbeat)(nil), // 0: master_pb.Heartbeat
(*HeartbeatResponse)(nil), // 1: master_pb.HeartbeatResponse
@@ -4619,20 +4507,18 @@ var file_master_proto_goTypes = []any{
(*RaftRemoveServerResponse)(nil), // 55: master_pb.RaftRemoveServerResponse
(*RaftListClusterServersRequest)(nil), // 56: master_pb.RaftListClusterServersRequest
(*RaftListClusterServersResponse)(nil), // 57: master_pb.RaftListClusterServersResponse
(*RaftLeadershipTransferRequest)(nil), // 58: master_pb.RaftLeadershipTransferRequest
(*RaftLeadershipTransferResponse)(nil), // 59: master_pb.RaftLeadershipTransferResponse
(*VolumeGrowResponse)(nil), // 60: master_pb.VolumeGrowResponse
nil, // 61: master_pb.Heartbeat.MaxVolumeCountsEntry
nil, // 62: master_pb.StorageBackend.PropertiesEntry
(*SuperBlockExtra_ErasureCoding)(nil), // 63: master_pb.SuperBlockExtra.ErasureCoding
(*LookupVolumeResponse_VolumeIdLocation)(nil), // 64: master_pb.LookupVolumeResponse.VolumeIdLocation
nil, // 65: master_pb.DataNodeInfo.DiskInfosEntry
nil, // 66: master_pb.RackInfo.DiskInfosEntry
nil, // 67: master_pb.DataCenterInfo.DiskInfosEntry
nil, // 68: master_pb.TopologyInfo.DiskInfosEntry
(*LookupEcVolumeResponse_EcShardIdLocation)(nil), // 69: master_pb.LookupEcVolumeResponse.EcShardIdLocation
(*ListClusterNodesResponse_ClusterNode)(nil), // 70: master_pb.ListClusterNodesResponse.ClusterNode
(*RaftListClusterServersResponse_ClusterServers)(nil), // 71: master_pb.RaftListClusterServersResponse.ClusterServers
(*VolumeGrowResponse)(nil), // 58: master_pb.VolumeGrowResponse
nil, // 59: master_pb.Heartbeat.MaxVolumeCountsEntry
nil, // 60: master_pb.StorageBackend.PropertiesEntry
(*SuperBlockExtra_ErasureCoding)(nil), // 61: master_pb.SuperBlockExtra.ErasureCoding
(*LookupVolumeResponse_VolumeIdLocation)(nil), // 62: master_pb.LookupVolumeResponse.VolumeIdLocation
nil, // 63: master_pb.DataNodeInfo.DiskInfosEntry
nil, // 64: master_pb.RackInfo.DiskInfosEntry
nil, // 65: master_pb.DataCenterInfo.DiskInfosEntry
nil, // 66: master_pb.TopologyInfo.DiskInfosEntry
(*LookupEcVolumeResponse_EcShardIdLocation)(nil), // 67: master_pb.LookupEcVolumeResponse.EcShardIdLocation
(*ListClusterNodesResponse_ClusterNode)(nil), // 68: master_pb.ListClusterNodesResponse.ClusterNode
(*RaftListClusterServersResponse_ClusterServers)(nil), // 69: master_pb.RaftListClusterServersResponse.ClusterServers
}
var file_master_proto_depIdxs = []int32{
2, // 0: master_pb.Heartbeat.volumes:type_name -> master_pb.VolumeInformationMessage
@@ -4641,30 +4527,30 @@ var file_master_proto_depIdxs = []int32{
4, // 3: master_pb.Heartbeat.ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
4, // 4: master_pb.Heartbeat.new_ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
4, // 5: master_pb.Heartbeat.deleted_ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
61, // 6: master_pb.Heartbeat.max_volume_counts:type_name -> master_pb.Heartbeat.MaxVolumeCountsEntry
59, // 6: master_pb.Heartbeat.max_volume_counts:type_name -> master_pb.Heartbeat.MaxVolumeCountsEntry
5, // 7: master_pb.HeartbeatResponse.storage_backends:type_name -> master_pb.StorageBackend
62, // 8: master_pb.StorageBackend.properties:type_name -> master_pb.StorageBackend.PropertiesEntry
63, // 9: master_pb.SuperBlockExtra.erasure_coding:type_name -> master_pb.SuperBlockExtra.ErasureCoding
60, // 8: master_pb.StorageBackend.properties:type_name -> master_pb.StorageBackend.PropertiesEntry
61, // 9: master_pb.SuperBlockExtra.erasure_coding:type_name -> master_pb.SuperBlockExtra.ErasureCoding
9, // 10: master_pb.KeepConnectedResponse.volume_location:type_name -> master_pb.VolumeLocation
10, // 11: master_pb.KeepConnectedResponse.cluster_node_update:type_name -> master_pb.ClusterNodeUpdate
64, // 12: master_pb.LookupVolumeResponse.volume_id_locations:type_name -> master_pb.LookupVolumeResponse.VolumeIdLocation
62, // 12: master_pb.LookupVolumeResponse.volume_id_locations:type_name -> master_pb.LookupVolumeResponse.VolumeIdLocation
14, // 13: master_pb.AssignResponse.replicas:type_name -> master_pb.Location
14, // 14: master_pb.AssignResponse.location:type_name -> master_pb.Location
20, // 15: master_pb.CollectionListResponse.collections:type_name -> master_pb.Collection
2, // 16: master_pb.DiskInfo.volume_infos:type_name -> master_pb.VolumeInformationMessage
4, // 17: master_pb.DiskInfo.ec_shard_infos:type_name -> master_pb.VolumeEcShardInformationMessage
65, // 18: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
63, // 18: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
26, // 19: master_pb.RackInfo.data_node_infos:type_name -> master_pb.DataNodeInfo
66, // 20: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
64, // 20: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
27, // 21: master_pb.DataCenterInfo.rack_infos:type_name -> master_pb.RackInfo
67, // 22: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
65, // 22: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
28, // 23: master_pb.TopologyInfo.data_center_infos:type_name -> master_pb.DataCenterInfo
68, // 24: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
66, // 24: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
29, // 25: master_pb.VolumeListResponse.topology_info:type_name -> master_pb.TopologyInfo
69, // 26: master_pb.LookupEcVolumeResponse.shard_id_locations:type_name -> master_pb.LookupEcVolumeResponse.EcShardIdLocation
67, // 26: master_pb.LookupEcVolumeResponse.shard_id_locations:type_name -> master_pb.LookupEcVolumeResponse.EcShardIdLocation
5, // 27: master_pb.GetMasterConfigurationResponse.storage_backends:type_name -> master_pb.StorageBackend
70, // 28: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode
71, // 29: master_pb.RaftListClusterServersResponse.cluster_servers:type_name -> master_pb.RaftListClusterServersResponse.ClusterServers
68, // 28: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode
69, // 29: master_pb.RaftListClusterServersResponse.cluster_servers:type_name -> master_pb.RaftListClusterServersResponse.ClusterServers
14, // 30: master_pb.LookupVolumeResponse.VolumeIdLocation.locations:type_name -> master_pb.Location
25, // 31: master_pb.DataNodeInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
25, // 32: master_pb.RackInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
@@ -4693,34 +4579,32 @@ var file_master_proto_depIdxs = []int32{
56, // 55: master_pb.Seaweed.RaftListClusterServers:input_type -> master_pb.RaftListClusterServersRequest
52, // 56: master_pb.Seaweed.RaftAddServer:input_type -> master_pb.RaftAddServerRequest
54, // 57: master_pb.Seaweed.RaftRemoveServer:input_type -> master_pb.RaftRemoveServerRequest
58, // 58: master_pb.Seaweed.RaftLeadershipTransfer:input_type -> master_pb.RaftLeadershipTransferRequest
16, // 59: master_pb.Seaweed.VolumeGrow:input_type -> master_pb.VolumeGrowRequest
1, // 60: master_pb.Seaweed.SendHeartbeat:output_type -> master_pb.HeartbeatResponse
11, // 61: master_pb.Seaweed.KeepConnected:output_type -> master_pb.KeepConnectedResponse
13, // 62: master_pb.Seaweed.LookupVolume:output_type -> master_pb.LookupVolumeResponse
17, // 63: master_pb.Seaweed.Assign:output_type -> master_pb.AssignResponse
17, // 64: master_pb.Seaweed.StreamAssign:output_type -> master_pb.AssignResponse
19, // 65: master_pb.Seaweed.Statistics:output_type -> master_pb.StatisticsResponse
22, // 66: master_pb.Seaweed.CollectionList:output_type -> master_pb.CollectionListResponse
24, // 67: master_pb.Seaweed.CollectionDelete:output_type -> master_pb.CollectionDeleteResponse
31, // 68: master_pb.Seaweed.VolumeList:output_type -> master_pb.VolumeListResponse
33, // 69: master_pb.Seaweed.LookupEcVolume:output_type -> master_pb.LookupEcVolumeResponse
35, // 70: master_pb.Seaweed.VacuumVolume:output_type -> master_pb.VacuumVolumeResponse
37, // 71: master_pb.Seaweed.DisableVacuum:output_type -> master_pb.DisableVacuumResponse
39, // 72: master_pb.Seaweed.EnableVacuum:output_type -> master_pb.EnableVacuumResponse
41, // 73: master_pb.Seaweed.VolumeMarkReadonly:output_type -> master_pb.VolumeMarkReadonlyResponse
43, // 74: master_pb.Seaweed.GetMasterConfiguration:output_type -> master_pb.GetMasterConfigurationResponse
45, // 75: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse
47, // 76: master_pb.Seaweed.LeaseAdminToken:output_type -> master_pb.LeaseAdminTokenResponse
49, // 77: master_pb.Seaweed.ReleaseAdminToken:output_type -> master_pb.ReleaseAdminTokenResponse
51, // 78: master_pb.Seaweed.Ping:output_type -> master_pb.PingResponse
57, // 79: master_pb.Seaweed.RaftListClusterServers:output_type -> master_pb.RaftListClusterServersResponse
53, // 80: master_pb.Seaweed.RaftAddServer:output_type -> master_pb.RaftAddServerResponse
55, // 81: master_pb.Seaweed.RaftRemoveServer:output_type -> master_pb.RaftRemoveServerResponse
59, // 82: master_pb.Seaweed.RaftLeadershipTransfer:output_type -> master_pb.RaftLeadershipTransferResponse
60, // 83: master_pb.Seaweed.VolumeGrow:output_type -> master_pb.VolumeGrowResponse
60, // [60:84] is the sub-list for method output_type
36, // [36:60] is the sub-list for method input_type
16, // 58: master_pb.Seaweed.VolumeGrow:input_type -> master_pb.VolumeGrowRequest
1, // 59: master_pb.Seaweed.SendHeartbeat:output_type -> master_pb.HeartbeatResponse
11, // 60: master_pb.Seaweed.KeepConnected:output_type -> master_pb.KeepConnectedResponse
13, // 61: master_pb.Seaweed.LookupVolume:output_type -> master_pb.LookupVolumeResponse
17, // 62: master_pb.Seaweed.Assign:output_type -> master_pb.AssignResponse
17, // 63: master_pb.Seaweed.StreamAssign:output_type -> master_pb.AssignResponse
19, // 64: master_pb.Seaweed.Statistics:output_type -> master_pb.StatisticsResponse
22, // 65: master_pb.Seaweed.CollectionList:output_type -> master_pb.CollectionListResponse
24, // 66: master_pb.Seaweed.CollectionDelete:output_type -> master_pb.CollectionDeleteResponse
31, // 67: master_pb.Seaweed.VolumeList:output_type -> master_pb.VolumeListResponse
33, // 68: master_pb.Seaweed.LookupEcVolume:output_type -> master_pb.LookupEcVolumeResponse
35, // 69: master_pb.Seaweed.VacuumVolume:output_type -> master_pb.VacuumVolumeResponse
37, // 70: master_pb.Seaweed.DisableVacuum:output_type -> master_pb.DisableVacuumResponse
39, // 71: master_pb.Seaweed.EnableVacuum:output_type -> master_pb.EnableVacuumResponse
41, // 72: master_pb.Seaweed.VolumeMarkReadonly:output_type -> master_pb.VolumeMarkReadonlyResponse
43, // 73: master_pb.Seaweed.GetMasterConfiguration:output_type -> master_pb.GetMasterConfigurationResponse
45, // 74: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse
47, // 75: master_pb.Seaweed.LeaseAdminToken:output_type -> master_pb.LeaseAdminTokenResponse
49, // 76: master_pb.Seaweed.ReleaseAdminToken:output_type -> master_pb.ReleaseAdminTokenResponse
51, // 77: master_pb.Seaweed.Ping:output_type -> master_pb.PingResponse
57, // 78: master_pb.Seaweed.RaftListClusterServers:output_type -> master_pb.RaftListClusterServersResponse
53, // 79: master_pb.Seaweed.RaftAddServer:output_type -> master_pb.RaftAddServerResponse
55, // 80: master_pb.Seaweed.RaftRemoveServer:output_type -> master_pb.RaftRemoveServerResponse
58, // 81: master_pb.Seaweed.VolumeGrow:output_type -> master_pb.VolumeGrowResponse
59, // [59:82] is the sub-list for method output_type
36, // [36:59] is the sub-list for method input_type
36, // [36:36] is the sub-list for extension type_name
36, // [36:36] is the sub-list for extension extendee
0, // [0:36] is the sub-list for field type_name
@@ -4737,7 +4621,7 @@ func file_master_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_master_proto_rawDesc), len(file_master_proto_rawDesc)),
NumEnums: 0,
NumMessages: 72,
NumMessages: 70,
NumExtensions: 0,
NumServices: 1,
},
-38
View File
@@ -41,7 +41,6 @@ const (
Seaweed_RaftListClusterServers_FullMethodName = "/master_pb.Seaweed/RaftListClusterServers"
Seaweed_RaftAddServer_FullMethodName = "/master_pb.Seaweed/RaftAddServer"
Seaweed_RaftRemoveServer_FullMethodName = "/master_pb.Seaweed/RaftRemoveServer"
Seaweed_RaftLeadershipTransfer_FullMethodName = "/master_pb.Seaweed/RaftLeadershipTransfer"
Seaweed_VolumeGrow_FullMethodName = "/master_pb.Seaweed/VolumeGrow"
)
@@ -71,7 +70,6 @@ type SeaweedClient interface {
RaftListClusterServers(ctx context.Context, in *RaftListClusterServersRequest, opts ...grpc.CallOption) (*RaftListClusterServersResponse, error)
RaftAddServer(ctx context.Context, in *RaftAddServerRequest, opts ...grpc.CallOption) (*RaftAddServerResponse, error)
RaftRemoveServer(ctx context.Context, in *RaftRemoveServerRequest, opts ...grpc.CallOption) (*RaftRemoveServerResponse, error)
RaftLeadershipTransfer(ctx context.Context, in *RaftLeadershipTransferRequest, opts ...grpc.CallOption) (*RaftLeadershipTransferResponse, error)
VolumeGrow(ctx context.Context, in *VolumeGrowRequest, opts ...grpc.CallOption) (*VolumeGrowResponse, error)
}
@@ -312,16 +310,6 @@ func (c *seaweedClient) RaftRemoveServer(ctx context.Context, in *RaftRemoveServ
return out, nil
}
func (c *seaweedClient) RaftLeadershipTransfer(ctx context.Context, in *RaftLeadershipTransferRequest, opts ...grpc.CallOption) (*RaftLeadershipTransferResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RaftLeadershipTransferResponse)
err := c.cc.Invoke(ctx, Seaweed_RaftLeadershipTransfer_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *seaweedClient) VolumeGrow(ctx context.Context, in *VolumeGrowRequest, opts ...grpc.CallOption) (*VolumeGrowResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(VolumeGrowResponse)
@@ -358,7 +346,6 @@ type SeaweedServer interface {
RaftListClusterServers(context.Context, *RaftListClusterServersRequest) (*RaftListClusterServersResponse, error)
RaftAddServer(context.Context, *RaftAddServerRequest) (*RaftAddServerResponse, error)
RaftRemoveServer(context.Context, *RaftRemoveServerRequest) (*RaftRemoveServerResponse, error)
RaftLeadershipTransfer(context.Context, *RaftLeadershipTransferRequest) (*RaftLeadershipTransferResponse, error)
VolumeGrow(context.Context, *VolumeGrowRequest) (*VolumeGrowResponse, error)
mustEmbedUnimplementedSeaweedServer()
}
@@ -436,9 +423,6 @@ func (UnimplementedSeaweedServer) RaftAddServer(context.Context, *RaftAddServerR
func (UnimplementedSeaweedServer) RaftRemoveServer(context.Context, *RaftRemoveServerRequest) (*RaftRemoveServerResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RaftRemoveServer not implemented")
}
func (UnimplementedSeaweedServer) RaftLeadershipTransfer(context.Context, *RaftLeadershipTransferRequest) (*RaftLeadershipTransferResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RaftLeadershipTransfer not implemented")
}
func (UnimplementedSeaweedServer) VolumeGrow(context.Context, *VolumeGrowRequest) (*VolumeGrowResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method VolumeGrow not implemented")
}
@@ -826,24 +810,6 @@ func _Seaweed_RaftRemoveServer_Handler(srv interface{}, ctx context.Context, dec
return interceptor(ctx, in, info, handler)
}
func _Seaweed_RaftLeadershipTransfer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RaftLeadershipTransferRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SeaweedServer).RaftLeadershipTransfer(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Seaweed_RaftLeadershipTransfer_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SeaweedServer).RaftLeadershipTransfer(ctx, req.(*RaftLeadershipTransferRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Seaweed_VolumeGrow_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(VolumeGrowRequest)
if err := dec(in); err != nil {
@@ -945,10 +911,6 @@ var Seaweed_ServiceDesc = grpc.ServiceDesc{
MethodName: "RaftRemoveServer",
Handler: _Seaweed_RaftRemoveServer_Handler,
},
{
MethodName: "RaftLeadershipTransfer",
Handler: _Seaweed_RaftLeadershipTransfer_Handler,
},
{
MethodName: "VolumeGrow",
Handler: _Seaweed_VolumeGrow_Handler,
+1 -2
View File
@@ -8,7 +8,6 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -62,7 +61,7 @@ func (s3a *S3ApiServer) startBucketSizeMetricsLoop(ctx context.Context) {
// Start long-lived lock - this S3 instance will only collect metrics when it holds the lock
lock := lockClient.StartLongLivedLock(s3MetricsLockName, owner, func(newLockOwner string) {
glog.V(1).Infof("S3 bucket size metrics lock owner changed to: %s", newLockOwner)
}, lock_manager.RenewInterval)
})
defer lock.Stop()
ticker := time.NewTicker(bucketSizeMetricsInterval)
+6 -29
View File
@@ -204,7 +204,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
// Location uses the S3 endpoint that the client connected to
// Format: scheme://s3-endpoint/bucket/object (following AWS S3 API)
return &CompleteMultipartUploadResult{
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
Location: aws.String(fmt.Sprintf("%s://%s/%s/%s", getRequestScheme(r), r.Host, url.PathEscape(*input.Bucket), urlPathEscape(*input.Key))),
Bucket: input.Bucket,
ETag: aws.String("\"" + filer.ETagChunks(entry.GetChunks()) + "\""),
Key: objectKey(input.Key),
@@ -360,18 +360,12 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
// Check if versioning is configured for this bucket BEFORE creating any files
versioningState, vErr := s3a.getVersioningState(*input.Bucket)
if vErr == nil && versioningState == s3_constants.VersioningEnabled {
// Use full object key (not just entryName) to ensure correct .versions directory is checked
normalizedKey := strings.TrimPrefix(*input.Key, "/")
useInvertedFormat := s3a.getVersionIdFormat(*input.Bucket, normalizedKey)
versionId := generateVersionId(useInvertedFormat)
// For versioned buckets, create a version and return the version ID
versionId := generateVersionId()
versionFileName := s3a.getVersionFileName(versionId)
versionDir := dirName + "/" + entryName + s3_constants.VersionsFolder
// Capture timestamp and owner once for consistency between version entry and cache entry
versionMtime := time.Now().Unix()
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
// Create the version file in the .versions directory
// Move the completed object to the versions directory
err = s3a.mkFile(versionDir, versionFileName, finalParts, func(versionEntry *filer_pb.Entry) {
if versionEntry.Extended == nil {
versionEntry.Extended = make(map[string][]byte)
@@ -386,6 +380,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
}
// Set object owner for versioned multipart objects
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
if amzAccountId != "" {
versionEntry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
}
@@ -408,7 +403,6 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
versionEntry.Attributes.Mime = mime
}
versionEntry.Attributes.FileSize = uint64(offset)
versionEntry.Attributes.Mtime = versionMtime
})
if err != nil {
@@ -416,25 +410,8 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
return nil, s3err.ErrInternalError
}
// Construct entry with metadata for caching in .versions directory
// Reuse versionMtime to keep list vs. HEAD timestamps aligned
etag := "\"" + filer.ETagChunks(finalParts) + "\""
versionEntryForCache := &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{
FileSize: uint64(offset),
Mtime: versionMtime,
},
Extended: map[string][]byte{
s3_constants.ExtETagKey: []byte(etag),
},
}
if amzAccountId != "" {
versionEntryForCache.Extended[s3_constants.ExtAmzOwnerKey] = []byte(amzAccountId)
}
// Update the .versions directory metadata to indicate this is the latest version
// Pass entry to cache its metadata for single-scan list efficiency
err = s3a.updateLatestVersionInDirectory(*input.Bucket, *input.Key, versionId, versionFileName, versionEntryForCache)
err = s3a.updateLatestVersionInDirectory(*input.Bucket, *input.Key, versionId, versionFileName)
if err != nil {
glog.Errorf("completeMultipartUpload: failed to update latest version in directory: %v", err)
return nil, s3err.ErrInternalError
-1
View File
@@ -4,4 +4,3 @@ const (
// DefaultBucketsPath is the default path for S3 buckets in the filer
DefaultBucketsPath = "/buckets"
)
+1 -7
View File
@@ -11,13 +11,7 @@ const (
ExtETagKey = "Seaweed-X-Amz-ETag"
ExtLatestVersionIdKey = "Seaweed-X-Amz-Latest-Version-Id"
ExtLatestVersionFileNameKey = "Seaweed-X-Amz-Latest-Version-File-Name"
// Cached list metadata in .versions directory for single-scan efficiency
ExtLatestVersionSizeKey = "Seaweed-X-Amz-Latest-Version-Size"
ExtLatestVersionETagKey = "Seaweed-X-Amz-Latest-Version-ETag"
ExtLatestVersionMtimeKey = "Seaweed-X-Amz-Latest-Version-Mtime"
ExtLatestVersionOwnerKey = "Seaweed-X-Amz-Latest-Version-Owner"
ExtLatestVersionIsDeleteMarker = "Seaweed-X-Amz-Latest-Version-Is-Delete-Marker"
ExtMultipartObjectKey = "key"
ExtMultipartObjectKey = "key"
// Bucket Policy
ExtBucketPolicyKey = "Seaweed-X-Amz-Bucket-Policy"
-1
View File
@@ -130,4 +130,3 @@ func TestRemoveDuplicateSlashes(t *testing.T) {
}
}
+25 -35
View File
@@ -73,35 +73,28 @@ func (s3a *S3ApiServer) ListBucketsHandler(w http.ResponseWriter, r *http.Reques
var listBuckets ListAllMyBucketsList
for _, entry := range entries {
if entry.IsDirectory {
// Unauthenticated users should not see any buckets
if identity == nil {
// Check ownership: only show buckets owned by this user (unless admin)
if !isBucketVisibleToIdentity(entry, identity) {
continue
}
// Check if bucket should be visible to this identity
// A bucket is visible if the user owns it OR has explicit permission to list it
isOwner := isBucketOwnedByIdentity(entry, identity)
// Skip permission check if user is already the owner (optimization)
if !isOwner {
hasPermission := false
// Check permissions for each bucket
// Check permissions for each bucket
if identity != nil {
// For JWT-authenticated users, use IAM authorization
sessionToken := r.Header.Get("X-SeaweedFS-Session-Token")
if s3a.iam.iamIntegration != nil && sessionToken != "" {
// Use IAM authorization for JWT users
errCode := s3a.iam.authorizeWithIAM(r, identity, s3_constants.ACTION_LIST, entry.Name, "")
hasPermission = (errCode == s3err.ErrNone)
if errCode != s3err.ErrNone {
continue
}
} else {
// Use legacy authorization for non-JWT users
hasPermission = identity.canDo(s3_constants.ACTION_LIST, entry.Name, "")
}
if !hasPermission {
continue
if !identity.canDo(s3_constants.ACTION_LIST, entry.Name, "") {
continue
}
}
}
listBuckets.Bucket = append(listBuckets.Bucket, ListAllMyBucketsEntry{
Name: entry.Name,
CreationDate: time.Unix(entry.Attributes.Crtime, 0).UTC(),
@@ -120,35 +113,40 @@ func (s3a *S3ApiServer) ListBucketsHandler(w http.ResponseWriter, r *http.Reques
writeSuccessResponseXML(w, r, response)
}
// isBucketOwnedByIdentity checks if a bucket entry is owned by the given identity.
// Returns true if the identity owns the bucket, false otherwise.
// isBucketVisibleToIdentity checks if a bucket entry should be visible to the given identity
// based on ownership rules. Returns true if the bucket should be visible, false otherwise.
//
// Ownership rules:
// - Admin users: considered owners of all buckets
// - Non-admin users: own buckets where AmzIdentityId matches identity.Name
// - Buckets without owner metadata are not owned by anyone (except admins)
func isBucketOwnedByIdentity(entry *filer_pb.Entry, identity *Identity) bool {
// Visibility rules:
// - Unauthenticated requests (identity == nil): no buckets visible
// - Admin users: all buckets visible
// - Non-admin users: only buckets they own (matching identity.Name) are visible
// - Buckets without owner metadata are hidden from non-admin users
func isBucketVisibleToIdentity(entry *filer_pb.Entry, identity *Identity) bool {
if !entry.IsDirectory {
return false
}
// Unauthenticated users should not see any buckets (standard S3 behavior)
if identity == nil {
return false
}
// Admin users are considered owners of all buckets
// Admin users bypass ownership check
if identity.isAdmin() {
return true
}
// Non-admin users with no name cannot own buckets.
// Non-admin users with no name cannot own or see buckets.
// This prevents misconfigured identities from matching buckets with empty owner IDs.
if identity.Name == "" {
return false
}
// Check ownership via AmzIdentityId metadata
// Non-admin users: check ownership
// Use the authenticated identity value directly (cannot be spoofed)
id, ok := entry.Extended[s3_constants.AmzIdentityId]
// Skip buckets that are not owned by the current user.
// Buckets without an owner are also skipped.
if !ok || string(id) != identity.Name {
return false
}
@@ -156,14 +154,6 @@ func isBucketOwnedByIdentity(entry *filer_pb.Entry, identity *Identity) bool {
return true
}
// isBucketVisibleToIdentity is kept for backward compatibility with tests.
// It checks if a bucket should be visible based on ownership only.
// Deprecated: Use isBucketOwnedByIdentity instead. The ListBucketsHandler
// now uses OR logic: a bucket is visible if user owns it OR has List permission.
func isBucketVisibleToIdentity(entry *filer_pb.Entry, identity *Identity) bool {
return isBucketOwnedByIdentity(entry, identity)
}
func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request) {
// collect parameters
-267
View File
@@ -776,270 +776,3 @@ func TestListBucketsIssue7647(t *testing.T) {
assert.False(t, isVisible, "Non-admin should not see buckets without owner metadata")
})
}
// TestListBucketsIssue7796 reproduces and verifies the fix for issue #7796
// where a user with bucket-specific List permission (e.g., "List:geoserver")
// couldn't see buckets they have access to but don't own
func TestListBucketsIssue7796(t *testing.T) {
t.Run("user with bucket-specific List permission can see bucket they don't own", func(t *testing.T) {
// Simulate the exact scenario from issue #7796:
// User "geoserver" with ["List:geoserver", "Read:geoserver", "Write:geoserver", ...] permissions
// But the bucket "geoserver" was created by a different user (e.g., admin)
geoserverIdentity := &Identity{
Name: "geoserver",
Credentials: []*Credential{
{
AccessKey: "geoserver",
SecretKey: "secret",
},
},
Actions: []Action{
Action("List:geoserver"),
Action("Read:geoserver"),
Action("Write:geoserver"),
Action("Admin:geoserver"),
Action("List:geoserver-ttl"),
Action("Read:geoserver-ttl"),
Action("Write:geoserver-ttl"),
},
}
// Bucket was created by admin, not by geoserver user
geoserverBucket := &filer_pb.Entry{
Name: "geoserver",
IsDirectory: true,
Extended: map[string][]byte{
s3_constants.AmzIdentityId: []byte("admin"), // Different owner
},
Attributes: &filer_pb.FuseAttributes{
Crtime: time.Now().Unix(),
Mtime: time.Now().Unix(),
},
}
// Test ownership check - should return false (not owned by geoserver)
isOwner := isBucketOwnedByIdentity(geoserverBucket, geoserverIdentity)
assert.False(t, isOwner, "geoserver user should not be owner of bucket created by admin")
// Test permission check - should return true (has List:geoserver permission)
canList := geoserverIdentity.canDo(s3_constants.ACTION_LIST, "geoserver", "")
assert.True(t, canList, "geoserver user with List:geoserver should be able to list geoserver bucket")
// Verify the combined visibility logic: ownership OR permission
isVisible := isOwner || canList
assert.True(t, isVisible, "Bucket should be visible due to permission (even though not owner)")
})
t.Run("user with bucket-specific permission sees bucket without owner metadata", func(t *testing.T) {
// Bucket exists but has no owner metadata (legacy bucket or created before ownership tracking)
geoserverIdentity := &Identity{
Name: "geoserver",
Actions: []Action{
Action("List:geoserver"),
Action("Read:geoserver"),
},
}
bucketWithoutOwner := &filer_pb.Entry{
Name: "geoserver",
IsDirectory: true,
Extended: map[string][]byte{}, // No owner metadata
Attributes: &filer_pb.FuseAttributes{
Crtime: time.Now().Unix(),
},
}
// Not owner (no owner metadata)
isOwner := isBucketOwnedByIdentity(bucketWithoutOwner, geoserverIdentity)
assert.False(t, isOwner, "No owner metadata means not owned")
// But has permission
canList := geoserverIdentity.canDo(s3_constants.ACTION_LIST, "geoserver", "")
assert.True(t, canList, "Has explicit List:geoserver permission")
// Verify the combined visibility logic: ownership OR permission
isVisible := isOwner || canList
assert.True(t, isVisible, "Bucket should be visible due to permission (even without owner metadata)")
})
t.Run("user cannot see bucket they neither own nor have permission for", func(t *testing.T) {
// User has no ownership and no permission for the bucket
geoserverIdentity := &Identity{
Name: "geoserver",
Actions: []Action{
Action("List:geoserver"),
Action("Read:geoserver"),
},
}
otherBucket := &filer_pb.Entry{
Name: "otherbucket",
IsDirectory: true,
Extended: map[string][]byte{
s3_constants.AmzIdentityId: []byte("admin"),
},
Attributes: &filer_pb.FuseAttributes{
Crtime: time.Now().Unix(),
},
}
// Not owner
isOwner := isBucketOwnedByIdentity(otherBucket, geoserverIdentity)
assert.False(t, isOwner, "geoserver doesn't own otherbucket")
// No permission for this bucket
canList := geoserverIdentity.canDo(s3_constants.ACTION_LIST, "otherbucket", "")
assert.False(t, canList, "geoserver has no List permission for otherbucket")
// Verify the combined visibility logic: ownership OR permission
isVisible := isOwner || canList
assert.False(t, isVisible, "Bucket should NOT be visible (neither owner nor has permission)")
})
t.Run("user with wildcard permission sees matching buckets", func(t *testing.T) {
// User has "List:geo*" permission - should see any bucket starting with "geo"
geoIdentity := &Identity{
Name: "geouser",
Actions: []Action{
Action("List:geo*"),
Action("Read:geo*"),
},
}
geoBucket := &filer_pb.Entry{
Name: "geoserver",
IsDirectory: true,
Extended: map[string][]byte{
s3_constants.AmzIdentityId: []byte("admin"),
},
Attributes: &filer_pb.FuseAttributes{
Crtime: time.Now().Unix(),
},
}
geoTTLBucket := &filer_pb.Entry{
Name: "geoserver-ttl",
IsDirectory: true,
Extended: map[string][]byte{
s3_constants.AmzIdentityId: []byte("admin"),
},
Attributes: &filer_pb.FuseAttributes{
Crtime: time.Now().Unix(),
},
}
// Not owner of either bucket
isOwnerGeo := isBucketOwnedByIdentity(geoBucket, geoIdentity)
isOwnerGeoTTL := isBucketOwnedByIdentity(geoTTLBucket, geoIdentity)
assert.False(t, isOwnerGeo)
assert.False(t, isOwnerGeoTTL)
// But has permission via wildcard
canListGeo := geoIdentity.canDo(s3_constants.ACTION_LIST, "geoserver", "")
canListGeoTTL := geoIdentity.canDo(s3_constants.ACTION_LIST, "geoserver-ttl", "")
assert.True(t, canListGeo)
assert.True(t, canListGeoTTL)
// Verify the combined visibility logic for matching buckets
assert.True(t, isOwnerGeo || canListGeo, "geoserver bucket should be visible via wildcard permission")
assert.True(t, isOwnerGeoTTL || canListGeoTTL, "geoserver-ttl bucket should be visible via wildcard permission")
// Should NOT have permission for unrelated buckets
canListOther := geoIdentity.canDo(s3_constants.ACTION_LIST, "otherbucket", "")
assert.False(t, canListOther, "No permission for otherbucket")
assert.False(t, false || canListOther, "otherbucket should NOT be visible (no ownership, no permission)")
})
t.Run("integration test: complete handler filtering logic", func(t *testing.T) {
// This test simulates the complete filtering logic as used in ListBucketsHandler
// to verify that the combination of ownership OR permission check works correctly
// User "geoserver" with bucket-specific permissions (same as issue #7796)
geoserverIdentity := &Identity{
Name: "geoserver",
Credentials: []*Credential{
{AccessKey: "geoserver", SecretKey: "secret"},
},
Actions: []Action{
Action("List:geoserver"),
Action("Read:geoserver"),
Action("Write:geoserver"),
Action("Admin:geoserver"),
Action("List:geoserver-ttl"),
Action("Read:geoserver-ttl"),
Action("Write:geoserver-ttl"),
},
}
// Create test buckets with various ownership scenarios
buckets := []*filer_pb.Entry{
{
// Bucket owned by admin but geoserver has permission
Name: "geoserver",
IsDirectory: true,
Extended: map[string][]byte{s3_constants.AmzIdentityId: []byte("admin")},
Attributes: &filer_pb.FuseAttributes{Crtime: time.Now().Unix()},
},
{
// Bucket with no owner but geoserver has permission
Name: "geoserver-ttl",
IsDirectory: true,
Extended: map[string][]byte{},
Attributes: &filer_pb.FuseAttributes{Crtime: time.Now().Unix()},
},
{
// Bucket owned by geoserver (should be visible via ownership)
Name: "geoserver-owned",
IsDirectory: true,
Extended: map[string][]byte{s3_constants.AmzIdentityId: []byte("geoserver")},
Attributes: &filer_pb.FuseAttributes{Crtime: time.Now().Unix()},
},
{
// Bucket owned by someone else, no permission for geoserver
Name: "otherbucket",
IsDirectory: true,
Extended: map[string][]byte{s3_constants.AmzIdentityId: []byte("otheruser")},
Attributes: &filer_pb.FuseAttributes{Crtime: time.Now().Unix()},
},
}
// Simulate the exact filtering logic from ListBucketsHandler
var visibleBuckets []string
for _, entry := range buckets {
if !entry.IsDirectory {
continue
}
// Check ownership
isOwner := isBucketOwnedByIdentity(entry, geoserverIdentity)
// Skip permission check if user is already the owner (optimization)
if !isOwner {
// Check permission
hasPermission := geoserverIdentity.canDo(s3_constants.ACTION_LIST, entry.Name, "")
if !hasPermission {
continue
}
}
visibleBuckets = append(visibleBuckets, entry.Name)
}
// Expected: geoserver should see:
// - "geoserver" (has List:geoserver permission, even though owned by admin)
// - "geoserver-ttl" (has List:geoserver-ttl permission, even though no owner)
// - "geoserver-owned" (owns this bucket)
// NOT "otherbucket" (neither owns nor has permission)
expectedBuckets := []string{"geoserver", "geoserver-ttl", "geoserver-owned"}
assert.ElementsMatch(t, expectedBuckets, visibleBuckets,
"geoserver should see buckets they own OR have permission for")
// Verify "otherbucket" is NOT in the list
assert.NotContains(t, visibleBuckets, "otherbucket",
"geoserver should NOT see buckets they neither own nor have permission for")
})
}
+10 -12
View File
@@ -641,18 +641,7 @@ func (e *EmbeddedIamApi) AuthIam(f http.HandlerFunc, _ Action) http.HandlerFunc
return
}
// Authenticate BEFORE parsing form.
// ParseForm() reads and consumes the request body, but signature verification
// needs to hash the body for IAM requests (service != "s3").
// The streamHashRequestBody function in auth_signature_v4.go preserves the body
// after reading it, so ParseForm() will work correctly after authentication.
identity, errCode := e.iam.AuthSignatureOnly(r)
if errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
// Now parse form to get Action and UserName (body was preserved by auth)
// Parse form to get Action and UserName
if err := r.ParseForm(); err != nil {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
return
@@ -661,6 +650,15 @@ func (e *EmbeddedIamApi) AuthIam(f http.HandlerFunc, _ Action) http.HandlerFunc
action := r.Form.Get("Action")
targetUserName := r.PostForm.Get("UserName")
// Authenticate the request using signature-only verification.
// This bypasses S3 authorization checks (identity.canDo) since IAM operations
// have their own permission model based on self-service vs admin operations.
identity, errCode := e.iam.AuthSignatureOnly(r)
if errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
// IAM API requests must be authenticated - reject nil identity
// (can happen for authTypePostPolicy or authTypeStreamingUnsigned)
if identity == nil {
-160
View File
@@ -3,22 +3,16 @@ package s3api
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
)
@@ -1508,157 +1502,3 @@ func TestInactiveAccessKeyLookupFails(t *testing.T) {
assert.NotNil(t, cred)
}
// TestAuthIamAuthenticatesBeforeParseForm verifies that AuthIam authenticates the request
// BEFORE parsing the form. This is critical because ParseForm() consumes the request body,
// but IAM signature verification needs to hash the body.
// This test reproduces the bug described in GitHub issue #7802.
func TestAuthIamAuthenticatesBeforeParseForm(t *testing.T) {
// Create IAM with test credentials
iam := &IdentityAccessManagement{
hashes: make(map[string]*sync.Pool),
hashCounters: make(map[string]*int32),
}
testConfig := &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{
Name: "admin",
Credentials: []*iam_pb.Credential{
{
AccessKey: "admin_access_key",
SecretKey: "admin_secret_key",
Status: "Active",
},
},
Actions: []string{"Admin"},
},
},
}
err := iam.loadS3ApiConfiguration(testConfig)
assert.NoError(t, err)
embeddedApi := &EmbeddedIamApi{
iam: iam,
}
// Create a properly signed IAM request
payload := "Action=CreateUser&Version=2010-05-08&UserName=bob"
// Use current time to avoid clock skew
now := time.Now().UTC()
amzDate := now.Format(iso8601Format)
dateStamp := now.Format(yyyymmdd)
credentialScope := dateStamp + "/us-east-1/iam/aws4_request"
req, err := http.NewRequest("POST", "http://localhost:8333/", strings.NewReader(payload))
assert.NoError(t, err)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
req.Header.Set("Host", "localhost:8333")
req.Header.Set("X-Amz-Date", amzDate)
// Calculate the correct signature using IAM service
payloadHash := getSHA256Hash([]byte(payload))
canonicalRequest := fmt.Sprintf("POST\n/\n\ncontent-type:application/x-www-form-urlencoded; charset=utf-8\nhost:localhost:8333\nx-amz-date:%s\n\ncontent-type;host;x-amz-date\n%s", amzDate, payloadHash)
canonicalRequestHash := getSHA256Hash([]byte(canonicalRequest))
stringToSign := fmt.Sprintf("AWS4-HMAC-SHA256\n%s\n%s\n%s", amzDate, credentialScope, canonicalRequestHash)
signingKey := getSigningKey("admin_secret_key", dateStamp, "us-east-1", "iam")
signature := getSignature(signingKey, stringToSign)
authHeader := fmt.Sprintf("AWS4-HMAC-SHA256 Credential=admin_access_key/%s, SignedHeaders=content-type;host;x-amz-date, Signature=%s",
credentialScope, signature)
req.Header.Set("Authorization", authHeader)
// Create a test handler that just returns OK
handlerCalled := false
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handlerCalled = true
w.WriteHeader(http.StatusOK)
})
// Wrap with AuthIam
authHandler := embeddedApi.AuthIam(testHandler, ACTION_WRITE)
// Execute the request
rr := httptest.NewRecorder()
authHandler.ServeHTTP(rr, req)
// The handler should be called (authentication succeeded)
// Before the fix, this would fail with SignatureDoesNotMatch because
// ParseForm was called before authentication, consuming the body
assert.True(t, handlerCalled, "Handler was not called - authentication failed")
assert.Equal(t, http.StatusOK, rr.Code, "Expected OK status, got %d", rr.Code)
}
// TestOldCodeOrderWouldFail demonstrates why the old code order was broken.
// This test shows that ParseForm() before signature verification causes auth failure.
func TestOldCodeOrderWouldFail(t *testing.T) {
// Create IAM with test credentials
iam := &IdentityAccessManagement{
hashes: make(map[string]*sync.Pool),
hashCounters: make(map[string]*int32),
}
testConfig := &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{
Name: "admin",
Credentials: []*iam_pb.Credential{
{
AccessKey: "admin_access_key",
SecretKey: "admin_secret_key",
Status: "Active",
},
},
Actions: []string{"Admin"},
},
},
}
err := iam.loadS3ApiConfiguration(testConfig)
assert.NoError(t, err)
// Create a properly signed IAM request
payload := "Action=CreateUser&Version=2010-05-08&UserName=bob"
now := time.Now().UTC()
amzDate := now.Format(iso8601Format)
dateStamp := now.Format(yyyymmdd)
credentialScope := dateStamp + "/us-east-1/iam/aws4_request"
req, err := http.NewRequest("POST", "http://localhost:8333/", strings.NewReader(payload))
assert.NoError(t, err)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
req.Header.Set("Host", "localhost:8333")
req.Header.Set("X-Amz-Date", amzDate)
// Calculate the correct signature using IAM service
payloadHash := getSHA256Hash([]byte(payload))
canonicalRequest := fmt.Sprintf("POST\n/\n\ncontent-type:application/x-www-form-urlencoded; charset=utf-8\nhost:localhost:8333\nx-amz-date:%s\n\ncontent-type;host;x-amz-date\n%s", amzDate, payloadHash)
canonicalRequestHash := getSHA256Hash([]byte(canonicalRequest))
stringToSign := fmt.Sprintf("AWS4-HMAC-SHA256\n%s\n%s\n%s", amzDate, credentialScope, canonicalRequestHash)
signingKey := getSigningKey("admin_secret_key", dateStamp, "us-east-1", "iam")
signature := getSignature(signingKey, stringToSign)
authHeader := fmt.Sprintf("AWS4-HMAC-SHA256 Credential=admin_access_key/%s, SignedHeaders=content-type;host;x-amz-date, Signature=%s",
credentialScope, signature)
req.Header.Set("Authorization", authHeader)
// Simulate OLD buggy code: ParseForm BEFORE authentication
// This consumes the request body!
err = req.ParseForm()
assert.NoError(t, err)
assert.Equal(t, "CreateUser", req.Form.Get("Action")) // Form parsing works
// Now try to authenticate - this should FAIL because body is consumed
identity, errCode := iam.AuthSignatureOnly(req)
// With old code order, this would fail with SignatureDoesNotMatch
// because the body is empty when signature verification tries to hash it
assert.Equal(t, s3err.ErrSignatureDoesNotMatch, errCode,
"Expected SignatureDoesNotMatch when ParseForm is called before auth")
assert.Nil(t, identity)
t.Log("This demonstrates the bug: ParseForm before auth causes SignatureDoesNotMatch")
}
+47 -111
View File
@@ -386,21 +386,10 @@ func newListEntry(entry *filer_pb.Entry, key string, dir string, name string, bu
if encodingTypeUrl {
key = urlPathEscape(key)
}
// Determine ETag: prioritize ExtETagKey for versioned objects (supports multipart ETags),
// then fall back to filer.ETag() which uses Md5 attribute or calculates from chunks
var etag string
if entry.Extended != nil {
if etagBytes, hasETag := entry.Extended[s3_constants.ExtETagKey]; hasETag {
etag = string(etagBytes)
}
}
if etag == "" {
etag = "\"" + filer.ETag(entry) + "\""
}
listEntry = ListEntry{
Key: key,
LastModified: time.Unix(entry.Attributes.Mtime, 0).UTC(),
ETag: etag,
ETag: "\"" + filer.ETag(entry) + "\"",
Size: int64(filer.FileSize(entry)),
StorageClass: StorageClass(storageClass),
}
@@ -670,19 +659,18 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
return
}
// Handle remote storage objects: cache to local cluster if object is remote-only
// This uses singleflight to deduplicate concurrent caching requests for the same object
// On cache error, gracefully falls back to streaming from remote
if objectEntryForSSE.IsInRemoteOnly() {
objectEntryForSSE = s3a.cacheRemoteObjectWithDedup(r.Context(), bucket, object, objectEntryForSSE)
}
// Re-check bucket policy with object entry for tag-based conditions (e.g., s3:ExistingObjectTag)
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, string(s3_constants.ACTION_READ), objectEntryForSSE.Extended, "GetObjectHandler"); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
// Handle remote storage objects: cache to local cluster if object is remote-only
// This uses singleflight to deduplicate concurrent caching requests for the same object
if objectEntryForSSE.IsInRemoteOnly() {
objectEntryForSSE = s3a.cacheRemoteObjectWithDedup(r.Context(), bucket, object, objectEntryForSSE)
}
// Check if PartNumber query parameter is present (for multipart GET requests)
partNumberStr := r.URL.Query().Get("partNumber")
if partNumberStr == "" {
@@ -760,7 +748,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
// Stream directly from volume servers with SSE support
tStream := time.Now()
err = s3a.streamFromVolumeServersWithSSE(w, r, objectEntryForSSE, primarySSEType, bucket, object, versionId)
err = s3a.streamFromVolumeServersWithSSE(w, r, objectEntryForSSE, primarySSEType)
streamTime = time.Since(tStream)
if err != nil {
glog.Errorf("GetObjectHandler: failed to stream from volume servers: %v", err)
@@ -784,7 +772,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
// streamFromVolumeServers streams object data directly from volume servers, bypassing filer proxy
// This eliminates the ~19ms filer proxy overhead by reading chunks directly
func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, sseType string, bucket, object, versionId string) error {
func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, sseType string) error {
// Profiling: Track overall and stage timings
t0 := time.Now()
var (
@@ -937,34 +925,17 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
len(chunks), totalSize, isRangeRequest, offset, size)
if len(chunks) == 0 {
// Check if this is a remote-only entry that needs caching
// This handles the case where initial caching attempt timed out or failed
if entry.IsInRemoteOnly() {
glog.V(1).Infof("streamFromVolumeServers: entry is remote-only, attempting to cache before streaming")
// Try to cache the remote object synchronously (like filer does)
cachedEntry := s3a.cacheRemoteObjectForStreaming(r, entry, bucket, object, versionId)
if cachedEntry != nil && len(cachedEntry.GetChunks()) > 0 {
chunks = cachedEntry.GetChunks()
entry = cachedEntry
glog.V(1).Infof("streamFromVolumeServers: successfully cached remote object, got %d chunks", len(chunks))
} else {
// Caching failed - return error to client
glog.Errorf("streamFromVolumeServers: failed to cache remote object for streaming")
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return newStreamErrorWithResponse(fmt.Errorf("failed to cache remote object for streaming"))
}
} else if totalSize > 0 && len(entry.Content) == 0 {
// Not a remote entry but has size without content - this is a data integrity issue
// BUG FIX: If totalSize > 0 but no chunks and no content, this is a data integrity issue
if totalSize > 0 && len(entry.Content) == 0 {
glog.Errorf("streamFromVolumeServers: Data integrity error - entry reports size %d but has no content or chunks", totalSize)
// Write S3-compliant XML error response
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return newStreamErrorWithResponse(fmt.Errorf("data integrity error: size %d reported but no content available", totalSize))
} else {
// Empty object - set headers and write status
s3a.setResponseHeaders(w, r, entry, totalSize)
w.WriteHeader(http.StatusOK)
return nil
}
// Empty object - set headers and write status
s3a.setResponseHeaders(w, r, entry, totalSize)
w.WriteHeader(http.StatusOK)
return nil
}
// Log chunk details (verbose only - high frequency)
@@ -1065,10 +1036,10 @@ func (s3a *S3ApiServer) createLookupFileIdFunction() func(context.Context, strin
}
// streamFromVolumeServersWithSSE handles streaming with inline SSE decryption
func (s3a *S3ApiServer) streamFromVolumeServersWithSSE(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, sseType string, bucket, object, versionId string) error {
func (s3a *S3ApiServer) streamFromVolumeServersWithSSE(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, sseType string) error {
// If not encrypted, use fast path without decryption
if sseType == "" || sseType == "None" {
return s3a.streamFromVolumeServers(w, r, entry, sseType, bucket, object, versionId)
return s3a.streamFromVolumeServers(w, r, entry, sseType)
}
// Profiling: Track SSE decryption stages
@@ -3355,26 +3326,34 @@ func (s3a *S3ApiServer) getMultipartInfo(entry *filer_pb.Entry, partNumber int)
return partsCount, nil
}
// buildRemoteObjectPath builds the filer directory and object name from S3 bucket/object.
// This is shared by all remote object caching functions.
func (s3a *S3ApiServer) buildRemoteObjectPath(bucket, object string) (dir, name string) {
dir = s3a.option.BucketsPath + "/" + bucket
name = strings.TrimPrefix(removeDuplicateSlashes(object), "/")
if idx := strings.LastIndex(name, "/"); idx > 0 {
dir = dir + "/" + name[:idx]
name = name[idx+1:]
}
return dir, name
}
// cacheRemoteObjectWithDedup caches a remote-only object to the local cluster.
// The filer server handles singleflight deduplication, so all clients (S3, HTTP, Hadoop) benefit.
// On cache error, returns the original entry (streaming from remote will still work).
// Uses a bounded timeout to avoid blocking requests indefinitely.
func (s3a *S3ApiServer) cacheRemoteObjectWithDedup(ctx context.Context, bucket, object string, entry *filer_pb.Entry) *filer_pb.Entry {
// Use a bounded timeout for caching to avoid blocking requests indefinitely
// 30 seconds should be enough for most objects; large objects may timeout but will still stream
const cacheTimeout = 30 * time.Second
cacheCtx, cancel := context.WithTimeout(ctx, cacheTimeout)
defer cancel()
// doCacheRemoteObject calls the filer's CacheRemoteObjectToLocalCluster gRPC endpoint.
// This is the core caching function used by both cacheRemoteObjectWithDedup and cacheRemoteObjectForStreaming.
func (s3a *S3ApiServer) doCacheRemoteObject(ctx context.Context, dir, name string) (*filer_pb.Entry, error) {
// Build the full path for the object
dir := s3a.option.BucketsPath + "/" + bucket
normalizedObject := removeDuplicateSlashes(object)
if idx := strings.LastIndex(normalizedObject, "/"); idx > 0 {
dir = dir + "/" + normalizedObject[:idx]
normalizedObject = normalizedObject[idx+1:]
}
glog.V(2).Infof("cacheRemoteObjectWithDedup: caching %s/%s (remote size: %d)", bucket, object, entry.RemoteEntry.RemoteSize)
// Call the filer's CacheRemoteObjectToLocalCluster via gRPC
// The filer handles singleflight deduplication internally
var cachedEntry *filer_pb.Entry
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, cacheErr := client.CacheRemoteObjectToLocalCluster(ctx, &filer_pb.CacheRemoteObjectToLocalClusterRequest{
resp, cacheErr := client.CacheRemoteObjectToLocalCluster(cacheCtx, &filer_pb.CacheRemoteObjectToLocalClusterRequest{
Directory: dir,
Name: name,
Name: normalizedObject,
})
if cacheErr != nil {
return cacheErr
@@ -3384,67 +3363,24 @@ func (s3a *S3ApiServer) doCacheRemoteObject(ctx context.Context, dir, name strin
}
return nil
})
return cachedEntry, err
}
// cacheRemoteObjectWithDedup caches a remote-only object to the local cluster.
// The filer server handles singleflight deduplication, so all clients (S3, HTTP, Hadoop) benefit.
// On cache error, returns the original entry (will retry in streamFromVolumeServers).
// Uses a bounded timeout to avoid blocking requests indefinitely.
func (s3a *S3ApiServer) cacheRemoteObjectWithDedup(ctx context.Context, bucket, object string, entry *filer_pb.Entry) *filer_pb.Entry {
const cacheTimeout = 30 * time.Second
cacheCtx, cancel := context.WithTimeout(ctx, cacheTimeout)
defer cancel()
dir, name := s3a.buildRemoteObjectPath(bucket, object)
glog.V(2).Infof("cacheRemoteObjectWithDedup: caching %s/%s (remote size: %d)", bucket, object, entry.RemoteEntry.RemoteSize)
cachedEntry, err := s3a.doCacheRemoteObject(cacheCtx, dir, name)
if err != nil {
// Caching failed - log and return original entry
// Streaming from remote storage will still work via filer proxy
if errors.Is(err, context.DeadlineExceeded) {
glog.V(1).Infof("cacheRemoteObjectWithDedup: timeout caching %s/%s after %v (will retry in streaming)", bucket, object, cacheTimeout)
glog.V(1).Infof("cacheRemoteObjectWithDedup: timeout caching %s/%s after %v (will stream from remote)", bucket, object, cacheTimeout)
} else {
glog.Warningf("cacheRemoteObjectWithDedup: failed to cache %s/%s: %v (will retry in streaming)", bucket, object, err)
glog.Warningf("cacheRemoteObjectWithDedup: failed to cache %s/%s: %v (will stream from remote)", bucket, object, err)
}
return entry
}
// If caching succeeded and we got chunks, use the cached entry's chunks
if cachedEntry != nil && len(cachedEntry.GetChunks()) > 0 {
glog.V(1).Infof("cacheRemoteObjectWithDedup: successfully cached %s/%s (%d chunks)", bucket, object, len(cachedEntry.GetChunks()))
// Preserve original entry metadata but use new chunks
entry.Chunks = cachedEntry.Chunks
}
return entry
}
// cacheRemoteObjectForStreaming caches a remote-only object to the local cluster for streaming.
// This is called from streamFromVolumeServers when the initial caching attempt timed out or failed.
// Uses the request context (no artificial timeout) to allow the caching to complete.
// For versioned objects, versionId determines the correct path in .versions/ directory.
func (s3a *S3ApiServer) cacheRemoteObjectForStreaming(r *http.Request, entry *filer_pb.Entry, bucket, object, versionId string) *filer_pb.Entry {
var dir, name string
if versionId != "" && versionId != "null" {
// This is a specific version - entry is located at /buckets/<bucket>/<object>.versions/v_<versionId>
normalizedObject := strings.TrimPrefix(removeDuplicateSlashes(object), "/")
dir = s3a.option.BucketsPath + "/" + bucket + "/" + normalizedObject + s3_constants.VersionsFolder
name = s3a.getVersionFileName(versionId)
} else {
// Non-versioned object or "null" version - lives at the main path
dir, name = s3a.buildRemoteObjectPath(bucket, object)
}
glog.V(1).Infof("cacheRemoteObjectForStreaming: caching %s/%s (remote size: %d, versionId: %s)", dir, name, entry.RemoteEntry.RemoteSize, versionId)
cachedEntry, err := s3a.doCacheRemoteObject(r.Context(), dir, name)
if err != nil {
glog.Errorf("cacheRemoteObjectForStreaming: failed to cache %s/%s: %v", dir, name, err)
return nil
}
if cachedEntry != nil && len(cachedEntry.GetChunks()) > 0 {
glog.V(1).Infof("cacheRemoteObjectForStreaming: successfully cached %s/%s (%d chunks)", dir, name, len(cachedEntry.GetChunks()))
return cachedEntry
}
return nil
}
+3 -4
View File
@@ -272,8 +272,8 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
var etag string
if shouldCreateVersionForCopy(dstVersioningState) {
// For versioned destination, create a new version using appropriate format
dstVersionId = s3a.generateVersionIdForObject(dstBucket, dstObject)
// For versioned destination, create a new version
dstVersionId = generateVersionId()
glog.V(2).Infof("CopyObjectHandler: creating version %s for destination %s/%s", dstVersionId, dstBucket, dstObject)
// Add version metadata to the entry
@@ -313,8 +313,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
}
// Update the .versions directory metadata
// Pass dstEntry to cache its metadata for single-scan list efficiency
err = s3a.updateLatestVersionInDirectory(dstBucket, dstObject, dstVersionId, versionFileName, dstEntry)
err = s3a.updateLatestVersionInDirectory(dstBucket, dstObject, dstVersionId, versionFileName)
if err != nil {
glog.Errorf("CopyObjectHandler: failed to update latest version in directory: %v", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
+50 -23
View File
@@ -3,11 +3,11 @@ package s3api
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"sort"
"strconv"
"strings"
@@ -53,16 +53,19 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
// collect parameters
bucket, _ := s3_constants.GetBucketAndObject(r)
originalPrefix, startAfter, delimiter, continuationToken, encodingTypeUrl, fetchOwner, maxKeys, allowUnordered, errCode := getListObjectsV2Args(r.URL.Query())
glog.V(3).Infof("ListObjectsV2Handler %s", bucket)
glog.V(2).Infof("ListObjectsV2Handler bucket=%s prefix=%s", bucket, originalPrefix)
originalPrefix, startAfter, delimiter, continuationToken, encodingTypeUrl, fetchOwner, maxKeys, allowUnordered, errCode := getListObjectsV2Args(r.URL.Query())
if errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
// maxKeys is uint16 here; negative values are rejected during parsing.
if maxKeys < 0 {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
return
}
// AWS S3 compatibility: allow-unordered cannot be used with delimiter
if allowUnordered && delimiter != "" {
@@ -118,9 +121,9 @@ func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Requ
// collect parameters
bucket, _ := s3_constants.GetBucketAndObject(r)
originalPrefix, marker, delimiter, encodingTypeUrl, maxKeys, allowUnordered, errCode := getListObjectsV1Args(r.URL.Query())
glog.V(3).Infof("ListObjectsV1Handler %s", bucket)
glog.V(2).Infof("ListObjectsV1Handler bucket=%s prefix=%s", bucket, originalPrefix)
originalPrefix, marker, delimiter, encodingTypeUrl, maxKeys, allowUnordered, errCode := getListObjectsV1Args(r.URL.Query())
if errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
@@ -444,8 +447,9 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
// prefix and marker should be under dir, marker may contain "/"
// maxKeys should be updated for each recursion
// glog.V(4).Infof("doListFilerEntries dir: %s, prefix: %s, marker %s, maxKeys: %d, prefixEndsOnDelimiter: %+v", dir, prefix, marker, cursor.maxKeys, cursor.prefixEndsOnDelimiter)
// When listing at bucket root with delimiter '/', prefix can be "/" after normalization.
// Returning early here would incorrectly hide all top-level entries (folders like "Veeam/").
if prefix == "/" && delimiter == "/" {
return
}
if cursor.maxKeys <= 0 {
return // Don't set isTruncated here - let caller decide based on whether more entries exist
}
@@ -487,8 +491,7 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
}
// Track .versions directories found in this directory for later processing
// Store the full entry to avoid additional getEntry calls (N+1 query optimization)
var versionsDirs []*filer_pb.Entry
var versionsDirs []string
for {
resp, recvErr := stream.Recv()
@@ -525,10 +528,9 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
}
// Skip .versions directories in regular list operations but track them for logical object creation
// Store the full entry to avoid additional getEntry calls later
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
glog.V(4).Infof("Found .versions directory: %s", entry.Name)
versionsDirs = append(versionsDirs, entry)
versionsDirs = append(versionsDirs, entry.Name)
continue
}
@@ -566,7 +568,6 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
// After processing all regular entries, handle versioned objects
// Create logical entries for objects that have .versions directories
// OPTIMIZATION: Use the already-fetched .versions directory entry to avoid N+1 queries
for _, versionsDir := range versionsDirs {
if cursor.maxKeys <= 0 {
cursor.isTruncated = true
@@ -575,10 +576,10 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
// Update nextMarker to ensure pagination advances past this .versions directory
// This is critical to prevent infinite loops when results are truncated
nextMarker = versionsDir.Name
nextMarker = versionsDir
// Extract object name from .versions directory name (remove .versions suffix)
baseObjectName := strings.TrimSuffix(versionsDir.Name, s3_constants.VersionsFolder)
baseObjectName := strings.TrimSuffix(versionsDir, s3_constants.VersionsFolder)
// Construct full object path relative to bucket
// dir is something like "/buckets/sea-test-1/Veeam/Backup/vbr/Config"
@@ -601,17 +602,12 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
glog.V(4).Infof("Processing versioned object: baseObjectName=%s, bucketRelativePath=%s, fullObjectPath=%s",
baseObjectName, bucketRelativePath, fullObjectPath)
// OPTIMIZATION: Use metadata from the already-fetched .versions directory entry
// This avoids additional getEntry calls which cause high "find" usage
if latestVersionEntry, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucketName, fullObjectPath, versionsDir); err == nil {
// Get the latest version information for this object
if latestVersionEntry, latestVersionErr := s3a.getLatestVersionEntryForListOperation(bucketName, fullObjectPath); latestVersionErr == nil {
glog.V(4).Infof("Creating logical entry for versioned object: %s", fullObjectPath)
eachEntryFn(dir, latestVersionEntry)
} else if errors.Is(err, ErrDeleteMarker) {
// Expected: latest version is a delete marker, object should not appear in list
glog.V(4).Infof("Skipping versioned object %s: delete marker", fullObjectPath)
} else {
// Unexpected failure: missing metadata, fetch error, etc.
glog.V(3).Infof("Skipping versioned object %s due to error: %v", fullObjectPath, err)
glog.V(4).Infof("Failed to get latest version for %s: %v", fullObjectPath, latestVersionErr)
}
}
@@ -716,6 +712,37 @@ func (s3a *S3ApiServer) ensureDirectoryAllEmpty(filerClient filer_pb.SeaweedFile
return true, nil
}
// getLatestVersionEntryForListOperation gets the latest version of an object and creates a logical entry for list operations
// This is used to show versioned objects as logical object names in regular list operations
func (s3a *S3ApiServer) getLatestVersionEntryForListOperation(bucket, object string) (*filer_pb.Entry, error) {
// Get the latest version entry
latestVersionEntry, err := s3a.getLatestObjectVersion(bucket, object)
if err != nil {
return nil, fmt.Errorf("failed to get latest version: %w", err)
}
// Check if this is a delete marker (should not be shown in regular list)
if latestVersionEntry.Extended != nil {
if deleteMarker, exists := latestVersionEntry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
return nil, fmt.Errorf("latest version is a delete marker")
}
}
// Create a logical entry that appears to be stored at the object path (not the versioned path)
// This allows the list operation to show the logical object name while preserving all metadata
// Use path.Base to get just the filename, since the entry.Name should be the local name only
// (the directory path is already included in the 'dir' parameter passed to eachEntryFn)
logicalEntry := &filer_pb.Entry{
Name: path.Base(object),
IsDirectory: false,
Attributes: latestVersionEntry.Attributes,
Extended: latestVersionEntry.Extended,
Chunks: latestVersionEntry.Chunks,
}
return logicalEntry, nil
}
// compareWithDelimiter compares two strings for sorting, treating the delimiter character
// as having lower precedence than other characters to match AWS S3 behavior.
// For example, with delimiter '/', 'foo/' should come before 'foo+1/' even though '+' < '/' in ASCII.
@@ -1,63 +1,14 @@
package s3api
import (
"context"
"io"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
grpc "google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
type testListEntriesStream struct {
entries []*filer_pb.Entry
idx int
}
func (s *testListEntriesStream) Recv() (*filer_pb.ListEntriesResponse, error) {
if s.idx >= len(s.entries) {
return nil, io.EOF
}
resp := &filer_pb.ListEntriesResponse{Entry: s.entries[s.idx]}
s.idx++
return resp, nil
}
func (s *testListEntriesStream) Header() (metadata.MD, error) { return metadata.MD{}, nil }
func (s *testListEntriesStream) Trailer() metadata.MD { return metadata.MD{} }
func (s *testListEntriesStream) Close() error { return nil }
func (s *testListEntriesStream) Context() context.Context { return context.Background() }
func (s *testListEntriesStream) SendMsg(m interface{}) error { return nil }
func (s *testListEntriesStream) RecvMsg(m interface{}) error { return nil }
func (s *testListEntriesStream) CloseSend() error { return nil }
type testFilerClient struct {
filer_pb.SeaweedFilerClient
entriesByDir map[string][]*filer_pb.Entry
}
func (c *testFilerClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
entries := c.entriesByDir[in.Directory]
// Simplified mock: implements basic prefix filtering but ignores Limit, StartFromFileName, and InclusiveStartFrom
// to keep test logic focused. Prefix "/" is treated as no filter for bucket root compatibility.
if in.Prefix != "" && in.Prefix != "/" {
filtered := make([]*filer_pb.Entry, 0)
for _, e := range entries {
if strings.HasPrefix(e.Name, in.Prefix) {
filtered = append(filtered, e)
}
}
entries = filtered
}
return &testListEntriesStream{entries: entries}, nil
}
func TestListObjectsHandler(t *testing.T) {
// https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html
@@ -102,13 +53,6 @@ func Test_normalizePrefixMarker(t *testing.T) {
wantAlignedPrefix string
wantAlignedMarker string
}{
{"bucket root listing with delimiter",
args{"/",
""},
"",
"",
"",
},
{"prefix is a directory",
args{"/parentDir/data/",
""},
@@ -202,31 +146,6 @@ func TestAllowUnorderedParameterValidation(t *testing.T) {
})
}
func TestDoListFilerEntries_BucketRootPrefixSlashDelimiterSlash_ListsDirectories(t *testing.T) {
// Regression test for a bug where doListFilerEntries returned early when
// prefix == "/" && delimiter == "/", causing bucket-root folder listings
// (e.g. Veeam v13) to return empty results.
s3a := &S3ApiServer{}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test-bucket": {
{Name: "Veeam", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
},
}
cursor := &ListingCursor{maxKeys: 1000}
seen := make([]string, 0)
_, err := s3a.doListFilerEntries(client, "/buckets/test-bucket", "/", cursor, "", "/", false, func(dir string, entry *filer_pb.Entry) {
if entry.IsDirectory {
seen = append(seen, entry.Name)
}
})
assert.NoError(t, err)
assert.Contains(t, seen, "Veeam")
}
func TestAllowUnorderedWithDelimiterValidation(t *testing.T) {
t.Run("should return error when allow-unordered=true and delimiter are both present", func(t *testing.T) {
// Create a request with both allow-unordered=true and delimiter
+17 -16
View File
@@ -76,7 +76,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
// http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
bucket, object := s3_constants.GetBucketAndObject(r)
glog.V(2).Infof("PutObjectHandler bucket=%s object=%s size=%d", bucket, object, r.ContentLength)
glog.V(3).Infof("PutObjectHandler %s %s", bucket, object)
_, err := validateContentMd5(r.Header)
if err != nil {
@@ -946,16 +946,13 @@ func (s3a *S3ApiServer) updateIsLatestFlagsForSuspendedVersioning(bucket, object
}
func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object string, dataReader io.Reader, objectContentType string) (versionId string, etag string, errCode s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
// Generate version ID
versionId = generateVersionId()
// Normalize object path to ensure consistency with toFilerPath behavior
normalizedObject := removeDuplicateSlashes(object)
// Check if .versions directory exists to determine format
useInvertedFormat := s3a.getVersionIdFormat(bucket, normalizedObject)
// Generate version ID using the appropriate format
versionId = generateVersionId(useInvertedFormat)
glog.V(2).Infof("putVersionedObject: creating version %s for %s/%s (normalized: %s, inverted=%v)", versionId, bucket, object, normalizedObject, useInvertedFormat)
glog.V(2).Infof("putVersionedObject: creating version %s for %s/%s (normalized: %s)", versionId, bucket, object, normalizedObject)
// Create the version file name
versionFileName := s3a.getVersionFileName(versionId)
@@ -964,7 +961,17 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
// We need to construct the object path relative to the bucket
versionObjectPath := normalizedObject + s3_constants.VersionsFolder + "/" + versionFileName
versionFilePath := s3a.toFilerPath(bucket, versionObjectPath)
// Ensure the .versions directory exists before uploading
bucketDir := s3a.option.BucketsPath + "/" + bucket
versionsDir := normalizedObject + s3_constants.VersionsFolder
err := s3a.mkdir(bucketDir, versionsDir, func(entry *filer_pb.Entry) {
entry.Attributes.Mime = s3_constants.FolderMimeType
})
if err != nil {
glog.Errorf("putVersionedObject: failed to create .versions directory: %v", err)
return "", "", s3err.ErrInternalError, SSEResponseMetadata{}
}
body := dataReader
if objectContentType == "" {
@@ -982,7 +989,6 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
// Get the uploaded entry to add versioning metadata
// Use retry logic to handle filer consistency delays
var versionEntry *filer_pb.Entry
var err error
maxRetries := 8
for attempt := 1; attempt <= maxRetries; attempt++ {
versionEntry, err = s3a.getEntry(bucketDir, versionObjectPath)
@@ -1035,8 +1041,7 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
}
// Update the .versions directory metadata to indicate this is the latest version
// Pass versionEntry to cache its metadata for single-scan list efficiency
err = s3a.updateLatestVersionInDirectory(bucket, normalizedObject, versionId, versionFileName, versionEntry)
err = s3a.updateLatestVersionInDirectory(bucket, normalizedObject, versionId, versionFileName)
if err != nil {
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
return "", "", s3err.ErrInternalError, SSEResponseMetadata{}
@@ -1046,8 +1051,7 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
}
// updateLatestVersionInDirectory updates the .versions directory metadata to indicate the latest version
// versionEntry contains the metadata (size, ETag, mtime, owner) to cache for single-scan list efficiency
func (s3a *S3ApiServer) updateLatestVersionInDirectory(bucket, object, versionId, versionFileName string, versionEntry *filer_pb.Entry) error {
func (s3a *S3ApiServer) updateLatestVersionInDirectory(bucket, object, versionId, versionFileName string) error {
bucketDir := s3a.option.BucketsPath + "/" + bucket
versionsObjectPath := object + s3_constants.VersionsFolder
@@ -1080,9 +1084,6 @@ func (s3a *S3ApiServer) updateLatestVersionInDirectory(bucket, object, versionId
versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey] = []byte(versionId)
versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte(versionFileName)
// Cache list metadata for single-scan efficiency (avoids extra getEntry per object during list)
setCachedListMetadata(versionsEntry, versionEntry)
// Update the .versions directory entry with metadata
err = s3a.mkFile(bucketDir, versionsObjectPath, versionsEntry.Chunks, func(updatedEntry *filer_pb.Entry) {
updatedEntry.Extended = versionsEntry.Extended
+329 -513
View File
@@ -1,13 +1,9 @@
package s3api
// This file contains the core S3 versioning operations.
// Version ID format handling is in s3api_version_id.go
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/xml"
"errors"
"fmt"
"net/http"
"path"
@@ -23,65 +19,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
// ErrDeleteMarker is returned when the latest version is a delete marker (expected condition)
var ErrDeleteMarker = errors.New("latest version is a delete marker")
// clearCachedVersionMetadata clears only the version metadata fields (not ID/filename).
// Used by setCachedListMetadata to prevent stale values when updating.
func clearCachedVersionMetadata(extended map[string][]byte) {
delete(extended, s3_constants.ExtLatestVersionSizeKey)
delete(extended, s3_constants.ExtLatestVersionMtimeKey)
delete(extended, s3_constants.ExtLatestVersionETagKey)
delete(extended, s3_constants.ExtLatestVersionOwnerKey)
delete(extended, s3_constants.ExtLatestVersionIsDeleteMarker)
}
// setCachedListMetadata caches list metadata in the .versions directory entry for single-scan efficiency
func setCachedListMetadata(versionsEntry, versionEntry *filer_pb.Entry) {
if versionEntry == nil || versionsEntry == nil {
return
}
if versionsEntry.Extended == nil {
versionsEntry.Extended = make(map[string][]byte)
}
// Clear old cached metadata to prevent stale values
// Note: We don't use clearCachedListMetadata here because it also clears
// ExtLatestVersionIdKey and ExtLatestVersionFileNameKey, which are set by the caller
clearCachedVersionMetadata(versionsEntry.Extended)
// Size and Mtime
if versionEntry.Attributes != nil {
versionsEntry.Extended[s3_constants.ExtLatestVersionSizeKey] = []byte(strconv.FormatUint(versionEntry.Attributes.FileSize, 10))
versionsEntry.Extended[s3_constants.ExtLatestVersionMtimeKey] = []byte(strconv.FormatInt(versionEntry.Attributes.Mtime, 10))
}
// ETag, Owner, DeleteMarker from Extended
if versionEntry.Extended != nil {
if etag, ok := versionEntry.Extended[s3_constants.ExtETagKey]; ok {
versionsEntry.Extended[s3_constants.ExtLatestVersionETagKey] = etag
}
if owner, ok := versionEntry.Extended[s3_constants.ExtAmzOwnerKey]; ok {
versionsEntry.Extended[s3_constants.ExtLatestVersionOwnerKey] = owner
}
if deleteMarker, ok := versionEntry.Extended[s3_constants.ExtDeleteMarkerKey]; ok {
versionsEntry.Extended[s3_constants.ExtLatestVersionIsDeleteMarker] = deleteMarker
} else {
versionsEntry.Extended[s3_constants.ExtLatestVersionIsDeleteMarker] = []byte("false")
}
}
}
// clearCachedListMetadata removes all cached list metadata from the .versions directory entry
func clearCachedListMetadata(extended map[string][]byte) {
if extended == nil {
return
}
delete(extended, s3_constants.ExtLatestVersionIdKey)
delete(extended, s3_constants.ExtLatestVersionFileNameKey)
clearCachedVersionMetadata(extended)
}
// S3ListObjectVersionsResult - Custom struct for S3 list-object-versions response
// This avoids conflicts with the XSD generated ListVersionsResult struct
// and ensures proper separation of versions and delete markers into arrays
@@ -136,59 +73,73 @@ type ObjectVersion struct {
OwnerID string // Owner ID extracted from entry metadata
}
// generateVersionId creates a unique version ID that preserves chronological order
func generateVersionId() string {
// Use nanosecond timestamp to ensure chronological ordering
// Format as 16-digit hex (first 16 chars of version ID)
now := time.Now().UnixNano()
timestampHex := fmt.Sprintf("%016x", now)
// Generate random 8 bytes for uniqueness (last 16 chars of version ID)
randBytes := make([]byte, 8)
if _, err := rand.Read(randBytes); err != nil {
glog.Errorf("Failed to generate random bytes for version ID: %v", err)
// Fallback to timestamp-only if random generation fails
return timestampHex + "0000000000000000"
}
// Combine timestamp (16 chars) + random (16 chars) = 32 chars total
randomHex := hex.EncodeToString(randBytes)
versionId := timestampHex + randomHex
return versionId
}
// getVersionedObjectDir returns the directory path for storing object versions
func (s3a *S3ApiServer) getVersionedObjectDir(bucket, object string) string {
return path.Join(s3a.option.BucketsPath, bucket, object+s3_constants.VersionsFolder)
}
// getVersionFileName returns the filename for a specific version
func (s3a *S3ApiServer) getVersionFileName(versionId string) string {
return fmt.Sprintf("v_%s", versionId)
}
// createDeleteMarker creates a delete marker for versioned delete operations
func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, error) {
// Clean up the object path first
cleanObject := strings.TrimPrefix(object, "/")
versionId := generateVersionId()
// Check if .versions directory exists to determine format
useInvertedFormat := s3a.getVersionIdFormat(bucket, cleanObject)
versionId := generateVersionId(useInvertedFormat)
glog.V(2).Infof("createDeleteMarker: creating delete marker %s for %s/%s (inverted=%v)", versionId, bucket, object, useInvertedFormat)
glog.V(2).Infof("createDeleteMarker: creating delete marker %s for %s/%s", versionId, bucket, object)
// Create the version file name for the delete marker
versionFileName := s3a.getVersionFileName(versionId)
// Store delete marker in the .versions directory
// Make sure to clean up the object path to remove leading slashes
cleanObject := strings.TrimPrefix(object, "/")
bucketDir := s3a.option.BucketsPath + "/" + bucket
versionsDir := bucketDir + "/" + cleanObject + s3_constants.VersionsFolder
// Create the delete marker entry in the .versions directory
deleteMarkerMtime := time.Now().Unix()
deleteMarkerExtended := map[string][]byte{
s3_constants.ExtVersionIdKey: []byte(versionId),
s3_constants.ExtDeleteMarkerKey: []byte("true"),
}
err := s3a.mkFile(versionsDir, versionFileName, nil, func(entry *filer_pb.Entry) {
entry.Name = versionFileName
entry.IsDirectory = false
if entry.Attributes == nil {
entry.Attributes = &filer_pb.FuseAttributes{}
}
entry.Attributes.Mtime = deleteMarkerMtime
entry.Attributes.Mtime = time.Now().Unix()
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
for k, v := range deleteMarkerExtended {
entry.Extended[k] = v
}
entry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionId)
entry.Extended[s3_constants.ExtDeleteMarkerKey] = []byte("true")
})
if err != nil {
return "", fmt.Errorf("failed to create delete marker in .versions directory: %w", err)
}
// Update the .versions directory metadata to indicate this delete marker is the latest version
// Pass deleteMarkerEntry to cache its metadata for single-scan list efficiency
deleteMarkerEntry := &filer_pb.Entry{
Name: versionFileName,
IsDirectory: false,
Attributes: &filer_pb.FuseAttributes{
Mtime: deleteMarkerMtime,
},
Extended: deleteMarkerExtended,
}
err = s3a.updateLatestVersionInDirectory(bucket, cleanObject, versionId, versionFileName, deleteMarkerEntry)
err = s3a.updateLatestVersionInDirectory(bucket, cleanObject, versionId, versionFileName)
if err != nil {
glog.Errorf("createDeleteMarker: failed to update latest version in directory: %v", err)
return "", fmt.Errorf("failed to update latest version in directory: %w", err)
@@ -208,7 +159,7 @@ func (s3a *S3ApiServer) listObjectVersions(bucket, prefix, keyMarker, versionIdM
// The extra 1 is for truncation detection
allVersions := make([]interface{}, 0, maxKeys+1)
glog.V(1).Infof("listObjectVersions: listing versions for bucket %s, prefix '%s', keyMarker '%s', versionIdMarker '%s'", bucket, prefix, keyMarker, versionIdMarker)
glog.V(1).Infof("listObjectVersions: listing versions for bucket %s, prefix '%s'", bucket, prefix)
// Track objects that have been processed to avoid duplicates
processedObjects := make(map[string]bool)
@@ -217,19 +168,14 @@ func (s3a *S3ApiServer) listObjectVersions(bucket, prefix, keyMarker, versionIdM
seenVersionIds := make(map[string]bool)
// Recursively find all .versions directories in the bucket
// Pass keyMarker and versionIdMarker to enable efficient pagination (skip entries before marker)
// When keyMarker is set, we need to collect all versions since filtering happens after sorting
// Pass 0 (unlimited) when keyMarker is set, otherwise maxKeys+1 for truncation detection
bucketPath := path.Join(s3a.option.BucketsPath, bucket)
// Memory optimization: limit collection to maxKeys+1 versions.
// This works correctly for objects using the NEW inverted-timestamp format, where
// filesystem order (lexicographic) matches sorted order (newest-first).
// For OLD format objects (raw timestamps), filesystem order is oldest-first, so
// limiting collection may return older versions instead of newest. However:
// - New objects going forward use the new format
// - The alternative (collecting all) causes memory issues for buckets with many versions
// - Pagination continues correctly; users can page through to see all versions
maxCollect := maxKeys + 1 // +1 to detect truncation
err := s3a.findVersionsRecursively(bucketPath, "", &allVersions, processedObjects, seenVersionIds, bucket, prefix, keyMarker, versionIdMarker, maxCollect)
maxCollect := maxKeys + 1
if keyMarker != "" {
maxCollect = 0 // Collect all versions when paginating, filter after sort
}
err := s3a.findVersionsRecursively(bucketPath, "", &allVersions, processedObjects, seenVersionIds, bucket, prefix, maxCollect)
if err != nil {
glog.Errorf("listObjectVersions: findVersionsRecursively failed: %v", err)
return nil, err
@@ -241,27 +187,31 @@ func (s3a *S3ApiServer) listObjectVersions(bucket, prefix, keyMarker, versionIdM
glog.V(1).Infof("listObjectVersions: found %d total versions", len(allVersions))
// Sort by key, then by version (newest first)
// Uses compareVersionIds to handle both old and new format version IDs
// Sort by key, then by LastModified (newest first), then by VersionId for deterministic ordering
sort.Slice(allVersions, func(i, j int) bool {
var keyI, keyJ string
var lastModifiedI, lastModifiedJ time.Time
var versionIdI, versionIdJ string
switch v := allVersions[i].(type) {
case *VersionEntry:
keyI = v.Key
lastModifiedI = v.LastModified
versionIdI = v.VersionId
case *DeleteMarkerEntry:
keyI = v.Key
lastModifiedI = v.LastModified
versionIdI = v.VersionId
}
switch v := allVersions[j].(type) {
case *VersionEntry:
keyJ = v.Key
lastModifiedJ = v.LastModified
versionIdJ = v.VersionId
case *DeleteMarkerEntry:
keyJ = v.Key
lastModifiedJ = v.LastModified
versionIdJ = v.VersionId
}
@@ -270,11 +220,53 @@ func (s3a *S3ApiServer) listObjectVersions(bucket, prefix, keyMarker, versionIdM
return keyI < keyJ
}
// Then by version ID (newest first)
// compareVersionIds handles both old (raw timestamp) and new (inverted timestamp) formats
return compareVersionIds(versionIdI, versionIdJ) < 0
// Then by modification time (newest first) - but use nanosecond precision for ties
timeDiff := lastModifiedI.Sub(lastModifiedJ)
if timeDiff.Abs() > time.Millisecond {
return lastModifiedI.After(lastModifiedJ)
}
// For very close timestamps (within 1ms), use version ID for deterministic ordering
// Sort version IDs in reverse lexicographic order to maintain newest-first semantics
return versionIdI > versionIdJ
})
// Apply key-marker and version-id-marker filtering
// S3 pagination: skip versions at or before the marker, return versions AFTER the marker
// Versions are sorted: key ascending, then versionId descending (newest first for same key)
//
// S3 behavior:
// - If key-marker is specified without version-id-marker: start after ALL versions of key-marker
// - If both are specified: start after the specific version of key-marker
if keyMarker != "" {
filteredVersions := make([]interface{}, 0, len(allVersions))
for _, version := range allVersions {
var key, versionId string
switch v := version.(type) {
case *VersionEntry:
key = v.Key
versionId = v.VersionId
case *DeleteMarkerEntry:
key = v.Key
versionId = v.VersionId
}
// Include this version if it's AFTER the marker
if key > keyMarker {
// Key is after marker key: always include
filteredVersions = append(filteredVersions, version)
} else if key == keyMarker && versionIdMarker != "" && versionId < versionIdMarker {
// Same key, but version is after the marker version (versionIds sorted descending)
filteredVersions = append(filteredVersions, version)
}
// else: key < keyMarker OR (key == keyMarker with no versionIdMarker or version already seen)
// skip this version (it was in a previous page)
}
glog.V(1).Infof("listObjectVersions: after applying markers (key=%s, versionId=%s), %d -> %d versions",
keyMarker, versionIdMarker, len(allVersions), len(filteredVersions))
allVersions = filteredVersions
}
// Build result using S3ListObjectVersionsResult to avoid conflicts with XSD structs
result := &S3ListObjectVersionsResult{
Name: bucket,
@@ -328,310 +320,255 @@ func (s3a *S3ApiServer) listObjectVersions(bucket, prefix, keyMarker, versionIdM
return result, nil
}
// versionCollector holds state for collecting object versions during recursive traversal
type versionCollector struct {
s3a *S3ApiServer
bucket string
prefix string
keyMarker string
versionIdMarker string
maxCollect int
allVersions *[]interface{}
processedObjects map[string]bool
seenVersionIds map[string]bool
}
// isFull returns true if we've collected enough versions
func (vc *versionCollector) isFull() bool {
return vc.maxCollect > 0 && len(*vc.allVersions) >= vc.maxCollect
}
// matchesPrefixFilter checks if an entry path matches the prefix filter
func (vc *versionCollector) matchesPrefixFilter(entryPath string, isDirectory bool) bool {
normalizedPrefix := strings.TrimPrefix(vc.prefix, "/")
if normalizedPrefix == "" {
return true
}
// Entry matches if its path starts with the prefix
isMatch := strings.HasPrefix(entryPath, normalizedPrefix)
if !isMatch && isDirectory {
// Directory might match with trailing slash
isMatch = strings.HasPrefix(entryPath+"/", normalizedPrefix)
}
// For directories, also check if we need to descend (prefix is deeper)
canDescend := isDirectory && strings.HasPrefix(normalizedPrefix, entryPath)
return isMatch || canDescend
}
// shouldSkipObjectForMarker returns true if the object should be skipped based on keyMarker
func (vc *versionCollector) shouldSkipObjectForMarker(objectKey string) bool {
if vc.keyMarker == "" {
return false
}
return objectKey < vc.keyMarker
}
// shouldSkipVersionForMarker returns true if a version should be skipped based on markers
// For the keyMarker object, skip versions that are newer than or equal to versionIdMarker
// (these were already returned in previous pages).
// Handles both old (raw timestamp) and new (inverted timestamp) version ID formats.
func (vc *versionCollector) shouldSkipVersionForMarker(objectKey, versionId string) bool {
if vc.keyMarker == "" || objectKey != vc.keyMarker {
return false
}
// Object matches keyMarker - apply version filtering
if vc.versionIdMarker == "" {
// No versionIdMarker means skip ALL versions of this key (they were all returned in previous pages)
return true
}
// Skip versions that are newer than or equal to versionIdMarker
// compareVersionIds returns negative if versionId is newer than marker
// We skip if versionId is newer (negative) or equal (zero) to the marker
cmp := compareVersionIds(versionId, vc.versionIdMarker)
return cmp <= 0
}
// addVersion adds a version or delete marker to results
func (vc *versionCollector) addVersion(version *ObjectVersion, objectKey string) {
if version.IsDeleteMarker {
deleteMarker := &DeleteMarkerEntry{
Key: objectKey,
VersionId: version.VersionId,
IsLatest: version.IsLatest,
LastModified: version.LastModified,
Owner: vc.s3a.getObjectOwnerFromVersion(version, vc.bucket, objectKey),
}
*vc.allVersions = append(*vc.allVersions, deleteMarker)
} else {
versionEntry := &VersionEntry{
Key: objectKey,
VersionId: version.VersionId,
IsLatest: version.IsLatest,
LastModified: version.LastModified,
ETag: version.ETag,
Size: version.Size,
Owner: vc.s3a.getObjectOwnerFromVersion(version, vc.bucket, objectKey),
StorageClass: "STANDARD",
}
*vc.allVersions = append(*vc.allVersions, versionEntry)
}
}
// processVersionsDirectory handles a .versions directory entry
func (vc *versionCollector) processVersionsDirectory(entryPath string) error {
objectKey := strings.TrimSuffix(entryPath, s3_constants.VersionsFolder)
normalizedObjectKey := removeDuplicateSlashes(objectKey)
// Mark as processed
vc.processedObjects[objectKey] = true
vc.processedObjects[normalizedObjectKey] = true
// Skip objects before keyMarker
if vc.shouldSkipObjectForMarker(normalizedObjectKey) {
glog.V(4).Infof("processVersionsDirectory: skipping object %s (before keyMarker %s)", normalizedObjectKey, vc.keyMarker)
return nil
}
glog.V(2).Infof("processVersionsDirectory: found object %s", normalizedObjectKey)
versions, err := vc.s3a.getObjectVersionList(vc.bucket, normalizedObjectKey)
if err != nil {
glog.Warningf("processVersionsDirectory: failed to get versions for %s: %v", normalizedObjectKey, err)
return nil // Continue with other entries
}
for _, version := range versions {
if vc.isFull() {
return nil
}
versionKey := normalizedObjectKey + ":" + version.VersionId
if vc.seenVersionIds[versionKey] {
continue
}
// Skip versions that were already returned in previous pages
if vc.shouldSkipVersionForMarker(normalizedObjectKey, version.VersionId) {
continue
}
vc.seenVersionIds[versionKey] = true
vc.addVersion(version, normalizedObjectKey)
}
return nil
}
// processExplicitDirectory handles an explicit S3 directory object
func (vc *versionCollector) processExplicitDirectory(entryPath string, entry *filer_pb.Entry) {
directoryKey := entryPath
if !strings.HasSuffix(directoryKey, "/") {
directoryKey += "/"
}
// Skip directories at or before keyMarker
if vc.keyMarker != "" && directoryKey <= vc.keyMarker {
return
}
versionEntry := &VersionEntry{
Key: directoryKey,
VersionId: "null",
IsLatest: true,
LastModified: time.Unix(entry.Attributes.Mtime, 0),
ETag: "\"d41d8cd98f00b204e9800998ecf8427e\"", // Empty content ETag
Size: 0,
Owner: vc.s3a.getObjectOwnerFromEntry(entry),
StorageClass: "STANDARD",
}
*vc.allVersions = append(*vc.allVersions, versionEntry)
}
// processRegularFile handles a regular file entry (pre-versioning or suspended-versioning object)
func (vc *versionCollector) processRegularFile(currentPath, entryPath string, entry *filer_pb.Entry) {
objectKey := entryPath
normalizedObjectKey := removeDuplicateSlashes(objectKey)
// Skip files before keyMarker
if vc.shouldSkipObjectForMarker(normalizedObjectKey) {
return
}
// For keyMarker match, skip if this null version was already returned
if vc.shouldSkipVersionForMarker(normalizedObjectKey, "null") {
return
}
// Skip if already processed via .versions directory
if vc.processedObjects[objectKey] || vc.processedObjects[normalizedObjectKey] {
return
}
// Check if this file has version metadata
hasVersionMeta := entry.Extended != nil && entry.Extended[s3_constants.ExtVersionIdKey] != nil
// Check if a .versions directory exists for this object
versionsEntryName := entry.Name + s3_constants.VersionsFolder
_, versionsErr := vc.s3a.getEntry(currentPath, versionsEntryName)
if versionsErr == nil && !hasVersionMeta {
// .versions exists but file has no version metadata - check for null version in .versions
versions, err := vc.s3a.getObjectVersionList(vc.bucket, normalizedObjectKey)
if err == nil {
for _, v := range versions {
if v.VersionId == "null" {
// Null version exists in .versions, skip this file
vc.processedObjects[objectKey] = true
vc.processedObjects[normalizedObjectKey] = true
return
}
}
}
}
// Check for duplicate
versionKey := normalizedObjectKey + ":null"
if vc.seenVersionIds[versionKey] {
return
}
vc.seenVersionIds[versionKey] = true
versionEntry := &VersionEntry{
Key: normalizedObjectKey,
VersionId: "null",
IsLatest: true,
LastModified: time.Unix(entry.Attributes.Mtime, 0),
ETag: vc.s3a.calculateETagFromChunks(entry.Chunks),
Size: int64(entry.Attributes.FileSize),
Owner: vc.s3a.getObjectOwnerFromEntry(entry),
StorageClass: "STANDARD",
}
*vc.allVersions = append(*vc.allVersions, versionEntry)
}
// findVersionsRecursively searches for .versions directories and regular files recursively
// with efficient pagination support. It skips objects before keyMarker and applies versionIdMarker filtering.
// maxCollect limits the number of versions to collect for memory efficiency (must be > 0)
func (s3a *S3ApiServer) findVersionsRecursively(currentPath, relativePath string, allVersions *[]interface{}, processedObjects map[string]bool, seenVersionIds map[string]bool, bucket, prefix, keyMarker, versionIdMarker string, maxCollect int) error {
vc := &versionCollector{
s3a: s3a,
bucket: bucket,
prefix: prefix,
keyMarker: keyMarker,
versionIdMarker: versionIdMarker,
maxCollect: maxCollect,
allVersions: allVersions,
processedObjects: processedObjects,
seenVersionIds: seenVersionIds,
}
return vc.collectVersions(currentPath, relativePath)
}
// collectVersions recursively collects versions from the given path
func (vc *versionCollector) collectVersions(currentPath, relativePath string) error {
// findVersionsRecursively searches for all .versions directories and regular files recursively
// maxCollect limits the number of versions to collect for memory efficiency (0 = unlimited)
func (s3a *S3ApiServer) findVersionsRecursively(currentPath, relativePath string, allVersions *[]interface{}, processedObjects map[string]bool, seenVersionIds map[string]bool, bucket, prefix string, maxCollect int) error {
// List entries in current directory with pagination
startFrom := ""
for {
if vc.isFull() {
// Early termination: stop if we've collected enough versions
if maxCollect > 0 && len(*allVersions) >= maxCollect {
return nil
}
entries, isLast, err := vc.s3a.list(currentPath, "", startFrom, false, filer.PaginationSize)
entries, isLast, err := s3a.list(currentPath, "", startFrom, false, filer.PaginationSize)
if err != nil {
return err
}
for _, entry := range entries {
if vc.isFull() {
// Early termination check inside loop
if maxCollect > 0 && len(*allVersions) >= maxCollect {
return nil
}
// Track last entry name for pagination
startFrom = entry.Name
entryPath := path.Join(relativePath, entry.Name)
if !vc.matchesPrefixFilter(entryPath, entry.IsDirectory) {
continue
// Skip if this doesn't match the prefix filter
if normalizedPrefix := strings.TrimPrefix(prefix, "/"); normalizedPrefix != "" {
// An entry is a candidate if:
// 1. Its path is a match for the prefix.
// 2. It is a directory that is an ancestor of the prefix path, so we must descend into it.
// Condition 1: The entry's path starts with the prefix.
isMatch := strings.HasPrefix(entryPath, normalizedPrefix)
if !isMatch && entry.IsDirectory {
// Also check if a directory entry matches a directory-style prefix (e.g., prefix "a/", entry "a").
isMatch = strings.HasPrefix(entryPath+"/", normalizedPrefix)
}
// Condition 2: The prefix path starts with the entry's path (and it's a directory).
canDescend := entry.IsDirectory && strings.HasPrefix(normalizedPrefix, entryPath)
if !isMatch && !canDescend {
continue
}
}
if entry.IsDirectory {
if err := vc.processDirectory(currentPath, entryPath, entry); err != nil {
return err
// Skip .uploads directory (multipart upload temporary files)
if strings.HasPrefix(entry.Name, ".uploads") {
continue
}
// Check if this is a .versions directory
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
// Extract object name from .versions directory name
objectKey := strings.TrimSuffix(entryPath, s3_constants.VersionsFolder)
normalizedObjectKey := removeDuplicateSlashes(objectKey)
// Mark both keys as processed for backward compatibility
processedObjects[objectKey] = true
processedObjects[normalizedObjectKey] = true
glog.V(2).Infof("Found .versions directory for object %s (normalized: %s)", objectKey, normalizedObjectKey)
versions, err := s3a.getObjectVersionList(bucket, normalizedObjectKey)
if err != nil {
glog.Warningf("Failed to get versions for object %s (normalized: %s): %v", objectKey, normalizedObjectKey, err)
continue
}
for _, version := range versions {
// Check for duplicate version IDs and skip if already seen
// Use normalized key for deduplication
versionKey := normalizedObjectKey + ":" + version.VersionId
if seenVersionIds[versionKey] {
glog.Warningf("findVersionsRecursively: duplicate version %s for object %s detected, skipping", version.VersionId, normalizedObjectKey)
continue
}
seenVersionIds[versionKey] = true
if version.IsDeleteMarker {
glog.V(4).Infof("Adding delete marker from .versions: objectKey=%s, versionId=%s, isLatest=%v, versionKey=%s",
normalizedObjectKey, version.VersionId, version.IsLatest, versionKey)
deleteMarker := &DeleteMarkerEntry{
Key: normalizedObjectKey, // Use normalized key for consistency
VersionId: version.VersionId,
IsLatest: version.IsLatest,
LastModified: version.LastModified,
Owner: s3a.getObjectOwnerFromVersion(version, bucket, normalizedObjectKey),
}
*allVersions = append(*allVersions, deleteMarker)
} else {
glog.V(4).Infof("Adding version from .versions: objectKey=%s, versionId=%s, isLatest=%v, versionKey=%s",
normalizedObjectKey, version.VersionId, version.IsLatest, versionKey)
versionEntry := &VersionEntry{
Key: normalizedObjectKey, // Use normalized key for consistency
VersionId: version.VersionId,
IsLatest: version.IsLatest,
LastModified: version.LastModified,
ETag: version.ETag,
Size: version.Size,
Owner: s3a.getObjectOwnerFromVersion(version, bucket, normalizedObjectKey),
StorageClass: "STANDARD",
}
*allVersions = append(*allVersions, versionEntry)
}
}
} else {
// This is a regular directory - check if it's an explicit S3 directory object
// Only include directories that were explicitly created via S3 API (have FolderMimeType)
// This excludes implicit directories created when uploading files like "test1/a"
if entry.Attributes.Mime == s3_constants.FolderMimeType {
directoryKey := entryPath
if !strings.HasSuffix(directoryKey, "/") {
directoryKey += "/"
}
// Add directory as a version entry with VersionId "null" (following S3/Minio behavior)
glog.V(2).Infof("findVersionsRecursively: found explicit S3 directory %s", directoryKey)
// Calculate ETag for empty directory
directoryETag := "\"d41d8cd98f00b204e9800998ecf8427e\""
versionEntry := &VersionEntry{
Key: directoryKey,
VersionId: "null",
IsLatest: true,
LastModified: time.Unix(entry.Attributes.Mtime, 0),
ETag: directoryETag,
Size: 0, // Directories have size 0
Owner: s3a.getObjectOwnerFromEntry(entry),
StorageClass: "STANDARD",
}
*allVersions = append(*allVersions, versionEntry)
}
// Recursively search subdirectories (regardless of whether they're explicit or implicit)
fullPath := path.Join(currentPath, entry.Name)
err := s3a.findVersionsRecursively(fullPath, entryPath, allVersions, processedObjects, seenVersionIds, bucket, prefix, maxCollect)
if err != nil {
glog.Warningf("Error searching subdirectory %s: %v", entryPath, err)
continue
}
// Check if we've collected enough after recursion
if maxCollect > 0 && len(*allVersions) >= maxCollect {
return nil
}
}
} else {
vc.processRegularFile(currentPath, entryPath, entry)
// This is a regular file - check if it's a pre-versioning object
objectKey := entryPath
// Normalize object key to ensure consistency with other version operations
normalizedObjectKey := removeDuplicateSlashes(objectKey)
// Skip if this object already has a .versions directory (already processed)
// Check both normalized and original keys for backward compatibility
if processedObjects[objectKey] || processedObjects[normalizedObjectKey] {
glog.V(4).Infof("Skipping already processed object: objectKey=%s, normalizedObjectKey=%s, processedObjects[objectKey]=%v, processedObjects[normalizedObjectKey]=%v",
objectKey, normalizedObjectKey, processedObjects[objectKey], processedObjects[normalizedObjectKey])
continue
}
glog.V(4).Infof("Processing regular file: objectKey=%s, normalizedObjectKey=%s, NOT in processedObjects", objectKey, normalizedObjectKey)
// This is a pre-versioning or suspended-versioning object
// Check if this file has version metadata (ExtVersionIdKey)
hasVersionMeta := false
if entry.Extended != nil {
if versionIdBytes, ok := entry.Extended[s3_constants.ExtVersionIdKey]; ok {
hasVersionMeta = true
glog.V(4).Infof("Regular file %s has version metadata: %s", normalizedObjectKey, string(versionIdBytes))
}
}
// Check if a .versions directory exists for this object
// Use entry.Name (relative to currentPath) to avoid duplicating subdirectory segments
versionsEntryName := entry.Name + s3_constants.VersionsFolder
_, versionsErr := s3a.getEntry(currentPath, versionsEntryName)
if versionsErr == nil {
// .versions directory exists
glog.V(4).Infof("Found .versions directory for regular file %s, hasVersionMeta=%v", normalizedObjectKey, hasVersionMeta)
// If this file has version metadata, it's a suspended versioning null version
// Include it and it will be the latest
if hasVersionMeta {
glog.V(4).Infof("Including suspended versioning file %s (has version metadata)", normalizedObjectKey)
// Continue to add it below
} else {
// No version metadata - this is a pre-versioning file
// Skip it if there's already a null version in .versions
versions, err := s3a.getObjectVersionList(bucket, normalizedObjectKey)
if err == nil {
hasNullVersion := false
for _, v := range versions {
if v.VersionId == "null" {
hasNullVersion = true
break
}
}
if hasNullVersion {
glog.V(4).Infof("Skipping pre-versioning file %s, null version exists in .versions", normalizedObjectKey)
processedObjects[objectKey] = true
processedObjects[normalizedObjectKey] = true
continue
}
}
glog.V(4).Infof("Including pre-versioning file %s (no null version in .versions)", normalizedObjectKey)
}
} else {
glog.V(4).Infof("No .versions directory for regular file %s, hasVersionMeta=%v", normalizedObjectKey, hasVersionMeta)
}
// Add this file as a null version with IsLatest=true
isLatest := true
// Check for duplicate version IDs and skip if already seen
// Use normalized key for deduplication to match how other version operations work
versionKey := normalizedObjectKey + ":null"
if seenVersionIds[versionKey] {
glog.Warningf("findVersionsRecursively: duplicate null version for object %s detected (versionKey=%s), skipping", normalizedObjectKey, versionKey)
continue
}
seenVersionIds[versionKey] = true
etag := s3a.calculateETagFromChunks(entry.Chunks)
glog.V(4).Infof("Adding null version from regular file: objectKey=%s, normalizedObjectKey=%s, versionKey=%s, isLatest=%v, hasVersionMeta=%v",
objectKey, normalizedObjectKey, versionKey, isLatest, hasVersionMeta)
versionEntry := &VersionEntry{
Key: normalizedObjectKey, // Use normalized key for consistency
VersionId: "null",
IsLatest: isLatest,
LastModified: time.Unix(entry.Attributes.Mtime, 0),
ETag: etag,
Size: int64(entry.Attributes.FileSize),
Owner: s3a.getObjectOwnerFromEntry(entry),
StorageClass: "STANDARD",
}
*allVersions = append(*allVersions, versionEntry)
}
}
// If we've reached the last page, stop pagination
if isLast {
break
}
}
return nil
}
// processDirectory handles directory entries
func (vc *versionCollector) processDirectory(currentPath, entryPath string, entry *filer_pb.Entry) error {
// Skip .uploads directory
if strings.HasPrefix(entry.Name, ".uploads") {
return nil
}
// Handle .versions directory
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
return vc.processVersionsDirectory(entryPath)
}
// Handle explicit S3 directory object
if entry.Attributes.Mime == s3_constants.FolderMimeType {
vc.processExplicitDirectory(entryPath, entry)
}
// Recursively search subdirectory
fullPath := path.Join(currentPath, entry.Name)
if err := vc.collectVersions(fullPath, entryPath); err != nil {
glog.Warningf("Error searching subdirectory %s: %v", entryPath, err)
}
return nil
}
@@ -904,7 +841,6 @@ func (s3a *S3ApiServer) updateLatestVersionAfterDeletion(bucket, object string)
// Find the most recent remaining version (latest timestamp in version ID)
var latestVersionId string
var latestVersionFileName string
var latestVersionEntry *filer_pb.Entry
for _, entry := range entries {
if entry.Extended == nil {
@@ -924,15 +860,13 @@ func (s3a *S3ApiServer) updateLatestVersionAfterDeletion(bucket, object string)
continue
}
// Compare version IDs chronologically using unified comparator (handles both old and new formats)
// compareVersionIds returns negative if first arg is newer
if latestVersionId == "" || compareVersionIds(versionId, latestVersionId) < 0 {
// Compare version IDs chronologically (our version IDs start with timestamp)
if latestVersionId == "" || versionId > latestVersionId {
glog.V(1).Infof("updateLatestVersionAfterDeletion: found newer version %s (file: %s)", versionId, entry.Name)
latestVersionId = versionId
latestVersionFileName = entry.Name
latestVersionEntry = entry
} else {
glog.V(1).Infof("updateLatestVersionAfterDeletion: skipping older or equal version %s", versionId)
glog.V(1).Infof("updateLatestVersionAfterDeletion: skipping older version %s", versionId)
}
}
@@ -950,14 +884,11 @@ func (s3a *S3ApiServer) updateLatestVersionAfterDeletion(bucket, object string)
// Update metadata to point to new latest version
versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey] = []byte(latestVersionId)
versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte(latestVersionFileName)
// Update cached list metadata from the new latest version entry
setCachedListMetadata(versionsEntry, latestVersionEntry)
glog.V(2).Infof("updateLatestVersionAfterDeletion: new latest version for %s/%s is %s", bucket, object, latestVersionId)
} else {
// No versions left, remove all cached metadata
clearCachedListMetadata(versionsEntry.Extended)
// No versions left, remove latest version metadata
delete(versionsEntry.Extended, s3_constants.ExtLatestVersionIdKey)
delete(versionsEntry.Extended, s3_constants.ExtLatestVersionFileNameKey)
glog.V(2).Infof("updateLatestVersionAfterDeletion: no versions left for %s/%s", bucket, object)
}
@@ -1125,121 +1056,6 @@ func (s3a *S3ApiServer) getLatestObjectVersion(bucket, object string) (*filer_pb
return latestVersionEntry, nil
}
// getLatestVersionEntryFromDirectoryEntry creates a logical entry for list operations using cached metadata
// from the .versions directory entry. This achieves SINGLE-SCAN efficiency - no additional getEntry calls needed.
//
// For N versioned objects:
// - Before: N×1 to N×12 find operations per list
// - After: 0 extra find operations (all metadata cached in .versions directory)
//
// Returns ErrDeleteMarker if the latest version is a delete marker (expected condition, not an error).
func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object string, versionsDirEntry *filer_pb.Entry) (*filer_pb.Entry, error) {
// Defensive nil check
if versionsDirEntry == nil {
return nil, fmt.Errorf("nil .versions directory entry")
}
normalizedObject := removeDuplicateSlashes(object)
// Check if the directory entry has latest version metadata
if versionsDirEntry.Extended == nil {
return nil, fmt.Errorf("no Extended metadata in .versions directory entry")
}
latestVersionIdBytes, hasLatestVersionId := versionsDirEntry.Extended[s3_constants.ExtLatestVersionIdKey]
if !hasLatestVersionId {
return nil, fmt.Errorf("missing latest version ID metadata in .versions directory entry")
}
// Check if this is a delete marker (should not be shown in regular list)
if isDeleteMarker, exists := versionsDirEntry.Extended[s3_constants.ExtLatestVersionIsDeleteMarker]; exists && string(isDeleteMarker) == "true" {
return nil, ErrDeleteMarker
}
latestVersionId := string(latestVersionIdBytes)
// Try to use cached metadata for zero-copy list (single-scan efficiency)
sizeBytes, hasSize := versionsDirEntry.Extended[s3_constants.ExtLatestVersionSizeKey]
mtimeBytes, hasMtime := versionsDirEntry.Extended[s3_constants.ExtLatestVersionMtimeKey]
etagBytes, hasEtag := versionsDirEntry.Extended[s3_constants.ExtLatestVersionETagKey]
if hasSize && hasMtime && hasEtag {
size, sizeErr := strconv.ParseUint(string(sizeBytes), 10, 64)
mtime, mtimeErr := strconv.ParseInt(string(mtimeBytes), 10, 64)
if sizeErr == nil && mtimeErr == nil {
// Use cached metadata - no getEntry call needed!
glog.V(3).Infof("getLatestVersionEntryFromDirectoryEntry: using cached metadata for %s/%s (size=%d, mtime=%d)", bucket, normalizedObject, size, mtime)
logicalEntry := &filer_pb.Entry{
Name: path.Base(normalizedObject),
IsDirectory: false,
Attributes: &filer_pb.FuseAttributes{
FileSize: size,
Mtime: mtime,
},
Extended: map[string][]byte{
s3_constants.ExtVersionIdKey: []byte(latestVersionId),
s3_constants.ExtETagKey: etagBytes,
},
}
// Attempt to parse the ETag and set it as Md5 attribute for compatibility with filer.ETag().
// This is a partial fix for single-part uploads. Multipart ETags will still use ExtETagKey.
if len(etagBytes) >= 2 && etagBytes[0] == '"' && etagBytes[len(etagBytes)-1] == '"' {
unquotedEtag := etagBytes[1 : len(etagBytes)-1]
if !bytes.Contains(unquotedEtag, []byte("-")) {
if md5bytes, err := hex.DecodeString(string(unquotedEtag)); err == nil {
logicalEntry.Attributes.Md5 = md5bytes
}
}
}
// Add owner if cached
if ownerBytes, hasOwner := versionsDirEntry.Extended[s3_constants.ExtLatestVersionOwnerKey]; hasOwner {
logicalEntry.Extended[s3_constants.ExtAmzOwnerKey] = ownerBytes
}
return logicalEntry, nil
}
glog.Warningf("getLatestVersionEntryFromDirectoryEntry: failed to parse cached metadata for %s/%s, falling back. sizeErr:%v, mtimeErr:%v", bucket, normalizedObject, sizeErr, mtimeErr)
}
// Fallback: fetch version file if cached metadata not available (for older versions)
latestVersionFileBytes, hasLatestVersionFile := versionsDirEntry.Extended[s3_constants.ExtLatestVersionFileNameKey]
if !hasLatestVersionFile {
return nil, fmt.Errorf("missing latest version file name metadata in .versions directory entry")
}
latestVersionFile := string(latestVersionFileBytes)
glog.V(3).Infof("getLatestVersionEntryFromDirectoryEntry: fetching version file for %s/%s (no cached metadata)", bucket, normalizedObject)
bucketDir := path.Join(s3a.option.BucketsPath, bucket)
versionsObjectPath := path.Join(normalizedObject, s3_constants.VersionsFolder)
latestVersionPath := path.Join(versionsObjectPath, latestVersionFile)
latestVersionEntry, err := s3a.getEntry(bucketDir, latestVersionPath)
if err != nil {
return nil, fmt.Errorf("failed to get latest version file %s: %v", latestVersionPath, err)
}
// Check if this is a delete marker (should not be shown in regular list)
if latestVersionEntry.Extended != nil {
if deleteMarker, exists := latestVersionEntry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
return nil, ErrDeleteMarker
}
}
// Create a logical entry that appears at the object path (not the versioned path)
logicalEntry := &filer_pb.Entry{
Name: path.Base(normalizedObject),
IsDirectory: false,
Attributes: latestVersionEntry.Attributes,
Extended: latestVersionEntry.Extended,
Chunks: latestVersionEntry.Chunks,
}
return logicalEntry, nil
}
// getObjectOwnerFromVersion extracts object owner information from version metadata
func (s3a *S3ApiServer) getObjectOwnerFromVersion(version *ObjectVersion, bucket, objectKey string) CanonicalUser {
// First try to get owner from the version's OwnerID field (extracted during listing)
-273
View File
@@ -1,273 +0,0 @@
package s3api
import (
"strings"
"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/stretchr/testify/assert"
)
// TestIsInRemoteOnly tests the IsInRemoteOnly method on filer_pb.Entry
func TestIsInRemoteOnly(t *testing.T) {
tests := []struct {
name string
entry *filer_pb.Entry
expected bool
}{
{
name: "remote-only entry with no chunks",
entry: &filer_pb.Entry{
Name: "remote-file.txt",
Chunks: nil,
RemoteEntry: &filer_pb.RemoteEntry{
RemoteSize: 1024,
},
},
expected: true,
},
{
name: "remote entry with chunks (cached)",
entry: &filer_pb.Entry{
Name: "cached-file.txt",
Chunks: []*filer_pb.FileChunk{
{FileId: "1,abc123", Size: 1024, Offset: 0},
},
RemoteEntry: &filer_pb.RemoteEntry{
RemoteSize: 1024,
},
},
expected: false,
},
{
name: "local file with chunks (not remote)",
entry: &filer_pb.Entry{
Name: "local-file.txt",
Chunks: []*filer_pb.FileChunk{
{FileId: "1,abc123", Size: 1024, Offset: 0},
},
RemoteEntry: nil,
},
expected: false,
},
{
name: "empty remote entry (size 0)",
entry: &filer_pb.Entry{
Name: "empty-remote.txt",
Chunks: nil,
RemoteEntry: &filer_pb.RemoteEntry{
RemoteSize: 0,
},
},
expected: false,
},
{
name: "no chunks but nil RemoteEntry",
entry: &filer_pb.Entry{
Name: "empty-local.txt",
Chunks: nil,
RemoteEntry: nil,
},
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.entry.IsInRemoteOnly()
assert.Equal(t, tt.expected, result,
"IsInRemoteOnly() for %s should return %v", tt.name, tt.expected)
})
}
}
// TestRemoteOnlyEntryDetection tests that the streamFromVolumeServers logic
// correctly distinguishes between remote-only entries and data integrity errors
func TestRemoteOnlyEntryDetection(t *testing.T) {
tests := []struct {
name string
entry *filer_pb.Entry
shouldBeRemote bool
shouldBeDataError bool
shouldBeEmpty bool
}{
{
name: "remote-only entry (no chunks, has remote entry)",
entry: &filer_pb.Entry{
Name: "remote-file.txt",
Chunks: nil,
Attributes: &filer_pb.FuseAttributes{
FileSize: 1024,
},
RemoteEntry: &filer_pb.RemoteEntry{
RemoteSize: 1024,
},
},
shouldBeRemote: true,
shouldBeDataError: false,
shouldBeEmpty: false,
},
{
name: "data integrity error (no chunks, no remote, has size)",
entry: &filer_pb.Entry{
Name: "corrupt-file.txt",
Chunks: nil,
Attributes: &filer_pb.FuseAttributes{
FileSize: 1024,
},
RemoteEntry: nil,
},
shouldBeRemote: false,
shouldBeDataError: true,
shouldBeEmpty: false,
},
{
name: "empty local file (no chunks, no remote, size 0)",
entry: &filer_pb.Entry{
Name: "empty-file.txt",
Chunks: nil,
Attributes: &filer_pb.FuseAttributes{
FileSize: 0,
},
RemoteEntry: nil,
},
shouldBeRemote: false,
shouldBeDataError: false,
shouldBeEmpty: true,
},
{
name: "normal file with chunks",
entry: &filer_pb.Entry{
Name: "normal-file.txt",
Chunks: []*filer_pb.FileChunk{
{FileId: "1,abc123", Size: 1024, Offset: 0},
},
Attributes: &filer_pb.FuseAttributes{
FileSize: 1024,
},
RemoteEntry: nil,
},
shouldBeRemote: false,
shouldBeDataError: false,
shouldBeEmpty: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
chunks := tt.entry.GetChunks()
totalSize := int64(filer.FileSize(tt.entry))
if len(chunks) == 0 {
// This mirrors the logic in streamFromVolumeServers
if tt.entry.IsInRemoteOnly() {
assert.True(t, tt.shouldBeRemote,
"Entry should be detected as remote-only")
} else if totalSize > 0 && len(tt.entry.Content) == 0 {
assert.True(t, tt.shouldBeDataError,
"Entry should be detected as data integrity error")
} else {
assert.True(t, tt.shouldBeEmpty,
"Entry should be detected as empty")
}
} else {
assert.False(t, tt.shouldBeRemote, "Entry with chunks should not be remote-only")
assert.False(t, tt.shouldBeDataError, "Entry with chunks should not be data error")
assert.False(t, tt.shouldBeEmpty, "Entry with chunks should not be empty")
}
})
}
}
// TestVersionedRemoteObjectPathBuilding tests that the path building logic
// correctly handles versioned objects stored in .versions/ directory
func TestVersionedRemoteObjectPathBuilding(t *testing.T) {
bucketsPath := "/buckets"
tests := []struct {
name string
bucket string
object string
versionId string
expectedDir string
expectedName string
}{
{
name: "non-versioned object (empty versionId)",
bucket: "mybucket",
object: "myobject.txt",
versionId: "",
expectedDir: "/buckets/mybucket",
expectedName: "myobject.txt",
},
{
name: "null version",
bucket: "mybucket",
object: "myobject.txt",
versionId: "null",
expectedDir: "/buckets/mybucket",
expectedName: "myobject.txt",
},
{
name: "specific version",
bucket: "mybucket",
object: "myobject.txt",
versionId: "abc123",
expectedDir: "/buckets/mybucket/myobject.txt" + s3_constants.VersionsFolder,
expectedName: "v_abc123",
},
{
name: "nested object with version",
bucket: "mybucket",
object: "folder/subfolder/file.txt",
versionId: "xyz789",
expectedDir: "/buckets/mybucket/folder/subfolder/file.txt" + s3_constants.VersionsFolder,
expectedName: "v_xyz789",
},
{
name: "object with leading slash and version",
bucket: "mybucket",
object: "/path/to/file.txt",
versionId: "ver456",
expectedDir: "/buckets/mybucket/path/to/file.txt" + s3_constants.VersionsFolder,
expectedName: "v_ver456",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var dir, name string
// This mirrors the logic in cacheRemoteObjectForStreaming
if tt.versionId != "" && tt.versionId != "null" {
// Versioned object path
normalizedObject := strings.TrimPrefix(removeDuplicateSlashesTest(tt.object), "/")
dir = bucketsPath + "/" + tt.bucket + "/" + normalizedObject + s3_constants.VersionsFolder
name = "v_" + tt.versionId
} else {
// Non-versioned path (simplified - just for testing)
dir = bucketsPath + "/" + tt.bucket
normalizedObject := strings.TrimPrefix(removeDuplicateSlashesTest(tt.object), "/")
if idx := strings.LastIndex(normalizedObject, "/"); idx > 0 {
dir = dir + "/" + normalizedObject[:idx]
name = normalizedObject[idx+1:]
} else {
name = normalizedObject
}
}
assert.Equal(t, tt.expectedDir, dir, "Directory path should match")
assert.Equal(t, tt.expectedName, name, "Name should match")
})
}
}
// removeDuplicateSlashesTest is a test helper that mirrors production code
func removeDuplicateSlashesTest(s string) string {
for strings.Contains(s, "//") {
s = strings.ReplaceAll(s, "//", "/")
}
return s
}
-187
View File
@@ -1,187 +0,0 @@
package s3api
import (
"crypto/rand"
"encoding/hex"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
s3_constants "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
// Version ID format constants
// New format uses inverted timestamps so newer versions sort first lexicographically
// Old format used raw timestamps where older versions sorted first
const (
// Threshold to distinguish old vs new format version IDs
// Around year 2024-2025:
// - Old format (raw ns): ~1.7×10¹⁸ ≈ 0x17... (BELOW threshold)
// - New format (MaxInt64 - ns): ~7.5×10¹⁸ ≈ 0x68... (ABOVE threshold)
// We use 0x4000000000000000 (~4.6×10¹⁸) as threshold
versionIdFormatThreshold = 0x4000000000000000
)
// generateVersionId creates a unique version ID
// If useInvertedFormat is true, uses inverted timestamps so newer versions sort first
// If false, uses raw timestamps (old format) for backward compatibility
func generateVersionId(useInvertedFormat bool) string {
now := time.Now().UnixNano()
var timestampHex string
if useInvertedFormat {
// INVERTED timestamp: newer versions have SMALLER values
// This makes lexicographic sorting return newest versions first
invertedTimestamp := math.MaxInt64 - now
timestampHex = fmt.Sprintf("%016x", invertedTimestamp)
} else {
// Raw timestamp: older versions have SMALLER values (old format)
timestampHex = fmt.Sprintf("%016x", now)
}
// Generate random 8 bytes for uniqueness (last 16 chars of version ID)
randBytes := make([]byte, 8)
if _, err := rand.Read(randBytes); err != nil {
glog.Errorf("Failed to generate random bytes for version ID: %v", err)
// Fallback to timestamp-only if random generation fails
return timestampHex + "0000000000000000"
}
// Combine timestamp (16 chars) + random (16 chars) = 32 chars total
randomHex := hex.EncodeToString(randBytes)
return timestampHex + randomHex
}
// isNewFormatVersionId returns true if the version ID uses the new inverted timestamp format
func isNewFormatVersionId(versionId string) bool {
if len(versionId) < 16 || versionId == "null" {
return false
}
// Parse the first 16 hex chars as the timestamp portion
timestampPart, err := strconv.ParseUint(versionId[:16], 16, 64)
if err != nil {
return false
}
// New format has inverted timestamps (MaxInt64 - ns), which are ABOVE the threshold (~0x68...)
// Old format has raw timestamps, which are BELOW the threshold (~0x17...)
return timestampPart > versionIdFormatThreshold
}
// getVersionTimestamp extracts the actual timestamp from a version ID,
// handling both old (raw) and new (inverted) formats
func getVersionTimestamp(versionId string) int64 {
if len(versionId) < 16 || versionId == "null" {
return 0
}
timestampPart, err := strconv.ParseUint(versionId[:16], 16, 64)
if err != nil {
return 0
}
if timestampPart > versionIdFormatThreshold {
// New format: inverted timestamp (above threshold), convert back
return int64(math.MaxInt64 - timestampPart)
}
// Validate old format timestamp is within int64 range
if timestampPart > math.MaxInt64 {
return 0
}
// Old format: raw timestamp (below threshold)
return int64(timestampPart)
}
// compareVersionIds compares two version IDs for sorting (newest first)
// Returns: negative if a is newer, positive if b is newer, 0 if equal
// Handles both old and new format version IDs
func compareVersionIds(a, b string) int {
if a == b {
return 0
}
if a == "null" {
return 1 // null versions sort last
}
if b == "null" {
return -1
}
aIsNew := isNewFormatVersionId(a)
bIsNew := isNewFormatVersionId(b)
if aIsNew == bIsNew {
// Same format - compare lexicographically
// For new format: smaller value = newer (correct)
// For old format: smaller value = older (need to invert)
if aIsNew {
// New format: lexicographic order is correct (smaller = newer)
if a < b {
return -1
}
return 1
} else {
// Old format: lexicographic order is inverted (smaller = older)
if a < b {
return 1
}
return -1
}
}
// Mixed formats - compare by actual timestamp
aTime := getVersionTimestamp(a)
bTime := getVersionTimestamp(b)
if aTime > bTime {
return -1 // a is newer
}
if aTime < bTime {
return 1 // b is newer
}
return 0
}
// getVersionedObjectDir returns the directory path for storing object versions
func (s3a *S3ApiServer) getVersionedObjectDir(bucket, object string) string {
return s3a.option.BucketsPath + "/" + bucket + "/" + object + s3_constants.VersionsFolder
}
// getVersionFileName returns the filename for a specific version
func (s3a *S3ApiServer) getVersionFileName(versionId string) string {
return fmt.Sprintf("v_%s", versionId)
}
// getVersionIdFormat checks the .versions directory to determine which version ID format to use.
// Returns true if inverted format (new format) should be used.
// For new .versions directories, returns true (use new format).
// For existing directories, infers format from the latest version ID.
func (s3a *S3ApiServer) getVersionIdFormat(bucket, object string) bool {
cleanObject := strings.TrimPrefix(object, "/")
bucketDir := s3a.option.BucketsPath + "/" + bucket
versionsPath := cleanObject + s3_constants.VersionsFolder
// Try to get the .versions directory entry
versionsEntry, err := s3a.getEntry(bucketDir, versionsPath)
if err != nil {
// .versions directory doesn't exist yet - use new format
return true
}
// Infer format from the latest version ID stored in metadata
if versionsEntry.Extended != nil {
if latestVersionId, exists := versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey]; exists {
return isNewFormatVersionId(string(latestVersionId))
}
}
// No latest version metadata - this is likely a new or empty directory
// Use new format
return true
}
// generateVersionIdForObject generates a version ID using the appropriate format for the object.
// For new objects, uses inverted format. For existing versioned objects, uses their existing format.
func (s3a *S3ApiServer) generateVersionIdForObject(bucket, object string) string {
useInvertedFormat := s3a.getVersionIdFormat(bucket, object)
return generateVersionId(useInvertedFormat)
}
-375
View File
@@ -1,375 +0,0 @@
package s3api
import (
"math"
"testing"
"time"
)
// TestVersionIdFormatDetection tests that old and new format version IDs are correctly identified
func TestVersionIdFormatDetection(t *testing.T) {
tests := []struct {
name string
versionId string
expectNew bool
}{
// New format (inverted timestamps) - values > 0x4000000000000000
{
name: "new format - inverted timestamp",
versionId: "68a1b2c3d4e5f6780000000000000000", // > 0x4000...
expectNew: true,
},
{
name: "new format - high value",
versionId: "7fffffffffffffff0000000000000000", // near max
expectNew: true,
},
// Old format (raw timestamps) - values < 0x4000000000000000
{
name: "old format - raw timestamp",
versionId: "179a1b2c3d4e5f670000000000000000", // ~2024-2025
expectNew: false,
},
{
name: "old format - low value",
versionId: "10000000000000000000000000000000",
expectNew: false,
},
// Edge cases
{
name: "null version",
versionId: "null",
expectNew: false,
},
{
name: "short version ID",
versionId: "abc123",
expectNew: false,
},
{
name: "empty version ID",
versionId: "",
expectNew: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isNewFormatVersionId(tt.versionId)
if got != tt.expectNew {
t.Errorf("isNewFormatVersionId(%s) = %v, want %v", tt.versionId, got, tt.expectNew)
}
})
}
}
// TestGenerateVersionIdFormats tests that generateVersionId produces correct format based on parameter
func TestGenerateVersionIdFormats(t *testing.T) {
// Generate old format version ID
oldFormatId := generateVersionId(false)
if len(oldFormatId) != 32 {
t.Errorf("old format version ID length = %d, want 32", len(oldFormatId))
}
if isNewFormatVersionId(oldFormatId) {
t.Errorf("generateVersionId(false) produced new format ID: %s", oldFormatId)
}
// Generate new format version ID
newFormatId := generateVersionId(true)
if len(newFormatId) != 32 {
t.Errorf("new format version ID length = %d, want 32", len(newFormatId))
}
if !isNewFormatVersionId(newFormatId) {
t.Errorf("generateVersionId(true) produced old format ID: %s", newFormatId)
}
}
// TestGetVersionTimestamp tests timestamp extraction from both formats
func TestGetVersionTimestamp(t *testing.T) {
now := time.Now().UnixNano()
// Generate old and new format IDs
oldId := generateVersionId(false)
newId := generateVersionId(true)
oldTs := getVersionTimestamp(oldId)
newTs := getVersionTimestamp(newId)
// Both should be close to current time (within 1 second)
tolerance := int64(time.Second)
if abs(oldTs-now) > tolerance {
t.Errorf("old format timestamp diff too large: got %d, want ~%d", oldTs, now)
}
if abs(newTs-now) > tolerance {
t.Errorf("new format timestamp diff too large: got %d, want ~%d", newTs, now)
}
// null should return 0
if ts := getVersionTimestamp("null"); ts != 0 {
t.Errorf("getVersionTimestamp(null) = %d, want 0", ts)
}
}
func abs(x int64) int64 {
if x < 0 {
return -x
}
return x
}
// TestCompareVersionIdsSameFormatOld tests sorting of old format version IDs (newest first)
func TestCompareVersionIdsSameFormatOld(t *testing.T) {
// Old format: larger hex value = newer (raw timestamp)
older := "1700000000000000" + "0000000000000000" // older timestamp
newer := "1800000000000000" + "0000000000000000" // newer timestamp
// Verify both are old format
if isNewFormatVersionId(older) || isNewFormatVersionId(newer) {
t.Fatal("test setup error: expected old format IDs")
}
// compareVersionIds should return negative if first arg is newer
result := compareVersionIds(newer, older)
if result >= 0 {
t.Errorf("compareVersionIds(newer, older) = %d, want negative", result)
}
result = compareVersionIds(older, newer)
if result <= 0 {
t.Errorf("compareVersionIds(older, newer) = %d, want positive", result)
}
result = compareVersionIds(older, older)
if result != 0 {
t.Errorf("compareVersionIds(same, same) = %d, want 0", result)
}
}
// TestCompareVersionIdsSameFormatNew tests sorting of new format version IDs (newest first)
func TestCompareVersionIdsSameFormatNew(t *testing.T) {
// New format: smaller hex value = newer (inverted timestamp)
// MaxInt64 - newer_ts < MaxInt64 - older_ts
newer := "6800000000000000" + "0000000000000000" // smaller = newer
older := "6900000000000000" + "0000000000000000" // larger = older
// Verify both are new format
if !isNewFormatVersionId(older) || !isNewFormatVersionId(newer) {
t.Fatal("test setup error: expected new format IDs")
}
// compareVersionIds should return negative if first arg is newer
result := compareVersionIds(newer, older)
if result >= 0 {
t.Errorf("compareVersionIds(newer, older) = %d, want negative", result)
}
result = compareVersionIds(older, newer)
if result <= 0 {
t.Errorf("compareVersionIds(older, newer) = %d, want positive", result)
}
}
// TestCompareVersionIdsMixedFormats tests sorting when comparing old and new format IDs
func TestCompareVersionIdsMixedFormats(t *testing.T) {
// Create IDs where we know the actual timestamps
// Old format: raw timestamp
oldFormatTs := int64(1700000000000000000) // some timestamp
oldFormatId := createOldFormatVersionId(oldFormatTs)
// New format: inverted timestamp (created 1 second later)
newFormatTs := oldFormatTs + int64(time.Second)
newFormatId := createNewFormatVersionId(newFormatTs)
// Verify formats
if isNewFormatVersionId(oldFormatId) {
t.Fatalf("expected old format for %s", oldFormatId)
}
if !isNewFormatVersionId(newFormatId) {
t.Fatalf("expected new format for %s", newFormatId)
}
// New format ID is newer (created 1 second later)
result := compareVersionIds(newFormatId, oldFormatId)
if result >= 0 {
t.Errorf("compareVersionIds(newer_new_format, older_old_format) = %d, want negative", result)
}
result = compareVersionIds(oldFormatId, newFormatId)
if result <= 0 {
t.Errorf("compareVersionIds(older_old_format, newer_new_format) = %d, want positive", result)
}
}
// TestCompareVersionIdsNullHandling tests that null versions sort last
func TestCompareVersionIdsNullHandling(t *testing.T) {
regular := generateVersionId(true)
// null should sort after regular versions
if result := compareVersionIds("null", regular); result <= 0 {
t.Errorf("compareVersionIds(null, regular) = %d, want positive (null sorts last)", result)
}
if result := compareVersionIds(regular, "null"); result >= 0 {
t.Errorf("compareVersionIds(regular, null) = %d, want negative (null sorts last)", result)
}
}
// Helper to create old format version ID from timestamp
func createOldFormatVersionId(ts int64) string {
return sprintf16x(uint64(ts)) + "0000000000000000"
}
// Helper to create new format version ID from timestamp
func createNewFormatVersionId(ts int64) string {
inverted := uint64(math.MaxInt64 - ts)
return sprintf16x(inverted) + "0000000000000000"
}
func sprintf16x(v uint64) string {
return sprintf("%016x", v)
}
func sprintf(format string, v uint64) string {
result := make([]byte, 16)
for i := 15; i >= 0; i-- {
digit := v & 0xf
if digit < 10 {
result[i] = byte('0' + digit)
} else {
result[i] = byte('a' + digit - 10)
}
v >>= 4
}
return string(result)
}
// TestOldFormatBackwardCompatibility ensures old format versions work correctly in sorting
func TestOldFormatBackwardCompatibility(t *testing.T) {
// Simulate a bucket that was created before the inverted format was introduced
// All versions should be old format and should sort correctly (newest first)
// Create 5 old format version IDs with known timestamps
baseTs := int64(1700000000000000000)
versions := make([]string, 5)
for i := 0; i < 5; i++ {
ts := baseTs + int64(i)*int64(time.Minute) // each 1 minute apart
versions[i] = createOldFormatVersionId(ts)
}
// Verify all are old format
for i, v := range versions {
if isNewFormatVersionId(v) {
t.Fatalf("version %d should be old format: %s", i, v)
}
}
// Verify sorting: versions[4] is newest, versions[0] is oldest
// compareVersionIds(newer, older) should return negative
for i := 0; i < 4; i++ {
newer := versions[i+1]
older := versions[i]
result := compareVersionIds(newer, older)
if result >= 0 {
t.Errorf("compareVersionIds(versions[%d], versions[%d]) = %d, want negative (newer first)", i+1, i, result)
}
}
// Verify extracted timestamps are correct
for i, v := range versions {
expectedTs := baseTs + int64(i)*int64(time.Minute)
gotTs := getVersionTimestamp(v)
if gotTs != expectedTs {
t.Errorf("getVersionTimestamp(versions[%d]) = %d, want %d", i, gotTs, expectedTs)
}
}
}
// TestNewFormatSorting ensures new format versions sort correctly (newest first)
func TestNewFormatSorting(t *testing.T) {
// Create 5 new format version IDs with known timestamps
baseTs := int64(1700000000000000000)
versions := make([]string, 5)
for i := 0; i < 5; i++ {
ts := baseTs + int64(i)*int64(time.Minute) // each 1 minute apart
versions[i] = createNewFormatVersionId(ts)
}
// Verify all are new format
for i, v := range versions {
if !isNewFormatVersionId(v) {
t.Fatalf("version %d should be new format: %s", i, v)
}
}
// Verify sorting: versions[4] is newest, versions[0] is oldest
for i := 0; i < 4; i++ {
newer := versions[i+1]
older := versions[i]
result := compareVersionIds(newer, older)
if result >= 0 {
t.Errorf("compareVersionIds(versions[%d], versions[%d]) = %d, want negative (newer first)", i+1, i, result)
}
}
// Verify extracted timestamps are correct
for i, v := range versions {
expectedTs := baseTs + int64(i)*int64(time.Minute)
gotTs := getVersionTimestamp(v)
if gotTs != expectedTs {
t.Errorf("getVersionTimestamp(versions[%d]) = %d, want %d", i, gotTs, expectedTs)
}
}
}
// TestMixedFormatTransition simulates a bucket transitioning from old to new format
func TestMixedFormatTransition(t *testing.T) {
baseTs := int64(1700000000000000000)
// First 3 versions created with old format (before upgrade)
oldVersions := make([]string, 3)
for i := 0; i < 3; i++ {
ts := baseTs + int64(i)*int64(time.Minute)
oldVersions[i] = createOldFormatVersionId(ts)
}
// Next 3 versions created with new format (after upgrade)
newVersions := make([]string, 3)
for i := 0; i < 3; i++ {
ts := baseTs + int64(3+i)*int64(time.Minute) // continue from where old left off
newVersions[i] = createNewFormatVersionId(ts)
}
// All versions in chronological order (oldest to newest)
allVersions := append(oldVersions, newVersions...)
// Verify mixed formats
for i := 0; i < 3; i++ {
if isNewFormatVersionId(allVersions[i]) {
t.Errorf("allVersions[%d] should be old format", i)
}
}
for i := 3; i < 6; i++ {
if !isNewFormatVersionId(allVersions[i]) {
t.Errorf("allVersions[%d] should be new format", i)
}
}
// Verify sorting works correctly across the format boundary
for i := 0; i < 5; i++ {
newer := allVersions[i+1]
older := allVersions[i]
result := compareVersionIds(newer, older)
if result >= 0 {
t.Errorf("compareVersionIds(allVersions[%d], allVersions[%d]) = %d, want negative (newer first)", i+1, i, result)
}
}
// Verify the newest (new format) version sorts before oldest (old format) when comparing directly
newest := allVersions[5] // newest, new format
oldest := allVersions[0] // oldest, old format
if result := compareVersionIds(newest, oldest); result >= 0 {
t.Errorf("compareVersionIds(newest_new_format, oldest_old_format) = %d, want negative", result)
}
}
+17 -51
View File
@@ -3,7 +3,6 @@ package weed_server
import (
"context"
"fmt"
"sort"
"strings"
"sync"
"time"
@@ -36,15 +35,8 @@ func (fs *FilerServer) CacheRemoteObjectToLocalCluster(ctx context.Context, req
if err != nil {
return nil, err
}
if result == nil {
return nil, fmt.Errorf("unexpected nil result from singleflight")
}
resp, ok := result.(*filer_pb.CacheRemoteObjectToLocalClusterResponse)
if !ok {
return nil, fmt.Errorf("unexpected result type from singleflight")
}
return resp, nil
return result.(*filer_pb.CacheRemoteObjectToLocalClusterResponse), nil
}
// doCacheRemoteObjectToLocalCluster performs the actual caching operation.
@@ -125,7 +117,6 @@ func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, re
dest := util.FullPath(remoteStorageMountedLocation.Path).Child(string(util.FullPath(req.Directory).Child(req.Name))[len(localMountedDir):])
var chunks []*filer_pb.FileChunk
var chunksMu sync.Mutex
var fetchAndWriteErr error
var wg sync.WaitGroup
@@ -144,28 +135,16 @@ func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, re
// assign one volume server
assignResult, err := operation.Assign(ctx, fs.filer.GetMaster, fs.grpcDialOption, assignRequest, altRequest)
if err != nil {
chunksMu.Lock()
if fetchAndWriteErr == nil {
fetchAndWriteErr = err
}
chunksMu.Unlock()
fetchAndWriteErr = err
return
}
if assignResult.Error != "" {
chunksMu.Lock()
if fetchAndWriteErr == nil {
fetchAndWriteErr = fmt.Errorf("assign: %v", assignResult.Error)
}
chunksMu.Unlock()
fetchAndWriteErr = fmt.Errorf("assign: %v", assignResult.Error)
return
}
fileId, parseErr := needle.ParseFileIdFromString(assignResult.Fid)
if parseErr != nil {
chunksMu.Lock()
if fetchAndWriteErr == nil {
fetchAndWriteErr = fmt.Errorf("unrecognized file id %s: %v", assignResult.Fid, parseErr)
}
chunksMu.Unlock()
if assignResult.Error != "" {
fetchAndWriteErr = fmt.Errorf("unrecognized file id %s: %v", assignResult.Fid, parseErr)
return
}
@@ -182,7 +161,7 @@ func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, re
assignedServerAddress := pb.NewServerAddressWithGrpcPort(assignResult.Url, assignResult.GrpcPort)
var etag string
err = operation.WithVolumeServerClient(false, assignedServerAddress, fs.grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
resp, fetchErr := volumeServerClient.FetchAndWriteNeedle(context.Background(), &volume_server_pb.FetchAndWriteNeedleRequest{
resp, fetchAndWriteErr := volumeServerClient.FetchAndWriteNeedle(context.Background(), &volume_server_pb.FetchAndWriteNeedleRequest{
VolumeId: uint32(fileId.VolumeId),
NeedleId: uint64(fileId.Key),
Cookie: uint32(fileId.Cookie),
@@ -197,23 +176,21 @@ func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, re
Path: string(dest),
},
})
if fetchErr != nil {
return fmt.Errorf("volume server %s fetchAndWrite %s: %v", assignResult.Url, dest, fetchErr)
if fetchAndWriteErr != nil {
return fmt.Errorf("volume server %s fetchAndWrite %s: %v", assignResult.Url, dest, fetchAndWriteErr)
} else {
etag = resp.ETag
}
etag = resp.ETag
return nil
})
if err != nil {
chunksMu.Lock()
if fetchAndWriteErr == nil {
fetchAndWriteErr = err
}
chunksMu.Unlock()
if err != nil && fetchAndWriteErr == nil {
fetchAndWriteErr = err
return
}
chunk := &filer_pb.FileChunk{
chunks = append(chunks, &filer_pb.FileChunk{
FileId: assignResult.Fid,
Offset: localOffset,
Size: uint64(size),
@@ -224,24 +201,13 @@ func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, re
FileKey: uint64(fileId.Key),
Cookie: uint32(fileId.Cookie),
},
}
chunksMu.Lock()
chunks = append(chunks, chunk)
chunksMu.Unlock()
})
})
}
wg.Wait()
chunksMu.Lock()
err = fetchAndWriteErr
// Sort chunks by offset to maintain file order
sort.Slice(chunks, func(i, j int) bool {
return chunks[i].Offset < chunks[j].Offset
})
chunksMu.Unlock()
if err != nil {
return nil, err
if fetchAndWriteErr != nil {
return nil, fetchAndWriteErr
}
garbage := entry.GetChunks()
-47
View File
@@ -90,50 +90,3 @@ func (ms *MasterServer) RaftRemoveServer(ctx context.Context, req *master_pb.Raf
}
return resp, nil
}
func (ms *MasterServer) RaftLeadershipTransfer(ctx context.Context, req *master_pb.RaftLeadershipTransferRequest) (*master_pb.RaftLeadershipTransferResponse, error) {
resp := &master_pb.RaftLeadershipTransferResponse{}
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
// Leadership transfer is only supported with hashicorp raft (-raftHashicorp=true)
// The default seaweedfs/raft (goraft) implementation does not support this feature
if ms.Topo.HashicorpRaft == nil {
if ms.Topo.RaftServer != nil {
return nil, fmt.Errorf("leadership transfer requires -raftHashicorp=true; the default raft implementation does not support this feature")
}
return nil, fmt.Errorf("raft not initialized (single master mode)")
}
if ms.Topo.HashicorpRaft.State() != raft.Leader {
leaderAddr, _ := ms.Topo.HashicorpRaft.LeaderWithID()
return nil, fmt.Errorf("this server is not the leader; current leader is %s", leaderAddr)
}
// Record previous leader
_, previousLeaderId := ms.Topo.HashicorpRaft.LeaderWithID()
resp.PreviousLeader = string(previousLeaderId)
var future raft.Future
if req.TargetId != "" && req.TargetAddress != "" {
// Transfer to specific server
future = ms.Topo.HashicorpRaft.LeadershipTransferToServer(
raft.ServerID(req.TargetId),
raft.ServerAddress(req.TargetAddress),
)
} else {
// Transfer to any eligible follower
future = ms.Topo.HashicorpRaft.LeadershipTransfer()
}
if err := future.Error(); err != nil {
return nil, fmt.Errorf("leadership transfer failed: %v", err)
}
// Get new leader info
_, newLeaderId := ms.Topo.HashicorpRaft.LeaderWithID()
resp.NewLeader = string(newLeaderId)
return resp, nil
}
-109
View File
@@ -1,109 +0,0 @@
package weed_server
// These tests cover the Raft gRPC handlers in scenarios where Raft is not initialized
// (single master mode). Testing with an initialized Raft cluster requires integration
// tests with a multi-master setup, as hashicorp/raft uses concrete types that cannot
// be easily mocked.
//
// Integration tests for RaftLeadershipTransfer should cover:
// - Successful leadership transfer to any follower (auto-selection)
// - Successful leadership transfer to a specific target server
// - Error when caller is not the current leader
// - Error when target server is not a voting member
// - Error when target server is unreachable
//
// These scenarios are best tested with test/multi_master/ integration tests
// using a real 3-node master cluster with -raftHashicorp=true.
import (
"context"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/topology"
)
func TestRaftLeadershipTransfer_NoRaft(t *testing.T) {
// Test case: raft not initialized (single master mode)
ms := &MasterServer{
Topo: topology.NewTopology("test", nil, 0, 0, false),
}
ctx := context.Background()
req := &master_pb.RaftLeadershipTransferRequest{}
_, err := ms.RaftLeadershipTransfer(ctx, req)
if err == nil {
t.Error("expected error when raft is not initialized")
}
expectedMsg := "single master mode"
if err != nil && !strings.Contains(err.Error(), expectedMsg) {
t.Errorf("expected error message to contain %q, got %q", expectedMsg, err.Error())
}
}
func TestRaftListClusterServers_NoRaft(t *testing.T) {
// Test case: raft not initialized returns empty response
ms := &MasterServer{
Topo: topology.NewTopology("test", nil, 0, 0, false),
}
ctx := context.Background()
req := &master_pb.RaftListClusterServersRequest{}
resp, err := ms.RaftListClusterServers(ctx, req)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if resp == nil {
t.Error("expected non-nil response")
}
if len(resp.ClusterServers) != 0 {
t.Errorf("expected empty cluster servers, got %d", len(resp.ClusterServers))
}
}
func TestRaftAddServer_NoRaft(t *testing.T) {
// Test case: raft not initialized returns empty response
ms := &MasterServer{
Topo: topology.NewTopology("test", nil, 0, 0, false),
}
ctx := context.Background()
req := &master_pb.RaftAddServerRequest{
Id: "test-server",
Address: "localhost:19333",
Voter: true,
}
resp, err := ms.RaftAddServer(ctx, req)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if resp == nil {
t.Error("expected non-nil response")
}
}
func TestRaftRemoveServer_NoRaft(t *testing.T) {
// Test case: raft not initialized returns empty response
ms := &MasterServer{
Topo: topology.NewTopology("test", nil, 0, 0, false),
}
ctx := context.Background()
req := &master_pb.RaftRemoveServerRequest{
Id: "test-server",
Force: true,
}
resp, err := ms.RaftRemoveServer(ctx, req)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if resp == nil {
t.Error("expected non-nil response")
}
}
+1 -6
View File
@@ -363,12 +363,7 @@ func (vs *VolumeServer) maybeCheckJwtAuthorization(r *http.Request, vid, fid str
if sepIndex := strings.LastIndex(fid, "_"); sepIndex > 0 {
fid = fid[:sepIndex]
}
expectedFid := vid + "," + fid
if sc.Fid != expectedFid {
glog.V(1).Infof("jwt fid mismatch from %s: token has %q, request has %q", r.RemoteAddr, sc.Fid, expectedFid)
return false
}
return true
return sc.Fid == vid+","+fid
}
glog.V(1).Infof("unexpected jwt from %s: %v", r.RemoteAddr, tokenStr)
return false
@@ -1,144 +0,0 @@
package shell
import (
"context"
"flag"
"fmt"
"io"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
func init() {
Commands = append(Commands, &commandRaftLeaderTransfer{})
}
type commandRaftLeaderTransfer struct{}
func (c *commandRaftLeaderTransfer) Name() string {
return "cluster.raft.transferLeader"
}
func (c *commandRaftLeaderTransfer) Help() string {
return `transfer raft leadership to another master server
This command initiates a graceful leadership transfer from the current
leader to another server. Use this before performing maintenance on
the current leader to reduce errors in filers and other components.
Examples:
# Transfer to any eligible follower (auto-selection)
cluster.raft.transferLeader
# Transfer to a specific server
cluster.raft.transferLeader -id <server_id> -address <server_grpc_address>
Notes:
- Requires hashicorp raft (-raftHashicorp=true on master)
- This command must be sent to the current leader
- The target server must be a voting member of the raft cluster
- Use 'cluster.raft.ps' to list available servers and identify the leader
`
}
func (c *commandRaftLeaderTransfer) HasTag(CommandTag) bool {
return false
}
func (c *commandRaftLeaderTransfer) Do(args []string, commandEnv *CommandEnv, writer io.Writer) error {
leaderTransferCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
targetId := leaderTransferCommand.String("id", "", "target server id (must be used with -address)")
targetAddress := leaderTransferCommand.String("address", "", "target server grpc address (must be used with -id)")
if err := leaderTransferCommand.Parse(args); err != nil {
return err
}
// Validate: id and address must be specified together
if *targetId != "" && *targetAddress == "" {
return fmt.Errorf("-address is required when -id is specified")
}
if *targetAddress != "" && *targetId == "" {
return fmt.Errorf("-id is required when -address is specified")
}
// First, show current cluster status
fmt.Fprintf(writer, "Checking current raft cluster status...\n")
var currentLeader string
err := commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := client.RaftListClusterServers(ctx, &master_pb.RaftListClusterServersRequest{})
if err != nil {
return fmt.Errorf("failed to list cluster servers: %v", err)
}
if len(resp.ClusterServers) == 0 {
fmt.Fprintf(writer, "No raft cluster configured (single master mode)\n")
return fmt.Errorf("leadership transfer not available in single master mode")
}
fmt.Fprintf(writer, "Raft cluster has %d servers:\n", len(resp.ClusterServers))
for _, server := range resp.ClusterServers {
suffix := ""
if server.IsLeader {
suffix = " <- current leader"
currentLeader = server.Id
}
fmt.Fprintf(writer, " %s %s [%s]%s\n", server.Id, server.Address, server.Suffrage, suffix)
}
return nil
})
if err != nil {
return err
}
if currentLeader == "" {
return fmt.Errorf("no leader found in cluster")
}
// Perform the transfer
targetDesc := "any eligible follower"
if *targetId != "" {
targetDesc = fmt.Sprintf("server %s (%s)", *targetId, *targetAddress)
}
fmt.Fprintf(writer, "\nTransferring leadership from %s to %s...\n", currentLeader, targetDesc)
err = commandEnv.MasterClient.WithClient(true, func(client master_pb.SeaweedClient) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
resp, err := client.RaftLeadershipTransfer(ctx, &master_pb.RaftLeadershipTransferRequest{
TargetId: *targetId,
TargetAddress: *targetAddress,
})
if err != nil {
return fmt.Errorf("leadership transfer failed: %v", err)
}
if resp.PreviousLeader != resp.NewLeader {
fmt.Fprintf(writer, "Leadership successfully transferred.\n")
fmt.Fprintf(writer, " Previous leader: %s\n", resp.PreviousLeader)
fmt.Fprintf(writer, " New leader: %s\n", resp.NewLeader)
} else {
fmt.Fprintf(writer, "Leadership transfer initiated, but the same leader was re-elected.\n")
fmt.Fprintf(writer, " Current leader: %s\n", resp.NewLeader)
}
return nil
})
if err != nil {
fmt.Fprintf(writer, "\nLeadership transfer failed: %v\n", err)
fmt.Fprintf(writer, "\nTroubleshooting:\n")
fmt.Fprintf(writer, " - Ensure you are connected to the current leader\n")
fmt.Fprintf(writer, " - Ensure target server is a voting member (use 'cluster.raft.ps')\n")
fmt.Fprintf(writer, " - Ensure target server is healthy and reachable\n")
return err
}
return nil
}
@@ -1,89 +0,0 @@
package shell
import (
"bytes"
"strings"
"testing"
)
func TestRaftLeaderTransfer_Name(t *testing.T) {
cmd := &commandRaftLeaderTransfer{}
expected := "cluster.raft.transferLeader"
if cmd.Name() != expected {
t.Errorf("expected name %q, got %q", expected, cmd.Name())
}
}
func TestRaftLeaderTransfer_Help(t *testing.T) {
cmd := &commandRaftLeaderTransfer{}
help := cmd.Help()
// Verify help text contains key information
expectedPhrases := []string{
"transfer raft leadership",
"cluster.raft.transferLeader",
"-id",
"-address",
"cluster.raft.ps",
"-raftHashicorp",
}
for _, phrase := range expectedPhrases {
if !strings.Contains(help, phrase) {
t.Errorf("help text should contain %q", phrase)
}
}
}
func TestRaftLeaderTransfer_HasTag(t *testing.T) {
cmd := &commandRaftLeaderTransfer{}
// The command should not have any special tags
if cmd.HasTag(ResourceHeavy) {
t.Error("expected HasTag to return false for ResourceHeavy")
}
}
func TestRaftLeaderTransfer_ValidateTargetIdWithoutAddress(t *testing.T) {
cmd := &commandRaftLeaderTransfer{}
var buf bytes.Buffer
// Create a mock command environment - this will fail because no master client
// but we can verify argument parsing
err := cmd.Do([]string{"-id", "test-server"}, nil, &buf)
// Should fail because -address is required when -id is specified
if err == nil {
t.Error("expected error when -id is specified without -address")
}
if err != nil && !strings.Contains(err.Error(), "-address is required") {
t.Errorf("expected error about missing -address, got: %v", err)
}
}
func TestRaftLeaderTransfer_ValidateTargetAddressWithoutId(t *testing.T) {
cmd := &commandRaftLeaderTransfer{}
var buf bytes.Buffer
// Verify argument parsing - address without id should fail
err := cmd.Do([]string{"-address", "localhost:19333"}, nil, &buf)
// Should fail because -id is required when -address is specified
if err == nil {
t.Error("expected error when -address is specified without -id")
}
if err != nil && !strings.Contains(err.Error(), "-id is required") {
t.Errorf("expected error about missing -id, got: %v", err)
}
}
func TestRaftLeaderTransfer_UnknownFlag(t *testing.T) {
cmd := &commandRaftLeaderTransfer{}
var buf bytes.Buffer
// Unknown flag should return an error
err := cmd.Do([]string{"-unknown-flag"}, nil, &buf)
if err == nil {
t.Error("expected error for unknown flag")
}
}
+13 -173
View File
@@ -1,19 +1,13 @@
package shell
import (
"context"
"flag"
"fmt"
"math"
"strings"
"sync"
"github.com/dustin/go-humanize"
"github.com/dustin/go-humanize/english"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
@@ -24,29 +18,15 @@ func init() {
Commands = append(Commands, &commandClusterStatus{})
}
// Map of volume_id -> [volume replicas] with stat details.
type VolumeReplicaStats struct {
Id string
VolumeId uint32
Files uint64
FilesDeleted uint64
TotalSize uint64
}
type RegularVolumeStats map[uint32][]*VolumeReplicaStats
type commandClusterStatus struct{}
type ClusterStatusPrinter struct {
writer io.Writer
writerMu sync.Mutex
humanize bool
maxParallelization int
writer io.Writer
humanize bool
locked bool
collections []string
topology *master_pb.TopologyInfo
volumeSizeLimitMb uint64
regularVolumeStats RegularVolumeStats
locked bool
collections []string
topology *master_pb.TopologyInfo
volumeSizeLimitMb uint64
}
func (c *commandClusterStatus) Name() string {
@@ -64,8 +44,6 @@ func (c *commandClusterStatus) HasTag(CommandTag) bool {
func (c *commandClusterStatus) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
flags := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
humanize := flags.Bool("humanize", true, "human-readable output")
includeFiles := flags.Bool("files", false, "include detailed file metrics, from all volume servers")
maxParallelization := flags.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
if err = flags.Parse(args); err != nil {
return err
@@ -81,21 +59,14 @@ func (c *commandClusterStatus) Do(args []string, commandEnv *CommandEnv, writer
}
sp := &ClusterStatusPrinter{
writer: writer,
humanize: *humanize,
maxParallelization: *maxParallelization,
writer: writer,
humanize: *humanize,
locked: commandEnv.isLocked(),
collections: collections,
topology: topology,
volumeSizeLimitMb: volumeSizeLimitMb,
}
if *includeFiles {
if err := sp.loadFileStats(commandEnv); err != nil {
return err
}
}
sp.Print()
return nil
@@ -112,19 +83,11 @@ func (sp *ClusterStatusPrinter) int(n int) string {
return sp.uint64(uint64(n))
}
func (sp *ClusterStatusPrinter) uint64Plural(n uint64, str string) string {
func (sp *ClusterStatusPrinter) plural(n int, str string) string {
if !sp.humanize {
return fmt.Sprintf("%s(s)", str)
}
uin := math.MaxInt
if n < math.MaxInt {
uin = int(n)
}
return english.PluralWord(int(uin), str, "")
}
func (sp *ClusterStatusPrinter) plural(n int, str string) string {
return sp.uint64Plural(uint64(n), str)
return english.PluralWord(n, str, "")
}
func (sp *ClusterStatusPrinter) bytes(b uint64) string {
@@ -165,90 +128,16 @@ func (sp *ClusterStatusPrinter) intPct(a, b int) string {
}
func (sp *ClusterStatusPrinter) write(format string, a ...any) {
sp.writerMu.Lock()
defer sp.writerMu.Unlock()
format = strings.TrimRight(format, " ")
if len(format) == 0 {
format = "\n"
}
fmt.Fprintf(sp.writer, format, a...)
last := format[len(format)-1:]
if last != "\n" && last != "\r" {
fmt.Fprint(sp.writer, "\n")
}
fmt.Fprintf(sp.writer, strings.TrimRight(format, "\r\n "), a...)
fmt.Fprint(sp.writer, "\n")
}
// TODO: add option to collect detailed file stats
func (sp *ClusterStatusPrinter) Print() {
sp.write("")
sp.printClusterInfo()
sp.printVolumeInfo()
sp.printStorageInfo()
sp.printFilesInfo()
}
// TODO: collect stats for EC volumes as well
func (sp *ClusterStatusPrinter) loadFileStats(commandEnv *CommandEnv) error {
sp.regularVolumeStats = RegularVolumeStats{}
var mu sync.Mutex
var progressTotal, progressDone uint64
ewg := NewErrorWaitGroup(sp.maxParallelization)
for _, dci := range sp.topology.DataCenterInfos {
for _, ri := range dci.RackInfos {
for _, dni := range ri.DataNodeInfos {
for _, d := range dni.DiskInfos {
mu.Lock()
progressTotal += uint64(len(d.VolumeInfos))
mu.Unlock()
for _, v := range d.VolumeInfos {
ewg.Add(func() error {
// Collect regular volume stats
err := operation.WithVolumeServerClient(false, pb.NewServerAddressWithGrpcPort(dni.Id, int(dni.GrpcPort)), commandEnv.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
resp, reqErr := volumeServerClient.VolumeStatus(context.Background(), &volume_server_pb.VolumeStatusRequest{
VolumeId: uint32(v.Id),
})
if reqErr != nil {
return reqErr
}
mu.Lock()
defer mu.Unlock()
if resp != nil {
if _, ok := sp.regularVolumeStats[v.Id]; !ok {
sp.regularVolumeStats[v.Id] = []*VolumeReplicaStats{}
}
sp.regularVolumeStats[v.Id] = append(sp.regularVolumeStats[v.Id], &VolumeReplicaStats{
Id: dni.Id,
VolumeId: v.Id,
Files: resp.FileCount,
FilesDeleted: resp.FileDeletedCount,
TotalSize: resp.VolumeSize,
})
}
progressDone++
return nil
})
if err != nil {
return err
}
mu.Lock()
sp.write("collecting file stats: %s \r", sp.uint64Pct(progressDone, progressTotal))
mu.Unlock()
return nil
})
}
}
}
}
}
err := ewg.Wait()
sp.write("")
return err
}
func (sp *ClusterStatusPrinter) printClusterInfo() {
@@ -388,52 +277,3 @@ func (sp *ClusterStatusPrinter) printStorageInfo() {
sp.write("\traw: %s on volume replicas, %s on EC shards", sp.bytes(rawVolumeSize), sp.bytes(rawEcVolumeSize))
sp.write("")
}
func (sp *ClusterStatusPrinter) printFilesInfo() {
if len(sp.regularVolumeStats) == 0 {
return
}
var regularFilesTotal, regularFilesDeleted, regularFilesSize uint64
var regularFilesTotalRaw, regularFilesDeletedRaw, regularFilesSizeRaw uint64
for _, replicaStats := range sp.regularVolumeStats {
rc := uint64(len(replicaStats))
var volumeFilesTotal, volumeFilesSize, volumeFilesDeleted uint64
for _, rs := range replicaStats {
regularFilesTotalRaw += rs.Files
regularFilesSizeRaw += rs.TotalSize
regularFilesDeletedRaw += rs.FilesDeleted
volumeFilesTotal += rs.Files
volumeFilesSize += rs.TotalSize
volumeFilesDeleted += rs.FilesDeleted
}
regularFilesTotal += (volumeFilesTotal / rc)
regularFilesSize += (volumeFilesSize / rc)
regularFilesDeleted += (volumeFilesDeleted / rc)
}
regularFiles := regularFilesTotal - regularFilesDeleted
regularFilesRaw := regularFilesTotalRaw - regularFilesDeletedRaw
var avgFileSize uint64
if regularFilesTotal != 0 {
avgFileSize = regularFilesSize / regularFilesTotal
}
sp.write("files:")
sp.write("\tregular: %s %s, %s readable (%s), %s deleted (%s), avg %s per file",
sp.uint64(regularFilesTotal), sp.uint64Plural(regularFilesTotal, "file"),
sp.uint64(regularFiles), sp.uint64Pct(regularFiles, regularFilesTotal),
sp.uint64(regularFilesDeleted), sp.uint64Pct(regularFilesDeleted, regularFilesTotal),
sp.bytes(avgFileSize))
sp.write("\tregular raw: %s %s, %s readable (%s), %s deleted (%s), %s total",
sp.uint64(regularFilesTotalRaw), sp.uint64Plural(regularFilesTotalRaw, "file"),
sp.uint64(regularFilesRaw), sp.uint64Pct(regularFilesRaw, regularFilesTotalRaw),
sp.uint64(regularFilesDeletedRaw), sp.uint64Pct(regularFilesDeletedRaw, regularFilesTotalRaw),
sp.bytes(regularFilesSizeRaw))
sp.write("\tEC: [no data]")
sp.write("\tEC raw: [no data]")
sp.write("")
}
-75
View File
@@ -138,78 +138,3 @@ func TestPrintStorageInfo(t *testing.T) {
}
}
}
func TestPrintFilesInfo(t *testing.T) {
testCases := []struct {
regularVolumeStats RegularVolumeStats
humanize bool
want string
}{
{
regularVolumeStats: RegularVolumeStats{
1: []*VolumeReplicaStats{
&VolumeReplicaStats{Id: "10.200.17.13:9001", VolumeId: 1, Files: 159, FilesDeleted: 8, TotalSize: 89762704},
&VolumeReplicaStats{Id: "10.200.17.13:9002", VolumeId: 1, Files: 159, FilesDeleted: 8, TotalSize: 89762704},
&VolumeReplicaStats{Id: "10.200.17.13:9008", VolumeId: 1, Files: 159, FilesDeleted: 8, TotalSize: 89762704},
},
2: []*VolumeReplicaStats{
&VolumeReplicaStats{Id: "10.200.17.13:9003", VolumeId: 2, Files: 192, FilesDeleted: 21, TotalSize: 93788632},
&VolumeReplicaStats{Id: "10.200.17.13:9004", VolumeId: 2, Files: 192, FilesDeleted: 21, TotalSize: 93788632},
&VolumeReplicaStats{Id: "10.200.17.13:9005", VolumeId: 2, Files: 192, FilesDeleted: 21, TotalSize: 93788632},
},
3: []*VolumeReplicaStats{
&VolumeReplicaStats{Id: "10.200.17.13:9001", VolumeId: 3, Files: 149, FilesDeleted: 0, TotalSize: 81643872},
&VolumeReplicaStats{Id: "10.200.17.13:9006", VolumeId: 3, Files: 149, FilesDeleted: 0, TotalSize: 81643872},
&VolumeReplicaStats{Id: "10.200.17.13:9009", VolumeId: 3, Files: 149, FilesDeleted: 0, TotalSize: 81643872},
},
},
humanize: false,
want: `files:
regular: 500 file(s), 471 readable (94.20%), 29 deleted (5.80%), avg 530390 byte(s) per file
regular raw: 1500 file(s), 1413 readable (94.20%), 87 deleted (5.80%), 795585624 byte(s) total
EC: [no data]
EC raw: [no data]
`,
},
{
regularVolumeStats: RegularVolumeStats{
1: []*VolumeReplicaStats{
&VolumeReplicaStats{Id: "10.200.17.13:9001", VolumeId: 1, Files: 184, FilesDeleted: 33, TotalSize: 79187475},
&VolumeReplicaStats{Id: "10.200.17.13:9008", VolumeId: 1, Files: 184, FilesDeleted: 33, TotalSize: 79187475},
},
2: []*VolumeReplicaStats{
&VolumeReplicaStats{Id: "10.200.17.13:9004", VolumeId: 2, Files: 245, FilesDeleted: 4, TotalSize: 89501070},
&VolumeReplicaStats{Id: "10.200.17.13:9005", VolumeId: 2, Files: 245, FilesDeleted: 4, TotalSize: 89501070},
},
3: []*VolumeReplicaStats{
&VolumeReplicaStats{Id: "10.200.17.13:9006", VolumeId: 3, Files: 171, FilesDeleted: 12, TotalSize: 124049530},
&VolumeReplicaStats{Id: "10.200.17.13:9009", VolumeId: 3, Files: 171, FilesDeleted: 12, TotalSize: 124049530},
},
},
humanize: true,
want: `files:
regular: 600 files, 551 readable (91.83%), 49 deleted (8.16%), avg 488 kB per file
regular raw: 1,200 files, 1,102 readable (91.83%), 98 deleted (8.16%), 586 MB total
EC: [no data]
EC raw: [no data]
`,
},
}
for i, tc := range testCases {
var buf bytes.Buffer
sp := &ClusterStatusPrinter{
writer: &buf,
humanize: tc.humanize,
regularVolumeStats: tc.regularVolumeStats,
}
sp.printFilesInfo()
got := buf.String()
if got != tc.want {
t.Errorf("#%d: got %v, want %v", i, got, tc.want)
}
}
}
+26 -199
View File
@@ -202,35 +202,6 @@ func collectEcNodes(commandEnv *CommandEnv, diskType types.DiskType) (ecNodes []
return collectEcNodesForDC(commandEnv, "", diskType)
}
// collectVolumeIdToCollection returns a map from volume ID to its collection name
func collectVolumeIdToCollection(t *master_pb.TopologyInfo, vids []needle.VolumeId) map[needle.VolumeId]string {
result := make(map[needle.VolumeId]string)
if len(vids) == 0 {
return result
}
vidSet := make(map[needle.VolumeId]bool)
for _, vid := range vids {
vidSet[vid] = true
}
for _, dc := range t.DataCenterInfos {
for _, r := range dc.RackInfos {
for _, dn := range r.DataNodeInfos {
for _, diskInfo := range dn.DiskInfos {
for _, vi := range diskInfo.VolumeInfos {
vid := needle.VolumeId(vi.Id)
if vidSet[vid] {
result[vid] = vi.Collection
}
}
}
}
}
}
return result
}
func collectCollectionsForVolumeIds(t *master_pb.TopologyInfo, vids []needle.VolumeId) []string {
if len(vids) == 0 {
return nil
@@ -679,25 +650,6 @@ type ecBalancer struct {
applyBalancing bool
maxParallelization int
diskType types.DiskType // target disk type for EC shards (default: HardDriveType)
// EC configuration for shard distribution (defaults to 10+4)
dataShardCount int
parityShardCount int
}
// getDataShardCount returns the configured data shard count, defaulting to standard 10
func (ecb *ecBalancer) getDataShardCount() int {
if ecb.dataShardCount > 0 {
return ecb.dataShardCount
}
return erasure_coding.DataShardsCount
}
// getParityShardCount returns the configured parity shard count, defaulting to standard 4
func (ecb *ecBalancer) getParityShardCount() int {
if ecb.parityShardCount > 0 {
return ecb.parityShardCount
}
return erasure_coding.ParityShardsCount
}
func (ecb *ecBalancer) errorWaitGroup() *ErrorWaitGroup {
@@ -804,176 +756,59 @@ func countShardsByRack(vid needle.VolumeId, locations []*EcNode, diskType types.
})
}
// shardsByTypePerRack counts data shards (< dataShards) and parity shards (>= dataShards) per rack
func shardsByTypePerRack(vid needle.VolumeId, locations []*EcNode, diskType types.DiskType, dataShards int) (dataPerRack, parityPerRack map[string][]erasure_coding.ShardId) {
dataPerRack = make(map[string][]erasure_coding.ShardId)
parityPerRack = make(map[string][]erasure_coding.ShardId)
for _, ecNode := range locations {
shardBits := findEcVolumeShards(ecNode, vid, diskType)
rackId := string(ecNode.rack)
for _, shardId := range shardBits.ShardIds() {
if int(shardId) < dataShards {
dataPerRack[rackId] = append(dataPerRack[rackId], shardId)
} else {
parityPerRack[rackId] = append(parityPerRack[rackId], shardId)
}
}
}
return
}
func (ecb *ecBalancer) doBalanceEcShardsAcrossRacks(collection string, vid needle.VolumeId, locations []*EcNode) error {
racks := ecb.racks()
numRacks := len(racks)
// Use configured EC scheme for shard type classification (defaults to 10+4)
dataShardCount := ecb.getDataShardCount()
parityShardCount := ecb.getParityShardCount()
// Get current distribution of data shards per rack (parity computed after data balancing)
dataPerRack, _ := shardsByTypePerRack(vid, locations, ecb.diskType, dataShardCount)
// Calculate max shards per rack for each type to ensure even spread
// Data: 10 shards / 6 racks = max 2 per rack
// Parity: 4 shards / 6 racks = max 1 per rack (with 2 racks having 0)
maxDataPerRack := ceilDivide(dataShardCount, numRacks)
maxParityPerRack := ceilDivide(parityShardCount, numRacks)
// see the volume's shards are in how many racks, and how many in each rack
rackToShardCount := countShardsByRack(vid, locations, ecb.diskType)
// Calculate actual total shards for this volume (not hardcoded default)
var totalShardsForVolume int
for _, count := range rackToShardCount {
totalShardsForVolume += count
}
// calculate average number of shards an ec rack should have for one volume
averageShardsPerEcRack := ceilDivide(totalShardsForVolume, len(racks))
rackEcNodesWithVid := groupBy(locations, func(ecNode *EcNode) string {
return string(ecNode.rack)
})
// Track total shard count per rack for slot management
rackToShardCount := countShardsByRack(vid, locations, ecb.diskType)
// First pass: Balance data shards across racks
if err := ecb.balanceShardTypeAcrossRacks(collection, vid, racks, rackEcNodesWithVid, dataPerRack, rackToShardCount, maxDataPerRack, "data"); err != nil {
return err
}
// Refresh locations after data shard moves and get parity distribution
locations = ecb.collectVolumeIdToEcNodes(collection)[vid]
_, parityPerRack := shardsByTypePerRack(vid, locations, ecb.diskType, dataShardCount)
rackEcNodesWithVid = groupBy(locations, func(ecNode *EcNode) string {
return string(ecNode.rack)
})
rackToShardCount = countShardsByRack(vid, locations, ecb.diskType)
// Second pass: Balance parity shards across racks
if err := ecb.balanceShardTypeAcrossRacks(collection, vid, racks, rackEcNodesWithVid, parityPerRack, rackToShardCount, maxParityPerRack, "parity"); err != nil {
return err
}
return nil
}
// balanceShardTypeAcrossRacks spreads shards of a specific type (data or parity) evenly across racks
func (ecb *ecBalancer) balanceShardTypeAcrossRacks(
collection string,
vid needle.VolumeId,
racks map[RackId]*EcRack,
rackEcNodesWithVid map[string][]*EcNode,
shardsPerRack map[string][]erasure_coding.ShardId,
rackToShardCount map[string]int,
maxPerRack int,
shardType string,
) error {
// Find racks with too many shards of this type
shardsToMove := make(map[erasure_coding.ShardId]*EcNode)
for rackId, shards := range shardsPerRack {
if len(shards) <= maxPerRack {
// ecShardsToMove = select overflown ec shards from racks with ec shard counts > averageShardsPerEcRack
ecShardsToMove := make(map[erasure_coding.ShardId]*EcNode)
for rackId, count := range rackToShardCount {
if count <= averageShardsPerEcRack {
continue
}
// Pick excess shards to move
excess := len(shards) - maxPerRack
ecNodes := rackEcNodesWithVid[rackId]
for i := 0; i < excess && i < len(shards); i++ {
shardId := shards[i]
// Find which node has this shard
for _, ecNode := range ecNodes {
shardBits := findEcVolumeShards(ecNode, vid, ecb.diskType)
if shardBits.HasShardId(shardId) {
shardsToMove[shardId] = ecNode
break
}
}
possibleEcNodes := rackEcNodesWithVid[rackId]
for shardId, ecNode := range pickNEcShardsToMoveFrom(possibleEcNodes, vid, count-averageShardsPerEcRack, ecb.diskType) {
ecShardsToMove[shardId] = ecNode
}
}
// Move shards to racks that have fewer than maxPerRack of this type
for shardId, ecNode := range shardsToMove {
// Find destination rack with room for this shard type
destRackId, err := ecb.pickRackForShardType(racks, shardsPerRack, maxPerRack, rackToShardCount)
for shardId, ecNode := range ecShardsToMove {
rackId, err := ecb.pickRackToBalanceShardsInto(racks, rackToShardCount)
if err != nil {
fmt.Printf("ec %s shard %d.%d at %s can not find a destination rack:\n%s\n", shardType, vid, shardId, ecNode.info.Id, err.Error())
fmt.Printf("ec shard %d.%d at %s can not find a destination rack:\n%s\n", vid, shardId, ecNode.info.Id, err.Error())
continue
}
var possibleDestinationEcNodes []*EcNode
for _, n := range racks[destRackId].ecNodes {
for _, n := range racks[rackId].ecNodes {
possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
}
err = ecb.pickOneEcNodeAndMoveOneShard(ecNode, collection, vid, shardId, possibleDestinationEcNodes)
if err != nil {
return err
}
// Update tracking
shardsPerRack[string(destRackId)] = append(shardsPerRack[string(destRackId)], shardId)
// Remove from source rack
srcRack := string(ecNode.rack)
for i, s := range shardsPerRack[srcRack] {
if s == shardId {
shardsPerRack[srcRack] = append(shardsPerRack[srcRack][:i], shardsPerRack[srcRack][i+1:]...)
break
}
}
rackToShardCount[string(destRackId)] += 1
rackToShardCount[srcRack] -= 1
racks[destRackId].freeEcSlot -= 1
racks[RackId(srcRack)].freeEcSlot += 1
rackToShardCount[string(rackId)] += 1
rackToShardCount[string(ecNode.rack)] -= 1
racks[rackId].freeEcSlot -= 1
racks[ecNode.rack].freeEcSlot += 1
}
return nil
}
// pickRackForShardType selects a rack that has room for more shards of a specific type
func (ecb *ecBalancer) pickRackForShardType(
rackToEcNodes map[RackId]*EcRack,
shardsPerRack map[string][]erasure_coding.ShardId,
maxPerRack int,
rackToShardCount map[string]int,
) (RackId, error) {
var candidates []RackId
minShards := maxPerRack + 1
for rackId, rack := range rackToEcNodes {
if rack.freeEcSlot <= 0 {
continue
}
currentCount := len(shardsPerRack[string(rackId)])
if currentCount >= maxPerRack {
continue
}
// For EC shards, replica placement constraint only applies when DiffRackCount > 0.
if ecb.replicaPlacement != nil && ecb.replicaPlacement.DiffRackCount > 0 && rackToShardCount[string(rackId)] >= ecb.replicaPlacement.DiffRackCount {
continue
}
if currentCount < minShards {
candidates = nil
minShards = currentCount
}
if currentCount == minShards {
candidates = append(candidates, rackId)
}
}
if len(candidates) == 0 {
return "", errors.New("no rack available for shard type balancing")
}
return candidates[rand.IntN(len(candidates))], nil
}
func (ecb *ecBalancer) pickRackToBalanceShardsInto(rackToEcNodes map[RackId]*EcRack, rackToShardCount map[string]int) (RackId, error) {
targets := []RackId{}
targetShards := -1
@@ -991,11 +826,7 @@ func (ecb *ecBalancer) pickRackToBalanceShardsInto(rackToEcNodes map[RackId]*EcR
details += fmt.Sprintf(" Skipped %s because it has no free slots\n", rackId)
continue
}
// For EC shards, replica placement constraint only applies when DiffRackCount > 0.
// When DiffRackCount = 0 (e.g., replica placement "000"), EC shards should be
// distributed freely across racks for fault tolerance - the "000" means
// "no volume replication needed" because erasure coding provides redundancy.
if ecb.replicaPlacement != nil && ecb.replicaPlacement.DiffRackCount > 0 && shards > ecb.replicaPlacement.DiffRackCount {
if ecb.replicaPlacement != nil && shards > ecb.replicaPlacement.DiffRackCount {
details += fmt.Sprintf(" Skipped %s because shards %d > replica placement limit for other racks (%d)\n", rackId, shards, ecb.replicaPlacement.DiffRackCount)
continue
}
@@ -1196,11 +1027,7 @@ func (ecb *ecBalancer) pickEcNodeToBalanceShardsInto(vid needle.VolumeId, existi
}
shards := nodeShards[node]
// For EC shards, replica placement constraint only applies when SameRackCount > 0.
// When SameRackCount = 0 (e.g., replica placement "000"), EC shards should be
// distributed freely within racks - the "000" means "no volume replication needed"
// because erasure coding provides redundancy.
if ecb.replicaPlacement != nil && ecb.replicaPlacement.SameRackCount > 0 && shards > ecb.replicaPlacement.SameRackCount+1 {
if ecb.replicaPlacement != nil && shards > ecb.replicaPlacement.SameRackCount+1 {
details += fmt.Sprintf(" Skipped %s because shards %d > replica placement limit for the rack (%d + 1)\n", node.info.Id, shards, ecb.replicaPlacement.SameRackCount)
continue
}
+1 -3
View File
@@ -133,9 +133,7 @@ func TestPickRackToBalanceShardsInto(t *testing.T) {
{testTopologyEc, "6241", "123", []string{"rack1", "rack2", "rack3", "rack4", "rack5", "rack6"}, ""},
{testTopologyEc, "6242", "123", []string{"rack1", "rack2", "rack3", "rack4", "rack5", "rack6"}, ""},
// EC volumes.
// With replication "000" (DiffRackCount=0), EC shards should be distributed freely
// because erasure coding provides its own redundancy. No replica placement error.
{testTopologyEc, "9577", "", []string{"rack1", "rack2", "rack3"}, ""},
{testTopologyEc, "9577", "", nil, "shards 1 > replica placement limit for other racks (0)"},
{testTopologyEc, "9577", "111", []string{"rack1", "rack2", "rack3"}, ""},
{testTopologyEc, "9577", "222", []string{"rack1", "rack2", "rack3"}, ""},
{testTopologyEc, "10457", "222", []string{"rack1"}, ""},
+8 -54
View File
@@ -94,7 +94,7 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
shardReplicaPlacement := encodeCommand.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty")
sourceDiskTypeStr := encodeCommand.String("sourceDiskType", "", "filter source volumes by disk type (hdd, ssd, or empty for all)")
diskTypeStr := encodeCommand.String("diskType", "", "target disk type for EC shards (hdd, ssd, or empty for default hdd)")
applyBalancing := encodeCommand.Bool("rebalance", true, "re-balance EC shards after creation (default: true)")
applyBalancing := encodeCommand.Bool("rebalance", false, "re-balance EC shards after creation")
verbose := encodeCommand.Bool("verbose", false, "show detailed reasons why volumes are not selected for encoding")
if err = encodeCommand.Parse(args); err != nil {
@@ -153,9 +153,6 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
return nil
}
// Collect volume ID to collection name mapping for the sync operation
volumeIdToCollection := collectVolumeIdToCollection(topologyInfo, volumeIds)
// Collect volume locations BEFORE EC encoding starts to avoid race condition
// where the master metadata is updated after EC encoding but before deletion
fmt.Printf("Collecting volume locations for %d volumes before EC encoding...\n", len(volumeIds))
@@ -164,34 +161,8 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr
return fmt.Errorf("failed to collect volume locations before EC encoding: %w", err)
}
// Pre-flight check: verify the target disk type has capacity for EC shards
// This prevents encoding shards only to fail during rebalance
_, totalFreeEcSlots, err := collectEcNodesForDC(commandEnv, "", diskType)
if err != nil {
return fmt.Errorf("failed to check EC shard capacity: %w", err)
}
// Calculate required slots: each volume needs TotalShardsCount (14) shards distributed
requiredSlots := len(volumeIds) * erasure_coding.TotalShardsCount
if totalFreeEcSlots < 1 {
// No capacity at all on the target disk type
if diskType != types.HardDriveType {
return fmt.Errorf("no free ec shard slots on disk type '%s'. The target disk type has no capacity.\n"+
"Your volumes are likely on a different disk type. Try:\n"+
" ec.encode -collection=%s -diskType=hdd\n"+
"Or omit -diskType to use the default (hdd)", diskType, *collection)
}
return fmt.Errorf("no free ec shard slots. only %d left on disk type '%s'", totalFreeEcSlots, diskType)
}
if totalFreeEcSlots < requiredSlots {
fmt.Printf("Warning: limited EC shard capacity. Need %d slots for %d volumes, but only %d slots available on disk type '%s'.\n",
requiredSlots, len(volumeIds), totalFreeEcSlots, diskType)
fmt.Printf("Rebalancing may not achieve optimal distribution.\n")
}
// encode all requested volumes...
if err = doEcEncode(commandEnv, writer, volumeIdToCollection, volumeIds, *maxParallelization); err != nil {
if err = doEcEncode(commandEnv, *collection, volumeIds, *maxParallelization); err != nil {
return fmt.Errorf("ec encode for volumes %v: %w", volumeIds, err)
}
// ...re-balance ec shards...
@@ -221,7 +192,7 @@ func volumeLocations(commandEnv *CommandEnv, volumeIds []needle.VolumeId) (map[n
return res, nil
}
func doEcEncode(commandEnv *CommandEnv, writer io.Writer, volumeIdToCollection map[needle.VolumeId]string, volumeIds []needle.VolumeId, maxParallelization int) error {
func doEcEncode(commandEnv *CommandEnv, collection string, volumeIds []needle.VolumeId, maxParallelization int) error {
if !commandEnv.isLocked() {
return fmt.Errorf("lock is lost")
}
@@ -246,26 +217,10 @@ func doEcEncode(commandEnv *CommandEnv, writer io.Writer, volumeIdToCollection m
return err
}
// Sync replicas and select the best one for each volume (with highest file count)
// This addresses data inconsistency risk in multi-replica volumes (issue #7797)
// by syncing missing entries between replicas before encoding
bestReplicas := make(map[needle.VolumeId]wdclient.Location)
for _, vid := range volumeIds {
locs := locations[vid]
collection := volumeIdToCollection[vid]
// Sync missing entries between replicas, then select the best one
bestLoc, selectErr := syncAndSelectBestReplica(commandEnv.option.GrpcDialOption, vid, collection, locs, "", writer)
if selectErr != nil {
return fmt.Errorf("failed to sync and select replica for volume %d: %v", vid, selectErr)
}
bestReplicas[vid] = bestLoc
}
// generate ec shards using the best replica for each volume
// generate ec shards
ewg.Reset()
for _, vid := range volumeIds {
target := bestReplicas[vid]
collection := volumeIdToCollection[vid]
for i, vid := range volumeIds {
target := locations[vid][i%len(locations[vid])]
ewg.Add(func() error {
if err := generateEcShards(commandEnv.option.GrpcDialOption, vid, collection, target.ServerAddress()); err != nil {
return fmt.Errorf("generate ec shards for volume %d on %s: %v", vid, target.Url, err)
@@ -284,9 +239,8 @@ func doEcEncode(commandEnv *CommandEnv, writer io.Writer, volumeIdToCollection m
}
ewg.Reset()
for _, vid := range volumeIds {
target := bestReplicas[vid]
collection := volumeIdToCollection[vid]
for i, vid := range volumeIds {
target := locations[vid][i%len(locations[vid])]
ewg.Add(func() error {
if err := mountEcShards(commandEnv.option.GrpcDialOption, collection, vid, target.ServerAddress(), shardIds); err != nil {
return fmt.Errorf("mount ec shards for volume %d on %s: %v", vid, target.Url, err)
-149
View File
@@ -4,7 +4,6 @@ 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/types"
)
@@ -137,151 +136,3 @@ func newEcNode(dc string, rack string, dataNodeId string, freeEcSlot int) *EcNod
func (ecNode *EcNode) addEcVolumeAndShardsForTest(vid uint32, collection string, shardIds []uint32) *EcNode {
return ecNode.addEcVolumeShards(needle.VolumeId(vid), collection, shardIds, types.HardDriveType)
}
// TestCommandEcBalanceEvenDataAndParityDistribution verifies that after balancing:
// 1. Data shards (0-9) are evenly distributed across racks (max 2 per rack for 6 racks)
// 2. Parity shards (10-13) are evenly distributed across racks (max 1 per rack for 6 racks)
func TestCommandEcBalanceEvenDataAndParityDistribution(t *testing.T) {
// Setup: All 14 shards start on rack1 (simulating fresh EC encode)
ecb := &ecBalancer{
ecNodes: []*EcNode{
// All shards initially on rack1/dn1
newEcNode("dc1", "rack1", "dn1", 100).addEcVolumeAndShardsForTest(1, "c1", []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}),
// Empty nodes on other racks
newEcNode("dc1", "rack2", "dn2", 100),
newEcNode("dc1", "rack3", "dn3", 100),
newEcNode("dc1", "rack4", "dn4", 100),
newEcNode("dc1", "rack5", "dn5", 100),
newEcNode("dc1", "rack6", "dn6", 100),
},
applyBalancing: false, // Dry-run mode (simulates moves by updating internal state)
diskType: types.HardDriveType,
}
ecb.balanceEcVolumes("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
vid := needle.VolumeId(1)
dataShardCount := erasure_coding.DataShardsCount // 10
parityShardCount := erasure_coding.ParityShardsCount // 4
// Count data and parity shards per rack based on current (updated) state
dataPerRack, parityPerRack := countDataAndParityShardsPerRack(ecb.ecNodes, vid, dataShardCount)
// With 6 racks:
// - Data shards (10): max 2 per rack (ceil(10/6) = 2)
// - Parity shards (4): max 1 per rack (ceil(4/6) = 1)
maxDataPerRack := ceilDivide(dataShardCount, 6) // 2
maxParityPerRack := ceilDivide(parityShardCount, 6) // 1
// Verify no rack has more than max data shards
for rackId, count := range dataPerRack {
if count > maxDataPerRack {
t.Errorf("rack %s has %d data shards, expected max %d", rackId, count, maxDataPerRack)
}
}
// Verify no rack has more than max parity shards
for rackId, count := range parityPerRack {
if count > maxParityPerRack {
t.Errorf("rack %s has %d parity shards, expected max %d", rackId, count, maxParityPerRack)
}
}
// Verify all shards are distributed (total counts)
totalData := 0
totalParity := 0
for _, count := range dataPerRack {
totalData += count
}
for _, count := range parityPerRack {
totalParity += count
}
if totalData != dataShardCount {
t.Errorf("total data shards = %d, expected %d", totalData, dataShardCount)
}
if totalParity != parityShardCount {
t.Errorf("total parity shards = %d, expected %d", totalParity, parityShardCount)
}
// Verify data shards are spread across at least 5 racks (10 shards / 2 max per rack)
racksWithData := len(dataPerRack)
minRacksForData := dataShardCount / maxDataPerRack // At least 5 racks needed for 10 data shards
if racksWithData < minRacksForData {
t.Errorf("data shards spread across only %d racks, expected at least %d", racksWithData, minRacksForData)
}
// Verify parity shards are spread across at least 4 racks (4 shards / 1 max per rack)
racksWithParity := len(parityPerRack)
if racksWithParity < parityShardCount {
t.Errorf("parity shards spread across only %d racks, expected at least %d", racksWithParity, parityShardCount)
}
t.Logf("Distribution after balancing:")
t.Logf(" Data shards per rack: %v (max allowed: %d)", dataPerRack, maxDataPerRack)
t.Logf(" Parity shards per rack: %v (max allowed: %d)", parityPerRack, maxParityPerRack)
}
// countDataAndParityShardsPerRack counts data and parity shards per rack
func countDataAndParityShardsPerRack(ecNodes []*EcNode, vid needle.VolumeId, dataShardCount int) (dataPerRack, parityPerRack map[string]int) {
dataPerRack = make(map[string]int)
parityPerRack = make(map[string]int)
for _, ecNode := range ecNodes {
shardBits := findEcVolumeShards(ecNode, vid, types.HardDriveType)
for _, shardId := range shardBits.ShardIds() {
rackId := string(ecNode.rack)
if int(shardId) < dataShardCount {
dataPerRack[rackId]++
} else {
parityPerRack[rackId]++
}
}
}
return
}
// TestCommandEcBalanceMultipleVolumesEvenDistribution tests that multiple volumes
// each get their data and parity shards evenly distributed
func TestCommandEcBalanceMultipleVolumesEvenDistribution(t *testing.T) {
// Setup: Two volumes, each with all 14 shards on different starting racks
ecb := &ecBalancer{
ecNodes: []*EcNode{
// Volume 1: all shards on rack1
newEcNode("dc1", "rack1", "dn1", 100).addEcVolumeAndShardsForTest(1, "c1", []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}),
// Volume 2: all shards on rack2
newEcNode("dc1", "rack2", "dn2", 100).addEcVolumeAndShardsForTest(2, "c1", []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}),
// Empty nodes on other racks
newEcNode("dc1", "rack3", "dn3", 100),
newEcNode("dc1", "rack4", "dn4", 100),
newEcNode("dc1", "rack5", "dn5", 100),
newEcNode("dc1", "rack6", "dn6", 100),
},
applyBalancing: false, // Dry-run mode
diskType: types.HardDriveType,
}
ecb.balanceEcVolumes("c1")
// Check both volumes
for _, vid := range []needle.VolumeId{1, 2} {
dataPerRack, parityPerRack := countDataAndParityShardsPerRack(ecb.ecNodes, vid, erasure_coding.DataShardsCount)
maxDataPerRack := ceilDivide(erasure_coding.DataShardsCount, 6)
maxParityPerRack := ceilDivide(erasure_coding.ParityShardsCount, 6)
for rackId, count := range dataPerRack {
if count > maxDataPerRack {
t.Errorf("volume %d: rack %s has %d data shards, expected max %d", vid, rackId, count, maxDataPerRack)
}
}
for rackId, count := range parityPerRack {
if count > maxParityPerRack {
t.Errorf("volume %d: rack %s has %d parity shards, expected max %d", vid, rackId, count, maxParityPerRack)
}
}
t.Logf("Volume %d - Data: %v, Parity: %v", vid, dataPerRack, parityPerRack)
}
}
+1 -1
View File
@@ -345,7 +345,7 @@ func (c *commandRemoteCache) doComprehensiveSync(commandEnv *CommandEnv, writer
fmt.Fprintf(writer, "Caching %s... ", pathToCacheCopy)
if _, err := filer.CacheRemoteObjectToLocalCluster(commandEnv, remoteConf, remoteLocation, util.FullPath(dir), localEntry); err != nil {
if err := filer.CacheRemoteObjectToLocalCluster(commandEnv, remoteConf, remoteLocation, util.FullPath(dir), localEntry); err != nil {
fmt.Fprintf(writer, "failed: %v\n", err)
if executionErr == nil {
executionErr = err
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more