mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-25 21:57:05 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a154ef9a0f | ||
|
|
6d00d84721 | ||
|
|
29255f286e | ||
|
|
499ab47eaa | ||
|
|
43cdd22133 | ||
|
|
20a2e672d2 | ||
|
|
1668c1042b | ||
|
|
69c49859fa | ||
|
|
f234455b76 | ||
|
|
b2fd31c08b | ||
|
|
c56a0a0ebd | ||
|
|
fb46a8a61f | ||
|
|
bdc20d1c1e | ||
|
|
b7e3284fc5 | ||
|
|
f096b067fd | ||
|
|
5ab49e2971 | ||
|
|
58acc14d2c | ||
|
|
f00ae727b7 | ||
|
|
d745e6e41d | ||
|
|
9f07bca9cc | ||
|
|
5810aba763 | ||
|
|
ba07b3e4c6 | ||
|
|
f5a57a6463 | ||
|
|
a6da3eb770 | ||
|
|
db35159a41 | ||
|
|
d00a2a8707 | ||
|
|
8a032bf57d | ||
|
|
9b6b564235 | ||
|
|
7e624d5355 | ||
|
|
eaecd8328b | ||
|
|
d4790cb8e6 | ||
|
|
ed023f4a7d | ||
|
|
ec4f7cf33c | ||
|
|
85bd593936 | ||
|
|
d19eca71eb | ||
|
|
20e0d91037 | ||
|
|
b8bef0328b | ||
|
|
7d26c8838f | ||
|
|
b7ba6785a2 | ||
|
|
208d7f24f4 | ||
|
|
decfb07eea | ||
|
|
f82c69b9a5 |
No files matched your search
@@ -45,7 +45,7 @@ jobs:
|
||||
run: ct lint --target-branch ${{ github.event.repository.default_branch }} --all --validate-maintainers=false --chart-dirs k8s/charts
|
||||
|
||||
- name: Create kind cluster
|
||||
uses: helm/kind-action@v1.12.0
|
||||
uses: helm/kind-action@v1.13.0
|
||||
|
||||
- name: Run chart-testing (install)
|
||||
run: ct install --target-branch ${{ github.event.repository.default_branch }} --all --chart-dirs k8s/charts
|
||||
@@ -77,3 +77,12 @@ jobs:
|
||||
aws --no-verify-ssl s3 cp --no-progress s3://bucket/test-multipart downloaded
|
||||
diff -q generated downloaded
|
||||
rm -f generated downloaded
|
||||
|
||||
- name: Test GetObject with If-Match
|
||||
run: |
|
||||
set -e
|
||||
dd if=/dev/urandom of=generated bs=1M count=32
|
||||
ETAG=$(aws --no-verify-ssl s3api put-object --bucket bucket --key test-get-obj --body generated | jq -r .ETag)
|
||||
aws --no-verify-ssl s3api get-object --bucket bucket --key test-get-obj --if-match ${ETAG:1:32} downloaded
|
||||
diff -q generated downloaded
|
||||
rm -f generated downloaded
|
||||
@@ -15,7 +15,11 @@ COPY --from=builder /go/bin/weed /usr/bin/
|
||||
RUN mkdir -p /etc/seaweedfs
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer.toml /etc/seaweedfs/filer.toml
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
|
||||
RUN apk add fuse # for weed mount
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk add --no-cache fuse && \
|
||||
addgroup -g 1000 seaweed && \
|
||||
adduser -D -u 1000 -G seaweed seaweed
|
||||
|
||||
# volume server gprc port
|
||||
EXPOSE 18080
|
||||
@@ -34,11 +38,16 @@ EXPOSE 8333
|
||||
# webdav server http port
|
||||
EXPOSE 7333
|
||||
|
||||
RUN mkdir -p /data/filerldb2
|
||||
# Create data directory and set proper ownership for seaweed user
|
||||
RUN mkdir -p /data/filerldb2 && \
|
||||
chown -R seaweed:seaweed /data && \
|
||||
chown -R seaweed:seaweed /etc/seaweedfs && \
|
||||
chmod 755 /entrypoint.sh
|
||||
|
||||
VOLUME /data
|
||||
WORKDIR /data
|
||||
|
||||
RUN chmod +x /entrypoint.sh
|
||||
# Switch to non-root user
|
||||
USER seaweed
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
+12
-4
@@ -6,8 +6,11 @@ COPY ./weed_sub* /usr/bin/
|
||||
RUN mkdir -p /etc/seaweedfs
|
||||
COPY ./filer.toml /etc/seaweedfs/filer.toml
|
||||
COPY ./entrypoint.sh /entrypoint.sh
|
||||
RUN apk add fuse # for weed mount
|
||||
RUN apk add curl # for health checks
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk add --no-cache fuse curl && \
|
||||
addgroup -g 1000 seaweed && \
|
||||
adduser -D -u 1000 -G seaweed seaweed
|
||||
|
||||
# volume server grpc port
|
||||
EXPOSE 18080
|
||||
@@ -26,11 +29,16 @@ EXPOSE 8333
|
||||
# webdav server http port
|
||||
EXPOSE 7333
|
||||
|
||||
RUN mkdir -p /data/filerldb2
|
||||
# Create data directory and set proper ownership for seaweed user
|
||||
RUN mkdir -p /data/filerldb2 && \
|
||||
chown -R seaweed:seaweed /data && \
|
||||
chown -R seaweed:seaweed /etc/seaweedfs && \
|
||||
chmod 755 /entrypoint.sh
|
||||
|
||||
VOLUME /data
|
||||
WORKDIR /data
|
||||
|
||||
RUN chmod +x /entrypoint.sh
|
||||
# Switch to non-root user
|
||||
USER seaweed
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
@@ -32,7 +32,11 @@ COPY --from=builder /go/bin/weed /usr/bin/
|
||||
RUN mkdir -p /etc/seaweedfs
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer_rocksdb.toml /etc/seaweedfs/filer.toml
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
|
||||
RUN apk add fuse snappy gflags
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk add --no-cache fuse snappy gflags && \
|
||||
addgroup -g 1000 seaweed && \
|
||||
adduser -D -u 1000 -G seaweed seaweed
|
||||
|
||||
# volume server gprc port
|
||||
EXPOSE 18080
|
||||
@@ -51,12 +55,17 @@ EXPOSE 8333
|
||||
# webdav server http port
|
||||
EXPOSE 7333
|
||||
|
||||
RUN mkdir -p /data/filer_rocksdb
|
||||
# Create data directory and set proper ownership for seaweed user
|
||||
RUN mkdir -p /data/filer_rocksdb && \
|
||||
chown -R seaweed:seaweed /data && \
|
||||
chown -R seaweed:seaweed /etc/seaweedfs && \
|
||||
chmod 755 /entrypoint.sh
|
||||
|
||||
VOLUME /data
|
||||
|
||||
WORKDIR /data
|
||||
|
||||
RUN chmod +x /entrypoint.sh
|
||||
# Switch to non-root user
|
||||
USER seaweed
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
@@ -15,7 +15,11 @@ COPY --from=builder /go/bin/weed /usr/bin/
|
||||
RUN mkdir -p /etc/seaweedfs
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer_rocksdb.toml /etc/seaweedfs/filer.toml
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
|
||||
RUN apk add fuse snappy gflags tmux
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk add --no-cache fuse snappy gflags tmux && \
|
||||
addgroup -g 1000 seaweed && \
|
||||
adduser -D -u 1000 -G seaweed seaweed
|
||||
|
||||
# volume server gprc port
|
||||
EXPOSE 18080
|
||||
@@ -34,12 +38,17 @@ EXPOSE 8333
|
||||
# webdav server http port
|
||||
EXPOSE 7333
|
||||
|
||||
RUN mkdir -p /data/filer_rocksdb
|
||||
# Create data directory and set proper ownership for seaweed user
|
||||
RUN mkdir -p /data/filer_rocksdb && \
|
||||
chown -R seaweed:seaweed /data && \
|
||||
chown -R seaweed:seaweed /etc/seaweedfs && \
|
||||
chmod 755 /entrypoint.sh
|
||||
|
||||
VOLUME /data
|
||||
|
||||
WORKDIR /data
|
||||
|
||||
RUN chmod +x /entrypoint.sh
|
||||
# Switch to non-root user
|
||||
USER seaweed
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
@@ -7,7 +7,7 @@ toolchain go1.24.1
|
||||
require (
|
||||
cloud.google.com/go v0.121.6 // indirect
|
||||
cloud.google.com/go/pubsub v1.50.1
|
||||
cloud.google.com/go/storage v1.57.0
|
||||
cloud.google.com/go/storage v1.57.1
|
||||
github.com/Shopify/sarama v1.38.1
|
||||
github.com/aws/aws-sdk-go v1.55.8
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
@@ -125,10 +125,10 @@ require (
|
||||
github.com/a-h/templ v0.3.943
|
||||
github.com/arangodb/go-driver v1.6.7
|
||||
github.com/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.39.4
|
||||
github.com/aws/aws-sdk-go-v2 v1.39.5
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.18.19
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.88.3
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.89.1
|
||||
github.com/cognusion/imaging v1.0.2
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
github.com/getsentry/sentry-go v0.36.1
|
||||
@@ -259,17 +259,17 @@ require (
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.11 // 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.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.8.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.12 // 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.29.8 // indirect
|
||||
@@ -464,7 +464,4 @@ require (
|
||||
storj.io/uplink v1.13.1 // indirect
|
||||
)
|
||||
|
||||
// Use the seaweedfs fork of cockroachdb-parser to fix cross-platform build issues
|
||||
replace github.com/cockroachdb/cockroachdb-parser => github.com/seaweedfs/cockroachdb-parser v0.0.0-20251021182748-d0c58c67297e
|
||||
|
||||
// replace github.com/seaweedfs/raft => /Users/chrislu/go/src/github.com/seaweedfs/raft
|
||||
@@ -477,8 +477,8 @@ cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq
|
||||
cloud.google.com/go/storage v1.23.0/go.mod h1:vOEEDNFnciUMhBeT6hsJIn3ieU5cFRmzeLgDvXzfIXc=
|
||||
cloud.google.com/go/storage v1.27.0/go.mod h1:x9DOL8TK/ygDUMieqwfhdpQryTeEkhGKMi80i/iqR2s=
|
||||
cloud.google.com/go/storage v1.28.1/go.mod h1:Qnisd4CqDdo6BGs2AD5LLnEsmSQ80wQ5ogcBBKhU86Y=
|
||||
cloud.google.com/go/storage v1.57.0 h1:4g7NB7Ta7KetVbOMpCqy89C+Vg5VE8scqlSHUPm7Rds=
|
||||
cloud.google.com/go/storage v1.57.0/go.mod h1:329cwlpzALLgJuu8beyJ/uvQznDHpa2U5lGjWednkzg=
|
||||
cloud.google.com/go/storage v1.57.1 h1:gzao6odNJ7dR3XXYvAgPK+Iw4fVPPznEPPyNjbaVkq8=
|
||||
cloud.google.com/go/storage v1.57.1/go.mod h1:329cwlpzALLgJuu8beyJ/uvQznDHpa2U5lGjWednkzg=
|
||||
cloud.google.com/go/storagetransfer v1.5.0/go.mod h1:dxNzUopWy7RQevYFHewchb29POFv3/AaBgnhqzqiK0w=
|
||||
cloud.google.com/go/storagetransfer v1.6.0/go.mod h1:y77xm4CQV/ZhFZH75PLEXY0ROiS7Gh6pSKrM8dJyg6I=
|
||||
cloud.google.com/go/storagetransfer v1.7.0/go.mod h1:8Giuj1QNb1kfLAiWM1bN6dHzfdlDAVC9rv9abHot2W4=
|
||||
@@ -664,10 +664,10 @@ 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.39.4 h1:qTsQKcdQPHnfGYBBs+Btl8QwxJeoWcOcPcixK90mRhg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.39.4/go.mod h1:yWSxrnioGUZ4WVv9TgMrNUeLV3PFESn/v+6T/Su8gnM=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.1 h1:i8p8P4diljCr60PpJp6qZXNlgX4m2yQFpYk+9ZT+J4E=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.1/go.mod h1:ddqbooRZYNoJ2dsTwOty16rM+/Aqmk/GOXrK8cg7V00=
|
||||
github.com/aws/aws-sdk-go-v2 v1.39.5 h1:e/SXuia3rkFtapghJROrydtQpfQaaUgd1cUvyO1mp2w=
|
||||
github.com/aws/aws-sdk-go-v2 v1.39.5/go.mod h1:yWSxrnioGUZ4WVv9TgMrNUeLV3PFESn/v+6T/Su8gnM=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.2 h1:t9yYsydLYNBk9cJ73rgPhPWqOh/52fcWDQB5b1JsKSY=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.2/go.mod h1:IusfVNTmiSN3t4rhxWFaBAqn+mcNdwKtPcV16eYdgko=
|
||||
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.18.19 h1:Jc1zzwkSY1QbkEcLujwqRTXOdvW8ppND3jRBb/VhBQc=
|
||||
@@ -676,24 +676,24 @@ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.11 h1:X7X4YKb+c0rkI6d4uJ5tEM
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.11/go.mod h1:EqM6vPZQsZHYvC4Cai35UDg/f5NCEU+vp0WfbVqVcZc=
|
||||
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.11 h1:7AANQZkF3ihM8fbdftpjhken0TP9sBzFbV/Ze/Y4HXA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.11/go.mod h1:NTF4QCGkm6fzVwncpkFQqoquQyOolcyXfbpC98urj+c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.11 h1:ShdtWUZT37LCAA4Mw2kJAJtzaszfSHFb5n25sdcv4YE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.11/go.mod h1:7bUb2sSr2MZ3M/N+VyETLTQtInemHXb/Fl3s8CLzm0Y=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.12 h1:p/9flfXdoAnwJnuW9xHEAFY22R3A6skYkW19JFF9F+8=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.12/go.mod h1:ZTLHakoVCTtW8AaLGSwJ3LXqHD9uQKnOcv1TrpO6u2k=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.12 h1:2lTWFvRcnWFFLzHWmtddu5MTchc5Oj2OOey++99tPZ0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.12/go.mod h1:hI92pK+ho8HVcWMHKHrK3Uml4pfG7wvL86FzO0LVtQQ=
|
||||
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/v4a v1.4.9 h1:w9LnHqTq8MEdlnyhV4Bwfizd65lfNCNgdlNC6mM5paE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.9/go.mod h1:LGEP6EK4nj+bwWNdrvX/FnDTFowdBNwcSPuZu/ouFys=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.12 h1:itu4KHu8JK/N6NcLIISlf3LL1LccMqruLUXZ9y7yBZw=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.12/go.mod h1:i+6vTU3xziikTY3vcox23X8pPGW5X3wVgd1VZ7ha+x8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.2 h1:xtuxji5CS0JknaXoACOunXOYOQzgfTvGAc9s2QdCJA4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.2/go.mod h1:zxwi0DIR0rcRcgdbl7E2MSOvxDyyXGBlScvBkARFaLQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.8.9 h1:by3nYZLR9l8bUH7kgaMU4dJgYFjyRdFEfORlDpPILB4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.8.9/go.mod h1:IWjQYlqw4EX9jw2g3qnEPPWvCE6bS8fKzhMed1OK7c8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.11 h1:GpMf3z2KJa4RnJ0ew3Hac+hRFYLZ9DDjfgXjuW+pB54=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.11/go.mod h1:6MZP3ZI4QQsgUCFTwMZA2V0sEriNQ8k2hmoHF3qjimQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.9 h1:wuZ5uW2uhJR63zwNlqWH2W4aL4ZjeJP3o92/W+odDY4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.9/go.mod h1:/G58M2fGszCrOzvJUkDdY8O9kycodunH4VdT5oBAqls=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.88.3 h1:P18I4ipbk+b/3dZNq5YYh+Hq6XC0vp5RWkLp1tJldDA=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.88.3/go.mod h1:Rm3gw2Jov6e6kDuamDvyIlZJDMYk97VeCZ82wz/mVZ0=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.3 h1:NEe7FaViguRQEm8zl8Ay/kC/QRsMtWUiCGZajQIsLdc=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.3/go.mod h1:JLuCKu5VfiLBBBl/5IzZILU7rxS0koQpHzMOCzycOJU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.12 h1:MM8imH7NZ0ovIVX7D2RxfMDv7Jt9OiUXkcQ+GqywA7M=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.12/go.mod h1:gf4OGwdNkbEsb7elw2Sy76odfhwNktWII3WgvQgQQ6w=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.12 h1:R3uW0iKl8rgNEXNjVGliW/oMEh9fO/LlUEV8RvIFr1I=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.12/go.mod h1:XEttbEr5yqsw8ebi7vlDoGJJjMXRez4/s9pibpJyL5s=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.89.1 h1:Dq82AV+Qxpno/fG162eAhnD8d48t9S+GZCfz7yv1VeA=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.89.1/go.mod h1:MbKLznDKpf7PnSonNRUVYZzfP0CeLkRIUexeblgKcU4=
|
||||
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=
|
||||
|
||||
@@ -3,4 +3,4 @@ description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "3.99"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.0.399
|
||||
version: 4.0.400
|
||||
@@ -392,10 +392,12 @@ spec:
|
||||
nodeSelector:
|
||||
{{ tpl .Values.filer.nodeSelector . | indent 8 | trim }}
|
||||
{{- end }}
|
||||
{{- if and (.Values.filer.enablePVC) (eq .Values.filer.data.type "persistentVolumeClaim") }}
|
||||
{{- if and (.Values.filer.enablePVC) (not .Values.filer.data) }}
|
||||
# DEPRECATION: Deprecate in favor of filer.data section below
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
- apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: data-filer
|
||||
spec:
|
||||
accessModes:
|
||||
@@ -411,7 +413,9 @@ spec:
|
||||
{{- if $pvc_exists }}
|
||||
volumeClaimTemplates:
|
||||
{{- if eq .Values.filer.data.type "persistentVolumeClaim" }}
|
||||
- metadata:
|
||||
- apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: data-filer
|
||||
{{- with .Values.filer.data.annotations }}
|
||||
annotations:
|
||||
@@ -425,7 +429,9 @@ spec:
|
||||
storage: {{ .Values.filer.data.size }}
|
||||
{{- end }}
|
||||
{{- if eq .Values.filer.logs.type "persistentVolumeClaim" }}
|
||||
- metadata:
|
||||
- apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: seaweedfs-filer-log-volume
|
||||
{{- with .Values.filer.logs.annotations }}
|
||||
annotations:
|
||||
|
||||
@@ -327,7 +327,9 @@ spec:
|
||||
{{- if $pvc_exists }}
|
||||
volumeClaimTemplates:
|
||||
{{- if eq .Values.master.data.type "persistentVolumeClaim"}}
|
||||
- metadata:
|
||||
- apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: data-{{ .Release.Namespace }}
|
||||
{{- with .Values.master.data.annotations }}
|
||||
annotations:
|
||||
@@ -341,7 +343,9 @@ spec:
|
||||
storage: {{ .Values.master.data.size }}
|
||||
{{- end }}
|
||||
{{- if eq .Values.master.logs.type "persistentVolumeClaim"}}
|
||||
- metadata:
|
||||
- apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: seaweedfs-master-log-volume
|
||||
{{- with .Values.master.logs.annotations }}
|
||||
annotations:
|
||||
|
||||
@@ -873,7 +873,7 @@ filer:
|
||||
# anonymousRead: false
|
||||
|
||||
s3:
|
||||
enabled: true
|
||||
enabled: false
|
||||
imageOverride: null
|
||||
restartPolicy: null
|
||||
replicas: 1
|
||||
|
||||
@@ -398,13 +398,15 @@ func TestCORSHeaderMatching(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCORSWithoutConfiguration tests CORS behavior when no configuration is set
|
||||
// TestCORSWithoutConfiguration tests CORS behavior when no bucket-level configuration is set
|
||||
// With the fallback feature, buckets without explicit CORS config will use the global CORS settings
|
||||
func TestCORSWithoutConfiguration(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := createTestBucket(t, client)
|
||||
defer cleanupTestBucket(t, client, bucketName)
|
||||
|
||||
// Test preflight request without CORS configuration
|
||||
// Test preflight request without bucket-level CORS configuration
|
||||
// The global CORS fallback (default: "*") should be used
|
||||
httpClient := &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
|
||||
@@ -412,15 +414,16 @@ func TestCORSWithoutConfiguration(t *testing.T) {
|
||||
|
||||
req.Header.Set("Origin", "https://example.com")
|
||||
req.Header.Set("Access-Control-Request-Method", "GET")
|
||||
req.Header.Set("Access-Control-Request-Headers", "Content-Type")
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
require.NoError(t, err, "Should be able to send OPTIONS request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Without CORS configuration, CORS headers should not be present
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"), "Should not have Allow-Origin header without CORS config")
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Methods"), "Should not have Allow-Methods header without CORS config")
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Headers"), "Should not have Allow-Headers header without CORS config")
|
||||
// With fallback CORS (global default: "*"), CORS headers should be present
|
||||
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have Allow-Origin header from global fallback")
|
||||
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Methods"), "GET", "Should have GET in Allow-Methods from global fallback")
|
||||
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Headers"), "Content-Type", "Should have requested headers in Allow-Headers from global fallback")
|
||||
}
|
||||
|
||||
// TestCORSMethodMatching tests method matching
|
||||
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
// matchesCollection checks if a volume/EC volume collection matches the filter collection.
|
||||
// Handles the special case where empty collection ("") represents the "default" collection.
|
||||
func matchesCollection(volumeCollection, filterCollection string) bool {
|
||||
// Both empty means default collection matches default filter
|
||||
if volumeCollection == "" && filterCollection == "" {
|
||||
// Handle special case where "default" filter matches empty collection
|
||||
if filterCollection == "default" && volumeCollection == "" {
|
||||
return true
|
||||
}
|
||||
// Direct string match for named collections
|
||||
@@ -68,7 +68,7 @@ func (s *AdminServer) GetClusterEcShards(page int, pageSize int, sortBy string,
|
||||
|
||||
// Create individual shard entries for each shard this server has
|
||||
shardBits := ecShardInfo.EcIndexBits
|
||||
for shardId := 0; shardId < erasure_coding.TotalShardsCount; shardId++ {
|
||||
for shardId := 0; shardId < erasure_coding.MaxShardCount; shardId++ {
|
||||
if (shardBits & (1 << uint(shardId))) != 0 {
|
||||
// Mark this shard as present for this volume
|
||||
volumeShardsMap[volumeId][shardId] = true
|
||||
@@ -112,6 +112,7 @@ func (s *AdminServer) GetClusterEcShards(page int, pageSize int, sortBy string,
|
||||
shardCount := len(shardsPresent)
|
||||
|
||||
// Find which shards are missing for this volume across ALL servers
|
||||
// Uses default 10+4 (14 total shards)
|
||||
for shardId := 0; shardId < erasure_coding.TotalShardsCount; shardId++ {
|
||||
if !shardsPresent[shardId] {
|
||||
missingShards = append(missingShards, shardId)
|
||||
@@ -332,7 +333,7 @@ func (s *AdminServer) GetClusterEcVolumes(page int, pageSize int, sortBy string,
|
||||
|
||||
// Process each shard this server has for this volume
|
||||
shardBits := ecShardInfo.EcIndexBits
|
||||
for shardId := 0; shardId < erasure_coding.TotalShardsCount; shardId++ {
|
||||
for shardId := 0; shardId < erasure_coding.MaxShardCount; shardId++ {
|
||||
if (shardBits & (1 << uint(shardId))) != 0 {
|
||||
// Record shard location
|
||||
volume.ShardLocations[shardId] = node.Id
|
||||
@@ -392,7 +393,7 @@ func (s *AdminServer) GetClusterEcVolumes(page int, pageSize int, sortBy string,
|
||||
for _, volume := range volumeData {
|
||||
volume.TotalShards = len(volume.ShardLocations)
|
||||
|
||||
// Find missing shards
|
||||
// Find missing shards (default 10+4 = 14 total shards)
|
||||
var missingShards []int
|
||||
for shardId := 0; shardId < erasure_coding.TotalShardsCount; shardId++ {
|
||||
if _, exists := volume.ShardLocations[shardId]; !exists {
|
||||
@@ -523,7 +524,7 @@ func sortEcVolumes(volumes []EcVolumeWithShards, sortBy string, sortOrder string
|
||||
// getShardCount returns the number of shards represented by the bitmap
|
||||
func getShardCount(ecIndexBits uint32) int {
|
||||
count := 0
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
for i := 0; i < erasure_coding.MaxShardCount; i++ {
|
||||
if (ecIndexBits & (1 << uint(i))) != 0 {
|
||||
count++
|
||||
}
|
||||
@@ -532,6 +533,7 @@ func getShardCount(ecIndexBits uint32) int {
|
||||
}
|
||||
|
||||
// getMissingShards returns a slice of missing shard IDs for a volume
|
||||
// Assumes default 10+4 EC configuration (14 total shards)
|
||||
func getMissingShards(ecIndexBits uint32) []int {
|
||||
var missing []int
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
@@ -614,7 +616,7 @@ func (s *AdminServer) GetEcVolumeDetails(volumeID uint32, sortBy string, sortOrd
|
||||
|
||||
// Create individual shard entries for each shard this server has
|
||||
shardBits := ecShardInfo.EcIndexBits
|
||||
for shardId := 0; shardId < erasure_coding.TotalShardsCount; shardId++ {
|
||||
for shardId := 0; shardId < erasure_coding.MaxShardCount; shardId++ {
|
||||
if (shardBits & (1 << uint(shardId))) != 0 {
|
||||
ecShard := EcShardWithInfo{
|
||||
VolumeID: ecShardInfo.Id,
|
||||
@@ -698,6 +700,7 @@ func (s *AdminServer) GetEcVolumeDetails(volumeID uint32, sortBy string, sortOrd
|
||||
}
|
||||
|
||||
totalUniqueShards := len(foundShards)
|
||||
// Check completeness using default 10+4 (14 total shards)
|
||||
isComplete := (totalUniqueShards == erasure_coding.TotalShardsCount)
|
||||
|
||||
// Calculate missing shards
|
||||
|
||||
@@ -170,12 +170,6 @@ func (h *ClusterHandlers) ShowCollectionDetails(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Map "default" collection to empty string for backend filtering
|
||||
actualCollectionName := collectionName
|
||||
if collectionName == "default" {
|
||||
actualCollectionName = ""
|
||||
}
|
||||
|
||||
// Parse query parameters
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "25"))
|
||||
@@ -183,7 +177,7 @@ func (h *ClusterHandlers) ShowCollectionDetails(c *gin.Context) {
|
||||
sortOrder := c.DefaultQuery("sort_order", "asc")
|
||||
|
||||
// Get collection details data (volumes and EC volumes)
|
||||
collectionDetailsData, err := h.adminServer.GetCollectionDetails(actualCollectionName, page, pageSize, sortBy, sortOrder)
|
||||
collectionDetailsData, err := h.adminServer.GetCollectionDetails(collectionName, page, pageSize, sortBy, sortOrder)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get collection details: " + err.Error()})
|
||||
return
|
||||
|
||||
@@ -46,7 +46,6 @@ func (h *MaintenanceHandlers) ShowTaskDetail(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
c.Header("Content-Type", "text/html")
|
||||
taskDetailComponent := app.TaskDetail(taskDetail)
|
||||
layoutComponent := layout.Layout(c, taskDetailComponent)
|
||||
|
||||
@@ -306,25 +306,21 @@ func (s *MaintenanceIntegration) CanScheduleWithTaskSchedulers(task *Maintenance
|
||||
return false // Fallback to existing logic for unknown types
|
||||
}
|
||||
|
||||
|
||||
// Convert task objects
|
||||
taskObject := s.convertTaskToTaskSystem(task)
|
||||
if taskObject == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
runningTaskObjects := s.convertTasksToTaskSystem(runningTasks)
|
||||
workerObjects := s.convertWorkersToTaskSystem(availableWorkers)
|
||||
|
||||
|
||||
// Get the appropriate scheduler
|
||||
scheduler := s.taskRegistry.GetScheduler(taskType)
|
||||
if scheduler == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
canSchedule := scheduler.CanScheduleNow(taskObject, runningTaskObjects, workerObjects)
|
||||
|
||||
return canSchedule
|
||||
|
||||
@@ -113,10 +113,17 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
for _, host := range data.VolumeServers {
|
||||
<tr>
|
||||
<td>
|
||||
<a href={templ.SafeURL(fmt.Sprintf("http://%s/ui/index.html", host.PublicURL))} target="_blank" class="text-decoration-none">
|
||||
{host.Address}
|
||||
<i class="fas fa-external-link-alt ms-1 text-muted"></i>
|
||||
</a>
|
||||
if host.PublicURL != "" {
|
||||
<a href={templ.SafeURL(fmt.Sprintf("http://%s/ui/index.html", host.PublicURL))} target="_blank" class="text-decoration-none">
|
||||
{host.Address}
|
||||
<i class="fas fa-external-link-alt ms-1 text-muted"></i>
|
||||
</a>
|
||||
} else {
|
||||
<a href={templ.SafeURL(fmt.Sprintf("http://%s/ui/index.html", host.Address))} target="_blank" class="text-decoration-none">
|
||||
{host.Address}
|
||||
<i class="fas fa-external-link-alt ms-1 text-muted"></i>
|
||||
</a>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge bg-light text-dark">{host.DataCenter}</span>
|
||||
@@ -165,24 +172,45 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<button type="button"
|
||||
class="btn btn-outline-primary btn-sm"
|
||||
title="View Details"
|
||||
data-action="view-details"
|
||||
data-id={host.ID}
|
||||
data-address={host.Address}
|
||||
data-public-url={host.PublicURL}
|
||||
data-datacenter={host.DataCenter}
|
||||
data-rack={host.Rack}
|
||||
data-volumes={fmt.Sprintf("%d", host.Volumes)}
|
||||
data-max-volumes={fmt.Sprintf("%d", host.MaxVolumes)}
|
||||
data-disk-usage={fmt.Sprintf("%d", host.DiskUsage)}
|
||||
data-disk-capacity={fmt.Sprintf("%d", host.DiskCapacity)}
|
||||
data-ec-volumes={fmt.Sprintf("%d", host.EcVolumes)}
|
||||
data-ec-shards={fmt.Sprintf("%d", host.EcShards)}
|
||||
data-last-heartbeat={host.LastHeartbeat.Format("2006-01-02 15:04:05")}>
|
||||
<i class="fas fa-eye"></i>
|
||||
</button>
|
||||
if host.PublicURL != "" {
|
||||
<button type="button"
|
||||
class="btn btn-outline-primary btn-sm"
|
||||
title="View Details"
|
||||
data-action="view-details"
|
||||
data-id={host.ID}
|
||||
data-address={host.Address}
|
||||
data-public-url={host.PublicURL}
|
||||
data-datacenter={host.DataCenter}
|
||||
data-rack={host.Rack}
|
||||
data-volumes={fmt.Sprintf("%d", host.Volumes)}
|
||||
data-max-volumes={fmt.Sprintf("%d", host.MaxVolumes)}
|
||||
data-disk-usage={fmt.Sprintf("%d", host.DiskUsage)}
|
||||
data-disk-capacity={fmt.Sprintf("%d", host.DiskCapacity)}
|
||||
data-ec-volumes={fmt.Sprintf("%d", host.EcVolumes)}
|
||||
data-ec-shards={fmt.Sprintf("%d", host.EcShards)}
|
||||
data-last-heartbeat={host.LastHeartbeat.Format("2006-01-02 15:04:05")}>
|
||||
<i class="fas fa-eye"></i>
|
||||
</button>
|
||||
} else {
|
||||
<button type="button"
|
||||
class="btn btn-outline-primary btn-sm"
|
||||
title="View Details"
|
||||
data-action="view-details"
|
||||
data-id={host.ID}
|
||||
data-address={host.Address}
|
||||
data-public-url={host.Address}
|
||||
data-datacenter={host.DataCenter}
|
||||
data-rack={host.Rack}
|
||||
data-volumes={fmt.Sprintf("%d", host.Volumes)}
|
||||
data-max-volumes={fmt.Sprintf("%d", host.MaxVolumes)}
|
||||
data-disk-usage={fmt.Sprintf("%d", host.DiskUsage)}
|
||||
data-disk-capacity={fmt.Sprintf("%d", host.DiskCapacity)}
|
||||
data-ec-volumes={fmt.Sprintf("%d", host.EcVolumes)}
|
||||
data-ec-shards={fmt.Sprintf("%d", host.EcShards)}
|
||||
data-last-heartbeat={host.LastHeartbeat.Format("2006-01-02 15:04:05")}>
|
||||
<i class="fas fa-eye"></i>
|
||||
</button>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
@@ -306,7 +334,7 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
'<div class="col-12">' +
|
||||
'<h6 class="text-primary"><i class="fas fa-link me-1"></i>Quick Actions</h6>' +
|
||||
'<div class="d-grid gap-2 d-md-flex">' +
|
||||
'<a href="http://' + server.publicUrl + '/ui/index.html" target="_blank" class="btn btn-outline-primary">' +
|
||||
'<a href="http://' + (server.publicUrl || server.address) + '/ui/index.html" target="_blank" class="btn btn-outline-primary">' +
|
||||
'<i class="fas fa-external-link-alt me-1"></i>Open Volume Server UI' +
|
||||
'</a>' +
|
||||
'<a href="/cluster/volumes?server=' + encodeURIComponent(server.address) + '" class="btn btn-outline-info">' +
|
||||
|
||||
@@ -83,368 +83,580 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, host := range data.VolumeServers {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<tr><td><a href=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<tr><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 templ.SafeURL
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("http://%s/ui/index.html", host.PublicURL)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 116, Col: 122}
|
||||
if host.PublicURL != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<a href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 templ.SafeURL
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("http://%s/ui/index.html", host.PublicURL)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 117, Col: 126}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "\" target=\"_blank\" class=\"text-decoration-none\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 118, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, " <i class=\"fas fa-external-link-alt ms-1 text-muted\"></i></a>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "<a href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 templ.SafeURL
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("http://%s/ui/index.html", host.Address)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 122, Col: 124}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "\" target=\"_blank\" class=\"text-decoration-none\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 123, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " <i class=\"fas fa-external-link-alt ms-1 text-muted\"></i></a>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\" target=\"_blank\" class=\"text-decoration-none\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 117, Col: 61}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, " <i class=\"fas fa-external-link-alt ms-1 text-muted\"></i></a></td><td><span class=\"badge bg-light text-dark\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 122, Col: 99}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</span></td><td><span class=\"badge bg-light text-dark\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 125, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</span></td><td><div class=\"d-flex align-items-center\"><div class=\"progress me-2\" style=\"width: 60px; height: 16px;\"><div class=\"progress-bar\" role=\"progressbar\" style=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</td><td><span class=\"badge bg-light text-dark\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(host.Volumes, host.MaxVolumes)))
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 131, Col: 139}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 129, Col: 99}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "\"></div></div><span class=\"badge bg-primary\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</span></td><td><span class=\"badge bg-light text-dark\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 134, Col: 111}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 132, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</span></div></td><td><span class=\"badge bg-secondary\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</span></td><td><div class=\"d-flex align-items-center\"><div class=\"progress me-2\" style=\"width: 60px; height: 16px;\"><div class=\"progress-bar\" role=\"progressbar\" style=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(host.Volumes, host.MaxVolumes)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 138, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 138, Col: 139}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</span></td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "\"></div></div><span class=\"badge bg-primary\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 141, Col: 111}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</span></div></td><td><span class=\"badge bg-secondary\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 145, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</span></td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if host.EcShards > 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "<div class=\"d-flex align-items-center\"><i class=\"fas fa-layer-group me-1 text-info\"></i> <span class=\"badge bg-info text-white me-1\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<div class=\"d-flex align-items-center\"><i class=\"fas fa-layer-group me-1 text-info\"></i> <span class=\"badge bg-info text-white me-1\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 144, Col: 129}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 151, Col: 129}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</span> <small class=\"text-muted\">shards</small></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</span> <small class=\"text-muted\">shards</small></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if host.EcVolumes > 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<div class=\"mt-1\"><small class=\"text-muted\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "<div class=\"mt-1\"><small class=\"text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d EC volumes", host.EcVolumes))
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d EC volumes", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 149, Col: 127}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 156, Col: 127}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
_, 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, 17, "</small></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</small></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "<span class=\"text-muted\">-</span>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<span class=\"text-muted\">-</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 156, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</td><td><div class=\"d-flex align-items-center\"><div class=\"progress me-2\" style=\"width: 60px; height: 16px;\"><div class=\"progress-bar\" role=\"progressbar\" style=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(int(host.DiskUsage), int(host.DiskCapacity))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 161, Col: 153}
|
||||
}
|
||||
_, 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, 21, "\"></div></div><small>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskUsage))
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 164, Col: 83}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 163, Col: 75}
|
||||
}
|
||||
_, 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, 22, "</small></div></td><td><button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "</td><td><div class=\"d-flex align-items-center\"><div class=\"progress me-2\" style=\"width: 60px; height: 16px;\"><div class=\"progress-bar\" role=\"progressbar\" style=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(host.ID)
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(int(host.DiskUsage), int(host.DiskCapacity))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 172, Col: 68}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 168, Col: 153}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "\" data-address=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "\"></div></div><small>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 173, Col: 78}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 171, Col: 83}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\" data-public-url=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</small></div></td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(host.PublicURL)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 174, Col: 83}
|
||||
if host.PublicURL != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(host.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 180, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\" data-address=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 181, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "\" data-public-url=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(host.PublicURL)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 182, Col: 87}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "\" data-datacenter=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 183, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" data-rack=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 184, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 185, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" data-max-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 186, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" data-disk-usage=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 187, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" data-disk-capacity=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 188, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 189, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 190, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 191, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(host.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 199, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\" data-address=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 200, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" data-public-url=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 201, Col: 85}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\" data-datacenter=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 202, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "\" data-rack=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 203, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "\" data-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 204, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "\" data-max-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var37 string
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 205, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" data-disk-usage=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 206, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "\" data-disk-capacity=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 207, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var40 string
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 208, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var41 string
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 209, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 210, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "\" data-datacenter=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 175, Col: 84}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "\" data-rack=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 176, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "\" data-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 177, Col: 97}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "\" data-max-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 178, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\" data-disk-usage=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 179, Col: 102}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "\" data-disk-capacity=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 180, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 181, Col: 102}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 182, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 183, Col: 121}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\"><i class=\"fas fa-eye\"></i></button></td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "</td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "</tbody></table></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</tbody></table></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "<div class=\"text-center py-5\"><i class=\"fas fa-server fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volume Servers Found</h5><p class=\"text-muted\">No volume servers are currently available in the cluster.</p></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "<div class=\"text-center py-5\"><i class=\"fas fa-server fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volume Servers Found</h5><p class=\"text-muted\">No volume servers are currently available in the cluster.</p></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "</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, 57, "</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
|
||||
}
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 207, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 235, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "</small></div></div></div><!-- JavaScript for cluster volume servers functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle volume server action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const serverData = {\n id: button.getAttribute('data-id'),\n address: button.getAttribute('data-address'),\n publicUrl: button.getAttribute('data-public-url'),\n datacenter: button.getAttribute('data-datacenter'),\n rack: button.getAttribute('data-rack'),\n volumes: parseInt(button.getAttribute('data-volumes')),\n maxVolumes: parseInt(button.getAttribute('data-max-volumes')),\n diskUsage: parseInt(button.getAttribute('data-disk-usage')),\n diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),\n ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),\n ecShards: parseInt(button.getAttribute('data-ec-shards')),\n lastHeartbeat: button.getAttribute('data-last-heartbeat')\n };\n showVolumeServerDetails(serverData);\n break;\n }\n });\n });\n \n function showVolumeServerDetails(server) {\n const volumePercent = server.maxVolumes > 0 ? Math.round((server.volumes / server.maxVolumes) * 100) : 0;\n const diskPercent = server.diskCapacity > 0 ? Math.round((server.diskUsage / server.diskCapacity) * 100) : 0;\n \n const modalHtml = '<div class=\"modal fade\" id=\"volumeServerDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-server me-2\"></i>Volume Server Details: ' + server.address + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Server ID:</strong></td><td><code>' + server.id + '</code></td></tr>' +\n '<tr><td><strong>Address:</strong></td><td>' + server.address + '</td></tr>' +\n '<tr><td><strong>Public URL:</strong></td><td>' + server.publicUrl + '</td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.datacenter + '</span></td></tr>' +\n '<tr><td><strong>Rack:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.rack + '</span></td></tr>' +\n '<tr><td><strong>Last Heartbeat:</strong></td><td>' + server.lastHeartbeat + '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Usage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + volumePercent + '%\"></div>' +\n '</div>' +\n '<span>' + server.volumes + '/' + server.maxVolumes + ' (' + volumePercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Disk Usage:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + diskPercent + '%\"></div>' +\n '</div>' +\n '<span>' + formatBytes(server.diskUsage) + '/' + formatBytes(server.diskCapacity) + ' (' + diskPercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +\n '</table>' +\n '</div>' +\n '</div>' +\n \n Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</small></div></div></div><!-- JavaScript for cluster volume servers functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle volume server action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const serverData = {\n id: button.getAttribute('data-id'),\n address: button.getAttribute('data-address'),\n publicUrl: button.getAttribute('data-public-url'),\n datacenter: button.getAttribute('data-datacenter'),\n rack: button.getAttribute('data-rack'),\n volumes: parseInt(button.getAttribute('data-volumes')),\n maxVolumes: parseInt(button.getAttribute('data-max-volumes')),\n diskUsage: parseInt(button.getAttribute('data-disk-usage')),\n diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),\n ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),\n ecShards: parseInt(button.getAttribute('data-ec-shards')),\n lastHeartbeat: button.getAttribute('data-last-heartbeat')\n };\n showVolumeServerDetails(serverData);\n break;\n }\n });\n });\n \n function showVolumeServerDetails(server) {\n const volumePercent = server.maxVolumes > 0 ? Math.round((server.volumes / server.maxVolumes) * 100) : 0;\n const diskPercent = server.diskCapacity > 0 ? Math.round((server.diskUsage / server.diskCapacity) * 100) : 0;\n \n const modalHtml = '<div class=\"modal fade\" id=\"volumeServerDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-server me-2\"></i>Volume Server Details: ' + server.address + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Server ID:</strong></td><td><code>' + server.id + '</code></td></tr>' +\n '<tr><td><strong>Address:</strong></td><td>' + server.address + '</td></tr>' +\n '<tr><td><strong>Public URL:</strong></td><td>' + server.publicUrl + '</td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.datacenter + '</span></td></tr>' +\n '<tr><td><strong>Rack:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.rack + '</span></td></tr>' +\n '<tr><td><strong>Last Heartbeat:</strong></td><td>' + server.lastHeartbeat + '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Usage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + volumePercent + '%\"></div>' +\n '</div>' +\n '<span>' + server.volumes + '/' + server.maxVolumes + ' (' + volumePercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Disk Usage:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + diskPercent + '%\"></div>' +\n '</div>' +\n '<span>' + formatBytes(server.diskUsage) + '/' + formatBytes(server.diskCapacity) + ' (' + diskPercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +\n '</table>' +\n '</div>' +\n '</div>' +\n \n Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -357,11 +357,10 @@ templ ClusterVolumes(data dash.ClusterVolumesData) {
|
||||
style={fmt.Sprintf("width: %.1f%%",
|
||||
func() float64 {
|
||||
if volume.Size > 0 {
|
||||
activePct := float64(volume.Size - volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
if data.VolumeSizeLimit > 0 {
|
||||
return activePct * float64(volume.Size) / float64(data.VolumeSizeLimit) * 100
|
||||
return float64(volume.Size - volume.DeletedByteCount) / float64(data.VolumeSizeLimit) * 100
|
||||
}
|
||||
return activePct
|
||||
return float64(volume.Size - volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
}
|
||||
return 0
|
||||
}())}
|
||||
@@ -372,11 +371,10 @@ templ ClusterVolumes(data dash.ClusterVolumesData) {
|
||||
style={fmt.Sprintf("width: %.1f%%",
|
||||
func() float64 {
|
||||
if volume.Size > 0 && volume.DeletedByteCount > 0 {
|
||||
garbagePct := float64(volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
if data.VolumeSizeLimit > 0 {
|
||||
return garbagePct * float64(volume.Size) / float64(data.VolumeSizeLimit) * 100
|
||||
return float64(volume.DeletedByteCount) / float64(data.VolumeSizeLimit) * 100
|
||||
}
|
||||
return garbagePct
|
||||
return float64(volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
}
|
||||
return 0
|
||||
}())}
|
||||
|
||||
@@ -627,16 +627,15 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %.1f%%",
|
||||
func() float64 {
|
||||
if volume.Size > 0 {
|
||||
activePct := float64(volume.Size-volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
if data.VolumeSizeLimit > 0 {
|
||||
return activePct * float64(volume.Size) / float64(data.VolumeSizeLimit) * 100
|
||||
return float64(volume.Size-volume.DeletedByteCount) / float64(data.VolumeSizeLimit) * 100
|
||||
}
|
||||
return activePct
|
||||
return float64(volume.Size-volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
}
|
||||
return 0
|
||||
}()))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 367, Col: 49}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 366, Col: 49}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -649,7 +648,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Active: %s", formatBytes(int64(volume.Size-volume.DeletedByteCount))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 368, Col: 132}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 367, Col: 132}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -663,16 +662,15 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %.1f%%",
|
||||
func() float64 {
|
||||
if volume.Size > 0 && volume.DeletedByteCount > 0 {
|
||||
garbagePct := float64(volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
if data.VolumeSizeLimit > 0 {
|
||||
return garbagePct * float64(volume.Size) / float64(data.VolumeSizeLimit) * 100
|
||||
return float64(volume.DeletedByteCount) / float64(data.VolumeSizeLimit) * 100
|
||||
}
|
||||
return garbagePct
|
||||
return float64(volume.DeletedByteCount) / float64(volume.Size) * 100
|
||||
}
|
||||
return 0
|
||||
}()))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 382, Col: 49}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 380, Col: 49}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -685,7 +683,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Garbage: %s", formatBytes(int64(volume.DeletedByteCount))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 383, Col: 119}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 381, Col: 119}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -703,7 +701,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return "N/A"
|
||||
}())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 392, Col: 39}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 390, Col: 39}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -716,7 +714,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.FileCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 396, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 394, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -729,7 +727,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%03d", volume.ReplicaPlacement))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 398, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 396, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -747,7 +745,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(volume.DiskType)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 402, Col: 95}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 400, Col: 95}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -766,7 +764,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("v%d", volume.Version))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 407, Col: 111}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 405, Col: 111}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -784,7 +782,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.Id))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 413, Col: 121}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 411, Col: 121}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -797,7 +795,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.Id))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 418, Col: 100}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 416, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -810,7 +808,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(volume.Server)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 419, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 417, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -828,7 +826,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var37 string
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 434, Col: 98}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 432, Col: 98}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -841,7 +839,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalVolumes)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 434, Col: 180}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 432, Col: 180}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -854,7 +852,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 434, Col: 222}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 432, Col: 222}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -872,7 +870,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var40 string
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 440, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 438, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -885,7 +883,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var41 string
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 440, Col: 117}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 438, Col: 117}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -913,7 +911,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 454, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 452, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -942,7 +940,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 470, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 468, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -960,7 +958,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var44 string
|
||||
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 474, Col: 125}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 472, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -973,7 +971,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var45 string
|
||||
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 474, Col: 148}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 472, Col: 148}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -997,7 +995,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var46 string
|
||||
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 482, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 480, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -1031,7 +1029,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var47 string
|
||||
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 512, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 510, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
|
||||
@@ -16,6 +16,9 @@ func ListExistingPeerUpdates(master pb.ServerAddress, grpcDialOption grpc.DialOp
|
||||
ClientType: clientType,
|
||||
FilerGroup: filerGroup,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glog.V(0).Infof("the cluster has %d %s\n", len(resp.ClusterNodes), clientType)
|
||||
for _, node := range resp.ClusterNodes {
|
||||
@@ -26,7 +29,7 @@ func ListExistingPeerUpdates(master pb.ServerAddress, grpcDialOption grpc.DialOp
|
||||
CreatedAtNs: node.CreatedAtNs,
|
||||
})
|
||||
}
|
||||
return err
|
||||
return nil
|
||||
}); grpcErr != nil {
|
||||
glog.V(0).Infof("connect to %s: %v", master, grpcErr)
|
||||
}
|
||||
|
||||
+22
-15
@@ -34,7 +34,8 @@ var (
|
||||
type AdminOptions struct {
|
||||
port *int
|
||||
grpcPort *int
|
||||
masters *string
|
||||
master *string
|
||||
masters *string // deprecated, for backward compatibility
|
||||
adminUser *string
|
||||
adminPassword *string
|
||||
dataDir *string
|
||||
@@ -44,7 +45,8 @@ func init() {
|
||||
cmdAdmin.Run = runAdmin // break init cycle
|
||||
a.port = cmdAdmin.Flag.Int("port", 23646, "admin server port")
|
||||
a.grpcPort = cmdAdmin.Flag.Int("port.grpc", 0, "gRPC server port for worker connections (default: http port + 10000)")
|
||||
a.masters = cmdAdmin.Flag.String("masters", "localhost:9333", "comma-separated master servers")
|
||||
a.master = cmdAdmin.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
a.masters = cmdAdmin.Flag.String("masters", "", "comma-separated master servers (deprecated, use -master instead)")
|
||||
a.dataDir = cmdAdmin.Flag.String("dataDir", "", "directory to store admin configuration and data files")
|
||||
|
||||
a.adminUser = cmdAdmin.Flag.String("adminUser", "admin", "admin interface username")
|
||||
@@ -52,7 +54,7 @@ func init() {
|
||||
}
|
||||
|
||||
var cmdAdmin = &Command{
|
||||
UsageLine: "admin -port=23646 -masters=localhost:9333 [-port.grpc=33646] [-dataDir=/path/to/data]",
|
||||
UsageLine: "admin -port=23646 -master=localhost:9333 [-port.grpc=33646] [-dataDir=/path/to/data]",
|
||||
Short: "start SeaweedFS web admin interface",
|
||||
Long: `Start a web admin interface for SeaweedFS cluster management.
|
||||
|
||||
@@ -68,10 +70,10 @@ var cmdAdmin = &Command{
|
||||
A gRPC server for worker connections runs on the configured gRPC port (default: HTTP port + 10000).
|
||||
|
||||
Example Usage:
|
||||
weed admin -port=23646 -masters="master1:9333,master2:9333"
|
||||
weed admin -port=23646 -masters="localhost:9333" -dataDir="/var/lib/seaweedfs-admin"
|
||||
weed admin -port=23646 -port.grpc=33646 -masters="localhost:9333" -dataDir="~/seaweedfs-admin"
|
||||
weed admin -port=9900 -port.grpc=19900 -masters="localhost:9333"
|
||||
weed admin -port=23646 -master="master1:9333,master2:9333"
|
||||
weed admin -port=23646 -master="localhost:9333" -dataDir="/var/lib/seaweedfs-admin"
|
||||
weed admin -port=23646 -port.grpc=33646 -master="localhost:9333" -dataDir="~/seaweedfs-admin"
|
||||
weed admin -port=9900 -port.grpc=19900 -master="localhost:9333"
|
||||
|
||||
Data Directory:
|
||||
- If dataDir is specified, admin configuration and maintenance data is persisted
|
||||
@@ -116,18 +118,23 @@ func runAdmin(cmd *Command, args []string) bool {
|
||||
// Load security configuration
|
||||
util.LoadSecurityConfiguration()
|
||||
|
||||
// Backward compatibility: if -masters is provided, use it
|
||||
if *a.masters != "" {
|
||||
*a.master = *a.masters
|
||||
}
|
||||
|
||||
// Validate required parameters
|
||||
if *a.masters == "" {
|
||||
fmt.Println("Error: masters parameter is required")
|
||||
fmt.Println("Usage: weed admin -masters=master1:9333,master2:9333")
|
||||
if *a.master == "" {
|
||||
fmt.Println("Error: master parameter is required")
|
||||
fmt.Println("Usage: weed admin -master=master1:9333,master2:9333")
|
||||
return false
|
||||
}
|
||||
|
||||
// Validate that masters string can be parsed
|
||||
masterAddresses := pb.ServerAddresses(*a.masters).ToAddresses()
|
||||
// Validate that master string can be parsed
|
||||
masterAddresses := pb.ServerAddresses(*a.master).ToAddresses()
|
||||
if len(masterAddresses) == 0 {
|
||||
fmt.Println("Error: no valid master addresses found")
|
||||
fmt.Println("Usage: weed admin -masters=master1:9333,master2:9333")
|
||||
fmt.Println("Usage: weed admin -master=master1:9333,master2:9333")
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -144,7 +151,7 @@ func runAdmin(cmd *Command, args []string) bool {
|
||||
|
||||
fmt.Printf("Starting SeaweedFS Admin Interface on port %d\n", *a.port)
|
||||
fmt.Printf("Worker gRPC server will run on port %d\n", *a.grpcPort)
|
||||
fmt.Printf("Masters: %s\n", *a.masters)
|
||||
fmt.Printf("Masters: %s\n", *a.master)
|
||||
fmt.Printf("Filers will be discovered automatically from masters\n")
|
||||
if *a.dataDir != "" {
|
||||
fmt.Printf("Data Directory: %s\n", *a.dataDir)
|
||||
@@ -242,7 +249,7 @@ func startAdminServer(ctx context.Context, options AdminOptions) error {
|
||||
}
|
||||
|
||||
// Create admin server
|
||||
adminServer := dash.NewAdminServer(*options.masters, nil, dataDir)
|
||||
adminServer := dash.NewAdminServer(*options.master, nil, dataDir)
|
||||
|
||||
// Show discovered filers
|
||||
filers := adminServer.GetAllFilers()
|
||||
|
||||
@@ -2,11 +2,11 @@ package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"github.com/posener/complete"
|
||||
completeinstall "github.com/posener/complete/cmd/install"
|
||||
flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
@@ -53,14 +53,14 @@ func printAutocompleteScript(shell string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
switch shell {
|
||||
case "bash":
|
||||
fmt.Printf("complete -C %q weed\n", binPath)
|
||||
case "zsh":
|
||||
fmt.Printf("autoload -U +X bashcompinit && bashcompinit\n")
|
||||
fmt.Printf("complete -o nospace -C %q weed\n", binPath)
|
||||
case "fish":
|
||||
fmt.Printf(`function __complete_weed
|
||||
switch shell {
|
||||
case "bash":
|
||||
fmt.Printf("complete -C %q weed\n", binPath)
|
||||
case "zsh":
|
||||
fmt.Printf("autoload -U +X bashcompinit && bashcompinit\n")
|
||||
fmt.Printf("complete -o nospace -C %q weed\n", binPath)
|
||||
case "fish":
|
||||
fmt.Printf(`function __complete_weed
|
||||
set -lx COMP_LINE (commandline -cp)
|
||||
test -z (commandline -ct)
|
||||
and set COMP_LINE "$COMP_LINE "
|
||||
@@ -68,10 +68,10 @@ func printAutocompleteScript(shell string) bool {
|
||||
end
|
||||
complete -f -c weed -a "(__complete_weed)"
|
||||
`, binPath)
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unsupported shell: %s. Supported shells: bash, zsh, fish\n", shell)
|
||||
return false
|
||||
}
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unsupported shell: %s. Supported shells: bash, zsh, fish\n", shell)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
+11
-3
@@ -21,6 +21,7 @@ var (
|
||||
|
||||
type BackupOptions struct {
|
||||
master *string
|
||||
server *string // deprecated, for backward compatibility
|
||||
collection *string
|
||||
dir *string
|
||||
volumeId *int
|
||||
@@ -30,7 +31,8 @@ type BackupOptions struct {
|
||||
|
||||
func init() {
|
||||
cmdBackup.Run = runBackup // break init cycle
|
||||
s.master = cmdBackup.Flag.String("server", "localhost:9333", "SeaweedFS master location")
|
||||
s.master = cmdBackup.Flag.String("master", "localhost:9333", "SeaweedFS master location")
|
||||
s.server = cmdBackup.Flag.String("server", "", "SeaweedFS master location (deprecated, use -master instead)")
|
||||
s.collection = cmdBackup.Flag.String("collection", "", "collection name")
|
||||
s.dir = cmdBackup.Flag.String("dir", ".", "directory to store volume data files")
|
||||
s.volumeId = cmdBackup.Flag.Int("volumeId", -1, "a volume id. The volume .dat and .idx files should already exist in the dir.")
|
||||
@@ -46,7 +48,7 @@ func init() {
|
||||
}
|
||||
|
||||
var cmdBackup = &Command{
|
||||
UsageLine: "backup -dir=. -volumeId=234 -server=localhost:9333",
|
||||
UsageLine: "backup -dir=. -volumeId=234 -master=localhost:9333",
|
||||
Short: "incrementally backup a volume to local folder",
|
||||
Long: `Incrementally backup volume data.
|
||||
|
||||
@@ -69,13 +71,19 @@ func runBackup(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
|
||||
// Backward compatibility: if -server is provided, use it
|
||||
masterServer := *s.master
|
||||
if *s.server != "" {
|
||||
masterServer = *s.server
|
||||
}
|
||||
|
||||
if *s.volumeId == -1 {
|
||||
return false
|
||||
}
|
||||
vid := needle.VolumeId(*s.volumeId)
|
||||
|
||||
// find volume location, replication, ttl info
|
||||
lookup, err := operation.LookupVolumeId(func(_ context.Context) pb.ServerAddress { return pb.ServerAddress(*s.master) }, grpcDialOption, vid.String())
|
||||
lookup, err := operation.LookupVolumeId(func(_ context.Context) pb.ServerAddress { return pb.ServerAddress(masterServer) }, grpcDialOption, vid.String())
|
||||
if err != nil {
|
||||
fmt.Printf("Error looking up volume %d: %v\n", vid, err)
|
||||
return true
|
||||
|
||||
@@ -32,9 +32,9 @@ type BenchmarkOptions struct {
|
||||
numberOfFiles *int
|
||||
fileSize *int
|
||||
idListFile *string
|
||||
write *bool
|
||||
deletePercentage *int
|
||||
read *bool
|
||||
readOnly *bool
|
||||
writeOnly *bool
|
||||
sequentialRead *bool
|
||||
collection *string
|
||||
replication *string
|
||||
@@ -60,9 +60,9 @@ func init() {
|
||||
b.fileSize = cmdBenchmark.Flag.Int("size", 1024, "simulated file size in bytes, with random(0~63) bytes padding")
|
||||
b.numberOfFiles = cmdBenchmark.Flag.Int("n", 1024*1024, "number of files to write for each thread")
|
||||
b.idListFile = cmdBenchmark.Flag.String("list", os.TempDir()+"/benchmark_list.txt", "list of uploaded file ids")
|
||||
b.write = cmdBenchmark.Flag.Bool("write", true, "enable write")
|
||||
b.deletePercentage = cmdBenchmark.Flag.Int("deletePercent", 0, "the percent of writes that are deletes")
|
||||
b.read = cmdBenchmark.Flag.Bool("read", true, "enable read")
|
||||
b.readOnly = cmdBenchmark.Flag.Bool("readOnly", false, "only benchmark read operations")
|
||||
b.writeOnly = cmdBenchmark.Flag.Bool("writeOnly", false, "only benchmark write operations")
|
||||
b.sequentialRead = cmdBenchmark.Flag.Bool("readSequentially", false, "randomly read by ids from \"-list\" specified file")
|
||||
b.collection = cmdBenchmark.Flag.String("collection", "benchmark", "write data to this collection")
|
||||
b.replication = cmdBenchmark.Flag.String("replication", "000", "replication type")
|
||||
@@ -84,7 +84,10 @@ var cmdBenchmark = &Command{
|
||||
|
||||
The file content is mostly zeros, but no compression is done.
|
||||
|
||||
You can choose to only benchmark read or write.
|
||||
You can choose to only benchmark read or write:
|
||||
-readOnly only benchmark read operations
|
||||
-writeOnly only benchmark write operations
|
||||
|
||||
During write, the list of uploaded file ids is stored in "-list" specified file.
|
||||
You can also use your own list of file ids to run read test.
|
||||
|
||||
@@ -130,16 +133,33 @@ func runBenchmark(cmd *Command, args []string) bool {
|
||||
defer pprof.StopCPUProfile()
|
||||
}
|
||||
|
||||
// Determine what operations to perform
|
||||
// Default: both write and read
|
||||
// -readOnly: only read
|
||||
// -writeOnly: only write
|
||||
if *b.readOnly && *b.writeOnly {
|
||||
fmt.Fprintln(os.Stderr, "Error: -readOnly and -writeOnly are mutually exclusive.")
|
||||
return false
|
||||
}
|
||||
|
||||
doWrite := true
|
||||
doRead := true
|
||||
if *b.readOnly {
|
||||
doWrite = false
|
||||
} else if *b.writeOnly {
|
||||
doRead = false
|
||||
}
|
||||
|
||||
b.masterClient = wdclient.NewMasterClient(b.grpcDialOption, "", "client", "", "", "", *pb.ServerAddresses(*b.masters).ToServiceDiscovery())
|
||||
ctx := context.Background()
|
||||
go b.masterClient.KeepConnectedToMaster(ctx)
|
||||
b.masterClient.WaitUntilConnected(ctx)
|
||||
|
||||
if *b.write {
|
||||
if doWrite {
|
||||
benchWrite()
|
||||
}
|
||||
|
||||
if *b.read {
|
||||
if doRead {
|
||||
benchRead()
|
||||
}
|
||||
|
||||
|
||||
@@ -23,18 +23,20 @@ var (
|
||||
)
|
||||
|
||||
type DownloadOptions struct {
|
||||
server *string
|
||||
dir *string
|
||||
master *string
|
||||
server *string // deprecated, for backward compatibility
|
||||
dir *string
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdDownload.Run = runDownload // break init cycle
|
||||
d.server = cmdDownload.Flag.String("server", "localhost:9333", "SeaweedFS master location")
|
||||
d.master = cmdDownload.Flag.String("master", "localhost:9333", "SeaweedFS master location")
|
||||
d.server = cmdDownload.Flag.String("server", "", "SeaweedFS master location (deprecated, use -master instead)")
|
||||
d.dir = cmdDownload.Flag.String("dir", ".", "Download the whole folder recursively if specified.")
|
||||
}
|
||||
|
||||
var cmdDownload = &Command{
|
||||
UsageLine: "download -server=localhost:9333 -dir=one_directory fid1 [fid2 fid3 ...]",
|
||||
UsageLine: "download -master=localhost:9333 -dir=one_directory fid1 [fid2 fid3 ...]",
|
||||
Short: "download files by file id",
|
||||
Long: `download files by file id.
|
||||
|
||||
@@ -51,8 +53,14 @@ func runDownload(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
|
||||
// Backward compatibility: if -server is provided, use it
|
||||
masterServer := *d.master
|
||||
if *d.server != "" {
|
||||
masterServer = *d.server
|
||||
}
|
||||
|
||||
for _, fid := range args {
|
||||
if e := downloadToFile(func(_ context.Context) pb.ServerAddress { return pb.ServerAddress(*d.server) }, grpcDialOption, fid, util.ResolvePath(*d.dir)); e != nil {
|
||||
if e := downloadToFile(func(_ context.Context) pb.ServerAddress { return pb.ServerAddress(masterServer) }, grpcDialOption, fid, util.ResolvePath(*d.dir)); e != nil {
|
||||
fmt.Println("Download Error: ", fid, e)
|
||||
}
|
||||
}
|
||||
|
||||
+35
-4
@@ -38,6 +38,10 @@ var (
|
||||
m MasterOptions
|
||||
)
|
||||
|
||||
const (
|
||||
raftJoinCheckDelay = 1500 * time.Millisecond // delay before checking if we should join a raft cluster
|
||||
)
|
||||
|
||||
type MasterOptions struct {
|
||||
port *int
|
||||
portGrpc *int
|
||||
@@ -45,6 +49,7 @@ type MasterOptions struct {
|
||||
ipBind *string
|
||||
metaFolder *string
|
||||
peers *string
|
||||
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
|
||||
volumeSizeLimitMB *uint
|
||||
volumePreallocate *bool
|
||||
maxParallelVacuumPerServer *int
|
||||
@@ -73,7 +78,7 @@ func init() {
|
||||
m.ip = cmdMaster.Flag.String("ip", util.DetectedHostAddress(), "master <ip>|<server> address, also used as identifier")
|
||||
m.ipBind = cmdMaster.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
m.metaFolder = cmdMaster.Flag.String("mdir", os.TempDir(), "data directory to store meta data")
|
||||
m.peers = cmdMaster.Flag.String("peers", "", "all master nodes in comma separated ip:port list, example: 127.0.0.1:9093,127.0.0.1:9094,127.0.0.1:9095")
|
||||
m.peers = cmdMaster.Flag.String("peers", "", "all master nodes in comma separated ip:port list, example: 127.0.0.1:9093,127.0.0.1:9094,127.0.0.1:9095; use 'none' for single-master mode")
|
||||
m.volumeSizeLimitMB = cmdMaster.Flag.Uint("volumeSizeLimitMB", 30*1000, "Master stops directing writes to oversized volumes.")
|
||||
m.volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
m.maxParallelVacuumPerServer = cmdMaster.Flag.Int("maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel per volume server")
|
||||
@@ -104,6 +109,9 @@ var cmdMaster = &Command{
|
||||
|
||||
The example security.toml configuration file can be generated by "weed scaffold -config=security"
|
||||
|
||||
For single-master setups, use -peers=none to skip Raft quorum wait and enable instant startup.
|
||||
This is ideal for development or standalone deployments.
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -180,6 +188,9 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
|
||||
// start raftServer
|
||||
metaDir := path.Join(*masterOption.metaFolder, fmt.Sprintf("m%d", *masterOption.port))
|
||||
|
||||
isSingleMaster := isSingleMasterMode(*masterOption.peers)
|
||||
|
||||
raftServerOption := &weed_server.RaftServerOption{
|
||||
GrpcDialOption: security.LoadClientTLS(util.GetViper(), "grpc.master"),
|
||||
Peers: masterPeers,
|
||||
@@ -202,6 +213,11 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
if raftServer == nil {
|
||||
glog.Fatalf("please verify %s is writable, see https://github.com/seaweedfs/seaweedfs/issues/717: %s", *masterOption.metaFolder, err)
|
||||
}
|
||||
// For single-master mode, initialize cluster immediately without waiting
|
||||
if isSingleMaster {
|
||||
glog.V(0).Infof("Single-master mode: initializing cluster immediately")
|
||||
raftServer.DoJoinCommand()
|
||||
}
|
||||
}
|
||||
ms.SetRaftServer(raftServer)
|
||||
r.HandleFunc("/cluster/status", raftServer.StatusHandler).Methods(http.MethodGet, http.MethodHead)
|
||||
@@ -229,10 +245,10 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
}
|
||||
go grpcS.Serve(grpcL)
|
||||
|
||||
timeSleep := 1500 * time.Millisecond
|
||||
if !*masterOption.raftHashicorp {
|
||||
// For multi-master mode with non-Hashicorp raft, wait and check if we should join
|
||||
if !*masterOption.raftHashicorp && !isSingleMaster {
|
||||
go func() {
|
||||
time.Sleep(timeSleep)
|
||||
time.Sleep(raftJoinCheckDelay)
|
||||
|
||||
ms.Topo.RaftServerAccessLock.RLock()
|
||||
isEmptyMaster := ms.Topo.RaftServer.Leader() == "" && ms.Topo.RaftServer.IsLogEmpty()
|
||||
@@ -291,9 +307,24 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
select {}
|
||||
}
|
||||
|
||||
func isSingleMasterMode(peers string) bool {
|
||||
p := strings.ToLower(strings.TrimSpace(peers))
|
||||
return p == "none"
|
||||
}
|
||||
|
||||
func checkPeers(masterIp string, masterPort int, masterGrpcPort int, peers string) (masterAddress pb.ServerAddress, cleanedPeers []pb.ServerAddress) {
|
||||
glog.V(0).Infof("current: %s:%d peers:%s", masterIp, masterPort, peers)
|
||||
masterAddress = pb.NewServerAddress(masterIp, masterPort, masterGrpcPort)
|
||||
|
||||
// Handle special case: -peers=none for single-master setup
|
||||
if isSingleMasterMode(peers) {
|
||||
glog.V(0).Infof("Running in single-master mode (peers=none), no quorum required")
|
||||
cleanedPeers = []pb.ServerAddress{masterAddress}
|
||||
return
|
||||
}
|
||||
|
||||
peers = strings.TrimSpace(peers)
|
||||
|
||||
cleanedPeers = pb.ServerAddresses(peers).ToAddresses()
|
||||
|
||||
hasSelf := false
|
||||
|
||||
@@ -27,7 +27,8 @@ func init() {
|
||||
mf.port = cmdMasterFollower.Flag.Int("port", 9334, "http listen port")
|
||||
mf.portGrpc = cmdMasterFollower.Flag.Int("port.grpc", 0, "grpc listen port")
|
||||
mf.ipBind = cmdMasterFollower.Flag.String("ip.bind", "", "ip address to bind to. Default to localhost.")
|
||||
mf.peers = cmdMasterFollower.Flag.String("masters", "localhost:9333", "all master nodes in comma separated ip:port list, example: 127.0.0.1:9093,127.0.0.1:9094,127.0.0.1:9095")
|
||||
mf.peers = cmdMasterFollower.Flag.String("master", "localhost:9333", "all master nodes in comma separated ip:port list, example: 127.0.0.1:9093,127.0.0.1:9094,127.0.0.1:9095")
|
||||
mf.mastersDeprecated = cmdMasterFollower.Flag.String("masters", "", "all master nodes in comma separated ip:port list (deprecated, use -master instead)")
|
||||
|
||||
mf.ip = aws.String(util.DetectedHostAddress())
|
||||
mf.metaFolder = aws.String("")
|
||||
@@ -43,7 +44,7 @@ func init() {
|
||||
}
|
||||
|
||||
var cmdMasterFollower = &Command{
|
||||
UsageLine: "master.follower -port=9333 -masters=<master1Host>:<master1Port>",
|
||||
UsageLine: "master.follower -port=9333 -master=<master1Host>:<master1Port>",
|
||||
Short: "start a master follower",
|
||||
Long: `start a master follower to provide volume=>location mapping service
|
||||
|
||||
@@ -72,6 +73,11 @@ func runMasterFollower(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
util.LoadConfiguration("master", false)
|
||||
|
||||
// Backward compatibility: if -masters is provided, use it
|
||||
if *mf.mastersDeprecated != "" {
|
||||
*mf.peers = *mf.mastersDeprecated
|
||||
}
|
||||
|
||||
if *mf.portGrpc == 0 {
|
||||
*mf.portGrpc = 10000 + *mf.port
|
||||
}
|
||||
|
||||
+21
-5
@@ -63,6 +63,7 @@ var (
|
||||
serverRack = cmdServer.Flag.String("rack", "", "current volume server's rack name")
|
||||
serverWhiteListOption = cmdServer.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
|
||||
serverDisableHttp = cmdServer.Flag.Bool("disableHttp", false, "disable http requests, only gRPC operations are allowed.")
|
||||
serverIamConfig = cmdServer.Flag.String("iam.config", "", "path to the advanced IAM config file for S3. An alias for -s3.iam.config, but with lower priority.")
|
||||
volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
|
||||
volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
|
||||
volumeMinFreeSpacePercent = cmdServer.Flag.String("volume.minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
|
||||
@@ -160,6 +161,7 @@ func init() {
|
||||
s3Options.tlsCACertificate = cmdServer.Flag.String("s3.cacert.file", "", "path to the TLS CA certificate file")
|
||||
s3Options.tlsVerifyClientCert = cmdServer.Flag.Bool("s3.tlsVerifyClientCert", false, "whether to verify the client's certificate")
|
||||
s3Options.config = cmdServer.Flag.String("s3.config", "", "path to the config file")
|
||||
s3Options.iamConfig = cmdServer.Flag.String("s3.iam.config", "", "path to the advanced IAM config file for S3. Overrides -iam.config if both are provided.")
|
||||
s3Options.auditLogConfig = cmdServer.Flag.String("s3.auditLogConfig", "", "path to the audit log config file")
|
||||
s3Options.allowEmptyFolder = cmdServer.Flag.Bool("s3.allowEmptyFolder", true, "allow empty folders")
|
||||
s3Options.allowDeleteBucketNotEmpty = cmdServer.Flag.Bool("s3.allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
|
||||
@@ -230,10 +232,17 @@ func runServer(cmd *Command, args []string) bool {
|
||||
*isStartingFiler = true
|
||||
}
|
||||
|
||||
var actualPeersForComponents string
|
||||
if *isStartingMasterServer {
|
||||
// If we are starting a master, validate and complete the peer list
|
||||
_, peerList := checkPeers(*serverIp, *masterOptions.port, *masterOptions.portGrpc, *masterOptions.peers)
|
||||
peers := strings.Join(pb.ToAddressStrings(peerList), ",")
|
||||
masterOptions.peers = &peers
|
||||
actualPeersForComponents = strings.Join(pb.ToAddressStrings(peerList), ",")
|
||||
} else if *masterOptions.peers != "" {
|
||||
if isSingleMasterMode(*masterOptions.peers) {
|
||||
glog.Fatalf("'-master.peers=none' is only valid when starting a master server, but master is not starting.")
|
||||
}
|
||||
// If not starting a master, just use the provided peers
|
||||
actualPeersForComponents = *masterOptions.peers
|
||||
}
|
||||
|
||||
if *serverBindIp == "" {
|
||||
@@ -247,7 +256,8 @@ func runServer(cmd *Command, args []string) bool {
|
||||
// ip address
|
||||
masterOptions.ip = serverIp
|
||||
masterOptions.ipBind = serverBindIp
|
||||
filerOptions.masters = pb.ServerAddresses(*masterOptions.peers).ToServiceDiscovery()
|
||||
// Use actualPeersForComponents for volume/filer, not masterOptions.peers which might be "none"
|
||||
filerOptions.masters = pb.ServerAddresses(actualPeersForComponents).ToServiceDiscovery()
|
||||
filerOptions.ip = serverIp
|
||||
filerOptions.bindIp = serverBindIp
|
||||
if *s3Options.bindIp == "" {
|
||||
@@ -257,11 +267,11 @@ func runServer(cmd *Command, args []string) bool {
|
||||
sftpOptions.bindIp = serverBindIp
|
||||
}
|
||||
iamOptions.ip = serverBindIp
|
||||
iamOptions.masters = masterOptions.peers
|
||||
iamOptions.masters = &actualPeersForComponents
|
||||
webdavOptions.ipBind = serverBindIp
|
||||
serverOptions.v.ip = serverIp
|
||||
serverOptions.v.bindIp = serverBindIp
|
||||
serverOptions.v.masters = pb.ServerAddresses(*masterOptions.peers).ToAddresses()
|
||||
serverOptions.v.masters = pb.ServerAddresses(actualPeersForComponents).ToAddresses()
|
||||
serverOptions.v.idleConnectionTimeout = serverTimeout
|
||||
serverOptions.v.dataCenter = serverDataCenter
|
||||
serverOptions.v.rack = serverRack
|
||||
@@ -321,6 +331,12 @@ func runServer(cmd *Command, args []string) bool {
|
||||
}
|
||||
|
||||
if *isStartingS3 {
|
||||
// Handle IAM config: -s3.iam.config takes precedence over -iam.config
|
||||
if *s3Options.iamConfig == "" {
|
||||
*s3Options.iamConfig = *serverIamConfig
|
||||
} else if *serverIamConfig != "" && *s3Options.iamConfig != *serverIamConfig {
|
||||
glog.V(0).Infof("both -s3.iam.config(%s) and -iam.config(%s) provided; using -s3.iam.config", *s3Options.iamConfig, *serverIamConfig)
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
s3Options.localFilerSocket = filerOptions.localSocket
|
||||
|
||||
@@ -44,6 +44,7 @@ type VolumeServerOptions struct {
|
||||
publicUrl *string
|
||||
bindIp *string
|
||||
mastersString *string
|
||||
mserverString *string // deprecated, for backward compatibility
|
||||
masters []pb.ServerAddress
|
||||
idleConnectionTimeout *int
|
||||
dataCenter *string
|
||||
@@ -79,7 +80,8 @@ func init() {
|
||||
v.ip = cmdVolume.Flag.String("ip", util.DetectedHostAddress(), "ip or server name, also used as identifier")
|
||||
v.publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible address")
|
||||
v.bindIp = cmdVolume.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
v.mastersString = cmdVolume.Flag.String("mserver", "localhost:9333", "comma-separated master servers")
|
||||
v.mastersString = cmdVolume.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
v.mserverString = cmdVolume.Flag.String("mserver", "", "comma-separated master servers (deprecated, use -master instead)")
|
||||
v.preStopSeconds = cmdVolume.Flag.Int("preStopSeconds", 10, "number of seconds between stop send heartbeats and stop volume server")
|
||||
// v.pulseSeconds = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than or equal to the master's setting")
|
||||
v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 30, "connection idle seconds")
|
||||
@@ -107,7 +109,7 @@ func init() {
|
||||
}
|
||||
|
||||
var cmdVolume = &Command{
|
||||
UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
|
||||
UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -master=localhost:9333",
|
||||
Short: "start a volume server",
|
||||
Long: `start a volume server to provide storage spaces
|
||||
|
||||
@@ -142,6 +144,11 @@ func runVolume(cmd *Command, args []string) bool {
|
||||
}
|
||||
go stats_collect.StartMetricsServer(*v.metricsHttpIp, *v.metricsHttpPort)
|
||||
|
||||
// Backward compatibility: if -mserver is provided, use it
|
||||
if *v.mserverString != "" {
|
||||
*v.mastersString = *v.mserverString
|
||||
}
|
||||
|
||||
minFreeSpaces := util.MustParseMinFreeSpace(*minFreeSpace, *minFreeSpacePercent)
|
||||
v.masters = pb.ServerAddresses(*v.mastersString).ToAddresses()
|
||||
v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, minFreeSpaces)
|
||||
|
||||
@@ -54,6 +54,8 @@ type Filer struct {
|
||||
RemoteStorage *FilerRemoteStorage
|
||||
Dlm *lock_manager.DistributedLockManager
|
||||
MaxFilenameLength uint32
|
||||
deletionQuit chan struct{}
|
||||
DeletionRetryQueue *DeletionRetryQueue
|
||||
}
|
||||
|
||||
func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerHost pb.ServerAddress, filerGroup string, collection string, replication string, dataCenter string, maxFilenameLength uint32, notifyFn func()) *Filer {
|
||||
@@ -66,6 +68,8 @@ func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerH
|
||||
UniqueFilerId: util.RandomInt32(),
|
||||
Dlm: lock_manager.NewDistributedLockManager(filerHost),
|
||||
MaxFilenameLength: maxFilenameLength,
|
||||
deletionQuit: make(chan struct{}),
|
||||
DeletionRetryQueue: NewDeletionRetryQueue(),
|
||||
}
|
||||
if f.UniqueFilerId < 0 {
|
||||
f.UniqueFilerId = -f.UniqueFilerId
|
||||
@@ -379,6 +383,7 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
|
||||
}
|
||||
|
||||
func (f *Filer) Shutdown() {
|
||||
close(f.deletionQuit)
|
||||
f.LocalMetaLogBuffer.ShutdownLogBuffer()
|
||||
f.Store.Shutdown()
|
||||
}
|
||||
+532
-50
@@ -1,20 +1,274 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
)
|
||||
|
||||
const (
|
||||
// Maximum number of retry attempts for failed deletions
|
||||
MaxRetryAttempts = 10
|
||||
// Initial retry delay (will be doubled with each attempt)
|
||||
InitialRetryDelay = 5 * time.Minute
|
||||
// Maximum retry delay
|
||||
MaxRetryDelay = 6 * time.Hour
|
||||
// Interval for checking retry queue for ready items
|
||||
DeletionRetryPollInterval = 1 * time.Minute
|
||||
// Maximum number of items to process per retry iteration
|
||||
DeletionRetryBatchSize = 1000
|
||||
// Maximum number of error details to include in log messages
|
||||
MaxLoggedErrorDetails = 10
|
||||
// Interval for polling the deletion queue for new items
|
||||
// Using a prime number to de-synchronize with other periodic tasks
|
||||
DeletionPollInterval = 1123 * time.Millisecond
|
||||
// Maximum number of file IDs to delete per batch (roughly 20 bytes per file ID)
|
||||
DeletionBatchSize = 100000
|
||||
)
|
||||
|
||||
// retryablePatterns contains error message patterns that indicate temporary/transient conditions
|
||||
// that should be retried. These patterns are based on actual error messages from the deletion pipeline.
|
||||
var retryablePatterns = []string{
|
||||
"is read only", // Volume temporarily read-only (tiering, maintenance)
|
||||
"error reading from server", // Network I/O errors
|
||||
"connection reset by peer", // Network connection issues
|
||||
"closed network connection", // Network connection closed unexpectedly
|
||||
"connection refused", // Server temporarily unavailable
|
||||
"timeout", // Operation timeout (network or server)
|
||||
"deadline exceeded", // Context deadline exceeded
|
||||
"context canceled", // Context cancellation (may be transient)
|
||||
"lookup error", // Volume lookup failures
|
||||
"lookup failed", // Volume server discovery issues
|
||||
"too many requests", // Rate limiting / backpressure
|
||||
"service unavailable", // HTTP 503 errors
|
||||
"temporarily unavailable", // Temporary service issues
|
||||
"try again", // Explicit retry suggestion
|
||||
"i/o timeout", // Network I/O timeout
|
||||
"broken pipe", // Connection broken during operation
|
||||
}
|
||||
|
||||
// DeletionRetryItem represents a file deletion that failed and needs to be retried
|
||||
type DeletionRetryItem struct {
|
||||
FileId string
|
||||
RetryCount int
|
||||
NextRetryAt time.Time
|
||||
LastError string
|
||||
heapIndex int // index in the heap (for heap.Interface)
|
||||
inFlight bool // true when item is being processed, prevents duplicate additions
|
||||
}
|
||||
|
||||
// retryHeap implements heap.Interface for DeletionRetryItem
|
||||
// Items are ordered by NextRetryAt (earliest first)
|
||||
type retryHeap []*DeletionRetryItem
|
||||
|
||||
// Compile-time assertion that retryHeap implements heap.Interface
|
||||
var _ heap.Interface = (*retryHeap)(nil)
|
||||
|
||||
func (h retryHeap) Len() int { return len(h) }
|
||||
|
||||
func (h retryHeap) Less(i, j int) bool {
|
||||
return h[i].NextRetryAt.Before(h[j].NextRetryAt)
|
||||
}
|
||||
|
||||
func (h retryHeap) Swap(i, j int) {
|
||||
h[i], h[j] = h[j], h[i]
|
||||
h[i].heapIndex = i
|
||||
h[j].heapIndex = j
|
||||
}
|
||||
|
||||
func (h *retryHeap) Push(x any) {
|
||||
item := x.(*DeletionRetryItem)
|
||||
item.heapIndex = len(*h)
|
||||
*h = append(*h, item)
|
||||
}
|
||||
|
||||
func (h *retryHeap) Pop() any {
|
||||
old := *h
|
||||
n := len(old)
|
||||
item := old[n-1]
|
||||
old[n-1] = nil // avoid memory leak
|
||||
item.heapIndex = -1 // mark as removed
|
||||
*h = old[0 : n-1]
|
||||
return item
|
||||
}
|
||||
|
||||
// DeletionRetryQueue manages the queue of failed deletions that need to be retried.
|
||||
// Uses a min-heap ordered by NextRetryAt for efficient retrieval of ready items.
|
||||
//
|
||||
// LIMITATION: Current implementation stores retry queue in memory only.
|
||||
// On filer restart, all pending retries are lost. With MaxRetryDelay up to 6 hours,
|
||||
// process restarts during this window will cause retry state loss.
|
||||
//
|
||||
// TODO: Consider persisting retry queue to durable storage for production resilience:
|
||||
// - Option 1: Leverage existing Filer store (KV operations)
|
||||
// - Option 2: Periodic snapshots to disk with recovery on startup
|
||||
// - Option 3: Write-ahead log for retry queue mutations
|
||||
// - Trade-offs: Performance vs durability, complexity vs reliability
|
||||
//
|
||||
// For now, accepting in-memory storage as pragmatic initial implementation.
|
||||
// Lost retries will be eventually consistent as files remain in deletion queue.
|
||||
type DeletionRetryQueue struct {
|
||||
heap retryHeap
|
||||
itemIndex map[string]*DeletionRetryItem // for O(1) lookup by FileId
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
// NewDeletionRetryQueue creates a new retry queue
|
||||
func NewDeletionRetryQueue() *DeletionRetryQueue {
|
||||
q := &DeletionRetryQueue{
|
||||
heap: make(retryHeap, 0),
|
||||
itemIndex: make(map[string]*DeletionRetryItem),
|
||||
}
|
||||
heap.Init(&q.heap)
|
||||
return q
|
||||
}
|
||||
|
||||
// calculateBackoff calculates the exponential backoff delay for a given retry count.
|
||||
// Uses exponential backoff formula: InitialRetryDelay * 2^(retryCount-1)
|
||||
// The first retry (retryCount=1) uses InitialRetryDelay, second uses 2x, third uses 4x, etc.
|
||||
// Includes overflow protection and caps at MaxRetryDelay.
|
||||
func calculateBackoff(retryCount int) time.Duration {
|
||||
// The first retry is attempt 1, but shift should start at 0
|
||||
if retryCount <= 1 {
|
||||
return InitialRetryDelay
|
||||
}
|
||||
|
||||
shiftAmount := uint(retryCount - 1)
|
||||
|
||||
// time.Duration is an int64. A left shift of 63 or more will result in a
|
||||
// negative number or zero. The multiplication can also overflow much earlier
|
||||
// (around a shift of 25 for a 5-minute initial delay).
|
||||
// The `delay <= 0` check below correctly catches all these overflow cases.
|
||||
delay := InitialRetryDelay << shiftAmount
|
||||
|
||||
if delay <= 0 || delay > MaxRetryDelay {
|
||||
return MaxRetryDelay
|
||||
}
|
||||
|
||||
return delay
|
||||
}
|
||||
|
||||
// AddOrUpdate adds a new failed deletion or updates an existing one
|
||||
// Time complexity: O(log N) for insertion/update
|
||||
func (q *DeletionRetryQueue) AddOrUpdate(fileId string, errorMsg string) {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
// Check if item already exists (including in-flight items)
|
||||
if item, exists := q.itemIndex[fileId]; exists {
|
||||
// Item is already in the queue or being processed. Just update the error.
|
||||
// The existing retry schedule should proceed.
|
||||
// RetryCount is only incremented in RequeueForRetry when an actual retry is performed.
|
||||
item.LastError = errorMsg
|
||||
if item.inFlight {
|
||||
glog.V(2).Infof("retry for %s in-flight: attempt %d, will preserve retry state", fileId, item.RetryCount)
|
||||
} else {
|
||||
glog.V(2).Infof("retry for %s already scheduled: attempt %d, next retry in %v", fileId, item.RetryCount, time.Until(item.NextRetryAt))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Add new item
|
||||
delay := InitialRetryDelay
|
||||
item := &DeletionRetryItem{
|
||||
FileId: fileId,
|
||||
RetryCount: 1,
|
||||
NextRetryAt: time.Now().Add(delay),
|
||||
LastError: errorMsg,
|
||||
inFlight: false,
|
||||
}
|
||||
heap.Push(&q.heap, item)
|
||||
q.itemIndex[fileId] = item
|
||||
glog.V(2).Infof("added retry for %s: next retry in %v", fileId, delay)
|
||||
}
|
||||
|
||||
// RequeueForRetry re-adds a previously failed item back to the queue with incremented retry count.
|
||||
// This method MUST be used when re-queuing items from processRetryBatch to preserve retry state.
|
||||
// Time complexity: O(log N) for insertion
|
||||
func (q *DeletionRetryQueue) RequeueForRetry(item *DeletionRetryItem, errorMsg string) {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
// Increment retry count
|
||||
item.RetryCount++
|
||||
item.LastError = errorMsg
|
||||
|
||||
// Calculate next retry time with exponential backoff
|
||||
delay := calculateBackoff(item.RetryCount)
|
||||
item.NextRetryAt = time.Now().Add(delay)
|
||||
item.inFlight = false // Clear in-flight flag
|
||||
glog.V(2).Infof("requeued retry for %s: attempt %d, next retry in %v", item.FileId, item.RetryCount, delay)
|
||||
|
||||
// Re-add to heap (item still in itemIndex)
|
||||
heap.Push(&q.heap, item)
|
||||
}
|
||||
|
||||
// GetReadyItems returns items that are ready to be retried and marks them as in-flight
|
||||
// Time complexity: O(K log N) where K is the number of ready items
|
||||
// Items are processed in order of NextRetryAt (earliest first)
|
||||
func (q *DeletionRetryQueue) GetReadyItems(maxItems int) []*DeletionRetryItem {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
var readyItems []*DeletionRetryItem
|
||||
|
||||
// Peek at items from the top of the heap (earliest NextRetryAt)
|
||||
for len(q.heap) > 0 && len(readyItems) < maxItems {
|
||||
item := q.heap[0]
|
||||
|
||||
// If the earliest item is not ready yet, no other items are ready either
|
||||
if item.NextRetryAt.After(now) {
|
||||
break
|
||||
}
|
||||
|
||||
// Remove from heap but keep in itemIndex with inFlight flag
|
||||
heap.Pop(&q.heap)
|
||||
|
||||
if item.RetryCount <= MaxRetryAttempts {
|
||||
item.inFlight = true // Mark as being processed
|
||||
readyItems = append(readyItems, item)
|
||||
} else {
|
||||
// Max attempts reached, log and discard completely
|
||||
delete(q.itemIndex, item.FileId)
|
||||
glog.Warningf("max retry attempts (%d) reached for %s, last error: %s", MaxRetryAttempts, item.FileId, item.LastError)
|
||||
}
|
||||
}
|
||||
|
||||
return readyItems
|
||||
}
|
||||
|
||||
// Remove removes an item from the queue (called when deletion succeeds or fails permanently)
|
||||
// Time complexity: O(1)
|
||||
func (q *DeletionRetryQueue) Remove(item *DeletionRetryItem) {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
// Item was already removed from heap by GetReadyItems, just remove from index
|
||||
delete(q.itemIndex, item.FileId)
|
||||
}
|
||||
|
||||
// Size returns the current size of the retry queue
|
||||
func (q *DeletionRetryQueue) Size() int {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
return len(q.heap)
|
||||
}
|
||||
|
||||
func LookupByMasterClientFn(masterClient *wdclient.MasterClient) func(vids []string) (map[string]*operation.LookupResult, error) {
|
||||
return func(vids []string) (map[string]*operation.LookupResult, error) {
|
||||
m := make(map[string]*operation.LookupResult)
|
||||
@@ -41,64 +295,292 @@ func (f *Filer) loopProcessingDeletion() {
|
||||
|
||||
lookupFunc := LookupByMasterClientFn(f.MasterClient)
|
||||
|
||||
DeletionBatchSize := 100000 // roughly 20 bytes cost per file id.
|
||||
// Start retry processor in a separate goroutine
|
||||
go f.loopProcessingDeletionRetry(lookupFunc)
|
||||
|
||||
ticker := time.NewTicker(DeletionPollInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
var deletionCount int
|
||||
for {
|
||||
deletionCount = 0
|
||||
f.fileIdDeletionQueue.Consume(func(fileIds []string) {
|
||||
for len(fileIds) > 0 {
|
||||
var toDeleteFileIds []string
|
||||
if len(fileIds) > DeletionBatchSize {
|
||||
toDeleteFileIds = fileIds[:DeletionBatchSize]
|
||||
fileIds = fileIds[DeletionBatchSize:]
|
||||
} else {
|
||||
toDeleteFileIds = fileIds
|
||||
fileIds = fileIds[:0]
|
||||
}
|
||||
deletionCount = len(toDeleteFileIds)
|
||||
results := operation.DeleteFileIdsWithLookupVolumeId(f.GrpcDialOption, toDeleteFileIds, lookupFunc)
|
||||
|
||||
// Process individual results for better error tracking
|
||||
var successCount, notFoundCount, errorCount int
|
||||
var errorDetails []string
|
||||
|
||||
for _, result := range results {
|
||||
if result.Error == "" {
|
||||
successCount++
|
||||
} else if result.Error == "not found" || strings.Contains(result.Error, storage.ErrorDeleted.Error()) {
|
||||
// Already deleted - acceptable
|
||||
notFoundCount++
|
||||
} else {
|
||||
// Actual error
|
||||
errorCount++
|
||||
if errorCount <= 10 {
|
||||
// Only log first 10 errors to avoid flooding logs
|
||||
errorDetails = append(errorDetails, result.FileId+": "+result.Error)
|
||||
}
|
||||
select {
|
||||
case <-f.deletionQuit:
|
||||
glog.V(0).Infof("deletion processor shutting down")
|
||||
return
|
||||
case <-ticker.C:
|
||||
f.fileIdDeletionQueue.Consume(func(fileIds []string) {
|
||||
for i := 0; i < len(fileIds); i += DeletionBatchSize {
|
||||
end := i + DeletionBatchSize
|
||||
if end > len(fileIds) {
|
||||
end = len(fileIds)
|
||||
}
|
||||
toDeleteFileIds := fileIds[i:end]
|
||||
f.processDeletionBatch(toDeleteFileIds, lookupFunc)
|
||||
}
|
||||
|
||||
if successCount > 0 || notFoundCount > 0 {
|
||||
glog.V(2).Infof("deleted %d files successfully, %d already deleted (not found)", successCount, notFoundCount)
|
||||
}
|
||||
|
||||
if errorCount > 0 {
|
||||
logMessage := fmt.Sprintf("failed to delete %d/%d files", errorCount, len(toDeleteFileIds))
|
||||
if errorCount > 10 {
|
||||
logMessage += " (showing first 10)"
|
||||
}
|
||||
glog.V(0).Infof("%s: %v", logMessage, strings.Join(errorDetails, "; "))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if deletionCount == 0 {
|
||||
time.Sleep(1123 * time.Millisecond)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// processDeletionBatch handles deletion of a batch of file IDs and processes results.
|
||||
// It classifies errors into retryable and permanent categories, adds retryable failures
|
||||
// to the retry queue, and logs appropriate messages.
|
||||
func (f *Filer) processDeletionBatch(toDeleteFileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) {
|
||||
// Deduplicate file IDs to prevent incorrect retry count increments for the same file ID within a single batch.
|
||||
uniqueFileIdsSlice := make([]string, 0, len(toDeleteFileIds))
|
||||
processed := make(map[string]struct{}, len(toDeleteFileIds))
|
||||
for _, fileId := range toDeleteFileIds {
|
||||
if _, found := processed[fileId]; !found {
|
||||
processed[fileId] = struct{}{}
|
||||
uniqueFileIdsSlice = append(uniqueFileIdsSlice, fileId)
|
||||
}
|
||||
}
|
||||
|
||||
if len(uniqueFileIdsSlice) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Delete files and classify outcomes
|
||||
outcomes := deleteFilesAndClassify(f.GrpcDialOption, uniqueFileIdsSlice, lookupFunc)
|
||||
|
||||
// Process outcomes
|
||||
var successCount, notFoundCount, retryableErrorCount, permanentErrorCount int
|
||||
var errorDetails []string
|
||||
|
||||
for _, fileId := range uniqueFileIdsSlice {
|
||||
outcome := outcomes[fileId]
|
||||
|
||||
switch outcome.status {
|
||||
case deletionOutcomeSuccess:
|
||||
successCount++
|
||||
case deletionOutcomeNotFound:
|
||||
notFoundCount++
|
||||
case deletionOutcomeRetryable, deletionOutcomeNoResult:
|
||||
retryableErrorCount++
|
||||
f.DeletionRetryQueue.AddOrUpdate(fileId, outcome.errorMsg)
|
||||
if len(errorDetails) < MaxLoggedErrorDetails {
|
||||
errorDetails = append(errorDetails, fileId+": "+outcome.errorMsg+" (will retry)")
|
||||
}
|
||||
case deletionOutcomePermanent:
|
||||
permanentErrorCount++
|
||||
if len(errorDetails) < MaxLoggedErrorDetails {
|
||||
errorDetails = append(errorDetails, fileId+": "+outcome.errorMsg+" (permanent)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if successCount > 0 || notFoundCount > 0 {
|
||||
glog.V(2).Infof("deleted %d files successfully, %d already deleted (not found)", successCount, notFoundCount)
|
||||
}
|
||||
|
||||
totalErrors := retryableErrorCount + permanentErrorCount
|
||||
if totalErrors > 0 {
|
||||
logMessage := fmt.Sprintf("failed to delete %d/%d files (%d retryable, %d permanent)",
|
||||
totalErrors, len(uniqueFileIdsSlice), retryableErrorCount, permanentErrorCount)
|
||||
if len(errorDetails) > 0 {
|
||||
if totalErrors > MaxLoggedErrorDetails {
|
||||
logMessage += fmt.Sprintf(" (showing first %d)", len(errorDetails))
|
||||
}
|
||||
glog.V(0).Infof("%s: %v", logMessage, strings.Join(errorDetails, "; "))
|
||||
} else {
|
||||
glog.V(0).Info(logMessage)
|
||||
}
|
||||
}
|
||||
|
||||
if f.DeletionRetryQueue.Size() > 0 {
|
||||
glog.V(2).Infof("retry queue size: %d", f.DeletionRetryQueue.Size())
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
deletionOutcomeSuccess = "success"
|
||||
deletionOutcomeNotFound = "not_found"
|
||||
deletionOutcomeRetryable = "retryable"
|
||||
deletionOutcomePermanent = "permanent"
|
||||
deletionOutcomeNoResult = "no_result"
|
||||
)
|
||||
|
||||
// deletionOutcome represents the result of classifying deletion results for a file
|
||||
type deletionOutcome struct {
|
||||
status string // One of the deletionOutcome* constants
|
||||
errorMsg string
|
||||
}
|
||||
|
||||
// deleteFilesAndClassify performs deletion and classifies outcomes for a list of file IDs
|
||||
func deleteFilesAndClassify(grpcDialOption grpc.DialOption, fileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) map[string]deletionOutcome {
|
||||
// Perform deletion
|
||||
results := operation.DeleteFileIdsWithLookupVolumeId(grpcDialOption, fileIds, lookupFunc)
|
||||
|
||||
// Group results by file ID to handle multiple results for replicated volumes
|
||||
resultsByFileId := make(map[string][]*volume_server_pb.DeleteResult)
|
||||
for _, result := range results {
|
||||
resultsByFileId[result.FileId] = append(resultsByFileId[result.FileId], result)
|
||||
}
|
||||
|
||||
// Classify outcome for each file
|
||||
outcomes := make(map[string]deletionOutcome, len(fileIds))
|
||||
for _, fileId := range fileIds {
|
||||
outcomes[fileId] = classifyDeletionOutcome(fileId, resultsByFileId)
|
||||
}
|
||||
|
||||
return outcomes
|
||||
}
|
||||
|
||||
// classifyDeletionOutcome examines all deletion results for a file ID and determines the overall outcome
|
||||
// Uses a single pass through results with early return for permanent errors (highest priority)
|
||||
// Priority: Permanent > Retryable > Success > Not Found
|
||||
func classifyDeletionOutcome(fileId string, resultsByFileId map[string][]*volume_server_pb.DeleteResult) deletionOutcome {
|
||||
fileIdResults, found := resultsByFileId[fileId]
|
||||
if !found || len(fileIdResults) == 0 {
|
||||
return deletionOutcome{
|
||||
status: deletionOutcomeNoResult,
|
||||
errorMsg: "no deletion result from volume server",
|
||||
}
|
||||
}
|
||||
|
||||
var firstRetryableError string
|
||||
hasSuccess := false
|
||||
|
||||
for _, res := range fileIdResults {
|
||||
if res.Error == "" {
|
||||
hasSuccess = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(res.Error, storage.ErrorDeleted.Error()) || res.Error == "not found" {
|
||||
continue
|
||||
}
|
||||
|
||||
if isRetryableError(res.Error) {
|
||||
if firstRetryableError == "" {
|
||||
firstRetryableError = res.Error
|
||||
}
|
||||
} else {
|
||||
// Permanent error takes highest precedence - return immediately
|
||||
return deletionOutcome{status: deletionOutcomePermanent, errorMsg: res.Error}
|
||||
}
|
||||
}
|
||||
|
||||
if firstRetryableError != "" {
|
||||
return deletionOutcome{status: deletionOutcomeRetryable, errorMsg: firstRetryableError}
|
||||
}
|
||||
|
||||
if hasSuccess {
|
||||
return deletionOutcome{status: deletionOutcomeSuccess, errorMsg: ""}
|
||||
}
|
||||
|
||||
// If we are here, all results were "not found"
|
||||
return deletionOutcome{status: deletionOutcomeNotFound, errorMsg: ""}
|
||||
}
|
||||
|
||||
// isRetryableError determines if an error is retryable based on its message.
|
||||
//
|
||||
// Current implementation uses string matching which is brittle and may break
|
||||
// if error messages change in dependencies. This is acceptable for the initial
|
||||
// implementation but should be improved in the future.
|
||||
//
|
||||
// TODO: Consider these improvements for more robust error handling:
|
||||
// - Pass DeleteResult instead of just error string to access Status codes
|
||||
// - Use HTTP status codes (503 Service Unavailable, 429 Too Many Requests, etc.)
|
||||
// - Implement structured error types that can be checked with errors.Is/errors.As
|
||||
// - Extract and check gRPC status codes for better classification
|
||||
// - Add error wrapping in the deletion pipeline to preserve error context
|
||||
//
|
||||
// For now, we use conservative string matching for known transient error patterns.
|
||||
func isRetryableError(errorMsg string) bool {
|
||||
// Empty errors are not retryable
|
||||
if errorMsg == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
errorLower := strings.ToLower(errorMsg)
|
||||
for _, pattern := range retryablePatterns {
|
||||
if strings.Contains(errorLower, pattern) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// loopProcessingDeletionRetry processes the retry queue for failed deletions
|
||||
func (f *Filer) loopProcessingDeletionRetry(lookupFunc func([]string) (map[string]*operation.LookupResult, error)) {
|
||||
|
||||
ticker := time.NewTicker(DeletionRetryPollInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-f.deletionQuit:
|
||||
glog.V(0).Infof("retry processor shutting down, %d items remaining in queue", f.DeletionRetryQueue.Size())
|
||||
return
|
||||
case <-ticker.C:
|
||||
// Process all ready items in batches until queue is empty
|
||||
totalProcessed := 0
|
||||
for {
|
||||
readyItems := f.DeletionRetryQueue.GetReadyItems(DeletionRetryBatchSize)
|
||||
if len(readyItems) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
f.processRetryBatch(readyItems, lookupFunc)
|
||||
totalProcessed += len(readyItems)
|
||||
}
|
||||
|
||||
if totalProcessed > 0 {
|
||||
glog.V(1).Infof("retried deletion of %d files", totalProcessed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// processRetryBatch attempts to retry deletion of files and processes results.
|
||||
// Successfully deleted items are removed from tracking, retryable failures are
|
||||
// re-queued with updated retry counts, and permanent errors are logged and discarded.
|
||||
func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) {
|
||||
// Extract file IDs from retry items
|
||||
fileIds := make([]string, 0, len(readyItems))
|
||||
for _, item := range readyItems {
|
||||
fileIds = append(fileIds, item.FileId)
|
||||
}
|
||||
|
||||
// Delete files and classify outcomes
|
||||
outcomes := deleteFilesAndClassify(f.GrpcDialOption, fileIds, lookupFunc)
|
||||
|
||||
// Process outcomes - iterate over readyItems to ensure all items are accounted for
|
||||
var successCount, notFoundCount, retryCount, permanentErrorCount int
|
||||
for _, item := range readyItems {
|
||||
outcome := outcomes[item.FileId]
|
||||
|
||||
switch outcome.status {
|
||||
case deletionOutcomeSuccess:
|
||||
successCount++
|
||||
f.DeletionRetryQueue.Remove(item) // Remove from queue (success)
|
||||
glog.V(2).Infof("retry successful for %s after %d attempts", item.FileId, item.RetryCount)
|
||||
case deletionOutcomeNotFound:
|
||||
notFoundCount++
|
||||
f.DeletionRetryQueue.Remove(item) // Remove from queue (already deleted)
|
||||
case deletionOutcomeRetryable, deletionOutcomeNoResult:
|
||||
retryCount++
|
||||
if outcome.status == deletionOutcomeNoResult {
|
||||
glog.Warningf("no deletion result for retried file %s, re-queuing to avoid loss", item.FileId)
|
||||
}
|
||||
f.DeletionRetryQueue.RequeueForRetry(item, outcome.errorMsg)
|
||||
case deletionOutcomePermanent:
|
||||
permanentErrorCount++
|
||||
f.DeletionRetryQueue.Remove(item) // Remove from queue (permanent failure)
|
||||
glog.Warningf("permanent error on retry for %s after %d attempts: %s", item.FileId, item.RetryCount, outcome.errorMsg)
|
||||
}
|
||||
}
|
||||
|
||||
if successCount > 0 || notFoundCount > 0 {
|
||||
glog.V(1).Infof("retry: deleted %d files successfully, %d already deleted", successCount, notFoundCount)
|
||||
}
|
||||
if retryCount > 0 {
|
||||
glog.V(1).Infof("retry: %d files still failing, will retry again later", retryCount)
|
||||
}
|
||||
if permanentErrorCount > 0 {
|
||||
glog.Warningf("retry: %d files failed with permanent errors", permanentErrorCount)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) DeleteUncommittedChunks(ctx context.Context, chunks []*filer_pb.FileChunk) {
|
||||
f.doDeleteChunks(ctx, chunks)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDeletionRetryQueue_AddAndRetrieve(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Add items
|
||||
queue.AddOrUpdate("file1", "is read only")
|
||||
queue.AddOrUpdate("file2", "connection reset")
|
||||
|
||||
if queue.Size() != 2 {
|
||||
t.Errorf("Expected queue size 2, got %d", queue.Size())
|
||||
}
|
||||
|
||||
// Items not ready yet (initial delay is 5 minutes)
|
||||
readyItems := queue.GetReadyItems(10)
|
||||
if len(readyItems) != 0 {
|
||||
t.Errorf("Expected 0 ready items, got %d", len(readyItems))
|
||||
}
|
||||
|
||||
// Size should remain unchanged
|
||||
if queue.Size() != 2 {
|
||||
t.Errorf("Expected queue size 2 after checking ready items, got %d", queue.Size())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletionRetryQueue_ExponentialBackoff(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Create an item
|
||||
item := &DeletionRetryItem{
|
||||
FileId: "test-file",
|
||||
RetryCount: 0,
|
||||
NextRetryAt: time.Now(),
|
||||
LastError: "test error",
|
||||
}
|
||||
|
||||
// Requeue multiple times to test backoff
|
||||
delays := []time.Duration{}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
beforeTime := time.Now()
|
||||
queue.RequeueForRetry(item, "error")
|
||||
|
||||
// Calculate expected delay for this retry count
|
||||
expectedDelay := InitialRetryDelay * time.Duration(1<<uint(i))
|
||||
if expectedDelay > MaxRetryDelay {
|
||||
expectedDelay = MaxRetryDelay
|
||||
}
|
||||
|
||||
// Verify NextRetryAt is approximately correct
|
||||
actualDelay := item.NextRetryAt.Sub(beforeTime)
|
||||
delays = append(delays, actualDelay)
|
||||
|
||||
// Allow small timing variance
|
||||
timeDiff := actualDelay - expectedDelay
|
||||
if timeDiff < 0 {
|
||||
timeDiff = -timeDiff
|
||||
}
|
||||
if timeDiff > 100*time.Millisecond {
|
||||
t.Errorf("Retry %d: expected delay ~%v, got %v (diff: %v)", i+1, expectedDelay, actualDelay, timeDiff)
|
||||
}
|
||||
|
||||
// Verify retry count incremented
|
||||
if item.RetryCount != i+1 {
|
||||
t.Errorf("Expected RetryCount %d, got %d", i+1, item.RetryCount)
|
||||
}
|
||||
|
||||
// Reset the heap for the next isolated test iteration
|
||||
queue.lock.Lock()
|
||||
queue.heap = retryHeap{}
|
||||
queue.lock.Unlock()
|
||||
}
|
||||
|
||||
t.Logf("Exponential backoff delays: %v", delays)
|
||||
}
|
||||
|
||||
func TestDeletionRetryQueue_OverflowProtection(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Create an item with very high retry count
|
||||
item := &DeletionRetryItem{
|
||||
FileId: "test-file",
|
||||
RetryCount: 60, // High count that would cause overflow without protection
|
||||
NextRetryAt: time.Now(),
|
||||
LastError: "test error",
|
||||
}
|
||||
|
||||
// Should not panic and should cap at MaxRetryDelay
|
||||
queue.RequeueForRetry(item, "error")
|
||||
|
||||
delay := time.Until(item.NextRetryAt)
|
||||
if delay > MaxRetryDelay+time.Second {
|
||||
t.Errorf("Delay exceeded MaxRetryDelay: %v > %v", delay, MaxRetryDelay)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletionRetryQueue_MaxAttemptsReached(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Add item
|
||||
queue.AddOrUpdate("file1", "error")
|
||||
|
||||
// Manually set retry count to max
|
||||
queue.lock.Lock()
|
||||
item, exists := queue.itemIndex["file1"]
|
||||
if !exists {
|
||||
queue.lock.Unlock()
|
||||
t.Fatal("Item not found in queue")
|
||||
}
|
||||
item.RetryCount = MaxRetryAttempts
|
||||
item.NextRetryAt = time.Now().Add(-1 * time.Second) // Ready now
|
||||
heap.Fix(&queue.heap, item.heapIndex)
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Try to get ready items - should be returned for the last retry (attempt #10)
|
||||
readyItems := queue.GetReadyItems(10)
|
||||
if len(readyItems) != 1 {
|
||||
t.Fatalf("Expected 1 item for last retry, got %d", len(readyItems))
|
||||
}
|
||||
|
||||
// Requeue it, which will increment its retry count beyond the max
|
||||
queue.RequeueForRetry(readyItems[0], "final error")
|
||||
|
||||
// Manually make it ready again
|
||||
queue.lock.Lock()
|
||||
item, exists = queue.itemIndex["file1"]
|
||||
if !exists {
|
||||
queue.lock.Unlock()
|
||||
t.Fatal("Item not found in queue after requeue")
|
||||
}
|
||||
item.NextRetryAt = time.Now().Add(-1 * time.Second)
|
||||
heap.Fix(&queue.heap, item.heapIndex)
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Now it should be discarded (retry count is 11, exceeds max of 10)
|
||||
readyItems = queue.GetReadyItems(10)
|
||||
if len(readyItems) != 0 {
|
||||
t.Errorf("Expected 0 items (max attempts exceeded), got %d", len(readyItems))
|
||||
}
|
||||
|
||||
// Should be removed from queue
|
||||
if queue.Size() != 0 {
|
||||
t.Errorf("Expected queue size 0 after max attempts exceeded, got %d", queue.Size())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculateBackoff(t *testing.T) {
|
||||
testCases := []struct {
|
||||
retryCount int
|
||||
expectedDelay time.Duration
|
||||
description string
|
||||
}{
|
||||
{1, InitialRetryDelay, "first retry"},
|
||||
{2, InitialRetryDelay * 2, "second retry"},
|
||||
{3, InitialRetryDelay * 4, "third retry"},
|
||||
{4, InitialRetryDelay * 8, "fourth retry"},
|
||||
{5, InitialRetryDelay * 16, "fifth retry"},
|
||||
{10, MaxRetryDelay, "capped at max delay"},
|
||||
{65, MaxRetryDelay, "overflow protection (shift > 63)"},
|
||||
{100, MaxRetryDelay, "very high retry count"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
result := calculateBackoff(tc.retryCount)
|
||||
if result != tc.expectedDelay {
|
||||
t.Errorf("%s (retry %d): expected %v, got %v",
|
||||
tc.description, tc.retryCount, tc.expectedDelay, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsRetryableError(t *testing.T) {
|
||||
testCases := []struct {
|
||||
error string
|
||||
retryable bool
|
||||
description string
|
||||
}{
|
||||
{"volume 123 is read only", true, "read-only volume"},
|
||||
{"connection reset by peer", true, "connection reset"},
|
||||
{"timeout exceeded", true, "timeout"},
|
||||
{"deadline exceeded", true, "deadline exceeded"},
|
||||
{"context canceled", true, "context canceled"},
|
||||
{"lookup error: volume not found", true, "lookup error"},
|
||||
{"connection refused", true, "connection refused"},
|
||||
{"too many requests", true, "rate limiting"},
|
||||
{"service unavailable", true, "service unavailable"},
|
||||
{"i/o timeout", true, "I/O timeout"},
|
||||
{"broken pipe", true, "broken pipe"},
|
||||
{"not found", false, "not found (not retryable)"},
|
||||
{"invalid file id", false, "invalid input (not retryable)"},
|
||||
{"", false, "empty error"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
result := isRetryableError(tc.error)
|
||||
if result != tc.retryable {
|
||||
t.Errorf("%s: expected retryable=%v, got %v for error: %q",
|
||||
tc.description, tc.retryable, result, tc.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletionRetryQueue_HeapOrdering(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
now := time.Now()
|
||||
|
||||
// Add items with different retry times (out of order)
|
||||
items := []*DeletionRetryItem{
|
||||
{FileId: "file3", RetryCount: 1, NextRetryAt: now.Add(30 * time.Second), LastError: "error3"},
|
||||
{FileId: "file1", RetryCount: 1, NextRetryAt: now.Add(10 * time.Second), LastError: "error1"},
|
||||
{FileId: "file2", RetryCount: 1, NextRetryAt: now.Add(20 * time.Second), LastError: "error2"},
|
||||
}
|
||||
|
||||
// Add items directly (simulating internal state)
|
||||
for _, item := range items {
|
||||
queue.lock.Lock()
|
||||
queue.itemIndex[item.FileId] = item
|
||||
queue.heap = append(queue.heap, item)
|
||||
queue.lock.Unlock()
|
||||
}
|
||||
|
||||
// Use container/heap.Init to establish heap property
|
||||
queue.lock.Lock()
|
||||
heap.Init(&queue.heap)
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Verify heap maintains min-heap property (earliest time at top)
|
||||
queue.lock.Lock()
|
||||
if queue.heap[0].FileId != "file1" {
|
||||
t.Errorf("Expected file1 at heap top (earliest time), got %s", queue.heap[0].FileId)
|
||||
}
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Set all items to ready while preserving their relative order
|
||||
queue.lock.Lock()
|
||||
for _, item := range queue.itemIndex {
|
||||
// Shift all times back by 40 seconds to make them ready, but preserve order
|
||||
item.NextRetryAt = item.NextRetryAt.Add(-40 * time.Second)
|
||||
}
|
||||
heap.Init(&queue.heap) // Re-establish heap property after modification
|
||||
queue.lock.Unlock()
|
||||
|
||||
// GetReadyItems should return in NextRetryAt order
|
||||
readyItems := queue.GetReadyItems(10)
|
||||
expectedOrder := []string{"file1", "file2", "file3"}
|
||||
|
||||
if len(readyItems) != 3 {
|
||||
t.Fatalf("Expected 3 ready items, got %d", len(readyItems))
|
||||
}
|
||||
|
||||
for i, item := range readyItems {
|
||||
if item.FileId != expectedOrder[i] {
|
||||
t.Errorf("Item %d: expected %s, got %s", i, expectedOrder[i], item.FileId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletionRetryQueue_DuplicateFileIds(t *testing.T) {
|
||||
queue := NewDeletionRetryQueue()
|
||||
|
||||
// Add same file ID twice with retryable error - simulates duplicate in batch
|
||||
queue.AddOrUpdate("file1", "timeout error")
|
||||
|
||||
// Verify only one item exists in queue
|
||||
if queue.Size() != 1 {
|
||||
t.Fatalf("Expected queue size 1 after first add, got %d", queue.Size())
|
||||
}
|
||||
|
||||
// Get initial retry count
|
||||
queue.lock.Lock()
|
||||
item1, exists := queue.itemIndex["file1"]
|
||||
if !exists {
|
||||
queue.lock.Unlock()
|
||||
t.Fatal("Item not found in queue after first add")
|
||||
}
|
||||
initialRetryCount := item1.RetryCount
|
||||
queue.lock.Unlock()
|
||||
|
||||
// Add same file ID again - should NOT increment retry count (just update error)
|
||||
queue.AddOrUpdate("file1", "timeout error again")
|
||||
|
||||
// Verify still only one item exists in queue (not duplicated)
|
||||
if queue.Size() != 1 {
|
||||
t.Errorf("Expected queue size 1 after duplicate add, got %d (duplicates detected)", queue.Size())
|
||||
}
|
||||
|
||||
// Verify retry count did NOT increment (AddOrUpdate only updates error, not count)
|
||||
queue.lock.Lock()
|
||||
item2, exists := queue.itemIndex["file1"]
|
||||
queue.lock.Unlock()
|
||||
|
||||
if !exists {
|
||||
t.Fatal("Item not found in queue after second add")
|
||||
}
|
||||
if item2.RetryCount != initialRetryCount {
|
||||
t.Errorf("Expected RetryCount to stay at %d after duplicate add (should not increment), got %d", initialRetryCount, item2.RetryCount)
|
||||
}
|
||||
if item2.LastError != "timeout error again" {
|
||||
t.Errorf("Expected LastError to be updated to 'timeout error again', got %q", item2.LastError)
|
||||
}
|
||||
}
|
||||
@@ -272,7 +272,6 @@ subscribeLoop:
|
||||
TsNs: logEntry.TsNs,
|
||||
}
|
||||
|
||||
|
||||
if err := stream.Send(&mq_pb.SubscribeMessageResponse{Message: &mq_pb.SubscribeMessageResponse_Data{
|
||||
Data: dataMsg,
|
||||
}}); err != nil {
|
||||
|
||||
@@ -103,15 +103,15 @@ func TestIncrementalCooperativeAssignmentStrategy_RebalanceWithRevocation(t *tes
|
||||
t.Errorf("Expected member-2 to have 0 partitions during revocation, got %d", len(member2Assignments))
|
||||
}
|
||||
|
||||
t.Logf("Revocation phase - Member-1: %d partitions, Member-2: %d partitions",
|
||||
t.Logf("Revocation phase - Member-1: %d partitions, Member-2: %d partitions",
|
||||
len(member1Assignments), len(member2Assignments))
|
||||
|
||||
// Simulate time passing and second call (should move to assignment phase)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
|
||||
// Force move to assignment phase by setting timeout to 0
|
||||
state.RevocationTimeout = 0
|
||||
|
||||
|
||||
assignments2 := strategy.Assign(members, topicPartitions)
|
||||
|
||||
// Should complete rebalance
|
||||
@@ -136,7 +136,7 @@ func TestIncrementalCooperativeAssignmentStrategy_RebalanceWithRevocation(t *tes
|
||||
t.Errorf("Expected 4 total partitions after rebalance, got %d", totalFinalPartitions)
|
||||
}
|
||||
|
||||
t.Logf("Final assignment - Member-1: %d partitions, Member-2: %d partitions",
|
||||
t.Logf("Final assignment - Member-1: %d partitions, Member-2: %d partitions",
|
||||
len(member1FinalAssignments), len(member2FinalAssignments))
|
||||
}
|
||||
|
||||
@@ -239,7 +239,7 @@ func TestIncrementalCooperativeAssignmentStrategy_MultipleTopics(t *testing.T) {
|
||||
t.Errorf("Expected partition %s to be assigned", expected)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Debug: Print all assigned partitions
|
||||
t.Logf("All assigned partitions: %v", allAssignedPartitions)
|
||||
}
|
||||
@@ -390,7 +390,7 @@ func TestIncrementalCooperativeAssignmentStrategy_StateTransitions(t *testing.T)
|
||||
// Force timeout to move to assignment phase
|
||||
state.RevocationTimeout = 0
|
||||
strategy.Assign(members, topicPartitions)
|
||||
|
||||
|
||||
// Should complete and return to None
|
||||
state = strategy.GetRebalanceState()
|
||||
if state.Phase != RebalancePhaseNone {
|
||||
|
||||
@@ -24,12 +24,12 @@ func (rtm *RebalanceTimeoutManager) CheckRebalanceTimeouts() {
|
||||
|
||||
for _, group := range rtm.coordinator.groups {
|
||||
group.Mu.Lock()
|
||||
|
||||
|
||||
// Only check timeouts for groups in rebalancing states
|
||||
if group.State == GroupStatePreparingRebalance || group.State == GroupStateCompletingRebalance {
|
||||
rtm.checkGroupRebalanceTimeout(group, now)
|
||||
}
|
||||
|
||||
|
||||
group.Mu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ func (rtm *RebalanceTimeoutManager) CheckRebalanceTimeouts() {
|
||||
// checkGroupRebalanceTimeout checks and handles rebalance timeout for a specific group
|
||||
func (rtm *RebalanceTimeoutManager) checkGroupRebalanceTimeout(group *ConsumerGroup, now time.Time) {
|
||||
expiredMembers := make([]string, 0)
|
||||
|
||||
|
||||
for memberID, member := range group.Members {
|
||||
// Check if member has exceeded its rebalance timeout
|
||||
rebalanceTimeout := time.Duration(member.RebalanceTimeout) * time.Millisecond
|
||||
@@ -45,21 +45,21 @@ func (rtm *RebalanceTimeoutManager) checkGroupRebalanceTimeout(group *ConsumerGr
|
||||
// Use default rebalance timeout if not specified
|
||||
rebalanceTimeout = time.Duration(rtm.coordinator.rebalanceTimeoutMs) * time.Millisecond
|
||||
}
|
||||
|
||||
|
||||
// For members in pending state during rebalance, check against join time
|
||||
if member.State == MemberStatePending {
|
||||
if now.Sub(member.JoinedAt) > rebalanceTimeout {
|
||||
expiredMembers = append(expiredMembers, memberID)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Also check session timeout as a fallback
|
||||
sessionTimeout := time.Duration(member.SessionTimeout) * time.Millisecond
|
||||
if now.Sub(member.LastHeartbeat) > sessionTimeout {
|
||||
expiredMembers = append(expiredMembers, memberID)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Remove expired members and trigger rebalance if necessary
|
||||
if len(expiredMembers) > 0 {
|
||||
rtm.evictExpiredMembers(group, expiredMembers)
|
||||
@@ -70,13 +70,13 @@ func (rtm *RebalanceTimeoutManager) checkGroupRebalanceTimeout(group *ConsumerGr
|
||||
func (rtm *RebalanceTimeoutManager) evictExpiredMembers(group *ConsumerGroup, expiredMembers []string) {
|
||||
for _, memberID := range expiredMembers {
|
||||
delete(group.Members, memberID)
|
||||
|
||||
|
||||
// If the leader was evicted, clear leader
|
||||
if group.Leader == memberID {
|
||||
group.Leader = ""
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Update group state based on remaining members
|
||||
if len(group.Members) == 0 {
|
||||
group.State = GroupStateEmpty
|
||||
@@ -92,18 +92,18 @@ func (rtm *RebalanceTimeoutManager) evictExpiredMembers(group *ConsumerGroup, ex
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Reset to preparing rebalance to restart the process
|
||||
group.State = GroupStatePreparingRebalance
|
||||
group.Generation++
|
||||
|
||||
|
||||
// Mark remaining members as pending
|
||||
for _, member := range group.Members {
|
||||
member.State = MemberStatePending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
group.LastActivity = time.Now()
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ func (rtm *RebalanceTimeoutManager) IsRebalanceStuck(group *ConsumerGroup, maxRe
|
||||
if group.State != GroupStatePreparingRebalance && group.State != GroupStateCompletingRebalance {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
return time.Since(group.LastActivity) > maxRebalanceDuration
|
||||
}
|
||||
|
||||
@@ -120,14 +120,14 @@ func (rtm *RebalanceTimeoutManager) IsRebalanceStuck(group *ConsumerGroup, maxRe
|
||||
func (rtm *RebalanceTimeoutManager) ForceCompleteRebalance(group *ConsumerGroup) {
|
||||
group.Mu.Lock()
|
||||
defer group.Mu.Unlock()
|
||||
|
||||
|
||||
// If stuck in preparing rebalance, move to completing
|
||||
if group.State == GroupStatePreparingRebalance {
|
||||
group.State = GroupStateCompletingRebalance
|
||||
group.LastActivity = time.Now()
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// If stuck in completing rebalance, force to stable
|
||||
if group.State == GroupStateCompletingRebalance {
|
||||
group.State = GroupStateStable
|
||||
@@ -145,21 +145,21 @@ func (rtm *RebalanceTimeoutManager) GetRebalanceStatus(groupID string) *Rebalanc
|
||||
if group == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
group.Mu.RLock()
|
||||
defer group.Mu.RUnlock()
|
||||
|
||||
|
||||
status := &RebalanceStatus{
|
||||
GroupID: groupID,
|
||||
State: group.State,
|
||||
Generation: group.Generation,
|
||||
MemberCount: len(group.Members),
|
||||
Leader: group.Leader,
|
||||
LastActivity: group.LastActivity,
|
||||
IsRebalancing: group.State == GroupStatePreparingRebalance || group.State == GroupStateCompletingRebalance,
|
||||
GroupID: groupID,
|
||||
State: group.State,
|
||||
Generation: group.Generation,
|
||||
MemberCount: len(group.Members),
|
||||
Leader: group.Leader,
|
||||
LastActivity: group.LastActivity,
|
||||
IsRebalancing: group.State == GroupStatePreparingRebalance || group.State == GroupStateCompletingRebalance,
|
||||
RebalanceDuration: time.Since(group.LastActivity),
|
||||
}
|
||||
|
||||
|
||||
// Calculate member timeout status
|
||||
now := time.Now()
|
||||
for memberID, member := range group.Members {
|
||||
@@ -171,48 +171,48 @@ func (rtm *RebalanceTimeoutManager) GetRebalanceStatus(groupID string) *Rebalanc
|
||||
SessionTimeout: time.Duration(member.SessionTimeout) * time.Millisecond,
|
||||
RebalanceTimeout: time.Duration(member.RebalanceTimeout) * time.Millisecond,
|
||||
}
|
||||
|
||||
|
||||
// Calculate time until session timeout
|
||||
sessionTimeRemaining := memberStatus.SessionTimeout - now.Sub(member.LastHeartbeat)
|
||||
if sessionTimeRemaining < 0 {
|
||||
sessionTimeRemaining = 0
|
||||
}
|
||||
memberStatus.SessionTimeRemaining = sessionTimeRemaining
|
||||
|
||||
|
||||
// Calculate time until rebalance timeout
|
||||
rebalanceTimeRemaining := memberStatus.RebalanceTimeout - now.Sub(member.JoinedAt)
|
||||
if rebalanceTimeRemaining < 0 {
|
||||
rebalanceTimeRemaining = 0
|
||||
}
|
||||
memberStatus.RebalanceTimeRemaining = rebalanceTimeRemaining
|
||||
|
||||
|
||||
status.Members = append(status.Members, memberStatus)
|
||||
}
|
||||
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
// RebalanceStatus represents the current status of a group's rebalance
|
||||
type RebalanceStatus struct {
|
||||
GroupID string `json:"group_id"`
|
||||
State GroupState `json:"state"`
|
||||
Generation int32 `json:"generation"`
|
||||
MemberCount int `json:"member_count"`
|
||||
Leader string `json:"leader"`
|
||||
LastActivity time.Time `json:"last_activity"`
|
||||
IsRebalancing bool `json:"is_rebalancing"`
|
||||
RebalanceDuration time.Duration `json:"rebalance_duration"`
|
||||
Members []MemberTimeoutStatus `json:"members"`
|
||||
GroupID string `json:"group_id"`
|
||||
State GroupState `json:"state"`
|
||||
Generation int32 `json:"generation"`
|
||||
MemberCount int `json:"member_count"`
|
||||
Leader string `json:"leader"`
|
||||
LastActivity time.Time `json:"last_activity"`
|
||||
IsRebalancing bool `json:"is_rebalancing"`
|
||||
RebalanceDuration time.Duration `json:"rebalance_duration"`
|
||||
Members []MemberTimeoutStatus `json:"members"`
|
||||
}
|
||||
|
||||
// MemberTimeoutStatus represents timeout status for a group member
|
||||
type MemberTimeoutStatus struct {
|
||||
MemberID string `json:"member_id"`
|
||||
State MemberState `json:"state"`
|
||||
LastHeartbeat time.Time `json:"last_heartbeat"`
|
||||
JoinedAt time.Time `json:"joined_at"`
|
||||
SessionTimeout time.Duration `json:"session_timeout"`
|
||||
RebalanceTimeout time.Duration `json:"rebalance_timeout"`
|
||||
SessionTimeRemaining time.Duration `json:"session_time_remaining"`
|
||||
RebalanceTimeRemaining time.Duration `json:"rebalance_time_remaining"`
|
||||
MemberID string `json:"member_id"`
|
||||
State MemberState `json:"state"`
|
||||
LastHeartbeat time.Time `json:"last_heartbeat"`
|
||||
JoinedAt time.Time `json:"joined_at"`
|
||||
SessionTimeout time.Duration `json:"session_timeout"`
|
||||
RebalanceTimeout time.Duration `json:"rebalance_timeout"`
|
||||
SessionTimeRemaining time.Duration `json:"session_time_remaining"`
|
||||
RebalanceTimeRemaining time.Duration `json:"rebalance_time_remaining"`
|
||||
}
|
||||
@@ -8,14 +8,14 @@ import (
|
||||
func TestRebalanceTimeoutManager_CheckRebalanceTimeouts(t *testing.T) {
|
||||
coordinator := NewGroupCoordinator()
|
||||
defer coordinator.Close()
|
||||
|
||||
|
||||
rtm := coordinator.rebalanceTimeoutManager
|
||||
|
||||
|
||||
// Create a group with a member that has a short rebalance timeout
|
||||
group := coordinator.GetOrCreateGroup("test-group")
|
||||
group.Mu.Lock()
|
||||
group.State = GroupStatePreparingRebalance
|
||||
|
||||
|
||||
member := &GroupMember{
|
||||
ID: "member1",
|
||||
ClientID: "client1",
|
||||
@@ -27,15 +27,15 @@ func TestRebalanceTimeoutManager_CheckRebalanceTimeouts(t *testing.T) {
|
||||
}
|
||||
group.Members["member1"] = member
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
// Check timeouts - member should be evicted
|
||||
rtm.CheckRebalanceTimeouts()
|
||||
|
||||
|
||||
group.Mu.RLock()
|
||||
if len(group.Members) != 0 {
|
||||
t.Errorf("Expected member to be evicted due to rebalance timeout, but %d members remain", len(group.Members))
|
||||
}
|
||||
|
||||
|
||||
if group.State != GroupStateEmpty {
|
||||
t.Errorf("Expected group state to be Empty after member eviction, got %s", group.State.String())
|
||||
}
|
||||
@@ -45,18 +45,18 @@ func TestRebalanceTimeoutManager_CheckRebalanceTimeouts(t *testing.T) {
|
||||
func TestRebalanceTimeoutManager_SessionTimeoutFallback(t *testing.T) {
|
||||
coordinator := NewGroupCoordinator()
|
||||
defer coordinator.Close()
|
||||
|
||||
|
||||
rtm := coordinator.rebalanceTimeoutManager
|
||||
|
||||
|
||||
// Create a group with a member that has exceeded session timeout
|
||||
group := coordinator.GetOrCreateGroup("test-group")
|
||||
group.Mu.Lock()
|
||||
group.State = GroupStatePreparingRebalance
|
||||
|
||||
|
||||
member := &GroupMember{
|
||||
ID: "member1",
|
||||
ClientID: "client1",
|
||||
SessionTimeout: 1000, // 1 second
|
||||
SessionTimeout: 1000, // 1 second
|
||||
RebalanceTimeout: 30000, // 30 seconds
|
||||
State: MemberStatePending,
|
||||
LastHeartbeat: time.Now().Add(-2 * time.Second), // Last heartbeat 2 seconds ago
|
||||
@@ -64,10 +64,10 @@ func TestRebalanceTimeoutManager_SessionTimeoutFallback(t *testing.T) {
|
||||
}
|
||||
group.Members["member1"] = member
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
// Check timeouts - member should be evicted due to session timeout
|
||||
rtm.CheckRebalanceTimeouts()
|
||||
|
||||
|
||||
group.Mu.RLock()
|
||||
if len(group.Members) != 0 {
|
||||
t.Errorf("Expected member to be evicted due to session timeout, but %d members remain", len(group.Members))
|
||||
@@ -78,15 +78,15 @@ func TestRebalanceTimeoutManager_SessionTimeoutFallback(t *testing.T) {
|
||||
func TestRebalanceTimeoutManager_LeaderEviction(t *testing.T) {
|
||||
coordinator := NewGroupCoordinator()
|
||||
defer coordinator.Close()
|
||||
|
||||
|
||||
rtm := coordinator.rebalanceTimeoutManager
|
||||
|
||||
|
||||
// Create a group with leader and another member
|
||||
group := coordinator.GetOrCreateGroup("test-group")
|
||||
group.Mu.Lock()
|
||||
group.State = GroupStatePreparingRebalance
|
||||
group.Leader = "member1"
|
||||
|
||||
|
||||
// Leader with expired rebalance timeout
|
||||
leader := &GroupMember{
|
||||
ID: "member1",
|
||||
@@ -98,7 +98,7 @@ func TestRebalanceTimeoutManager_LeaderEviction(t *testing.T) {
|
||||
JoinedAt: time.Now().Add(-2 * time.Second),
|
||||
}
|
||||
group.Members["member1"] = leader
|
||||
|
||||
|
||||
// Another member that's still valid
|
||||
member2 := &GroupMember{
|
||||
ID: "member2",
|
||||
@@ -111,19 +111,19 @@ func TestRebalanceTimeoutManager_LeaderEviction(t *testing.T) {
|
||||
}
|
||||
group.Members["member2"] = member2
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
// Check timeouts - leader should be evicted, new leader selected
|
||||
rtm.CheckRebalanceTimeouts()
|
||||
|
||||
|
||||
group.Mu.RLock()
|
||||
if len(group.Members) != 1 {
|
||||
t.Errorf("Expected 1 member to remain after leader eviction, got %d", len(group.Members))
|
||||
}
|
||||
|
||||
|
||||
if group.Leader != "member2" {
|
||||
t.Errorf("Expected member2 to become new leader, got %s", group.Leader)
|
||||
}
|
||||
|
||||
|
||||
if group.State != GroupStatePreparingRebalance {
|
||||
t.Errorf("Expected group to restart rebalancing after leader eviction, got %s", group.State.String())
|
||||
}
|
||||
@@ -133,37 +133,37 @@ func TestRebalanceTimeoutManager_LeaderEviction(t *testing.T) {
|
||||
func TestRebalanceTimeoutManager_IsRebalanceStuck(t *testing.T) {
|
||||
coordinator := NewGroupCoordinator()
|
||||
defer coordinator.Close()
|
||||
|
||||
|
||||
rtm := coordinator.rebalanceTimeoutManager
|
||||
|
||||
|
||||
// Create a group that's been rebalancing for a while
|
||||
group := coordinator.GetOrCreateGroup("test-group")
|
||||
group.Mu.Lock()
|
||||
group.State = GroupStatePreparingRebalance
|
||||
group.LastActivity = time.Now().Add(-15 * time.Minute) // 15 minutes ago
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
// Check if rebalance is stuck (max 10 minutes)
|
||||
maxDuration := 10 * time.Minute
|
||||
if !rtm.IsRebalanceStuck(group, maxDuration) {
|
||||
t.Error("Expected rebalance to be detected as stuck")
|
||||
}
|
||||
|
||||
|
||||
// Test with a group that's not stuck
|
||||
group.Mu.Lock()
|
||||
group.LastActivity = time.Now().Add(-5 * time.Minute) // 5 minutes ago
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
if rtm.IsRebalanceStuck(group, maxDuration) {
|
||||
t.Error("Expected rebalance to not be detected as stuck")
|
||||
}
|
||||
|
||||
|
||||
// Test with stable group (should not be stuck)
|
||||
group.Mu.Lock()
|
||||
group.State = GroupStateStable
|
||||
group.LastActivity = time.Now().Add(-15 * time.Minute)
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
if rtm.IsRebalanceStuck(group, maxDuration) {
|
||||
t.Error("Stable group should not be detected as stuck")
|
||||
}
|
||||
@@ -172,37 +172,37 @@ func TestRebalanceTimeoutManager_IsRebalanceStuck(t *testing.T) {
|
||||
func TestRebalanceTimeoutManager_ForceCompleteRebalance(t *testing.T) {
|
||||
coordinator := NewGroupCoordinator()
|
||||
defer coordinator.Close()
|
||||
|
||||
|
||||
rtm := coordinator.rebalanceTimeoutManager
|
||||
|
||||
|
||||
// Test forcing completion from PreparingRebalance
|
||||
group := coordinator.GetOrCreateGroup("test-group")
|
||||
group.Mu.Lock()
|
||||
group.State = GroupStatePreparingRebalance
|
||||
|
||||
|
||||
member := &GroupMember{
|
||||
ID: "member1",
|
||||
State: MemberStatePending,
|
||||
}
|
||||
group.Members["member1"] = member
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
rtm.ForceCompleteRebalance(group)
|
||||
|
||||
|
||||
group.Mu.RLock()
|
||||
if group.State != GroupStateCompletingRebalance {
|
||||
t.Errorf("Expected group state to be CompletingRebalance, got %s", group.State.String())
|
||||
}
|
||||
group.Mu.RUnlock()
|
||||
|
||||
|
||||
// Test forcing completion from CompletingRebalance
|
||||
rtm.ForceCompleteRebalance(group)
|
||||
|
||||
|
||||
group.Mu.RLock()
|
||||
if group.State != GroupStateStable {
|
||||
t.Errorf("Expected group state to be Stable, got %s", group.State.String())
|
||||
}
|
||||
|
||||
|
||||
if member.State != MemberStateStable {
|
||||
t.Errorf("Expected member state to be Stable, got %s", member.State.String())
|
||||
}
|
||||
@@ -212,15 +212,15 @@ func TestRebalanceTimeoutManager_ForceCompleteRebalance(t *testing.T) {
|
||||
func TestRebalanceTimeoutManager_GetRebalanceStatus(t *testing.T) {
|
||||
coordinator := NewGroupCoordinator()
|
||||
defer coordinator.Close()
|
||||
|
||||
|
||||
rtm := coordinator.rebalanceTimeoutManager
|
||||
|
||||
|
||||
// Test with non-existent group
|
||||
status := rtm.GetRebalanceStatus("non-existent")
|
||||
if status != nil {
|
||||
t.Error("Expected nil status for non-existent group")
|
||||
}
|
||||
|
||||
|
||||
// Create a group with members
|
||||
group := coordinator.GetOrCreateGroup("test-group")
|
||||
group.Mu.Lock()
|
||||
@@ -228,7 +228,7 @@ func TestRebalanceTimeoutManager_GetRebalanceStatus(t *testing.T) {
|
||||
group.Generation = 5
|
||||
group.Leader = "member1"
|
||||
group.LastActivity = time.Now().Add(-2 * time.Minute)
|
||||
|
||||
|
||||
member1 := &GroupMember{
|
||||
ID: "member1",
|
||||
State: MemberStatePending,
|
||||
@@ -238,7 +238,7 @@ func TestRebalanceTimeoutManager_GetRebalanceStatus(t *testing.T) {
|
||||
RebalanceTimeout: 300000, // 5 minutes
|
||||
}
|
||||
group.Members["member1"] = member1
|
||||
|
||||
|
||||
member2 := &GroupMember{
|
||||
ID: "member2",
|
||||
State: MemberStatePending,
|
||||
@@ -249,48 +249,48 @@ func TestRebalanceTimeoutManager_GetRebalanceStatus(t *testing.T) {
|
||||
}
|
||||
group.Members["member2"] = member2
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
// Get status
|
||||
status = rtm.GetRebalanceStatus("test-group")
|
||||
|
||||
|
||||
if status == nil {
|
||||
t.Fatal("Expected non-nil status")
|
||||
}
|
||||
|
||||
|
||||
if status.GroupID != "test-group" {
|
||||
t.Errorf("Expected group ID 'test-group', got %s", status.GroupID)
|
||||
}
|
||||
|
||||
|
||||
if status.State != GroupStatePreparingRebalance {
|
||||
t.Errorf("Expected state PreparingRebalance, got %s", status.State.String())
|
||||
}
|
||||
|
||||
|
||||
if status.Generation != 5 {
|
||||
t.Errorf("Expected generation 5, got %d", status.Generation)
|
||||
}
|
||||
|
||||
|
||||
if status.MemberCount != 2 {
|
||||
t.Errorf("Expected 2 members, got %d", status.MemberCount)
|
||||
}
|
||||
|
||||
|
||||
if status.Leader != "member1" {
|
||||
t.Errorf("Expected leader 'member1', got %s", status.Leader)
|
||||
}
|
||||
|
||||
|
||||
if !status.IsRebalancing {
|
||||
t.Error("Expected IsRebalancing to be true")
|
||||
}
|
||||
|
||||
|
||||
if len(status.Members) != 2 {
|
||||
t.Errorf("Expected 2 member statuses, got %d", len(status.Members))
|
||||
}
|
||||
|
||||
|
||||
// Check member timeout calculations
|
||||
for _, memberStatus := range status.Members {
|
||||
if memberStatus.SessionTimeRemaining < 0 {
|
||||
t.Errorf("Session time remaining should not be negative for member %s", memberStatus.MemberID)
|
||||
}
|
||||
|
||||
|
||||
if memberStatus.RebalanceTimeRemaining < 0 {
|
||||
t.Errorf("Rebalance time remaining should not be negative for member %s", memberStatus.MemberID)
|
||||
}
|
||||
@@ -300,14 +300,14 @@ func TestRebalanceTimeoutManager_GetRebalanceStatus(t *testing.T) {
|
||||
func TestRebalanceTimeoutManager_DefaultRebalanceTimeout(t *testing.T) {
|
||||
coordinator := NewGroupCoordinator()
|
||||
defer coordinator.Close()
|
||||
|
||||
|
||||
rtm := coordinator.rebalanceTimeoutManager
|
||||
|
||||
|
||||
// Create a group with a member that has no rebalance timeout set (0)
|
||||
group := coordinator.GetOrCreateGroup("test-group")
|
||||
group.Mu.Lock()
|
||||
group.State = GroupStatePreparingRebalance
|
||||
|
||||
|
||||
member := &GroupMember{
|
||||
ID: "member1",
|
||||
ClientID: "client1",
|
||||
@@ -319,10 +319,10 @@ func TestRebalanceTimeoutManager_DefaultRebalanceTimeout(t *testing.T) {
|
||||
}
|
||||
group.Members["member1"] = member
|
||||
group.Mu.Unlock()
|
||||
|
||||
|
||||
// Default rebalance timeout is 5 minutes (300000ms), so member should be evicted
|
||||
rtm.CheckRebalanceTimeouts()
|
||||
|
||||
|
||||
group.Mu.RLock()
|
||||
if len(group.Members) != 0 {
|
||||
t.Errorf("Expected member to be evicted using default rebalance timeout, but %d members remain", len(group.Members))
|
||||
|
||||
@@ -142,4 +142,3 @@ func (m *MemoryStorage) Close() error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -206,4 +206,3 @@ func TestMemoryStorageOverwrite(t *testing.T) {
|
||||
assert.Equal(t, int64(20), offset)
|
||||
assert.Equal(t, "meta2", metadata)
|
||||
}
|
||||
|
||||
@@ -56,4 +56,3 @@ var (
|
||||
ErrInvalidPartition = fmt.Errorf("invalid partition")
|
||||
ErrStorageClosed = fmt.Errorf("storage is closed")
|
||||
)
|
||||
|
||||
@@ -121,7 +121,6 @@ func (m *mockSeaweedMQHandler) ProduceRecord(ctx context.Context, topicName stri
|
||||
offset := m.offsets[topicName][partitionID]
|
||||
m.offsets[topicName][partitionID]++
|
||||
|
||||
|
||||
// Store record
|
||||
record := &mockRecord{
|
||||
key: key,
|
||||
|
||||
@@ -9,5 +9,3 @@ package kafka
|
||||
// - offset/: Offset management
|
||||
// - schema/: Schema registry integration
|
||||
// - consumer/: Consumer group coordination
|
||||
|
||||
|
||||
@@ -51,5 +51,3 @@ func GetRangeSize() int32 {
|
||||
func GetMaxKafkaPartitions() int32 {
|
||||
return int32(pub_balancer.MaxPartitionCount) / 35 // 72 partitions
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ func (h *Handler) handleDescribeCluster(correlationID uint32, apiVersion uint16,
|
||||
// Tagged fields at end of request
|
||||
// (We don't parse them, just skip)
|
||||
|
||||
|
||||
// Build response
|
||||
response := make([]byte, 0, 256)
|
||||
|
||||
@@ -109,6 +108,5 @@ func (h *Handler) handleDescribeCluster(correlationID uint32, apiVersion uint16,
|
||||
// Response-level tagged fields (flexible response)
|
||||
response = append(response, 0x00) // Empty tagged fields
|
||||
|
||||
|
||||
return response, nil
|
||||
}
|
||||
@@ -268,7 +268,6 @@ func parseCompactString(data []byte) ([]byte, int) {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
|
||||
if actualLength == 0 {
|
||||
// Empty string (length was 1)
|
||||
return []byte{}, consumed
|
||||
|
||||
@@ -107,13 +107,13 @@ func (h *Handler) describeGroup(groupID string) DescribeGroupsGroup {
|
||||
}
|
||||
|
||||
return DescribeGroupsGroup{
|
||||
ErrorCode: 0,
|
||||
GroupID: groupID,
|
||||
State: stateStr,
|
||||
ProtocolType: "consumer", // Default protocol type
|
||||
Protocol: group.Protocol,
|
||||
Members: members,
|
||||
AuthorizedOps: []int32{}, // Empty for now
|
||||
ErrorCode: 0,
|
||||
GroupID: groupID,
|
||||
State: stateStr,
|
||||
ProtocolType: "consumer", // Default protocol type
|
||||
Protocol: group.Protocol,
|
||||
Members: members,
|
||||
AuthorizedOps: []int32{}, // Empty for now
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,8 +175,8 @@ func (h *Handler) listAllGroups(statesFilter []string) []ListGroupsGroup {
|
||||
// Request/Response structures
|
||||
|
||||
type DescribeGroupsRequest struct {
|
||||
GroupIDs []string
|
||||
IncludeAuthorizedOps bool
|
||||
GroupIDs []string
|
||||
IncludeAuthorizedOps bool
|
||||
}
|
||||
|
||||
type DescribeGroupsResponse struct {
|
||||
|
||||
@@ -661,7 +661,7 @@ func (h *Handler) HandleConn(ctx context.Context, conn net.Conn) error {
|
||||
return
|
||||
}
|
||||
// Removed V(4) logging from hot path - only log errors and important events
|
||||
|
||||
|
||||
// Wrap request processing with panic recovery to prevent deadlocks
|
||||
// If processRequestSync panics, we MUST still send a response to avoid blocking the response writer
|
||||
var response []byte
|
||||
@@ -881,7 +881,6 @@ func (h *Handler) HandleConn(ctx context.Context, conn net.Conn) error {
|
||||
return fmt.Errorf("read message: %w", err)
|
||||
}
|
||||
|
||||
|
||||
// Parse at least the basic header to get API key and correlation ID
|
||||
if len(messageBuf) < 8 {
|
||||
return fmt.Errorf("message too short")
|
||||
@@ -890,7 +889,7 @@ func (h *Handler) HandleConn(ctx context.Context, conn net.Conn) error {
|
||||
apiKey := binary.BigEndian.Uint16(messageBuf[0:2])
|
||||
apiVersion := binary.BigEndian.Uint16(messageBuf[2:4])
|
||||
correlationID := binary.BigEndian.Uint32(messageBuf[4:8])
|
||||
|
||||
|
||||
// Validate API version against what we support
|
||||
if err := h.validateAPIVersion(apiKey, apiVersion); err != nil {
|
||||
glog.Errorf("API VERSION VALIDATION FAILED: Key=%d (%s), Version=%d, error=%v", apiKey, getAPIName(APIKey(apiKey)), apiVersion, err)
|
||||
@@ -1050,7 +1049,6 @@ func (h *Handler) processRequestSync(req *kafkaRequest) ([]byte, error) {
|
||||
requestStart := time.Now()
|
||||
apiName := getAPIName(APIKey(req.apiKey))
|
||||
|
||||
|
||||
// Only log high-volume requests at V(2), not V(4)
|
||||
if glog.V(2) {
|
||||
glog.V(2).Infof("[API] %s (key=%d, ver=%d, corr=%d)",
|
||||
@@ -1589,15 +1587,15 @@ func (h *Handler) HandleMetadataV2(correlationID uint32, requestBody []byte) ([]
|
||||
for partitionID := int32(0); partitionID < partitionCount; partitionID++ {
|
||||
binary.Write(&buf, binary.BigEndian, int16(0)) // ErrorCode
|
||||
binary.Write(&buf, binary.BigEndian, partitionID) // PartitionIndex
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // LeaderID
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // LeaderID
|
||||
|
||||
// ReplicaNodes array (4 bytes length + nodes)
|
||||
binary.Write(&buf, binary.BigEndian, int32(1)) // 1 replica
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
|
||||
// IsrNodes array (4 bytes length + nodes)
|
||||
binary.Write(&buf, binary.BigEndian, int32(1)) // 1 ISR node
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1716,15 +1714,15 @@ func (h *Handler) HandleMetadataV3V4(correlationID uint32, requestBody []byte) (
|
||||
for partitionID := int32(0); partitionID < partitionCount; partitionID++ {
|
||||
binary.Write(&buf, binary.BigEndian, int16(0)) // ErrorCode
|
||||
binary.Write(&buf, binary.BigEndian, partitionID) // PartitionIndex
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // LeaderID
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // LeaderID
|
||||
|
||||
// ReplicaNodes array (4 bytes length + nodes)
|
||||
binary.Write(&buf, binary.BigEndian, int32(1)) // 1 replica
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
|
||||
// IsrNodes array (4 bytes length + nodes)
|
||||
binary.Write(&buf, binary.BigEndian, int32(1)) // 1 ISR node
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1737,7 +1735,7 @@ func (h *Handler) HandleMetadataV3V4(correlationID uint32, requestBody []byte) (
|
||||
}
|
||||
if len(response) > 100 {
|
||||
}
|
||||
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
@@ -1828,7 +1826,6 @@ func (h *Handler) handleMetadataV5ToV8(correlationID uint32, requestBody []byte,
|
||||
// NOTE: Correlation ID is handled by writeResponseWithCorrelationID
|
||||
// Do NOT include it in the response body
|
||||
|
||||
|
||||
// ThrottleTimeMs (4 bytes) - v3+ addition
|
||||
binary.Write(&buf, binary.BigEndian, int32(0)) // No throttling
|
||||
|
||||
@@ -1896,7 +1893,7 @@ func (h *Handler) handleMetadataV5ToV8(correlationID uint32, requestBody []byte,
|
||||
for partitionID := int32(0); partitionID < partitionCount; partitionID++ {
|
||||
binary.Write(&buf, binary.BigEndian, int16(0)) // ErrorCode
|
||||
binary.Write(&buf, binary.BigEndian, partitionID) // PartitionIndex
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // LeaderID
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // LeaderID
|
||||
|
||||
// LeaderEpoch (4 bytes) - v7+ addition
|
||||
if apiVersion >= 7 {
|
||||
@@ -1905,11 +1902,11 @@ func (h *Handler) handleMetadataV5ToV8(correlationID uint32, requestBody []byte,
|
||||
|
||||
// ReplicaNodes array (4 bytes length + nodes)
|
||||
binary.Write(&buf, binary.BigEndian, int32(1)) // 1 replica
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
|
||||
// IsrNodes array (4 bytes length + nodes)
|
||||
binary.Write(&buf, binary.BigEndian, int32(1)) // 1 ISR node
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
binary.Write(&buf, binary.BigEndian, nodeID) // NodeID 1
|
||||
|
||||
// OfflineReplicas array (4 bytes length + nodes) - v5+ addition
|
||||
binary.Write(&buf, binary.BigEndian, int32(0)) // No offline replicas
|
||||
@@ -1930,7 +1927,7 @@ func (h *Handler) handleMetadataV5ToV8(correlationID uint32, requestBody []byte,
|
||||
}
|
||||
if len(response) > 100 {
|
||||
}
|
||||
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
@@ -1994,12 +1991,11 @@ func (h *Handler) handleListOffsets(correlationID uint32, apiVersion uint16, req
|
||||
// Parse minimal request to understand what's being asked (header already stripped)
|
||||
offset := 0
|
||||
|
||||
|
||||
maxBytes := len(requestBody)
|
||||
if maxBytes > 64 {
|
||||
maxBytes = 64
|
||||
}
|
||||
|
||||
|
||||
// v1+ has replica_id(4)
|
||||
if apiVersion >= 1 {
|
||||
if len(requestBody) < offset+4 {
|
||||
@@ -3930,12 +3926,11 @@ func (h *Handler) handleInitProducerId(correlationID uint32, apiVersion uint16,
|
||||
// v2+: transactional_id(NULLABLE_STRING) + transaction_timeout_ms(INT32) + producer_id(INT64) + producer_epoch(INT16)
|
||||
// v4+: Uses flexible format with tagged fields
|
||||
|
||||
|
||||
maxBytes := len(requestBody)
|
||||
if maxBytes > 64 {
|
||||
maxBytes = 64
|
||||
}
|
||||
|
||||
|
||||
offset := 0
|
||||
|
||||
// Parse transactional_id (NULLABLE_STRING or COMPACT_NULLABLE_STRING for flexible versions)
|
||||
|
||||
@@ -47,4 +47,3 @@ func (a *offsetStorageAdapter) DeleteGroup(group string) error {
|
||||
func (a *offsetStorageAdapter) Close() error {
|
||||
return a.storage.Close()
|
||||
}
|
||||
|
||||
@@ -140,4 +140,3 @@ func TestMetadataResponseHasBrokers(t *testing.T) {
|
||||
|
||||
t.Logf("✓ Metadata response correctly has %d broker(s)", parsedCount)
|
||||
}
|
||||
|
||||
@@ -7,46 +7,46 @@ import (
|
||||
|
||||
func TestParseConfluentEnvelope(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input []byte
|
||||
expectOK bool
|
||||
expectID uint32
|
||||
name string
|
||||
input []byte
|
||||
expectOK bool
|
||||
expectID uint32
|
||||
expectFormat Format
|
||||
}{
|
||||
{
|
||||
name: "valid Avro message",
|
||||
input: []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x48, 0x65, 0x6c, 0x6c, 0x6f}, // schema ID 1 + "Hello"
|
||||
expectOK: true,
|
||||
expectID: 1,
|
||||
name: "valid Avro message",
|
||||
input: []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x48, 0x65, 0x6c, 0x6c, 0x6f}, // schema ID 1 + "Hello"
|
||||
expectOK: true,
|
||||
expectID: 1,
|
||||
expectFormat: FormatAvro,
|
||||
},
|
||||
{
|
||||
name: "valid message with larger schema ID",
|
||||
input: []byte{0x00, 0x00, 0x00, 0x04, 0xd2, 0x02, 0x66, 0x6f, 0x6f}, // schema ID 1234 + "foo"
|
||||
expectOK: true,
|
||||
expectID: 1234,
|
||||
name: "valid message with larger schema ID",
|
||||
input: []byte{0x00, 0x00, 0x00, 0x04, 0xd2, 0x02, 0x66, 0x6f, 0x6f}, // schema ID 1234 + "foo"
|
||||
expectOK: true,
|
||||
expectID: 1234,
|
||||
expectFormat: FormatAvro,
|
||||
},
|
||||
{
|
||||
name: "too short message",
|
||||
input: []byte{0x00, 0x00, 0x00},
|
||||
expectOK: false,
|
||||
name: "too short message",
|
||||
input: []byte{0x00, 0x00, 0x00},
|
||||
expectOK: false,
|
||||
},
|
||||
{
|
||||
name: "no magic byte",
|
||||
input: []byte{0x01, 0x00, 0x00, 0x00, 0x01, 0x48, 0x65, 0x6c, 0x6c, 0x6f},
|
||||
expectOK: false,
|
||||
name: "no magic byte",
|
||||
input: []byte{0x01, 0x00, 0x00, 0x00, 0x01, 0x48, 0x65, 0x6c, 0x6c, 0x6f},
|
||||
expectOK: false,
|
||||
},
|
||||
{
|
||||
name: "empty message",
|
||||
input: []byte{},
|
||||
expectOK: false,
|
||||
name: "empty message",
|
||||
input: []byte{},
|
||||
expectOK: false,
|
||||
},
|
||||
{
|
||||
name: "minimal valid message",
|
||||
input: []byte{0x00, 0x00, 0x00, 0x00, 0x01}, // schema ID 1, empty payload
|
||||
expectOK: true,
|
||||
expectID: 1,
|
||||
name: "minimal valid message",
|
||||
input: []byte{0x00, 0x00, 0x00, 0x00, 0x01}, // schema ID 1, empty payload
|
||||
expectOK: true,
|
||||
expectID: 1,
|
||||
expectFormat: FormatAvro,
|
||||
},
|
||||
}
|
||||
@@ -54,24 +54,24 @@ func TestParseConfluentEnvelope(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
envelope, ok := ParseConfluentEnvelope(tt.input)
|
||||
|
||||
|
||||
if ok != tt.expectOK {
|
||||
t.Errorf("ParseConfluentEnvelope() ok = %v, want %v", ok, tt.expectOK)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if !tt.expectOK {
|
||||
return // No need to check further if we expected failure
|
||||
}
|
||||
|
||||
|
||||
if envelope.SchemaID != tt.expectID {
|
||||
t.Errorf("ParseConfluentEnvelope() schemaID = %v, want %v", envelope.SchemaID, tt.expectID)
|
||||
}
|
||||
|
||||
|
||||
if envelope.Format != tt.expectFormat {
|
||||
t.Errorf("ParseConfluentEnvelope() format = %v, want %v", envelope.Format, tt.expectFormat)
|
||||
}
|
||||
|
||||
|
||||
// Verify payload extraction
|
||||
expectedPayloadLen := len(tt.input) - 5 // 5 bytes for magic + schema ID
|
||||
if len(envelope.Payload) != expectedPayloadLen {
|
||||
@@ -150,11 +150,11 @@ func TestExtractSchemaID(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
id, ok := ExtractSchemaID(tt.input)
|
||||
|
||||
|
||||
if ok != tt.expectOK {
|
||||
t.Errorf("ExtractSchemaID() ok = %v, want %v", ok, tt.expectOK)
|
||||
}
|
||||
|
||||
|
||||
if id != tt.expectID {
|
||||
t.Errorf("ExtractSchemaID() id = %v, want %v", id, tt.expectID)
|
||||
}
|
||||
@@ -200,12 +200,12 @@ func TestCreateConfluentEnvelope(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := CreateConfluentEnvelope(tt.format, tt.schemaID, tt.indexes, tt.payload)
|
||||
|
||||
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("CreateConfluentEnvelope() length = %v, want %v", len(result), len(tt.expected))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
for i, b := range result {
|
||||
if b != tt.expected[i] {
|
||||
t.Errorf("CreateConfluentEnvelope() byte[%d] = %v, want %v", i, b, tt.expected[i])
|
||||
@@ -262,7 +262,7 @@ func TestEnvelopeValidate(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.envelope.Validate()
|
||||
|
||||
|
||||
if (err != nil) != tt.expectErr {
|
||||
t.Errorf("Envelope.Validate() error = %v, expectErr %v", err, tt.expectErr)
|
||||
}
|
||||
@@ -297,7 +297,7 @@ func TestEnvelopeMetadata(t *testing.T) {
|
||||
func BenchmarkParseConfluentEnvelope(b *testing.B) {
|
||||
// Create a test message
|
||||
testMsg := make([]byte, 1024)
|
||||
testMsg[0] = 0x00 // Magic byte
|
||||
testMsg[0] = 0x00 // Magic byte
|
||||
binary.BigEndian.PutUint32(testMsg[1:5], 123) // Schema ID
|
||||
// Fill rest with dummy data
|
||||
for i := 5; i < len(testMsg); i++ {
|
||||
|
||||
@@ -100,7 +100,7 @@ func TestCreateConfluentEnvelopeWithProtobufIndexes(t *testing.T) {
|
||||
parsed, ok := ParseConfluentEnvelope(envelope)
|
||||
require.True(t, ok, "Should be able to parse envelope")
|
||||
assert.Equal(t, tc.schemaID, parsed.SchemaID)
|
||||
|
||||
|
||||
if tc.format == FormatProtobuf && len(tc.indexes) == 0 {
|
||||
// For Protobuf without indexes, payload should match
|
||||
assert.Equal(t, tc.payload, parsed.Payload, "Payload should match")
|
||||
|
||||
@@ -17,5 +17,3 @@ const (
|
||||
// Source file tracking for parquet deduplication
|
||||
ExtendedAttrSources = "sources" // JSON-encoded list of source log files
|
||||
)
|
||||
|
||||
|
||||
+27
-27
@@ -118,17 +118,17 @@ func (m *MigrationManager) GetCurrentVersion() (int, error) {
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create migrations table: %w", err)
|
||||
}
|
||||
|
||||
|
||||
var version sql.NullInt64
|
||||
err = m.db.QueryRow("SELECT MAX(version) FROM schema_migrations").Scan(&version)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to get current version: %w", err)
|
||||
}
|
||||
|
||||
|
||||
if !version.Valid {
|
||||
return 0, nil // No migrations applied yet
|
||||
}
|
||||
|
||||
|
||||
return int(version.Int64), nil
|
||||
}
|
||||
|
||||
@@ -138,29 +138,29 @@ func (m *MigrationManager) ApplyMigrations() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get current version: %w", err)
|
||||
}
|
||||
|
||||
|
||||
migrations := GetMigrations()
|
||||
|
||||
|
||||
for _, migration := range migrations {
|
||||
if migration.Version <= currentVersion {
|
||||
continue // Already applied
|
||||
}
|
||||
|
||||
|
||||
fmt.Printf("Applying migration %d: %s\n", migration.Version, migration.Description)
|
||||
|
||||
|
||||
// Begin transaction
|
||||
tx, err := m.db.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction for migration %d: %w", migration.Version, err)
|
||||
}
|
||||
|
||||
|
||||
// Execute migration SQL
|
||||
_, err = tx.Exec(migration.SQL)
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("failed to execute migration %d: %w", migration.Version, err)
|
||||
}
|
||||
|
||||
|
||||
// Record migration as applied
|
||||
_, err = tx.Exec(
|
||||
"INSERT INTO schema_migrations (version, description, applied_at) VALUES (?, ?, ?)",
|
||||
@@ -172,16 +172,16 @@ func (m *MigrationManager) ApplyMigrations() error {
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("failed to record migration %d: %w", migration.Version, err)
|
||||
}
|
||||
|
||||
|
||||
// Commit transaction
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to commit migration %d: %w", migration.Version, err)
|
||||
}
|
||||
|
||||
|
||||
fmt.Printf("Successfully applied migration %d\n", migration.Version)
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ func (m *MigrationManager) GetAppliedMigrations() ([]AppliedMigration, error) {
|
||||
return nil, fmt.Errorf("failed to query applied migrations: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
|
||||
var migrations []AppliedMigration
|
||||
for rows.Next() {
|
||||
var migration AppliedMigration
|
||||
@@ -213,7 +213,7 @@ func (m *MigrationManager) GetAppliedMigrations() ([]AppliedMigration, error) {
|
||||
}
|
||||
migrations = append(migrations, migration)
|
||||
}
|
||||
|
||||
|
||||
return migrations, nil
|
||||
}
|
||||
|
||||
@@ -223,17 +223,17 @@ func (m *MigrationManager) ValidateSchema() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get current version: %w", err)
|
||||
}
|
||||
|
||||
|
||||
migrations := GetMigrations()
|
||||
if len(migrations) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
latestVersion := migrations[len(migrations)-1].Version
|
||||
if currentVersion < latestVersion {
|
||||
return fmt.Errorf("schema is outdated: current version %d, latest version %d", currentVersion, latestVersion)
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -253,21 +253,21 @@ func getCurrentTimestamp() int64 {
|
||||
func CreateDatabase(dbPath string) (*sql.DB, error) {
|
||||
// TODO: Support different database types (PostgreSQL, MySQL, etc.)
|
||||
// ASSUMPTION: Using SQLite for now, can be extended for other databases
|
||||
|
||||
|
||||
db, err := sql.Open("sqlite3", dbPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open database: %w", err)
|
||||
}
|
||||
|
||||
|
||||
// Configure SQLite for better performance
|
||||
pragmas := []string{
|
||||
"PRAGMA journal_mode=WAL", // Write-Ahead Logging for better concurrency
|
||||
"PRAGMA synchronous=NORMAL", // Balance between safety and performance
|
||||
"PRAGMA cache_size=10000", // Increase cache size
|
||||
"PRAGMA foreign_keys=ON", // Enable foreign key constraints
|
||||
"PRAGMA temp_store=MEMORY", // Store temporary tables in memory
|
||||
"PRAGMA journal_mode=WAL", // Write-Ahead Logging for better concurrency
|
||||
"PRAGMA synchronous=NORMAL", // Balance between safety and performance
|
||||
"PRAGMA cache_size=10000", // Increase cache size
|
||||
"PRAGMA foreign_keys=ON", // Enable foreign key constraints
|
||||
"PRAGMA temp_store=MEMORY", // Store temporary tables in memory
|
||||
}
|
||||
|
||||
|
||||
for _, pragma := range pragmas {
|
||||
_, err := db.Exec(pragma)
|
||||
if err != nil {
|
||||
@@ -275,7 +275,7 @@ func CreateDatabase(dbPath string) (*sql.DB, error) {
|
||||
return nil, fmt.Errorf("failed to set pragma %s: %w", pragma, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Apply migrations
|
||||
migrationManager := NewMigrationManager(db)
|
||||
err = migrationManager.ApplyMigrations()
|
||||
@@ -283,7 +283,7 @@ func CreateDatabase(dbPath string) (*sql.DB, error) {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("failed to apply migrations: %w", err)
|
||||
}
|
||||
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -248,11 +248,11 @@ func TestValidateKeyColumns(t *testing.T) {
|
||||
|
||||
// Helper function to check if string contains substring
|
||||
func contains(str, substr string) bool {
|
||||
return len(str) >= len(substr) &&
|
||||
(len(substr) == 0 || str[len(str)-len(substr):] == substr ||
|
||||
str[:len(substr)] == substr ||
|
||||
len(str) > len(substr) && (str[len(str)-len(substr)-1:len(str)-len(substr)] == " " || str[len(str)-len(substr)-1] == ' ') && str[len(str)-len(substr):] == substr ||
|
||||
findInString(str, substr))
|
||||
return len(str) >= len(substr) &&
|
||||
(len(substr) == 0 || str[len(str)-len(substr):] == substr ||
|
||||
str[:len(substr)] == substr ||
|
||||
len(str) > len(substr) && (str[len(str)-len(substr)-1:len(str)-len(substr)] == " " || str[len(str)-len(substr)-1] == ' ') && str[len(str)-len(substr):] == substr ||
|
||||
findInString(str, substr))
|
||||
}
|
||||
|
||||
func findInString(str, substr string) bool {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package mq_agent_pb
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPublishRecordResponseSerialization(t *testing.T) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package schema_pb
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOffsetTypeEnums(t *testing.T) {
|
||||
@@ -34,8 +34,8 @@ func TestPartitionOffsetSerialization(t *testing.T) {
|
||||
RangeStop: 31,
|
||||
UnixTimeNs: 1234567890,
|
||||
},
|
||||
StartTsNs: 1234567890,
|
||||
StartOffset: 42, // New field
|
||||
StartTsNs: 1234567890,
|
||||
StartOffset: 42, // New field
|
||||
}
|
||||
|
||||
// Test proto marshaling/unmarshaling
|
||||
|
||||
@@ -525,6 +525,13 @@ message VolumeInfo {
|
||||
int64 dat_file_size = 5; // store the original dat file size
|
||||
uint64 expire_at_sec = 6; // expiration time of ec volume
|
||||
bool read_only = 7;
|
||||
EcShardConfig ec_shard_config = 8; // EC shard configuration (optional, null = use default 10+4)
|
||||
}
|
||||
|
||||
// EcShardConfig specifies erasure coding shard configuration
|
||||
message EcShardConfig {
|
||||
uint32 data_shards = 1; // Number of data shards (e.g., 10)
|
||||
uint32 parity_shards = 2; // Number of parity shards (e.g., 4)
|
||||
}
|
||||
message OldVersionVolumeInfo {
|
||||
repeated RemoteFile files = 1;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -28,8 +28,35 @@ import (
|
||||
const (
|
||||
defaultBlockSize = 4 * 1024 * 1024
|
||||
defaultConcurrency = 16
|
||||
|
||||
// DefaultAzureOpTimeout is the timeout for individual Azure blob operations.
|
||||
// This should be larger than the maximum time the Azure SDK client will spend
|
||||
// retrying. With MaxRetries=3 (4 total attempts) and TryTimeout=10s, the maximum
|
||||
// time is roughly 4*10s + delays(~7s) = 47s. We use 60s to provide a reasonable
|
||||
// buffer while still failing faster than indefinite hangs.
|
||||
DefaultAzureOpTimeout = 60 * time.Second
|
||||
)
|
||||
|
||||
// DefaultAzBlobClientOptions returns the default Azure blob client options
|
||||
// with consistent retry configuration across the application.
|
||||
// This centralizes the retry policy to ensure uniform behavior between
|
||||
// remote storage and replication sink implementations.
|
||||
//
|
||||
// Related: Use DefaultAzureOpTimeout for context.WithTimeout when calling Azure operations
|
||||
// to ensure the timeout accommodates all retry attempts configured here.
|
||||
func DefaultAzBlobClientOptions() *azblob.ClientOptions {
|
||||
return &azblob.ClientOptions{
|
||||
ClientOptions: azcore.ClientOptions{
|
||||
Retry: policy.RetryOptions{
|
||||
MaxRetries: 3, // Reasonable retry count - aggressive retries mask configuration errors
|
||||
TryTimeout: 10 * time.Second, // Reduced from 1 minute to fail faster on auth issues
|
||||
RetryDelay: 1 * time.Second,
|
||||
MaxRetryDelay: 10 * time.Second,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// invalidMetadataChars matches any character that is not valid in Azure metadata keys.
|
||||
// Azure metadata keys must be valid C# identifiers: letters, digits, and underscores only.
|
||||
var invalidMetadataChars = regexp.MustCompile(`[^a-zA-Z0-9_]`)
|
||||
@@ -86,16 +113,7 @@ func (s azureRemoteStorageMaker) Make(conf *remote_pb.RemoteConf) (remote_storag
|
||||
}
|
||||
|
||||
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
|
||||
azClient, err := azblob.NewClientWithSharedKeyCredential(serviceURL, credential, &azblob.ClientOptions{
|
||||
ClientOptions: azcore.ClientOptions{
|
||||
Retry: policy.RetryOptions{
|
||||
MaxRetries: 10, // Increased from default 3 to maintain resiliency similar to old SDK's 20
|
||||
TryTimeout: time.Minute,
|
||||
RetryDelay: 2 * time.Second,
|
||||
MaxRetryDelay: time.Minute,
|
||||
},
|
||||
},
|
||||
})
|
||||
azClient, err := azblob.NewClientWithSharedKeyCredential(serviceURL, credential, DefaultAzBlobClientOptions())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create Azure client: %w", err)
|
||||
}
|
||||
|
||||
@@ -229,22 +229,22 @@ func TestToMetadata(t *testing.T) {
|
||||
s3_constants.AmzUserMetaPrefix + "789": []byte("value3"),
|
||||
},
|
||||
expected: map[string]*string{
|
||||
"_123key": stringPtr("value1"), // starts with digit -> prefix _
|
||||
"_456_2d_test": stringPtr("value2"), // starts with digit AND has dash
|
||||
"_789": stringPtr("value3"),
|
||||
"_123key": stringPtr("value1"), // starts with digit -> prefix _
|
||||
"_456_2d_test": stringPtr("value2"), // starts with digit AND has dash
|
||||
"_789": stringPtr("value3"),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "uppercase and mixed case keys",
|
||||
input: map[string][]byte{
|
||||
s3_constants.AmzUserMetaPrefix + "My-Key": []byte("value1"),
|
||||
s3_constants.AmzUserMetaPrefix + "UPPERCASE": []byte("value2"),
|
||||
s3_constants.AmzUserMetaPrefix + "MiXeD-CaSe": []byte("value3"),
|
||||
s3_constants.AmzUserMetaPrefix + "My-Key": []byte("value1"),
|
||||
s3_constants.AmzUserMetaPrefix + "UPPERCASE": []byte("value2"),
|
||||
s3_constants.AmzUserMetaPrefix + "MiXeD-CaSe": []byte("value3"),
|
||||
},
|
||||
expected: map[string]*string{
|
||||
"my_2d_key": stringPtr("value1"), // lowercase + dash -> _2d_
|
||||
"uppercase": stringPtr("value2"),
|
||||
"mixed_2d_case": stringPtr("value3"),
|
||||
"my_2d_key": stringPtr("value1"), // lowercase + dash -> _2d_
|
||||
"uppercase": stringPtr("value2"),
|
||||
"mixed_2d_case": stringPtr("value3"),
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -336,7 +336,10 @@ func TestAzureRemoteStorageMaker(t *testing.T) {
|
||||
t.Error("Expected HasBucket() to return true")
|
||||
}
|
||||
|
||||
// Test with missing credentials
|
||||
// Test with missing credentials - unset env vars (auto-restored by t.Setenv)
|
||||
t.Setenv("AZURE_STORAGE_ACCOUNT", "")
|
||||
t.Setenv("AZURE_STORAGE_ACCESS_KEY", "")
|
||||
|
||||
conf := &remote_pb.RemoteConf{
|
||||
Name: "test",
|
||||
}
|
||||
|
||||
@@ -3,14 +3,9 @@ package azuresink
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
|
||||
@@ -20,6 +15,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage/azure"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/repl_util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/sink"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
@@ -75,22 +71,25 @@ func (g *AzureSink) initialize(accountName, accountKey, container, dir string) e
|
||||
}
|
||||
|
||||
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
|
||||
client, err := azblob.NewClientWithSharedKeyCredential(serviceURL, credential, &azblob.ClientOptions{
|
||||
ClientOptions: azcore.ClientOptions{
|
||||
Retry: policy.RetryOptions{
|
||||
MaxRetries: 10, // Increased from default 3 for replication sink resiliency
|
||||
TryTimeout: time.Minute,
|
||||
RetryDelay: 2 * time.Second,
|
||||
MaxRetryDelay: time.Minute,
|
||||
},
|
||||
},
|
||||
})
|
||||
client, err := azblob.NewClientWithSharedKeyCredential(serviceURL, credential, azure.DefaultAzBlobClientOptions())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create Azure client: %w", err)
|
||||
}
|
||||
|
||||
g.client = client
|
||||
|
||||
// Validate that the container exists early to catch configuration errors
|
||||
containerClient := client.ServiceClient().NewContainerClient(container)
|
||||
ctxValidate, cancelValidate := context.WithTimeout(context.Background(), azure.DefaultAzureOpTimeout)
|
||||
defer cancelValidate()
|
||||
_, err = containerClient.GetProperties(ctxValidate, nil)
|
||||
if err != nil {
|
||||
if bloberror.HasCode(err, bloberror.ContainerNotFound) {
|
||||
return fmt.Errorf("Azure container '%s' does not exist. Please create it first", container)
|
||||
}
|
||||
return fmt.Errorf("failed to validate Azure container '%s': %w", container, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -103,7 +102,9 @@ func (g *AzureSink) DeleteEntry(key string, isDirectory, deleteIncludeChunks boo
|
||||
}
|
||||
|
||||
blobClient := g.client.ServiceClient().NewContainerClient(g.container).NewBlobClient(key)
|
||||
_, err := blobClient.Delete(context.Background(), &blob.DeleteOptions{
|
||||
ctxDelete, cancelDelete := context.WithTimeout(context.Background(), azure.DefaultAzureOpTimeout)
|
||||
defer cancelDelete()
|
||||
_, err := blobClient.Delete(ctxDelete, &blob.DeleteOptions{
|
||||
DeleteSnapshots: to.Ptr(blob.DeleteSnapshotsOptionTypeInclude),
|
||||
})
|
||||
if err != nil {
|
||||
@@ -131,35 +132,34 @@ func (g *AzureSink) CreateEntry(key string, entry *filer_pb.Entry, signatures []
|
||||
// Create append blob client
|
||||
appendBlobClient := g.client.ServiceClient().NewContainerClient(g.container).NewAppendBlobClient(key)
|
||||
|
||||
// Create blob with access conditions
|
||||
accessConditions := &blob.AccessConditions{}
|
||||
if entry.Attributes != nil && entry.Attributes.Mtime > 0 {
|
||||
modifiedTime := time.Unix(entry.Attributes.Mtime, 0)
|
||||
accessConditions.ModifiedAccessConditions = &blob.ModifiedAccessConditions{
|
||||
IfUnmodifiedSince: &modifiedTime,
|
||||
}
|
||||
}
|
||||
|
||||
_, err := appendBlobClient.Create(context.Background(), &appendblob.CreateOptions{
|
||||
AccessConditions: accessConditions,
|
||||
})
|
||||
// Try to create the blob first (without access conditions for initial creation)
|
||||
ctxCreate, cancelCreate := context.WithTimeout(context.Background(), azure.DefaultAzureOpTimeout)
|
||||
defer cancelCreate()
|
||||
_, err := appendBlobClient.Create(ctxCreate, nil)
|
||||
|
||||
needsWrite := true
|
||||
if err != nil {
|
||||
if bloberror.HasCode(err, bloberror.BlobAlreadyExists) {
|
||||
// Blob already exists, which is fine for an append blob - we can append to it
|
||||
} else {
|
||||
// Check if this is a precondition failed error (HTTP 412)
|
||||
var respErr *azcore.ResponseError
|
||||
if ok := errors.As(err, &respErr); ok && respErr.StatusCode == http.StatusPreconditionFailed {
|
||||
glog.V(0).Infof("skip overwriting %s/%s: precondition failed", g.container, key)
|
||||
return nil
|
||||
// Handle existing blob - check if overwrite is needed and perform it if necessary
|
||||
var handleErr error
|
||||
needsWrite, handleErr = g.handleExistingBlob(appendBlobClient, key, entry, totalSize)
|
||||
if handleErr != nil {
|
||||
return handleErr
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("azure create append blob %s/%s: %w", g.container, key, err)
|
||||
}
|
||||
}
|
||||
|
||||
// If we don't need to write (blob is up-to-date), return early
|
||||
if !needsWrite {
|
||||
return nil
|
||||
}
|
||||
|
||||
writeFunc := func(data []byte) error {
|
||||
_, writeErr := appendBlobClient.AppendBlock(context.Background(), streaming.NopCloser(bytes.NewReader(data)), &appendblob.AppendBlockOptions{})
|
||||
ctxWrite, cancelWrite := context.WithTimeout(context.Background(), azure.DefaultAzureOpTimeout)
|
||||
defer cancelWrite()
|
||||
_, writeErr := appendBlobClient.AppendBlock(ctxWrite, streaming.NopCloser(bytes.NewReader(data)), &appendblob.AppendBlockOptions{})
|
||||
return writeErr
|
||||
}
|
||||
|
||||
@@ -174,14 +174,88 @@ func (g *AzureSink) CreateEntry(key string, entry *filer_pb.Entry, signatures []
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleExistingBlob determines whether an existing blob needs to be overwritten and performs the overwrite if necessary.
|
||||
// It returns:
|
||||
// - needsWrite: true if the caller should write data to the blob, false if the blob is already up-to-date
|
||||
// - error: any error encountered during the operation
|
||||
func (g *AzureSink) handleExistingBlob(appendBlobClient *appendblob.Client, key string, entry *filer_pb.Entry, totalSize uint64) (needsWrite bool, err error) {
|
||||
// Get the blob's properties to decide whether to overwrite.
|
||||
// Use a timeout to fail fast on network issues.
|
||||
ctxProps, cancelProps := context.WithTimeout(context.Background(), azure.DefaultAzureOpTimeout)
|
||||
defer cancelProps()
|
||||
props, propErr := appendBlobClient.GetProperties(ctxProps, nil)
|
||||
|
||||
// Fail fast if we cannot fetch properties - we should not proceed to delete without knowing the blob state.
|
||||
if propErr != nil {
|
||||
return false, fmt.Errorf("azure get properties %s/%s: %w", g.container, key, propErr)
|
||||
}
|
||||
|
||||
// Check if we can skip writing based on modification time and size.
|
||||
if entry.Attributes != nil && entry.Attributes.Mtime > 0 && props.LastModified != nil && props.ContentLength != nil {
|
||||
const clockSkewTolerance = int64(2) // seconds - allow small clock differences
|
||||
remoteMtime := props.LastModified.Unix()
|
||||
localMtime := entry.Attributes.Mtime
|
||||
// Skip if remote is newer/same (within skew tolerance) and has the SAME size.
|
||||
// This prevents skipping partial/corrupted files that may have a newer mtime.
|
||||
if remoteMtime >= localMtime-clockSkewTolerance && *props.ContentLength == int64(totalSize) {
|
||||
glog.V(2).Infof("skip overwriting %s/%s: remote is up-to-date (remote mtime: %d >= local mtime: %d, size: %d)",
|
||||
g.container, key, remoteMtime, localMtime, *props.ContentLength)
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Blob is empty or outdated - we need to delete and recreate it.
|
||||
// REQUIRE ETag for conditional delete to avoid race conditions and data loss.
|
||||
if props.ETag == nil {
|
||||
return false, fmt.Errorf("azure blob %s/%s: missing ETag; refusing to delete without conditional", g.container, key)
|
||||
}
|
||||
|
||||
deleteOpts := &blob.DeleteOptions{
|
||||
DeleteSnapshots: to.Ptr(blob.DeleteSnapshotsOptionTypeInclude),
|
||||
AccessConditions: &blob.AccessConditions{
|
||||
ModifiedAccessConditions: &blob.ModifiedAccessConditions{
|
||||
IfMatch: props.ETag,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Delete existing blob with conditional delete and timeout.
|
||||
ctxDel, cancelDel := context.WithTimeout(context.Background(), azure.DefaultAzureOpTimeout)
|
||||
defer cancelDel()
|
||||
_, delErr := appendBlobClient.Delete(ctxDel, deleteOpts)
|
||||
|
||||
if delErr != nil {
|
||||
// If the precondition fails, the blob was modified by another process after we checked it.
|
||||
// Failing here is safe; replication will retry.
|
||||
if bloberror.HasCode(delErr, bloberror.ConditionNotMet) {
|
||||
return false, fmt.Errorf("azure blob %s/%s was modified concurrently, preventing overwrite: %w", g.container, key, delErr)
|
||||
}
|
||||
// Ignore BlobNotFound, as the goal is to delete it anyway.
|
||||
if !bloberror.HasCode(delErr, bloberror.BlobNotFound) {
|
||||
return false, fmt.Errorf("azure delete existing blob %s/%s: %w", g.container, key, delErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Recreate the blob with timeout.
|
||||
ctxRecreate, cancelRecreate := context.WithTimeout(context.Background(), azure.DefaultAzureOpTimeout)
|
||||
defer cancelRecreate()
|
||||
_, createErr := appendBlobClient.Create(ctxRecreate, nil)
|
||||
|
||||
if createErr != nil {
|
||||
// It's possible another process recreated it after our delete.
|
||||
// Failing is safe, as a retry of the whole function will handle it.
|
||||
return false, fmt.Errorf("azure recreate append blob %s/%s: %w", g.container, key, createErr)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (g *AzureSink) UpdateEntry(key string, oldEntry *filer_pb.Entry, newParentPath string, newEntry *filer_pb.Entry, deleteIncludeChunks bool, signatures []int32) (foundExistingEntry bool, err error) {
|
||||
key = cleanKey(key)
|
||||
return true, g.CreateEntry(key, newEntry, signatures)
|
||||
}
|
||||
|
||||
func cleanKey(key string) string {
|
||||
if strings.HasPrefix(key, "/") {
|
||||
key = key[1:]
|
||||
}
|
||||
return key
|
||||
// Remove all leading slashes (TrimLeft handles multiple slashes, unlike TrimPrefix)
|
||||
return strings.TrimLeft(key, "/")
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package azuresink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -320,6 +321,126 @@ func TestAzureSinkPrecondition(t *testing.T) {
|
||||
sink.DeleteEntry(testKey, false, false, nil)
|
||||
}
|
||||
|
||||
// Helper function to get blob content length with timeout
|
||||
func getBlobContentLength(t *testing.T, sink *AzureSink, key string) int64 {
|
||||
t.Helper()
|
||||
containerClient := sink.client.ServiceClient().NewContainerClient(sink.container)
|
||||
blobClient := containerClient.NewAppendBlobClient(cleanKey(key))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
props, err := blobClient.GetProperties(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get blob properties: %v", err)
|
||||
}
|
||||
if props.ContentLength == nil {
|
||||
return 0
|
||||
}
|
||||
return *props.ContentLength
|
||||
}
|
||||
|
||||
// Test that repeated creates don't result in zero-byte files (regression test for critical bug)
|
||||
func TestAzureSinkIdempotentCreate(t *testing.T) {
|
||||
accountName := os.Getenv("AZURE_STORAGE_ACCOUNT")
|
||||
accountKey := os.Getenv("AZURE_STORAGE_ACCESS_KEY")
|
||||
testContainer := os.Getenv("AZURE_TEST_CONTAINER")
|
||||
|
||||
if accountName == "" || accountKey == "" {
|
||||
t.Skip("Skipping Azure sink idempotent create test: credentials not set")
|
||||
}
|
||||
if testContainer == "" {
|
||||
testContainer = "seaweedfs-test"
|
||||
}
|
||||
|
||||
sink := &AzureSink{}
|
||||
err := sink.initialize(accountName, accountKey, testContainer, "/test")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize: %v", err)
|
||||
}
|
||||
|
||||
testKey := "/test-idempotent-" + time.Now().Format("20060102-150405") + ".txt"
|
||||
testContent := []byte("This is test content that should never be empty!")
|
||||
|
||||
// Use fixed time reference for deterministic behavior
|
||||
testTime := time.Now()
|
||||
|
||||
// Clean up at the end
|
||||
defer sink.DeleteEntry(testKey, false, false, nil)
|
||||
|
||||
// Test 1: Create a file with content
|
||||
t.Run("FirstCreate", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Content: testContent,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: testTime.Unix(),
|
||||
},
|
||||
}
|
||||
err := sink.CreateEntry(testKey, entry, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create entry: %v", err)
|
||||
}
|
||||
|
||||
// Verify the file has content (not zero bytes)
|
||||
contentLength := getBlobContentLength(t, sink, testKey)
|
||||
if contentLength == 0 {
|
||||
t.Errorf("File has zero bytes after creation! Expected %d bytes", len(testContent))
|
||||
} else if contentLength != int64(len(testContent)) {
|
||||
t.Errorf("File size mismatch: expected %d, got %d", len(testContent), contentLength)
|
||||
} else {
|
||||
t.Logf("File created with correct size: %d bytes", contentLength)
|
||||
}
|
||||
})
|
||||
|
||||
// Test 2: Create the same file again (idempotent operation - simulates replication running multiple times)
|
||||
// This is where the zero-byte bug occurred: blob existed, precondition failed, returned early without writing data
|
||||
t.Run("IdempotentCreate", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Content: testContent,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: testTime.Add(1 * time.Second).Unix(), // Slightly newer mtime
|
||||
},
|
||||
}
|
||||
err := sink.CreateEntry(testKey, entry, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed on idempotent create: %v", err)
|
||||
}
|
||||
|
||||
// CRITICAL: Verify the file STILL has content (not zero bytes)
|
||||
contentLength := getBlobContentLength(t, sink, testKey)
|
||||
if contentLength == 0 {
|
||||
t.Errorf("ZERO-BYTE BUG: File became empty after idempotent create! Expected %d bytes", len(testContent))
|
||||
} else if contentLength < int64(len(testContent)) {
|
||||
t.Errorf("File lost content: expected at least %d bytes, got %d", len(testContent), contentLength)
|
||||
} else {
|
||||
t.Logf("File still has content after idempotent create: %d bytes", contentLength)
|
||||
}
|
||||
})
|
||||
|
||||
// Test 3: Try creating with older mtime (should skip but not leave zero bytes)
|
||||
t.Run("CreateWithOlderMtime", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{
|
||||
Content: []byte("This content should be skipped"),
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: testTime.Add(-1 * time.Hour).Unix(), // Older timestamp
|
||||
},
|
||||
}
|
||||
err := sink.CreateEntry(testKey, entry, nil)
|
||||
// Should succeed by skipping (no error expected)
|
||||
if err != nil {
|
||||
t.Fatalf("Create with older mtime should be skipped and return no error, but got: %v", err)
|
||||
}
|
||||
|
||||
// Verify file STILL has content
|
||||
contentLength := getBlobContentLength(t, sink, testKey)
|
||||
if contentLength == 0 {
|
||||
t.Errorf("File became empty after create with older mtime!")
|
||||
} else {
|
||||
t.Logf("File preserved content despite older mtime: %d bytes", contentLength)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Benchmark tests
|
||||
func BenchmarkCleanKey(b *testing.B) {
|
||||
keys := []string{
|
||||
|
||||
@@ -153,10 +153,10 @@ func NewIdentityAccessManagementWithStore(option *S3ApiServerOption, explicitSto
|
||||
if err := iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {
|
||||
glog.Fatalf("fail to load config file %s: %v", option.Config, err)
|
||||
}
|
||||
// Mark as loaded since an explicit config file was provided
|
||||
// This prevents fallback to environment variables even if no identities were loaded
|
||||
// (e.g., config file contains only KMS settings)
|
||||
configLoaded = true
|
||||
// Check if any identities were actually loaded from the config file
|
||||
iam.m.RLock()
|
||||
configLoaded = len(iam.identities) > 0
|
||||
iam.m.RUnlock()
|
||||
} else {
|
||||
glog.V(3).Infof("no static config file specified... loading config from credential manager")
|
||||
if err := iam.loadS3ApiConfigurationFromFiler(option); err != nil {
|
||||
@@ -164,9 +164,7 @@ func NewIdentityAccessManagementWithStore(option *S3ApiServerOption, explicitSto
|
||||
} else {
|
||||
// Check if any identities were actually loaded from filer
|
||||
iam.m.RLock()
|
||||
if len(iam.identities) > 0 {
|
||||
configLoaded = true
|
||||
}
|
||||
configLoaded = len(iam.identities) > 0
|
||||
iam.m.RUnlock()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,6 +109,9 @@ func (s3a *S3ApiServer) updateBucketConfigCacheFromEntry(entry *filer_pb.Entry)
|
||||
|
||||
bucket := entry.Name
|
||||
|
||||
glog.V(3).Infof("updateBucketConfigCacheFromEntry: called for bucket %s, ExtObjectLockEnabledKey=%s",
|
||||
bucket, string(entry.Extended[s3_constants.ExtObjectLockEnabledKey]))
|
||||
|
||||
// Create new bucket config from the entry
|
||||
config := &BucketConfig{
|
||||
Name: bucket,
|
||||
@@ -138,7 +141,9 @@ func (s3a *S3ApiServer) updateBucketConfigCacheFromEntry(entry *filer_pb.Entry)
|
||||
// Parse Object Lock configuration if present
|
||||
if objectLockConfig, found := LoadObjectLockConfigurationFromExtended(entry); found {
|
||||
config.ObjectLockConfig = objectLockConfig
|
||||
glog.V(2).Infof("updateBucketConfigCacheFromEntry: cached Object Lock configuration for bucket %s", bucket)
|
||||
glog.V(2).Infof("updateBucketConfigCacheFromEntry: cached Object Lock configuration for bucket %s: %+v", bucket, objectLockConfig)
|
||||
} else {
|
||||
glog.V(3).Infof("updateBucketConfigCacheFromEntry: no Object Lock configuration found for bucket %s", bucket)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +161,7 @@ func (s3a *S3ApiServer) updateBucketConfigCacheFromEntry(entry *filer_pb.Entry)
|
||||
config.LastModified = time.Now()
|
||||
|
||||
// Update cache
|
||||
glog.V(3).Infof("updateBucketConfigCacheFromEntry: updating cache for bucket %s, ObjectLockConfig=%+v", bucket, config.ObjectLockConfig)
|
||||
s3a.bucketConfigCache.Set(bucket, config)
|
||||
}
|
||||
|
||||
|
||||
@@ -362,6 +362,52 @@ func TestNewIdentityAccessManagementWithStoreEnvVars(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigFileWithNoIdentitiesAllowsEnvVars tests that when a config file exists
|
||||
// but contains no identities (e.g., only KMS settings), environment variables should still work.
|
||||
// This test validates the fix for issue #7311.
|
||||
func TestConfigFileWithNoIdentitiesAllowsEnvVars(t *testing.T) {
|
||||
// Set environment variables
|
||||
testAccessKey := "AKIATEST1234567890AB"
|
||||
testSecretKey := "testSecret1234567890123456789012345678901234"
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", testAccessKey)
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", testSecretKey)
|
||||
|
||||
// Create a temporary config file with only KMS settings (no identities)
|
||||
configContent := `{
|
||||
"kms": {
|
||||
"default": {
|
||||
"provider": "local",
|
||||
"config": {
|
||||
"keyPath": "/tmp/test-key"
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
tmpFile, err := os.CreateTemp("", "s3-config-*.json")
|
||||
assert.NoError(t, err, "Should create temp config file")
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
_, err = tmpFile.Write([]byte(configContent))
|
||||
assert.NoError(t, err, "Should write config content")
|
||||
tmpFile.Close()
|
||||
|
||||
// Create IAM instance with config file that has no identities
|
||||
option := &S3ApiServerOption{
|
||||
Config: tmpFile.Name(),
|
||||
}
|
||||
iam := NewIdentityAccessManagementWithStore(option, string(credential.StoreTypeMemory))
|
||||
|
||||
// Should have exactly one identity from environment variables
|
||||
assert.Len(t, iam.identities, 1, "Should have exactly one identity from environment variables even when config file exists with no identities")
|
||||
|
||||
identity := iam.identities[0]
|
||||
assert.Equal(t, "admin-AKIATEST", identity.Name, "Identity name should be based on access key")
|
||||
assert.Len(t, identity.Credentials, 1, "Should have one credential")
|
||||
assert.Equal(t, testAccessKey, identity.Credentials[0].AccessKey, "Access key should match environment variable")
|
||||
assert.Equal(t, testSecretKey, identity.Credentials[0].SecretKey, "Secret key should match environment variable")
|
||||
assert.Contains(t, identity.Actions, Action(ACTION_ADMIN), "Should have admin action")
|
||||
}
|
||||
|
||||
// TestBucketLevelListPermissions tests that bucket-level List permissions work correctly
|
||||
// This test validates the fix for issue #7066
|
||||
func TestBucketLevelListPermissions(t *testing.T) {
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
@@ -590,31 +591,88 @@ func extractSignedHeaders(signedHeaders []string, r *http.Request) (http.Header,
|
||||
|
||||
// extractHostHeader returns the value of host header if available.
|
||||
func extractHostHeader(r *http.Request) string {
|
||||
// Check for X-Forwarded-Host header first, which is set by reverse proxies
|
||||
if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
|
||||
// Check if reverse proxy also forwarded the port
|
||||
if forwardedPort := r.Header.Get("X-Forwarded-Port"); forwardedPort != "" {
|
||||
// Determine the protocol to check for standard ports
|
||||
proto := strings.ToLower(r.Header.Get("X-Forwarded-Proto"))
|
||||
// Only add port if it's not the standard port for the protocol
|
||||
if (proto == "https" && forwardedPort != "443") || (proto != "https" && forwardedPort != "80") {
|
||||
return forwardedHost + ":" + forwardedPort
|
||||
}
|
||||
}
|
||||
// Using reverse proxy with X-Forwarded-Host (standard port or no port forwarded).
|
||||
return forwardedHost
|
||||
forwardedHost := r.Header.Get("X-Forwarded-Host")
|
||||
forwardedPort := r.Header.Get("X-Forwarded-Port")
|
||||
forwardedProto := r.Header.Get("X-Forwarded-Proto")
|
||||
|
||||
// Determine the effective scheme with correct order of precedence:
|
||||
// 1. X-Forwarded-Proto (most authoritative, reflects client's original protocol)
|
||||
// 2. r.TLS (authoritative for direct connection to server)
|
||||
// 3. r.URL.Scheme (fallback, may not always be set correctly)
|
||||
// 4. Default to "http"
|
||||
scheme := "http"
|
||||
if r.URL.Scheme != "" {
|
||||
scheme = r.URL.Scheme
|
||||
}
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
if forwardedProto != "" {
|
||||
scheme = forwardedProto
|
||||
}
|
||||
|
||||
hostHeaderValue := r.Host
|
||||
// For standard requests, this should be fine.
|
||||
if r.Host != "" {
|
||||
return hostHeaderValue
|
||||
var host, port string
|
||||
if forwardedHost != "" {
|
||||
// X-Forwarded-Host can be a comma-separated list of hosts when there are multiple proxies.
|
||||
// Use only the first host in the list and trim spaces for robustness.
|
||||
if comma := strings.Index(forwardedHost, ","); comma != -1 {
|
||||
host = strings.TrimSpace(forwardedHost[:comma])
|
||||
} else {
|
||||
host = strings.TrimSpace(forwardedHost)
|
||||
}
|
||||
port = forwardedPort
|
||||
if h, p, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
if port == "" {
|
||||
port = p
|
||||
}
|
||||
}
|
||||
} else {
|
||||
host = r.Host
|
||||
if host == "" {
|
||||
host = r.URL.Host
|
||||
}
|
||||
if h, p, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
port = p
|
||||
}
|
||||
}
|
||||
// If no host header is found, then check for host URL value.
|
||||
if r.URL.Host != "" {
|
||||
hostHeaderValue = r.URL.Host
|
||||
|
||||
// If we have a non-default port, join it with the host.
|
||||
// net.JoinHostPort will handle bracketing for IPv6.
|
||||
if port != "" && !isDefaultPort(scheme, port) {
|
||||
// Strip existing brackets before calling JoinHostPort, which automatically adds
|
||||
// brackets for IPv6 addresses. This prevents double-bracketing like [[::1]]:8080.
|
||||
// Using Trim handles both well-formed and malformed bracketed hosts.
|
||||
host = strings.Trim(host, "[]")
|
||||
return net.JoinHostPort(host, port)
|
||||
}
|
||||
|
||||
// No port or default port was stripped. According to AWS SDK behavior (aws-sdk-go-v2),
|
||||
// when a default port is removed from an IPv6 address, the brackets should also be removed.
|
||||
// This matches AWS S3 signature calculation requirements.
|
||||
// Reference: https://github.com/aws/aws-sdk-go-v2/blob/main/aws/signer/internal/v4/host.go
|
||||
// The stripPort function returns IPv6 without brackets when port is stripped.
|
||||
if strings.Contains(host, ":") {
|
||||
// This is an IPv6 address. Strip brackets to match AWS SDK behavior.
|
||||
return strings.Trim(host, "[]")
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func isDefaultPort(scheme, port string) bool {
|
||||
if port == "" {
|
||||
return true
|
||||
}
|
||||
|
||||
switch port {
|
||||
case "80":
|
||||
return strings.EqualFold(scheme, "http")
|
||||
case "443":
|
||||
return strings.EqualFold(scheme, "https")
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return hostHeaderValue
|
||||
}
|
||||
|
||||
// getScope generate a string of a specific date, an AWS region, and a service.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -89,3 +90,174 @@ func TestBuildPathWithForwardedPrefix(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractHostHeader tests the extractHostHeader function with various scenarios
|
||||
func TestExtractHostHeader(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
hostHeader string
|
||||
forwardedHost string
|
||||
forwardedPort string
|
||||
forwardedProto string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "basic host without forwarding",
|
||||
hostHeader: "example.com",
|
||||
forwardedHost: "",
|
||||
forwardedPort: "",
|
||||
forwardedProto: "",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
name: "host with port without forwarding",
|
||||
hostHeader: "example.com:8080",
|
||||
forwardedHost: "",
|
||||
forwardedPort: "",
|
||||
forwardedProto: "",
|
||||
expected: "example.com:8080",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host without port",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "example.com",
|
||||
forwardedPort: "",
|
||||
forwardedProto: "",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with X-Forwarded-Port (HTTP non-standard)",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "example.com",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expected: "example.com:8080",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with X-Forwarded-Port (HTTPS non-standard)",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "example.com",
|
||||
forwardedPort: "8443",
|
||||
forwardedProto: "https",
|
||||
expected: "example.com:8443",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with X-Forwarded-Port (HTTP standard port 80)",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "example.com",
|
||||
forwardedPort: "80",
|
||||
forwardedProto: "http",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with X-Forwarded-Port (HTTPS standard port 443)",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "example.com",
|
||||
forwardedPort: "443",
|
||||
forwardedProto: "https",
|
||||
expected: "example.com",
|
||||
},
|
||||
// Issue #6649: X-Forwarded-Host already contains port (Traefik/HAProxy style)
|
||||
{
|
||||
name: "X-Forwarded-Host with port already included (should not add port again)",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "127.0.0.1:8433",
|
||||
forwardedPort: "8433",
|
||||
forwardedProto: "https",
|
||||
expected: "127.0.0.1:8433",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with port, no X-Forwarded-Port header",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "example.com:9000",
|
||||
forwardedPort: "",
|
||||
forwardedProto: "http",
|
||||
expected: "example.com:9000",
|
||||
},
|
||||
// IPv6 test cases
|
||||
{
|
||||
name: "IPv6 address with brackets and port in X-Forwarded-Host",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "[::1]:8080",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expected: "[::1]:8080",
|
||||
},
|
||||
{
|
||||
name: "IPv6 address without brackets, should add brackets with port",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "::1",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expected: "[::1]:8080",
|
||||
},
|
||||
{
|
||||
name: "IPv6 address without brackets and standard port, should strip brackets per AWS SDK",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "::1",
|
||||
forwardedPort: "80",
|
||||
forwardedProto: "http",
|
||||
expected: "::1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 address without brackets and standard HTTPS port, should strip brackets per AWS SDK",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "2001:db8::1",
|
||||
forwardedPort: "443",
|
||||
forwardedProto: "https",
|
||||
expected: "2001:db8::1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 address with brackets but no port, should add port",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "[2001:db8::1]",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expected: "[2001:db8::1]:8080",
|
||||
},
|
||||
{
|
||||
name: "IPv6 full address with brackets and default port (should strip port and brackets)",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "[2001:db8:85a3::8a2e:370:7334]:443",
|
||||
forwardedPort: "443",
|
||||
forwardedProto: "https",
|
||||
expected: "2001:db8:85a3::8a2e:370:7334",
|
||||
},
|
||||
{
|
||||
name: "IPv4-mapped IPv6 address without brackets, should add brackets with port",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "::ffff:127.0.0.1",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expected: "[::ffff:127.0.0.1]:8080",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create a mock request
|
||||
req, err := http.NewRequest("GET", "http://"+tt.hostHeader+"/bucket/object", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create request: %v", err)
|
||||
}
|
||||
|
||||
// Set headers
|
||||
req.Host = tt.hostHeader
|
||||
if tt.forwardedHost != "" {
|
||||
req.Header.Set("X-Forwarded-Host", tt.forwardedHost)
|
||||
}
|
||||
if tt.forwardedPort != "" {
|
||||
req.Header.Set("X-Forwarded-Port", tt.forwardedPort)
|
||||
}
|
||||
if tt.forwardedProto != "" {
|
||||
req.Header.Set("X-Forwarded-Proto", tt.forwardedProto)
|
||||
}
|
||||
|
||||
// Test the function
|
||||
result := extractHostHeader(req)
|
||||
if result != tt.expected {
|
||||
t.Errorf("extractHostHeader() = %q, want %q", result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -392,6 +392,125 @@ func TestSignatureV4WithForwardedPrefixTrailingSlash(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignatureV4WithoutProxy(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
host string
|
||||
proto string
|
||||
expectedHost string
|
||||
}{
|
||||
{
|
||||
name: "HTTP with non-standard port",
|
||||
host: "backend:8333",
|
||||
proto: "http",
|
||||
expectedHost: "backend:8333",
|
||||
},
|
||||
{
|
||||
name: "HTTPS with non-standard port",
|
||||
host: "backend:8333",
|
||||
proto: "https",
|
||||
expectedHost: "backend:8333",
|
||||
},
|
||||
{
|
||||
name: "HTTP with standard port",
|
||||
host: "backend:80",
|
||||
proto: "http",
|
||||
expectedHost: "backend",
|
||||
},
|
||||
{
|
||||
name: "HTTPS with standard port",
|
||||
host: "backend:443",
|
||||
proto: "https",
|
||||
expectedHost: "backend",
|
||||
},
|
||||
{
|
||||
name: "HTTP without port",
|
||||
host: "backend",
|
||||
proto: "http",
|
||||
expectedHost: "backend",
|
||||
},
|
||||
{
|
||||
name: "HTTPS without port",
|
||||
host: "backend",
|
||||
proto: "https",
|
||||
expectedHost: "backend",
|
||||
},
|
||||
{
|
||||
name: "IPv6 HTTP with non-standard port",
|
||||
host: "[::1]:8333",
|
||||
proto: "http",
|
||||
expectedHost: "[::1]:8333",
|
||||
},
|
||||
{
|
||||
name: "IPv6 HTTPS with non-standard port",
|
||||
host: "[::1]:8333",
|
||||
proto: "https",
|
||||
expectedHost: "[::1]:8333",
|
||||
},
|
||||
{
|
||||
name: "IPv6 HTTP with standard port",
|
||||
host: "[::1]:80",
|
||||
proto: "http",
|
||||
expectedHost: "::1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 HTTPS with standard port",
|
||||
host: "[::1]:443",
|
||||
proto: "https",
|
||||
expectedHost: "::1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 HTTP without port",
|
||||
host: "::1",
|
||||
proto: "http",
|
||||
expectedHost: "::1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 HTTPS without port",
|
||||
host: "::1",
|
||||
proto: "https",
|
||||
expectedHost: "::1",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
iam := newTestIAM()
|
||||
|
||||
// Create a request
|
||||
r, err := newTestRequest("GET", tt.proto+"://"+tt.host+"/test-bucket/test-object", 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test request: %v", err)
|
||||
}
|
||||
|
||||
// Set the mux variables manually since we're not going through the actual router
|
||||
r = mux.SetURLVars(r, map[string]string{
|
||||
"bucket": "test-bucket",
|
||||
"object": "test-object",
|
||||
})
|
||||
|
||||
// Set forwarded headers
|
||||
r.Header.Set("Host", tt.host)
|
||||
|
||||
// First, verify that extractHostHeader returns the expected value
|
||||
extractedHost := extractHostHeader(r)
|
||||
if extractedHost != tt.expectedHost {
|
||||
t.Errorf("extractHostHeader() = %q, want %q", extractedHost, tt.expectedHost)
|
||||
}
|
||||
|
||||
// Sign the request with the expected host header
|
||||
// We need to temporarily modify the Host header for signing
|
||||
signV4WithPath(r, "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", r.URL.Path)
|
||||
|
||||
// Test signature verification
|
||||
_, _, errCode := iam.doesSignatureMatch(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
t.Errorf("Expected successful signature validation, got error: %v (code: %d)", errCode, int(errCode))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Test X-Forwarded-Port support for reverse proxy scenarios
|
||||
func TestSignatureV4WithForwardedPort(t *testing.T) {
|
||||
tests := []struct {
|
||||
@@ -450,6 +569,87 @@ func TestSignatureV4WithForwardedPort(t *testing.T) {
|
||||
forwardedProto: "",
|
||||
expectedHost: "example.com",
|
||||
},
|
||||
// Test cases for issue #6649: X-Forwarded-Host already contains port
|
||||
{
|
||||
name: "X-Forwarded-Host with port already included (Traefik/HAProxy style)",
|
||||
host: "backend:8333",
|
||||
forwardedHost: "127.0.0.1:8433",
|
||||
forwardedPort: "8433",
|
||||
forwardedProto: "https",
|
||||
expectedHost: "127.0.0.1:8433",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with port, no X-Forwarded-Port header",
|
||||
host: "backend:8333",
|
||||
forwardedHost: "example.com:9000",
|
||||
forwardedPort: "",
|
||||
forwardedProto: "http",
|
||||
expectedHost: "example.com:9000",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with standard https port already included (Traefik/HAProxy style)",
|
||||
host: "backend:443",
|
||||
forwardedHost: "127.0.0.1:443",
|
||||
forwardedPort: "443",
|
||||
forwardedProto: "https",
|
||||
expectedHost: "127.0.0.1",
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host with standard http port already included (Traefik/HAProxy style)",
|
||||
host: "backend:80",
|
||||
forwardedHost: "127.0.0.1:80",
|
||||
forwardedPort: "80",
|
||||
forwardedProto: "http",
|
||||
expectedHost: "127.0.0.1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 X-Forwarded-Host with standard https port already included (Traefik/HAProxy style)",
|
||||
host: "backend:443",
|
||||
forwardedHost: "[::1]:443",
|
||||
forwardedPort: "443",
|
||||
forwardedProto: "https",
|
||||
expectedHost: "::1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 X-Forwarded-Host with standard http port already included (Traefik/HAProxy style)",
|
||||
host: "backend:80",
|
||||
forwardedHost: "[::1]:80",
|
||||
forwardedPort: "80",
|
||||
forwardedProto: "http",
|
||||
expectedHost: "::1",
|
||||
},
|
||||
{
|
||||
name: "IPv6 with port in brackets",
|
||||
host: "backend:8333",
|
||||
forwardedHost: "[::1]:8080",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expectedHost: "[::1]:8080",
|
||||
},
|
||||
{
|
||||
name: "IPv6 without port - should add port with brackets",
|
||||
host: "backend:8333",
|
||||
forwardedHost: "::1",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expectedHost: "[::1]:8080",
|
||||
},
|
||||
{
|
||||
name: "IPv6 in brackets without port - should add port",
|
||||
host: "backend:8333",
|
||||
forwardedHost: "[2001:db8::1]",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expectedHost: "[2001:db8::1]:8080",
|
||||
},
|
||||
{
|
||||
name: "IPv4-mapped IPv6 without port - should add port with brackets",
|
||||
host: "backend:8333",
|
||||
forwardedHost: "::ffff:127.0.0.1",
|
||||
forwardedPort: "8080",
|
||||
forwardedProto: "http",
|
||||
expectedHost: "[::ffff:127.0.0.1]:8080",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -369,7 +369,6 @@ func (cr *s3ChunkedReader) Read(buf []byte) (n int, err error) {
|
||||
// If we're at the end of a chunk.
|
||||
if cr.n == 0 {
|
||||
cr.state = readChunkTrailer
|
||||
continue
|
||||
}
|
||||
case verifyChunk:
|
||||
// Check if we have credentials for signature verification
|
||||
|
||||
@@ -285,7 +285,16 @@ func TestSignedStreamingUploadInvalidSignature(t *testing.T) {
|
||||
|
||||
// Build the chunked payload with INTENTIONALLY WRONG chunk signature
|
||||
// We'll use a modified signature to simulate a tampered request
|
||||
wrongChunkSignature := strings.Replace(chunk1Signature, "a", "b", 1)
|
||||
wrongChunkSignatureBytes := []byte(chunk1Signature)
|
||||
if len(wrongChunkSignatureBytes) > 0 {
|
||||
// Flip the first hex character to guarantee a different signature
|
||||
if wrongChunkSignatureBytes[0] == '0' {
|
||||
wrongChunkSignatureBytes[0] = '1'
|
||||
} else {
|
||||
wrongChunkSignatureBytes[0] = '0'
|
||||
}
|
||||
}
|
||||
wrongChunkSignature := string(wrongChunkSignatureBytes)
|
||||
payload := fmt.Sprintf("400;chunk-signature=%s\r\n%s\r\n", wrongChunkSignature, chunk1Data) +
|
||||
fmt.Sprintf("0;chunk-signature=%s\r\n\r\n", finalSignature)
|
||||
|
||||
|
||||
@@ -22,16 +22,47 @@ type CORSConfigGetter interface {
|
||||
type Middleware struct {
|
||||
bucketChecker BucketChecker
|
||||
corsConfigGetter CORSConfigGetter
|
||||
fallbackConfig *CORSConfiguration // Global CORS configuration as fallback
|
||||
}
|
||||
|
||||
// NewMiddleware creates a new CORS middleware instance
|
||||
func NewMiddleware(bucketChecker BucketChecker, corsConfigGetter CORSConfigGetter) *Middleware {
|
||||
// NewMiddleware creates a new CORS middleware instance with optional global fallback config
|
||||
func NewMiddleware(bucketChecker BucketChecker, corsConfigGetter CORSConfigGetter, fallbackConfig *CORSConfiguration) *Middleware {
|
||||
return &Middleware{
|
||||
bucketChecker: bucketChecker,
|
||||
corsConfigGetter: corsConfigGetter,
|
||||
fallbackConfig: fallbackConfig,
|
||||
}
|
||||
}
|
||||
|
||||
// getCORSConfig retrieves the applicable CORS configuration, trying bucket-specific first, then fallback.
|
||||
// Returns the configuration and a boolean indicating if any configuration was found.
|
||||
// Only falls back to global config when there's explicitly no bucket-level config.
|
||||
// For other errors (e.g., access denied), returns false to let the handler deny the request.
|
||||
func (m *Middleware) getCORSConfig(bucket string) (*CORSConfiguration, bool) {
|
||||
config, errCode := m.corsConfigGetter.GetCORSConfiguration(bucket)
|
||||
|
||||
switch errCode {
|
||||
case s3err.ErrNone:
|
||||
if config != nil {
|
||||
// Found a bucket-specific config, use it.
|
||||
return config, true
|
||||
}
|
||||
// No bucket config, proceed to fallback.
|
||||
case s3err.ErrNoSuchCORSConfiguration:
|
||||
// No bucket config, proceed to fallback.
|
||||
default:
|
||||
// Any other error means we should not proceed.
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// No bucket-level config found, try global fallback
|
||||
if m.fallbackConfig != nil {
|
||||
return m.fallbackConfig, true
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Handler returns the CORS middleware handler
|
||||
func (m *Middleware) Handler(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -58,10 +89,10 @@ func (m *Middleware) Handler(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// Load CORS configuration from cache
|
||||
config, errCode := m.corsConfigGetter.GetCORSConfiguration(bucket)
|
||||
if errCode != s3err.ErrNone || config == nil {
|
||||
// No CORS configuration, handle based on request type
|
||||
// Get CORS configuration (bucket-specific or fallback)
|
||||
config, found := m.getCORSConfig(bucket)
|
||||
if !found {
|
||||
// No CORS configuration at all, handle based on request type
|
||||
if corsReq.IsPreflightRequest {
|
||||
// Preflight request without CORS config should fail
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
@@ -126,10 +157,10 @@ func (m *Middleware) HandleOptionsRequest(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
// Load CORS configuration from cache
|
||||
config, errCode := m.corsConfigGetter.GetCORSConfiguration(bucket)
|
||||
if errCode != s3err.ErrNone || config == nil {
|
||||
// No CORS configuration for OPTIONS request should return access denied
|
||||
// Get CORS configuration (bucket-specific or fallback)
|
||||
config, found := m.getCORSConfig(bucket)
|
||||
if !found {
|
||||
// No CORS configuration at all for OPTIONS request should return access denied
|
||||
if corsReq.IsPreflightRequest {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
package cors
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// Mock implementations for testing
|
||||
|
||||
type mockBucketChecker struct {
|
||||
bucketExists bool
|
||||
}
|
||||
|
||||
func (m *mockBucketChecker) CheckBucket(r *http.Request, bucket string) s3err.ErrorCode {
|
||||
if m.bucketExists {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
return s3err.ErrNoSuchBucket
|
||||
}
|
||||
|
||||
type mockCORSConfigGetter struct {
|
||||
config *CORSConfiguration
|
||||
errCode s3err.ErrorCode
|
||||
}
|
||||
|
||||
func (m *mockCORSConfigGetter) GetCORSConfiguration(bucket string) (*CORSConfiguration, s3err.ErrorCode) {
|
||||
return m.config, m.errCode
|
||||
}
|
||||
|
||||
// TestMiddlewareFallbackConfig tests that the middleware uses fallback config when bucket-level config is not available
|
||||
func TestMiddlewareFallbackConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
bucketConfig *CORSConfiguration
|
||||
fallbackConfig *CORSConfiguration
|
||||
requestOrigin string
|
||||
requestMethod string
|
||||
isOptions bool
|
||||
expectedStatus int
|
||||
expectedOriginHeader string
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "No bucket config, fallback to global config with wildcard",
|
||||
bucketConfig: nil,
|
||||
fallbackConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "HEAD"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
requestOrigin: "https://example.com",
|
||||
requestMethod: "GET",
|
||||
isOptions: false,
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedOriginHeader: "https://example.com",
|
||||
description: "Should use fallback global config when no bucket config exists",
|
||||
},
|
||||
{
|
||||
name: "No bucket config, fallback to global config with specific origin",
|
||||
bucketConfig: nil,
|
||||
fallbackConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"https://example.com"},
|
||||
AllowedMethods: []string{"GET", "POST"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
requestOrigin: "https://example.com",
|
||||
requestMethod: "GET",
|
||||
isOptions: false,
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedOriginHeader: "https://example.com",
|
||||
description: "Should use fallback config with specific origin match",
|
||||
},
|
||||
{
|
||||
name: "No bucket config, fallback rejects non-matching origin",
|
||||
bucketConfig: nil,
|
||||
fallbackConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"https://allowed.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
requestOrigin: "https://notallowed.com",
|
||||
requestMethod: "GET",
|
||||
isOptions: false,
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedOriginHeader: "",
|
||||
description: "Should not apply CORS headers when origin doesn't match fallback config",
|
||||
},
|
||||
{
|
||||
name: "Bucket config takes precedence over fallback",
|
||||
bucketConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"https://bucket-specific.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
fallbackConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
requestOrigin: "https://bucket-specific.com",
|
||||
requestMethod: "GET",
|
||||
isOptions: false,
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedOriginHeader: "https://bucket-specific.com",
|
||||
description: "Bucket-level config should be used instead of fallback",
|
||||
},
|
||||
{
|
||||
name: "Bucket config rejects, even though fallback would allow",
|
||||
bucketConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"https://restricted.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
fallbackConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
requestOrigin: "https://example.com",
|
||||
requestMethod: "GET",
|
||||
isOptions: false,
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedOriginHeader: "",
|
||||
description: "Bucket-level config is authoritative, fallback should not apply",
|
||||
},
|
||||
{
|
||||
name: "No config at all, no CORS headers",
|
||||
bucketConfig: nil,
|
||||
fallbackConfig: nil,
|
||||
requestOrigin: "https://example.com",
|
||||
requestMethod: "GET",
|
||||
isOptions: false,
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedOriginHeader: "",
|
||||
description: "Without any config, no CORS headers should be applied",
|
||||
},
|
||||
{
|
||||
name: "OPTIONS preflight with fallback config",
|
||||
bucketConfig: nil,
|
||||
fallbackConfig: &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"https://example.com"},
|
||||
AllowedMethods: []string{"GET", "POST"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
requestOrigin: "https://example.com",
|
||||
requestMethod: "OPTIONS",
|
||||
isOptions: true,
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedOriginHeader: "https://example.com",
|
||||
description: "OPTIONS preflight should work with fallback config",
|
||||
},
|
||||
{
|
||||
name: "OPTIONS preflight without any config should fail",
|
||||
bucketConfig: nil,
|
||||
fallbackConfig: nil,
|
||||
requestOrigin: "https://example.com",
|
||||
requestMethod: "OPTIONS",
|
||||
isOptions: true,
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedOriginHeader: "",
|
||||
description: "OPTIONS preflight without config should return 403",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Setup mocks
|
||||
bucketChecker := &mockBucketChecker{bucketExists: true}
|
||||
configGetter := &mockCORSConfigGetter{
|
||||
config: tt.bucketConfig,
|
||||
errCode: s3err.ErrNone,
|
||||
}
|
||||
|
||||
// Create middleware with optional fallback
|
||||
middleware := NewMiddleware(bucketChecker, configGetter, tt.fallbackConfig)
|
||||
|
||||
// Create request with mux variables
|
||||
req := httptest.NewRequest(tt.requestMethod, "/testbucket/testobject", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{
|
||||
"bucket": "testbucket",
|
||||
"object": "testobject",
|
||||
})
|
||||
if tt.requestOrigin != "" {
|
||||
req.Header.Set("Origin", tt.requestOrigin)
|
||||
}
|
||||
if tt.isOptions {
|
||||
req.Header.Set("Access-Control-Request-Method", "GET")
|
||||
}
|
||||
|
||||
// Create response recorder
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// Create a simple handler that returns 200 OK
|
||||
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
// Execute middleware
|
||||
if tt.isOptions {
|
||||
middleware.HandleOptionsRequest(w, req)
|
||||
} else {
|
||||
middleware.Handler(nextHandler).ServeHTTP(w, req)
|
||||
}
|
||||
|
||||
// Check status code
|
||||
if w.Code != tt.expectedStatus {
|
||||
t.Errorf("%s: expected status %d, got %d", tt.description, tt.expectedStatus, w.Code)
|
||||
}
|
||||
|
||||
// Check CORS header
|
||||
actualOrigin := w.Header().Get("Access-Control-Allow-Origin")
|
||||
if actualOrigin != tt.expectedOriginHeader {
|
||||
t.Errorf("%s: expected Access-Control-Allow-Origin='%s', got '%s'",
|
||||
tt.description, tt.expectedOriginHeader, actualOrigin)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMiddlewareFallbackConfigWithMultipleOrigins tests fallback with multiple allowed origins
|
||||
func TestMiddlewareFallbackConfigWithMultipleOrigins(t *testing.T) {
|
||||
fallbackConfig := &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"https://example1.com", "https://example2.com"},
|
||||
AllowedMethods: []string{"GET", "POST"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
bucketChecker := &mockBucketChecker{bucketExists: true}
|
||||
configGetter := &mockCORSConfigGetter{
|
||||
config: nil, // No bucket config
|
||||
errCode: s3err.ErrNone,
|
||||
}
|
||||
|
||||
middleware := NewMiddleware(bucketChecker, configGetter, fallbackConfig)
|
||||
|
||||
tests := []struct {
|
||||
origin string
|
||||
shouldMatch bool
|
||||
description string
|
||||
}{
|
||||
{
|
||||
origin: "https://example1.com",
|
||||
shouldMatch: true,
|
||||
description: "First allowed origin should match",
|
||||
},
|
||||
{
|
||||
origin: "https://example2.com",
|
||||
shouldMatch: true,
|
||||
description: "Second allowed origin should match",
|
||||
},
|
||||
{
|
||||
origin: "https://example3.com",
|
||||
shouldMatch: false,
|
||||
description: "Non-allowed origin should not match",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/testbucket/testobject", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{
|
||||
"bucket": "testbucket",
|
||||
"object": "testobject",
|
||||
})
|
||||
req.Header.Set("Origin", tt.origin)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
middleware.Handler(nextHandler).ServeHTTP(w, req)
|
||||
|
||||
actualOrigin := w.Header().Get("Access-Control-Allow-Origin")
|
||||
if tt.shouldMatch {
|
||||
if actualOrigin != tt.origin {
|
||||
t.Errorf("%s: expected Access-Control-Allow-Origin='%s', got '%s'",
|
||||
tt.description, tt.origin, actualOrigin)
|
||||
}
|
||||
} else {
|
||||
if actualOrigin != "" {
|
||||
t.Errorf("%s: expected no Access-Control-Allow-Origin header, got '%s'",
|
||||
tt.description, actualOrigin)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMiddlewareFallbackWithError tests that real errors (not "no config") don't trigger fallback
|
||||
func TestMiddlewareFallbackWithError(t *testing.T) {
|
||||
fallbackConfig := &CORSConfiguration{
|
||||
CORSRules: []CORSRule{
|
||||
{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
errCode s3err.ErrorCode
|
||||
expectedOriginHeader string
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "ErrAccessDenied should not trigger fallback",
|
||||
errCode: s3err.ErrAccessDenied,
|
||||
expectedOriginHeader: "",
|
||||
description: "Access denied errors should not expose CORS headers",
|
||||
},
|
||||
{
|
||||
name: "ErrInternalError should not trigger fallback",
|
||||
errCode: s3err.ErrInternalError,
|
||||
expectedOriginHeader: "",
|
||||
description: "Internal errors should not expose CORS headers",
|
||||
},
|
||||
{
|
||||
name: "ErrNoSuchBucket should not trigger fallback",
|
||||
errCode: s3err.ErrNoSuchBucket,
|
||||
expectedOriginHeader: "",
|
||||
description: "Bucket not found errors should not expose CORS headers",
|
||||
},
|
||||
{
|
||||
name: "ErrNoSuchCORSConfiguration should trigger fallback",
|
||||
errCode: s3err.ErrNoSuchCORSConfiguration,
|
||||
expectedOriginHeader: "https://example.com",
|
||||
description: "Explicit no CORS config should use fallback",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
bucketChecker := &mockBucketChecker{bucketExists: true}
|
||||
configGetter := &mockCORSConfigGetter{
|
||||
config: nil,
|
||||
errCode: tt.errCode,
|
||||
}
|
||||
|
||||
middleware := NewMiddleware(bucketChecker, configGetter, fallbackConfig)
|
||||
|
||||
req := httptest.NewRequest("GET", "/testbucket/testobject", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{
|
||||
"bucket": "testbucket",
|
||||
"object": "testobject",
|
||||
})
|
||||
req.Header.Set("Origin", "https://example.com")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
middleware.Handler(nextHandler).ServeHTTP(w, req)
|
||||
|
||||
actualOrigin := w.Header().Get("Access-Control-Allow-Origin")
|
||||
if actualOrigin != tt.expectedOriginHeader {
|
||||
t.Errorf("%s: expected Access-Control-Allow-Origin='%s', got '%s'",
|
||||
tt.description, tt.expectedOriginHeader, actualOrigin)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -143,42 +143,106 @@ func TestBucketResourceValidation(t *testing.T) {
|
||||
bucket string
|
||||
valid bool
|
||||
}{
|
||||
// SeaweedFS ARN format
|
||||
{
|
||||
name: "Exact bucket ARN",
|
||||
name: "Exact bucket ARN (SeaweedFS)",
|
||||
resource: "arn:seaweed:s3:::test-bucket",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "Bucket wildcard ARN",
|
||||
name: "Bucket wildcard ARN (SeaweedFS)",
|
||||
resource: "arn:seaweed:s3:::test-bucket/*",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "Specific object ARN",
|
||||
name: "Specific object ARN (SeaweedFS)",
|
||||
resource: "arn:seaweed:s3:::test-bucket/path/to/object.txt",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
// AWS ARN format (compatibility)
|
||||
{
|
||||
name: "Different bucket ARN",
|
||||
name: "Exact bucket ARN (AWS)",
|
||||
resource: "arn:aws:s3:::test-bucket",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "Bucket wildcard ARN (AWS)",
|
||||
resource: "arn:aws:s3:::test-bucket/*",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "Specific object ARN (AWS)",
|
||||
resource: "arn:aws:s3:::test-bucket/path/to/object.txt",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
// Simplified format (without ARN prefix)
|
||||
{
|
||||
name: "Simplified bucket name",
|
||||
resource: "test-bucket",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "Simplified bucket wildcard",
|
||||
resource: "test-bucket/*",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "Simplified specific object",
|
||||
resource: "test-bucket/path/to/object.txt",
|
||||
bucket: "test-bucket",
|
||||
valid: true,
|
||||
},
|
||||
// Invalid cases
|
||||
{
|
||||
name: "Different bucket ARN (SeaweedFS)",
|
||||
resource: "arn:seaweed:s3:::other-bucket/*",
|
||||
bucket: "test-bucket",
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
name: "Global S3 wildcard",
|
||||
name: "Different bucket ARN (AWS)",
|
||||
resource: "arn:aws:s3:::other-bucket/*",
|
||||
bucket: "test-bucket",
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
name: "Different bucket simplified",
|
||||
resource: "other-bucket/*",
|
||||
bucket: "test-bucket",
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
name: "Global S3 wildcard (SeaweedFS)",
|
||||
resource: "arn:seaweed:s3:::*",
|
||||
bucket: "test-bucket",
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
name: "Global S3 wildcard (AWS)",
|
||||
resource: "arn:aws:s3:::*",
|
||||
bucket: "test-bucket",
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid ARN format",
|
||||
resource: "invalid-arn",
|
||||
bucket: "test-bucket",
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
name: "Bucket name prefix match but different bucket",
|
||||
resource: "test-bucket-different/*",
|
||||
bucket: "test-bucket",
|
||||
valid: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -226,3 +290,106 @@ func marshalPolicy(t *testing.T, policyDoc *policy.PolicyDocument) []byte {
|
||||
require.NoError(t, err)
|
||||
return data
|
||||
}
|
||||
|
||||
// TestIssue7252Examples tests the specific examples from GitHub issue #7252
|
||||
func TestIssue7252Examples(t *testing.T) {
|
||||
s3Server := &S3ApiServer{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
policy *policy.PolicyDocument
|
||||
bucket string
|
||||
expectedValid bool
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "Issue #7252 - Standard ARN with wildcard",
|
||||
policy: &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{
|
||||
{
|
||||
Effect: "Allow",
|
||||
Principal: map[string]interface{}{
|
||||
"AWS": "*",
|
||||
},
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"arn:aws:s3:::main-bucket/*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
bucket: "main-bucket",
|
||||
expectedValid: true,
|
||||
description: "AWS ARN format should be accepted",
|
||||
},
|
||||
{
|
||||
name: "Issue #7252 - Simplified resource with wildcard",
|
||||
policy: &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{
|
||||
{
|
||||
Effect: "Allow",
|
||||
Principal: map[string]interface{}{
|
||||
"AWS": "*",
|
||||
},
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"main-bucket/*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
bucket: "main-bucket",
|
||||
expectedValid: true,
|
||||
description: "Simplified format with wildcard should be accepted",
|
||||
},
|
||||
{
|
||||
name: "Issue #7252 - Resource as exact bucket name",
|
||||
policy: &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{
|
||||
{
|
||||
Effect: "Allow",
|
||||
Principal: map[string]interface{}{
|
||||
"AWS": "*",
|
||||
},
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"main-bucket"},
|
||||
},
|
||||
},
|
||||
},
|
||||
bucket: "main-bucket",
|
||||
expectedValid: true,
|
||||
description: "Exact bucket name should be accepted",
|
||||
},
|
||||
{
|
||||
name: "Public read policy with AWS ARN",
|
||||
policy: &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{
|
||||
{
|
||||
Sid: "PublicReadGetObject",
|
||||
Effect: "Allow",
|
||||
Principal: map[string]interface{}{
|
||||
"AWS": "*",
|
||||
},
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"arn:aws:s3:::my-public-bucket/*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
bucket: "my-public-bucket",
|
||||
expectedValid: true,
|
||||
description: "Standard public read policy with AWS ARN should work",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := s3Server.validateBucketPolicy(tt.policy, tt.bucket)
|
||||
|
||||
if tt.expectedValid {
|
||||
assert.NoError(t, err, "Policy should be valid: %s", tt.description)
|
||||
} else {
|
||||
assert.Error(t, err, "Policy should be invalid: %s", tt.description)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ func TestSSES3EndToEndSmallFile(t *testing.T) {
|
||||
|
||||
// Step 3: Decrypt (simulates what happens during GET)
|
||||
// This tests the IV retrieval path for inline files
|
||||
|
||||
|
||||
// First, deserialize metadata from storage
|
||||
retrievedKeyData := mockEntry.Extended[s3_constants.SeaweedFSSSES3Key]
|
||||
retrievedKey, err := DeserializeSSES3Metadata(retrievedKeyData, keyManager)
|
||||
|
||||
@@ -71,7 +71,7 @@ func ValidateSSES3Key(sseKey *SSES3Key) error {
|
||||
if sseKey == nil {
|
||||
return fmt.Errorf("SSE-S3 key cannot be nil")
|
||||
}
|
||||
|
||||
|
||||
// Validate key bytes
|
||||
if sseKey.Key == nil {
|
||||
return fmt.Errorf("SSE-S3 key bytes cannot be nil")
|
||||
@@ -79,22 +79,22 @@ func ValidateSSES3Key(sseKey *SSES3Key) error {
|
||||
if len(sseKey.Key) != SSES3KeySize {
|
||||
return fmt.Errorf("invalid SSE-S3 key size: expected %d bytes, got %d", SSES3KeySize, len(sseKey.Key))
|
||||
}
|
||||
|
||||
|
||||
// Validate algorithm
|
||||
if sseKey.Algorithm != SSES3Algorithm {
|
||||
return fmt.Errorf("invalid SSE-S3 algorithm: expected %q, got %q", SSES3Algorithm, sseKey.Algorithm)
|
||||
}
|
||||
|
||||
|
||||
// Validate key ID (should not be empty)
|
||||
if sseKey.KeyID == "" {
|
||||
return fmt.Errorf("SSE-S3 key ID cannot be empty")
|
||||
}
|
||||
|
||||
|
||||
// IV validation is optional during key creation - it will be set during encryption
|
||||
// If IV is set, validate its length
|
||||
if len(sseKey.IV) > 0 && len(sseKey.IV) != s3_constants.AESBlockSize {
|
||||
return fmt.Errorf("invalid SSE-S3 IV length: expected %d bytes, got %d", s3_constants.AESBlockSize, len(sseKey.IV))
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -350,6 +350,8 @@ func (s3a *S3ApiServer) getBucketConfig(bucket string) (*BucketConfig, s3err.Err
|
||||
|
||||
// Extract configuration from extended attributes
|
||||
if entry.Extended != nil {
|
||||
glog.V(3).Infof("getBucketConfig: checking extended attributes for bucket %s, ExtObjectLockEnabledKey value=%s",
|
||||
bucket, string(entry.Extended[s3_constants.ExtObjectLockEnabledKey]))
|
||||
if versioning, exists := entry.Extended[s3_constants.ExtVersioningKey]; exists {
|
||||
config.Versioning = string(versioning)
|
||||
}
|
||||
@@ -370,7 +372,9 @@ func (s3a *S3ApiServer) getBucketConfig(bucket string) (*BucketConfig, s3err.Err
|
||||
// Parse Object Lock configuration if present
|
||||
if objectLockConfig, found := LoadObjectLockConfigurationFromExtended(entry); found {
|
||||
config.ObjectLockConfig = objectLockConfig
|
||||
glog.V(2).Infof("getBucketConfig: cached Object Lock configuration for bucket %s", bucket)
|
||||
glog.V(3).Infof("getBucketConfig: loaded Object Lock config from extended attributes for bucket %s: %+v", bucket, objectLockConfig)
|
||||
} else {
|
||||
glog.V(3).Infof("getBucketConfig: no Object Lock config found in extended attributes for bucket %s", bucket)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,20 +430,26 @@ func (s3a *S3ApiServer) updateBucketConfig(bucket string, updateFn func(*BucketC
|
||||
}
|
||||
// Update Object Lock configuration
|
||||
if config.ObjectLockConfig != nil {
|
||||
glog.V(3).Infof("updateBucketConfig: storing Object Lock config for bucket %s: %+v", bucket, config.ObjectLockConfig)
|
||||
if err := StoreObjectLockConfigurationInExtended(config.Entry, config.ObjectLockConfig); err != nil {
|
||||
glog.Errorf("updateBucketConfig: failed to store Object Lock configuration for bucket %s: %v", bucket, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
glog.V(3).Infof("updateBucketConfig: stored Object Lock config in extended attributes for bucket %s, key=%s, value=%s",
|
||||
bucket, s3_constants.ExtObjectLockEnabledKey, string(config.Entry.Extended[s3_constants.ExtObjectLockEnabledKey]))
|
||||
}
|
||||
|
||||
// Save to filer
|
||||
glog.V(3).Infof("updateBucketConfig: saving entry to filer for bucket %s", bucket)
|
||||
err := s3a.updateEntry(s3a.option.BucketsPath, config.Entry)
|
||||
if err != nil {
|
||||
glog.Errorf("updateBucketConfig: failed to update bucket entry for %s: %v", bucket, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
glog.V(3).Infof("updateBucketConfig: saved entry to filer for bucket %s", bucket)
|
||||
|
||||
// Update cache
|
||||
glog.V(3).Infof("updateBucketConfig: updating cache for bucket %s, ObjectLockConfig=%+v", bucket, config.ObjectLockConfig)
|
||||
s3a.bucketConfigCache.Set(bucket, config)
|
||||
|
||||
return s3err.ErrNone
|
||||
|
||||
@@ -10,6 +10,19 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// Default CORS configuration for global fallback
|
||||
var (
|
||||
defaultFallbackAllowedMethods = []string{"GET", "PUT", "POST", "DELETE", "HEAD"}
|
||||
defaultFallbackExposeHeaders = []string{
|
||||
"ETag",
|
||||
"Content-Length",
|
||||
"Content-Type",
|
||||
"Last-Modified",
|
||||
"x-amz-request-id",
|
||||
"x-amz-version-id",
|
||||
}
|
||||
)
|
||||
|
||||
// S3BucketChecker implements cors.BucketChecker interface
|
||||
type S3BucketChecker struct {
|
||||
server *S3ApiServer
|
||||
@@ -28,12 +41,36 @@ func (g *S3CORSConfigGetter) GetCORSConfiguration(bucket string) (*cors.CORSConf
|
||||
return g.server.getCORSConfiguration(bucket)
|
||||
}
|
||||
|
||||
// getCORSMiddleware returns a CORS middleware instance with caching
|
||||
// getCORSMiddleware returns a CORS middleware instance with global fallback config
|
||||
func (s3a *S3ApiServer) getCORSMiddleware() *cors.Middleware {
|
||||
bucketChecker := &S3BucketChecker{server: s3a}
|
||||
corsConfigGetter := &S3CORSConfigGetter{server: s3a}
|
||||
|
||||
return cors.NewMiddleware(bucketChecker, corsConfigGetter)
|
||||
// Create fallback CORS configuration from global AllowedOrigins setting
|
||||
fallbackConfig := s3a.createFallbackCORSConfig()
|
||||
|
||||
return cors.NewMiddleware(bucketChecker, corsConfigGetter, fallbackConfig)
|
||||
}
|
||||
|
||||
// createFallbackCORSConfig creates a CORS configuration from global AllowedOrigins
|
||||
func (s3a *S3ApiServer) createFallbackCORSConfig() *cors.CORSConfiguration {
|
||||
if len(s3a.option.AllowedOrigins) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create a permissive CORS rule based on global allowed origins
|
||||
// This matches the behavior of handleCORSOriginValidation
|
||||
rule := cors.CORSRule{
|
||||
AllowedOrigins: s3a.option.AllowedOrigins,
|
||||
AllowedMethods: defaultFallbackAllowedMethods,
|
||||
AllowedHeaders: []string{"*"},
|
||||
ExposeHeaders: defaultFallbackExposeHeaders,
|
||||
MaxAgeSeconds: nil, // No max age by default
|
||||
}
|
||||
|
||||
return &cors.CORSConfiguration{
|
||||
CORSRules: []cors.CORSRule{rule},
|
||||
}
|
||||
}
|
||||
|
||||
// GetBucketCorsHandler handles Get bucket CORS configuration
|
||||
|
||||
@@ -224,6 +224,7 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
// Set the cached Object Lock configuration
|
||||
bucketConfig.ObjectLockConfig = objectLockConfig
|
||||
glog.V(3).Infof("PutBucketHandler: set ObjectLockConfig for bucket %s: %+v", bucket, objectLockConfig)
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -2,11 +2,11 @@ package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"errors"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
@@ -82,7 +82,7 @@ func (s3a *S3ApiServer) GetObjectLockConfigurationHandler(w http.ResponseWriter,
|
||||
return
|
||||
}
|
||||
|
||||
var configXML []byte
|
||||
glog.V(3).Infof("GetObjectLockConfigurationHandler: retrieved bucket config for %s, ObjectLockConfig=%+v", bucket, bucketConfig.ObjectLockConfig)
|
||||
|
||||
// Check if we have cached Object Lock configuration
|
||||
if bucketConfig.ObjectLockConfig != nil {
|
||||
@@ -105,46 +105,67 @@ func (s3a *S3ApiServer) GetObjectLockConfigurationHandler(w http.ResponseWriter,
|
||||
glog.Errorf("GetObjectLockConfigurationHandler: failed to write config XML: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Record metrics
|
||||
stats_collect.RecordBucketActiveTime(bucket)
|
||||
|
||||
glog.V(3).Infof("GetObjectLockConfigurationHandler: successfully retrieved cached object lock config for %s", bucket)
|
||||
return
|
||||
}
|
||||
|
||||
// Fallback: check for legacy storage in extended attributes
|
||||
if bucketConfig.Entry.Extended != nil {
|
||||
// Check if Object Lock is enabled via boolean flag
|
||||
if enabledBytes, exists := bucketConfig.Entry.Extended[s3_constants.ExtObjectLockEnabledKey]; exists {
|
||||
enabled := string(enabledBytes)
|
||||
if enabled == s3_constants.ObjectLockEnabled || enabled == "true" {
|
||||
// Generate minimal XML configuration for enabled Object Lock without retention policies
|
||||
minimalConfig := `<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>`
|
||||
configXML = []byte(minimalConfig)
|
||||
}
|
||||
// If no cached Object Lock configuration, reload entry from filer to get the latest extended attributes
|
||||
// This handles cases where the cache might have a stale entry due to timing issues with metadata updates
|
||||
glog.V(3).Infof("GetObjectLockConfigurationHandler: no cached ObjectLockConfig, reloading entry from filer for %s", bucket)
|
||||
freshEntry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
glog.V(1).Infof("GetObjectLockConfigurationHandler: bucket %s not found while reloading entry", bucket)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// If no Object Lock configuration found, return error
|
||||
if len(configXML) == 0 {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrObjectLockConfigurationNotFoundError)
|
||||
glog.Errorf("GetObjectLockConfigurationHandler: failed to reload bucket entry: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
// Set response headers
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
// Try to load Object Lock configuration from the fresh entry
|
||||
// LoadObjectLockConfigurationFromExtended already checks ExtObjectLockEnabledKey and returns
|
||||
// a basic configuration even when there's no default retention policy
|
||||
if objectLockConfig, found := LoadObjectLockConfigurationFromExtended(freshEntry); found {
|
||||
glog.V(3).Infof("GetObjectLockConfigurationHandler: loaded Object Lock config from fresh entry for %s: %+v", bucket, objectLockConfig)
|
||||
|
||||
// Write XML response
|
||||
if _, err := w.Write([]byte(xml.Header)); err != nil {
|
||||
glog.Errorf("GetObjectLockConfigurationHandler: failed to write XML header: %v", err)
|
||||
// Rebuild the entire cached config from the fresh entry to maintain cache coherence
|
||||
// This ensures all fields (Versioning, Owner, ACL, IsPublicRead, CORS, etc.) are up-to-date,
|
||||
// not just ObjectLockConfig, before resetting the TTL
|
||||
s3a.updateBucketConfigCacheFromEntry(freshEntry)
|
||||
|
||||
// Marshal and return the configuration
|
||||
marshaledXML, err := xml.Marshal(objectLockConfig)
|
||||
if err != nil {
|
||||
glog.Errorf("GetObjectLockConfigurationHandler: failed to marshal Object Lock config: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := w.Write([]byte(xml.Header)); err != nil {
|
||||
glog.Errorf("GetObjectLockConfigurationHandler: failed to write XML header: %v", err)
|
||||
return
|
||||
}
|
||||
if _, err := w.Write(marshaledXML); err != nil {
|
||||
glog.Errorf("GetObjectLockConfigurationHandler: failed to write config XML: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Record metrics
|
||||
stats_collect.RecordBucketActiveTime(bucket)
|
||||
|
||||
glog.V(3).Infof("GetObjectLockConfigurationHandler: successfully retrieved object lock config from fresh entry for %s", bucket)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := w.Write(configXML); err != nil {
|
||||
glog.Errorf("GetObjectLockConfigurationHandler: failed to write config XML: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Record metrics
|
||||
stats_collect.RecordBucketActiveTime(bucket)
|
||||
|
||||
glog.V(3).Infof("GetObjectLockConfigurationHandler: successfully retrieved object lock config for %s", bucket)
|
||||
// No Object Lock configuration found
|
||||
glog.V(3).Infof("GetObjectLockConfigurationHandler: no Object Lock configuration found for %s", bucket)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrObjectLockConfigurationNotFoundError)
|
||||
}
|
||||
@@ -274,18 +274,38 @@ func (s3a *S3ApiServer) validateBucketPolicy(policyDoc *policy.PolicyDocument, b
|
||||
|
||||
// validateResourceForBucket checks if a resource ARN is valid for the given bucket
|
||||
func (s3a *S3ApiServer) validateResourceForBucket(resource, bucket string) bool {
|
||||
// Expected formats:
|
||||
// arn:seaweed:s3:::bucket-name
|
||||
// arn:seaweed:s3:::bucket-name/*
|
||||
// arn:seaweed:s3:::bucket-name/path/to/object
|
||||
// Accepted formats for S3 bucket policies:
|
||||
// AWS-style ARNs:
|
||||
// arn:aws:s3:::bucket-name
|
||||
// arn:aws:s3:::bucket-name/*
|
||||
// arn:aws:s3:::bucket-name/path/to/object
|
||||
// SeaweedFS ARNs:
|
||||
// arn:seaweed:s3:::bucket-name
|
||||
// arn:seaweed:s3:::bucket-name/*
|
||||
// arn:seaweed:s3:::bucket-name/path/to/object
|
||||
// Simplified formats (for convenience):
|
||||
// bucket-name
|
||||
// bucket-name/*
|
||||
// bucket-name/path/to/object
|
||||
|
||||
expectedBucketArn := fmt.Sprintf("arn:seaweed:s3:::%s", bucket)
|
||||
expectedBucketWildcard := fmt.Sprintf("arn:seaweed:s3:::%s/*", bucket)
|
||||
expectedBucketPath := fmt.Sprintf("arn:seaweed:s3:::%s/", bucket)
|
||||
var resourcePath string
|
||||
const awsPrefix = "arn:aws:s3:::"
|
||||
const seaweedPrefix = "arn:seaweed:s3:::"
|
||||
|
||||
return resource == expectedBucketArn ||
|
||||
resource == expectedBucketWildcard ||
|
||||
strings.HasPrefix(resource, expectedBucketPath)
|
||||
// Strip the optional ARN prefix to get the resource path
|
||||
if path, ok := strings.CutPrefix(resource, awsPrefix); ok {
|
||||
resourcePath = path
|
||||
} else if path, ok := strings.CutPrefix(resource, seaweedPrefix); ok {
|
||||
resourcePath = path
|
||||
} else {
|
||||
resourcePath = resource
|
||||
}
|
||||
|
||||
// After stripping the optional ARN prefix, the resource path must
|
||||
// either match the bucket name exactly, or be a path within the bucket.
|
||||
return resourcePath == bucket ||
|
||||
resourcePath == bucket+"/*" ||
|
||||
strings.HasPrefix(resourcePath, bucket+"/")
|
||||
}
|
||||
|
||||
// IAM integration functions
|
||||
|
||||
@@ -2,6 +2,7 @@ package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -671,6 +672,86 @@ func TestETagMatching(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetObjectETagWithMd5AndChunks tests the fix for issue #7274
|
||||
// When an object has both Attributes.Md5 and multiple chunks, getObjectETag should
|
||||
// prefer Attributes.Md5 to match the behavior of HeadObject and filer.ETag
|
||||
func TestGetObjectETagWithMd5AndChunks(t *testing.T) {
|
||||
s3a := NewS3ApiServerForTest()
|
||||
if s3a == nil {
|
||||
t.Skip("S3ApiServer not available for testing")
|
||||
}
|
||||
|
||||
// Create an object with both Md5 and multiple chunks (like in issue #7274)
|
||||
// Md5: ZjcmMwrCVGNVgb4HoqHe9g== (base64) = 663726330ac254635581be07a2a1def6 (hex)
|
||||
md5HexString := "663726330ac254635581be07a2a1def6"
|
||||
md5Bytes, err := hex.DecodeString(md5HexString)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to decode md5 hex string: %v", err)
|
||||
}
|
||||
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "test-multipart-object",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
FileSize: 5597744,
|
||||
Md5: md5Bytes,
|
||||
},
|
||||
// Two chunks - if we only used ETagChunks, it would return format "hash-2"
|
||||
Chunks: []*filer_pb.FileChunk{
|
||||
{
|
||||
FileId: "chunk1",
|
||||
Offset: 0,
|
||||
Size: 4194304,
|
||||
ETag: "9+yCD2DGwMG5uKwAd+y04Q==",
|
||||
},
|
||||
{
|
||||
FileId: "chunk2",
|
||||
Offset: 4194304,
|
||||
Size: 1403440,
|
||||
ETag: "cs6SVSTgZ8W3IbIrAKmklg==",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// getObjectETag should return the Md5 in hex with quotes
|
||||
expectedETag := "\"" + md5HexString + "\""
|
||||
actualETag := s3a.getObjectETag(entry)
|
||||
|
||||
if actualETag != expectedETag {
|
||||
t.Errorf("Expected ETag %s, got %s", expectedETag, actualETag)
|
||||
}
|
||||
|
||||
// Now test that conditional headers work with this ETag
|
||||
bucket := "test-bucket"
|
||||
object := "/test-object"
|
||||
|
||||
// Test If-Match with the Md5-based ETag (should succeed)
|
||||
t.Run("IfMatch_WithMd5BasedETag_ShouldSucceed", func(t *testing.T) {
|
||||
getter := createMockEntryGetter(entry)
|
||||
req := createTestGetRequest(bucket, object)
|
||||
// Client sends the ETag from HeadObject (without quotes)
|
||||
req.Header.Set(s3_constants.IfMatch, md5HexString)
|
||||
|
||||
result := s3a.checkConditionalHeadersForReadsWithGetter(getter, req, bucket, object)
|
||||
if result.ErrorCode != s3err.ErrNone {
|
||||
t.Errorf("Expected ErrNone when If-Match uses Md5-based ETag, got %v (ETag was %s)", result.ErrorCode, actualETag)
|
||||
}
|
||||
})
|
||||
|
||||
// Test If-Match with chunk-based ETag format (should fail - this was the old incorrect behavior)
|
||||
t.Run("IfMatch_WithChunkBasedETag_ShouldFail", func(t *testing.T) {
|
||||
getter := createMockEntryGetter(entry)
|
||||
req := createTestGetRequest(bucket, object)
|
||||
// If we incorrectly calculated ETag from chunks, it would be in format "hash-2"
|
||||
req.Header.Set(s3_constants.IfMatch, "123294de680f28bde364b81477549f7d-2")
|
||||
|
||||
result := s3a.checkConditionalHeadersForReadsWithGetter(getter, req, bucket, object)
|
||||
if result.ErrorCode != s3err.ErrPreconditionFailed {
|
||||
t.Errorf("Expected ErrPreconditionFailed when If-Match uses chunk-based ETag format, got %v", result.ErrorCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestConditionalHeadersIntegration tests conditional headers with full integration
|
||||
func TestConditionalHeadersIntegration(t *testing.T) {
|
||||
// This would be a full integration test that requires a running SeaweedFS instance
|
||||
|
||||
@@ -1257,6 +1257,11 @@ func (s3a *S3ApiServer) getObjectETag(entry *filer_pb.Entry) string {
|
||||
if etagBytes, hasETag := entry.Extended[s3_constants.ExtETagKey]; hasETag {
|
||||
return string(etagBytes)
|
||||
}
|
||||
// Check for Md5 in Attributes (matches filer.ETag behavior)
|
||||
// Note: len(nil slice) == 0 in Go, so no need for explicit nil check
|
||||
if entry.Attributes != nil && len(entry.Attributes.Md5) > 0 {
|
||||
return fmt.Sprintf("\"%x\"", entry.Attributes.Md5)
|
||||
}
|
||||
// Fallback: calculate ETag from chunks
|
||||
return s3a.calculateETagFromChunks(entry.Chunks)
|
||||
}
|
||||
|
||||
@@ -473,12 +473,23 @@ func loadIAMManagerFromConfig(configPath string, filerAddressProvider func() str
|
||||
return nil, fmt.Errorf("failed to parse config: %w", err)
|
||||
}
|
||||
|
||||
// Ensure a valid policy engine config exists
|
||||
if configRoot.Policy == nil {
|
||||
// Provide a secure default if not specified in the config file
|
||||
// Default to Deny with in-memory store so that JSON-defined policies work without filer
|
||||
glog.V(0).Infof("No policy engine config provided; using defaults (DefaultEffect=%s, StoreType=%s)", sts.EffectDeny, sts.StoreTypeMemory)
|
||||
configRoot.Policy = &policy.PolicyEngineConfig{
|
||||
DefaultEffect: sts.EffectDeny,
|
||||
StoreType: sts.StoreTypeMemory,
|
||||
}
|
||||
}
|
||||
|
||||
// Create IAM configuration
|
||||
iamConfig := &integration.IAMConfig{
|
||||
STS: configRoot.STS,
|
||||
Policy: configRoot.Policy,
|
||||
Roles: &integration.RoleStoreConfig{
|
||||
StoreType: "memory", // Use memory store for JSON config-based setup
|
||||
StoreType: sts.StoreTypeMemory, // Use memory store for JSON config-based setup
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -369,8 +369,7 @@ func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64
|
||||
err = writeFn(bufferedWriter)
|
||||
if err != nil {
|
||||
glog.Errorf("ProcessRangeRequest range[0]: %+v err: %v", w.Header(), err)
|
||||
w.Header().Del("Content-Length")
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
// Cannot call http.Error() here because WriteHeader was already called
|
||||
return fmt.Errorf("ProcessRangeRequest range[0]: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -424,7 +423,7 @@ func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
if _, err := io.CopyN(bufferedWriter, sendContent, sendSize); err != nil {
|
||||
glog.Errorf("ProcessRangeRequest err: %v", err)
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
// Cannot call http.Error() here because WriteHeader was already called
|
||||
return fmt.Errorf("ProcessRangeRequest err: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
@@ -17,6 +16,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
)
|
||||
|
||||
func (fs *FilerServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
@@ -94,31 +94,31 @@ func (fs *FilerServer) LookupVolume(ctx context.Context, req *filer_pb.LookupVol
|
||||
LocationsMap: make(map[string]*filer_pb.Locations),
|
||||
}
|
||||
|
||||
for _, vidString := range req.VolumeIds {
|
||||
vid, err := strconv.Atoi(vidString)
|
||||
if err != nil {
|
||||
glog.V(1).InfofCtx(ctx, "Unknown volume id %d", vid)
|
||||
return nil, err
|
||||
}
|
||||
var locs []*filer_pb.Location
|
||||
locations, found := fs.filer.MasterClient.GetLocations(uint32(vid))
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
for _, loc := range locations {
|
||||
locs = append(locs, &filer_pb.Location{
|
||||
Url: loc.Url,
|
||||
PublicUrl: loc.PublicUrl,
|
||||
GrpcPort: uint32(loc.GrpcPort),
|
||||
DataCenter: loc.DataCenter,
|
||||
})
|
||||
}
|
||||
// Use master client's lookup with fallback - it handles cache and master query
|
||||
vidLocations, err := fs.filer.MasterClient.LookupVolumeIdsWithFallback(ctx, req.VolumeIds)
|
||||
|
||||
// Convert wdclient.Location to filer_pb.Location
|
||||
// Return partial results even if there was an error
|
||||
for vidString, locations := range vidLocations {
|
||||
resp.LocationsMap[vidString] = &filer_pb.Locations{
|
||||
Locations: locs,
|
||||
Locations: wdclientLocationsToPb(locations),
|
||||
}
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func wdclientLocationsToPb(locations []wdclient.Location) []*filer_pb.Location {
|
||||
locs := make([]*filer_pb.Location, 0, len(locations))
|
||||
for _, loc := range locations {
|
||||
locs = append(locs, &filer_pb.Location{
|
||||
Url: loc.Url,
|
||||
PublicUrl: loc.PublicUrl,
|
||||
GrpcPort: uint32(loc.GrpcPort),
|
||||
DataCenter: loc.DataCenter,
|
||||
})
|
||||
}
|
||||
return locs
|
||||
}
|
||||
|
||||
func (fs *FilerServer) lookupFileId(ctx context.Context, fileId string) (targetUrls []string, err error) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
@@ -287,13 +288,20 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
streamFn, err := filer.PrepareStreamContentWithThrottler(ctx, fs.filer.MasterClient, fs.maybeGetVolumeReadJwtAuthorizationToken, chunks, offset, size, fs.option.DownloadMaxBytesPs)
|
||||
// Use a detached context for streaming so client disconnects/cancellations don't abort volume server operations,
|
||||
// while preserving request-scoped values like tracing IDs.
|
||||
// Matches S3 API behavior. Request context (ctx) is used for metadata operations above.
|
||||
streamCtx, streamCancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
|
||||
streamFn, err := filer.PrepareStreamContentWithThrottler(streamCtx, fs.filer.MasterClient, fs.maybeGetVolumeReadJwtAuthorizationToken, chunks, offset, size, fs.option.DownloadMaxBytesPs)
|
||||
if err != nil {
|
||||
streamCancel()
|
||||
stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadStream).Inc()
|
||||
glog.ErrorfCtx(ctx, "failed to prepare stream content %s: %v", r.URL, err)
|
||||
return nil, err
|
||||
}
|
||||
return func(writer io.Writer) error {
|
||||
defer streamCancel()
|
||||
err := streamFn(writer)
|
||||
if err != nil {
|
||||
stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadStream).Inc()
|
||||
|
||||
@@ -50,20 +50,38 @@ func (vs *VolumeServer) VolumeEcShardsGenerate(ctx context.Context, req *volume_
|
||||
return nil, fmt.Errorf("existing collection:%v unexpected input: %v", v.Collection, req.Collection)
|
||||
}
|
||||
|
||||
// Create EC context - prefer existing .vif config if present (for regeneration scenarios)
|
||||
ecCtx := erasure_coding.NewDefaultECContext(req.Collection, needle.VolumeId(req.VolumeId))
|
||||
if volumeInfo, _, found, _ := volume_info.MaybeLoadVolumeInfo(baseFileName + ".vif"); found && volumeInfo.EcShardConfig != nil {
|
||||
ds := int(volumeInfo.EcShardConfig.DataShards)
|
||||
ps := int(volumeInfo.EcShardConfig.ParityShards)
|
||||
|
||||
// Validate and use existing EC config
|
||||
if ds > 0 && ps > 0 && ds+ps <= erasure_coding.MaxShardCount {
|
||||
ecCtx.DataShards = ds
|
||||
ecCtx.ParityShards = ps
|
||||
glog.V(0).Infof("Using existing EC config for volume %d: %s", req.VolumeId, ecCtx.String())
|
||||
} else {
|
||||
glog.Warningf("Invalid EC config in .vif for volume %d (data=%d, parity=%d), using defaults", req.VolumeId, ds, ps)
|
||||
}
|
||||
} else {
|
||||
glog.V(0).Infof("Using default EC config for volume %d: %s", req.VolumeId, ecCtx.String())
|
||||
}
|
||||
|
||||
shouldCleanup := true
|
||||
defer func() {
|
||||
if !shouldCleanup {
|
||||
return
|
||||
}
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
os.Remove(fmt.Sprintf("%s.ec%2d", baseFileName, i))
|
||||
for i := 0; i < ecCtx.Total(); i++ {
|
||||
os.Remove(baseFileName + ecCtx.ToExt(i))
|
||||
}
|
||||
os.Remove(v.IndexFileName() + ".ecx")
|
||||
}()
|
||||
|
||||
// write .ec00 ~ .ec13 files
|
||||
if err := erasure_coding.WriteEcFiles(baseFileName); err != nil {
|
||||
return nil, fmt.Errorf("WriteEcFiles %s: %v", baseFileName, err)
|
||||
// write .ec00 ~ .ec[TotalShards-1] files using context
|
||||
if err := erasure_coding.WriteEcFilesWithContext(baseFileName, ecCtx); err != nil {
|
||||
return nil, fmt.Errorf("WriteEcFilesWithContext %s: %v", baseFileName, err)
|
||||
}
|
||||
|
||||
// write .ecx file
|
||||
@@ -84,6 +102,21 @@ func (vs *VolumeServer) VolumeEcShardsGenerate(ctx context.Context, req *volume_
|
||||
|
||||
datSize, _, _ := v.FileStat()
|
||||
volumeInfo.DatFileSize = int64(datSize)
|
||||
|
||||
// Validate EC configuration before saving to .vif
|
||||
if ecCtx.DataShards <= 0 || ecCtx.ParityShards <= 0 || ecCtx.Total() > erasure_coding.MaxShardCount {
|
||||
return nil, fmt.Errorf("invalid EC config before saving: data=%d, parity=%d, total=%d (max=%d)",
|
||||
ecCtx.DataShards, ecCtx.ParityShards, ecCtx.Total(), erasure_coding.MaxShardCount)
|
||||
}
|
||||
|
||||
// Save EC configuration to VolumeInfo
|
||||
volumeInfo.EcShardConfig = &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(ecCtx.DataShards),
|
||||
ParityShards: uint32(ecCtx.ParityShards),
|
||||
}
|
||||
glog.V(1).Infof("Saving EC config to .vif for volume %d: %d+%d (total: %d)",
|
||||
req.VolumeId, ecCtx.DataShards, ecCtx.ParityShards, ecCtx.Total())
|
||||
|
||||
if err := volume_info.SaveVolumeInfo(baseFileName+".vif", volumeInfo); err != nil {
|
||||
return nil, fmt.Errorf("SaveVolumeInfo %s: %v", baseFileName, err)
|
||||
}
|
||||
@@ -442,9 +475,10 @@ func (vs *VolumeServer) VolumeEcShardsToVolume(ctx context.Context, req *volume_
|
||||
|
||||
glog.V(0).Infof("VolumeEcShardsToVolume: %v", req)
|
||||
|
||||
// collect .ec00 ~ .ec09 files
|
||||
shardFileNames := make([]string, erasure_coding.DataShardsCount)
|
||||
v, found := vs.store.CollectEcShards(needle.VolumeId(req.VolumeId), shardFileNames)
|
||||
// Collect all EC shards (NewEcVolume will load EC config from .vif into v.ECContext)
|
||||
// Use MaxShardCount (32) to support custom EC ratios up to 32 total shards
|
||||
tempShards := make([]string, erasure_coding.MaxShardCount)
|
||||
v, found := vs.store.CollectEcShards(needle.VolumeId(req.VolumeId), tempShards)
|
||||
if !found {
|
||||
return nil, fmt.Errorf("ec volume %d not found", req.VolumeId)
|
||||
}
|
||||
@@ -453,7 +487,19 @@ func (vs *VolumeServer) VolumeEcShardsToVolume(ctx context.Context, req *volume_
|
||||
return nil, fmt.Errorf("existing collection:%v unexpected input: %v", v.Collection, req.Collection)
|
||||
}
|
||||
|
||||
for shardId := 0; shardId < erasure_coding.DataShardsCount; shardId++ {
|
||||
// Use EC context (already loaded from .vif) to determine data shard count
|
||||
dataShards := v.ECContext.DataShards
|
||||
|
||||
// Defensive validation to prevent panics from corrupted ECContext
|
||||
if dataShards <= 0 || dataShards > erasure_coding.MaxShardCount {
|
||||
return nil, fmt.Errorf("invalid data shard count %d for volume %d (must be 1..%d)", dataShards, req.VolumeId, erasure_coding.MaxShardCount)
|
||||
}
|
||||
|
||||
shardFileNames := tempShards[:dataShards]
|
||||
glog.V(1).Infof("Using EC config from volume %d: %d data shards", req.VolumeId, dataShards)
|
||||
|
||||
// Verify all data shards are present
|
||||
for shardId := 0; shardId < dataShards; shardId++ {
|
||||
if shardFileNames[shardId] == "" {
|
||||
return nil, fmt.Errorf("ec volume %d missing shard %d", req.VolumeId, shardId)
|
||||
}
|
||||
|
||||
@@ -622,7 +622,8 @@ func (ecb *ecBalancer) deleteDuplicatedEcShards(collection string) error {
|
||||
|
||||
func (ecb *ecBalancer) doDeduplicateEcShards(collection string, vid needle.VolumeId, locations []*EcNode) error {
|
||||
// check whether this volume has ecNodes that are over average
|
||||
shardToLocations := make([][]*EcNode, erasure_coding.TotalShardsCount)
|
||||
// Use MaxShardCount (32) to support custom EC ratios
|
||||
shardToLocations := make([][]*EcNode, erasure_coding.MaxShardCount)
|
||||
for _, ecNode := range locations {
|
||||
shardBits := findEcVolumeShards(ecNode, vid)
|
||||
for _, shardId := range shardBits.ShardIds() {
|
||||
@@ -677,11 +678,16 @@ func countShardsByRack(vid needle.VolumeId, locations []*EcNode) map[string]int
|
||||
func (ecb *ecBalancer) doBalanceEcShardsAcrossRacks(collection string, vid needle.VolumeId, locations []*EcNode) error {
|
||||
racks := ecb.racks()
|
||||
|
||||
// calculate average number of shards an ec rack should have for one volume
|
||||
averageShardsPerEcRack := ceilDivide(erasure_coding.TotalShardsCount, len(racks))
|
||||
|
||||
// see the volume's shards are in how many racks, and how many in each rack
|
||||
rackToShardCount := countShardsByRack(vid, locations)
|
||||
|
||||
// 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)
|
||||
})
|
||||
|
||||
@@ -79,20 +79,20 @@ func (c *commandEcRebuild) Do(args []string, commandEnv *CommandEnv, writer io.W
|
||||
return err
|
||||
}
|
||||
|
||||
var collections []string
|
||||
if *collection == "EACH_COLLECTION" {
|
||||
collections, err := ListCollectionNames(commandEnv, false, true)
|
||||
collections, err = ListCollectionNames(commandEnv, false, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("rebuildEcVolumes collections %+v\n", len(collections))
|
||||
for _, c := range collections {
|
||||
fmt.Printf("rebuildEcVolumes collection %+v\n", c)
|
||||
if err = rebuildEcVolumes(commandEnv, allEcNodes, c, writer, *applyChanges); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err = rebuildEcVolumes(commandEnv, allEcNodes, *collection, writer, *applyChanges); err != nil {
|
||||
collections = []string{*collection}
|
||||
}
|
||||
|
||||
fmt.Printf("rebuildEcVolumes for %d collection(s)\n", len(collections))
|
||||
for _, c := range collections {
|
||||
fmt.Printf("rebuildEcVolumes collection %s\n", c)
|
||||
if err = rebuildEcVolumes(commandEnv, allEcNodes, c, writer, *applyChanges); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -264,7 +264,8 @@ func (ecShardMap EcShardMap) registerEcNode(ecNode *EcNode, collection string) {
|
||||
if shardInfo.Collection == collection {
|
||||
existing, found := ecShardMap[needle.VolumeId(shardInfo.Id)]
|
||||
if !found {
|
||||
existing = make([][]*EcNode, erasure_coding.TotalShardsCount)
|
||||
// Use MaxShardCount (32) to support custom EC ratios
|
||||
existing = make([][]*EcNode, erasure_coding.MaxShardCount)
|
||||
ecShardMap[needle.VolumeId(shardInfo.Id)] = existing
|
||||
}
|
||||
for _, shardId := range erasure_coding.ShardBits(shardInfo.EcIndexBits).ShardIds() {
|
||||
|
||||
@@ -116,7 +116,7 @@ func (ce *CommandEnv) AdjustedUrl(location *filer_pb.Location) string {
|
||||
}
|
||||
|
||||
func (ce *CommandEnv) GetDataCenter() string {
|
||||
return ce.MasterClient.DataCenter
|
||||
return ce.MasterClient.GetDataCenter()
|
||||
}
|
||||
|
||||
func parseFilerUrl(entryPath string) (filerServer string, filerPort int64, path string, err error) {
|
||||
|
||||
@@ -16,7 +16,9 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
re = regexp.MustCompile(`\.ec[0-9][0-9]`)
|
||||
// Match .ec00 through .ec999 (currently only .ec00-.ec31 are used)
|
||||
// Using \d{2,3} for future-proofing if MaxShardCount is ever increased beyond 99
|
||||
re = regexp.MustCompile(`\.ec\d{2,3}`)
|
||||
)
|
||||
|
||||
func (l *DiskLocation) FindEcVolume(vid needle.VolumeId) (*erasure_coding.EcVolume, bool) {
|
||||
@@ -398,8 +400,8 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
|
||||
var actualShardSize int64 = -1
|
||||
|
||||
// Count shards and validate they all have the same size (required for Reed-Solomon EC)
|
||||
// Shard files (.ec00 - .ec13) are always in l.Directory, not l.IdxDirectory
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
// Check up to MaxShardCount (32) to support custom EC ratios
|
||||
for i := 0; i < erasure_coding.MaxShardCount; i++ {
|
||||
shardFileName := baseFileName + erasure_coding.ToExt(i)
|
||||
fi, err := os.Stat(shardFileName)
|
||||
|
||||
@@ -472,8 +474,9 @@ func (l *DiskLocation) removeEcVolumeFiles(collection string, vid needle.VolumeI
|
||||
removeFile(indexBaseFileName+".ecx", "EC index file")
|
||||
removeFile(indexBaseFileName+".ecj", "EC journal file")
|
||||
|
||||
// Remove all EC shard files (.ec00 ~ .ec13) from data directory
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
// Remove all EC shard files (.ec00 ~ .ec31) from data directory
|
||||
// Use MaxShardCount (32) to support custom EC ratios
|
||||
for i := 0; i < erasure_coding.MaxShardCount; i++ {
|
||||
removeFile(baseFileName+erasure_coding.ToExt(i), "EC shard file")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/klauspost/reedsolomon"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
// ECContext encapsulates erasure coding parameters for encoding/decoding operations
|
||||
type ECContext struct {
|
||||
DataShards int
|
||||
ParityShards int
|
||||
Collection string
|
||||
VolumeId needle.VolumeId
|
||||
}
|
||||
|
||||
// Total returns the total number of shards (data + parity)
|
||||
func (ctx *ECContext) Total() int {
|
||||
return ctx.DataShards + ctx.ParityShards
|
||||
}
|
||||
|
||||
// NewDefaultECContext creates a context with default 10+4 shard configuration
|
||||
func NewDefaultECContext(collection string, volumeId needle.VolumeId) *ECContext {
|
||||
return &ECContext{
|
||||
DataShards: DataShardsCount,
|
||||
ParityShards: ParityShardsCount,
|
||||
Collection: collection,
|
||||
VolumeId: volumeId,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateEncoder creates a Reed-Solomon encoder for this context
|
||||
func (ctx *ECContext) CreateEncoder() (reedsolomon.Encoder, error) {
|
||||
return reedsolomon.New(ctx.DataShards, ctx.ParityShards)
|
||||
}
|
||||
|
||||
// ToExt returns the file extension for a given shard index
|
||||
func (ctx *ECContext) ToExt(shardIndex int) string {
|
||||
return fmt.Sprintf(".ec%02d", shardIndex)
|
||||
}
|
||||
|
||||
// String returns a human-readable representation of the EC configuration
|
||||
func (ctx *ECContext) String() string {
|
||||
return fmt.Sprintf("%d+%d (total: %d)", ctx.DataShards, ctx.ParityShards, ctx.Total())
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -18,6 +19,7 @@ const (
|
||||
DataShardsCount = 10
|
||||
ParityShardsCount = 4
|
||||
TotalShardsCount = DataShardsCount + ParityShardsCount
|
||||
MaxShardCount = 32 // Maximum number of shards since ShardBits is uint32 (bits 0-31)
|
||||
MinTotalDisks = TotalShardsCount/ParityShardsCount + 1
|
||||
ErasureCodingLargeBlockSize = 1024 * 1024 * 1024 // 1GB
|
||||
ErasureCodingSmallBlockSize = 1024 * 1024 // 1MB
|
||||
@@ -54,20 +56,53 @@ func WriteSortedFileFromIdx(baseFileName string, ext string) (e error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteEcFiles generates .ec00 ~ .ec13 files
|
||||
// WriteEcFiles generates .ec00 ~ .ec13 files using default EC context
|
||||
func WriteEcFiles(baseFileName string) error {
|
||||
return generateEcFiles(baseFileName, 256*1024, ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize)
|
||||
ctx := NewDefaultECContext("", 0)
|
||||
return WriteEcFilesWithContext(baseFileName, ctx)
|
||||
}
|
||||
|
||||
// WriteEcFilesWithContext generates EC files using the provided context
|
||||
func WriteEcFilesWithContext(baseFileName string, ctx *ECContext) error {
|
||||
return generateEcFiles(baseFileName, 256*1024, ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize, ctx)
|
||||
}
|
||||
|
||||
func RebuildEcFiles(baseFileName string) ([]uint32, error) {
|
||||
return generateMissingEcFiles(baseFileName, 256*1024, ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize)
|
||||
// Attempt to load EC config from .vif file to preserve original configuration
|
||||
var ctx *ECContext
|
||||
if volumeInfo, _, found, _ := volume_info.MaybeLoadVolumeInfo(baseFileName + ".vif"); found && volumeInfo.EcShardConfig != nil {
|
||||
ds := int(volumeInfo.EcShardConfig.DataShards)
|
||||
ps := int(volumeInfo.EcShardConfig.ParityShards)
|
||||
|
||||
// Validate EC config before using it
|
||||
if ds > 0 && ps > 0 && ds+ps <= MaxShardCount {
|
||||
ctx = &ECContext{
|
||||
DataShards: ds,
|
||||
ParityShards: ps,
|
||||
}
|
||||
glog.V(0).Infof("Rebuilding EC files for %s with config from .vif: %s", baseFileName, ctx.String())
|
||||
} else {
|
||||
glog.Warningf("Invalid EC config in .vif for %s (data=%d, parity=%d), using default", baseFileName, ds, ps)
|
||||
ctx = NewDefaultECContext("", 0)
|
||||
}
|
||||
} else {
|
||||
glog.V(0).Infof("Rebuilding EC files for %s with default config", baseFileName)
|
||||
ctx = NewDefaultECContext("", 0)
|
||||
}
|
||||
|
||||
return RebuildEcFilesWithContext(baseFileName, ctx)
|
||||
}
|
||||
|
||||
// RebuildEcFilesWithContext rebuilds missing EC files using the provided context
|
||||
func RebuildEcFilesWithContext(baseFileName string, ctx *ECContext) ([]uint32, error) {
|
||||
return generateMissingEcFiles(baseFileName, 256*1024, ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize, ctx)
|
||||
}
|
||||
|
||||
func ToExt(ecIndex int) string {
|
||||
return fmt.Sprintf(".ec%02d", ecIndex)
|
||||
}
|
||||
|
||||
func generateEcFiles(baseFileName string, bufferSize int, largeBlockSize int64, smallBlockSize int64) error {
|
||||
func generateEcFiles(baseFileName string, bufferSize int, largeBlockSize int64, smallBlockSize int64, ctx *ECContext) error {
|
||||
file, err := os.OpenFile(baseFileName+".dat", os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open dat file: %w", err)
|
||||
@@ -79,21 +114,21 @@ func generateEcFiles(baseFileName string, bufferSize int, largeBlockSize int64,
|
||||
return fmt.Errorf("failed to stat dat file: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("encodeDatFile %s.dat size:%d", baseFileName, fi.Size())
|
||||
err = encodeDatFile(fi.Size(), baseFileName, bufferSize, largeBlockSize, file, smallBlockSize)
|
||||
glog.V(0).Infof("encodeDatFile %s.dat size:%d with EC context %s", baseFileName, fi.Size(), ctx.String())
|
||||
err = encodeDatFile(fi.Size(), baseFileName, bufferSize, largeBlockSize, file, smallBlockSize, ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encodeDatFile: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateMissingEcFiles(baseFileName string, bufferSize int, largeBlockSize int64, smallBlockSize int64) (generatedShardIds []uint32, err error) {
|
||||
func generateMissingEcFiles(baseFileName string, bufferSize int, largeBlockSize int64, smallBlockSize int64, ctx *ECContext) (generatedShardIds []uint32, err error) {
|
||||
|
||||
shardHasData := make([]bool, TotalShardsCount)
|
||||
inputFiles := make([]*os.File, TotalShardsCount)
|
||||
outputFiles := make([]*os.File, TotalShardsCount)
|
||||
for shardId := 0; shardId < TotalShardsCount; shardId++ {
|
||||
shardFileName := baseFileName + ToExt(shardId)
|
||||
shardHasData := make([]bool, ctx.Total())
|
||||
inputFiles := make([]*os.File, ctx.Total())
|
||||
outputFiles := make([]*os.File, ctx.Total())
|
||||
for shardId := 0; shardId < ctx.Total(); shardId++ {
|
||||
shardFileName := baseFileName + ctx.ToExt(shardId)
|
||||
if util.FileExists(shardFileName) {
|
||||
shardHasData[shardId] = true
|
||||
inputFiles[shardId], err = os.OpenFile(shardFileName, os.O_RDONLY, 0)
|
||||
@@ -111,14 +146,14 @@ func generateMissingEcFiles(baseFileName string, bufferSize int, largeBlockSize
|
||||
}
|
||||
}
|
||||
|
||||
err = rebuildEcFiles(shardHasData, inputFiles, outputFiles)
|
||||
err = rebuildEcFiles(shardHasData, inputFiles, outputFiles, ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("rebuildEcFiles: %w", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func encodeData(file *os.File, enc reedsolomon.Encoder, startOffset, blockSize int64, buffers [][]byte, outputs []*os.File) error {
|
||||
func encodeData(file *os.File, enc reedsolomon.Encoder, startOffset, blockSize int64, buffers [][]byte, outputs []*os.File, ctx *ECContext) error {
|
||||
|
||||
bufferSize := int64(len(buffers[0]))
|
||||
if bufferSize == 0 {
|
||||
@@ -131,7 +166,7 @@ func encodeData(file *os.File, enc reedsolomon.Encoder, startOffset, blockSize i
|
||||
}
|
||||
|
||||
for b := int64(0); b < batchCount; b++ {
|
||||
err := encodeDataOneBatch(file, enc, startOffset+b*bufferSize, blockSize, buffers, outputs)
|
||||
err := encodeDataOneBatch(file, enc, startOffset+b*bufferSize, blockSize, buffers, outputs, ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -140,9 +175,9 @@ func encodeData(file *os.File, enc reedsolomon.Encoder, startOffset, blockSize i
|
||||
return nil
|
||||
}
|
||||
|
||||
func openEcFiles(baseFileName string, forRead bool) (files []*os.File, err error) {
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
fname := baseFileName + ToExt(i)
|
||||
func openEcFiles(baseFileName string, forRead bool, ctx *ECContext) (files []*os.File, err error) {
|
||||
for i := 0; i < ctx.Total(); i++ {
|
||||
fname := baseFileName + ctx.ToExt(i)
|
||||
openOption := os.O_TRUNC | os.O_CREATE | os.O_WRONLY
|
||||
if forRead {
|
||||
openOption = os.O_RDONLY
|
||||
@@ -164,10 +199,10 @@ func closeEcFiles(files []*os.File) {
|
||||
}
|
||||
}
|
||||
|
||||
func encodeDataOneBatch(file *os.File, enc reedsolomon.Encoder, startOffset, blockSize int64, buffers [][]byte, outputs []*os.File) error {
|
||||
func encodeDataOneBatch(file *os.File, enc reedsolomon.Encoder, startOffset, blockSize int64, buffers [][]byte, outputs []*os.File, ctx *ECContext) error {
|
||||
|
||||
// read data into buffers
|
||||
for i := 0; i < DataShardsCount; i++ {
|
||||
for i := 0; i < ctx.DataShards; i++ {
|
||||
n, err := file.ReadAt(buffers[i], startOffset+blockSize*int64(i))
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
@@ -186,7 +221,7 @@ func encodeDataOneBatch(file *os.File, enc reedsolomon.Encoder, startOffset, blo
|
||||
return err
|
||||
}
|
||||
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
for i := 0; i < ctx.Total(); i++ {
|
||||
_, err := outputs[i].Write(buffers[i])
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -196,53 +231,57 @@ func encodeDataOneBatch(file *os.File, enc reedsolomon.Encoder, startOffset, blo
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeDatFile(remainingSize int64, baseFileName string, bufferSize int, largeBlockSize int64, file *os.File, smallBlockSize int64) error {
|
||||
func encodeDatFile(remainingSize int64, baseFileName string, bufferSize int, largeBlockSize int64, file *os.File, smallBlockSize int64, ctx *ECContext) error {
|
||||
|
||||
var processedSize int64
|
||||
|
||||
enc, err := reedsolomon.New(DataShardsCount, ParityShardsCount)
|
||||
enc, err := ctx.CreateEncoder()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create encoder: %w", err)
|
||||
}
|
||||
|
||||
buffers := make([][]byte, TotalShardsCount)
|
||||
buffers := make([][]byte, ctx.Total())
|
||||
for i := range buffers {
|
||||
buffers[i] = make([]byte, bufferSize)
|
||||
}
|
||||
|
||||
outputs, err := openEcFiles(baseFileName, false)
|
||||
outputs, err := openEcFiles(baseFileName, false, ctx)
|
||||
defer closeEcFiles(outputs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open ec files %s: %v", baseFileName, err)
|
||||
}
|
||||
|
||||
for remainingSize > largeBlockSize*DataShardsCount {
|
||||
err = encodeData(file, enc, processedSize, largeBlockSize, buffers, outputs)
|
||||
// Pre-calculate row sizes to avoid redundant calculations in loops
|
||||
largeRowSize := largeBlockSize * int64(ctx.DataShards)
|
||||
smallRowSize := smallBlockSize * int64(ctx.DataShards)
|
||||
|
||||
for remainingSize >= largeRowSize {
|
||||
err = encodeData(file, enc, processedSize, largeBlockSize, buffers, outputs, ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode large chunk data: %w", err)
|
||||
}
|
||||
remainingSize -= largeBlockSize * DataShardsCount
|
||||
processedSize += largeBlockSize * DataShardsCount
|
||||
remainingSize -= largeRowSize
|
||||
processedSize += largeRowSize
|
||||
}
|
||||
for remainingSize > 0 {
|
||||
err = encodeData(file, enc, processedSize, smallBlockSize, buffers, outputs)
|
||||
err = encodeData(file, enc, processedSize, smallBlockSize, buffers, outputs, ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode small chunk data: %w", err)
|
||||
}
|
||||
remainingSize -= smallBlockSize * DataShardsCount
|
||||
processedSize += smallBlockSize * DataShardsCount
|
||||
remainingSize -= smallRowSize
|
||||
processedSize += smallRowSize
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func rebuildEcFiles(shardHasData []bool, inputFiles []*os.File, outputFiles []*os.File) error {
|
||||
func rebuildEcFiles(shardHasData []bool, inputFiles []*os.File, outputFiles []*os.File, ctx *ECContext) error {
|
||||
|
||||
enc, err := reedsolomon.New(DataShardsCount, ParityShardsCount)
|
||||
enc, err := ctx.CreateEncoder()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create encoder: %w", err)
|
||||
}
|
||||
|
||||
buffers := make([][]byte, TotalShardsCount)
|
||||
buffers := make([][]byte, ctx.Total())
|
||||
for i := range buffers {
|
||||
if shardHasData[i] {
|
||||
buffers[i] = make([]byte, ErasureCodingSmallBlockSize)
|
||||
@@ -254,7 +293,7 @@ func rebuildEcFiles(shardHasData []bool, inputFiles []*os.File, outputFiles []*o
|
||||
for {
|
||||
|
||||
// read the input data from files
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
for i := 0; i < ctx.Total(); i++ {
|
||||
if shardHasData[i] {
|
||||
n, _ := inputFiles[i].ReadAt(buffers[i], startOffset)
|
||||
if n == 0 {
|
||||
@@ -278,7 +317,7 @@ func rebuildEcFiles(shardHasData []bool, inputFiles []*os.File, outputFiles []*o
|
||||
}
|
||||
|
||||
// write the data to output files
|
||||
for i := 0; i < TotalShardsCount; i++ {
|
||||
for i := 0; i < ctx.Total(); i++ {
|
||||
if !shardHasData[i] {
|
||||
n, _ := outputFiles[i].WriteAt(buffers[i][:inputBufferDataSize], startOffset)
|
||||
if inputBufferDataSize != n {
|
||||
|
||||
@@ -23,7 +23,10 @@ func TestEncodingDecoding(t *testing.T) {
|
||||
bufferSize := 50
|
||||
baseFileName := "1"
|
||||
|
||||
err := generateEcFiles(baseFileName, bufferSize, largeBlockSize, smallBlockSize)
|
||||
// Create default EC context for testing
|
||||
ctx := NewDefaultECContext("", 0)
|
||||
|
||||
err := generateEcFiles(baseFileName, bufferSize, largeBlockSize, smallBlockSize, ctx)
|
||||
if err != nil {
|
||||
t.Logf("generateEcFiles: %v", err)
|
||||
}
|
||||
@@ -33,16 +36,16 @@ func TestEncodingDecoding(t *testing.T) {
|
||||
t.Logf("WriteSortedFileFromIdx: %v", err)
|
||||
}
|
||||
|
||||
err = validateFiles(baseFileName)
|
||||
err = validateFiles(baseFileName, ctx)
|
||||
if err != nil {
|
||||
t.Logf("WriteSortedFileFromIdx: %v", err)
|
||||
}
|
||||
|
||||
removeGeneratedFiles(baseFileName)
|
||||
removeGeneratedFiles(baseFileName, ctx)
|
||||
|
||||
}
|
||||
|
||||
func validateFiles(baseFileName string) error {
|
||||
func validateFiles(baseFileName string, ctx *ECContext) error {
|
||||
nm, err := readNeedleMap(baseFileName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("readNeedleMap: %v", err)
|
||||
@@ -60,7 +63,7 @@ func validateFiles(baseFileName string) error {
|
||||
return fmt.Errorf("failed to stat dat file: %v", err)
|
||||
}
|
||||
|
||||
ecFiles, err := openEcFiles(baseFileName, true)
|
||||
ecFiles, err := openEcFiles(baseFileName, true, ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error opening ec files: %w", err)
|
||||
}
|
||||
@@ -184,9 +187,9 @@ func readFromFile(file *os.File, data []byte, ecFileOffset int64) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func removeGeneratedFiles(baseFileName string) {
|
||||
for i := 0; i < DataShardsCount+ParityShardsCount; i++ {
|
||||
fname := fmt.Sprintf("%s.ec%02d", baseFileName, i)
|
||||
func removeGeneratedFiles(baseFileName string, ctx *ECContext) {
|
||||
for i := 0; i < ctx.Total(); i++ {
|
||||
fname := baseFileName + ctx.ToExt(i)
|
||||
os.Remove(fname)
|
||||
}
|
||||
os.Remove(baseFileName + ".ecx")
|
||||
|
||||
@@ -41,7 +41,8 @@ type EcVolume struct {
|
||||
ecjFileAccessLock sync.Mutex
|
||||
diskType types.DiskType
|
||||
datFileSize int64
|
||||
ExpireAtSec uint64 //ec volume destroy time, calculated from the ec volume was created
|
||||
ExpireAtSec uint64 //ec volume destroy time, calculated from the ec volume was created
|
||||
ECContext *ECContext // EC encoding parameters
|
||||
}
|
||||
|
||||
func NewEcVolume(diskType types.DiskType, dir string, dirIdx string, collection string, vid needle.VolumeId) (ev *EcVolume, err error) {
|
||||
@@ -73,9 +74,32 @@ func NewEcVolume(diskType types.DiskType, dir string, dirIdx string, collection
|
||||
ev.Version = needle.Version(volumeInfo.Version)
|
||||
ev.datFileSize = volumeInfo.DatFileSize
|
||||
ev.ExpireAtSec = volumeInfo.ExpireAtSec
|
||||
|
||||
// Initialize EC context from .vif if present; fallback to defaults
|
||||
if volumeInfo.EcShardConfig != nil {
|
||||
ds := int(volumeInfo.EcShardConfig.DataShards)
|
||||
ps := int(volumeInfo.EcShardConfig.ParityShards)
|
||||
|
||||
// Validate shard counts to prevent zero or invalid values
|
||||
if ds <= 0 || ps <= 0 || ds+ps > MaxShardCount {
|
||||
glog.Warningf("Invalid EC config in VolumeInfo for volume %d (data=%d, parity=%d), using defaults", vid, ds, ps)
|
||||
ev.ECContext = NewDefaultECContext(collection, vid)
|
||||
} else {
|
||||
ev.ECContext = &ECContext{
|
||||
Collection: collection,
|
||||
VolumeId: vid,
|
||||
DataShards: ds,
|
||||
ParityShards: ps,
|
||||
}
|
||||
glog.V(1).Infof("Loaded EC config from VolumeInfo for volume %d: %s", vid, ev.ECContext.String())
|
||||
}
|
||||
} else {
|
||||
ev.ECContext = NewDefaultECContext(collection, vid)
|
||||
}
|
||||
} else {
|
||||
glog.Warningf("vif file not found,volumeId:%d, filename:%s", vid, dataBaseFileName)
|
||||
volume_info.SaveVolumeInfo(dataBaseFileName+".vif", &volume_server_pb.VolumeInfo{Version: uint32(ev.Version)})
|
||||
ev.ECContext = NewDefaultECContext(collection, vid)
|
||||
}
|
||||
|
||||
ev.ShardLocations = make(map[ShardId][]pb.ServerAddress)
|
||||
@@ -260,7 +284,7 @@ func (ev *EcVolume) LocateEcShardNeedleInterval(version needle.Version, offset i
|
||||
if ev.datFileSize > 0 {
|
||||
// To get the correct LargeBlockRowsCount
|
||||
// use datFileSize to calculate the shardSize to match the EC encoding logic.
|
||||
shardSize = ev.datFileSize / DataShardsCount
|
||||
shardSize = ev.datFileSize / int64(ev.ECContext.DataShards)
|
||||
}
|
||||
// calculate the locations in the ec shards
|
||||
intervals = LocateData(ErasureCodingLargeBlockSize, ErasureCodingSmallBlockSize, shardSize, offset, types.Size(needle.GetActualSize(size, version)))
|
||||
|
||||
@@ -87,7 +87,7 @@ func (ecInfo *EcVolumeInfo) Minus(other *EcVolumeInfo) *EcVolumeInfo {
|
||||
|
||||
// Copy shard sizes for remaining shards
|
||||
retIndex := 0
|
||||
for shardId := ShardId(0); shardId < TotalShardsCount && retIndex < len(ret.ShardSizes); shardId++ {
|
||||
for shardId := ShardId(0); shardId < ShardId(MaxShardCount) && retIndex < len(ret.ShardSizes); shardId++ {
|
||||
if ret.ShardBits.HasShardId(shardId) {
|
||||
if size, exists := ecInfo.GetShardSize(shardId); exists {
|
||||
ret.ShardSizes[retIndex] = size
|
||||
@@ -119,19 +119,28 @@ func (ecInfo *EcVolumeInfo) ToVolumeEcShardInformationMessage() (ret *master_pb.
|
||||
type ShardBits uint32 // use bits to indicate the shard id, use 32 bits just for possible future extension
|
||||
|
||||
func (b ShardBits) AddShardId(id ShardId) ShardBits {
|
||||
if id >= MaxShardCount {
|
||||
return b // Reject out-of-range shard IDs
|
||||
}
|
||||
return b | (1 << id)
|
||||
}
|
||||
|
||||
func (b ShardBits) RemoveShardId(id ShardId) ShardBits {
|
||||
if id >= MaxShardCount {
|
||||
return b // Reject out-of-range shard IDs
|
||||
}
|
||||
return b &^ (1 << id)
|
||||
}
|
||||
|
||||
func (b ShardBits) HasShardId(id ShardId) bool {
|
||||
if id >= MaxShardCount {
|
||||
return false // Out-of-range shard IDs are never present
|
||||
}
|
||||
return b&(1<<id) > 0
|
||||
}
|
||||
|
||||
func (b ShardBits) ShardIds() (ret []ShardId) {
|
||||
for i := ShardId(0); i < TotalShardsCount; i++ {
|
||||
for i := ShardId(0); i < ShardId(MaxShardCount); i++ {
|
||||
if b.HasShardId(i) {
|
||||
ret = append(ret, i)
|
||||
}
|
||||
@@ -140,7 +149,7 @@ func (b ShardBits) ShardIds() (ret []ShardId) {
|
||||
}
|
||||
|
||||
func (b ShardBits) ToUint32Slice() (ret []uint32) {
|
||||
for i := uint32(0); i < TotalShardsCount; i++ {
|
||||
for i := uint32(0); i < uint32(MaxShardCount); i++ {
|
||||
if b.HasShardId(ShardId(i)) {
|
||||
ret = append(ret, i)
|
||||
}
|
||||
@@ -164,6 +173,8 @@ func (b ShardBits) Plus(other ShardBits) ShardBits {
|
||||
}
|
||||
|
||||
func (b ShardBits) MinusParityShards() ShardBits {
|
||||
// Removes parity shards from the bit mask
|
||||
// Assumes default 10+4 EC layout where parity shards are IDs 10-13
|
||||
for i := DataShardsCount; i < TotalShardsCount; i++ {
|
||||
b = b.RemoveShardId(ShardId(i))
|
||||
}
|
||||
@@ -205,7 +216,7 @@ func (b ShardBits) IndexToShardId(index int) (shardId ShardId, found bool) {
|
||||
}
|
||||
|
||||
currentIndex := 0
|
||||
for i := ShardId(0); i < TotalShardsCount; i++ {
|
||||
for i := ShardId(0); i < ShardId(MaxShardCount); i++ {
|
||||
if b.HasShardId(i) {
|
||||
if currentIndex == index {
|
||||
return i, true
|
||||
@@ -234,7 +245,7 @@ func (ecInfo *EcVolumeInfo) resizeShardSizes(prevShardBits ShardBits) {
|
||||
// Copy existing sizes to new positions based on current ShardBits
|
||||
if len(ecInfo.ShardSizes) > 0 {
|
||||
newIndex := 0
|
||||
for shardId := ShardId(0); shardId < TotalShardsCount && newIndex < expectedLength; shardId++ {
|
||||
for shardId := ShardId(0); shardId < ShardId(MaxShardCount) && newIndex < expectedLength; shardId++ {
|
||||
if ecInfo.ShardBits.HasShardId(shardId) {
|
||||
// Try to find the size for this shard in the old array using previous ShardBits
|
||||
if oldIndex, found := prevShardBits.ShardIdToIndex(shardId); found && oldIndex < len(ecInfo.ShardSizes) {
|
||||
|
||||
@@ -350,7 +350,8 @@ func (s *Store) recoverOneRemoteEcShardInterval(needleId types.NeedleId, ecVolum
|
||||
return 0, false, fmt.Errorf("failed to create encoder: %w", err)
|
||||
}
|
||||
|
||||
bufs := make([][]byte, erasure_coding.TotalShardsCount)
|
||||
// Use MaxShardCount to support custom EC ratios up to 32 shards
|
||||
bufs := make([][]byte, erasure_coding.MaxShardCount)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
|
||||
@@ -510,7 +510,7 @@ func (v *Volume) copyDataBasedOnIndexFile(srcDatName, srcIdxName, dstDatName, da
|
||||
return fmt.Errorf("volume %s unexpected new data size: %d does not match size of content minus deleted: %d",
|
||||
v.Id.String(), dstDatSize, expectedContentSize)
|
||||
}
|
||||
} else {
|
||||
} else if v.nm.DeletedSize() > v.nm.ContentSize() {
|
||||
glog.Warningf("volume %s content size: %d less deleted size: %d, new size: %d",
|
||||
v.Id.String(), v.nm.ContentSize(), v.nm.DeletedSize(), dstDatSize)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ import (
|
||||
|
||||
type EcShardLocations struct {
|
||||
Collection string
|
||||
Locations [erasure_coding.TotalShardsCount][]*DataNode
|
||||
// Use MaxShardCount (32) to support custom EC ratios
|
||||
Locations [erasure_coding.MaxShardCount][]*DataNode
|
||||
}
|
||||
|
||||
func (t *Topology) SyncDataNodeEcShards(shardInfos []*master_pb.VolumeEcShardInformationMessage, dn *DataNode) (newShards, deletedShards []*erasure_coding.EcVolumeInfo) {
|
||||
@@ -90,6 +91,10 @@ func NewEcShardLocations(collection string) *EcShardLocations {
|
||||
}
|
||||
|
||||
func (loc *EcShardLocations) AddShard(shardId erasure_coding.ShardId, dn *DataNode) (added bool) {
|
||||
// Defensive bounds check to prevent panic with out-of-range shard IDs
|
||||
if int(shardId) >= erasure_coding.MaxShardCount {
|
||||
return false
|
||||
}
|
||||
dataNodes := loc.Locations[shardId]
|
||||
for _, n := range dataNodes {
|
||||
if n.Id() == dn.Id() {
|
||||
@@ -101,6 +106,10 @@ func (loc *EcShardLocations) AddShard(shardId erasure_coding.ShardId, dn *DataNo
|
||||
}
|
||||
|
||||
func (loc *EcShardLocations) DeleteShard(shardId erasure_coding.ShardId, dn *DataNode) (deleted bool) {
|
||||
// Defensive bounds check to prevent panic with out-of-range shard IDs
|
||||
if int(shardId) >= erasure_coding.MaxShardCount {
|
||||
return false
|
||||
}
|
||||
dataNodes := loc.Locations[shardId]
|
||||
foundIndex := -1
|
||||
for index, n := range dataNodes {
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user