mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 01:57:10 +01:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d75290601 | ||
|
|
289ec5e2f5 | ||
|
|
683e3d06a4 | ||
|
|
2567be8040 | ||
|
|
14df5d1bb5 | ||
|
|
ce71968bad | ||
|
|
a898160e39 | ||
|
|
aaa6de7712 | ||
|
|
1d0361d936 | ||
|
|
276fd764da | ||
|
|
044e448305 | ||
|
|
cc2edfaf68 | ||
|
|
9a4f32fc49 | ||
|
|
683eef72a6 | ||
|
|
1dfda78e59 | ||
|
|
31cb28d9d3 | ||
|
|
3613279f25 | ||
|
|
f67ba35f4a | ||
|
|
f63d9ad390 | ||
|
|
5b86d33c3c | ||
|
|
4a764dbb37 | ||
|
|
4aa50bfa6a | ||
|
|
77a56c2857 | ||
|
|
f4cdfcc5fd |
No files matched your search
@@ -224,3 +224,4 @@ jobs:
|
||||
echo "✓ Successfully copied ${{ matrix.variant }} to Docker Hub"
|
||||
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ jobs:
|
||||
run: |
|
||||
cd test/kafka
|
||||
go mod download
|
||||
go mod tidy
|
||||
|
||||
- name: Run Kafka Gateway Unit Tests
|
||||
run: |
|
||||
@@ -96,6 +97,7 @@ jobs:
|
||||
run: |
|
||||
cd test/kafka
|
||||
go mod download
|
||||
go mod tidy
|
||||
|
||||
- name: Run Integration Tests
|
||||
run: |
|
||||
@@ -154,6 +156,7 @@ jobs:
|
||||
cd test/kafka
|
||||
# Use go mod download with timeout to prevent hanging
|
||||
timeout 90s go mod download || echo "Warning: Dependency download timed out, continuing with cached modules"
|
||||
go mod tidy
|
||||
|
||||
- name: Build and start SeaweedFS MQ
|
||||
run: |
|
||||
@@ -332,6 +335,7 @@ jobs:
|
||||
cd test/kafka
|
||||
# Use go mod download with timeout to prevent hanging
|
||||
timeout 90s go mod download || echo "Warning: Dependency download timed out, continuing with cached modules"
|
||||
go mod tidy
|
||||
|
||||
- name: Build and start SeaweedFS MQ
|
||||
run: |
|
||||
@@ -492,6 +496,7 @@ jobs:
|
||||
run: |
|
||||
cd test/kafka
|
||||
timeout 90s go mod download || echo "Warning: Dependency download timed out, continuing with cached modules"
|
||||
go mod tidy
|
||||
|
||||
- name: Build and start SeaweedFS MQ
|
||||
run: |
|
||||
@@ -649,6 +654,7 @@ jobs:
|
||||
run: |
|
||||
cd test/kafka
|
||||
timeout 90s go mod download || echo "Warning: Dependency download timed out, continuing with cached modules"
|
||||
go mod tidy
|
||||
|
||||
- name: Build and start SeaweedFS MQ
|
||||
run: |
|
||||
@@ -803,6 +809,7 @@ jobs:
|
||||
run: |
|
||||
cd test/kafka
|
||||
go mod download
|
||||
go mod tidy
|
||||
|
||||
- name: Run Protocol Tests
|
||||
run: |
|
||||
|
||||
@@ -83,3 +83,4 @@ jobs:
|
||||
path: test/s3/filer_group/weed-test*.log
|
||||
retention-days: 3
|
||||
|
||||
|
||||
@@ -91,3 +91,4 @@ jobs:
|
||||
echo "| readonly | /public | Read-only |" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ defaults:
|
||||
jobs:
|
||||
awscli-tests:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
|
||||
@@ -130,3 +130,4 @@ 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
|
||||
@@ -96,12 +96,12 @@ require (
|
||||
gocloud.dev v0.43.0
|
||||
gocloud.dev/pubsub/natspubsub v0.43.0
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.43.0
|
||||
golang.org/x/crypto v0.45.0
|
||||
golang.org/x/crypto v0.46.0
|
||||
golang.org/x/exp v0.0.0-20250811191247-51f88131bc50
|
||||
golang.org/x/image v0.34.0
|
||||
golang.org/x/net v0.47.0
|
||||
golang.org/x/net v0.48.0
|
||||
golang.org/x/oauth2 v0.32.0 // indirect
|
||||
golang.org/x/sys v0.38.0
|
||||
golang.org/x/sys v0.39.0
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
golang.org/x/tools v0.39.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
@@ -127,8 +127,8 @@ require (
|
||||
github.com/arangodb/go-driver v1.6.9
|
||||
github.com/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.0
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.5
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.6
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.6
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.93.0
|
||||
github.com/cognusion/imaging v1.0.2
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
@@ -158,7 +158,7 @@ require (
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.1
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.122.0
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.6
|
||||
go.uber.org/atomic v1.11.0
|
||||
@@ -173,6 +173,7 @@ require (
|
||||
cloud.google.com/go/longrunning v0.6.7 // indirect
|
||||
cloud.google.com/go/pubsub/v2 v2.0.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 // indirect
|
||||
github.com/bazelbuild/rules_go v0.46.0 // indirect
|
||||
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
|
||||
github.com/blevesearch/snowballstem v0.9.0 // indirect
|
||||
@@ -264,7 +265,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.18.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.6 // indirect
|
||||
@@ -272,7 +273,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.34.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.38.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 // indirect
|
||||
github.com/aws/smithy-go v1.24.0 // indirect
|
||||
@@ -445,7 +446,7 @@ require (
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
golang.org/x/arch v0.20.0 // indirect
|
||||
golang.org/x/term v0.37.0 // indirect
|
||||
golang.org/x/term v0.38.0 // indirect
|
||||
golang.org/x/time v0.12.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251111163417-95abcf5c77ba // indirect
|
||||
|
||||
@@ -669,10 +669,10 @@ github.com/aws/aws-sdk-go-v2 v1.41.0 h1:tNvqh1s+v0vFYdA1xq0aOJH+Y5cRyZ5upu6roPgP
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.0/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3 h1:RIb3yr/+PZ18YYNe6MDiG/3jVoJrPmdoCARwNkMGvco=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3/go.mod h1:jjgx1n7x0FAKl6TnakqrpkHWWKcX3xfWtdnIJs5K9CE=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.5 h1:xMo63RlqP3ZZydpJDMBsH9uJ10hgHYfQFIk1cHDXrR4=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.5/go.mod h1:hhbH6oRcou+LpXfA/0vPElh/e0M3aFeOblE1sssAAEk=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.6 h1:hFLBGUKjmLAekvi1evLi5hVvFQtSo3GYwi+Bx4lpJf8=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.6/go.mod h1:lcUL/gcd8WyjCrMnxez5OXkO3/rwcNmvfno62tnXNcI=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.6 h1:F9vWao2TwjV2MyiyVS+duza0NIRtAslgLUM0vTA1ZaE=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.6/go.mod h1:SgHzKjEVsdQr6Opor0ihgWtkWdfRAIwxYzSJ8O85VHY=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 h1:80+uETIWS1BqjnN9uJ0dBUaETh+P1XwFy5vwHwK5r9k=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16/go.mod h1:wOOsYuxYuB/7FlnVtzeBYRcjSRtQpAW0hCP7tIULMwo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.18.4 h1:0SzCLoPRSK3qSydsaFQWugP+lOBCTPwfcBOm6222+UA=
|
||||
@@ -681,8 +681,8 @@ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 h1:rgGwPzb82iBYSvHMH
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16/go.mod h1:L/UxsGeKpGoIj6DxfhOWHWQ/kGKcd4I1VncE4++IyKA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 h1:1jtGzuV7c82xnqOVfx2F0xmJcOw5374L7N6juGW6x6U=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16/go.mod h1:M2E5OQf+XLe+SZGmmpaI2yy+J326aFf6/+54PoxSANc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d2KyU5X/BZxjOkRo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.15 h1:NLYTEyZmVZo0Qh183sC8nC+ydJXOOeIL/qI/sS3PdLY=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.15/go.mod h1:Z803iB3B0bc8oJV8zH2PERLRfQUJ2n2BXISpsA4+O1M=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
|
||||
@@ -695,12 +695,14 @@ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.15 h1:wsSQ4SVz5YE1c
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.15/go.mod h1:I7sditnFGtYMIqPRU1QoHZAUrXkGp4SczmlLwrNPlD0=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.93.0 h1:IrbE3B8O9pm3lsg96AXIN5MXX4pECEuExh/A0Du3AuI=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.93.0/go.mod h1:/sJLzHtiiZvs6C1RbxS/anSAFwZD6oC6M/kotQzOiLw=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 h1:HpI7aMmJ+mm1wkSHIA2t5EaFFv5EFYXePW30p1EIrbQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.4/go.mod h1:C5RdGMYGlfM0gYq/tifqgn4EbyX99V15P2V3R+VHbQU=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.34.7 h1:OBuZE9Wt8h2imuRktu+WfjiTGrnYdCIJg8IX92aalHE=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.34.7/go.mod h1:4WYoZAhHt+dWYpoOQUgkUKfuQbE6Gg/hW4oXE0pKS9U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.38.8 h1:80dpSqWMwx2dAm30Ib7J6ucz1ZHfiv5OCRwN/EnCOXQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.38.8/go.mod h1:IzNt/udsXlETCdvBOL0nmyMe2t9cGmXmZgsdoZGYYhI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.7 h1:eYnlt6QxnFINKzwxP5/Ucs1vkG7VT3Iezmvfgc2waUw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.7/go.mod h1:+fWt2UHSb4kS7Pu8y+BMBvJF0EWx+4H0hzNwtDNRTrg=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 h1:aM/Q24rIlS3bRAhTyFurowU8A0SMyGDtEOY/l/s/1Uw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.8/go.mod h1:+fWt2UHSb4kS7Pu8y+BMBvJF0EWx+4H0hzNwtDNRTrg=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 h1:AHDr0DaHIAo8c9t1emrzAlVDFp+iMMKnPdYy6XO4MCE=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12/go.mod h1:GQ73XawFFiWxyWXMHWfhiomvP3tXtdNar/fi8z18sx0=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 h1:SciGFVNZ4mHdm7gpD1dgZYnCuVdX1s+lFTg4+4DOy70=
|
||||
@@ -1777,8 +1779,8 @@ github.com/ydb-platform/ydb-go-genproto v0.0.0-20221215182650-986f9d10542f/go.mo
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20230528143953-42c825ace222/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20251125145508-6d7ef87db5cb h1:LZ6dhVfWzhicf/P5Xh7fA0Jd7rfGduxmB2QZpD+Lz9Q=
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20251125145508-6d7ef87db5cb/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.0 h1:/NyPd9KnCJgzrEXCArqk1ThqCH2Dh31uUwl88o/VkuM=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.0/go.mod h1:9YzkhlIymWaJGX6KMU3vh5sOf3UKbCXkG/ZdjaI3zNM=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1 h1:XaRxeVrOyl3y6v9CiYMWaFdZ6zevvYe+TRxOR8ifa2s=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1/go.mod h1:9YzkhlIymWaJGX6KMU3vh5sOf3UKbCXkG/ZdjaI3zNM=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.44.0/go.mod h1:oSLwnuilwIpaF5bJJMAofnGgzPJusoI3zWMNb8I+GnM=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.47.3/go.mod h1:bWnOIcUHd7+Sl7DN+yhyY1H/I61z53GczvwJgXMgvj0=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.122.0 h1:uvqheUfoEJz0CLLLaYct69wpvoaosM/2joWFcbwoqfw=
|
||||
@@ -1917,8 +1919,8 @@ golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
@@ -2056,8 +2058,8 @@ golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -2218,8 +2220,8 @@ golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -2237,8 +2239,8 @@ golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
||||
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
|
||||
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.03"
|
||||
appVersion: "4.04"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.0.403
|
||||
version: 4.0.404
|
||||
@@ -0,0 +1,187 @@
|
||||
# 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"
|
||||
|
||||
@@ -78,6 +78,43 @@ 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
|
||||
|
||||
+16
-15
@@ -43,24 +43,25 @@ require (
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/aws/aws-sdk-go v1.55.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.40.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.18.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.93.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 // indirect
|
||||
github.com/aws/smithy-go v1.24.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bradenaw/juniper v0.15.3 // indirect
|
||||
@@ -229,14 +230,14 @@ require (
|
||||
go.opentelemetry.io/otel/trace v1.38.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.45.0 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250811191247-51f88131bc50 // indirect
|
||||
golang.org/x/image v0.34.0 // indirect
|
||||
golang.org/x/net v0.47.0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/oauth2 v0.32.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/term v0.37.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/term v0.38.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
golang.org/x/time v0.12.0 // indirect
|
||||
google.golang.org/api v0.247.0 // indirect
|
||||
|
||||
+32
-30
@@ -102,42 +102,44 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3d
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.40.1 h1:difXb4maDZkRH0x//Qkwcfpdg1XQVXEAEs2DdXldFFc=
|
||||
github.com/aws/aws-sdk-go-v2 v1.40.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.0 h1:tNvqh1s+v0vFYdA1xq0aOJH+Y5cRyZ5upu6roPgPKd4=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.0/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3 h1:RIb3yr/+PZ18YYNe6MDiG/3jVoJrPmdoCARwNkMGvco=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3/go.mod h1:jjgx1n7x0FAKl6TnakqrpkHWWKcX3xfWtdnIJs5K9CE=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.3 h1:01Ym72hK43hjwDeJUfi1l2oYLXBAOR8gNSZNmXmvuas=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.3/go.mod h1:55nWF/Sr9Zvls0bGnWkRxUdhzKqj9uRNlPvgV1vgxKc=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.15 h1:utxLraaifrSBkeyII9mIbVwXXWrZdlPO7FIKmyLCEcY=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.15/go.mod h1:hW6zjYUDQwfz3icf4g2O41PHi77u10oAzJ84iSzR/lo=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.6 h1:hFLBGUKjmLAekvi1evLi5hVvFQtSo3GYwi+Bx4lpJf8=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.6/go.mod h1:lcUL/gcd8WyjCrMnxez5OXkO3/rwcNmvfno62tnXNcI=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.6 h1:F9vWao2TwjV2MyiyVS+duza0NIRtAslgLUM0vTA1ZaE=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.6/go.mod h1:SgHzKjEVsdQr6Opor0ihgWtkWdfRAIwxYzSJ8O85VHY=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 h1:80+uETIWS1BqjnN9uJ0dBUaETh+P1XwFy5vwHwK5r9k=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16/go.mod h1:wOOsYuxYuB/7FlnVtzeBYRcjSRtQpAW0hCP7tIULMwo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.18.4 h1:0SzCLoPRSK3qSydsaFQWugP+lOBCTPwfcBOm6222+UA=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.18.4/go.mod h1:JAet9FsBHjfdI+TnMBX4ModNNaQHAd3dc/Bk+cNsxeM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.15 h1:Y5YXgygXwDI5P4RkteB5yF7v35neH7LfJKBG+hzIons=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.15/go.mod h1:K+/1EpG42dFSY7CBj+Fruzm8PsCGWTXJ3jdeJ659oGQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.15 h1:AvltKnW9ewxX2hFmQS0FyJH93aSvJVUEFvXfU+HWtSE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.15/go.mod h1:3I4oCdZdmgrREhU74qS1dK9yZ62yumob+58AbFR4cQA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d2KyU5X/BZxjOkRo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 h1:rgGwPzb82iBYSvHMHXc8h9mRoOUBZIGFgKb9qniaZZc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16/go.mod h1:L/UxsGeKpGoIj6DxfhOWHWQ/kGKcd4I1VncE4++IyKA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 h1:1jtGzuV7c82xnqOVfx2F0xmJcOw5374L7N6juGW6x6U=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16/go.mod h1:M2E5OQf+XLe+SZGmmpaI2yy+J326aFf6/+54PoxSANc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.15 h1:NLYTEyZmVZo0Qh183sC8nC+ydJXOOeIL/qI/sS3PdLY=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.15/go.mod h1:Z803iB3B0bc8oJV8zH2PERLRfQUJ2n2BXISpsA4+O1M=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.6 h1:P1MU/SuhadGvg2jtviDXPEejU3jBNhoeeAlRadHzvHI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.6/go.mod h1:5KYaMG6wmVKMFBSfWoyG/zH8pWwzQFnKgpoSRlXHKdQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.15 h1:3/u/4yZOffg5jdNk1sDpOQ4Y+R6Xbh+GzpDrSZjuy3U=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.15/go.mod h1:4Zkjq0FKjE78NKjabuM4tRXKFzUJWXgP0ItEZK8l7JU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 h1:oHjJHeUy0ImIV0bsrX0X91GkV5nJAyv1l1CC9lnO0TI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16/go.mod h1:iRSNGgOYmiYwSCXxXaKb9HfOEj40+oTKn8pTxMlYkRM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.15 h1:wsSQ4SVz5YE1crz0Ap7VBZrV4nNqZt4CIBBT8mnwoNc=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.15/go.mod h1:I7sditnFGtYMIqPRU1QoHZAUrXkGp4SczmlLwrNPlD0=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.93.0 h1:IrbE3B8O9pm3lsg96AXIN5MXX4pECEuExh/A0Du3AuI=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.93.0/go.mod h1:/sJLzHtiiZvs6C1RbxS/anSAFwZD6oC6M/kotQzOiLw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.6 h1:8sTTiw+9yuNXcfWeqKF2x01GqCF49CpP4Z9nKrrk/ts=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.6/go.mod h1:8WYg+Y40Sn3X2hioaaWAAIngndR8n1XFdRPPX+7QBaM=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.11 h1:E+KqWoVsSrj1tJ6I/fjDIu5xoS2Zacuu1zT+H7KtiIk=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.11/go.mod h1:qyWHz+4lvkXcr3+PoGlGHEI+3DLLiU6/GdrFfMaAhB0=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.3 h1:tzMkjh0yTChUqJDgGkcDdxvZDSrJ/WB6R6ymI5ehqJI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.3/go.mod h1:T270C0R5sZNLbWUe8ueiAF42XSZxxPocTaGSgs5c/60=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 h1:HpI7aMmJ+mm1wkSHIA2t5EaFFv5EFYXePW30p1EIrbQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.4/go.mod h1:C5RdGMYGlfM0gYq/tifqgn4EbyX99V15P2V3R+VHbQU=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 h1:aM/Q24rIlS3bRAhTyFurowU8A0SMyGDtEOY/l/s/1Uw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.8/go.mod h1:+fWt2UHSb4kS7Pu8y+BMBvJF0EWx+4H0hzNwtDNRTrg=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 h1:AHDr0DaHIAo8c9t1emrzAlVDFp+iMMKnPdYy6XO4MCE=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12/go.mod h1:GQ73XawFFiWxyWXMHWfhiomvP3tXtdNar/fi8z18sx0=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 h1:SciGFVNZ4mHdm7gpD1dgZYnCuVdX1s+lFTg4+4DOy70=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5/go.mod h1:iW40X4QBmUxdP+fZNOpfmkdMZqsovezbAeO+Ubiv2pk=
|
||||
github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=
|
||||
github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
@@ -730,8 +732,8 @@ golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -811,8 +813,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -890,8 +892,8 @@ golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -904,8 +906,8 @@ golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
||||
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
|
||||
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
|
||||
@@ -25,3 +25,4 @@ test-resume: build-weed
|
||||
clean:
|
||||
rm -f ../../weed/weed
|
||||
|
||||
|
||||
@@ -47,3 +47,4 @@ 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)
|
||||
|
||||
|
||||
@@ -90,3 +90,4 @@ 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)
|
||||
|
||||
|
||||
@@ -17,3 +17,4 @@
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,4 +5,4 @@
|
||||
"secret_key": "some_secret_key1",
|
||||
"region": "us-east-1",
|
||||
"filer_group": "testgroup"
|
||||
}
|
||||
}
|
||||
@@ -90,3 +90,4 @@ To debug test failures:
|
||||
```
|
||||
|
||||
|
||||
|
||||
Vendored
+1
@@ -35,3 +35,4 @@
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -340,7 +341,7 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
}
|
||||
|
||||
// Get versioning, object lock, and owner information from extended attributes
|
||||
versioningEnabled := false
|
||||
versioningStatus := ""
|
||||
objectLockEnabled := false
|
||||
objectLockMode := ""
|
||||
var objectLockDuration int32 = 0
|
||||
@@ -348,7 +349,7 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
|
||||
if resp.Entry.Extended != nil {
|
||||
// Use shared utility to extract versioning information
|
||||
versioningEnabled = extractVersioningFromEntry(resp.Entry)
|
||||
versioningStatus = extractVersioningFromEntry(resp.Entry)
|
||||
|
||||
// Use shared utility to extract Object Lock information
|
||||
objectLockEnabled, objectLockMode, objectLockDuration = extractObjectLockInfoFromEntry(resp.Entry)
|
||||
@@ -367,7 +368,7 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
LastModified: time.Unix(resp.Entry.Attributes.Mtime, 0),
|
||||
Quota: quota,
|
||||
QuotaEnabled: quotaEnabled,
|
||||
VersioningEnabled: versioningEnabled,
|
||||
VersioningStatus: versioningStatus,
|
||||
ObjectLockEnabled: objectLockEnabled,
|
||||
ObjectLockMode: objectLockMode,
|
||||
ObjectLockDuration: objectLockDuration,
|
||||
@@ -430,7 +431,7 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
details.Bucket.QuotaEnabled = quotaEnabled
|
||||
|
||||
// Get versioning, object lock, and owner information from extended attributes
|
||||
versioningEnabled := false
|
||||
versioningStatus := ""
|
||||
objectLockEnabled := false
|
||||
objectLockMode := ""
|
||||
var objectLockDuration int32 = 0
|
||||
@@ -438,7 +439,7 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
|
||||
if bucketResp.Entry.Extended != nil {
|
||||
// Use shared utility to extract versioning information
|
||||
versioningEnabled = extractVersioningFromEntry(bucketResp.Entry)
|
||||
versioningStatus = extractVersioningFromEntry(bucketResp.Entry)
|
||||
|
||||
// Use shared utility to extract Object Lock information
|
||||
objectLockEnabled, objectLockMode, objectLockDuration = extractObjectLockInfoFromEntry(bucketResp.Entry)
|
||||
@@ -449,7 +450,7 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
}
|
||||
}
|
||||
|
||||
details.Bucket.VersioningEnabled = versioningEnabled
|
||||
details.Bucket.VersioningStatus = versioningStatus
|
||||
details.Bucket.ObjectLockEnabled = objectLockEnabled
|
||||
details.Bucket.ObjectLockMode = objectLockMode
|
||||
details.Bucket.ObjectLockDuration = objectLockDuration
|
||||
@@ -491,6 +492,45 @@ func (s *AdminServer) listBucketObjects(client filer_pb.SeaweedFilerClient, buck
|
||||
|
||||
entry := resp.Entry
|
||||
if entry.IsDirectory {
|
||||
// Check if this is a .versions directory (represents a versioned object)
|
||||
if strings.HasSuffix(entry.Name, ".versions") {
|
||||
// This directory represents an object, add it as an object without the .versions suffix
|
||||
objectName := strings.TrimSuffix(entry.Name, ".versions")
|
||||
objectKey := objectName
|
||||
if directory != bucketBasePath {
|
||||
relativePath := directory[len(bucketBasePath)+1:]
|
||||
objectKey = fmt.Sprintf("%s/%s", relativePath, objectName)
|
||||
}
|
||||
|
||||
// Extract latest version metadata from extended attributes
|
||||
var size int64 = 0
|
||||
var mtime int64 = entry.Attributes.Mtime
|
||||
if entry.Extended != nil {
|
||||
// Get size of latest version
|
||||
if sizeBytes, ok := entry.Extended[s3_constants.ExtLatestVersionSizeKey]; ok && len(sizeBytes) == 8 {
|
||||
size = int64(util.BytesToUint64(sizeBytes))
|
||||
}
|
||||
// Get mtime of latest version
|
||||
if mtimeBytes, ok := entry.Extended[s3_constants.ExtLatestVersionMtimeKey]; ok && len(mtimeBytes) == 8 {
|
||||
mtime = int64(util.BytesToUint64(mtimeBytes))
|
||||
}
|
||||
}
|
||||
|
||||
obj := S3Object{
|
||||
Key: objectKey,
|
||||
Size: size,
|
||||
LastModified: time.Unix(mtime, 0),
|
||||
ETag: "",
|
||||
StorageClass: "STANDARD",
|
||||
}
|
||||
|
||||
details.Objects = append(details.Objects, obj)
|
||||
details.TotalCount++
|
||||
details.TotalSize += size
|
||||
// Don't recurse into .versions directories
|
||||
continue
|
||||
}
|
||||
|
||||
// Recursively list subdirectories
|
||||
subDir := fmt.Sprintf("%s/%s", directory, entry.Name)
|
||||
err := s.listBucketObjects(client, bucketBasePath, subDir, "", details)
|
||||
@@ -1902,9 +1942,8 @@ func extractObjectLockInfoFromEntry(entry *filer_pb.Entry) (bool, string, int32)
|
||||
}
|
||||
|
||||
// Function to extract versioning information from bucket entry using shared utilities
|
||||
func extractVersioningFromEntry(entry *filer_pb.Entry) bool {
|
||||
enabled, _ := s3api.LoadVersioningFromExtended(entry)
|
||||
return enabled
|
||||
func extractVersioningFromEntry(entry *filer_pb.Entry) string {
|
||||
return s3api.GetVersioningStatus(entry)
|
||||
}
|
||||
|
||||
// GetConfigPersistence returns the config persistence manager
|
||||
|
||||
@@ -125,6 +125,12 @@ func (s *AdminServer) CreateBucket(c *gin.Context) {
|
||||
// Convert quota to bytes
|
||||
quotaBytes := convertQuotaToBytes(req.QuotaSize, req.QuotaUnit)
|
||||
|
||||
// Validate quota: if enabled, size must be greater than 0
|
||||
if req.QuotaEnabled && quotaBytes <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Quota size must be greater than 0 when quota is enabled"})
|
||||
return
|
||||
}
|
||||
|
||||
// Sanitize owner: trim whitespace and enforce max length
|
||||
owner := strings.TrimSpace(req.Owner)
|
||||
if len(owner) > MaxOwnerNameLength {
|
||||
@@ -466,16 +472,19 @@ func (s *AdminServer) CreateS3BucketWithObjectLock(bucketName string, quotaBytes
|
||||
// Handle Object Lock configuration using shared utilities
|
||||
if objectLockEnabled {
|
||||
var duration int32 = 0
|
||||
var mode string = ""
|
||||
|
||||
if setDefaultRetention {
|
||||
// Validate Object Lock parameters only when setting default retention
|
||||
if err := s3api.ValidateObjectLockParameters(objectLockEnabled, objectLockMode, objectLockDuration); err != nil {
|
||||
return fmt.Errorf("invalid Object Lock parameters: %w", err)
|
||||
}
|
||||
duration = objectLockDuration
|
||||
mode = objectLockMode
|
||||
}
|
||||
|
||||
// Create Object Lock configuration using shared utility
|
||||
objectLockConfig := s3api.CreateObjectLockConfigurationFromParams(objectLockEnabled, objectLockMode, duration)
|
||||
objectLockConfig := s3api.CreateObjectLockConfigurationFromParams(objectLockEnabled, mode, duration)
|
||||
|
||||
// Store Object Lock configuration in extended attributes using shared utility
|
||||
if err := s3api.StoreObjectLockConfigurationInExtended(bucketEntry, objectLockConfig); err != nil {
|
||||
|
||||
@@ -78,7 +78,7 @@ type S3Bucket struct {
|
||||
LastModified time.Time `json:"last_modified"`
|
||||
Quota int64 `json:"quota"` // Quota in bytes, 0 means no quota
|
||||
QuotaEnabled bool `json:"quota_enabled"` // Whether quota is enabled
|
||||
VersioningEnabled bool `json:"versioning_enabled"` // Whether versioning is enabled
|
||||
VersioningStatus string `json:"versioning_status"` // Versioning status: "" (never enabled), "Enabled", or "Suspended"
|
||||
ObjectLockEnabled bool `json:"object_lock_enabled"` // Whether object lock is enabled
|
||||
ObjectLockMode string `json:"object_lock_mode"` // Object lock mode: "GOVERNANCE" or "COMPLIANCE"
|
||||
ObjectLockDuration int32 `json:"object_lock_duration"` // Default retention duration in days
|
||||
|
||||
@@ -117,7 +117,7 @@ func (s *WorkerGrpcServer) Stop() error {
|
||||
s.connMutex.Lock()
|
||||
for _, conn := range s.connections {
|
||||
conn.cancel()
|
||||
close(conn.outgoing)
|
||||
s.safeCloseOutgoingChannel(conn, "Stop")
|
||||
}
|
||||
s.connections = make(map[string]*WorkerConnection)
|
||||
s.connMutex.Unlock()
|
||||
@@ -182,15 +182,27 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
}
|
||||
conn.capabilities = capabilities
|
||||
|
||||
// Register connection
|
||||
// Register connection - clean up old connection if worker is reconnecting
|
||||
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)
|
||||
|
||||
// Send registration response
|
||||
// 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)
|
||||
regResponse := &worker_pb.AdminMessage{
|
||||
Timestamp: time.Now().Unix(),
|
||||
Message: &worker_pb.AdminMessage_RegistrationResponse{
|
||||
@@ -203,13 +215,11 @@ 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 {
|
||||
@@ -235,7 +245,9 @@ 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)
|
||||
}
|
||||
}
|
||||
@@ -440,16 +452,36 @@ 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()
|
||||
if conn, exists := s.connections[workerID]; exists {
|
||||
conn.cancel()
|
||||
close(conn.outgoing)
|
||||
delete(s.connections, workerID)
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
@@ -479,7 +511,7 @@ func (s *WorkerGrpcServer) cleanupStaleConnections() {
|
||||
if conn.lastSeen.Before(cutoff) {
|
||||
glog.Warningf("Cleaning up stale worker connection: %s", workerID)
|
||||
conn.cancel()
|
||||
close(conn.outgoing)
|
||||
s.safeCloseOutgoingChannel(conn, "cleanupStaleConnections")
|
||||
delete(s.connections, workerID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,7 +266,26 @@ 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 {
|
||||
return s.activeTopology.UpdateTopology(topologyInfo)
|
||||
// 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
|
||||
}
|
||||
|
||||
// convertToExistingFormat converts task results to existing system format using dynamic mapping
|
||||
|
||||
@@ -137,6 +137,7 @@ 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
|
||||
@@ -255,6 +256,54 @@ 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,11 +8,53 @@ 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()
|
||||
|
||||
@@ -142,8 +184,21 @@ 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)
|
||||
|
||||
@@ -164,14 +164,16 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
if bucket.VersioningEnabled {
|
||||
if bucket.VersioningStatus == "Enabled" {
|
||||
<span class="badge bg-success">
|
||||
<i class="fas fa-check me-1"></i>Enabled
|
||||
</span>
|
||||
} else {
|
||||
<span class="badge bg-secondary">
|
||||
<i class="fas fa-times me-1"></i>Disabled
|
||||
} else if bucket.VersioningStatus == "Suspended" {
|
||||
<span class="badge bg-warning">
|
||||
<i class="fas fa-pause me-1"></i>Suspended
|
||||
</span>
|
||||
} else {
|
||||
<span class="text-muted">Not configured</span>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@@ -185,9 +187,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
</div>
|
||||
</div>
|
||||
} else {
|
||||
<span class="badge bg-secondary">
|
||||
<i class="fas fa-unlock me-1"></i>Disabled
|
||||
</span>
|
||||
<span class="text-muted">Not configured</span>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@@ -1044,9 +1044,11 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
'<tr>' +
|
||||
'<td><strong>Versioning:</strong></td>' +
|
||||
'<td>' +
|
||||
(bucket.versioning_enabled ?
|
||||
(bucket.versioning_status === 'Enabled' ?
|
||||
'<span class="badge bg-success"><i class="fas fa-check me-1"></i>Enabled</span>' :
|
||||
'<span class="badge bg-secondary"><i class="fas fa-times me-1"></i>Disabled</span>'
|
||||
bucket.versioning_status === 'Suspended' ?
|
||||
'<span class="badge bg-warning"><i class="fas fa-pause me-1"></i>Suspended</span>' :
|
||||
'<span class="text-muted">Not configured</span>'
|
||||
) +
|
||||
'</td>' +
|
||||
'</tr>' +
|
||||
@@ -1055,8 +1057,10 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
'<td>' +
|
||||
(bucket.object_lock_enabled ?
|
||||
'<span class="badge bg-warning"><i class="fas fa-lock me-1"></i>Enabled</span>' +
|
||||
'<br><small class="text-muted">' + escapeHtml(bucket.object_lock_mode) + ' • ' + bucket.object_lock_duration + ' days</small>' :
|
||||
'<span class="badge bg-secondary"><i class="fas fa-unlock me-1"></i>Disabled</span>'
|
||||
(bucket.object_lock_mode && bucket.object_lock_duration > 0 ?
|
||||
'<br><small class="text-muted">' + escapeHtml(bucket.object_lock_mode) + ' • ' + bucket.object_lock_duration + ' days</small>' :
|
||||
'') :
|
||||
'<span class="text-muted">Not configured</span>'
|
||||
) +
|
||||
'</td>' +
|
||||
'</tr>' +
|
||||
|
||||
@@ -253,59 +253,64 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if bucket.VersioningEnabled {
|
||||
if bucket.VersioningStatus == "Enabled" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Enabled</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else if bucket.VersioningStatus == "Suspended" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<span class=\"badge bg-warning\"><i class=\"fas fa-pause me-1\"></i>Suspended</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<span class=\"badge bg-secondary\"><i class=\"fas fa-times me-1\"></i>Disabled</span>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "<span class=\"text-muted\">Not configured</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if bucket.ObjectLockEnabled {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<div><span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span><div class=\"small text-muted\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "<div><span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span><div class=\"small text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 184, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 186, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, " • ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, " • ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 184, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 186, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</div></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "</div></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "<span class=\"badge bg-secondary\"><i class=\"fas fa-unlock me-1\"></i>Disabled</span>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "<span class=\"text-muted\">Not configured</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -318,7 +323,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -331,7 +336,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm owner-btn\" data-bucket-name=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm owner-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -344,7 +349,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" data-current-owner=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" data-current-owner=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -357,7 +362,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" title=\"Manage Owner\"><i class=\"fas fa-user-edit\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" title=\"Manage Owner\"><i class=\"fas fa-user-edit\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -370,7 +375,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-current-quota=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-current-quota=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -383,7 +388,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-quota-enabled=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" data-quota-enabled=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -396,7 +401,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -409,18 +414,18 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
if len(data.Buckets) == 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<tr><td colspan=\"9\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "<tr><td colspan=\"9\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "</tbody></table></div></div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "</tbody></table></div></div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -433,7 +438,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package cluster
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -41,6 +42,7 @@ type LiveLock struct {
|
||||
self string
|
||||
lc *LockClient
|
||||
owner string
|
||||
lockTTL time.Duration
|
||||
}
|
||||
|
||||
// NewShortLivedLock creates a lock with a 5-second duration
|
||||
@@ -59,17 +61,24 @@ 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)) (lock *LiveLock) {
|
||||
// lockTTL specifies how long the lock should be held. The renewal interval is
|
||||
// automatically derived as lockTTL / 2 to ensure timely renewals.
|
||||
func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerChange func(newLockOwner string), lockTTL time.Duration) (lock *LiveLock) {
|
||||
lock = &LiveLock{
|
||||
key: key,
|
||||
hostFiler: lc.seedFiler,
|
||||
cancelCh: make(chan struct{}),
|
||||
expireAtNs: time.Now().Add(lock_manager.LiveLockTTL).UnixNano(),
|
||||
expireAtNs: time.Now().Add(lockTTL).UnixNano(),
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
self: owner,
|
||||
lc: lc,
|
||||
lockTTL: lockTTL,
|
||||
}
|
||||
if lock.lockTTL == 0 {
|
||||
lock.lockTTL = lock_manager.LiveLockTTL
|
||||
}
|
||||
go func() {
|
||||
renewInterval := lock.lockTTL / 2
|
||||
isLocked := false
|
||||
lockOwner := ""
|
||||
for {
|
||||
@@ -82,13 +91,13 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
}
|
||||
|
||||
if isLocked {
|
||||
if err := lock.AttemptToLock(lock_manager.LiveLockTTL); err != nil {
|
||||
if err := lock.AttemptToLock(lock.lockTTL); err != nil {
|
||||
glog.V(0).Infof("Lost lock %s: %v", key, err)
|
||||
isLocked = false
|
||||
atomic.StoreInt32(&lock.isLocked, 0)
|
||||
}
|
||||
} else {
|
||||
if err := lock.AttemptToLock(lock_manager.LiveLockTTL); err == nil {
|
||||
if err := lock.AttemptToLock(lock.lockTTL); err == nil {
|
||||
isLocked = true
|
||||
// Note: AttemptToLock already sets lock.isLocked atomically on success
|
||||
}
|
||||
@@ -102,7 +111,11 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
case <-lock.cancelCh:
|
||||
return
|
||||
default:
|
||||
time.Sleep(lock_manager.RenewInterval)
|
||||
if isLocked {
|
||||
time.Sleep(renewInterval)
|
||||
} else {
|
||||
time.Sleep(5 * renewInterval)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -129,7 +142,11 @@ func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
|
||||
return err
|
||||
}
|
||||
if errorMessage != "" {
|
||||
glog.V(1).Infof("LOCK: doLock returned error message for key=%s: %s", lock.key, 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)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
return fmt.Errorf("%v", errorMessage)
|
||||
}
|
||||
@@ -206,7 +223,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(1).Infof("LOCK: Host changed from %s to %s for key=%s", previousHostFiler, resp.LockHostMovedTo, lock.key)
|
||||
glog.V(2).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 != "" {
|
||||
@@ -214,12 +231,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(1).Infof("LOCK: Owner changed from %s to %s for key=%s", previousOwner, resp.LockOwner, lock.key)
|
||||
glog.V(2).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(1).Infof("LOCK: Owner cleared for key=%s", lock.key)
|
||||
glog.V(2).Infof("LOCK: Owner cleared for key=%s", lock.key)
|
||||
lock.owner = ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ var Commands = []*Command{
|
||||
cmdIam,
|
||||
cmdMaster,
|
||||
cmdMasterFollower,
|
||||
cmdMini,
|
||||
cmdMount,
|
||||
cmdMqAgent,
|
||||
cmdMqBroker,
|
||||
|
||||
@@ -244,11 +244,6 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
raftServer.TransportManager.Register(grpcS)
|
||||
} else {
|
||||
protobuf.RegisterRaftServer(grpcS, raftServer)
|
||||
// Also register hashicorp transport for dual-write migration
|
||||
if raftServer.TransportManager != nil {
|
||||
raftServer.TransportManager.Register(grpcS)
|
||||
glog.V(0).Infof("Dual-write: hashicorp raft transport registered")
|
||||
}
|
||||
}
|
||||
reflection.Register(grpcS)
|
||||
glog.V(0).Infof("Start Seaweed Master %s grpc server at %s:%d", version.Version(), *masterOption.ipBind, grpcPort)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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", 32, "limit concurrent goroutine writers")
|
||||
mountOptions.concurrentReaders = cmdMount.Flag.Int("concurrentReaders", 16, "limit concurrent chunk fetches for read operations")
|
||||
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.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")
|
||||
|
||||
+1
-1
@@ -246,7 +246,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(0).Infof("wait to connect to filers %v grpc address", filerAddresses)
|
||||
glog.V(2).Infof("wait to connect to filers %v grpc address", filerAddresses)
|
||||
time.Sleep(time.Second)
|
||||
} else {
|
||||
glog.V(0).Infof("connected to filers %v", filerAddresses)
|
||||
|
||||
@@ -3,13 +3,14 @@ package command
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -102,7 +103,7 @@ func (wo *WebDavOption) startWebDav() bool {
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(0).Infof("wait to connect to filer %s grpc address %s", *wo.filer, filerAddress.ToGrpcAddress())
|
||||
glog.V(2).Infof("wait to connect to filer %s grpc address %s", *wo.filer, filerAddress.ToGrpcAddress())
|
||||
time.Sleep(time.Second)
|
||||
} else {
|
||||
glog.V(0).Infof("connected to filer %s grpc address %s", *wo.filer, filerAddress.ToGrpcAddress())
|
||||
|
||||
@@ -205,3 +205,4 @@ func (q *CleanupQueue) OldestAge() time.Duration {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -369,3 +369,4 @@ func TestCleanupQueue_Concurrent(t *testing.T) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -124,3 +124,4 @@ func MaskAccessKey(accessKeyId string) string {
|
||||
return accessKeyId
|
||||
}
|
||||
|
||||
|
||||
@@ -133,3 +133,4 @@ func TestMaskAccessKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ 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"
|
||||
@@ -142,7 +143,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.LiveLockTTL)
|
||||
mqBroker.KeepConnectedToBrokerBalancer(newBrokerBalancerCh)
|
||||
}()
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ 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"
|
||||
@@ -180,6 +181,7 @@ func (cr *CoordinatorRegistry) startLeaderElection() {
|
||||
GatewayLeaderLockKey,
|
||||
cr.gatewayAddress,
|
||||
cr.onLeadershipChange,
|
||||
lock_manager.LiveLockTTL,
|
||||
)
|
||||
|
||||
// Wait for shutdown
|
||||
|
||||
@@ -19,7 +19,9 @@ 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"
|
||||
@@ -56,9 +58,8 @@ 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
|
||||
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
|
||||
@@ -112,9 +113,11 @@ 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 {
|
||||
@@ -127,6 +130,7 @@ 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
|
||||
}
|
||||
@@ -163,6 +167,33 @@ 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 {
|
||||
|
||||
@@ -173,11 +204,11 @@ func WithGrpcClient(streamingMode bool, signature int32, fn func(*grpc.ClientCon
|
||||
}
|
||||
executionErr := fn(vgc.ClientConn)
|
||||
if executionErr != nil {
|
||||
if strings.Contains(executionErr.Error(), "transport") ||
|
||||
strings.Contains(executionErr.Error(), "connection closed") {
|
||||
if shouldInvalidateConnection(executionErr) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -51,6 +51,8 @@ service Seaweed {
|
||||
}
|
||||
rpc RaftRemoveServer (RaftRemoveServerRequest) returns (RaftRemoveServerResponse) {
|
||||
}
|
||||
rpc RaftLeadershipTransfer (RaftLeadershipTransferRequest) returns (RaftLeadershipTransferResponse) {
|
||||
}
|
||||
rpc VolumeGrow (VolumeGrowRequest) returns (VolumeGrowResponse) {
|
||||
}
|
||||
}
|
||||
@@ -443,5 +445,14 @@ 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 {
|
||||
}
|
||||
+183
-67
@@ -3690,6 +3690,110 @@ 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
|
||||
@@ -3698,7 +3802,7 @@ type VolumeGrowResponse struct {
|
||||
|
||||
func (x *VolumeGrowResponse) Reset() {
|
||||
*x = VolumeGrowResponse{}
|
||||
mi := &file_master_proto_msgTypes[58]
|
||||
mi := &file_master_proto_msgTypes[60]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -3710,7 +3814,7 @@ func (x *VolumeGrowResponse) String() string {
|
||||
func (*VolumeGrowResponse) ProtoMessage() {}
|
||||
|
||||
func (x *VolumeGrowResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[58]
|
||||
mi := &file_master_proto_msgTypes[60]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -3723,7 +3827,7 @@ func (x *VolumeGrowResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use VolumeGrowResponse.ProtoReflect.Descriptor instead.
|
||||
func (*VolumeGrowResponse) Descriptor() ([]byte, []int) {
|
||||
return file_master_proto_rawDescGZIP(), []int{58}
|
||||
return file_master_proto_rawDescGZIP(), []int{60}
|
||||
}
|
||||
|
||||
type SuperBlockExtra_ErasureCoding struct {
|
||||
@@ -3737,7 +3841,7 @@ type SuperBlockExtra_ErasureCoding struct {
|
||||
|
||||
func (x *SuperBlockExtra_ErasureCoding) Reset() {
|
||||
*x = SuperBlockExtra_ErasureCoding{}
|
||||
mi := &file_master_proto_msgTypes[61]
|
||||
mi := &file_master_proto_msgTypes[63]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -3749,7 +3853,7 @@ func (x *SuperBlockExtra_ErasureCoding) String() string {
|
||||
func (*SuperBlockExtra_ErasureCoding) ProtoMessage() {}
|
||||
|
||||
func (x *SuperBlockExtra_ErasureCoding) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[61]
|
||||
mi := &file_master_proto_msgTypes[63]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -3798,7 +3902,7 @@ type LookupVolumeResponse_VolumeIdLocation struct {
|
||||
|
||||
func (x *LookupVolumeResponse_VolumeIdLocation) Reset() {
|
||||
*x = LookupVolumeResponse_VolumeIdLocation{}
|
||||
mi := &file_master_proto_msgTypes[62]
|
||||
mi := &file_master_proto_msgTypes[64]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -3810,7 +3914,7 @@ func (x *LookupVolumeResponse_VolumeIdLocation) String() string {
|
||||
func (*LookupVolumeResponse_VolumeIdLocation) ProtoMessage() {}
|
||||
|
||||
func (x *LookupVolumeResponse_VolumeIdLocation) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[62]
|
||||
mi := &file_master_proto_msgTypes[64]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -3864,7 +3968,7 @@ type LookupEcVolumeResponse_EcShardIdLocation struct {
|
||||
|
||||
func (x *LookupEcVolumeResponse_EcShardIdLocation) Reset() {
|
||||
*x = LookupEcVolumeResponse_EcShardIdLocation{}
|
||||
mi := &file_master_proto_msgTypes[67]
|
||||
mi := &file_master_proto_msgTypes[69]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -3876,7 +3980,7 @@ func (x *LookupEcVolumeResponse_EcShardIdLocation) String() string {
|
||||
func (*LookupEcVolumeResponse_EcShardIdLocation) ProtoMessage() {}
|
||||
|
||||
func (x *LookupEcVolumeResponse_EcShardIdLocation) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[67]
|
||||
mi := &file_master_proto_msgTypes[69]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -3919,7 +4023,7 @@ type ListClusterNodesResponse_ClusterNode struct {
|
||||
|
||||
func (x *ListClusterNodesResponse_ClusterNode) Reset() {
|
||||
*x = ListClusterNodesResponse_ClusterNode{}
|
||||
mi := &file_master_proto_msgTypes[68]
|
||||
mi := &file_master_proto_msgTypes[70]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -3931,7 +4035,7 @@ func (x *ListClusterNodesResponse_ClusterNode) String() string {
|
||||
func (*ListClusterNodesResponse_ClusterNode) ProtoMessage() {}
|
||||
|
||||
func (x *ListClusterNodesResponse_ClusterNode) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[68]
|
||||
mi := &file_master_proto_msgTypes[70]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -3994,7 +4098,7 @@ type RaftListClusterServersResponse_ClusterServers struct {
|
||||
|
||||
func (x *RaftListClusterServersResponse_ClusterServers) Reset() {
|
||||
*x = RaftListClusterServersResponse_ClusterServers{}
|
||||
mi := &file_master_proto_msgTypes[69]
|
||||
mi := &file_master_proto_msgTypes[71]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -4006,7 +4110,7 @@ func (x *RaftListClusterServersResponse_ClusterServers) String() string {
|
||||
func (*RaftListClusterServersResponse_ClusterServers) ProtoMessage() {}
|
||||
|
||||
func (x *RaftListClusterServersResponse_ClusterServers) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[69]
|
||||
mi := &file_master_proto_msgTypes[71]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -4405,8 +4509,15 @@ 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\"\x14\n" +
|
||||
"\x12VolumeGrowResponse2\xd5\x0f\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" +
|
||||
"\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" +
|
||||
@@ -4431,7 +4542,8 @@ 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\x12K\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" +
|
||||
"\n" +
|
||||
"VolumeGrow\x12\x1c.master_pb.VolumeGrowRequest\x1a\x1d.master_pb.VolumeGrowResponse\"\x00B2Z0github.com/seaweedfs/seaweedfs/weed/pb/master_pbb\x06proto3"
|
||||
|
||||
@@ -4447,7 +4559,7 @@ func file_master_proto_rawDescGZIP() []byte {
|
||||
return file_master_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 70)
|
||||
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 72)
|
||||
var file_master_proto_goTypes = []any{
|
||||
(*Heartbeat)(nil), // 0: master_pb.Heartbeat
|
||||
(*HeartbeatResponse)(nil), // 1: master_pb.HeartbeatResponse
|
||||
@@ -4507,18 +4619,20 @@ var file_master_proto_goTypes = []any{
|
||||
(*RaftRemoveServerResponse)(nil), // 55: master_pb.RaftRemoveServerResponse
|
||||
(*RaftListClusterServersRequest)(nil), // 56: master_pb.RaftListClusterServersRequest
|
||||
(*RaftListClusterServersResponse)(nil), // 57: master_pb.RaftListClusterServersResponse
|
||||
(*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
|
||||
(*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
|
||||
}
|
||||
var file_master_proto_depIdxs = []int32{
|
||||
2, // 0: master_pb.Heartbeat.volumes:type_name -> master_pb.VolumeInformationMessage
|
||||
@@ -4527,30 +4641,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
|
||||
59, // 6: master_pb.Heartbeat.max_volume_counts:type_name -> master_pb.Heartbeat.MaxVolumeCountsEntry
|
||||
61, // 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
|
||||
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
|
||||
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
|
||||
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
|
||||
62, // 12: master_pb.LookupVolumeResponse.volume_id_locations:type_name -> master_pb.LookupVolumeResponse.VolumeIdLocation
|
||||
64, // 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
|
||||
63, // 18: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
|
||||
65, // 18: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
|
||||
26, // 19: master_pb.RackInfo.data_node_infos:type_name -> master_pb.DataNodeInfo
|
||||
64, // 20: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
|
||||
66, // 20: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
|
||||
27, // 21: master_pb.DataCenterInfo.rack_infos:type_name -> master_pb.RackInfo
|
||||
65, // 22: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
|
||||
67, // 22: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
|
||||
28, // 23: master_pb.TopologyInfo.data_center_infos:type_name -> master_pb.DataCenterInfo
|
||||
66, // 24: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
|
||||
68, // 24: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
|
||||
29, // 25: master_pb.VolumeListResponse.topology_info:type_name -> master_pb.TopologyInfo
|
||||
67, // 26: master_pb.LookupEcVolumeResponse.shard_id_locations:type_name -> master_pb.LookupEcVolumeResponse.EcShardIdLocation
|
||||
69, // 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
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -4579,32 +4693,34 @@ 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
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -4621,7 +4737,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: 70,
|
||||
NumMessages: 72,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -41,6 +41,7 @@ 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"
|
||||
)
|
||||
|
||||
@@ -70,6 +71,7 @@ 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)
|
||||
}
|
||||
|
||||
@@ -310,6 +312,16 @@ 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)
|
||||
@@ -346,6 +358,7 @@ 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()
|
||||
}
|
||||
@@ -423,6 +436,9 @@ 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")
|
||||
}
|
||||
@@ -810,6 +826,24 @@ 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 {
|
||||
@@ -911,6 +945,10 @@ var Seaweed_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "RaftRemoveServer",
|
||||
Handler: _Seaweed_RaftRemoveServer_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RaftLeadershipTransfer",
|
||||
Handler: _Seaweed_RaftLeadershipTransfer_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "VolumeGrow",
|
||||
Handler: _Seaweed_VolumeGrow_Handler,
|
||||
|
||||
@@ -2,12 +2,13 @@ package filersink
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -114,6 +115,7 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string)
|
||||
IsInputCompressed: "gzip" == header.Get("Content-Encoding"),
|
||||
MimeType: header.Get("Content-Type"),
|
||||
PairMap: nil,
|
||||
RetryForever: true,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
|
||||
@@ -61,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)
|
||||
})
|
||||
}, bucketSizeMetricsInterval)
|
||||
defer lock.Stop()
|
||||
|
||||
ticker := time.NewTicker(bucketSizeMetricsInterval)
|
||||
|
||||
@@ -28,7 +28,8 @@ func StoreVersioningInExtended(entry *filer_pb.Entry, enabled bool) error {
|
||||
if enabled {
|
||||
entry.Extended[s3_constants.ExtVersioningKey] = []byte(s3_constants.VersioningEnabled)
|
||||
} else {
|
||||
entry.Extended[s3_constants.ExtVersioningKey] = []byte(s3_constants.VersioningSuspended)
|
||||
// Don't set the header when versioning is not enabled
|
||||
delete(entry.Extended, s3_constants.ExtVersioningKey)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -49,6 +50,20 @@ func LoadVersioningFromExtended(entry *filer_pb.Entry) (bool, bool) {
|
||||
return false, false // not found
|
||||
}
|
||||
|
||||
// GetVersioningStatus returns the versioning status as a string: "", "Enabled", or "Suspended"
|
||||
// Empty string means versioning was never enabled
|
||||
func GetVersioningStatus(entry *filer_pb.Entry) string {
|
||||
if entry == nil || entry.Extended == nil {
|
||||
return "" // Never enabled
|
||||
}
|
||||
|
||||
if versioningBytes, exists := entry.Extended[s3_constants.ExtVersioningKey]; exists {
|
||||
return string(versioningBytes) // "Enabled" or "Suspended"
|
||||
}
|
||||
|
||||
return "" // Never enabled
|
||||
}
|
||||
|
||||
// CreateObjectLockConfiguration creates a new ObjectLockConfiguration with the specified parameters
|
||||
func CreateObjectLockConfiguration(enabled bool, mode string, days int, years int) *ObjectLockConfiguration {
|
||||
if !enabled {
|
||||
|
||||
@@ -4,3 +4,4 @@ const (
|
||||
// DefaultBucketsPath is the default path for S3 buckets in the filer
|
||||
DefaultBucketsPath = "/buckets"
|
||||
)
|
||||
|
||||
@@ -130,3 +130,4 @@ func TestRemoveDuplicateSlashes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -53,19 +53,16 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
|
||||
|
||||
// collect parameters
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("ListObjectsV2Handler %s", bucket)
|
||||
|
||||
originalPrefix, startAfter, delimiter, continuationToken, encodingTypeUrl, fetchOwner, maxKeys, allowUnordered, errCode := getListObjectsV2Args(r.URL.Query())
|
||||
|
||||
glog.V(2).Infof("ListObjectsV2Handler bucket=%s prefix=%s", bucket, originalPrefix)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
if maxKeys < 0 {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
|
||||
return
|
||||
}
|
||||
// maxKeys is uint16 here; negative values are rejected during parsing.
|
||||
|
||||
// AWS S3 compatibility: allow-unordered cannot be used with delimiter
|
||||
if allowUnordered && delimiter != "" {
|
||||
@@ -121,10 +118,10 @@ func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Requ
|
||||
|
||||
// collect parameters
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("ListObjectsV1Handler %s", bucket)
|
||||
|
||||
originalPrefix, marker, delimiter, encodingTypeUrl, maxKeys, allowUnordered, errCode := getListObjectsV1Args(r.URL.Query())
|
||||
|
||||
glog.V(2).Infof("ListObjectsV1Handler bucket=%s prefix=%s delimiter=%s maxKeys=%d", bucket, originalPrefix, delimiter, maxKeys)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
@@ -206,7 +203,7 @@ func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, m
|
||||
for {
|
||||
empty := true
|
||||
|
||||
nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, cursor, marker, delimiter, false, func(dir string, entry *filer_pb.Entry) {
|
||||
nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, cursor, marker, delimiter, false, bucket, func(dir string, entry *filer_pb.Entry) {
|
||||
empty = false
|
||||
dirName, entryName, _ := entryUrlEncode(dir, entry.Name, encodingTypeUrl)
|
||||
if entry.IsDirectory {
|
||||
@@ -310,6 +307,7 @@ func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, m
|
||||
}
|
||||
}
|
||||
if !delimiterFound {
|
||||
glog.V(4).Infof("Adding file to contents: %s", entryName)
|
||||
contents = append(contents, newListEntry(entry, "", dirName, entryName, bucketPrefix, fetchOwner, false, false, s3a.iam))
|
||||
cursor.maxKeys--
|
||||
lastEntryWasCommonPrefix = false
|
||||
@@ -442,14 +440,13 @@ func toParentAndDescendants(dirAndName string) (dir, name string) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
|
||||
func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, bucket string, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
|
||||
// invariants
|
||||
// prefix and marker should be under dir, marker may contain "/"
|
||||
// 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)
|
||||
if prefix == "/" && delimiter == "/" {
|
||||
return
|
||||
}
|
||||
// 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 cursor.maxKeys <= 0 {
|
||||
return // Don't set isTruncated here - let caller decide based on whether more entries exist
|
||||
}
|
||||
@@ -457,7 +454,7 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
|
||||
if strings.Contains(marker, "/") {
|
||||
subDir, subMarker := toParentAndDescendants(marker)
|
||||
// println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", cursor, subMarker, delimiter, false, eachEntryFn)
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", cursor, subMarker, delimiter, false, bucket, eachEntryFn)
|
||||
if subErr != nil {
|
||||
err = subErr
|
||||
return
|
||||
@@ -490,10 +487,6 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr != nil {
|
||||
@@ -508,7 +501,7 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
|
||||
|
||||
if cursor.maxKeys <= 0 {
|
||||
cursor.isTruncated = true
|
||||
continue
|
||||
break
|
||||
}
|
||||
|
||||
// Set nextMarker only when we have quota to process this entry
|
||||
@@ -528,24 +521,42 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip .versions directories in regular list operations but track them for logical object creation
|
||||
// Store the full entry to avoid additional getEntry calls later
|
||||
// Process .versions directories immediately to create logical versioned object entries
|
||||
// These directories are never traversed (we continue here), so each is only encountered once
|
||||
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
|
||||
glog.V(4).Infof("Found .versions directory: %s", entry.Name)
|
||||
versionsDirs = append(versionsDirs, entry)
|
||||
// Extract object name from .versions directory name
|
||||
baseObjectName := strings.TrimSuffix(entry.Name, s3_constants.VersionsFolder)
|
||||
// Construct full object path relative to bucket
|
||||
bucketFullPath := s3a.option.BucketsPath + "/" + bucket
|
||||
bucketRelativePath := strings.TrimPrefix(dir, bucketFullPath)
|
||||
bucketRelativePath = strings.TrimPrefix(bucketRelativePath, "/")
|
||||
var fullObjectPath string
|
||||
if bucketRelativePath == "" {
|
||||
fullObjectPath = baseObjectName
|
||||
} else {
|
||||
fullObjectPath = bucketRelativePath + "/" + baseObjectName
|
||||
}
|
||||
// Use metadata from the already-fetched .versions directory entry
|
||||
if latestVersionEntry, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, entry); err == nil {
|
||||
eachEntryFn(dir, latestVersionEntry)
|
||||
} else if !errors.Is(err, ErrDeleteMarker) {
|
||||
// Log unexpected errors (delete markers are expected)
|
||||
glog.V(2).Infof("Skipping versioned object %s due to error: %v", fullObjectPath, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
|
||||
// When delimiter is empty (recursive mode), recurse into directories but don't add them to results
|
||||
// Only files and versioned objects should appear in results
|
||||
if cursor.prefixEndsOnDelimiter {
|
||||
cursor.prefixEndsOnDelimiter = false
|
||||
if entry.IsDirectoryKeyObject() {
|
||||
eachEntryFn(dir, entry)
|
||||
}
|
||||
} else {
|
||||
eachEntryFn(dir, entry)
|
||||
}
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, eachEntryFn)
|
||||
// Recurse into subdirectory - don't add the directory itself to results
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, bucket, eachEntryFn)
|
||||
if subErr != nil {
|
||||
err = fmt.Errorf("doListFilerEntries2: %w", subErr)
|
||||
return
|
||||
@@ -568,57 +579,7 @@ 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
|
||||
break
|
||||
}
|
||||
|
||||
// Update nextMarker to ensure pagination advances past this .versions directory
|
||||
// This is critical to prevent infinite loops when results are truncated
|
||||
nextMarker = versionsDir.Name
|
||||
|
||||
// Extract object name from .versions directory name (remove .versions suffix)
|
||||
baseObjectName := strings.TrimSuffix(versionsDir.Name, s3_constants.VersionsFolder)
|
||||
|
||||
// Construct full object path relative to bucket
|
||||
// dir is something like "/buckets/sea-test-1/Veeam/Backup/vbr/Config"
|
||||
// we need to get the path relative to bucket: "Veeam/Backup/vbr/Config/Owner"
|
||||
bucketPath := strings.TrimPrefix(dir, s3a.option.BucketsPath+"/")
|
||||
bucketName := strings.Split(bucketPath, "/")[0]
|
||||
|
||||
// Remove bucket name from path to get directory within bucket
|
||||
bucketRelativePath := strings.Join(strings.Split(bucketPath, "/")[1:], "/")
|
||||
|
||||
var fullObjectPath string
|
||||
if bucketRelativePath == "" {
|
||||
// Object is at bucket root
|
||||
fullObjectPath = baseObjectName
|
||||
} else {
|
||||
// Object is in subdirectory
|
||||
fullObjectPath = bucketRelativePath + "/" + baseObjectName
|
||||
}
|
||||
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// Versioned directories are processed above (lines 524-546)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -720,7 +681,6 @@ func (s3a *S3ApiServer) ensureDirectoryAllEmpty(filerClient filer_pb.SeaweedFile
|
||||
return true, nil
|
||||
}
|
||||
|
||||
|
||||
// compareWithDelimiter compares two strings for sorting, treating the delimiter character
|
||||
// as having lower precedence than other characters to match AWS S3 behavior.
|
||||
// For example, with delimiter '/', 'foo/' should come before 'foo+1/' even though '+' < '/' in ASCII.
|
||||
|
||||
@@ -1,14 +1,63 @@
|
||||
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
|
||||
@@ -53,6 +102,13 @@ func Test_normalizePrefixMarker(t *testing.T) {
|
||||
wantAlignedPrefix string
|
||||
wantAlignedMarker string
|
||||
}{
|
||||
{"bucket root listing with delimiter",
|
||||
args{"/",
|
||||
""},
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
},
|
||||
{"prefix is a directory",
|
||||
args{"/parentDir/data/",
|
||||
""},
|
||||
@@ -146,6 +202,31 @@ 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, "test-bucket", 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
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
grpc "google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// TestListObjectsWithVersionedObjects tests that versioned objects are properly listed
|
||||
// This validates the fix for duplicate versioned objects issue
|
||||
func TestListObjectsWithVersionedObjects(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
|
||||
// Create test filer client with versioned objects
|
||||
filerClient := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test-bucket": {
|
||||
// Regular directory
|
||||
{
|
||||
Name: "folder1",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
},
|
||||
// .versions directory with metadata for versioned object
|
||||
{
|
||||
Name: "file1.txt" + s3_constants.VersionsFolder,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v1-abc123"),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("1234"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(fmt.Sprintf("\"%s\"", hex.EncodeToString([]byte("test-etag-1")))),
|
||||
},
|
||||
},
|
||||
// Another .versions directory
|
||||
{
|
||||
Name: "file2.txt" + s3_constants.VersionsFolder,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v2-def456"),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("5678"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(fmt.Sprintf("\"%s\"", hex.EncodeToString([]byte("test-etag-2")))),
|
||||
},
|
||||
},
|
||||
},
|
||||
"/buckets/test-bucket/folder1": {
|
||||
// Versioned object in subdirectory
|
||||
{
|
||||
Name: "nested.txt" + s3_constants.VersionsFolder,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v3-ghi789"),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("9012"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(fmt.Sprintf("\"%s\"", hex.EncodeToString([]byte("test-etag-3")))),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
bucket string
|
||||
prefix string
|
||||
delimiter string
|
||||
expectedCount int
|
||||
expectedKeys []string
|
||||
expectedPrefixes []string
|
||||
}{
|
||||
{
|
||||
name: "List all objects including versioned (no delimiter)",
|
||||
bucket: "test-bucket",
|
||||
prefix: "",
|
||||
delimiter: "",
|
||||
expectedCount: 3, // file1.txt, file2.txt, folder1/nested.txt
|
||||
expectedKeys: []string{
|
||||
"file1.txt",
|
||||
"file2.txt",
|
||||
"folder1/nested.txt",
|
||||
},
|
||||
expectedPrefixes: []string{},
|
||||
},
|
||||
{
|
||||
name: "List bucket root with delimiter",
|
||||
bucket: "test-bucket",
|
||||
prefix: "",
|
||||
delimiter: "/",
|
||||
expectedCount: 2, // file1.txt, file2.txt (folder1/ becomes common prefix)
|
||||
expectedKeys: []string{
|
||||
"file1.txt",
|
||||
"file2.txt",
|
||||
},
|
||||
expectedPrefixes: []string{
|
||||
"folder1/",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Directly call doListFilerEntries with a callback to exercise the versioned objects
|
||||
// listing logic. The callback mirrors the production listFilerEntries behavior for
|
||||
// path extraction and accumulation so that this test validates the internal listing
|
||||
// implementation in isolation from the HTTP layer.
|
||||
cursor := &ListingCursor{maxKeys: uint16(tt.expectedCount + 10)}
|
||||
contents := []ListEntry{}
|
||||
commonPrefixes := []PrefixEntry{}
|
||||
bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, tt.bucket)
|
||||
|
||||
_, err := s3a.doListFilerEntries(filerClient, bucketPrefix[:len(bucketPrefix)-1], tt.prefix, cursor, "", tt.delimiter, false, tt.bucket, func(dir string, entry *filer_pb.Entry) {
|
||||
if cursor.maxKeys <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if entry.IsDirectory {
|
||||
if tt.delimiter == "/" {
|
||||
// Extract relative path from bucket prefix
|
||||
relDir := strings.TrimPrefix(dir, bucketPrefix[:len(bucketPrefix)-1])
|
||||
if relDir != "" && relDir[0] == '/' {
|
||||
relDir = relDir[1:]
|
||||
}
|
||||
prefix := relDir
|
||||
if prefix != "" {
|
||||
prefix += "/"
|
||||
}
|
||||
prefix += entry.Name + "/"
|
||||
|
||||
commonPrefixes = append(commonPrefixes, PrefixEntry{
|
||||
Prefix: prefix,
|
||||
})
|
||||
cursor.maxKeys--
|
||||
}
|
||||
} else {
|
||||
// Extract key from dir and entry name
|
||||
relDir := strings.TrimPrefix(dir, bucketPrefix[:len(bucketPrefix)-1])
|
||||
if relDir != "" && relDir[0] == '/' {
|
||||
relDir = relDir[1:]
|
||||
}
|
||||
key := entry.Name
|
||||
if relDir != "" {
|
||||
key = relDir + "/" + entry.Name
|
||||
}
|
||||
|
||||
contents = append(contents, ListEntry{
|
||||
Key: key,
|
||||
})
|
||||
cursor.maxKeys--
|
||||
}
|
||||
})
|
||||
|
||||
assert.NoError(t, err, "doListFilerEntries should not return error")
|
||||
assert.Equal(t, tt.expectedCount, len(contents), "Should return correct number of objects")
|
||||
assert.Equal(t, len(tt.expectedPrefixes), len(commonPrefixes), "Should return correct number of common prefixes")
|
||||
|
||||
// Verify keys
|
||||
actualKeys := make([]string, len(contents))
|
||||
for i, entry := range contents {
|
||||
actualKeys[i] = entry.Key
|
||||
}
|
||||
assert.ElementsMatch(t, tt.expectedKeys, actualKeys, "Should return expected keys")
|
||||
|
||||
// Verify common prefixes
|
||||
actualPrefixes := make([]string, len(commonPrefixes))
|
||||
for i, prefix := range commonPrefixes {
|
||||
actualPrefixes[i] = prefix.Prefix
|
||||
}
|
||||
assert.ElementsMatch(t, tt.expectedPrefixes, actualPrefixes, "Should return expected prefixes")
|
||||
|
||||
// Verify each versioned object has correct version metadata
|
||||
for _, entry := range contents {
|
||||
assert.NotEmpty(t, entry.Key, "Versioned object should have key")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestVersionedObjectsNoDuplication ensures that .versions directories are only processed once
|
||||
// This is the core test for the bug fix - previously versioned objects were duplicated 250x
|
||||
func TestVersionedObjectsNoDuplication(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
|
||||
// Create a single .versions directory
|
||||
filerClient := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test-bucket": {
|
||||
{
|
||||
Name: "test.txt" + s3_constants.VersionsFolder,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v1-test"),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("100"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte("\"test-etag\""),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
|
||||
cursor := &ListingCursor{maxKeys: uint16(1000)}
|
||||
contents := []ListEntry{}
|
||||
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
|
||||
if cursor.maxKeys <= 0 {
|
||||
return
|
||||
}
|
||||
contents = append(contents, ListEntry{Key: entry.Name})
|
||||
cursor.maxKeys--
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 1, len(contents), "Should return exactly 1 object (no duplicates)")
|
||||
assert.Equal(t, "test.txt", contents[0].Key, "Should return correct key")
|
||||
}
|
||||
|
||||
// TestVersionedObjectsWithDeleteMarker tests that objects with delete markers are not listed
|
||||
func TestVersionedObjectsWithDeleteMarker(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
|
||||
filerClient := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test-bucket": {
|
||||
// Active versioned object
|
||||
{
|
||||
Name: "active.txt" + s3_constants.VersionsFolder,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v1-active"),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("100"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte("\"etag-active\""),
|
||||
},
|
||||
},
|
||||
// Deleted object (has delete marker)
|
||||
{
|
||||
Name: "deleted.txt" + s3_constants.VersionsFolder,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v1-deleted"),
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker: []byte("true"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
|
||||
cursor := &ListingCursor{maxKeys: uint16(1000)}
|
||||
contents := []ListEntry{}
|
||||
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
|
||||
if cursor.maxKeys <= 0 {
|
||||
return
|
||||
}
|
||||
contents = append(contents, ListEntry{Key: entry.Name})
|
||||
cursor.maxKeys--
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 1, len(contents), "Should only return active object, not deleted")
|
||||
assert.Equal(t, "active.txt", contents[0].Key, "Should return the active object")
|
||||
}
|
||||
|
||||
// TestVersionedObjectsMaxKeys tests pagination with versioned objects
|
||||
func TestVersionedObjectsMaxKeys(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
|
||||
// Create 5 versioned objects
|
||||
entries := make([]*filer_pb.Entry, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
entries[i] = &filer_pb.Entry{
|
||||
Name: fmt.Sprintf("file%d.txt"+s3_constants.VersionsFolder, i),
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(fmt.Sprintf("v%d", i)),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("100"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(fmt.Sprintf("\"etag-%d\"", i)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
filerClient := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test-bucket": entries,
|
||||
},
|
||||
}
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
|
||||
cursor := &ListingCursor{maxKeys: uint16(3)}
|
||||
contents := []ListEntry{}
|
||||
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
|
||||
if cursor.maxKeys <= 0 {
|
||||
return
|
||||
}
|
||||
contents = append(contents, ListEntry{Key: entry.Name})
|
||||
cursor.maxKeys--
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 3, len(contents), "Should respect maxKeys limit")
|
||||
assert.True(t, cursor.isTruncated, "Should set IsTruncated when there are more results")
|
||||
|
||||
// Verify truncation is properly set when maxKeys is exceeded
|
||||
// (The test mock doesn't implement marker-based pagination, but we can verify
|
||||
// that the cursor state is correct for actual pagination to work)
|
||||
assert.True(t, cursor.isTruncated, "IsTruncated should be true when maxKeys is exhausted with more entries available")
|
||||
}
|
||||
|
||||
// TestVersionsDirectoryNotTraversed ensures .versions directories are never traversed
|
||||
func TestVersionsDirectoryNotTraversed(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
traversedDirs := make(map[string]bool)
|
||||
|
||||
// Custom filer client that tracks which directories are accessed
|
||||
customClient := &customTestFilerClient{
|
||||
testFilerClient: testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test-bucket": {
|
||||
{
|
||||
Name: "object.txt" + s3_constants.VersionsFolder,
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v1"),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("100"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte("\"etag\""),
|
||||
},
|
||||
},
|
||||
},
|
||||
// This directory should NEVER be accessed
|
||||
"/buckets/test-bucket/object.txt.versions": {
|
||||
{
|
||||
Name: "should-not-see-this",
|
||||
IsDirectory: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
traversedDirs: &traversedDirs,
|
||||
}
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
},
|
||||
}
|
||||
|
||||
cursor := &ListingCursor{maxKeys: uint16(1000)}
|
||||
contents := []ListEntry{}
|
||||
_, err := s3a.doListFilerEntries(customClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
|
||||
if cursor.maxKeys <= 0 {
|
||||
return
|
||||
}
|
||||
contents = append(contents, ListEntry{Key: entry.Name})
|
||||
cursor.maxKeys--
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 1, len(contents))
|
||||
|
||||
// Verify .versions directory was NEVER traversed
|
||||
_, wasTraversed := traversedDirs["/buckets/test-bucket/object.txt.versions"]
|
||||
assert.False(t, wasTraversed, ".versions directory should never be traversed")
|
||||
}
|
||||
|
||||
// customTestFilerClient tracks which directories are accessed
|
||||
type customTestFilerClient struct {
|
||||
testFilerClient
|
||||
traversedDirs *map[string]bool
|
||||
}
|
||||
|
||||
func (c *customTestFilerClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
|
||||
(*c.traversedDirs)[in.Directory] = true
|
||||
return c.testFilerClient.ListEntries(ctx, in, opts...)
|
||||
}
|
||||
@@ -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(3).Infof("PutObjectHandler %s %s", bucket, object)
|
||||
glog.V(2).Infof("PutObjectHandler bucket=%s object=%s size=%d", bucket, object, r.ContentLength)
|
||||
|
||||
_, err := validateContentMd5(r.Header)
|
||||
if err != nil {
|
||||
|
||||
@@ -201,11 +201,11 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
|
||||
newVolumes, deletedVolumes := ms.Topo.SyncDataNodeRegistration(heartbeat.Volumes, dn)
|
||||
|
||||
for _, v := range newVolumes {
|
||||
glog.V(0).Infof("master see new volume %d from %s", uint32(v.Id), dn.Url())
|
||||
glog.V(1).Infof("master see new volume %d from %s", uint32(v.Id), dn.Url())
|
||||
message.NewVids = append(message.NewVids, uint32(v.Id))
|
||||
}
|
||||
for _, v := range deletedVolumes {
|
||||
glog.V(0).Infof("master see deleted volume %d from %s", uint32(v.Id), dn.Url())
|
||||
glog.V(1).Infof("master see deleted volume %d from %s", uint32(v.Id), dn.Url())
|
||||
message.DeletedVids = append(message.DeletedVids, uint32(v.Id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,3 +90,50 @@ 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
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -209,16 +209,9 @@ func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
|
||||
if ms.Topo.RaftServer.Leader() != "" {
|
||||
glog.V(0).Infof("[%s] %s becomes leader.", ms.Topo.RaftServer.Name(), ms.Topo.RaftServer.Leader())
|
||||
ms.Topo.LastLeaderChangeTime = time.Now()
|
||||
// Sync hashicorp raft leadership to match seaweedfs/raft leader for dual-write
|
||||
raftServer.SyncHashicorpRaftLeadership(ms.Topo.RaftServer.Leader())
|
||||
}
|
||||
})
|
||||
raftServerName = fmt.Sprintf("[%s]", ms.Topo.RaftServer.Name())
|
||||
// Also set HashicorpRaft if available for dual-write migration
|
||||
if raftServer.RaftHashicorp != nil {
|
||||
ms.Topo.HashicorpRaft = raftServer.RaftHashicorp
|
||||
glog.V(0).Infof("Dual-write mode: hashicorp raft enabled alongside seaweedfs/raft")
|
||||
}
|
||||
} else if raftServer.RaftHashicorp != nil {
|
||||
ms.Topo.HashicorpRaft = raftServer.RaftHashicorp
|
||||
raftServerName = ms.Topo.HashicorpRaft.String()
|
||||
|
||||
@@ -2,7 +2,6 @@ package weed_server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
@@ -10,7 +9,6 @@ import (
|
||||
"time"
|
||||
|
||||
transport "github.com/Jille/raft-grpc-transport"
|
||||
boltdb "github.com/hashicorp/raft-boltdb/v2"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
@@ -169,13 +167,6 @@ func NewRaftServer(option *RaftServerOption) (*RaftServer, error) {
|
||||
|
||||
glog.V(0).Infof("current cluster leader: %v", s.raftServer.Leader())
|
||||
|
||||
// Also initialize hashicorp raft in parallel for seamless future migration
|
||||
if err := s.initHashicorpRaftForDualWrite(option); err != nil {
|
||||
glog.Warningf("failed to initialize hashicorp raft for dual-write, migration will require manual steps: %v", err)
|
||||
} else {
|
||||
glog.V(0).Infof("hashicorp raft initialized for dual-write migration")
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -206,111 +197,3 @@ func (s *RaftServer) DoJoinCommand() {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// initHashicorpRaftForDualWrite initializes hashicorp raft alongside seaweedfs/raft
|
||||
// for seamless future migration. State changes are written to both implementations.
|
||||
func (s *RaftServer) initHashicorpRaftForDualWrite(option *RaftServerOption) error {
|
||||
c := hashicorpRaft.DefaultConfig()
|
||||
c.LocalID = hashicorpRaft.ServerID(s.serverAddr)
|
||||
c.HeartbeatTimeout = time.Duration(float64(option.HeartbeatInterval) * (rand.Float64()*0.25 + 1))
|
||||
c.ElectionTimeout = option.ElectionTimeout
|
||||
if c.LeaderLeaseTimeout > c.HeartbeatTimeout {
|
||||
c.LeaderLeaseTimeout = c.HeartbeatTimeout
|
||||
}
|
||||
if glog.V(4) {
|
||||
c.LogLevel = "Debug"
|
||||
} else if glog.V(2) {
|
||||
c.LogLevel = "Info"
|
||||
} else if glog.V(1) {
|
||||
c.LogLevel = "Warn"
|
||||
} else if glog.V(0) {
|
||||
c.LogLevel = "Error"
|
||||
}
|
||||
|
||||
if err := hashicorpRaft.ValidateConfig(c); err != nil {
|
||||
return fmt.Errorf("raft.ValidateConfig: %w", err)
|
||||
}
|
||||
|
||||
// Use a subdirectory to keep hashicorp raft data separate from old raft
|
||||
hashicorpDataDir := path.Join(s.dataDir, "hashicorp")
|
||||
if option.RaftBootstrap {
|
||||
os.RemoveAll(path.Join(hashicorpDataDir, ldbFile))
|
||||
os.RemoveAll(path.Join(hashicorpDataDir, sdbFile))
|
||||
os.RemoveAll(path.Join(hashicorpDataDir, "snapshots"))
|
||||
}
|
||||
if err := os.MkdirAll(path.Join(hashicorpDataDir, "snapshots"), os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ldb, err := boltdb.NewBoltStore(path.Join(hashicorpDataDir, ldbFile))
|
||||
if err != nil {
|
||||
return fmt.Errorf("boltdb.NewBoltStore(%q): %v", path.Join(hashicorpDataDir, ldbFile), err)
|
||||
}
|
||||
|
||||
sdb, err := boltdb.NewBoltStore(path.Join(hashicorpDataDir, sdbFile))
|
||||
if err != nil {
|
||||
return fmt.Errorf("boltdb.NewBoltStore(%q): %v", path.Join(hashicorpDataDir, sdbFile), err)
|
||||
}
|
||||
|
||||
fss, err := hashicorpRaft.NewFileSnapshotStore(hashicorpDataDir, 3, os.Stderr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("raft.NewFileSnapshotStore(%q, ...): %v", hashicorpDataDir, err)
|
||||
}
|
||||
|
||||
s.TransportManager = transport.New(hashicorpRaft.ServerAddress(s.serverAddr), []grpc.DialOption{option.GrpcDialOption})
|
||||
|
||||
stateMachine := StateMachine{topo: option.Topo}
|
||||
s.RaftHashicorp, err = hashicorpRaft.NewRaft(c, &stateMachine, ldb, sdb, fss, s.TransportManager.Transport())
|
||||
if err != nil {
|
||||
return fmt.Errorf("raft.NewRaft: %w", err)
|
||||
}
|
||||
|
||||
if option.RaftBootstrap || len(s.RaftHashicorp.GetConfiguration().Configuration().Servers) == 0 {
|
||||
cfg := s.AddPeersConfiguration()
|
||||
peerIdx := getPeerIdx(s.serverAddr, s.peers)
|
||||
timeSleep := time.Duration(float64(c.LeaderLeaseTimeout) * (rand.Float64()*0.25 + 1) * float64(peerIdx))
|
||||
glog.V(0).Infof("Dual-write: Bootstrapping hashicorp raft idx: %d sleep: %v cluster: %+v", peerIdx, timeSleep, cfg)
|
||||
time.Sleep(timeSleep)
|
||||
f := s.RaftHashicorp.BootstrapCluster(cfg)
|
||||
if err := f.Error(); err != nil {
|
||||
return fmt.Errorf("raft.Raft.BootstrapCluster: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SyncHashicorpRaftLeadership transfers hashicorp raft leadership to match seaweedfs/raft leader.
|
||||
// This ensures both raft systems have the same leader for dual-write to work correctly.
|
||||
func (s *RaftServer) SyncHashicorpRaftLeadership(seaweedfsRaftLeader string) {
|
||||
if s.RaftHashicorp == nil || seaweedfsRaftLeader == "" {
|
||||
return
|
||||
}
|
||||
|
||||
hashicorpLeader, _ := s.RaftHashicorp.LeaderWithID()
|
||||
targetLeader := pb.ServerAddress(seaweedfsRaftLeader)
|
||||
|
||||
// If hashicorp raft already has the same leader, nothing to do
|
||||
if string(hashicorpLeader) == targetLeader.ToGrpcAddress() {
|
||||
glog.V(1).Infof("Dual-write: hashicorp raft leader already matches seaweedfs/raft leader: %s", seaweedfsRaftLeader)
|
||||
return
|
||||
}
|
||||
|
||||
// Only the current hashicorp raft leader can transfer leadership
|
||||
if s.RaftHashicorp.State() != hashicorpRaft.Leader {
|
||||
glog.V(1).Infof("Dual-write: not hashicorp raft leader, cannot transfer leadership to %s", seaweedfsRaftLeader)
|
||||
return
|
||||
}
|
||||
|
||||
// Transfer leadership to the seaweedfs/raft leader
|
||||
glog.V(0).Infof("Dual-write: transferring hashicorp raft leadership to match seaweedfs/raft leader: %s", seaweedfsRaftLeader)
|
||||
future := s.RaftHashicorp.LeadershipTransferToServer(
|
||||
hashicorpRaft.ServerID(targetLeader),
|
||||
hashicorpRaft.ServerAddress(targetLeader.ToGrpcAddress()),
|
||||
)
|
||||
if err := future.Error(); err != nil {
|
||||
glog.Warningf("Dual-write: failed to transfer hashicorp raft leadership to %s: %v", seaweedfsRaftLeader, err)
|
||||
} else {
|
||||
glog.V(0).Infof("Dual-write: hashicorp raft leadership transferred to %s", seaweedfsRaftLeader)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
+170
-26
@@ -679,6 +679,25 @@ 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 {
|
||||
@@ -785,59 +804,176 @@ 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)
|
||||
|
||||
// see the volume's shards are in how many racks, and how many in each rack
|
||||
rackToShardCount := countShardsByRack(vid, locations, ecb.diskType)
|
||||
// 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)
|
||||
|
||||
// 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)
|
||||
})
|
||||
|
||||
// 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 {
|
||||
// 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 {
|
||||
continue
|
||||
}
|
||||
possibleEcNodes := rackEcNodesWithVid[rackId]
|
||||
for shardId, ecNode := range pickNEcShardsToMoveFrom(possibleEcNodes, vid, count-averageShardsPerEcRack, ecb.diskType) {
|
||||
ecShardsToMove[shardId] = ecNode
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for shardId, ecNode := range ecShardsToMove {
|
||||
rackId, err := ecb.pickRackToBalanceShardsInto(racks, rackToShardCount)
|
||||
// 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)
|
||||
if err != nil {
|
||||
fmt.Printf("ec shard %d.%d at %s can not find a destination rack:\n%s\n", vid, shardId, ecNode.info.Id, err.Error())
|
||||
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())
|
||||
continue
|
||||
}
|
||||
|
||||
var possibleDestinationEcNodes []*EcNode
|
||||
for _, n := range racks[rackId].ecNodes {
|
||||
for _, n := range racks[destRackId].ecNodes {
|
||||
possibleDestinationEcNodes = append(possibleDestinationEcNodes, n)
|
||||
}
|
||||
err = ecb.pickOneEcNodeAndMoveOneShard(ecNode, collection, vid, shardId, possibleDestinationEcNodes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rackToShardCount[string(rackId)] += 1
|
||||
rackToShardCount[string(ecNode.rack)] -= 1
|
||||
racks[rackId].freeEcSlot -= 1
|
||||
racks[ecNode.rack].freeEcSlot += 1
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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
|
||||
@@ -855,7 +991,11 @@ func (ecb *ecBalancer) pickRackToBalanceShardsInto(rackToEcNodes map[RackId]*EcR
|
||||
details += fmt.Sprintf(" Skipped %s because it has no free slots\n", rackId)
|
||||
continue
|
||||
}
|
||||
if ecb.replicaPlacement != nil && shards > ecb.replicaPlacement.DiffRackCount {
|
||||
// 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 {
|
||||
details += fmt.Sprintf(" Skipped %s because shards %d > replica placement limit for other racks (%d)\n", rackId, shards, ecb.replicaPlacement.DiffRackCount)
|
||||
continue
|
||||
}
|
||||
@@ -1056,7 +1196,11 @@ func (ecb *ecBalancer) pickEcNodeToBalanceShardsInto(vid needle.VolumeId, existi
|
||||
}
|
||||
|
||||
shards := nodeShards[node]
|
||||
if ecb.replicaPlacement != nil && shards > ecb.replicaPlacement.SameRackCount+1 {
|
||||
// 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 {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -133,7 +133,9 @@ 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.
|
||||
{testTopologyEc, "9577", "", nil, "shards 1 > replica placement limit for other racks (0)"},
|
||||
// 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", "111", []string{"rack1", "rack2", "rack3"}, ""},
|
||||
{testTopologyEc, "9577", "222", []string{"rack1", "rack2", "rack3"}, ""},
|
||||
{testTopologyEc, "10457", "222", []string{"rack1"}, ""},
|
||||
|
||||
@@ -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", false, "re-balance EC shards after creation")
|
||||
applyBalancing := encodeCommand.Bool("rebalance", true, "re-balance EC shards after creation (default: true)")
|
||||
verbose := encodeCommand.Bool("verbose", false, "show detailed reasons why volumes are not selected for encoding")
|
||||
|
||||
if err = encodeCommand.Parse(args); err != nil {
|
||||
@@ -164,6 +164,32 @@ 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 {
|
||||
return fmt.Errorf("ec encode for volumes %v: %w", volumeIds, err)
|
||||
|
||||
@@ -4,6 +4,7 @@ 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"
|
||||
)
|
||||
@@ -136,3 +137,151 @@ 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/distribution"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// ECDistribution is an alias to the distribution package type for backward compatibility
|
||||
type ECDistribution = distribution.ECDistribution
|
||||
|
||||
// CalculateECDistribution computes the target EC shard distribution based on replication policy.
|
||||
// This is a convenience wrapper that uses the default 10+4 EC configuration.
|
||||
// For custom EC ratios, use the distribution package directly.
|
||||
func CalculateECDistribution(totalShards, parityShards int, rp *super_block.ReplicaPlacement) *ECDistribution {
|
||||
ec := distribution.ECConfig{
|
||||
DataShards: totalShards - parityShards,
|
||||
ParityShards: parityShards,
|
||||
}
|
||||
rep := distribution.NewReplicationConfig(rp)
|
||||
return distribution.CalculateDistribution(ec, rep)
|
||||
}
|
||||
|
||||
// TopologyDistributionAnalysis holds the current shard distribution analysis
|
||||
// This wraps the distribution package's TopologyAnalysis with shell-specific EcNode handling
|
||||
type TopologyDistributionAnalysis struct {
|
||||
inner *distribution.TopologyAnalysis
|
||||
|
||||
// Shell-specific mappings
|
||||
nodeMap map[string]*EcNode // nodeID -> EcNode
|
||||
}
|
||||
|
||||
// NewTopologyDistributionAnalysis creates a new analysis structure
|
||||
func NewTopologyDistributionAnalysis() *TopologyDistributionAnalysis {
|
||||
return &TopologyDistributionAnalysis{
|
||||
inner: distribution.NewTopologyAnalysis(),
|
||||
nodeMap: make(map[string]*EcNode),
|
||||
}
|
||||
}
|
||||
|
||||
// AddNode adds a node and its shards to the analysis
|
||||
func (a *TopologyDistributionAnalysis) AddNode(node *EcNode, shardBits erasure_coding.ShardBits) {
|
||||
nodeId := node.info.Id
|
||||
|
||||
// Create distribution.TopologyNode from EcNode
|
||||
topoNode := &distribution.TopologyNode{
|
||||
NodeID: nodeId,
|
||||
DataCenter: string(node.dc),
|
||||
Rack: string(node.rack),
|
||||
FreeSlots: node.freeEcSlot,
|
||||
TotalShards: shardBits.ShardIdCount(),
|
||||
}
|
||||
|
||||
for _, shardId := range shardBits.ShardIds() {
|
||||
topoNode.ShardIDs = append(topoNode.ShardIDs, int(shardId))
|
||||
}
|
||||
|
||||
a.inner.AddNode(topoNode)
|
||||
a.nodeMap[nodeId] = node
|
||||
|
||||
// Add shard locations
|
||||
for _, shardId := range shardBits.ShardIds() {
|
||||
a.inner.AddShardLocation(distribution.ShardLocation{
|
||||
ShardID: int(shardId),
|
||||
NodeID: nodeId,
|
||||
DataCenter: string(node.dc),
|
||||
Rack: string(node.rack),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Finalize completes the analysis
|
||||
func (a *TopologyDistributionAnalysis) Finalize() {
|
||||
a.inner.Finalize()
|
||||
}
|
||||
|
||||
// String returns a summary
|
||||
func (a *TopologyDistributionAnalysis) String() string {
|
||||
return a.inner.String()
|
||||
}
|
||||
|
||||
// DetailedString returns detailed analysis
|
||||
func (a *TopologyDistributionAnalysis) DetailedString() string {
|
||||
return a.inner.DetailedString()
|
||||
}
|
||||
|
||||
// GetShardsByDC returns shard counts by DC
|
||||
func (a *TopologyDistributionAnalysis) GetShardsByDC() map[DataCenterId]int {
|
||||
result := make(map[DataCenterId]int)
|
||||
for dc, count := range a.inner.ShardsByDC {
|
||||
result[DataCenterId(dc)] = count
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetShardsByRack returns shard counts by rack
|
||||
func (a *TopologyDistributionAnalysis) GetShardsByRack() map[RackId]int {
|
||||
result := make(map[RackId]int)
|
||||
for rack, count := range a.inner.ShardsByRack {
|
||||
result[RackId(rack)] = count
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetShardsByNode returns shard counts by node
|
||||
func (a *TopologyDistributionAnalysis) GetShardsByNode() map[EcNodeId]int {
|
||||
result := make(map[EcNodeId]int)
|
||||
for nodeId, count := range a.inner.ShardsByNode {
|
||||
result[EcNodeId(nodeId)] = count
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// AnalyzeVolumeDistribution creates an analysis of current shard distribution for a volume
|
||||
func AnalyzeVolumeDistribution(volumeId needle.VolumeId, locations []*EcNode, diskType types.DiskType) *TopologyDistributionAnalysis {
|
||||
analysis := NewTopologyDistributionAnalysis()
|
||||
|
||||
for _, node := range locations {
|
||||
shardBits := findEcVolumeShards(node, volumeId, diskType)
|
||||
if shardBits.ShardIdCount() > 0 {
|
||||
analysis.AddNode(node, shardBits)
|
||||
}
|
||||
}
|
||||
|
||||
analysis.Finalize()
|
||||
return analysis
|
||||
}
|
||||
|
||||
// ECShardMove represents a planned shard move (shell-specific with EcNode references)
|
||||
type ECShardMove struct {
|
||||
VolumeId needle.VolumeId
|
||||
ShardId erasure_coding.ShardId
|
||||
SourceNode *EcNode
|
||||
DestNode *EcNode
|
||||
Reason string
|
||||
}
|
||||
|
||||
// String returns a human-readable description
|
||||
func (m ECShardMove) String() string {
|
||||
return fmt.Sprintf("volume %d shard %d: %s -> %s (%s)",
|
||||
m.VolumeId, m.ShardId, m.SourceNode.info.Id, m.DestNode.info.Id, m.Reason)
|
||||
}
|
||||
|
||||
// ProportionalECRebalancer implements proportional shard distribution for shell commands
|
||||
type ProportionalECRebalancer struct {
|
||||
ecNodes []*EcNode
|
||||
replicaPlacement *super_block.ReplicaPlacement
|
||||
diskType types.DiskType
|
||||
ecConfig distribution.ECConfig
|
||||
}
|
||||
|
||||
// NewProportionalECRebalancer creates a new proportional rebalancer with default EC config
|
||||
func NewProportionalECRebalancer(
|
||||
ecNodes []*EcNode,
|
||||
rp *super_block.ReplicaPlacement,
|
||||
diskType types.DiskType,
|
||||
) *ProportionalECRebalancer {
|
||||
return NewProportionalECRebalancerWithConfig(
|
||||
ecNodes,
|
||||
rp,
|
||||
diskType,
|
||||
distribution.DefaultECConfig(),
|
||||
)
|
||||
}
|
||||
|
||||
// NewProportionalECRebalancerWithConfig creates a rebalancer with custom EC configuration
|
||||
func NewProportionalECRebalancerWithConfig(
|
||||
ecNodes []*EcNode,
|
||||
rp *super_block.ReplicaPlacement,
|
||||
diskType types.DiskType,
|
||||
ecConfig distribution.ECConfig,
|
||||
) *ProportionalECRebalancer {
|
||||
return &ProportionalECRebalancer{
|
||||
ecNodes: ecNodes,
|
||||
replicaPlacement: rp,
|
||||
diskType: diskType,
|
||||
ecConfig: ecConfig,
|
||||
}
|
||||
}
|
||||
|
||||
// PlanMoves generates a plan for moving shards to achieve proportional distribution
|
||||
func (r *ProportionalECRebalancer) PlanMoves(
|
||||
volumeId needle.VolumeId,
|
||||
locations []*EcNode,
|
||||
) ([]ECShardMove, error) {
|
||||
// Build topology analysis
|
||||
analysis := distribution.NewTopologyAnalysis()
|
||||
nodeMap := make(map[string]*EcNode)
|
||||
|
||||
// Add all EC nodes to the analysis (even those without shards)
|
||||
for _, node := range r.ecNodes {
|
||||
nodeId := node.info.Id
|
||||
topoNode := &distribution.TopologyNode{
|
||||
NodeID: nodeId,
|
||||
DataCenter: string(node.dc),
|
||||
Rack: string(node.rack),
|
||||
FreeSlots: node.freeEcSlot,
|
||||
}
|
||||
analysis.AddNode(topoNode)
|
||||
nodeMap[nodeId] = node
|
||||
}
|
||||
|
||||
// Add shard locations from nodes that have shards
|
||||
for _, node := range locations {
|
||||
nodeId := node.info.Id
|
||||
shardBits := findEcVolumeShards(node, volumeId, r.diskType)
|
||||
for _, shardId := range shardBits.ShardIds() {
|
||||
analysis.AddShardLocation(distribution.ShardLocation{
|
||||
ShardID: int(shardId),
|
||||
NodeID: nodeId,
|
||||
DataCenter: string(node.dc),
|
||||
Rack: string(node.rack),
|
||||
})
|
||||
}
|
||||
if _, exists := nodeMap[nodeId]; !exists {
|
||||
nodeMap[nodeId] = node
|
||||
}
|
||||
}
|
||||
|
||||
analysis.Finalize()
|
||||
|
||||
// Create rebalancer and plan moves
|
||||
rep := distribution.NewReplicationConfig(r.replicaPlacement)
|
||||
rebalancer := distribution.NewRebalancer(r.ecConfig, rep)
|
||||
|
||||
plan, err := rebalancer.PlanRebalance(analysis)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Convert distribution moves to shell moves
|
||||
var moves []ECShardMove
|
||||
for _, move := range plan.Moves {
|
||||
srcNode := nodeMap[move.SourceNode.NodeID]
|
||||
destNode := nodeMap[move.DestNode.NodeID]
|
||||
if srcNode == nil || destNode == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
moves = append(moves, ECShardMove{
|
||||
VolumeId: volumeId,
|
||||
ShardId: erasure_coding.ShardId(move.ShardID),
|
||||
SourceNode: srcNode,
|
||||
DestNode: destNode,
|
||||
Reason: move.Reason,
|
||||
})
|
||||
}
|
||||
|
||||
return moves, nil
|
||||
}
|
||||
|
||||
// GetDistributionSummary returns a summary of the planned distribution
|
||||
func GetDistributionSummary(rp *super_block.ReplicaPlacement) string {
|
||||
ec := distribution.DefaultECConfig()
|
||||
rep := distribution.NewReplicationConfig(rp)
|
||||
dist := distribution.CalculateDistribution(ec, rep)
|
||||
return dist.Summary()
|
||||
}
|
||||
|
||||
// GetDistributionSummaryWithConfig returns a summary with custom EC configuration
|
||||
func GetDistributionSummaryWithConfig(rp *super_block.ReplicaPlacement, ecConfig distribution.ECConfig) string {
|
||||
rep := distribution.NewReplicationConfig(rp)
|
||||
dist := distribution.CalculateDistribution(ecConfig, rep)
|
||||
return dist.Summary()
|
||||
}
|
||||
|
||||
// GetFaultToleranceAnalysis returns fault tolerance analysis for the given configuration
|
||||
func GetFaultToleranceAnalysis(rp *super_block.ReplicaPlacement) string {
|
||||
ec := distribution.DefaultECConfig()
|
||||
rep := distribution.NewReplicationConfig(rp)
|
||||
dist := distribution.CalculateDistribution(ec, rep)
|
||||
return dist.FaultToleranceAnalysis()
|
||||
}
|
||||
|
||||
// GetFaultToleranceAnalysisWithConfig returns fault tolerance analysis with custom EC configuration
|
||||
func GetFaultToleranceAnalysisWithConfig(rp *super_block.ReplicaPlacement, ecConfig distribution.ECConfig) string {
|
||||
rep := distribution.NewReplicationConfig(rp)
|
||||
dist := distribution.CalculateDistribution(ecConfig, rep)
|
||||
return dist.FaultToleranceAnalysis()
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/distribution"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func TestCalculateECDistributionShell(t *testing.T) {
|
||||
// Test the shell wrapper function
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("110")
|
||||
|
||||
dist := CalculateECDistribution(
|
||||
erasure_coding.TotalShardsCount,
|
||||
erasure_coding.ParityShardsCount,
|
||||
rp,
|
||||
)
|
||||
|
||||
if dist.ReplicationConfig.MinDataCenters != 2 {
|
||||
t.Errorf("Expected 2 DCs, got %d", dist.ReplicationConfig.MinDataCenters)
|
||||
}
|
||||
if dist.TargetShardsPerDC != 7 {
|
||||
t.Errorf("Expected 7 shards per DC, got %d", dist.TargetShardsPerDC)
|
||||
}
|
||||
|
||||
t.Log(dist.Summary())
|
||||
}
|
||||
|
||||
func TestAnalyzeVolumeDistributionShell(t *testing.T) {
|
||||
diskType := types.HardDriveType
|
||||
diskTypeKey := string(diskType)
|
||||
|
||||
// Build a topology with unbalanced distribution
|
||||
node1 := &EcNode{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "127.0.0.1:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
|
||||
{
|
||||
Id: 1,
|
||||
Collection: "test",
|
||||
EcIndexBits: 0x3FFF, // All 14 shards
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
dc: "dc1",
|
||||
rack: "rack1",
|
||||
freeEcSlot: 5,
|
||||
}
|
||||
|
||||
node2 := &EcNode{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "127.0.0.1:8081",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{},
|
||||
},
|
||||
},
|
||||
},
|
||||
dc: "dc2",
|
||||
rack: "rack2",
|
||||
freeEcSlot: 10,
|
||||
}
|
||||
|
||||
locations := []*EcNode{node1, node2}
|
||||
volumeId := needle.VolumeId(1)
|
||||
|
||||
analysis := AnalyzeVolumeDistribution(volumeId, locations, diskType)
|
||||
|
||||
shardsByDC := analysis.GetShardsByDC()
|
||||
if shardsByDC["dc1"] != 14 {
|
||||
t.Errorf("Expected 14 shards in dc1, got %d", shardsByDC["dc1"])
|
||||
}
|
||||
|
||||
t.Log(analysis.DetailedString())
|
||||
}
|
||||
|
||||
func TestProportionalRebalancerShell(t *testing.T) {
|
||||
diskType := types.HardDriveType
|
||||
diskTypeKey := string(diskType)
|
||||
|
||||
// Build topology: 2 DCs, 2 racks each, all shards on one node
|
||||
nodes := []*EcNode{
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "dc1-rack1-node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
|
||||
{Id: 1, Collection: "test", EcIndexBits: 0x3FFF},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
dc: "dc1", rack: "dc1-rack1", freeEcSlot: 0,
|
||||
},
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "dc1-rack2-node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {Type: diskTypeKey, MaxVolumeCount: 10},
|
||||
},
|
||||
},
|
||||
dc: "dc1", rack: "dc1-rack2", freeEcSlot: 10,
|
||||
},
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "dc2-rack1-node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {Type: diskTypeKey, MaxVolumeCount: 10},
|
||||
},
|
||||
},
|
||||
dc: "dc2", rack: "dc2-rack1", freeEcSlot: 10,
|
||||
},
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "dc2-rack2-node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {Type: diskTypeKey, MaxVolumeCount: 10},
|
||||
},
|
||||
},
|
||||
dc: "dc2", rack: "dc2-rack2", freeEcSlot: 10,
|
||||
},
|
||||
}
|
||||
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("110")
|
||||
rebalancer := NewProportionalECRebalancer(nodes, rp, diskType)
|
||||
|
||||
volumeId := needle.VolumeId(1)
|
||||
moves, err := rebalancer.PlanMoves(volumeId, []*EcNode{nodes[0]})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("PlanMoves failed: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Planned %d moves", len(moves))
|
||||
for i, move := range moves {
|
||||
t.Logf(" %d. %s", i+1, move.String())
|
||||
}
|
||||
|
||||
// Verify moves to dc2
|
||||
movedToDC2 := 0
|
||||
for _, move := range moves {
|
||||
if move.DestNode.dc == "dc2" {
|
||||
movedToDC2++
|
||||
}
|
||||
}
|
||||
|
||||
if movedToDC2 == 0 {
|
||||
t.Error("Expected some moves to dc2")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomECConfigRebalancer(t *testing.T) {
|
||||
diskType := types.HardDriveType
|
||||
diskTypeKey := string(diskType)
|
||||
|
||||
// Test with custom 8+4 EC configuration
|
||||
ecConfig, err := distribution.NewECConfig(8, 4)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create EC config: %v", err)
|
||||
}
|
||||
|
||||
// Build topology for 12 shards (8+4)
|
||||
nodes := []*EcNode{
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "dc1-node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
|
||||
{Id: 1, Collection: "test", EcIndexBits: 0x0FFF}, // 12 shards (bits 0-11)
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
dc: "dc1", rack: "dc1-rack1", freeEcSlot: 0,
|
||||
},
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "dc2-node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {Type: diskTypeKey, MaxVolumeCount: 10},
|
||||
},
|
||||
},
|
||||
dc: "dc2", rack: "dc2-rack1", freeEcSlot: 10,
|
||||
},
|
||||
{
|
||||
info: &master_pb.DataNodeInfo{
|
||||
Id: "dc3-node1",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {Type: diskTypeKey, MaxVolumeCount: 10},
|
||||
},
|
||||
},
|
||||
dc: "dc3", rack: "dc3-rack1", freeEcSlot: 10,
|
||||
},
|
||||
}
|
||||
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("200") // 3 DCs
|
||||
rebalancer := NewProportionalECRebalancerWithConfig(nodes, rp, diskType, ecConfig)
|
||||
|
||||
volumeId := needle.VolumeId(1)
|
||||
moves, err := rebalancer.PlanMoves(volumeId, []*EcNode{nodes[0]})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("PlanMoves failed: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Custom 8+4 EC with 200 replication: planned %d moves", len(moves))
|
||||
|
||||
// Get the distribution summary
|
||||
summary := GetDistributionSummaryWithConfig(rp, ecConfig)
|
||||
t.Log(summary)
|
||||
|
||||
analysis := GetFaultToleranceAnalysisWithConfig(rp, ecConfig)
|
||||
t.Log(analysis)
|
||||
}
|
||||
|
||||
func TestGetDistributionSummaryShell(t *testing.T) {
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("110")
|
||||
|
||||
summary := GetDistributionSummary(rp)
|
||||
t.Log(summary)
|
||||
|
||||
if len(summary) == 0 {
|
||||
t.Error("Summary should not be empty")
|
||||
}
|
||||
|
||||
analysis := GetFaultToleranceAnalysis(rp)
|
||||
t.Log(analysis)
|
||||
|
||||
if len(analysis) == 0 {
|
||||
t.Error("Analysis should not be empty")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// TestECRebalanceWithLimitedSlots tests that EC rebalance handles the scenario
|
||||
// where there are limited free slots on volume servers.
|
||||
//
|
||||
// This is a regression test for the error:
|
||||
//
|
||||
// "no free ec shard slots. only 0 left"
|
||||
//
|
||||
// Scenario (from real usage):
|
||||
// - 6 volume servers in 6 racks
|
||||
// - Each server has max=10 volume slots
|
||||
// - 7 volumes were EC encoded (7 × 14 = 98 EC shards)
|
||||
// - All 14 shards per volume are on the original server (not yet distributed)
|
||||
//
|
||||
// Expected behavior:
|
||||
// - The rebalance algorithm should distribute shards across servers
|
||||
// - Even if perfect distribution isn't possible, it should do best-effort
|
||||
// - Currently fails with "no free ec shard slots" because freeSlots calculation
|
||||
//
|
||||
// doesn't account for shards being moved (freed slots on source, used on target)
|
||||
func TestECRebalanceWithLimitedSlots(t *testing.T) {
|
||||
// Build a topology matching the problematic scenario:
|
||||
// 6 servers, each with 2+ volumes worth of EC shards (all 14 shards per volume on same server)
|
||||
topology := buildLimitedSlotsTopology()
|
||||
|
||||
// Collect EC nodes from the topology
|
||||
ecNodes, totalFreeEcSlots := collectEcVolumeServersByDc(topology, "", types.HardDriveType)
|
||||
|
||||
t.Logf("Topology summary:")
|
||||
t.Logf(" Number of EC nodes: %d", len(ecNodes))
|
||||
t.Logf(" Total free EC slots: %d", totalFreeEcSlots)
|
||||
|
||||
// Log per-node details
|
||||
for _, node := range ecNodes {
|
||||
shardCount := 0
|
||||
for _, diskInfo := range node.info.DiskInfos {
|
||||
for _, ecShard := range diskInfo.EcShardInfos {
|
||||
shardCount += erasure_coding.ShardBits(ecShard.EcIndexBits).ShardIdCount()
|
||||
}
|
||||
}
|
||||
t.Logf(" Node %s (rack %s): %d shards, %d free slots",
|
||||
node.info.Id, node.rack, shardCount, node.freeEcSlot)
|
||||
}
|
||||
|
||||
// Calculate total EC shards
|
||||
totalEcShards := 0
|
||||
for _, node := range ecNodes {
|
||||
for _, diskInfo := range node.info.DiskInfos {
|
||||
for _, ecShard := range diskInfo.EcShardInfos {
|
||||
totalEcShards += erasure_coding.ShardBits(ecShard.EcIndexBits).ShardIdCount()
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Logf(" Total EC shards: %d", totalEcShards)
|
||||
|
||||
// Document the issue:
|
||||
// With 98 EC shards (7 volumes × 14 shards) on 6 servers with max=10 each,
|
||||
// total capacity is 60 slots. But shards already occupy slots on their current servers.
|
||||
//
|
||||
// The current algorithm calculates free slots as:
|
||||
// freeSlots = maxVolumeCount - volumeCount - ecShardCount
|
||||
//
|
||||
// If all shards are on their original servers:
|
||||
// - Server A has 28 shards (2 volumes × 14) → may have negative free slots
|
||||
// - This causes totalFreeEcSlots to be 0 or negative
|
||||
//
|
||||
// The EXPECTED improvement:
|
||||
// - Rebalance should recognize that moving a shard FREES a slot on the source
|
||||
// - The algorithm should work iteratively, moving shards one at a time
|
||||
// - Even if starting with 0 free slots, moving one shard opens a slot
|
||||
|
||||
if totalFreeEcSlots < 1 {
|
||||
// This is the current (buggy) behavior we're documenting
|
||||
t.Logf("")
|
||||
t.Logf("KNOWN ISSUE: totalFreeEcSlots = %d (< 1)", totalFreeEcSlots)
|
||||
t.Logf("")
|
||||
t.Logf("This triggers the error: 'no free ec shard slots. only %d left'", totalFreeEcSlots)
|
||||
t.Logf("")
|
||||
t.Logf("Analysis:")
|
||||
t.Logf(" - %d EC shards across %d servers", totalEcShards, len(ecNodes))
|
||||
t.Logf(" - Shards are concentrated on original servers (not distributed)")
|
||||
t.Logf(" - Current slot calculation doesn't account for slots freed by moving shards")
|
||||
t.Logf("")
|
||||
t.Logf("Expected fix:")
|
||||
t.Logf(" 1. Rebalance should work iteratively, moving one shard at a time")
|
||||
t.Logf(" 2. Moving a shard from A to B: frees 1 slot on A, uses 1 slot on B")
|
||||
t.Logf(" 3. The 'free slots' check should be per-move, not global")
|
||||
t.Logf(" 4. Or: calculate 'redistributable slots' = total capacity - shards that must stay")
|
||||
|
||||
// For now, document this is a known issue - don't fail the test
|
||||
// When the fix is implemented, this test should be updated to verify the fix works
|
||||
return
|
||||
}
|
||||
|
||||
// If we get here, the issue might have been fixed
|
||||
t.Logf("totalFreeEcSlots = %d, rebalance should be possible", totalFreeEcSlots)
|
||||
}
|
||||
|
||||
// TestECRebalanceZeroFreeSlots tests the specific scenario where
|
||||
// the topology appears to have free slots but rebalance fails.
|
||||
//
|
||||
// This can happen when the VolumeCount in the topology includes the original
|
||||
// volumes that were EC-encoded, making the free slot calculation incorrect.
|
||||
func TestECRebalanceZeroFreeSlots(t *testing.T) {
|
||||
// Build a topology where volumes were NOT deleted after EC encoding
|
||||
// (VolumeCount still reflects the original volumes)
|
||||
topology := buildZeroFreeSlotTopology()
|
||||
|
||||
ecNodes, totalFreeEcSlots := collectEcVolumeServersByDc(topology, "", types.HardDriveType)
|
||||
|
||||
t.Logf("Zero free slots scenario:")
|
||||
for _, node := range ecNodes {
|
||||
shardCount := 0
|
||||
for _, diskInfo := range node.info.DiskInfos {
|
||||
for _, ecShard := range diskInfo.EcShardInfos {
|
||||
shardCount += erasure_coding.ShardBits(ecShard.EcIndexBits).ShardIdCount()
|
||||
}
|
||||
}
|
||||
t.Logf(" Node %s: %d shards, %d free slots, volumeCount=%d, max=%d",
|
||||
node.info.Id, shardCount, node.freeEcSlot,
|
||||
node.info.DiskInfos[string(types.HardDriveType)].VolumeCount,
|
||||
node.info.DiskInfos[string(types.HardDriveType)].MaxVolumeCount)
|
||||
}
|
||||
t.Logf(" Total free slots: %d", totalFreeEcSlots)
|
||||
|
||||
if totalFreeEcSlots == 0 {
|
||||
t.Logf("")
|
||||
t.Logf("SCENARIO REPRODUCED: totalFreeEcSlots = 0")
|
||||
t.Logf("This would trigger: 'no free ec shard slots. only 0 left'")
|
||||
}
|
||||
}
|
||||
|
||||
// buildZeroFreeSlotTopology creates a topology where rebalance will fail
|
||||
// because servers are at capacity (volumeCount equals maxVolumeCount)
|
||||
func buildZeroFreeSlotTopology() *master_pb.TopologyInfo {
|
||||
diskTypeKey := string(types.HardDriveType)
|
||||
|
||||
// Each server has max=10, volumeCount=10 (full capacity)
|
||||
// Free capacity = (10-10) * 10 = 0 per server
|
||||
// This will trigger "no free ec shard slots" error
|
||||
return &master_pb.TopologyInfo{
|
||||
Id: "test_zero_free_slots",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
{
|
||||
Id: "rack0",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{
|
||||
Id: "127.0.0.1:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
VolumeCount: 10, // At full capacity
|
||||
EcShardInfos: buildEcShards([]uint32{3, 4}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{
|
||||
Id: "127.0.0.1:8081",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
VolumeCount: 10,
|
||||
EcShardInfos: buildEcShards([]uint32{1, 7}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: "rack2",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{
|
||||
Id: "127.0.0.1:8082",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
VolumeCount: 10,
|
||||
EcShardInfos: buildEcShards([]uint32{2}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: "rack3",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{
|
||||
Id: "127.0.0.1:8083",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: 10,
|
||||
VolumeCount: 10,
|
||||
EcShardInfos: buildEcShards([]uint32{5, 6}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func buildEcShards(volumeIds []uint32) []*master_pb.VolumeEcShardInformationMessage {
|
||||
var shards []*master_pb.VolumeEcShardInformationMessage
|
||||
for _, vid := range volumeIds {
|
||||
allShardBits := erasure_coding.ShardBits(0)
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
allShardBits = allShardBits.AddShardId(erasure_coding.ShardId(i))
|
||||
}
|
||||
shards = append(shards, &master_pb.VolumeEcShardInformationMessage{
|
||||
Id: vid,
|
||||
Collection: "ectest",
|
||||
EcIndexBits: uint32(allShardBits),
|
||||
})
|
||||
}
|
||||
return shards
|
||||
}
|
||||
|
||||
// buildLimitedSlotsTopology creates a topology matching the problematic scenario:
|
||||
// - 6 servers in 6 racks
|
||||
// - Each server has max=10 volume slots
|
||||
// - 7 volumes were EC encoded, shards distributed as follows:
|
||||
// - rack0 (8080): volumes 3,4 → 28 shards
|
||||
// - rack1 (8081): volumes 1,7 → 28 shards
|
||||
// - rack2 (8082): volume 2 → 14 shards
|
||||
// - rack3 (8083): volumes 5,6 → 28 shards
|
||||
// - rack4 (8084): (no volumes originally)
|
||||
// - rack5 (8085): (no volumes originally)
|
||||
func buildLimitedSlotsTopology() *master_pb.TopologyInfo {
|
||||
return &master_pb.TopologyInfo{
|
||||
Id: "test_limited_slots",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{
|
||||
buildRackWithEcShards("rack0", "127.0.0.1:8080", 10, []uint32{3, 4}),
|
||||
buildRackWithEcShards("rack1", "127.0.0.1:8081", 10, []uint32{1, 7}),
|
||||
buildRackWithEcShards("rack2", "127.0.0.1:8082", 10, []uint32{2}),
|
||||
buildRackWithEcShards("rack3", "127.0.0.1:8083", 10, []uint32{5, 6}),
|
||||
buildRackWithEcShards("rack4", "127.0.0.1:8084", 10, []uint32{}),
|
||||
buildRackWithEcShards("rack5", "127.0.0.1:8085", 10, []uint32{}),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// buildRackWithEcShards creates a rack with one data node containing EC shards
|
||||
// for the specified volume IDs (all 14 shards per volume)
|
||||
func buildRackWithEcShards(rackId, nodeId string, maxVolumes int64, volumeIds []uint32) *master_pb.RackInfo {
|
||||
// Note: types.HardDriveType is "" (empty string), so we use "" as the key
|
||||
diskTypeKey := string(types.HardDriveType)
|
||||
|
||||
return &master_pb.RackInfo{
|
||||
Id: rackId,
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{
|
||||
Id: nodeId,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
diskTypeKey: {
|
||||
Type: diskTypeKey,
|
||||
MaxVolumeCount: maxVolumes,
|
||||
VolumeCount: int64(len(volumeIds)), // Original volumes still counted
|
||||
EcShardInfos: buildEcShards(volumeIds),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,7 @@ func (l *DiskLocation) loadExistingVolume(dirEntry os.DirEntry, needleMapKind Ne
|
||||
l.SetVolume(vid, v)
|
||||
|
||||
size, _, _ := v.FileStat()
|
||||
glog.V(0).Infof("data file %s, replication=%s v=%d size=%d ttl=%s disk_id=%d",
|
||||
glog.V(2).Infof("data file %s, replication=%s v=%d size=%d ttl=%s disk_id=%d",
|
||||
l.Directory+"/"+volumeName+".dat", v.ReplicaPlacement, v.Version(), size, v.Ttl.String(), diskId)
|
||||
return true
|
||||
}
|
||||
@@ -257,10 +257,10 @@ func (l *DiskLocation) loadExistingVolumesWithId(needleMapKind NeedleMapKind, ld
|
||||
}
|
||||
}
|
||||
l.concurrentLoadingVolumes(needleMapKind, workerNum, ldbTimeout, diskId)
|
||||
glog.V(0).Infof("Store started on dir: %s with %d volumes max %d (disk ID: %d)", l.Directory, len(l.volumes), l.MaxVolumeCount, diskId)
|
||||
glog.V(2).Infof("Store started on dir: %s with %d volumes max %d (disk ID: %d)", l.Directory, len(l.volumes), l.MaxVolumeCount, diskId)
|
||||
|
||||
l.loadAllEcShards()
|
||||
glog.V(0).Infof("Store started on dir: %s with %d ec shards (disk ID: %d)", l.Directory, len(l.ecVolumes), diskId)
|
||||
glog.V(2).Infof("Store started on dir: %s with %d ec shards (disk ID: %d)", l.Directory, len(l.ecVolumes), diskId)
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# EC Distribution Package
|
||||
|
||||
This package provides erasure coding (EC) shard distribution algorithms that are:
|
||||
|
||||
- **Configurable**: Works with any EC ratio (e.g., 10+4, 8+4, 6+3)
|
||||
- **Reusable**: Used by shell commands, worker tasks, and seaweed-enterprise
|
||||
- **Topology-aware**: Distributes shards across data centers, racks, and nodes proportionally
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Usage with Default 10+4 EC
|
||||
|
||||
```go
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/distribution"
|
||||
)
|
||||
|
||||
// Parse replication policy
|
||||
rep, _ := distribution.NewReplicationConfigFromString("110")
|
||||
|
||||
// Use default 10+4 EC configuration
|
||||
ec := distribution.DefaultECConfig()
|
||||
|
||||
// Calculate distribution plan
|
||||
dist := distribution.CalculateDistribution(ec, rep)
|
||||
|
||||
fmt.Println(dist.Summary())
|
||||
// Output:
|
||||
// EC Configuration: 10+4 (total: 14, can lose: 4)
|
||||
// Replication: replication=110 (DCs:2, Racks/DC:2, Nodes/Rack:1)
|
||||
// Distribution Plan:
|
||||
// Data Centers: 2 (target 7 shards each, max 9)
|
||||
// Racks per DC: 2 (target 4 shards each, max 6)
|
||||
// Nodes per Rack: 1 (target 4 shards each, max 6)
|
||||
```
|
||||
|
||||
### Custom EC Ratios (seaweed-enterprise)
|
||||
|
||||
```go
|
||||
// Create custom 8+4 EC configuration
|
||||
ec, err := distribution.NewECConfig(8, 4)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
rep, _ := distribution.NewReplicationConfigFromString("200")
|
||||
dist := distribution.CalculateDistribution(ec, rep)
|
||||
|
||||
// Check fault tolerance
|
||||
fmt.Println(dist.FaultToleranceAnalysis())
|
||||
// Output:
|
||||
// Fault Tolerance Analysis for 8+4:
|
||||
// DC Failure: SURVIVABLE ✓
|
||||
// - Losing one DC loses ~4 shards
|
||||
// - Remaining: 8 shards (need 8)
|
||||
```
|
||||
|
||||
### Planning Shard Moves
|
||||
|
||||
```go
|
||||
// Build topology analysis
|
||||
analysis := distribution.NewTopologyAnalysis()
|
||||
|
||||
// Add nodes and their shard locations
|
||||
for _, node := range nodes {
|
||||
analysis.AddNode(&distribution.TopologyNode{
|
||||
NodeID: node.ID,
|
||||
DataCenter: node.DC,
|
||||
Rack: node.Rack,
|
||||
FreeSlots: node.FreeSlots,
|
||||
})
|
||||
for _, shardID := range node.ShardIDs {
|
||||
analysis.AddShardLocation(distribution.ShardLocation{
|
||||
ShardID: shardID,
|
||||
NodeID: node.ID,
|
||||
DataCenter: node.DC,
|
||||
Rack: node.Rack,
|
||||
})
|
||||
}
|
||||
}
|
||||
analysis.Finalize()
|
||||
|
||||
// Create rebalancer and plan moves
|
||||
rebalancer := distribution.NewRebalancer(ec, rep)
|
||||
plan, err := rebalancer.PlanRebalance(analysis)
|
||||
|
||||
for _, move := range plan.Moves {
|
||||
fmt.Printf("Move shard %d from %s to %s\n",
|
||||
move.ShardID, move.SourceNode.NodeID, move.DestNode.NodeID)
|
||||
}
|
||||
```
|
||||
|
||||
## Algorithm
|
||||
|
||||
### Proportional Distribution
|
||||
|
||||
The replication policy `XYZ` is interpreted as a ratio:
|
||||
|
||||
| Replication | DCs | Racks/DC | Nodes/Rack | 14 Shards Distribution |
|
||||
|-------------|-----|----------|------------|------------------------|
|
||||
| `000` | 1 | 1 | 1 | All in one place |
|
||||
| `001` | 1 | 1 | 2 | 7 per node |
|
||||
| `010` | 1 | 2 | 1 | 7 per rack |
|
||||
| `100` | 2 | 1 | 1 | 7 per DC |
|
||||
| `110` | 2 | 2 | 1 | 7/DC, 4/rack |
|
||||
| `200` | 3 | 1 | 1 | 5 per DC |
|
||||
|
||||
### Rebalancing Process
|
||||
|
||||
1. **DC-level balancing**: Move shards to achieve target shards per DC
|
||||
2. **Rack-level balancing**: Within each DC, balance across racks
|
||||
3. **Node-level balancing**: Within each rack, balance across nodes
|
||||
|
||||
### Shard Priority: Data First, Parity Moves First
|
||||
|
||||
When rebalancing, the algorithm prioritizes keeping data shards spread out:
|
||||
|
||||
- **Data shards (0 to DataShards-1)**: Serve read requests directly
|
||||
- **Parity shards (DataShards to TotalShards-1)**: Only used for reconstruction
|
||||
|
||||
**Rebalancing Strategy**:
|
||||
- When moving shards FROM an overloaded node, **parity shards are moved first**
|
||||
- This keeps data shards in place on well-distributed nodes
|
||||
- Result: Data shards remain spread out for optimal read performance
|
||||
|
||||
```go
|
||||
// Check shard type
|
||||
if ec.IsDataShard(shardID) {
|
||||
// Shard serves read requests
|
||||
}
|
||||
if ec.IsParityShard(shardID) {
|
||||
// Shard only used for reconstruction
|
||||
}
|
||||
|
||||
// Sort shards for placement (data first for initial distribution)
|
||||
sorted := ec.SortShardsDataFirst(shards)
|
||||
|
||||
// Sort shards for rebalancing (parity first to move them away)
|
||||
sorted := ec.SortShardsParityFirst(shards)
|
||||
```
|
||||
|
||||
### Fault Tolerance
|
||||
|
||||
The package provides fault tolerance analysis:
|
||||
|
||||
- **DC Failure**: Can the data survive complete DC loss?
|
||||
- **Rack Failure**: Can the data survive complete rack loss?
|
||||
- **Node Failure**: Can the data survive single node loss?
|
||||
|
||||
For example, with 10+4 EC (can lose 4 shards):
|
||||
- Need 4+ DCs for DC-level fault tolerance
|
||||
- Need 4+ racks for rack-level fault tolerance
|
||||
- Usually survivable at node level
|
||||
|
||||
## API Reference
|
||||
|
||||
### Types
|
||||
|
||||
- `ECConfig`: EC configuration (data shards, parity shards)
|
||||
- `ReplicationConfig`: Parsed replication policy
|
||||
- `ECDistribution`: Calculated distribution plan
|
||||
- `TopologyAnalysis`: Current shard distribution analysis
|
||||
- `Rebalancer`: Plans shard moves
|
||||
- `RebalancePlan`: List of planned moves
|
||||
- `ShardMove`: Single shard move operation
|
||||
|
||||
### Key Functions
|
||||
|
||||
- `NewECConfig(data, parity int)`: Create EC configuration
|
||||
- `DefaultECConfig()`: Returns 10+4 configuration
|
||||
- `CalculateDistribution(ec, rep)`: Calculate distribution plan
|
||||
- `NewRebalancer(ec, rep)`: Create rebalancer
|
||||
- `PlanRebalance(analysis)`: Generate rebalancing plan
|
||||
|
||||
## Integration
|
||||
|
||||
### Shell Commands
|
||||
|
||||
The shell package wraps this distribution package for `ec.balance`:
|
||||
|
||||
```go
|
||||
import "github.com/seaweedfs/seaweedfs/weed/shell"
|
||||
|
||||
rebalancer := shell.NewProportionalECRebalancer(nodes, rp, diskType)
|
||||
moves, _ := rebalancer.PlanMoves(volumeId, locations)
|
||||
```
|
||||
|
||||
### Worker Tasks
|
||||
|
||||
Worker tasks can use the distribution package directly:
|
||||
|
||||
```go
|
||||
import "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/distribution"
|
||||
|
||||
ec := distribution.ECConfig{DataShards: 8, ParityShards: 4}
|
||||
rep := distribution.NewReplicationConfig(rp)
|
||||
dist := distribution.CalculateDistribution(ec, rep)
|
||||
```
|
||||
|
||||
### seaweed-enterprise
|
||||
|
||||
Enterprise features can provide custom EC configurations:
|
||||
|
||||
```go
|
||||
// Custom EC ratio from license/config
|
||||
ec, _ := distribution.NewECConfig(customData, customParity)
|
||||
rebalancer := distribution.NewRebalancer(ec, rep)
|
||||
```
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// ShardLocation represents where a shard is located in the topology
|
||||
type ShardLocation struct {
|
||||
ShardID int
|
||||
NodeID string
|
||||
DataCenter string
|
||||
Rack string
|
||||
}
|
||||
|
||||
// TopologyNode represents a node in the topology that can hold EC shards
|
||||
type TopologyNode struct {
|
||||
NodeID string
|
||||
DataCenter string
|
||||
Rack string
|
||||
FreeSlots int // Available slots for new shards
|
||||
ShardIDs []int // Shard IDs currently on this node for a specific volume
|
||||
TotalShards int // Total shards on this node (for all volumes)
|
||||
}
|
||||
|
||||
// TopologyAnalysis holds the current shard distribution analysis for a volume
|
||||
type TopologyAnalysis struct {
|
||||
// Shard counts at each level
|
||||
ShardsByDC map[string]int
|
||||
ShardsByRack map[string]int
|
||||
ShardsByNode map[string]int
|
||||
|
||||
// Detailed shard locations
|
||||
DCToShards map[string][]int // DC -> list of shard IDs
|
||||
RackToShards map[string][]int // Rack -> list of shard IDs
|
||||
NodeToShards map[string][]int // NodeID -> list of shard IDs
|
||||
|
||||
// Topology structure
|
||||
DCToRacks map[string][]string // DC -> list of rack IDs
|
||||
RackToNodes map[string][]*TopologyNode // Rack -> list of nodes
|
||||
AllNodes map[string]*TopologyNode // NodeID -> node info
|
||||
|
||||
// Statistics
|
||||
TotalShards int
|
||||
TotalNodes int
|
||||
TotalRacks int
|
||||
TotalDCs int
|
||||
}
|
||||
|
||||
// NewTopologyAnalysis creates a new empty analysis
|
||||
func NewTopologyAnalysis() *TopologyAnalysis {
|
||||
return &TopologyAnalysis{
|
||||
ShardsByDC: make(map[string]int),
|
||||
ShardsByRack: make(map[string]int),
|
||||
ShardsByNode: make(map[string]int),
|
||||
DCToShards: make(map[string][]int),
|
||||
RackToShards: make(map[string][]int),
|
||||
NodeToShards: make(map[string][]int),
|
||||
DCToRacks: make(map[string][]string),
|
||||
RackToNodes: make(map[string][]*TopologyNode),
|
||||
AllNodes: make(map[string]*TopologyNode),
|
||||
}
|
||||
}
|
||||
|
||||
// AddShardLocation adds a shard location to the analysis
|
||||
func (a *TopologyAnalysis) AddShardLocation(loc ShardLocation) {
|
||||
// Update counts
|
||||
a.ShardsByDC[loc.DataCenter]++
|
||||
a.ShardsByRack[loc.Rack]++
|
||||
a.ShardsByNode[loc.NodeID]++
|
||||
|
||||
// Update shard lists
|
||||
a.DCToShards[loc.DataCenter] = append(a.DCToShards[loc.DataCenter], loc.ShardID)
|
||||
a.RackToShards[loc.Rack] = append(a.RackToShards[loc.Rack], loc.ShardID)
|
||||
a.NodeToShards[loc.NodeID] = append(a.NodeToShards[loc.NodeID], loc.ShardID)
|
||||
|
||||
a.TotalShards++
|
||||
}
|
||||
|
||||
// AddNode adds a node to the topology (even if it has no shards)
|
||||
func (a *TopologyAnalysis) AddNode(node *TopologyNode) {
|
||||
if _, exists := a.AllNodes[node.NodeID]; exists {
|
||||
return // Already added
|
||||
}
|
||||
|
||||
a.AllNodes[node.NodeID] = node
|
||||
a.TotalNodes++
|
||||
|
||||
// Update topology structure
|
||||
if !slices.Contains(a.DCToRacks[node.DataCenter], node.Rack) {
|
||||
a.DCToRacks[node.DataCenter] = append(a.DCToRacks[node.DataCenter], node.Rack)
|
||||
}
|
||||
a.RackToNodes[node.Rack] = append(a.RackToNodes[node.Rack], node)
|
||||
|
||||
// Update counts
|
||||
if _, exists := a.ShardsByDC[node.DataCenter]; !exists {
|
||||
a.TotalDCs++
|
||||
}
|
||||
if _, exists := a.ShardsByRack[node.Rack]; !exists {
|
||||
a.TotalRacks++
|
||||
}
|
||||
}
|
||||
|
||||
// Finalize computes final statistics after all data is added
|
||||
func (a *TopologyAnalysis) Finalize() {
|
||||
// Ensure we have accurate DC and rack counts
|
||||
dcSet := make(map[string]bool)
|
||||
rackSet := make(map[string]bool)
|
||||
for _, node := range a.AllNodes {
|
||||
dcSet[node.DataCenter] = true
|
||||
rackSet[node.Rack] = true
|
||||
}
|
||||
a.TotalDCs = len(dcSet)
|
||||
a.TotalRacks = len(rackSet)
|
||||
a.TotalNodes = len(a.AllNodes)
|
||||
}
|
||||
|
||||
// String returns a summary of the analysis
|
||||
func (a *TopologyAnalysis) String() string {
|
||||
return fmt.Sprintf("TopologyAnalysis{shards:%d, nodes:%d, racks:%d, dcs:%d}",
|
||||
a.TotalShards, a.TotalNodes, a.TotalRacks, a.TotalDCs)
|
||||
}
|
||||
|
||||
// DetailedString returns a detailed multi-line summary
|
||||
func (a *TopologyAnalysis) DetailedString() string {
|
||||
s := fmt.Sprintf("Topology Analysis:\n")
|
||||
s += fmt.Sprintf(" Total Shards: %d\n", a.TotalShards)
|
||||
s += fmt.Sprintf(" Data Centers: %d\n", a.TotalDCs)
|
||||
for dc, count := range a.ShardsByDC {
|
||||
s += fmt.Sprintf(" %s: %d shards\n", dc, count)
|
||||
}
|
||||
s += fmt.Sprintf(" Racks: %d\n", a.TotalRacks)
|
||||
for rack, count := range a.ShardsByRack {
|
||||
s += fmt.Sprintf(" %s: %d shards\n", rack, count)
|
||||
}
|
||||
s += fmt.Sprintf(" Nodes: %d\n", a.TotalNodes)
|
||||
for nodeID, count := range a.ShardsByNode {
|
||||
if count > 0 {
|
||||
s += fmt.Sprintf(" %s: %d shards\n", nodeID, count)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// TopologyExcess represents a topology level (DC/rack/node) with excess shards
|
||||
type TopologyExcess struct {
|
||||
ID string // DC/rack/node ID
|
||||
Level string // "dc", "rack", or "node"
|
||||
Excess int // Number of excess shards (above target)
|
||||
Shards []int // Shard IDs at this level
|
||||
Nodes []*TopologyNode // Nodes at this level (for finding sources)
|
||||
}
|
||||
|
||||
// CalculateDCExcess returns DCs with more shards than the target
|
||||
func CalculateDCExcess(analysis *TopologyAnalysis, dist *ECDistribution) []TopologyExcess {
|
||||
var excess []TopologyExcess
|
||||
|
||||
for dc, count := range analysis.ShardsByDC {
|
||||
if count > dist.TargetShardsPerDC {
|
||||
// Collect nodes in this DC
|
||||
var nodes []*TopologyNode
|
||||
for _, rack := range analysis.DCToRacks[dc] {
|
||||
nodes = append(nodes, analysis.RackToNodes[rack]...)
|
||||
}
|
||||
excess = append(excess, TopologyExcess{
|
||||
ID: dc,
|
||||
Level: "dc",
|
||||
Excess: count - dist.TargetShardsPerDC,
|
||||
Shards: analysis.DCToShards[dc],
|
||||
Nodes: nodes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by excess (most excess first)
|
||||
slices.SortFunc(excess, func(a, b TopologyExcess) int {
|
||||
return b.Excess - a.Excess
|
||||
})
|
||||
|
||||
return excess
|
||||
}
|
||||
|
||||
// CalculateRackExcess returns racks with more shards than the target (within a DC)
|
||||
func CalculateRackExcess(analysis *TopologyAnalysis, dc string, targetPerRack int) []TopologyExcess {
|
||||
var excess []TopologyExcess
|
||||
|
||||
for _, rack := range analysis.DCToRacks[dc] {
|
||||
count := analysis.ShardsByRack[rack]
|
||||
if count > targetPerRack {
|
||||
excess = append(excess, TopologyExcess{
|
||||
ID: rack,
|
||||
Level: "rack",
|
||||
Excess: count - targetPerRack,
|
||||
Shards: analysis.RackToShards[rack],
|
||||
Nodes: analysis.RackToNodes[rack],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
slices.SortFunc(excess, func(a, b TopologyExcess) int {
|
||||
return b.Excess - a.Excess
|
||||
})
|
||||
|
||||
return excess
|
||||
}
|
||||
|
||||
// CalculateUnderservedDCs returns DCs that have fewer shards than target
|
||||
func CalculateUnderservedDCs(analysis *TopologyAnalysis, dist *ECDistribution) []string {
|
||||
var underserved []string
|
||||
|
||||
// Check existing DCs
|
||||
for dc, count := range analysis.ShardsByDC {
|
||||
if count < dist.TargetShardsPerDC {
|
||||
underserved = append(underserved, dc)
|
||||
}
|
||||
}
|
||||
|
||||
// Check DCs with nodes but no shards
|
||||
for dc := range analysis.DCToRacks {
|
||||
if _, exists := analysis.ShardsByDC[dc]; !exists {
|
||||
underserved = append(underserved, dc)
|
||||
}
|
||||
}
|
||||
|
||||
return underserved
|
||||
}
|
||||
|
||||
// CalculateUnderservedRacks returns racks that have fewer shards than target
|
||||
func CalculateUnderservedRacks(analysis *TopologyAnalysis, dc string, targetPerRack int) []string {
|
||||
var underserved []string
|
||||
|
||||
for _, rack := range analysis.DCToRacks[dc] {
|
||||
count := analysis.ShardsByRack[rack]
|
||||
if count < targetPerRack {
|
||||
underserved = append(underserved, rack)
|
||||
}
|
||||
}
|
||||
|
||||
return underserved
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
// Package distribution provides EC shard distribution algorithms with configurable EC ratios.
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
)
|
||||
|
||||
// ECConfig holds erasure coding configuration parameters.
|
||||
// This replaces hard-coded constants like DataShardsCount=10, ParityShardsCount=4.
|
||||
type ECConfig struct {
|
||||
DataShards int // Number of data shards (e.g., 10)
|
||||
ParityShards int // Number of parity shards (e.g., 4)
|
||||
}
|
||||
|
||||
// DefaultECConfig returns the standard 10+4 EC configuration
|
||||
func DefaultECConfig() ECConfig {
|
||||
return ECConfig{
|
||||
DataShards: 10,
|
||||
ParityShards: 4,
|
||||
}
|
||||
}
|
||||
|
||||
// NewECConfig creates a new EC configuration with validation
|
||||
func NewECConfig(dataShards, parityShards int) (ECConfig, error) {
|
||||
if dataShards <= 0 {
|
||||
return ECConfig{}, fmt.Errorf("dataShards must be positive, got %d", dataShards)
|
||||
}
|
||||
if parityShards <= 0 {
|
||||
return ECConfig{}, fmt.Errorf("parityShards must be positive, got %d", parityShards)
|
||||
}
|
||||
if dataShards+parityShards > 32 {
|
||||
return ECConfig{}, fmt.Errorf("total shards (%d+%d=%d) exceeds maximum of 32",
|
||||
dataShards, parityShards, dataShards+parityShards)
|
||||
}
|
||||
return ECConfig{
|
||||
DataShards: dataShards,
|
||||
ParityShards: parityShards,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// TotalShards returns the total number of shards (data + parity)
|
||||
func (c ECConfig) TotalShards() int {
|
||||
return c.DataShards + c.ParityShards
|
||||
}
|
||||
|
||||
// MaxTolerableLoss returns the maximum number of shards that can be lost
|
||||
// while still being able to reconstruct the data
|
||||
func (c ECConfig) MaxTolerableLoss() int {
|
||||
return c.ParityShards
|
||||
}
|
||||
|
||||
// MinShardsForReconstruction returns the minimum number of shards needed
|
||||
// to reconstruct the original data
|
||||
func (c ECConfig) MinShardsForReconstruction() int {
|
||||
return c.DataShards
|
||||
}
|
||||
|
||||
// String returns a human-readable representation
|
||||
func (c ECConfig) String() string {
|
||||
return fmt.Sprintf("%d+%d (total: %d, can lose: %d)",
|
||||
c.DataShards, c.ParityShards, c.TotalShards(), c.MaxTolerableLoss())
|
||||
}
|
||||
|
||||
// IsDataShard returns true if the shard ID is a data shard (0 to DataShards-1)
|
||||
func (c ECConfig) IsDataShard(shardID int) bool {
|
||||
return shardID >= 0 && shardID < c.DataShards
|
||||
}
|
||||
|
||||
// IsParityShard returns true if the shard ID is a parity shard (DataShards to TotalShards-1)
|
||||
func (c ECConfig) IsParityShard(shardID int) bool {
|
||||
return shardID >= c.DataShards && shardID < c.TotalShards()
|
||||
}
|
||||
|
||||
// SortShardsDataFirst returns a copy of shards sorted with data shards first.
|
||||
// This is useful for initial placement where data shards should be spread out first.
|
||||
func (c ECConfig) SortShardsDataFirst(shards []int) []int {
|
||||
result := make([]int, len(shards))
|
||||
copy(result, shards)
|
||||
|
||||
// Partition: data shards first, then parity shards
|
||||
dataIdx := 0
|
||||
parityIdx := len(result) - 1
|
||||
|
||||
sorted := make([]int, len(result))
|
||||
for _, s := range result {
|
||||
if c.IsDataShard(s) {
|
||||
sorted[dataIdx] = s
|
||||
dataIdx++
|
||||
} else {
|
||||
sorted[parityIdx] = s
|
||||
parityIdx--
|
||||
}
|
||||
}
|
||||
|
||||
return sorted
|
||||
}
|
||||
|
||||
// SortShardsParityFirst returns a copy of shards sorted with parity shards first.
|
||||
// This is useful for rebalancing where we prefer to move parity shards.
|
||||
func (c ECConfig) SortShardsParityFirst(shards []int) []int {
|
||||
result := make([]int, len(shards))
|
||||
copy(result, shards)
|
||||
|
||||
// Partition: parity shards first, then data shards
|
||||
parityIdx := 0
|
||||
dataIdx := len(result) - 1
|
||||
|
||||
sorted := make([]int, len(result))
|
||||
for _, s := range result {
|
||||
if c.IsParityShard(s) {
|
||||
sorted[parityIdx] = s
|
||||
parityIdx++
|
||||
} else {
|
||||
sorted[dataIdx] = s
|
||||
dataIdx--
|
||||
}
|
||||
}
|
||||
|
||||
return sorted
|
||||
}
|
||||
|
||||
// ReplicationConfig holds the parsed replication policy
|
||||
type ReplicationConfig struct {
|
||||
MinDataCenters int // X+1 from XYZ replication (minimum DCs to use)
|
||||
MinRacksPerDC int // Y+1 from XYZ replication (minimum racks per DC)
|
||||
MinNodesPerRack int // Z+1 from XYZ replication (minimum nodes per rack)
|
||||
|
||||
// Original replication string (for logging/debugging)
|
||||
Original string
|
||||
}
|
||||
|
||||
// NewReplicationConfig creates a ReplicationConfig from a ReplicaPlacement
|
||||
func NewReplicationConfig(rp *super_block.ReplicaPlacement) ReplicationConfig {
|
||||
if rp == nil {
|
||||
return ReplicationConfig{
|
||||
MinDataCenters: 1,
|
||||
MinRacksPerDC: 1,
|
||||
MinNodesPerRack: 1,
|
||||
Original: "000",
|
||||
}
|
||||
}
|
||||
return ReplicationConfig{
|
||||
MinDataCenters: rp.DiffDataCenterCount + 1,
|
||||
MinRacksPerDC: rp.DiffRackCount + 1,
|
||||
MinNodesPerRack: rp.SameRackCount + 1,
|
||||
Original: rp.String(),
|
||||
}
|
||||
}
|
||||
|
||||
// NewReplicationConfigFromString creates a ReplicationConfig from a replication string
|
||||
func NewReplicationConfigFromString(replication string) (ReplicationConfig, error) {
|
||||
rp, err := super_block.NewReplicaPlacementFromString(replication)
|
||||
if err != nil {
|
||||
return ReplicationConfig{}, err
|
||||
}
|
||||
return NewReplicationConfig(rp), nil
|
||||
}
|
||||
|
||||
// TotalPlacementSlots returns the minimum number of unique placement locations
|
||||
// based on the replication policy
|
||||
func (r ReplicationConfig) TotalPlacementSlots() int {
|
||||
return r.MinDataCenters * r.MinRacksPerDC * r.MinNodesPerRack
|
||||
}
|
||||
|
||||
// String returns a human-readable representation
|
||||
func (r ReplicationConfig) String() string {
|
||||
return fmt.Sprintf("replication=%s (DCs:%d, Racks/DC:%d, Nodes/Rack:%d)",
|
||||
r.Original, r.MinDataCenters, r.MinRacksPerDC, r.MinNodesPerRack)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ECDistribution represents the target distribution of EC shards
|
||||
// based on EC configuration and replication policy.
|
||||
type ECDistribution struct {
|
||||
// EC configuration
|
||||
ECConfig ECConfig
|
||||
|
||||
// Replication configuration
|
||||
ReplicationConfig ReplicationConfig
|
||||
|
||||
// Target shard counts per topology level (balanced distribution)
|
||||
TargetShardsPerDC int
|
||||
TargetShardsPerRack int
|
||||
TargetShardsPerNode int
|
||||
|
||||
// Maximum shard counts per topology level (fault tolerance limits)
|
||||
// These prevent any single failure domain from having too many shards
|
||||
MaxShardsPerDC int
|
||||
MaxShardsPerRack int
|
||||
MaxShardsPerNode int
|
||||
}
|
||||
|
||||
// CalculateDistribution computes the target EC shard distribution based on
|
||||
// EC configuration and replication policy.
|
||||
//
|
||||
// The algorithm:
|
||||
// 1. Uses replication policy to determine minimum topology spread
|
||||
// 2. Calculates target shards per level (evenly distributed)
|
||||
// 3. Calculates max shards per level (for fault tolerance)
|
||||
func CalculateDistribution(ec ECConfig, rep ReplicationConfig) *ECDistribution {
|
||||
totalShards := ec.TotalShards()
|
||||
|
||||
// Target distribution (balanced, rounded up to ensure all shards placed)
|
||||
targetShardsPerDC := ceilDivide(totalShards, rep.MinDataCenters)
|
||||
targetShardsPerRack := ceilDivide(targetShardsPerDC, rep.MinRacksPerDC)
|
||||
targetShardsPerNode := ceilDivide(targetShardsPerRack, rep.MinNodesPerRack)
|
||||
|
||||
// Maximum limits for fault tolerance
|
||||
// The key constraint: losing one failure domain shouldn't lose more than parityShards
|
||||
// So max shards per domain = totalShards - parityShards + tolerance
|
||||
// We add small tolerance (+2) to allow for imbalanced topologies
|
||||
faultToleranceLimit := totalShards - ec.ParityShards + 1
|
||||
|
||||
maxShardsPerDC := min(faultToleranceLimit, targetShardsPerDC+2)
|
||||
maxShardsPerRack := min(faultToleranceLimit, targetShardsPerRack+2)
|
||||
maxShardsPerNode := min(faultToleranceLimit, targetShardsPerNode+2)
|
||||
|
||||
return &ECDistribution{
|
||||
ECConfig: ec,
|
||||
ReplicationConfig: rep,
|
||||
TargetShardsPerDC: targetShardsPerDC,
|
||||
TargetShardsPerRack: targetShardsPerRack,
|
||||
TargetShardsPerNode: targetShardsPerNode,
|
||||
MaxShardsPerDC: maxShardsPerDC,
|
||||
MaxShardsPerRack: maxShardsPerRack,
|
||||
MaxShardsPerNode: maxShardsPerNode,
|
||||
}
|
||||
}
|
||||
|
||||
// String returns a human-readable description of the distribution
|
||||
func (d *ECDistribution) String() string {
|
||||
return fmt.Sprintf(
|
||||
"ECDistribution{EC:%s, DCs:%d (target:%d/max:%d), Racks/DC:%d (target:%d/max:%d), Nodes/Rack:%d (target:%d/max:%d)}",
|
||||
d.ECConfig.String(),
|
||||
d.ReplicationConfig.MinDataCenters, d.TargetShardsPerDC, d.MaxShardsPerDC,
|
||||
d.ReplicationConfig.MinRacksPerDC, d.TargetShardsPerRack, d.MaxShardsPerRack,
|
||||
d.ReplicationConfig.MinNodesPerRack, d.TargetShardsPerNode, d.MaxShardsPerNode,
|
||||
)
|
||||
}
|
||||
|
||||
// Summary returns a multi-line summary of the distribution plan
|
||||
func (d *ECDistribution) Summary() string {
|
||||
summary := fmt.Sprintf("EC Configuration: %s\n", d.ECConfig.String())
|
||||
summary += fmt.Sprintf("Replication: %s\n", d.ReplicationConfig.String())
|
||||
summary += fmt.Sprintf("Distribution Plan:\n")
|
||||
summary += fmt.Sprintf(" Data Centers: %d (target %d shards each, max %d)\n",
|
||||
d.ReplicationConfig.MinDataCenters, d.TargetShardsPerDC, d.MaxShardsPerDC)
|
||||
summary += fmt.Sprintf(" Racks per DC: %d (target %d shards each, max %d)\n",
|
||||
d.ReplicationConfig.MinRacksPerDC, d.TargetShardsPerRack, d.MaxShardsPerRack)
|
||||
summary += fmt.Sprintf(" Nodes per Rack: %d (target %d shards each, max %d)\n",
|
||||
d.ReplicationConfig.MinNodesPerRack, d.TargetShardsPerNode, d.MaxShardsPerNode)
|
||||
return summary
|
||||
}
|
||||
|
||||
// CanSurviveDCFailure returns true if the distribution can survive
|
||||
// complete loss of one data center
|
||||
func (d *ECDistribution) CanSurviveDCFailure() bool {
|
||||
// After losing one DC with max shards, check if remaining shards are enough
|
||||
remainingAfterDCLoss := d.ECConfig.TotalShards() - d.TargetShardsPerDC
|
||||
return remainingAfterDCLoss >= d.ECConfig.MinShardsForReconstruction()
|
||||
}
|
||||
|
||||
// CanSurviveRackFailure returns true if the distribution can survive
|
||||
// complete loss of one rack
|
||||
func (d *ECDistribution) CanSurviveRackFailure() bool {
|
||||
remainingAfterRackLoss := d.ECConfig.TotalShards() - d.TargetShardsPerRack
|
||||
return remainingAfterRackLoss >= d.ECConfig.MinShardsForReconstruction()
|
||||
}
|
||||
|
||||
// MinDCsForDCFaultTolerance calculates the minimum number of DCs needed
|
||||
// to survive complete DC failure with this EC configuration
|
||||
func (d *ECDistribution) MinDCsForDCFaultTolerance() int {
|
||||
// To survive DC failure, max shards per DC = parityShards
|
||||
maxShardsPerDC := d.ECConfig.MaxTolerableLoss()
|
||||
if maxShardsPerDC == 0 {
|
||||
return d.ECConfig.TotalShards() // Would need one DC per shard
|
||||
}
|
||||
return ceilDivide(d.ECConfig.TotalShards(), maxShardsPerDC)
|
||||
}
|
||||
|
||||
// FaultToleranceAnalysis returns a detailed analysis of fault tolerance
|
||||
func (d *ECDistribution) FaultToleranceAnalysis() string {
|
||||
analysis := fmt.Sprintf("Fault Tolerance Analysis for %s:\n", d.ECConfig.String())
|
||||
|
||||
// DC failure
|
||||
dcSurvive := d.CanSurviveDCFailure()
|
||||
shardsAfterDC := d.ECConfig.TotalShards() - d.TargetShardsPerDC
|
||||
analysis += fmt.Sprintf(" DC Failure: %s\n", boolToResult(dcSurvive))
|
||||
analysis += fmt.Sprintf(" - Losing one DC loses ~%d shards\n", d.TargetShardsPerDC)
|
||||
analysis += fmt.Sprintf(" - Remaining: %d shards (need %d)\n", shardsAfterDC, d.ECConfig.DataShards)
|
||||
if !dcSurvive {
|
||||
analysis += fmt.Sprintf(" - Need at least %d DCs for DC fault tolerance\n", d.MinDCsForDCFaultTolerance())
|
||||
}
|
||||
|
||||
// Rack failure
|
||||
rackSurvive := d.CanSurviveRackFailure()
|
||||
shardsAfterRack := d.ECConfig.TotalShards() - d.TargetShardsPerRack
|
||||
analysis += fmt.Sprintf(" Rack Failure: %s\n", boolToResult(rackSurvive))
|
||||
analysis += fmt.Sprintf(" - Losing one rack loses ~%d shards\n", d.TargetShardsPerRack)
|
||||
analysis += fmt.Sprintf(" - Remaining: %d shards (need %d)\n", shardsAfterRack, d.ECConfig.DataShards)
|
||||
|
||||
// Node failure (usually survivable)
|
||||
shardsAfterNode := d.ECConfig.TotalShards() - d.TargetShardsPerNode
|
||||
nodeSurvive := shardsAfterNode >= d.ECConfig.DataShards
|
||||
analysis += fmt.Sprintf(" Node Failure: %s\n", boolToResult(nodeSurvive))
|
||||
analysis += fmt.Sprintf(" - Losing one node loses ~%d shards\n", d.TargetShardsPerNode)
|
||||
analysis += fmt.Sprintf(" - Remaining: %d shards (need %d)\n", shardsAfterNode, d.ECConfig.DataShards)
|
||||
|
||||
return analysis
|
||||
}
|
||||
|
||||
func boolToResult(b bool) string {
|
||||
if b {
|
||||
return "SURVIVABLE ✓"
|
||||
}
|
||||
return "NOT SURVIVABLE ✗"
|
||||
}
|
||||
|
||||
// ceilDivide performs ceiling division
|
||||
func ceilDivide(a, b int) int {
|
||||
if b <= 0 {
|
||||
return a
|
||||
}
|
||||
return (a + b - 1) / b
|
||||
}
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewECConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dataShards int
|
||||
parityShards int
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid 10+4", 10, 4, false},
|
||||
{"valid 8+4", 8, 4, false},
|
||||
{"valid 6+3", 6, 3, false},
|
||||
{"valid 4+2", 4, 2, false},
|
||||
{"invalid data=0", 0, 4, true},
|
||||
{"invalid parity=0", 10, 0, true},
|
||||
{"invalid total>32", 20, 15, true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
config, err := NewECConfig(tt.dataShards, tt.parityShards)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("NewECConfig() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !tt.wantErr {
|
||||
if config.DataShards != tt.dataShards {
|
||||
t.Errorf("DataShards = %d, want %d", config.DataShards, tt.dataShards)
|
||||
}
|
||||
if config.ParityShards != tt.parityShards {
|
||||
t.Errorf("ParityShards = %d, want %d", config.ParityShards, tt.parityShards)
|
||||
}
|
||||
if config.TotalShards() != tt.dataShards+tt.parityShards {
|
||||
t.Errorf("TotalShards() = %d, want %d", config.TotalShards(), tt.dataShards+tt.parityShards)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculateDistribution(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ecConfig ECConfig
|
||||
replication string
|
||||
expectedMinDCs int
|
||||
expectedMinRacksPerDC int
|
||||
expectedMinNodesPerRack int
|
||||
expectedTargetPerDC int
|
||||
expectedTargetPerRack int
|
||||
expectedTargetPerNode int
|
||||
}{
|
||||
{
|
||||
name: "10+4 with 000",
|
||||
ecConfig: DefaultECConfig(),
|
||||
replication: "000",
|
||||
expectedMinDCs: 1,
|
||||
expectedMinRacksPerDC: 1,
|
||||
expectedMinNodesPerRack: 1,
|
||||
expectedTargetPerDC: 14,
|
||||
expectedTargetPerRack: 14,
|
||||
expectedTargetPerNode: 14,
|
||||
},
|
||||
{
|
||||
name: "10+4 with 100",
|
||||
ecConfig: DefaultECConfig(),
|
||||
replication: "100",
|
||||
expectedMinDCs: 2,
|
||||
expectedMinRacksPerDC: 1,
|
||||
expectedMinNodesPerRack: 1,
|
||||
expectedTargetPerDC: 7,
|
||||
expectedTargetPerRack: 7,
|
||||
expectedTargetPerNode: 7,
|
||||
},
|
||||
{
|
||||
name: "10+4 with 110",
|
||||
ecConfig: DefaultECConfig(),
|
||||
replication: "110",
|
||||
expectedMinDCs: 2,
|
||||
expectedMinRacksPerDC: 2,
|
||||
expectedMinNodesPerRack: 1,
|
||||
expectedTargetPerDC: 7,
|
||||
expectedTargetPerRack: 4,
|
||||
expectedTargetPerNode: 4,
|
||||
},
|
||||
{
|
||||
name: "10+4 with 200",
|
||||
ecConfig: DefaultECConfig(),
|
||||
replication: "200",
|
||||
expectedMinDCs: 3,
|
||||
expectedMinRacksPerDC: 1,
|
||||
expectedMinNodesPerRack: 1,
|
||||
expectedTargetPerDC: 5,
|
||||
expectedTargetPerRack: 5,
|
||||
expectedTargetPerNode: 5,
|
||||
},
|
||||
{
|
||||
name: "8+4 with 110",
|
||||
ecConfig: ECConfig{
|
||||
DataShards: 8,
|
||||
ParityShards: 4,
|
||||
},
|
||||
replication: "110",
|
||||
expectedMinDCs: 2,
|
||||
expectedMinRacksPerDC: 2,
|
||||
expectedMinNodesPerRack: 1,
|
||||
expectedTargetPerDC: 6, // 12/2 = 6
|
||||
expectedTargetPerRack: 3, // 6/2 = 3
|
||||
expectedTargetPerNode: 3,
|
||||
},
|
||||
{
|
||||
name: "6+3 with 100",
|
||||
ecConfig: ECConfig{
|
||||
DataShards: 6,
|
||||
ParityShards: 3,
|
||||
},
|
||||
replication: "100",
|
||||
expectedMinDCs: 2,
|
||||
expectedMinRacksPerDC: 1,
|
||||
expectedMinNodesPerRack: 1,
|
||||
expectedTargetPerDC: 5, // ceil(9/2) = 5
|
||||
expectedTargetPerRack: 5,
|
||||
expectedTargetPerNode: 5,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rep, err := NewReplicationConfigFromString(tt.replication)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse replication %s: %v", tt.replication, err)
|
||||
}
|
||||
|
||||
dist := CalculateDistribution(tt.ecConfig, rep)
|
||||
|
||||
if dist.ReplicationConfig.MinDataCenters != tt.expectedMinDCs {
|
||||
t.Errorf("MinDataCenters = %d, want %d", dist.ReplicationConfig.MinDataCenters, tt.expectedMinDCs)
|
||||
}
|
||||
if dist.ReplicationConfig.MinRacksPerDC != tt.expectedMinRacksPerDC {
|
||||
t.Errorf("MinRacksPerDC = %d, want %d", dist.ReplicationConfig.MinRacksPerDC, tt.expectedMinRacksPerDC)
|
||||
}
|
||||
if dist.ReplicationConfig.MinNodesPerRack != tt.expectedMinNodesPerRack {
|
||||
t.Errorf("MinNodesPerRack = %d, want %d", dist.ReplicationConfig.MinNodesPerRack, tt.expectedMinNodesPerRack)
|
||||
}
|
||||
if dist.TargetShardsPerDC != tt.expectedTargetPerDC {
|
||||
t.Errorf("TargetShardsPerDC = %d, want %d", dist.TargetShardsPerDC, tt.expectedTargetPerDC)
|
||||
}
|
||||
if dist.TargetShardsPerRack != tt.expectedTargetPerRack {
|
||||
t.Errorf("TargetShardsPerRack = %d, want %d", dist.TargetShardsPerRack, tt.expectedTargetPerRack)
|
||||
}
|
||||
if dist.TargetShardsPerNode != tt.expectedTargetPerNode {
|
||||
t.Errorf("TargetShardsPerNode = %d, want %d", dist.TargetShardsPerNode, tt.expectedTargetPerNode)
|
||||
}
|
||||
|
||||
t.Logf("Distribution for %s: %s", tt.name, dist.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFaultToleranceAnalysis(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ecConfig ECConfig
|
||||
replication string
|
||||
canSurviveDC bool
|
||||
canSurviveRack bool
|
||||
}{
|
||||
// 10+4 = 14 shards, need 10 to reconstruct, can lose 4
|
||||
{"10+4 000", DefaultECConfig(), "000", false, false}, // All in one, any failure is fatal
|
||||
{"10+4 100", DefaultECConfig(), "100", false, false}, // 7 per DC/rack, 7 remaining < 10
|
||||
{"10+4 200", DefaultECConfig(), "200", false, false}, // 5 per DC/rack, 9 remaining < 10
|
||||
{"10+4 110", DefaultECConfig(), "110", false, true}, // 4 per rack, 10 remaining = enough for rack
|
||||
|
||||
// 8+4 = 12 shards, need 8 to reconstruct, can lose 4
|
||||
{"8+4 100", ECConfig{8, 4}, "100", false, false}, // 6 per DC/rack, 6 remaining < 8
|
||||
{"8+4 200", ECConfig{8, 4}, "200", true, true}, // 4 per DC/rack, 8 remaining = enough!
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rep, _ := NewReplicationConfigFromString(tt.replication)
|
||||
dist := CalculateDistribution(tt.ecConfig, rep)
|
||||
|
||||
if dist.CanSurviveDCFailure() != tt.canSurviveDC {
|
||||
t.Errorf("CanSurviveDCFailure() = %v, want %v", dist.CanSurviveDCFailure(), tt.canSurviveDC)
|
||||
}
|
||||
if dist.CanSurviveRackFailure() != tt.canSurviveRack {
|
||||
t.Errorf("CanSurviveRackFailure() = %v, want %v", dist.CanSurviveRackFailure(), tt.canSurviveRack)
|
||||
}
|
||||
|
||||
t.Log(dist.FaultToleranceAnalysis())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMinDCsForDCFaultTolerance(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ecConfig ECConfig
|
||||
minDCs int
|
||||
}{
|
||||
// 10+4: can lose 4, so max 4 per DC, 14/4 = 4 DCs needed
|
||||
{"10+4", DefaultECConfig(), 4},
|
||||
// 8+4: can lose 4, so max 4 per DC, 12/4 = 3 DCs needed
|
||||
{"8+4", ECConfig{8, 4}, 3},
|
||||
// 6+3: can lose 3, so max 3 per DC, 9/3 = 3 DCs needed
|
||||
{"6+3", ECConfig{6, 3}, 3},
|
||||
// 4+2: can lose 2, so max 2 per DC, 6/2 = 3 DCs needed
|
||||
{"4+2", ECConfig{4, 2}, 3},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rep, _ := NewReplicationConfigFromString("000")
|
||||
dist := CalculateDistribution(tt.ecConfig, rep)
|
||||
|
||||
if dist.MinDCsForDCFaultTolerance() != tt.minDCs {
|
||||
t.Errorf("MinDCsForDCFaultTolerance() = %d, want %d",
|
||||
dist.MinDCsForDCFaultTolerance(), tt.minDCs)
|
||||
}
|
||||
|
||||
t.Logf("%s: needs %d DCs for DC fault tolerance", tt.name, dist.MinDCsForDCFaultTolerance())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTopologyAnalysis(t *testing.T) {
|
||||
analysis := NewTopologyAnalysis()
|
||||
|
||||
// Add nodes to topology
|
||||
node1 := &TopologyNode{
|
||||
NodeID: "node1",
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack1",
|
||||
FreeSlots: 5,
|
||||
}
|
||||
node2 := &TopologyNode{
|
||||
NodeID: "node2",
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack2",
|
||||
FreeSlots: 10,
|
||||
}
|
||||
node3 := &TopologyNode{
|
||||
NodeID: "node3",
|
||||
DataCenter: "dc2",
|
||||
Rack: "rack3",
|
||||
FreeSlots: 10,
|
||||
}
|
||||
|
||||
analysis.AddNode(node1)
|
||||
analysis.AddNode(node2)
|
||||
analysis.AddNode(node3)
|
||||
|
||||
// Add shard locations (all on node1)
|
||||
for i := 0; i < 14; i++ {
|
||||
analysis.AddShardLocation(ShardLocation{
|
||||
ShardID: i,
|
||||
NodeID: "node1",
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack1",
|
||||
})
|
||||
}
|
||||
|
||||
analysis.Finalize()
|
||||
|
||||
// Verify counts
|
||||
if analysis.TotalShards != 14 {
|
||||
t.Errorf("TotalShards = %d, want 14", analysis.TotalShards)
|
||||
}
|
||||
if analysis.ShardsByDC["dc1"] != 14 {
|
||||
t.Errorf("ShardsByDC[dc1] = %d, want 14", analysis.ShardsByDC["dc1"])
|
||||
}
|
||||
if analysis.ShardsByRack["rack1"] != 14 {
|
||||
t.Errorf("ShardsByRack[rack1] = %d, want 14", analysis.ShardsByRack["rack1"])
|
||||
}
|
||||
if analysis.ShardsByNode["node1"] != 14 {
|
||||
t.Errorf("ShardsByNode[node1] = %d, want 14", analysis.ShardsByNode["node1"])
|
||||
}
|
||||
|
||||
t.Log(analysis.DetailedString())
|
||||
}
|
||||
|
||||
func TestRebalancer(t *testing.T) {
|
||||
// Build topology: 2 DCs, 2 racks each, all shards on one node
|
||||
analysis := NewTopologyAnalysis()
|
||||
|
||||
// Add nodes
|
||||
nodes := []*TopologyNode{
|
||||
{NodeID: "dc1-rack1-node1", DataCenter: "dc1", Rack: "dc1-rack1", FreeSlots: 0},
|
||||
{NodeID: "dc1-rack2-node1", DataCenter: "dc1", Rack: "dc1-rack2", FreeSlots: 10},
|
||||
{NodeID: "dc2-rack1-node1", DataCenter: "dc2", Rack: "dc2-rack1", FreeSlots: 10},
|
||||
{NodeID: "dc2-rack2-node1", DataCenter: "dc2", Rack: "dc2-rack2", FreeSlots: 10},
|
||||
}
|
||||
for _, node := range nodes {
|
||||
analysis.AddNode(node)
|
||||
}
|
||||
|
||||
// Add all 14 shards to first node
|
||||
for i := 0; i < 14; i++ {
|
||||
analysis.AddShardLocation(ShardLocation{
|
||||
ShardID: i,
|
||||
NodeID: "dc1-rack1-node1",
|
||||
DataCenter: "dc1",
|
||||
Rack: "dc1-rack1",
|
||||
})
|
||||
}
|
||||
analysis.Finalize()
|
||||
|
||||
// Create rebalancer with 110 replication (2 DCs, 2 racks each)
|
||||
ec := DefaultECConfig()
|
||||
rep, _ := NewReplicationConfigFromString("110")
|
||||
rebalancer := NewRebalancer(ec, rep)
|
||||
|
||||
plan, err := rebalancer.PlanRebalance(analysis)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanRebalance failed: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Planned %d moves", plan.TotalMoves)
|
||||
t.Log(plan.DetailedString())
|
||||
|
||||
// Verify we're moving shards to dc2
|
||||
movedToDC2 := 0
|
||||
for _, move := range plan.Moves {
|
||||
if move.DestNode.DataCenter == "dc2" {
|
||||
movedToDC2++
|
||||
}
|
||||
}
|
||||
|
||||
if movedToDC2 == 0 {
|
||||
t.Error("Expected some moves to dc2")
|
||||
}
|
||||
|
||||
// With "110" replication, target is 7 shards per DC
|
||||
// Starting with 14 in dc1, should plan to move 7 to dc2
|
||||
if plan.MovesAcrossDC < 7 {
|
||||
t.Errorf("Expected at least 7 cross-DC moves for 110 replication, got %d", plan.MovesAcrossDC)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomECRatios(t *testing.T) {
|
||||
// Test various custom EC ratios that seaweed-enterprise might use
|
||||
ratios := []struct {
|
||||
name string
|
||||
data int
|
||||
parity int
|
||||
}{
|
||||
{"4+2", 4, 2},
|
||||
{"6+3", 6, 3},
|
||||
{"8+2", 8, 2},
|
||||
{"8+4", 8, 4},
|
||||
{"10+4", 10, 4},
|
||||
{"12+4", 12, 4},
|
||||
{"16+4", 16, 4},
|
||||
}
|
||||
|
||||
for _, ratio := range ratios {
|
||||
t.Run(ratio.name, func(t *testing.T) {
|
||||
ec, err := NewECConfig(ratio.data, ratio.parity)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create EC config: %v", err)
|
||||
}
|
||||
|
||||
rep, _ := NewReplicationConfigFromString("110")
|
||||
dist := CalculateDistribution(ec, rep)
|
||||
|
||||
t.Logf("EC %s with replication 110:", ratio.name)
|
||||
t.Logf(" Total shards: %d", ec.TotalShards())
|
||||
t.Logf(" Can lose: %d shards", ec.MaxTolerableLoss())
|
||||
t.Logf(" Target per DC: %d", dist.TargetShardsPerDC)
|
||||
t.Logf(" Target per rack: %d", dist.TargetShardsPerRack)
|
||||
t.Logf(" Min DCs for DC fault tolerance: %d", dist.MinDCsForDCFaultTolerance())
|
||||
|
||||
// Verify basic sanity
|
||||
if dist.TargetShardsPerDC*2 < ec.TotalShards() {
|
||||
t.Errorf("Target per DC (%d) * 2 should be >= total (%d)",
|
||||
dist.TargetShardsPerDC, ec.TotalShards())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShardClassification(t *testing.T) {
|
||||
ec := DefaultECConfig() // 10+4
|
||||
|
||||
// Test IsDataShard
|
||||
for i := 0; i < 10; i++ {
|
||||
if !ec.IsDataShard(i) {
|
||||
t.Errorf("Shard %d should be a data shard", i)
|
||||
}
|
||||
if ec.IsParityShard(i) {
|
||||
t.Errorf("Shard %d should not be a parity shard", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Test IsParityShard
|
||||
for i := 10; i < 14; i++ {
|
||||
if ec.IsDataShard(i) {
|
||||
t.Errorf("Shard %d should not be a data shard", i)
|
||||
}
|
||||
if !ec.IsParityShard(i) {
|
||||
t.Errorf("Shard %d should be a parity shard", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Test with custom 8+4 EC
|
||||
ec84, _ := NewECConfig(8, 4)
|
||||
for i := 0; i < 8; i++ {
|
||||
if !ec84.IsDataShard(i) {
|
||||
t.Errorf("8+4 EC: Shard %d should be a data shard", i)
|
||||
}
|
||||
}
|
||||
for i := 8; i < 12; i++ {
|
||||
if !ec84.IsParityShard(i) {
|
||||
t.Errorf("8+4 EC: Shard %d should be a parity shard", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortShardsDataFirst(t *testing.T) {
|
||||
ec := DefaultECConfig() // 10+4
|
||||
|
||||
// Mixed shards: [0, 10, 5, 11, 2, 12, 7, 13]
|
||||
shards := []int{0, 10, 5, 11, 2, 12, 7, 13}
|
||||
sorted := ec.SortShardsDataFirst(shards)
|
||||
|
||||
t.Logf("Original: %v", shards)
|
||||
t.Logf("Sorted (data first): %v", sorted)
|
||||
|
||||
// First 4 should be data shards (0, 5, 2, 7)
|
||||
for i := 0; i < 4; i++ {
|
||||
if !ec.IsDataShard(sorted[i]) {
|
||||
t.Errorf("Position %d should be a data shard, got %d", i, sorted[i])
|
||||
}
|
||||
}
|
||||
|
||||
// Last 4 should be parity shards (10, 11, 12, 13)
|
||||
for i := 4; i < 8; i++ {
|
||||
if !ec.IsParityShard(sorted[i]) {
|
||||
t.Errorf("Position %d should be a parity shard, got %d", i, sorted[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortShardsParityFirst(t *testing.T) {
|
||||
ec := DefaultECConfig() // 10+4
|
||||
|
||||
// Mixed shards: [0, 10, 5, 11, 2, 12, 7, 13]
|
||||
shards := []int{0, 10, 5, 11, 2, 12, 7, 13}
|
||||
sorted := ec.SortShardsParityFirst(shards)
|
||||
|
||||
t.Logf("Original: %v", shards)
|
||||
t.Logf("Sorted (parity first): %v", sorted)
|
||||
|
||||
// First 4 should be parity shards (10, 11, 12, 13)
|
||||
for i := 0; i < 4; i++ {
|
||||
if !ec.IsParityShard(sorted[i]) {
|
||||
t.Errorf("Position %d should be a parity shard, got %d", i, sorted[i])
|
||||
}
|
||||
}
|
||||
|
||||
// Last 4 should be data shards (0, 5, 2, 7)
|
||||
for i := 4; i < 8; i++ {
|
||||
if !ec.IsDataShard(sorted[i]) {
|
||||
t.Errorf("Position %d should be a data shard, got %d", i, sorted[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRebalancerPrefersMovingParityShards(t *testing.T) {
|
||||
// Build topology where one node has all shards including mix of data and parity
|
||||
analysis := NewTopologyAnalysis()
|
||||
|
||||
// Node 1: Has all 14 shards (mixed data and parity)
|
||||
node1 := &TopologyNode{
|
||||
NodeID: "node1",
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack1",
|
||||
FreeSlots: 0,
|
||||
}
|
||||
analysis.AddNode(node1)
|
||||
|
||||
// Node 2: Empty, ready to receive
|
||||
node2 := &TopologyNode{
|
||||
NodeID: "node2",
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack1",
|
||||
FreeSlots: 10,
|
||||
}
|
||||
analysis.AddNode(node2)
|
||||
|
||||
// Add all 14 shards to node1
|
||||
for i := 0; i < 14; i++ {
|
||||
analysis.AddShardLocation(ShardLocation{
|
||||
ShardID: i,
|
||||
NodeID: "node1",
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack1",
|
||||
})
|
||||
}
|
||||
analysis.Finalize()
|
||||
|
||||
// Create rebalancer
|
||||
ec := DefaultECConfig()
|
||||
rep, _ := NewReplicationConfigFromString("000")
|
||||
rebalancer := NewRebalancer(ec, rep)
|
||||
|
||||
plan, err := rebalancer.PlanRebalance(analysis)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanRebalance failed: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Planned %d moves", len(plan.Moves))
|
||||
|
||||
// Check that parity shards are moved first
|
||||
parityMovesFirst := 0
|
||||
dataMovesFirst := 0
|
||||
seenDataMove := false
|
||||
|
||||
for _, move := range plan.Moves {
|
||||
isParity := ec.IsParityShard(move.ShardID)
|
||||
t.Logf("Move shard %d (parity=%v): %s -> %s",
|
||||
move.ShardID, isParity, move.SourceNode.NodeID, move.DestNode.NodeID)
|
||||
|
||||
if isParity && !seenDataMove {
|
||||
parityMovesFirst++
|
||||
} else if !isParity {
|
||||
seenDataMove = true
|
||||
dataMovesFirst++
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("Parity moves before first data move: %d", parityMovesFirst)
|
||||
t.Logf("Data moves: %d", dataMovesFirst)
|
||||
|
||||
// With 10+4 EC, there are 4 parity shards
|
||||
// They should be moved before data shards when possible
|
||||
if parityMovesFirst < 4 && len(plan.Moves) >= 4 {
|
||||
t.Logf("Note: Expected parity shards to be moved first, but got %d parity moves before data moves", parityMovesFirst)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributionSummary(t *testing.T) {
|
||||
ec := DefaultECConfig()
|
||||
rep, _ := NewReplicationConfigFromString("110")
|
||||
dist := CalculateDistribution(ec, rep)
|
||||
|
||||
summary := dist.Summary()
|
||||
t.Log(summary)
|
||||
|
||||
if len(summary) == 0 {
|
||||
t.Error("Summary should not be empty")
|
||||
}
|
||||
|
||||
analysis := dist.FaultToleranceAnalysis()
|
||||
t.Log(analysis)
|
||||
|
||||
if len(analysis) == 0 {
|
||||
t.Error("Fault tolerance analysis should not be empty")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// ShardMove represents a planned shard move
|
||||
type ShardMove struct {
|
||||
ShardID int
|
||||
SourceNode *TopologyNode
|
||||
DestNode *TopologyNode
|
||||
Reason string
|
||||
}
|
||||
|
||||
// String returns a human-readable description of the move
|
||||
func (m ShardMove) String() string {
|
||||
return fmt.Sprintf("shard %d: %s -> %s (%s)",
|
||||
m.ShardID, m.SourceNode.NodeID, m.DestNode.NodeID, m.Reason)
|
||||
}
|
||||
|
||||
// RebalancePlan contains the complete plan for rebalancing EC shards
|
||||
type RebalancePlan struct {
|
||||
Moves []ShardMove
|
||||
Distribution *ECDistribution
|
||||
Analysis *TopologyAnalysis
|
||||
|
||||
// Statistics
|
||||
TotalMoves int
|
||||
MovesAcrossDC int
|
||||
MovesAcrossRack int
|
||||
MovesWithinRack int
|
||||
}
|
||||
|
||||
// String returns a summary of the plan
|
||||
func (p *RebalancePlan) String() string {
|
||||
return fmt.Sprintf("RebalancePlan{moves:%d, acrossDC:%d, acrossRack:%d, withinRack:%d}",
|
||||
p.TotalMoves, p.MovesAcrossDC, p.MovesAcrossRack, p.MovesWithinRack)
|
||||
}
|
||||
|
||||
// DetailedString returns a detailed multi-line summary
|
||||
func (p *RebalancePlan) DetailedString() string {
|
||||
s := fmt.Sprintf("Rebalance Plan:\n")
|
||||
s += fmt.Sprintf(" Total Moves: %d\n", p.TotalMoves)
|
||||
s += fmt.Sprintf(" Across DC: %d\n", p.MovesAcrossDC)
|
||||
s += fmt.Sprintf(" Across Rack: %d\n", p.MovesAcrossRack)
|
||||
s += fmt.Sprintf(" Within Rack: %d\n", p.MovesWithinRack)
|
||||
s += fmt.Sprintf("\nMoves:\n")
|
||||
for i, move := range p.Moves {
|
||||
s += fmt.Sprintf(" %d. %s\n", i+1, move.String())
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Rebalancer plans shard moves to achieve proportional distribution
|
||||
type Rebalancer struct {
|
||||
ecConfig ECConfig
|
||||
repConfig ReplicationConfig
|
||||
}
|
||||
|
||||
// NewRebalancer creates a new rebalancer with the given configuration
|
||||
func NewRebalancer(ec ECConfig, rep ReplicationConfig) *Rebalancer {
|
||||
return &Rebalancer{
|
||||
ecConfig: ec,
|
||||
repConfig: rep,
|
||||
}
|
||||
}
|
||||
|
||||
// PlanRebalance creates a rebalancing plan based on current topology analysis
|
||||
func (r *Rebalancer) PlanRebalance(analysis *TopologyAnalysis) (*RebalancePlan, error) {
|
||||
dist := CalculateDistribution(r.ecConfig, r.repConfig)
|
||||
|
||||
plan := &RebalancePlan{
|
||||
Distribution: dist,
|
||||
Analysis: analysis,
|
||||
}
|
||||
|
||||
// Step 1: Balance across data centers
|
||||
dcMoves := r.planDCMoves(analysis, dist)
|
||||
for _, move := range dcMoves {
|
||||
plan.Moves = append(plan.Moves, move)
|
||||
plan.MovesAcrossDC++
|
||||
}
|
||||
|
||||
// Update analysis after DC moves (for planning purposes)
|
||||
r.applyMovesToAnalysis(analysis, dcMoves)
|
||||
|
||||
// Step 2: Balance across racks within each DC
|
||||
rackMoves := r.planRackMoves(analysis, dist)
|
||||
for _, move := range rackMoves {
|
||||
plan.Moves = append(plan.Moves, move)
|
||||
plan.MovesAcrossRack++
|
||||
}
|
||||
|
||||
// Update analysis after rack moves
|
||||
r.applyMovesToAnalysis(analysis, rackMoves)
|
||||
|
||||
// Step 3: Balance across nodes within each rack
|
||||
nodeMoves := r.planNodeMoves(analysis, dist)
|
||||
for _, move := range nodeMoves {
|
||||
plan.Moves = append(plan.Moves, move)
|
||||
plan.MovesWithinRack++
|
||||
}
|
||||
|
||||
plan.TotalMoves = len(plan.Moves)
|
||||
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// planDCMoves plans moves to balance shards across data centers
|
||||
func (r *Rebalancer) planDCMoves(analysis *TopologyAnalysis, dist *ECDistribution) []ShardMove {
|
||||
var moves []ShardMove
|
||||
|
||||
overDCs := CalculateDCExcess(analysis, dist)
|
||||
underDCs := CalculateUnderservedDCs(analysis, dist)
|
||||
|
||||
underIdx := 0
|
||||
for _, over := range overDCs {
|
||||
for over.Excess > 0 && underIdx < len(underDCs) {
|
||||
destDC := underDCs[underIdx]
|
||||
|
||||
// Find a shard and source node
|
||||
shardID, srcNode := r.pickShardToMove(analysis, over.Nodes)
|
||||
if srcNode == nil {
|
||||
break
|
||||
}
|
||||
|
||||
// Find destination node in target DC
|
||||
destNode := r.pickBestDestination(analysis, destDC, "", dist)
|
||||
if destNode == nil {
|
||||
underIdx++
|
||||
continue
|
||||
}
|
||||
|
||||
moves = append(moves, ShardMove{
|
||||
ShardID: shardID,
|
||||
SourceNode: srcNode,
|
||||
DestNode: destNode,
|
||||
Reason: fmt.Sprintf("balance DC: %s -> %s", srcNode.DataCenter, destDC),
|
||||
})
|
||||
|
||||
over.Excess--
|
||||
analysis.ShardsByDC[srcNode.DataCenter]--
|
||||
analysis.ShardsByDC[destDC]++
|
||||
|
||||
// Check if destDC reached target
|
||||
if analysis.ShardsByDC[destDC] >= dist.TargetShardsPerDC {
|
||||
underIdx++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return moves
|
||||
}
|
||||
|
||||
// planRackMoves plans moves to balance shards across racks within each DC
|
||||
func (r *Rebalancer) planRackMoves(analysis *TopologyAnalysis, dist *ECDistribution) []ShardMove {
|
||||
var moves []ShardMove
|
||||
|
||||
for dc := range analysis.DCToRacks {
|
||||
dcShards := analysis.ShardsByDC[dc]
|
||||
numRacks := len(analysis.DCToRacks[dc])
|
||||
if numRacks == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
targetPerRack := ceilDivide(dcShards, max(numRacks, dist.ReplicationConfig.MinRacksPerDC))
|
||||
|
||||
overRacks := CalculateRackExcess(analysis, dc, targetPerRack)
|
||||
underRacks := CalculateUnderservedRacks(analysis, dc, targetPerRack)
|
||||
|
||||
underIdx := 0
|
||||
for _, over := range overRacks {
|
||||
for over.Excess > 0 && underIdx < len(underRacks) {
|
||||
destRack := underRacks[underIdx]
|
||||
|
||||
// Find shard and source node
|
||||
shardID, srcNode := r.pickShardToMove(analysis, over.Nodes)
|
||||
if srcNode == nil {
|
||||
break
|
||||
}
|
||||
|
||||
// Find destination node in target rack
|
||||
destNode := r.pickBestDestination(analysis, dc, destRack, dist)
|
||||
if destNode == nil {
|
||||
underIdx++
|
||||
continue
|
||||
}
|
||||
|
||||
moves = append(moves, ShardMove{
|
||||
ShardID: shardID,
|
||||
SourceNode: srcNode,
|
||||
DestNode: destNode,
|
||||
Reason: fmt.Sprintf("balance rack: %s -> %s", srcNode.Rack, destRack),
|
||||
})
|
||||
|
||||
over.Excess--
|
||||
analysis.ShardsByRack[srcNode.Rack]--
|
||||
analysis.ShardsByRack[destRack]++
|
||||
|
||||
if analysis.ShardsByRack[destRack] >= targetPerRack {
|
||||
underIdx++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return moves
|
||||
}
|
||||
|
||||
// planNodeMoves plans moves to balance shards across nodes within each rack
|
||||
func (r *Rebalancer) planNodeMoves(analysis *TopologyAnalysis, dist *ECDistribution) []ShardMove {
|
||||
var moves []ShardMove
|
||||
|
||||
for rack, nodes := range analysis.RackToNodes {
|
||||
if len(nodes) <= 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
rackShards := analysis.ShardsByRack[rack]
|
||||
targetPerNode := ceilDivide(rackShards, max(len(nodes), dist.ReplicationConfig.MinNodesPerRack))
|
||||
|
||||
// Find over and under nodes
|
||||
var overNodes []*TopologyNode
|
||||
var underNodes []*TopologyNode
|
||||
|
||||
for _, node := range nodes {
|
||||
count := analysis.ShardsByNode[node.NodeID]
|
||||
if count > targetPerNode {
|
||||
overNodes = append(overNodes, node)
|
||||
} else if count < targetPerNode {
|
||||
underNodes = append(underNodes, node)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by excess/deficit
|
||||
slices.SortFunc(overNodes, func(a, b *TopologyNode) int {
|
||||
return analysis.ShardsByNode[b.NodeID] - analysis.ShardsByNode[a.NodeID]
|
||||
})
|
||||
|
||||
underIdx := 0
|
||||
for _, srcNode := range overNodes {
|
||||
excess := analysis.ShardsByNode[srcNode.NodeID] - targetPerNode
|
||||
|
||||
for excess > 0 && underIdx < len(underNodes) {
|
||||
destNode := underNodes[underIdx]
|
||||
|
||||
// Pick a shard from this node, preferring parity shards
|
||||
shards := analysis.NodeToShards[srcNode.NodeID]
|
||||
if len(shards) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Find a parity shard first, fallback to data shard
|
||||
shardID := -1
|
||||
shardIdx := -1
|
||||
for i, s := range shards {
|
||||
if r.ecConfig.IsParityShard(s) {
|
||||
shardID = s
|
||||
shardIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if shardID == -1 {
|
||||
shardID = shards[0]
|
||||
shardIdx = 0
|
||||
}
|
||||
|
||||
moves = append(moves, ShardMove{
|
||||
ShardID: shardID,
|
||||
SourceNode: srcNode,
|
||||
DestNode: destNode,
|
||||
Reason: fmt.Sprintf("balance node: %s -> %s", srcNode.NodeID, destNode.NodeID),
|
||||
})
|
||||
|
||||
excess--
|
||||
analysis.ShardsByNode[srcNode.NodeID]--
|
||||
analysis.ShardsByNode[destNode.NodeID]++
|
||||
|
||||
// Update shard lists - remove the specific shard we picked
|
||||
analysis.NodeToShards[srcNode.NodeID] = append(
|
||||
shards[:shardIdx], shards[shardIdx+1:]...)
|
||||
analysis.NodeToShards[destNode.NodeID] = append(
|
||||
analysis.NodeToShards[destNode.NodeID], shardID)
|
||||
|
||||
if analysis.ShardsByNode[destNode.NodeID] >= targetPerNode {
|
||||
underIdx++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return moves
|
||||
}
|
||||
|
||||
// pickShardToMove selects a shard and its node from the given nodes.
|
||||
// It prefers to move parity shards first, keeping data shards spread out
|
||||
// since data shards serve read requests while parity shards are only for reconstruction.
|
||||
func (r *Rebalancer) pickShardToMove(analysis *TopologyAnalysis, nodes []*TopologyNode) (int, *TopologyNode) {
|
||||
// Sort by shard count (most shards first)
|
||||
slices.SortFunc(nodes, func(a, b *TopologyNode) int {
|
||||
return analysis.ShardsByNode[b.NodeID] - analysis.ShardsByNode[a.NodeID]
|
||||
})
|
||||
|
||||
// First pass: try to find a parity shard to move (prefer moving parity)
|
||||
for _, node := range nodes {
|
||||
shards := analysis.NodeToShards[node.NodeID]
|
||||
for _, shardID := range shards {
|
||||
if r.ecConfig.IsParityShard(shardID) {
|
||||
return shardID, node
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: if no parity shards, move a data shard
|
||||
for _, node := range nodes {
|
||||
shards := analysis.NodeToShards[node.NodeID]
|
||||
if len(shards) > 0 {
|
||||
return shards[0], node
|
||||
}
|
||||
}
|
||||
|
||||
return -1, nil
|
||||
}
|
||||
|
||||
// pickBestDestination selects the best destination node
|
||||
func (r *Rebalancer) pickBestDestination(analysis *TopologyAnalysis, targetDC, targetRack string, dist *ECDistribution) *TopologyNode {
|
||||
var candidates []*TopologyNode
|
||||
|
||||
// Collect candidates
|
||||
for _, node := range analysis.AllNodes {
|
||||
// Filter by DC if specified
|
||||
if targetDC != "" && node.DataCenter != targetDC {
|
||||
continue
|
||||
}
|
||||
// Filter by rack if specified
|
||||
if targetRack != "" && node.Rack != targetRack {
|
||||
continue
|
||||
}
|
||||
// Check capacity
|
||||
if node.FreeSlots <= 0 {
|
||||
continue
|
||||
}
|
||||
// Check max shards limit
|
||||
if analysis.ShardsByNode[node.NodeID] >= dist.MaxShardsPerNode {
|
||||
continue
|
||||
}
|
||||
|
||||
candidates = append(candidates, node)
|
||||
}
|
||||
|
||||
if len(candidates) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sort by: 1) fewer shards, 2) more free slots
|
||||
slices.SortFunc(candidates, func(a, b *TopologyNode) int {
|
||||
aShards := analysis.ShardsByNode[a.NodeID]
|
||||
bShards := analysis.ShardsByNode[b.NodeID]
|
||||
if aShards != bShards {
|
||||
return aShards - bShards
|
||||
}
|
||||
return b.FreeSlots - a.FreeSlots
|
||||
})
|
||||
|
||||
return candidates[0]
|
||||
}
|
||||
|
||||
// applyMovesToAnalysis is a no-op placeholder for potential future use.
|
||||
// Note: All planners (planDCMoves, planRackMoves, planNodeMoves) update
|
||||
// their respective counts (ShardsByDC, ShardsByRack, ShardsByNode) and
|
||||
// shard lists (NodeToShards) inline during planning. This avoids duplicate
|
||||
// updates that would occur if we also updated counts here.
|
||||
func (r *Rebalancer) applyMovesToAnalysis(analysis *TopologyAnalysis, moves []ShardMove) {
|
||||
// Counts are already updated by the individual planners.
|
||||
// This function is kept for API compatibility and potential future use.
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
if err == nil {
|
||||
v.volumeInfo.Version = uint32(v.SuperBlock.Version)
|
||||
}
|
||||
glog.V(0).Infof("readSuperBlock volume %d version %v", v.Id, v.SuperBlock.Version)
|
||||
glog.V(2).Infof("readSuperBlock volume %d version %v", v.Id, v.SuperBlock.Version)
|
||||
if v.HasRemoteFile() {
|
||||
// maybe temporary network problem
|
||||
glog.Errorf("readSuperBlock remote volume %d: %v", v.Id, err)
|
||||
@@ -149,7 +149,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
// storage tier, and download to local storage, which may cause the
|
||||
// capactiy overloading.
|
||||
if !v.HasRemoteFile() {
|
||||
glog.V(0).Infof("checking volume data integrity for volume %d", v.Id)
|
||||
glog.V(2).Infof("checking volume data integrity for volume %d", v.Id)
|
||||
if v.lastAppendAtNs, err = CheckVolumeDataIntegrity(v, indexFile); err != nil {
|
||||
v.noWriteOrDelete = true
|
||||
glog.V(0).Infof("volumeDataIntegrityChecking failed %v", err)
|
||||
@@ -164,10 +164,10 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
switch needleMapKind {
|
||||
case NeedleMapInMemory:
|
||||
if v.tmpNm != nil {
|
||||
glog.V(0).Infof("updating memory compact index %s ", v.FileName(".idx"))
|
||||
glog.V(2).Infof("updating memory compact index %s ", v.FileName(".idx"))
|
||||
err = v.tmpNm.UpdateNeedleMap(v, indexFile, nil, 0)
|
||||
} else {
|
||||
glog.V(0).Infoln("loading memory index", v.FileName(".idx"), "to memory")
|
||||
glog.V(2).Infoln("loading memory index", v.FileName(".idx"), "to memory")
|
||||
if v.nm, err = LoadCompactNeedleMap(indexFile); err != nil {
|
||||
glog.V(0).Infof("loading index %s to memory error: %v", v.FileName(".idx"), err)
|
||||
}
|
||||
|
||||
@@ -237,15 +237,6 @@ func (t *Topology) NextVolumeId() (needle.VolumeId, error) {
|
||||
if _, err := t.RaftServer.Do(NewMaxVolumeIdCommand(next)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Dual-write to hashicorp raft if available for seamless migration
|
||||
if t.HashicorpRaft != nil {
|
||||
b, err := json.Marshal(NewMaxVolumeIdCommand(next))
|
||||
if err != nil {
|
||||
glog.Warningf("failed to marshal MaxVolumeIdCommand for dual-write: %v", err)
|
||||
} else if future := t.HashicorpRaft.Apply(b, time.Second); future.Error() != nil {
|
||||
glog.Warningf("failed to apply MaxVolumeIdCommand to hashicorp raft for dual-write: %v", future.Error())
|
||||
}
|
||||
}
|
||||
} else if t.HashicorpRaft != nil {
|
||||
b, err := json.Marshal(NewMaxVolumeIdCommand(next))
|
||||
if err != nil {
|
||||
|
||||
@@ -414,7 +414,7 @@ func (vl *VolumeLayout) setVolumeWritable(vid needle.VolumeId) bool {
|
||||
return false
|
||||
}
|
||||
}
|
||||
glog.V(0).Infoln("Volume", vid, "becomes writable")
|
||||
glog.V(1).Infoln("Volume", vid, "becomes writable")
|
||||
vl.writables = append(vl.writables, vid)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(03)
|
||||
MINOR_VERSION = int32(04)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
@@ -165,6 +165,7 @@ func (mc *MasterClient) tryAllMasters(ctx context.Context) {
|
||||
func (mc *MasterClient) tryConnectToMaster(ctx context.Context, master pb.ServerAddress) (nextHintedLeader pb.ServerAddress) {
|
||||
glog.V(1).Infof("%s.%s masterClient Connecting to master %v", mc.FilerGroup, mc.clientType, master)
|
||||
stats.MasterClientConnectCounter.WithLabelValues("total").Inc()
|
||||
connectStartTime := time.Now()
|
||||
gprcErr := pb.WithMasterClient(true, master, mc.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
@@ -175,6 +176,7 @@ func (mc *MasterClient) tryConnectToMaster(ctx context.Context, master pb.Server
|
||||
stats.MasterClientConnectCounter.WithLabelValues(stats.FailedToKeepConnected).Inc()
|
||||
return err
|
||||
}
|
||||
glog.V(0).Infof("%s.%s masterClient gRPC stream established to %s in %v", mc.FilerGroup, mc.clientType, master, time.Since(connectStartTime))
|
||||
|
||||
if err = stream.Send(&master_pb.KeepConnectedRequest{
|
||||
FilerGroup: mc.FilerGroup,
|
||||
@@ -380,14 +382,22 @@ func (mc *MasterClient) WaitUntilConnected(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (mc *MasterClient) KeepConnectedToMaster(ctx context.Context) {
|
||||
glog.V(1).Infof("%s.%s masterClient bootstraps with masters %v", mc.FilerGroup, mc.clientType, mc.masters)
|
||||
glog.V(0).Infof("%s.%s masterClient bootstraps with masters %v", mc.FilerGroup, mc.clientType, mc.masters)
|
||||
reconnectCount := 0
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.V(0).Infof("Connection to masters stopped: %v", ctx.Err())
|
||||
return
|
||||
default:
|
||||
reconnectStart := time.Now()
|
||||
if reconnectCount > 0 {
|
||||
glog.V(0).Infof("%s.%s masterClient reconnection attempt #%d", mc.FilerGroup, mc.clientType, reconnectCount)
|
||||
}
|
||||
mc.tryAllMasters(ctx)
|
||||
reconnectCount++
|
||||
glog.V(1).Infof("%s.%s masterClient connection cycle completed in %v, sleeping before retry",
|
||||
mc.FilerGroup, mc.clientType, time.Since(reconnectStart))
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,3 +102,4 @@ func TestMasterClientFilerGroupLogging(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+167
-105
@@ -74,6 +74,8 @@ type grpcState struct {
|
||||
lastWorkerInfo *types.WorkerData
|
||||
reconnectStop chan struct{}
|
||||
streamExit chan struct{}
|
||||
streamFailed chan struct{} // Signals when stream has failed
|
||||
regWait chan *worker_pb.RegistrationResponse
|
||||
}
|
||||
|
||||
// NewGrpcAdminClient creates a new gRPC admin client
|
||||
@@ -98,6 +100,36 @@ func NewGrpcAdminClient(adminAddress string, workerID string, dialOption grpc.Di
|
||||
return c
|
||||
}
|
||||
|
||||
// drainAndCloseRegWaitChannel drains any pending messages from the regWait channel
|
||||
// and then safely closes it. This prevents losing RegistrationResponse messages
|
||||
// that were sent before the channel is closed.
|
||||
func drainAndCloseRegWaitChannel(ch *chan *worker_pb.RegistrationResponse) {
|
||||
if ch == nil || *ch == nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-*ch:
|
||||
// continue draining until channel is empty
|
||||
default:
|
||||
close(*ch)
|
||||
*ch = nil
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// safeCloseChannel safely closes a channel and sets it to nil to prevent double-close panics.
|
||||
// NOTE: This function is NOT thread-safe. It is safe to use in this codebase because all calls
|
||||
// are serialized within the managerLoop goroutine. If this function is used in concurrent contexts
|
||||
// in the future, synchronization (e.g., sync.Mutex) should be added.
|
||||
func (c *GrpcAdminClient) safeCloseChannel(chPtr *chan struct{}) {
|
||||
if *chPtr != nil {
|
||||
close(*chPtr)
|
||||
*chPtr = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *GrpcAdminClient) managerLoop() {
|
||||
state := &grpcState{shouldReconnect: true}
|
||||
|
||||
@@ -129,7 +161,14 @@ out:
|
||||
req.Resp <- nil
|
||||
continue
|
||||
}
|
||||
err := c.sendRegistration(req.Worker)
|
||||
// Capture channel pointers to avoid race condition with reconnect
|
||||
streamFailedCh := state.streamFailed
|
||||
regWaitCh := state.regWait
|
||||
if streamFailedCh == nil || regWaitCh == nil {
|
||||
req.Resp <- fmt.Errorf("stream not ready for registration")
|
||||
continue
|
||||
}
|
||||
err := c.sendRegistration(req.Worker, streamFailedCh, regWaitCh)
|
||||
req.Resp <- err
|
||||
case ActionQueryConnected:
|
||||
respCh := cmd.data.(chan bool)
|
||||
@@ -211,10 +250,22 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
s.connected = true
|
||||
s.stream = stream
|
||||
|
||||
// Start stream handlers BEFORE sending registration
|
||||
// This ensures handleIncoming is ready to receive the registration response
|
||||
s.streamExit = make(chan struct{})
|
||||
s.streamFailed = make(chan struct{})
|
||||
s.regWait = make(chan *worker_pb.RegistrationResponse, 1)
|
||||
go handleOutgoing(s.stream, s.streamExit, c.outgoing, c.cmds)
|
||||
go handleIncoming(c.workerID, s.stream, s.streamExit, c.incoming, c.cmds, s.streamFailed, s.regWait)
|
||||
|
||||
// Always check for worker info and send registration immediately as the very first message
|
||||
if s.lastWorkerInfo != nil {
|
||||
// Send registration synchronously as the very first message
|
||||
if err := c.sendRegistrationSync(s.lastWorkerInfo, s.stream); err != nil {
|
||||
// Send registration via the normal outgoing channel and wait for response via incoming
|
||||
if err := c.sendRegistration(s.lastWorkerInfo, s.streamFailed, s.regWait); err != nil {
|
||||
c.safeCloseChannel(&s.streamExit)
|
||||
c.safeCloseChannel(&s.streamFailed)
|
||||
drainAndCloseRegWaitChannel(&s.regWait)
|
||||
s.streamCancel()
|
||||
s.conn.Close()
|
||||
s.connected = false
|
||||
return fmt.Errorf("failed to register worker: %w", err)
|
||||
@@ -225,11 +276,6 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
glog.V(1).Infof("Connected to admin server, waiting for worker registration info")
|
||||
}
|
||||
|
||||
// Start stream handlers
|
||||
s.streamExit = make(chan struct{})
|
||||
go handleOutgoing(s.stream, s.streamExit, c.outgoing, c.cmds)
|
||||
go handleIncoming(c.workerID, s.stream, s.streamExit, c.incoming, c.cmds)
|
||||
|
||||
glog.Infof("Connected to admin server at %s", c.adminAddress)
|
||||
return nil
|
||||
}
|
||||
@@ -237,6 +283,9 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
// reconnect attempts to re-establish the connection
|
||||
func (c *GrpcAdminClient) reconnect(s *grpcState) error {
|
||||
// Clean up existing connection completely
|
||||
c.safeCloseChannel(&s.streamExit)
|
||||
c.safeCloseChannel(&s.streamFailed)
|
||||
drainAndCloseRegWaitChannel(&s.regWait)
|
||||
if s.streamCancel != nil {
|
||||
s.streamCancel()
|
||||
}
|
||||
@@ -309,32 +358,70 @@ func handleOutgoing(
|
||||
streamExit <-chan struct{},
|
||||
outgoing <-chan *worker_pb.WorkerMessage,
|
||||
cmds chan<- grpcCommand) {
|
||||
|
||||
msgCh := make(chan *worker_pb.WorkerMessage)
|
||||
msgCh := make(chan *worker_pb.WorkerMessage, 1)
|
||||
errCh := make(chan error, 1) // Buffered to prevent blocking if the manager is busy
|
||||
// Goroutine to handle blocking stream.Recv() and simultaneously handle exit
|
||||
// signals
|
||||
|
||||
// Goroutine that reads from msgCh and performs the blocking stream.Send() calls.
|
||||
go func() {
|
||||
for msg := range msgCh {
|
||||
if err := stream.Send(msg); err != nil {
|
||||
errCh <- err
|
||||
return // Exit the receiver goroutine on error/EOF
|
||||
return
|
||||
}
|
||||
}
|
||||
close(errCh)
|
||||
}()
|
||||
|
||||
for msg := range outgoing {
|
||||
select {
|
||||
case msgCh <- msg:
|
||||
case err := <-errCh:
|
||||
// Helper function to handle stream errors and cleanup
|
||||
handleStreamError := func(err error) {
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to send message to admin: %v", err)
|
||||
cmds <- grpcCommand{action: ActionStreamError, data: err}
|
||||
return
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: err}:
|
||||
// Successfully queued
|
||||
default:
|
||||
// Manager busy, queue asynchronously to avoid blocking
|
||||
glog.V(2).Infof("Manager busy, queuing stream error asynchronously from outgoing handler: %v", err)
|
||||
go func(e error) {
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: e}:
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("Failed to send stream error to manager from outgoing handler, channel blocked: %v", e)
|
||||
}
|
||||
}(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to cleanup resources
|
||||
cleanup := func() {
|
||||
close(msgCh)
|
||||
<-errCh
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-streamExit:
|
||||
close(msgCh)
|
||||
<-errCh
|
||||
cleanup()
|
||||
return
|
||||
case err := <-errCh:
|
||||
handleStreamError(err)
|
||||
return
|
||||
case msg, ok := <-outgoing:
|
||||
if !ok {
|
||||
cleanup()
|
||||
return
|
||||
}
|
||||
select {
|
||||
case msgCh <- msg:
|
||||
// Message queued successfully
|
||||
case <-streamExit:
|
||||
cleanup()
|
||||
return
|
||||
case err := <-errCh:
|
||||
handleStreamError(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -345,10 +432,15 @@ func handleIncoming(
|
||||
stream worker_pb.WorkerService_WorkerStreamClient,
|
||||
streamExit <-chan struct{},
|
||||
incoming chan<- *worker_pb.AdminMessage,
|
||||
cmds chan<- grpcCommand) {
|
||||
cmds chan<- grpcCommand,
|
||||
streamFailed chan<- struct{},
|
||||
regWait chan<- *worker_pb.RegistrationResponse) {
|
||||
glog.V(1).Infof("INCOMING HANDLER STARTED: Worker %s incoming message handler started", workerID)
|
||||
msgCh := make(chan *worker_pb.AdminMessage)
|
||||
errCh := make(chan error, 1) // Buffered to prevent blocking if the manager is busy
|
||||
// regWait is buffered with size 1 so that the registration response can be sent
|
||||
// even if the receiver goroutine has not yet started waiting on the channel.
|
||||
// This non-blocking send pattern avoids a race between sendRegistration and handleIncoming.
|
||||
// Goroutine to handle blocking stream.Recv() and simultaneously handle exit
|
||||
// signals
|
||||
go func() {
|
||||
@@ -370,7 +462,19 @@ func handleIncoming(
|
||||
// Message successfully received from the stream
|
||||
glog.V(4).Infof("MESSAGE RECEIVED: Worker %s received message from admin server: %T", workerID, msg.Message)
|
||||
|
||||
// Route message to waiting goroutines or general handler (original select logic)
|
||||
// If this is a registration response, also publish to the registration waiter.
|
||||
// regWait is buffered (size 1) so that the response can be sent even if sendRegistration
|
||||
// hasn't started waiting yet, preventing a race condition between the two goroutines.
|
||||
if rr := msg.GetRegistrationResponse(); rr != nil {
|
||||
select {
|
||||
case regWait <- rr:
|
||||
glog.V(3).Infof("REGISTRATION RESPONSE: Worker %s routed registration response to waiter", workerID)
|
||||
default:
|
||||
glog.V(2).Infof("REGISTRATION RESPONSE DROPPED: Worker %s registration response dropped (no waiter)", workerID)
|
||||
}
|
||||
}
|
||||
|
||||
// Route message to general handler.
|
||||
select {
|
||||
case incoming <- msg:
|
||||
glog.V(3).Infof("MESSAGE ROUTED: Worker %s successfully routed message to handler", workerID)
|
||||
@@ -386,8 +490,27 @@ func handleIncoming(
|
||||
glog.Errorf("RECEIVE ERROR: Worker %s failed to receive message from admin: %v", workerID, err)
|
||||
}
|
||||
|
||||
// Report the failure as a command to the managerLoop (blocking)
|
||||
cmds <- grpcCommand{action: ActionStreamError, data: err}
|
||||
// Signal that stream has failed (non-blocking)
|
||||
select {
|
||||
case streamFailed <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
|
||||
// Report the failure as a command to the managerLoop.
|
||||
// Try non-blocking first; if the manager is busy and the channel is full,
|
||||
// fall back to an asynchronous blocking send so the error is not lost.
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: err}:
|
||||
default:
|
||||
glog.V(2).Infof("Manager busy, queuing stream error asynchronously: %v", err)
|
||||
go func(e error) {
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: e}:
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("Failed to send stream error to manager, channel blocked: %v", e)
|
||||
}
|
||||
}(err)
|
||||
}
|
||||
|
||||
// Exit the main handler loop
|
||||
glog.V(1).Infof("INCOMING HANDLER STOPPED: Worker %s stopping incoming handler due to stream error", workerID)
|
||||
@@ -419,7 +542,7 @@ func (c *GrpcAdminClient) handleDisconnect(cmd grpcCommand, s *grpcState) {
|
||||
}
|
||||
|
||||
// Send shutdown signal to stop reconnection loop
|
||||
close(s.reconnectStop)
|
||||
c.safeCloseChannel(&s.reconnectStop)
|
||||
|
||||
s.connected = false
|
||||
s.shouldReconnect = false
|
||||
@@ -444,7 +567,9 @@ func (c *GrpcAdminClient) handleDisconnect(cmd grpcCommand, s *grpcState) {
|
||||
}
|
||||
|
||||
// Send shutdown signal to stop handlers loop
|
||||
close(s.streamExit)
|
||||
c.safeCloseChannel(&s.streamExit)
|
||||
c.safeCloseChannel(&s.streamFailed)
|
||||
drainAndCloseRegWaitChannel(&s.regWait)
|
||||
|
||||
// Cancel stream context
|
||||
if s.streamCancel != nil {
|
||||
@@ -456,7 +581,8 @@ func (c *GrpcAdminClient) handleDisconnect(cmd grpcCommand, s *grpcState) {
|
||||
s.conn.Close()
|
||||
}
|
||||
|
||||
// Close channels
|
||||
// Close channels to signal all goroutines to stop
|
||||
// This will cause any pending sends/receives to fail gracefully
|
||||
close(c.outgoing)
|
||||
close(c.incoming)
|
||||
|
||||
@@ -479,7 +605,7 @@ func (c *GrpcAdminClient) RegisterWorker(worker *types.WorkerData) error {
|
||||
}
|
||||
|
||||
// sendRegistration sends the registration message and waits for response
|
||||
func (c *GrpcAdminClient) sendRegistration(worker *types.WorkerData) error {
|
||||
func (c *GrpcAdminClient) sendRegistration(worker *types.WorkerData, streamFailed <-chan struct{}, regWait <-chan *worker_pb.RegistrationResponse) error {
|
||||
capabilities := make([]string, len(worker.Capabilities))
|
||||
for i, cap := range worker.Capabilities {
|
||||
capabilities[i] = string(cap)
|
||||
@@ -503,95 +629,31 @@ func (c *GrpcAdminClient) sendRegistration(worker *types.WorkerData) error {
|
||||
case c.outgoing <- msg:
|
||||
case <-time.After(5 * time.Second):
|
||||
return fmt.Errorf("failed to send registration message: timeout")
|
||||
case <-streamFailed:
|
||||
return fmt.Errorf("stream failed before registration message could be sent")
|
||||
}
|
||||
|
||||
// Wait for registration response
|
||||
timeout := time.NewTimer(10 * time.Second)
|
||||
// Use longer timeout for reconnections since admin server might be busy
|
||||
timeout := time.NewTimer(30 * time.Second)
|
||||
defer timeout.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case response := <-c.incoming:
|
||||
if regResp := response.GetRegistrationResponse(); regResp != nil {
|
||||
if regResp.Success {
|
||||
glog.Infof("Worker registered successfully: %s", regResp.Message)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("registration failed: %s", regResp.Message)
|
||||
case regResp, ok := <-regWait:
|
||||
if !ok || regResp == nil {
|
||||
return fmt.Errorf("registration failed: channel closed unexpectedly")
|
||||
}
|
||||
case <-timeout.C:
|
||||
return fmt.Errorf("registration timeout")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sendRegistrationSync sends the registration message synchronously
|
||||
func (c *GrpcAdminClient) sendRegistrationSync(worker *types.WorkerData, stream worker_pb.WorkerService_WorkerStreamClient) error {
|
||||
capabilities := make([]string, len(worker.Capabilities))
|
||||
for i, cap := range worker.Capabilities {
|
||||
capabilities[i] = string(cap)
|
||||
}
|
||||
|
||||
msg := &worker_pb.WorkerMessage{
|
||||
WorkerId: c.workerID,
|
||||
Timestamp: time.Now().Unix(),
|
||||
Message: &worker_pb.WorkerMessage_Registration{
|
||||
Registration: &worker_pb.WorkerRegistration{
|
||||
WorkerId: c.workerID,
|
||||
Address: worker.Address,
|
||||
Capabilities: capabilities,
|
||||
MaxConcurrent: int32(worker.MaxConcurrent),
|
||||
Metadata: make(map[string]string),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Send directly to stream to ensure it's the first message
|
||||
if err := stream.Send(msg); err != nil {
|
||||
return fmt.Errorf("failed to send registration message: %w", err)
|
||||
}
|
||||
|
||||
// Create a channel to receive the response
|
||||
responseChan := make(chan *worker_pb.AdminMessage, 1)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
// Start a goroutine to listen for the response
|
||||
go func() {
|
||||
for {
|
||||
response, err := stream.Recv()
|
||||
if err != nil {
|
||||
errChan <- fmt.Errorf("failed to receive registration response: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
if regResp := response.GetRegistrationResponse(); regResp != nil {
|
||||
responseChan <- response
|
||||
return
|
||||
}
|
||||
// Continue waiting if it's not a registration response
|
||||
// If stream is stuck, reconnect() will kill it, cleaning up this
|
||||
// goroutine
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for registration response with timeout
|
||||
timeout := time.NewTimer(10 * time.Second)
|
||||
defer timeout.Stop()
|
||||
|
||||
select {
|
||||
case response := <-responseChan:
|
||||
if regResp := response.GetRegistrationResponse(); regResp != nil {
|
||||
if regResp.Success {
|
||||
glog.V(1).Infof("Worker registered successfully: %s", regResp.Message)
|
||||
glog.Infof("Worker registered successfully: %s", regResp.Message)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("registration failed: %s", regResp.Message)
|
||||
case <-streamFailed:
|
||||
return fmt.Errorf("registration failed: stream closed by server")
|
||||
case <-timeout.C:
|
||||
return fmt.Errorf("registration failed: timeout waiting for response")
|
||||
}
|
||||
return fmt.Errorf("unexpected response type")
|
||||
case err := <-errChan:
|
||||
return err
|
||||
case <-timeout.C:
|
||||
return fmt.Errorf("registration timeout")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user