mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-01 16:47:06 +01:00
Compare commits
61
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1031e7190 | ||
|
|
8b9a48c1b5 | ||
|
|
498922dbb2 | ||
|
|
bba8931d64 | ||
|
|
c238153a3b | ||
|
|
c4c4d227a1 | ||
|
|
60f9dea60a | ||
|
|
cb952ff107 | ||
|
|
fe972eab44 | ||
|
|
5810aba763 | ||
|
|
7275613cc3 | ||
|
|
3b1755a1ee | ||
|
|
f383230766 | ||
|
|
d00308399d | ||
|
|
e8e50ebc75 | ||
|
|
6cbfb24022 | ||
|
|
d1428df1df | ||
|
|
6b2f5147b9 | ||
|
|
422ecb8953 | ||
|
|
0667c4964e | ||
|
|
5737f77d5f | ||
|
|
55bf25e338 | ||
|
|
7df898e00b | ||
|
|
3be91b2125 | ||
|
|
d9e19cc49b | ||
|
|
aded68d69e | ||
|
|
ba07b3e4c6 | ||
|
|
f5a57a6463 | ||
|
|
a6da3eb770 | ||
|
|
db35159a41 | ||
|
|
d00a2a8707 | ||
|
|
8a032bf57d | ||
|
|
9b6b564235 | ||
|
|
7e624d5355 | ||
|
|
eaecd8328b | ||
|
|
d4790cb8e6 | ||
|
|
ed023f4a7d | ||
|
|
ec4f7cf33c | ||
|
|
85bd593936 | ||
|
|
d19eca71eb | ||
|
|
20e0d91037 | ||
|
|
b8bef0328b | ||
|
|
7d26c8838f | ||
|
|
b7ba6785a2 | ||
|
|
208d7f24f4 | ||
|
|
decfb07eea | ||
|
|
f82c69b9a5 | ||
|
|
a80b5eea5e | ||
|
|
51d16258fe | ||
|
|
e8a91aaf85 | ||
|
|
8667aa8e17 | ||
|
|
fe532592cc | ||
|
|
290c245095 | ||
|
|
68710a93a0 | ||
|
|
f2c888c3fe | ||
|
|
a943c611ed | ||
|
|
78b95b8320 | ||
|
|
4b76b2ad3c | ||
|
|
838e3104c4 | ||
|
|
2ad2ffcdff | ||
|
|
0813138d57 |
No files matched your search
@@ -134,7 +134,7 @@ jobs:
|
||||
|
||||
- name: Archive logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: output-logs
|
||||
path: docker/output.log
|
||||
|
||||
@@ -183,7 +183,7 @@ jobs:
|
||||
|
||||
- name: Upload Test Artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: fuse-integration-test-results
|
||||
path: |
|
||||
|
||||
@@ -62,7 +62,7 @@ jobs:
|
||||
|
||||
- name: Archive logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: postgres-logs
|
||||
path: test/postgres/postgres-output.log
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-versioning-test-logs-${{ matrix.test-type }}
|
||||
path: test/s3/versioning/weed-test*.log
|
||||
@@ -124,7 +124,7 @@ jobs:
|
||||
|
||||
- name: Upload server logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-versioning-compatibility-logs
|
||||
path: test/s3/versioning/weed-test*.log
|
||||
@@ -172,7 +172,7 @@ jobs:
|
||||
|
||||
- name: Upload server logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-cors-compatibility-logs
|
||||
path: test/s3/cors/weed-test*.log
|
||||
@@ -239,7 +239,7 @@ jobs:
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-retention-test-logs-${{ matrix.test-type }}
|
||||
path: test/s3/retention/weed-test*.log
|
||||
@@ -306,7 +306,7 @@ jobs:
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-cors-test-logs-${{ matrix.test-type }}
|
||||
path: test/s3/cors/weed-test*.log
|
||||
@@ -355,7 +355,7 @@ jobs:
|
||||
|
||||
- name: Upload server logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-retention-worm-logs
|
||||
path: test/s3/retention/weed-test*.log
|
||||
@@ -405,7 +405,7 @@ jobs:
|
||||
|
||||
- name: Upload stress test logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-versioning-stress-logs
|
||||
path: test/s3/versioning/weed-test*.log
|
||||
|
||||
@@ -65,7 +65,7 @@ jobs:
|
||||
|
||||
- name: Upload test results on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: iam-unit-test-results
|
||||
path: |
|
||||
@@ -162,7 +162,7 @@ jobs:
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-iam-integration-logs-${{ matrix.test-type }}
|
||||
path: test/s3/iam/weed-*.log
|
||||
@@ -222,7 +222,7 @@ jobs:
|
||||
|
||||
- name: Upload distributed test logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-iam-distributed-logs
|
||||
path: test/s3/iam/weed-*.log
|
||||
@@ -274,7 +274,7 @@ jobs:
|
||||
|
||||
- name: Upload performance test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-iam-performance-results
|
||||
path: |
|
||||
|
||||
@@ -152,7 +152,7 @@ jobs:
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-keycloak-test-logs
|
||||
path: |
|
||||
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-sse-test-logs-${{ matrix.test-type }}
|
||||
path: test/s3/sse/weed-test*.log
|
||||
@@ -141,7 +141,7 @@ jobs:
|
||||
|
||||
- name: Upload server logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-sse-compatibility-logs
|
||||
path: test/s3/sse/weed-test*.log
|
||||
@@ -190,7 +190,7 @@ jobs:
|
||||
|
||||
- name: Upload server logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-sse-metadata-persistence-logs
|
||||
path: test/s3/sse/weed-test*.log
|
||||
@@ -239,7 +239,7 @@ jobs:
|
||||
|
||||
- name: Upload server logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-sse-copy-operations-logs
|
||||
path: test/s3/sse/weed-test*.log
|
||||
@@ -288,7 +288,7 @@ jobs:
|
||||
|
||||
- name: Upload server logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-sse-multipart-logs
|
||||
path: test/s3/sse/weed-test*.log
|
||||
@@ -338,7 +338,7 @@ jobs:
|
||||
|
||||
- name: Upload performance test logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: s3-sse-performance-logs
|
||||
path: test/s3/sse/weed-test*.log
|
||||
|
||||
@@ -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"]
|
||||
@@ -67,7 +67,7 @@ require (
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.66.1 // indirect
|
||||
github.com/prometheus/procfs v0.17.0
|
||||
github.com/prometheus/procfs v0.19.1
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/seaweedfs/goexif v1.0.3
|
||||
@@ -99,7 +99,7 @@ require (
|
||||
golang.org/x/crypto v0.43.0
|
||||
golang.org/x/exp v0.0.0-20250811191247-51f88131bc50
|
||||
golang.org/x/image v0.32.0
|
||||
golang.org/x/net v0.45.0
|
||||
golang.org/x/net v0.46.0
|
||||
golang.org/x/oauth2 v0.30.0 // indirect
|
||||
golang.org/x/sys v0.37.0
|
||||
golang.org/x/text v0.30.0 // indirect
|
||||
@@ -125,13 +125,13 @@ 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.2
|
||||
github.com/aws/aws-sdk-go-v2 v1.39.4
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.3
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.18.10
|
||||
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/cognusion/imaging v1.0.2
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
github.com/getsentry/sentry-go v0.35.3
|
||||
github.com/getsentry/sentry-go v0.36.1
|
||||
github.com/gin-contrib/sessions v1.0.4
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
@@ -147,14 +147,14 @@ require (
|
||||
github.com/minio/crc64nvme v1.1.1
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1
|
||||
github.com/parquet-go/parquet-go v0.25.1
|
||||
github.com/pkg/sftp v1.13.9
|
||||
github.com/pkg/sftp v1.13.10
|
||||
github.com/rabbitmq/amqp091-go v1.10.0
|
||||
github.com/rclone/rclone v1.71.1
|
||||
github.com/rclone/rclone v1.71.2
|
||||
github.com/rdleal/intervalst v1.5.0
|
||||
github.com/redis/go-redis/v9 v9.14.1
|
||||
github.com/schollz/progressbar/v3 v3.18.0
|
||||
github.com/shirou/gopsutil/v4 v4.25.9
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.0
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.1
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.0
|
||||
@@ -260,22 +260,22 @@ require (
|
||||
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/feature/ec2/imds v1.18.6 // 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.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.9 // 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/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/service/internal/accept-encoding v1.13.1 // 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.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/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.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.34.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.38.2 // indirect
|
||||
github.com/aws/smithy-go v1.23.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.29.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.38.9 // indirect
|
||||
github.com/aws/smithy-go v1.23.1 // indirect
|
||||
github.com/boltdb/bolt v1.3.1 // indirect
|
||||
github.com/bradenaw/juniper v0.15.3 // indirect
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
@@ -409,7 +409,7 @@ require (
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20241213151442-a19cff0ec7b5 // indirect
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20250926104142-ccb8d3498e6c // indirect
|
||||
github.com/tarantool/go-iproto v1.1.0 // indirect
|
||||
github.com/tiancaiamao/gp v0.0.0-20221230034425-4025bc8a4d4a // indirect
|
||||
github.com/tikv/pd/client v0.0.0-20230329114254-1948c247c2b1 // indirect
|
||||
|
||||
@@ -664,32 +664,32 @@ 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.2 h1:EJLg8IdbzgeD7xgvZ+I8M1e0fL0ptn/M47lianzth0I=
|
||||
github.com/aws/aws-sdk-go-v2 v1.39.2/go.mod h1:sDioUELIUO9Znk23YVmIk86/9DOpkbyyVb1i/gUNFXY=
|
||||
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/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.10 h1:xdJnXCouCx8Y0NncgoptztUocIYLKeQxrCgN6x9sdhg=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.18.10/go.mod h1:7tQk08ntj914F/5i9jC4+2HQTAuJirq7m1vZVIhEkWs=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.6 h1:wbjnrrMnKew78/juW7I2BtKQwa1qlf6EjQgS69uYY14=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.6/go.mod h1:AtiqqNrDioJXuUgz3+3T0mBWN7Hro2n9wll2zRUc0ww=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.18.19 h1:Jc1zzwkSY1QbkEcLujwqRTXOdvW8ppND3jRBb/VhBQc=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.18.19/go.mod h1:DIfQ9fAk5H0pGtnqfqkbSIzky82qYnGvh06ASQXXg6A=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.11 h1:X7X4YKb+c0rkI6d4uJ5tEMxXgCZ+jZ/D6mvkno8c8Uw=
|
||||
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.9 h1:se2vOWGD3dWQUtfn4wEjRQJb1HK1XsNIt825gskZ970=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.9/go.mod h1:hijCGH2VfbZQxqCDN7bwz/4dzxV+hkyhjawAtdPWKZA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.9 h1:6RBnKZLkJM4hQ+kN6E7yWFveOTg8NLPHAkqrs4ZPlTU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.9/go.mod h1:V9rQKRmK7AWuEsOMnHzKj8WyrIir1yUJbZxDuZLFvXI=
|
||||
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/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/service/internal/accept-encoding v1.13.1 h1:oegbebPEMA/1Jny7kvwejowCaHz1FWZAQ94WXFNCyTM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.1/go.mod h1:kemo5Myr9ac0U9JfSjMo9yHLtw+pECEHsFtJ9tqCEI8=
|
||||
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.9 h1:5r34CgVOD4WZudeEKZ9/iKpiT6cM1JyEROpXjOcdWv8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.9/go.mod h1:dB12CEbNWPbzO2uC6QSWHteqOg4JfBVJOojbAoAUb5I=
|
||||
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=
|
||||
@@ -698,14 +698,14 @@ github.com/aws/aws-sdk-go-v2/service/sns v1.34.7 h1:OBuZE9Wt8h2imuRktu+WfjiTGrnY
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.34.7/go.mod h1:4WYoZAhHt+dWYpoOQUgkUKfuQbE6Gg/hW4oXE0pKS9U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.38.8 h1:80dpSqWMwx2dAm30Ib7J6ucz1ZHfiv5OCRwN/EnCOXQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.38.8/go.mod h1:IzNt/udsXlETCdvBOL0nmyMe2t9cGmXmZgsdoZGYYhI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.29.1 h1:8OLZnVJPvjnrxEwHFg9hVUof/P4sibH+Ea4KKuqAGSg=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.29.1/go.mod h1:27M3BpVi0C02UiQh1w9nsBEit6pLhlaH3NHna6WUbDE=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.34.2 h1:gKWSTnqudpo8dAxqBqZnDoDWCiEh/40FziUjr/mo6uA=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.34.2/go.mod h1:x7+rkNmRoEN1U13A6JE2fXne9EWyJy54o3n6d4mGaXQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.38.2 h1:YZPjhyaGzhDQEvsffDEcpycq49nl7fiGcfJTIo8BszI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.38.2/go.mod h1:2dIN8qhQfv37BdUYGgEC8Q3tteM3zFxTI1MLO2O3J3c=
|
||||
github.com/aws/smithy-go v1.23.0 h1:8n6I3gXzWJB2DxBDnfxgBaSX6oe0d/t10qGz7OKqMCE=
|
||||
github.com/aws/smithy-go v1.23.0/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.29.8 h1:M5nimZmugcZUO9wG7iVtROxPhiqyZX6ejS1lxlDPbTU=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.29.8/go.mod h1:mbef/pgKhtKRwrigPPs7SSSKZgytzP8PQ6P6JAAdqyM=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.3 h1:S5GuJZpYxE0lKeMHKn+BRTz6PTFpgThyJ+5mYfux7BM=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.3/go.mod h1:X4OF+BTd7HIb3L+tc4UlWHVrpgwZZIVENU15pRDVTI0=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.38.9 h1:Ekml5vGg6sHSZLZJQJagefnVe6PmqC2oiRkBq4F7fU0=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.38.9/go.mod h1:/e15V+o1zFHWdH3u7lpI3rVBcxszktIKuHKCY2/py+k=
|
||||
github.com/aws/smithy-go v1.23.1 h1:sLvcH6dfAFwGkHLZ7dGiYF7aK6mg4CgKA/iDKjLDt9M=
|
||||
github.com/aws/smithy-go v1.23.1/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
|
||||
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
|
||||
github.com/bazelbuild/rules_go v0.46.0/go.mod h1:Dhcz716Kqg1RHNWos+N6MlXNkjNP2EwZQ0LukRKJfMs=
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
@@ -926,8 +926,8 @@ github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBv
|
||||
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
|
||||
github.com/geoffgarside/ber v1.2.0 h1:/loowoRcs/MWLYmGX9QtIAbA+V/FrnVLsMMPhwiRm64=
|
||||
github.com/geoffgarside/ber v1.2.0/go.mod h1:jVPKeCbj6MvQZhwLYsGwaGI52oUorHoHKNecGT85ZCc=
|
||||
github.com/getsentry/sentry-go v0.35.3 h1:u5IJaEqZyPdWqe/hKlBKBBnMTSxB/HenCqF3QLabeds=
|
||||
github.com/getsentry/sentry-go v0.35.3/go.mod h1:mdL49ixwT2yi57k5eh7mpnDyPybixPzlzEJFu0Z76QA=
|
||||
github.com/getsentry/sentry-go v0.36.1 h1:kMJt0WWsxWATUxkvFgVBZdIeHSk/Oiv5P0jZ9e5m/Lw=
|
||||
github.com/getsentry/sentry-go v0.36.1/go.mod h1:p5Im24mJBeruET8Q4bbcMfCQ+F+Iadc4L48tB1apo2c=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/gin-contrib/sessions v1.0.4 h1:ha6CNdpYiTOK/hTp05miJLbpTSNfOnFg5Jm2kbcqy8U=
|
||||
github.com/gin-contrib/sessions v1.0.4/go.mod h1:ccmkrb2z6iU2osiAHZG3x3J4suJK+OU27oqzlWOqQgs=
|
||||
@@ -1525,8 +1525,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
|
||||
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
|
||||
github.com/pkg/sftp v1.13.9 h1:4NGkvGudBL7GteO3m6qnaQ4pC0Kvf0onSVc9gR3EWBw=
|
||||
github.com/pkg/sftp v1.13.9/go.mod h1:OBN7bVXdstkFFN/gdnHPUb5TE8eb8G1Rp9wCItqjkkA=
|
||||
github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU=
|
||||
github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA=
|
||||
github.com/pkg/xattr v0.4.12 h1:rRTkSyFNTRElv6pkA3zpjHpQ90p/OdHQC1GmGh1aTjM=
|
||||
github.com/pkg/xattr v0.4.12/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
|
||||
@@ -1567,8 +1567,8 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT
|
||||
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
|
||||
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
||||
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
|
||||
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
|
||||
github.com/prometheus/procfs v0.19.1 h1:QVtROpTkphuXuNlnCv3m1ut3JytkXHtQ3xvck/YmzMM=
|
||||
github.com/prometheus/procfs v0.19.1/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 h1:Y258uzXU/potCYnQd1r6wlAnoMB68BiCkCcCnKx1SH8=
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8/go.mod h1:bSJjRokAHHOhA+XFxplld8w2R/dXLH7Z3BZ532vhFwU=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
@@ -1577,8 +1577,8 @@ github.com/quic-go/quic-go v0.54.1 h1:4ZAWm0AhCb6+hE+l5Q1NAL0iRn/ZrMwqHRGQiFwj2e
|
||||
github.com/quic-go/quic-go v0.54.1/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rclone/rclone v1.71.1 h1:cpODfWTRz5i/WAzXsyW85tzfIKNsd1aq8CE8lUB+0zg=
|
||||
github.com/rclone/rclone v1.71.1/go.mod h1:NLyX57FrnZ9nVLTY5TRdMmGelrGKbIRYGcgRkNdqqlA=
|
||||
github.com/rclone/rclone v1.71.2 h1:3Jk5xNPFrZhVABRuN/OPvApuZQddpE2tkhYMuEn1Ud4=
|
||||
github.com/rclone/rclone v1.71.2/go.mod h1:dCK9FzPDlpkbQJ9M7MmWsmv3X5nibfWe+ogJXu6gSgM=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
|
||||
@@ -1702,13 +1702,13 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965 h1:1oFLiOyVl+W7bnBzGhf7BbIv9loSFQcieWWYIjLqcAw=
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA=
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20241213151442-a19cff0ec7b5 h1:Sa+sR8aaAMFwxhXWENEnE6ZpqhZ9d7u1RT2722Rw6hc=
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20241213151442-a19cff0ec7b5/go.mod h1:UdZiFUFu6e2WjjtjxivwXWcwc1N/8zgbkBR9QNucUOY=
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20250926104142-ccb8d3498e6c h1:BLopNCyqewbE8+BtlIp/Juzu8AJGxz0gHdGADnsblVc=
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20250926104142-ccb8d3498e6c/go.mod h1:ykucQyiE9Q2qx1wLlEtZkkNn1IURib/2O+Mvd25i1Fo=
|
||||
github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502/go.mod h1:p9lPsd+cx33L3H9nNoecRRxPssFKUwwI50I3pZ0yT+8=
|
||||
github.com/tarantool/go-iproto v1.1.0 h1:HULVOIHsiehI+FnHfM7wMDntuzUddO09DKqu2WnFQ5A=
|
||||
github.com/tarantool/go-iproto v1.1.0/go.mod h1:LNCtdyZxojUed8SbOiYHoc3v9NvaZTB7p96hUySMlIo=
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.0 h1:cfGngxdknpVVbd/vF2LvaoWsKjsLV9i3xC859XgsJlI=
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.0/go.mod h1:MTbhdjFc3Jl63Lgi/UJr5D+QbT+QegqOzsNJGmaw7VM=
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.1 h1:Bk9mh+gMPVmHTSefHvVBpEkf6P2UZA/8xa5kqgyQtyo=
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.1/go.mod h1:MTbhdjFc3Jl63Lgi/UJr5D+QbT+QegqOzsNJGmaw7VM=
|
||||
github.com/the42/cartconvert v0.0.0-20131203171324-aae784c392b8 h1:I4DY8wLxJXCrMYzDM6lKCGc3IQwJX0PlTLsd3nQqI3c=
|
||||
github.com/the42/cartconvert v0.0.0-20131203171324-aae784c392b8/go.mod h1:fWO/msnJVhHqN1yX6OBoxSyfj7TEj1hHiL8bJSQsK30=
|
||||
github.com/tiancaiamao/gp v0.0.0-20221230034425-4025bc8a4d4a h1:J/YdBZ46WKpXsxsW93SG+q0F8KI+yFrcIDT4c/RNoc4=
|
||||
@@ -2065,8 +2065,8 @@ golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.45.0 h1:RLBg5JKixCy82FtLJpeNlVM0nrSqpCRYzVU1n8kj0tM=
|
||||
golang.org/x/net v0.45.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
|
||||
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "3.98"
|
||||
appVersion: "3.99"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.0.398
|
||||
version: 4.0.399
|
||||
@@ -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
|
||||
@@ -979,7 +979,7 @@ s3:
|
||||
# Custom command line arguments to add to the s3 command
|
||||
# Example to fix connection idle seconds:
|
||||
extraArgs: ["-idleTimeout=30"]
|
||||
#extraArgs: []
|
||||
# extraArgs: []
|
||||
|
||||
# used to configure livenessProbe on s3 containers
|
||||
#
|
||||
|
||||
+3
-3
@@ -168,14 +168,14 @@ require (
|
||||
github.com/pierrec/lz4/v4 v4.1.22 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pkg/sftp v1.13.9 // indirect
|
||||
github.com/pkg/sftp v1.13.10 // indirect
|
||||
github.com/pkg/xattr v0.4.12 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.66.1 // indirect
|
||||
github.com/prometheus/procfs v0.17.0 // indirect
|
||||
github.com/prometheus/procfs v0.19.1 // indirect
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 // indirect
|
||||
github.com/rclone/rclone v1.71.1 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
@@ -231,7 +231,7 @@ require (
|
||||
golang.org/x/crypto v0.43.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250811191247-51f88131bc50 // indirect
|
||||
golang.org/x/image v0.32.0 // indirect
|
||||
golang.org/x/net v0.45.0 // indirect
|
||||
golang.org/x/net v0.46.0 // indirect
|
||||
golang.org/x/oauth2 v0.30.0 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/sys v0.37.0 // indirect
|
||||
|
||||
+6
-6
@@ -516,8 +516,8 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjL
|
||||
github.com/pkg/diff v0.0.0-20200914180035-5b29258ca4f7/go.mod h1:zO8QMzTeZd5cpnIkz/Gn6iK0jDfGicM1nynOkkPIl28=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/sftp v1.13.9 h1:4NGkvGudBL7GteO3m6qnaQ4pC0Kvf0onSVc9gR3EWBw=
|
||||
github.com/pkg/sftp v1.13.9/go.mod h1:OBN7bVXdstkFFN/gdnHPUb5TE8eb8G1Rp9wCItqjkkA=
|
||||
github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU=
|
||||
github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA=
|
||||
github.com/pkg/xattr v0.4.12 h1:rRTkSyFNTRElv6pkA3zpjHpQ90p/OdHQC1GmGh1aTjM=
|
||||
github.com/pkg/xattr v0.4.12/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
@@ -532,8 +532,8 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
||||
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||
github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
|
||||
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
|
||||
github.com/prometheus/procfs v0.19.1 h1:QVtROpTkphuXuNlnCv3m1ut3JytkXHtQ3xvck/YmzMM=
|
||||
github.com/prometheus/procfs v0.19.1/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 h1:Y258uzXU/potCYnQd1r6wlAnoMB68BiCkCcCnKx1SH8=
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8/go.mod h1:bSJjRokAHHOhA+XFxplld8w2R/dXLH7Z3BZ532vhFwU=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
@@ -815,8 +815,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.45.0 h1:RLBg5JKixCy82FtLJpeNlVM0nrSqpCRYzVU1n8kj0tM=
|
||||
golang.org/x/net v0.45.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
|
||||
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
@@ -321,6 +323,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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,83 @@ 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, just ensure host is correctly formatted (IPv6 brackets).
|
||||
if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
|
||||
return "[" + 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 return bracketed IPv6",
|
||||
hostHeader: "backend:8333",
|
||||
forwardedHost: "::1",
|
||||
forwardedPort: "80",
|
||||
forwardedProto: "http",
|
||||
expected: "[::1]",
|
||||
},
|
||||
{
|
||||
name: "IPv6 address without brackets and standard HTTPS port, should return bracketed IPv6",
|
||||
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)",
|
||||
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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -144,10 +144,26 @@ func (l *DiskLocation) loadExistingVolume(dirEntry os.DirEntry, needleMapKind Ne
|
||||
return false
|
||||
}
|
||||
|
||||
// skip if ec volumes exists
|
||||
// parse out collection, volume id (moved up to use in EC validation)
|
||||
vid, collection, err := volumeIdFromFileName(basename)
|
||||
if err != nil {
|
||||
glog.Warningf("get volume id failed, %s, err : %s", volumeName, err)
|
||||
return false
|
||||
}
|
||||
|
||||
// skip if ec volumes exists, but validate EC files first
|
||||
if skipIfEcVolumesExists {
|
||||
if util.FileExists(l.IdxDirectory + "/" + volumeName + ".ecx") {
|
||||
return false
|
||||
ecxFilePath := filepath.Join(l.IdxDirectory, volumeName+".ecx")
|
||||
if util.FileExists(ecxFilePath) {
|
||||
// Validate EC volume: shard count, size consistency, and expected size vs .dat file
|
||||
if !l.validateEcVolume(collection, vid) {
|
||||
glog.Warningf("EC volume %d validation failed, removing incomplete EC files to allow .dat file loading", vid)
|
||||
l.removeEcVolumeFiles(collection, vid)
|
||||
// Continue to load .dat file
|
||||
} else {
|
||||
// Valid EC volume exists, skip .dat file
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,13 +177,6 @@ func (l *DiskLocation) loadExistingVolume(dirEntry os.DirEntry, needleMapKind Ne
|
||||
return false
|
||||
}
|
||||
|
||||
// parse out collection, volume id
|
||||
vid, collection, err := volumeIdFromFileName(basename)
|
||||
if err != nil {
|
||||
glog.Warningf("get volume id failed, %s, err : %s", volumeName, err)
|
||||
return false
|
||||
}
|
||||
|
||||
// avoid loading one volume more than once
|
||||
l.volumesLock.RLock()
|
||||
_, found := l.volumes[vid]
|
||||
|
||||
@@ -10,12 +10,15 @@ import (
|
||||
|
||||
"slices"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
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) {
|
||||
@@ -40,6 +43,23 @@ func (l *DiskLocation) DestroyEcVolume(vid needle.VolumeId) {
|
||||
}
|
||||
}
|
||||
|
||||
// unloadEcVolume removes an EC volume from memory without deleting its files on disk.
|
||||
// This is useful for distributed EC volumes where shards may be on other servers.
|
||||
func (l *DiskLocation) unloadEcVolume(vid needle.VolumeId) {
|
||||
var toClose *erasure_coding.EcVolume
|
||||
l.ecVolumesLock.Lock()
|
||||
if ecVolume, found := l.ecVolumes[vid]; found {
|
||||
toClose = ecVolume
|
||||
delete(l.ecVolumes, vid)
|
||||
}
|
||||
l.ecVolumesLock.Unlock()
|
||||
|
||||
// Close outside the lock to avoid holding write lock during I/O
|
||||
if toClose != nil {
|
||||
toClose.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DiskLocation) CollectEcShards(vid needle.VolumeId, shardFileNames []string) (ecVolume *erasure_coding.EcVolume, found bool) {
|
||||
l.ecVolumesLock.RLock()
|
||||
defer l.ecVolumesLock.RUnlock()
|
||||
@@ -154,8 +174,18 @@ func (l *DiskLocation) loadAllEcShards() (err error) {
|
||||
slices.SortFunc(dirEntries, func(a, b os.DirEntry) int {
|
||||
return strings.Compare(a.Name(), b.Name())
|
||||
})
|
||||
|
||||
var sameVolumeShards []string
|
||||
var prevVolumeId needle.VolumeId
|
||||
var prevCollection string
|
||||
|
||||
// Helper to reset state between volume processing
|
||||
reset := func() {
|
||||
sameVolumeShards = nil
|
||||
prevVolumeId = 0
|
||||
prevCollection = ""
|
||||
}
|
||||
|
||||
for _, fileInfo := range dirEntries {
|
||||
if fileInfo.IsDir() {
|
||||
continue
|
||||
@@ -178,24 +208,31 @@ func (l *DiskLocation) loadAllEcShards() (err error) {
|
||||
// 0 byte files should be only appearing erroneously for ec data files
|
||||
// so we ignore them
|
||||
if re.MatchString(ext) && info.Size() > 0 {
|
||||
if prevVolumeId == 0 || volumeId == prevVolumeId {
|
||||
// Group shards by both collection and volumeId to avoid mixing collections
|
||||
if prevVolumeId == 0 || (volumeId == prevVolumeId && collection == prevCollection) {
|
||||
sameVolumeShards = append(sameVolumeShards, fileInfo.Name())
|
||||
} else {
|
||||
// Before starting a new group, check if previous group had orphaned shards
|
||||
l.checkOrphanedShards(sameVolumeShards, prevCollection, prevVolumeId)
|
||||
sameVolumeShards = []string{fileInfo.Name()}
|
||||
}
|
||||
prevVolumeId = volumeId
|
||||
prevCollection = collection
|
||||
continue
|
||||
}
|
||||
|
||||
if ext == ".ecx" && volumeId == prevVolumeId {
|
||||
if err = l.loadEcShards(sameVolumeShards, collection, volumeId); err != nil {
|
||||
return fmt.Errorf("loadEcShards collection:%v volumeId:%d : %v", collection, volumeId, err)
|
||||
}
|
||||
prevVolumeId = volumeId
|
||||
if ext == ".ecx" && volumeId == prevVolumeId && collection == prevCollection {
|
||||
l.handleFoundEcxFile(sameVolumeShards, collection, volumeId)
|
||||
reset()
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Check for orphaned EC shards without .ecx file at the end of the directory scan
|
||||
// This handles the last group of shards in the directory
|
||||
l.checkOrphanedShards(sameVolumeShards, prevCollection, prevVolumeId)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -237,3 +274,209 @@ func (l *DiskLocation) EcShardCount() int {
|
||||
}
|
||||
return shardCount
|
||||
}
|
||||
|
||||
// handleFoundEcxFile processes a complete group of EC shards when their .ecx file is found.
|
||||
// This includes validation, loading, and cleanup of incomplete/invalid EC volumes.
|
||||
func (l *DiskLocation) handleFoundEcxFile(shards []string, collection string, volumeId needle.VolumeId) {
|
||||
// Check if this is an incomplete EC encoding (not a distributed EC volume)
|
||||
// Key distinction: if .dat file still exists, EC encoding may have failed
|
||||
// If .dat file is gone, this is likely a distributed EC volume with shards on multiple servers
|
||||
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(volumeId))
|
||||
datFileName := baseFileName + ".dat"
|
||||
|
||||
// Determine .dat presence robustly; unexpected errors are treated as "exists"
|
||||
datExists := l.checkDatFileExists(datFileName)
|
||||
|
||||
// Validate EC volume if .dat file exists (incomplete EC encoding scenario)
|
||||
// This checks shard count, shard size consistency, and expected size vs .dat file
|
||||
// If .dat is gone, EC encoding completed and shards are distributed across servers
|
||||
if datExists && !l.validateEcVolume(collection, volumeId) {
|
||||
glog.Warningf("Incomplete or invalid EC volume %d: .dat exists but validation failed, cleaning up EC files...", volumeId)
|
||||
l.removeEcVolumeFiles(collection, volumeId)
|
||||
return
|
||||
}
|
||||
|
||||
// Attempt to load the EC shards
|
||||
if err := l.loadEcShards(shards, collection, volumeId); err != nil {
|
||||
// If EC shards failed to load and .dat still exists, clean up EC files to allow .dat file to be used
|
||||
// If .dat is gone, log error but don't clean up (may be waiting for shards from other servers)
|
||||
if datExists {
|
||||
glog.Warningf("Failed to load EC shards for volume %d and .dat exists: %v, cleaning up EC files to use .dat...", volumeId, err)
|
||||
// Unload first to release FDs, then remove files
|
||||
l.unloadEcVolume(volumeId)
|
||||
l.removeEcVolumeFiles(collection, volumeId)
|
||||
} else {
|
||||
glog.Warningf("Failed to load EC shards for volume %d: %v (this may be normal for distributed EC volumes)", volumeId, err)
|
||||
// Clean up any partially loaded in-memory state. This does not delete files.
|
||||
l.unloadEcVolume(volumeId)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// checkDatFileExists checks if .dat file exists with robust error handling.
|
||||
// Unexpected errors (permission, I/O) are treated as "exists" to avoid misclassifying
|
||||
// local EC as distributed EC, which is the safer fallback.
|
||||
func (l *DiskLocation) checkDatFileExists(datFileName string) bool {
|
||||
if _, err := os.Stat(datFileName); err == nil {
|
||||
return true
|
||||
} else if !os.IsNotExist(err) {
|
||||
glog.Warningf("Failed to stat .dat file %s: %v", datFileName, err)
|
||||
// Safer to assume local .dat exists to avoid misclassifying as distributed EC
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkOrphanedShards checks if the given shards are orphaned (no .ecx file) and cleans them up if needed.
|
||||
// Returns true if orphaned shards were found and cleaned up.
|
||||
// This handles the case where EC encoding was interrupted before creating the .ecx file.
|
||||
func (l *DiskLocation) checkOrphanedShards(shards []string, collection string, volumeId needle.VolumeId) bool {
|
||||
if len(shards) == 0 || volumeId == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if .dat file exists (incomplete encoding, not distributed EC)
|
||||
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(volumeId))
|
||||
datFileName := baseFileName + ".dat"
|
||||
|
||||
if l.checkDatFileExists(datFileName) {
|
||||
glog.Warningf("Found %d EC shards without .ecx file for volume %d (incomplete encoding interrupted before .ecx creation), cleaning up...",
|
||||
len(shards), volumeId)
|
||||
l.removeEcVolumeFiles(collection, volumeId)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// calculateExpectedShardSize computes the exact expected shard size based on .dat file size
|
||||
// The EC encoding process is deterministic:
|
||||
// 1. Data is processed in batches of (LargeBlockSize * DataShardsCount) for large blocks
|
||||
// 2. Remaining data is processed in batches of (SmallBlockSize * DataShardsCount) for small blocks
|
||||
// 3. Each shard gets exactly its portion, with zero-padding applied to incomplete blocks
|
||||
func calculateExpectedShardSize(datFileSize int64) int64 {
|
||||
var shardSize int64
|
||||
|
||||
// Process large blocks (1GB * 10 = 10GB batches)
|
||||
largeBatchSize := int64(erasure_coding.ErasureCodingLargeBlockSize) * int64(erasure_coding.DataShardsCount)
|
||||
numLargeBatches := datFileSize / largeBatchSize
|
||||
shardSize = numLargeBatches * int64(erasure_coding.ErasureCodingLargeBlockSize)
|
||||
remainingSize := datFileSize - (numLargeBatches * largeBatchSize)
|
||||
|
||||
// Process remaining data in small blocks (1MB * 10 = 10MB batches)
|
||||
if remainingSize > 0 {
|
||||
smallBatchSize := int64(erasure_coding.ErasureCodingSmallBlockSize) * int64(erasure_coding.DataShardsCount)
|
||||
numSmallBatches := (remainingSize + smallBatchSize - 1) / smallBatchSize // Ceiling division
|
||||
shardSize += numSmallBatches * int64(erasure_coding.ErasureCodingSmallBlockSize)
|
||||
}
|
||||
|
||||
return shardSize
|
||||
}
|
||||
|
||||
// validateEcVolume checks if EC volume has enough shards to be functional
|
||||
// For distributed EC volumes (where .dat is deleted), any number of shards is valid
|
||||
// For incomplete EC encoding (where .dat still exists), we need at least DataShardsCount shards
|
||||
// Also validates that all shards have the same size (required for Reed-Solomon EC)
|
||||
// If .dat exists, it also validates shards match the expected size based on .dat file size
|
||||
func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId) bool {
|
||||
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
|
||||
datFileName := baseFileName + ".dat"
|
||||
|
||||
var expectedShardSize int64 = -1
|
||||
datExists := false
|
||||
|
||||
// If .dat file exists, compute exact expected shard size from it
|
||||
if datFileInfo, err := os.Stat(datFileName); err == nil {
|
||||
datExists = true
|
||||
expectedShardSize = calculateExpectedShardSize(datFileInfo.Size())
|
||||
} else if !os.IsNotExist(err) {
|
||||
// If stat fails with unexpected error (permission, I/O), fail validation
|
||||
// Don't treat this as "distributed EC" - it could be a temporary error
|
||||
glog.Warningf("Failed to stat .dat file %s: %v", datFileName, err)
|
||||
return false
|
||||
}
|
||||
|
||||
shardCount := 0
|
||||
var actualShardSize int64 = -1
|
||||
|
||||
// Count shards and validate they all have the same size (required for Reed-Solomon EC)
|
||||
// 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)
|
||||
|
||||
if err == nil {
|
||||
// Check if file has non-zero size
|
||||
if fi.Size() > 0 {
|
||||
// Validate all shards are the same size (required for Reed-Solomon EC)
|
||||
if actualShardSize == -1 {
|
||||
actualShardSize = fi.Size()
|
||||
} else if fi.Size() != actualShardSize {
|
||||
glog.Warningf("EC volume %d shard %d has size %d, expected %d (all EC shards must be same size)",
|
||||
vid, i, fi.Size(), actualShardSize)
|
||||
return false
|
||||
}
|
||||
shardCount++
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
// If stat fails with unexpected error (permission, I/O), fail validation
|
||||
// This is consistent with .dat file error handling
|
||||
glog.Warningf("Failed to stat shard file %s: %v", shardFileName, err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// If .dat file exists, validate shard size matches expected size
|
||||
if datExists && actualShardSize > 0 && expectedShardSize > 0 {
|
||||
if actualShardSize != expectedShardSize {
|
||||
glog.Warningf("EC volume %d: shard size %d doesn't match expected size %d (based on .dat file size)",
|
||||
vid, actualShardSize, expectedShardSize)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// If .dat file is gone, this is a distributed EC volume - any shard count is valid
|
||||
if !datExists {
|
||||
glog.V(1).Infof("EC volume %d: distributed EC (.dat removed) with %d shards", vid, shardCount)
|
||||
return true
|
||||
}
|
||||
|
||||
// If .dat file exists, we need at least DataShardsCount shards locally
|
||||
// Otherwise it's an incomplete EC encoding that should be cleaned up
|
||||
if shardCount < erasure_coding.DataShardsCount {
|
||||
glog.Warningf("EC volume %d has .dat file but only %d shards (need at least %d for local EC)",
|
||||
vid, shardCount, erasure_coding.DataShardsCount)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// removeEcVolumeFiles removes all EC-related files for a volume
|
||||
func (l *DiskLocation) removeEcVolumeFiles(collection string, vid needle.VolumeId) {
|
||||
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
|
||||
indexBaseFileName := erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid))
|
||||
|
||||
// Helper to remove a file with consistent error handling
|
||||
removeFile := func(filePath, description string) {
|
||||
if err := os.Remove(filePath); err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
glog.Warningf("Failed to remove incomplete %s %s: %v", description, filePath, err)
|
||||
}
|
||||
} else {
|
||||
glog.V(2).Infof("Removed incomplete %s: %s", description, filePath)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove index files first (.ecx, .ecj) before shard files
|
||||
// This ensures that if cleanup is interrupted, the .ecx file won't trigger
|
||||
// EC loading for incomplete/missing shards on next startup
|
||||
removeFile(indexBaseFileName+".ecx", "EC index file")
|
||||
removeFile(indexBaseFileName+".ecj", "EC journal file")
|
||||
|
||||
// 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,198 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// TestCalculateExpectedShardSizeWithRealEncoding validates our shard size calculation
|
||||
// by actually running EC encoding on real files and comparing the results
|
||||
func TestCalculateExpectedShardSizeWithRealEncoding(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
datFileSize int64
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "5MB file",
|
||||
datFileSize: 5 * 1024 * 1024,
|
||||
description: "Small file that needs 1 small block per shard",
|
||||
},
|
||||
{
|
||||
name: "10MB file (exactly 10 small blocks)",
|
||||
datFileSize: 10 * 1024 * 1024,
|
||||
description: "Exactly fits in 1MB small blocks",
|
||||
},
|
||||
{
|
||||
name: "15MB file",
|
||||
datFileSize: 15 * 1024 * 1024,
|
||||
description: "Requires 2 small blocks per shard",
|
||||
},
|
||||
{
|
||||
name: "50MB file",
|
||||
datFileSize: 50 * 1024 * 1024,
|
||||
description: "Requires 5 small blocks per shard",
|
||||
},
|
||||
{
|
||||
name: "100MB file",
|
||||
datFileSize: 100 * 1024 * 1024,
|
||||
description: "Requires 10 small blocks per shard",
|
||||
},
|
||||
{
|
||||
name: "512MB file",
|
||||
datFileSize: 512 * 1024 * 1024,
|
||||
description: "Requires 52 small blocks per shard (rounded up)",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create a test .dat file with the specified size
|
||||
baseFileName := filepath.Join(tempDir, "test_volume")
|
||||
datFileName := baseFileName + ".dat"
|
||||
|
||||
// Create .dat file with random data pattern (so it's compressible but realistic)
|
||||
datFile, err := os.Create(datFileName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .dat file: %v", err)
|
||||
}
|
||||
|
||||
// Write some pattern data (not all zeros, to be more realistic)
|
||||
pattern := make([]byte, 4096)
|
||||
for i := range pattern {
|
||||
pattern[i] = byte(i % 256)
|
||||
}
|
||||
|
||||
written := int64(0)
|
||||
for written < tt.datFileSize {
|
||||
toWrite := tt.datFileSize - written
|
||||
if toWrite > int64(len(pattern)) {
|
||||
toWrite = int64(len(pattern))
|
||||
}
|
||||
n, err := datFile.Write(pattern[:toWrite])
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write to .dat file: %v", err)
|
||||
}
|
||||
written += int64(n)
|
||||
}
|
||||
datFile.Close()
|
||||
|
||||
// Calculate expected shard size using our function
|
||||
expectedShardSize := calculateExpectedShardSize(tt.datFileSize)
|
||||
|
||||
// Run actual EC encoding
|
||||
err = erasure_coding.WriteEcFiles(baseFileName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to encode EC files: %v", err)
|
||||
}
|
||||
|
||||
// Measure actual shard sizes
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardFileName := baseFileName + erasure_coding.ToExt(i)
|
||||
shardInfo, err := os.Stat(shardFileName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to stat shard file %s: %v", shardFileName, err)
|
||||
}
|
||||
|
||||
actualShardSize := shardInfo.Size()
|
||||
|
||||
// Verify actual size matches expected size
|
||||
if actualShardSize != expectedShardSize {
|
||||
t.Errorf("Shard %d size mismatch:\n"+
|
||||
" .dat file size: %d bytes\n"+
|
||||
" Expected shard size: %d bytes\n"+
|
||||
" Actual shard size: %d bytes\n"+
|
||||
" Difference: %d bytes\n"+
|
||||
" %s",
|
||||
i, tt.datFileSize, expectedShardSize, actualShardSize,
|
||||
actualShardSize-expectedShardSize, tt.description)
|
||||
}
|
||||
}
|
||||
|
||||
// If we got here, all shards match!
|
||||
t.Logf("✓ SUCCESS: .dat size %d → actual shard size %d matches calculated size (%s)",
|
||||
tt.datFileSize, expectedShardSize, tt.description)
|
||||
|
||||
// Cleanup
|
||||
os.Remove(datFileName)
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
os.Remove(baseFileName + erasure_coding.ToExt(i))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCalculateExpectedShardSizeEdgeCases tests edge cases with real encoding
|
||||
func TestCalculateExpectedShardSizeEdgeCases(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
datFileSize int64
|
||||
}{
|
||||
{"1 byte file", 1},
|
||||
{"1KB file", 1024},
|
||||
{"10KB file", 10 * 1024},
|
||||
{"1MB file (1 small block)", 1024 * 1024},
|
||||
{"1MB + 1 byte", 1024*1024 + 1},
|
||||
{"9.9MB (almost 1 small block per shard)", 9*1024*1024 + 900*1024},
|
||||
{"10.1MB (just over 1 small block per shard)", 10*1024*1024 + 100*1024},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseFileName := filepath.Join(tempDir, tt.name)
|
||||
datFileName := baseFileName + ".dat"
|
||||
|
||||
// Create .dat file
|
||||
datFile, err := os.Create(datFileName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .dat file: %v", err)
|
||||
}
|
||||
|
||||
// Write exactly the specified number of bytes
|
||||
data := make([]byte, tt.datFileSize)
|
||||
for i := range data {
|
||||
data[i] = byte(i % 256)
|
||||
}
|
||||
datFile.Write(data)
|
||||
datFile.Close()
|
||||
|
||||
// Calculate expected
|
||||
expectedShardSize := calculateExpectedShardSize(tt.datFileSize)
|
||||
|
||||
// Run actual EC encoding
|
||||
err = erasure_coding.WriteEcFiles(baseFileName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to encode EC files: %v", err)
|
||||
}
|
||||
|
||||
// Check first shard (all should be same size)
|
||||
shardFileName := baseFileName + erasure_coding.ToExt(0)
|
||||
shardInfo, err := os.Stat(shardFileName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to stat shard file: %v", err)
|
||||
}
|
||||
|
||||
actualShardSize := shardInfo.Size()
|
||||
|
||||
if actualShardSize != expectedShardSize {
|
||||
t.Errorf("File size %d: expected shard %d, got %d (diff: %d)",
|
||||
tt.datFileSize, expectedShardSize, actualShardSize, actualShardSize-expectedShardSize)
|
||||
} else {
|
||||
t.Logf("✓ File size %d → shard size %d (correct)", tt.datFileSize, actualShardSize)
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
os.Remove(datFileName)
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
os.Remove(baseFileName + erasure_coding.ToExt(i))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCalculateExpectedShardSize(t *testing.T) {
|
||||
const (
|
||||
largeBlock = 1024 * 1024 * 1024 // 1GB
|
||||
smallBlock = 1024 * 1024 // 1MB
|
||||
dataShards = 10
|
||||
largeBatchSize = largeBlock * dataShards // 10GB
|
||||
smallBatchSize = smallBlock * dataShards // 10MB
|
||||
)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
datFileSize int64
|
||||
expectedShardSize int64
|
||||
description string
|
||||
}{
|
||||
// Edge case: empty file
|
||||
{
|
||||
name: "0 bytes (empty file)",
|
||||
datFileSize: 0,
|
||||
expectedShardSize: 0,
|
||||
description: "Empty file has 0 shard size",
|
||||
},
|
||||
|
||||
// Boundary tests: exact multiples of large block
|
||||
{
|
||||
name: "Exact 10GB (1 large batch)",
|
||||
datFileSize: largeBatchSize, // 10GB = 1 large batch
|
||||
expectedShardSize: largeBlock, // 1GB per shard
|
||||
description: "Exactly fits in large blocks",
|
||||
},
|
||||
{
|
||||
name: "Exact 20GB (2 large batches)",
|
||||
datFileSize: 2 * largeBatchSize, // 20GB
|
||||
expectedShardSize: 2 * largeBlock, // 2GB per shard
|
||||
description: "2 complete large batches",
|
||||
},
|
||||
{
|
||||
name: "Just under large batch (10GB - 1 byte)",
|
||||
datFileSize: largeBatchSize - 1, // 10,737,418,239 bytes
|
||||
expectedShardSize: 1024 * smallBlock, // 1024MB = 1GB (needs 1024 small blocks)
|
||||
description: "Just under 10GB needs 1024 small blocks",
|
||||
},
|
||||
{
|
||||
name: "Just over large batch (10GB + 1 byte)",
|
||||
datFileSize: largeBatchSize + 1, // 10GB + 1 byte
|
||||
expectedShardSize: largeBlock + smallBlock, // 1GB + 1MB
|
||||
description: "Just over 10GB adds 1 small block",
|
||||
},
|
||||
|
||||
// Boundary tests: exact multiples of small batch
|
||||
{
|
||||
name: "Exact 10MB (1 small batch)",
|
||||
datFileSize: smallBatchSize, // 10MB
|
||||
expectedShardSize: smallBlock, // 1MB per shard
|
||||
description: "Exactly fits in 1 small batch",
|
||||
},
|
||||
{
|
||||
name: "Exact 20MB (2 small batches)",
|
||||
datFileSize: 2 * smallBatchSize, // 20MB
|
||||
expectedShardSize: 2 * smallBlock, // 2MB per shard
|
||||
description: "2 complete small batches",
|
||||
},
|
||||
{
|
||||
name: "Just under small batch (10MB - 1 byte)",
|
||||
datFileSize: smallBatchSize - 1, // 10MB - 1 byte
|
||||
expectedShardSize: smallBlock, // Still needs 1MB per shard (rounds up)
|
||||
description: "Just under 10MB rounds up to 1 small block",
|
||||
},
|
||||
{
|
||||
name: "Just over small batch (10MB + 1 byte)",
|
||||
datFileSize: smallBatchSize + 1, // 10MB + 1 byte
|
||||
expectedShardSize: 2 * smallBlock, // 2MB per shard
|
||||
description: "Just over 10MB needs 2 small blocks",
|
||||
},
|
||||
|
||||
// Mixed: large batch + partial small batch
|
||||
{
|
||||
name: "10GB + 1MB",
|
||||
datFileSize: largeBatchSize + 1*1024*1024, // 10GB + 1MB
|
||||
expectedShardSize: largeBlock + smallBlock, // 1GB + 1MB
|
||||
description: "1 large batch + 1MB needs 1 small block",
|
||||
},
|
||||
{
|
||||
name: "10GB + 5MB",
|
||||
datFileSize: largeBatchSize + 5*1024*1024, // 10GB + 5MB
|
||||
expectedShardSize: largeBlock + smallBlock, // 1GB + 1MB
|
||||
description: "1 large batch + 5MB rounds up to 1 small block",
|
||||
},
|
||||
{
|
||||
name: "10GB + 15MB",
|
||||
datFileSize: largeBatchSize + 15*1024*1024, // 10GB + 15MB
|
||||
expectedShardSize: largeBlock + 2*smallBlock, // 1GB + 2MB
|
||||
description: "1 large batch + 15MB needs 2 small blocks",
|
||||
},
|
||||
|
||||
// Original test cases
|
||||
{
|
||||
name: "11GB (1 large batch + 103 small blocks)",
|
||||
datFileSize: 11 * 1024 * 1024 * 1024, // 11GB
|
||||
expectedShardSize: 1*1024*1024*1024 + 103*1024*1024, // 1GB + 103MB (103 small blocks for 1GB remaining)
|
||||
description: "1GB large + 1GB remaining needs 103 small blocks",
|
||||
},
|
||||
{
|
||||
name: "5MB (requires 1 small block per shard)",
|
||||
datFileSize: 5 * 1024 * 1024, // 5MB
|
||||
expectedShardSize: 1 * 1024 * 1024, // 1MB per shard (rounded up)
|
||||
description: "Small file rounds up to 1MB per shard",
|
||||
},
|
||||
{
|
||||
name: "1KB (minimum size)",
|
||||
datFileSize: 1024,
|
||||
expectedShardSize: 1 * 1024 * 1024, // 1MB per shard (1 small block)
|
||||
description: "Tiny file needs 1 small block",
|
||||
},
|
||||
{
|
||||
name: "10.5GB (mixed)",
|
||||
datFileSize: 10*1024*1024*1024 + 512*1024*1024, // 10.5GB
|
||||
expectedShardSize: 1*1024*1024*1024 + 52*1024*1024, // 1GB + 52MB (52 small blocks for 512MB remaining)
|
||||
description: "1GB large + 512MB remaining needs 52 small blocks",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
actualShardSize := calculateExpectedShardSize(tt.datFileSize)
|
||||
|
||||
if actualShardSize != tt.expectedShardSize {
|
||||
t.Errorf("Expected shard size %d, got %d. %s",
|
||||
tt.expectedShardSize, actualShardSize, tt.description)
|
||||
}
|
||||
|
||||
t.Logf("✓ File size: %d → Shard size: %d (%s)",
|
||||
tt.datFileSize, actualShardSize, tt.description)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestShardSizeValidationScenarios tests realistic scenarios
|
||||
func TestShardSizeValidationScenarios(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
datFileSize int64
|
||||
actualShardSize int64
|
||||
shouldBeValid bool
|
||||
}{
|
||||
{
|
||||
name: "Valid: exact match for 10GB",
|
||||
datFileSize: 10 * 1024 * 1024 * 1024, // 10GB
|
||||
actualShardSize: 1 * 1024 * 1024 * 1024, // 1GB (exact)
|
||||
shouldBeValid: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid: 1 byte too small",
|
||||
datFileSize: 10 * 1024 * 1024 * 1024, // 10GB
|
||||
actualShardSize: 1*1024*1024*1024 - 1, // 1GB - 1 byte
|
||||
shouldBeValid: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid: 1 byte too large",
|
||||
datFileSize: 10 * 1024 * 1024 * 1024, // 10GB
|
||||
actualShardSize: 1*1024*1024*1024 + 1, // 1GB + 1 byte
|
||||
shouldBeValid: false,
|
||||
},
|
||||
{
|
||||
name: "Valid: small file exact match",
|
||||
datFileSize: 5 * 1024 * 1024, // 5MB
|
||||
actualShardSize: 1 * 1024 * 1024, // 1MB (exact)
|
||||
shouldBeValid: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid: wrong size for small file",
|
||||
datFileSize: 5 * 1024 * 1024, // 5MB
|
||||
actualShardSize: 500 * 1024, // 500KB (too small)
|
||||
shouldBeValid: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, scenario := range scenarios {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
expectedSize := calculateExpectedShardSize(scenario.datFileSize)
|
||||
isValid := scenario.actualShardSize == expectedSize
|
||||
|
||||
if isValid != scenario.shouldBeValid {
|
||||
t.Errorf("Expected validation result %v, got %v. Actual shard: %d, Expected: %d",
|
||||
scenario.shouldBeValid, isValid, scenario.actualShardSize, expectedSize)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// TestIncompleteEcEncodingCleanup tests the cleanup logic for incomplete EC encoding scenarios
|
||||
func TestIncompleteEcEncodingCleanup(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
volumeId needle.VolumeId
|
||||
collection string
|
||||
createDatFile bool
|
||||
createEcxFile bool
|
||||
createEcjFile bool
|
||||
numShards int
|
||||
expectCleanup bool
|
||||
expectLoadSuccess bool
|
||||
}{
|
||||
{
|
||||
name: "Incomplete EC: shards without .ecx, .dat exists - should cleanup",
|
||||
volumeId: 100,
|
||||
collection: "",
|
||||
createDatFile: true,
|
||||
createEcxFile: false,
|
||||
createEcjFile: false,
|
||||
numShards: 14, // All shards but no .ecx
|
||||
expectCleanup: true,
|
||||
expectLoadSuccess: false,
|
||||
},
|
||||
{
|
||||
name: "Distributed EC: shards without .ecx, .dat deleted - should NOT cleanup",
|
||||
volumeId: 101,
|
||||
collection: "",
|
||||
createDatFile: false,
|
||||
createEcxFile: false,
|
||||
createEcjFile: false,
|
||||
numShards: 5, // Partial shards, distributed
|
||||
expectCleanup: false,
|
||||
expectLoadSuccess: false,
|
||||
},
|
||||
{
|
||||
name: "Incomplete EC: shards with .ecx but < 10 shards, .dat exists - should cleanup",
|
||||
volumeId: 102,
|
||||
collection: "",
|
||||
createDatFile: true,
|
||||
createEcxFile: true,
|
||||
createEcjFile: false,
|
||||
numShards: 7, // Less than DataShardsCount (10)
|
||||
expectCleanup: true,
|
||||
expectLoadSuccess: false,
|
||||
},
|
||||
{
|
||||
name: "Valid local EC: shards with .ecx, >= 10 shards, .dat exists - should load",
|
||||
volumeId: 103,
|
||||
collection: "",
|
||||
createDatFile: true,
|
||||
createEcxFile: true,
|
||||
createEcjFile: false,
|
||||
numShards: 14, // All shards
|
||||
expectCleanup: false,
|
||||
expectLoadSuccess: true, // Would succeed if .ecx was valid
|
||||
},
|
||||
{
|
||||
name: "Distributed EC: shards with .ecx, .dat deleted - should load",
|
||||
volumeId: 104,
|
||||
collection: "",
|
||||
createDatFile: false,
|
||||
createEcxFile: true,
|
||||
createEcjFile: false,
|
||||
numShards: 10, // Enough shards
|
||||
expectCleanup: false,
|
||||
expectLoadSuccess: true, // Would succeed if .ecx was valid
|
||||
},
|
||||
{
|
||||
name: "Incomplete EC with collection: shards without .ecx, .dat exists - should cleanup",
|
||||
volumeId: 105,
|
||||
collection: "test_collection",
|
||||
createDatFile: true,
|
||||
createEcxFile: false,
|
||||
createEcjFile: false,
|
||||
numShards: 14,
|
||||
expectCleanup: true,
|
||||
expectLoadSuccess: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Use per-subtest temp directory for stronger isolation
|
||||
tempDir := t.TempDir()
|
||||
|
||||
// Create DiskLocation
|
||||
minFreeSpace := util.MinFreeSpace{Type: util.AsPercent, Percent: 1, Raw: "1"}
|
||||
diskLocation := &DiskLocation{
|
||||
Directory: tempDir,
|
||||
DirectoryUuid: "test-uuid",
|
||||
IdxDirectory: tempDir,
|
||||
DiskType: types.HddType,
|
||||
MaxVolumeCount: 100,
|
||||
OriginalMaxVolumeCount: 100,
|
||||
MinFreeSpace: minFreeSpace,
|
||||
}
|
||||
diskLocation.volumes = make(map[needle.VolumeId]*Volume)
|
||||
diskLocation.ecVolumes = make(map[needle.VolumeId]*erasure_coding.EcVolume)
|
||||
|
||||
// Setup test files
|
||||
baseFileName := erasure_coding.EcShardFileName(tt.collection, tempDir, int(tt.volumeId))
|
||||
|
||||
// Use deterministic but small size: 10MB .dat => 1MB per shard
|
||||
datFileSize := int64(10 * 1024 * 1024) // 10MB
|
||||
expectedShardSize := calculateExpectedShardSize(datFileSize)
|
||||
|
||||
// Create .dat file if needed
|
||||
if tt.createDatFile {
|
||||
datFile, err := os.Create(baseFileName + ".dat")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .dat file: %v", err)
|
||||
}
|
||||
if err := datFile.Truncate(datFileSize); err != nil {
|
||||
t.Fatalf("Failed to truncate .dat file: %v", err)
|
||||
}
|
||||
if err := datFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .dat file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create EC shard files
|
||||
for i := 0; i < tt.numShards; i++ {
|
||||
shardFile, err := os.Create(baseFileName + erasure_coding.ToExt(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create shard file: %v", err)
|
||||
}
|
||||
if err := shardFile.Truncate(expectedShardSize); err != nil {
|
||||
t.Fatalf("Failed to truncate shard file: %v", err)
|
||||
}
|
||||
if err := shardFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close shard file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create .ecx file if needed
|
||||
if tt.createEcxFile {
|
||||
ecxFile, err := os.Create(baseFileName + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .ecx file: %v", err)
|
||||
}
|
||||
if _, err := ecxFile.WriteString("dummy ecx data"); err != nil {
|
||||
ecxFile.Close()
|
||||
t.Fatalf("Failed to write .ecx file: %v", err)
|
||||
}
|
||||
if err := ecxFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .ecx file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create .ecj file if needed
|
||||
if tt.createEcjFile {
|
||||
ecjFile, err := os.Create(baseFileName + ".ecj")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .ecj file: %v", err)
|
||||
}
|
||||
if _, err := ecjFile.WriteString("dummy ecj data"); err != nil {
|
||||
ecjFile.Close()
|
||||
t.Fatalf("Failed to write .ecj file: %v", err)
|
||||
}
|
||||
if err := ecjFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .ecj file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Run loadAllEcShards
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards returned error (expected in some cases): %v", loadErr)
|
||||
}
|
||||
|
||||
// Test idempotency - running again should not cause issues
|
||||
loadErr2 := diskLocation.loadAllEcShards()
|
||||
if loadErr2 != nil {
|
||||
t.Logf("Second loadAllEcShards returned error: %v", loadErr2)
|
||||
}
|
||||
|
||||
// Verify cleanup expectations
|
||||
if tt.expectCleanup {
|
||||
// Check that files were cleaned up
|
||||
if util.FileExists(baseFileName + ".ecx") {
|
||||
t.Errorf("Expected .ecx to be cleaned up but it still exists")
|
||||
}
|
||||
if util.FileExists(baseFileName + ".ecj") {
|
||||
t.Errorf("Expected .ecj to be cleaned up but it still exists")
|
||||
}
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardFile := baseFileName + erasure_coding.ToExt(i)
|
||||
if util.FileExists(shardFile) {
|
||||
t.Errorf("Expected shard %d to be cleaned up but it still exists", i)
|
||||
}
|
||||
}
|
||||
// .dat file should still exist (not cleaned up)
|
||||
if tt.createDatFile && !util.FileExists(baseFileName+".dat") {
|
||||
t.Errorf("Expected .dat file to remain but it was deleted")
|
||||
}
|
||||
} else {
|
||||
// Check that files were NOT cleaned up
|
||||
for i := 0; i < tt.numShards; i++ {
|
||||
shardFile := baseFileName + erasure_coding.ToExt(i)
|
||||
if !util.FileExists(shardFile) {
|
||||
t.Errorf("Expected shard %d to remain but it was cleaned up", i)
|
||||
}
|
||||
}
|
||||
if tt.createEcxFile && !util.FileExists(baseFileName+".ecx") {
|
||||
t.Errorf("Expected .ecx to remain but it was cleaned up")
|
||||
}
|
||||
}
|
||||
|
||||
// Verify load expectations
|
||||
if tt.expectLoadSuccess {
|
||||
if diskLocation.EcShardCount() == 0 {
|
||||
t.Errorf("Expected EC shards to be loaded for volume %d", tt.volumeId)
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateEcVolume tests the validateEcVolume function
|
||||
func TestValidateEcVolume(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
minFreeSpace := util.MinFreeSpace{Type: util.AsPercent, Percent: 1, Raw: "1"}
|
||||
diskLocation := &DiskLocation{
|
||||
Directory: tempDir,
|
||||
DirectoryUuid: "test-uuid",
|
||||
IdxDirectory: tempDir,
|
||||
DiskType: types.HddType,
|
||||
MinFreeSpace: minFreeSpace,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
volumeId needle.VolumeId
|
||||
collection string
|
||||
createDatFile bool
|
||||
numShards int
|
||||
expectValid bool
|
||||
}{
|
||||
{
|
||||
name: "Valid: .dat exists with 10+ shards",
|
||||
volumeId: 200,
|
||||
collection: "",
|
||||
createDatFile: true,
|
||||
numShards: 10,
|
||||
expectValid: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid: .dat exists with < 10 shards",
|
||||
volumeId: 201,
|
||||
collection: "",
|
||||
createDatFile: true,
|
||||
numShards: 9,
|
||||
expectValid: false,
|
||||
},
|
||||
{
|
||||
name: "Valid: .dat deleted (distributed EC) with any shards",
|
||||
volumeId: 202,
|
||||
collection: "",
|
||||
createDatFile: false,
|
||||
numShards: 5,
|
||||
expectValid: true,
|
||||
},
|
||||
{
|
||||
name: "Valid: .dat deleted (distributed EC) with no shards",
|
||||
volumeId: 203,
|
||||
collection: "",
|
||||
createDatFile: false,
|
||||
numShards: 0,
|
||||
expectValid: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid: zero-byte shard files should not count",
|
||||
volumeId: 204,
|
||||
collection: "",
|
||||
createDatFile: true,
|
||||
numShards: 0, // Will create 10 zero-byte files below
|
||||
expectValid: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid: .dat exists with different size shards",
|
||||
volumeId: 205,
|
||||
collection: "",
|
||||
createDatFile: true,
|
||||
numShards: 10, // Will create shards with varying sizes
|
||||
expectValid: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseFileName := erasure_coding.EcShardFileName(tt.collection, tempDir, int(tt.volumeId))
|
||||
|
||||
// For proper testing, we need to use realistic sizes that match EC encoding
|
||||
// EC uses large blocks (1GB) and small blocks (1MB)
|
||||
// For test purposes, use a small .dat file size that still exercises the logic
|
||||
// 10MB .dat file = 1MB per shard (one small batch, fast and deterministic)
|
||||
datFileSize := int64(10 * 1024 * 1024) // 10MB
|
||||
expectedShardSize := calculateExpectedShardSize(datFileSize)
|
||||
|
||||
// Create .dat file if needed
|
||||
if tt.createDatFile {
|
||||
datFile, err := os.Create(baseFileName + ".dat")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .dat file: %v", err)
|
||||
}
|
||||
// Write minimal data (don't need to fill entire 10GB for tests)
|
||||
datFile.Truncate(datFileSize)
|
||||
datFile.Close()
|
||||
}
|
||||
|
||||
// Create EC shard files with correct size
|
||||
for i := 0; i < tt.numShards; i++ {
|
||||
shardFile, err := os.Create(baseFileName + erasure_coding.ToExt(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create shard file: %v", err)
|
||||
}
|
||||
// Use truncate to create file of correct size without allocating all the space
|
||||
if err := shardFile.Truncate(expectedShardSize); err != nil {
|
||||
shardFile.Close()
|
||||
t.Fatalf("Failed to truncate shard file: %v", err)
|
||||
}
|
||||
if err := shardFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close shard file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// For zero-byte test case, create empty files for all data shards
|
||||
if tt.volumeId == 204 {
|
||||
for i := 0; i < erasure_coding.DataShardsCount; i++ {
|
||||
shardFile, err := os.Create(baseFileName + erasure_coding.ToExt(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create empty shard file: %v", err)
|
||||
}
|
||||
// Don't write anything - leave as zero-byte
|
||||
shardFile.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// For mismatched shard size test case, create shards with different sizes
|
||||
if tt.volumeId == 205 {
|
||||
for i := 0; i < erasure_coding.DataShardsCount; i++ {
|
||||
shardFile, err := os.Create(baseFileName + erasure_coding.ToExt(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create shard file: %v", err)
|
||||
}
|
||||
// Write different amount of data to each shard
|
||||
data := make([]byte, 100+i*10)
|
||||
shardFile.Write(data)
|
||||
shardFile.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Test validation
|
||||
isValid := diskLocation.validateEcVolume(tt.collection, tt.volumeId)
|
||||
if isValid != tt.expectValid {
|
||||
t.Errorf("Expected validation result %v but got %v", tt.expectValid, isValid)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoveEcVolumeFiles tests the removeEcVolumeFiles function
|
||||
func TestRemoveEcVolumeFiles(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
separateIdxDir bool
|
||||
}{
|
||||
{"Same directory for data and index", false},
|
||||
{"Separate idx directory", true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
var dataDir, idxDir string
|
||||
if tt.separateIdxDir {
|
||||
dataDir = filepath.Join(tempDir, "data")
|
||||
idxDir = filepath.Join(tempDir, "idx")
|
||||
os.MkdirAll(dataDir, 0755)
|
||||
os.MkdirAll(idxDir, 0755)
|
||||
} else {
|
||||
dataDir = tempDir
|
||||
idxDir = tempDir
|
||||
}
|
||||
|
||||
minFreeSpace := util.MinFreeSpace{Type: util.AsPercent, Percent: 1, Raw: "1"}
|
||||
diskLocation := &DiskLocation{
|
||||
Directory: dataDir,
|
||||
DirectoryUuid: "test-uuid",
|
||||
IdxDirectory: idxDir,
|
||||
DiskType: types.HddType,
|
||||
MinFreeSpace: minFreeSpace,
|
||||
}
|
||||
|
||||
volumeId := needle.VolumeId(300)
|
||||
collection := ""
|
||||
dataBaseFileName := erasure_coding.EcShardFileName(collection, dataDir, int(volumeId))
|
||||
idxBaseFileName := erasure_coding.EcShardFileName(collection, idxDir, int(volumeId))
|
||||
|
||||
// Create all EC shard files in data directory
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardFile, err := os.Create(dataBaseFileName + erasure_coding.ToExt(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create shard file: %v", err)
|
||||
}
|
||||
if _, err := shardFile.WriteString("dummy shard data"); err != nil {
|
||||
shardFile.Close()
|
||||
t.Fatalf("Failed to write shard file: %v", err)
|
||||
}
|
||||
if err := shardFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close shard file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create .ecx file in idx directory
|
||||
ecxFile, err := os.Create(idxBaseFileName + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .ecx file: %v", err)
|
||||
}
|
||||
if _, err := ecxFile.WriteString("dummy ecx data"); err != nil {
|
||||
ecxFile.Close()
|
||||
t.Fatalf("Failed to write .ecx file: %v", err)
|
||||
}
|
||||
if err := ecxFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .ecx file: %v", err)
|
||||
}
|
||||
|
||||
// Create .ecj file in idx directory
|
||||
ecjFile, err := os.Create(idxBaseFileName + ".ecj")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .ecj file: %v", err)
|
||||
}
|
||||
if _, err := ecjFile.WriteString("dummy ecj data"); err != nil {
|
||||
ecjFile.Close()
|
||||
t.Fatalf("Failed to write .ecj file: %v", err)
|
||||
}
|
||||
if err := ecjFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .ecj file: %v", err)
|
||||
}
|
||||
|
||||
// Create .dat file in data directory (should NOT be removed)
|
||||
datFile, err := os.Create(dataBaseFileName + ".dat")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .dat file: %v", err)
|
||||
}
|
||||
if _, err := datFile.WriteString("dummy dat data"); err != nil {
|
||||
datFile.Close()
|
||||
t.Fatalf("Failed to write .dat file: %v", err)
|
||||
}
|
||||
if err := datFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .dat file: %v", err)
|
||||
}
|
||||
|
||||
// Call removeEcVolumeFiles
|
||||
diskLocation.removeEcVolumeFiles(collection, volumeId)
|
||||
|
||||
// Verify all EC shard files are removed from data directory
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardFile := dataBaseFileName + erasure_coding.ToExt(i)
|
||||
if util.FileExists(shardFile) {
|
||||
t.Errorf("Shard file %d should be removed but still exists", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify .ecx file is removed from idx directory
|
||||
if util.FileExists(idxBaseFileName + ".ecx") {
|
||||
t.Errorf(".ecx file should be removed but still exists")
|
||||
}
|
||||
|
||||
// Verify .ecj file is removed from idx directory
|
||||
if util.FileExists(idxBaseFileName + ".ecj") {
|
||||
t.Errorf(".ecj file should be removed but still exists")
|
||||
}
|
||||
|
||||
// Verify .dat file is NOT removed from data directory
|
||||
if !util.FileExists(dataBaseFileName + ".dat") {
|
||||
t.Errorf(".dat file should NOT be removed but was deleted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestEcCleanupWithSeparateIdxDirectory tests EC cleanup when idx directory is different
|
||||
func TestEcCleanupWithSeparateIdxDirectory(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
idxDir := filepath.Join(tempDir, "idx")
|
||||
dataDir := filepath.Join(tempDir, "data")
|
||||
os.MkdirAll(idxDir, 0755)
|
||||
os.MkdirAll(dataDir, 0755)
|
||||
|
||||
minFreeSpace := util.MinFreeSpace{Type: util.AsPercent, Percent: 1, Raw: "1"}
|
||||
diskLocation := &DiskLocation{
|
||||
Directory: dataDir,
|
||||
DirectoryUuid: "test-uuid",
|
||||
IdxDirectory: idxDir,
|
||||
DiskType: types.HddType,
|
||||
MinFreeSpace: minFreeSpace,
|
||||
}
|
||||
diskLocation.volumes = make(map[needle.VolumeId]*Volume)
|
||||
diskLocation.ecVolumes = make(map[needle.VolumeId]*erasure_coding.EcVolume)
|
||||
|
||||
volumeId := needle.VolumeId(400)
|
||||
collection := ""
|
||||
|
||||
// Create shards in data directory (shards only go to Directory, not IdxDirectory)
|
||||
dataBaseFileName := erasure_coding.EcShardFileName(collection, dataDir, int(volumeId))
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardFile, err := os.Create(dataBaseFileName + erasure_coding.ToExt(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create shard file: %v", err)
|
||||
}
|
||||
if _, err := shardFile.WriteString("dummy shard data"); err != nil {
|
||||
t.Fatalf("Failed to write shard file: %v", err)
|
||||
}
|
||||
if err := shardFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close shard file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create .dat in data directory
|
||||
datFile, err := os.Create(dataBaseFileName + ".dat")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .dat file: %v", err)
|
||||
}
|
||||
if _, err := datFile.WriteString("dummy data"); err != nil {
|
||||
t.Fatalf("Failed to write .dat file: %v", err)
|
||||
}
|
||||
if err := datFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .dat file: %v", err)
|
||||
}
|
||||
|
||||
// Do not create .ecx: trigger orphaned-shards cleanup when .dat exists
|
||||
|
||||
// Run loadAllEcShards
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards error: %v", loadErr)
|
||||
}
|
||||
|
||||
// Verify cleanup occurred in data directory (shards)
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
shardFile := dataBaseFileName + erasure_coding.ToExt(i)
|
||||
if util.FileExists(shardFile) {
|
||||
t.Errorf("Shard file %d should be cleaned up but still exists", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify .dat in data directory still exists (only EC files are cleaned up)
|
||||
if !util.FileExists(dataBaseFileName + ".dat") {
|
||||
t.Errorf(".dat file should remain but was deleted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDistributedEcVolumeNoFileDeletion verifies that distributed EC volumes
|
||||
// (where .dat is deleted) do NOT have their shard files deleted when load fails
|
||||
// This tests the critical bug fix where DestroyEcVolume was incorrectly deleting files
|
||||
func TestDistributedEcVolumeNoFileDeletion(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
minFreeSpace := util.MinFreeSpace{Type: util.AsPercent, Percent: 1, Raw: "1"}
|
||||
diskLocation := &DiskLocation{
|
||||
Directory: tempDir,
|
||||
DirectoryUuid: "test-uuid",
|
||||
IdxDirectory: tempDir,
|
||||
DiskType: types.HddType,
|
||||
MinFreeSpace: minFreeSpace,
|
||||
ecVolumes: make(map[needle.VolumeId]*erasure_coding.EcVolume),
|
||||
}
|
||||
|
||||
collection := ""
|
||||
volumeId := needle.VolumeId(500)
|
||||
baseFileName := erasure_coding.EcShardFileName(collection, tempDir, int(volumeId))
|
||||
|
||||
// Create EC shards (only 5 shards - less than DataShardsCount, but OK for distributed EC)
|
||||
numDistributedShards := 5
|
||||
for i := 0; i < numDistributedShards; i++ {
|
||||
shardFile, err := os.Create(baseFileName + erasure_coding.ToExt(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create shard file: %v", err)
|
||||
}
|
||||
if _, err := shardFile.WriteString("dummy shard data"); err != nil {
|
||||
shardFile.Close()
|
||||
t.Fatalf("Failed to write shard file: %v", err)
|
||||
}
|
||||
if err := shardFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close shard file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create .ecx file to trigger EC loading
|
||||
ecxFile, err := os.Create(baseFileName + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create .ecx file: %v", err)
|
||||
}
|
||||
if _, err := ecxFile.WriteString("dummy ecx data"); err != nil {
|
||||
ecxFile.Close()
|
||||
t.Fatalf("Failed to write .ecx file: %v", err)
|
||||
}
|
||||
if err := ecxFile.Close(); err != nil {
|
||||
t.Fatalf("Failed to close .ecx file: %v", err)
|
||||
}
|
||||
|
||||
// NO .dat file - this is a distributed EC volume
|
||||
|
||||
// Run loadAllEcShards - this should fail but NOT delete shard files
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards returned error (expected): %v", loadErr)
|
||||
}
|
||||
|
||||
// CRITICAL CHECK: Verify shard files still exist (should NOT be deleted)
|
||||
for i := 0; i < 5; i++ {
|
||||
shardFile := baseFileName + erasure_coding.ToExt(i)
|
||||
if !util.FileExists(shardFile) {
|
||||
t.Errorf("CRITICAL BUG: Shard file %s was deleted for distributed EC volume!", shardFile)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify .ecx file still exists (should NOT be deleted for distributed EC)
|
||||
if !util.FileExists(baseFileName + ".ecx") {
|
||||
t.Errorf("CRITICAL BUG: .ecx file was deleted for distributed EC volume!")
|
||||
}
|
||||
|
||||
t.Logf("SUCCESS: Distributed EC volume files preserved (not deleted)")
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -15,10 +15,11 @@ import (
|
||||
// are lost in the gap between flushed disk data and in-memory buffer.
|
||||
//
|
||||
// OBSERVED BEHAVIOR FROM LOGS:
|
||||
// Request offset: 1764
|
||||
// Disk contains: 1000-1763 (764 messages)
|
||||
// Memory buffer starts at: 1800
|
||||
// Gap: 1764-1799 (36 messages) ← MISSING!
|
||||
//
|
||||
// Request offset: 1764
|
||||
// Disk contains: 1000-1763 (764 messages)
|
||||
// Memory buffer starts at: 1800
|
||||
// Gap: 1764-1799 (36 messages) ← MISSING!
|
||||
//
|
||||
// This test verifies:
|
||||
// 1. All messages sent to buffer are accounted for
|
||||
@@ -27,46 +28,46 @@ import (
|
||||
func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
|
||||
var flushedMessages []*filer_pb.LogEntry
|
||||
var flushMu sync.Mutex
|
||||
|
||||
|
||||
flushFn := func(logBuffer *LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
|
||||
t.Logf("FLUSH: minOffset=%d maxOffset=%d size=%d bytes", minOffset, maxOffset, len(buf))
|
||||
|
||||
|
||||
// Parse and store flushed messages
|
||||
flushMu.Lock()
|
||||
defer flushMu.Unlock()
|
||||
|
||||
|
||||
// Parse buffer to extract messages
|
||||
parsedCount := 0
|
||||
for pos := 0; pos+4 < len(buf); {
|
||||
if pos+4 > len(buf) {
|
||||
break
|
||||
}
|
||||
|
||||
|
||||
size := uint32(buf[pos])<<24 | uint32(buf[pos+1])<<16 | uint32(buf[pos+2])<<8 | uint32(buf[pos+3])
|
||||
if pos+4+int(size) > len(buf) {
|
||||
break
|
||||
}
|
||||
|
||||
|
||||
entryData := buf[pos+4 : pos+4+int(size)]
|
||||
logEntry := &filer_pb.LogEntry{}
|
||||
if err := proto.Unmarshal(entryData, logEntry); err == nil {
|
||||
flushedMessages = append(flushedMessages, logEntry)
|
||||
parsedCount++
|
||||
}
|
||||
|
||||
|
||||
pos += 4 + int(size)
|
||||
}
|
||||
|
||||
|
||||
t.Logf(" Parsed %d messages from flush buffer", parsedCount)
|
||||
}
|
||||
|
||||
|
||||
logBuffer := NewLogBuffer("test", 100*time.Millisecond, flushFn, nil, nil)
|
||||
defer logBuffer.ShutdownLogBuffer()
|
||||
|
||||
|
||||
// Send 100 messages
|
||||
messageCount := 100
|
||||
t.Logf("Sending %d messages...", messageCount)
|
||||
|
||||
|
||||
for i := 0; i < messageCount; i++ {
|
||||
logBuffer.AddToBuffer(&mq_pb.DataMessage{
|
||||
Key: []byte(fmt.Sprintf("key-%d", i)),
|
||||
@@ -74,11 +75,11 @@ func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
|
||||
TsNs: time.Now().UnixNano(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// Force flush multiple times to simulate real workload
|
||||
t.Logf("Forcing flush...")
|
||||
logBuffer.ForceFlush()
|
||||
|
||||
|
||||
// Add more messages after flush
|
||||
for i := messageCount; i < messageCount+50; i++ {
|
||||
logBuffer.AddToBuffer(&mq_pb.DataMessage{
|
||||
@@ -87,18 +88,18 @@ func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
|
||||
TsNs: time.Now().UnixNano(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// Force another flush
|
||||
logBuffer.ForceFlush()
|
||||
time.Sleep(200 * time.Millisecond) // Wait for flush to complete
|
||||
|
||||
|
||||
// Now check the buffer state
|
||||
logBuffer.RLock()
|
||||
bufferStartOffset := logBuffer.bufferStartOffset
|
||||
currentOffset := logBuffer.offset
|
||||
pos := logBuffer.pos
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
flushMu.Lock()
|
||||
flushedCount := len(flushedMessages)
|
||||
var maxFlushedOffset int64 = -1
|
||||
@@ -108,51 +109,51 @@ func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
|
||||
maxFlushedOffset = flushedMessages[flushedCount-1].Offset
|
||||
}
|
||||
flushMu.Unlock()
|
||||
|
||||
|
||||
t.Logf("\nBUFFER STATE AFTER FLUSH:")
|
||||
t.Logf(" bufferStartOffset: %d", bufferStartOffset)
|
||||
t.Logf(" currentOffset (HWM): %d", currentOffset)
|
||||
t.Logf(" pos (bytes in buffer): %d", pos)
|
||||
t.Logf(" Messages sent: %d (offsets 0-%d)", messageCount+50, messageCount+49)
|
||||
t.Logf(" Messages flushed to disk: %d (offsets %d-%d)", flushedCount, minFlushedOffset, maxFlushedOffset)
|
||||
|
||||
|
||||
// CRITICAL CHECK: Is there a gap between flushed data and memory buffer?
|
||||
if flushedCount > 0 && maxFlushedOffset >= 0 {
|
||||
gap := bufferStartOffset - (maxFlushedOffset + 1)
|
||||
|
||||
|
||||
t.Logf("\nOFFSET CONTINUITY CHECK:")
|
||||
t.Logf(" Last flushed offset: %d", maxFlushedOffset)
|
||||
t.Logf(" Buffer starts at: %d", bufferStartOffset)
|
||||
t.Logf(" Gap: %d offsets", gap)
|
||||
|
||||
|
||||
if gap > 0 {
|
||||
t.Errorf("❌ CRITICAL BUG REPRODUCED: OFFSET GAP DETECTED!")
|
||||
t.Errorf("CRITICAL BUG REPRODUCED: OFFSET GAP DETECTED!")
|
||||
t.Errorf(" Disk has offsets %d-%d", minFlushedOffset, maxFlushedOffset)
|
||||
t.Errorf(" Memory buffer starts at: %d", bufferStartOffset)
|
||||
t.Errorf(" MISSING OFFSETS: %d-%d (%d messages)", maxFlushedOffset+1, bufferStartOffset-1, gap)
|
||||
t.Errorf(" These messages are LOST - neither on disk nor in memory!")
|
||||
} else if gap < 0 {
|
||||
t.Errorf("❌ OFFSET OVERLAP: Memory buffer starts BEFORE last flushed offset!")
|
||||
t.Errorf("OFFSET OVERLAP: Memory buffer starts BEFORE last flushed offset!")
|
||||
t.Errorf(" This indicates data corruption or race condition")
|
||||
} else {
|
||||
t.Logf("✅ PASS: No gap detected - offsets are continuous")
|
||||
t.Logf("PASS: No gap detected - offsets are continuous")
|
||||
}
|
||||
|
||||
|
||||
// Check if we can read all expected offsets
|
||||
t.Logf("\nREADABILITY CHECK:")
|
||||
for testOffset := int64(0); testOffset < currentOffset; testOffset += 10 {
|
||||
// Try to read from buffer
|
||||
requestPosition := NewMessagePositionFromOffset(testOffset)
|
||||
buf, _, err := logBuffer.ReadFromBuffer(requestPosition)
|
||||
|
||||
|
||||
isReadable := (buf != nil && len(buf.Bytes()) > 0) || err == ResumeFromDiskError
|
||||
status := "✅"
|
||||
status := "OK"
|
||||
if !isReadable && err == nil {
|
||||
status = "❌ NOT READABLE"
|
||||
status = "NOT READABLE"
|
||||
}
|
||||
|
||||
|
||||
t.Logf(" Offset %d: %s (buf=%v, err=%v)", testOffset, status, buf != nil, err)
|
||||
|
||||
|
||||
// If offset is in the gap, it should fail to read
|
||||
if flushedCount > 0 && testOffset > maxFlushedOffset && testOffset < bufferStartOffset {
|
||||
if isReadable {
|
||||
@@ -163,23 +164,23 @@ func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Check that all sent messages are accounted for
|
||||
expectedMessageCount := messageCount + 50
|
||||
messagesInMemory := int(currentOffset - bufferStartOffset)
|
||||
totalAccountedFor := flushedCount + messagesInMemory
|
||||
|
||||
|
||||
t.Logf("\nMESSAGE ACCOUNTING:")
|
||||
t.Logf(" Expected: %d messages", expectedMessageCount)
|
||||
t.Logf(" Flushed to disk: %d", flushedCount)
|
||||
t.Logf(" In memory buffer: %d (offset range %d-%d)", messagesInMemory, bufferStartOffset, currentOffset-1)
|
||||
t.Logf(" Total accounted for: %d", totalAccountedFor)
|
||||
t.Logf(" Missing: %d messages", expectedMessageCount-totalAccountedFor)
|
||||
|
||||
|
||||
if totalAccountedFor < expectedMessageCount {
|
||||
t.Errorf("❌ DATA LOSS CONFIRMED: %d messages are missing!", expectedMessageCount-totalAccountedFor)
|
||||
t.Errorf("DATA LOSS CONFIRMED: %d messages are missing!", expectedMessageCount-totalAccountedFor)
|
||||
} else {
|
||||
t.Logf("✅ All messages accounted for")
|
||||
t.Logf("All messages accounted for")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,23 +189,23 @@ func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
|
||||
func TestFlushOffsetGap_CheckPrevBuffers(t *testing.T) {
|
||||
var flushCount int
|
||||
var flushMu sync.Mutex
|
||||
|
||||
|
||||
flushFn := func(logBuffer *LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
|
||||
flushMu.Lock()
|
||||
flushCount++
|
||||
count := flushCount
|
||||
flushMu.Unlock()
|
||||
|
||||
|
||||
t.Logf("FLUSH #%d: minOffset=%d maxOffset=%d size=%d bytes", count, minOffset, maxOffset, len(buf))
|
||||
}
|
||||
|
||||
|
||||
logBuffer := NewLogBuffer("test", 100*time.Millisecond, flushFn, nil, nil)
|
||||
defer logBuffer.ShutdownLogBuffer()
|
||||
|
||||
|
||||
// Send messages in batches with flushes in between
|
||||
for batch := 0; batch < 5; batch++ {
|
||||
t.Logf("\nBatch %d:", batch)
|
||||
|
||||
|
||||
// Send 20 messages
|
||||
for i := 0; i < 20; i++ {
|
||||
offset := int64(batch*20 + i)
|
||||
@@ -214,28 +215,28 @@ func TestFlushOffsetGap_CheckPrevBuffers(t *testing.T) {
|
||||
TsNs: time.Now().UnixNano(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// Check state before flush
|
||||
logBuffer.RLock()
|
||||
beforeFlushOffset := logBuffer.offset
|
||||
beforeFlushStart := logBuffer.bufferStartOffset
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
// Force flush
|
||||
logBuffer.ForceFlush()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
|
||||
// Check state after flush
|
||||
logBuffer.RLock()
|
||||
afterFlushOffset := logBuffer.offset
|
||||
afterFlushStart := logBuffer.bufferStartOffset
|
||||
prevBufferCount := len(logBuffer.prevBuffers.buffers)
|
||||
|
||||
|
||||
// Check prevBuffers state
|
||||
t.Logf(" Before flush: offset=%d, bufferStartOffset=%d", beforeFlushOffset, beforeFlushStart)
|
||||
t.Logf(" After flush: offset=%d, bufferStartOffset=%d, prevBuffers=%d",
|
||||
afterFlushOffset, afterFlushStart, prevBufferCount)
|
||||
|
||||
|
||||
// Check each prevBuffer
|
||||
for i, prevBuf := range logBuffer.prevBuffers.buffers {
|
||||
if prevBuf.size > 0 {
|
||||
@@ -244,11 +245,11 @@ func TestFlushOffsetGap_CheckPrevBuffers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
// CRITICAL: Check if bufferStartOffset advanced correctly
|
||||
expectedNewStart := beforeFlushOffset
|
||||
if afterFlushStart != expectedNewStart {
|
||||
t.Errorf(" ❌ bufferStartOffset mismatch!")
|
||||
t.Errorf(" bufferStartOffset mismatch!")
|
||||
t.Errorf(" Expected: %d (= offset before flush)", expectedNewStart)
|
||||
t.Errorf(" Actual: %d", afterFlushStart)
|
||||
t.Errorf(" Gap: %d offsets", expectedNewStart-afterFlushStart)
|
||||
@@ -261,10 +262,10 @@ func TestFlushOffsetGap_CheckPrevBuffers(t *testing.T) {
|
||||
func TestFlushOffsetGap_ConcurrentWriteAndFlush(t *testing.T) {
|
||||
var allFlushedOffsets []int64
|
||||
var flushMu sync.Mutex
|
||||
|
||||
|
||||
flushFn := func(logBuffer *LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
|
||||
t.Logf("FLUSH: offsets %d-%d (%d bytes)", minOffset, maxOffset, len(buf))
|
||||
|
||||
|
||||
flushMu.Lock()
|
||||
// Record the offset range that was flushed
|
||||
for offset := minOffset; offset <= maxOffset; offset++ {
|
||||
@@ -272,13 +273,13 @@ func TestFlushOffsetGap_ConcurrentWriteAndFlush(t *testing.T) {
|
||||
}
|
||||
flushMu.Unlock()
|
||||
}
|
||||
|
||||
|
||||
logBuffer := NewLogBuffer("test", 50*time.Millisecond, flushFn, nil, nil)
|
||||
defer logBuffer.ShutdownLogBuffer()
|
||||
|
||||
|
||||
// Concurrently write messages and force flushes
|
||||
var wg sync.WaitGroup
|
||||
|
||||
|
||||
// Writer goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
@@ -294,7 +295,7 @@ func TestFlushOffsetGap_ConcurrentWriteAndFlush(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
// Flusher goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
@@ -304,33 +305,33 @@ func TestFlushOffsetGap_ConcurrentWriteAndFlush(t *testing.T) {
|
||||
logBuffer.ForceFlush()
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
wg.Wait()
|
||||
time.Sleep(200 * time.Millisecond) // Wait for final flush
|
||||
|
||||
|
||||
// Check final state
|
||||
logBuffer.RLock()
|
||||
finalOffset := logBuffer.offset
|
||||
finalBufferStart := logBuffer.bufferStartOffset
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
flushMu.Lock()
|
||||
flushedCount := len(allFlushedOffsets)
|
||||
flushMu.Unlock()
|
||||
|
||||
|
||||
expectedCount := int(finalOffset)
|
||||
inMemory := int(finalOffset - finalBufferStart)
|
||||
totalAccountedFor := flushedCount + inMemory
|
||||
|
||||
|
||||
t.Logf("\nFINAL STATE:")
|
||||
t.Logf(" Total messages sent: %d (offsets 0-%d)", expectedCount, expectedCount-1)
|
||||
t.Logf(" Flushed to disk: %d", flushedCount)
|
||||
t.Logf(" In memory: %d (offsets %d-%d)", inMemory, finalBufferStart, finalOffset-1)
|
||||
t.Logf(" Total accounted: %d", totalAccountedFor)
|
||||
t.Logf(" Missing: %d", expectedCount-totalAccountedFor)
|
||||
|
||||
|
||||
if totalAccountedFor < expectedCount {
|
||||
t.Errorf("❌ DATA LOSS in concurrent scenario: %d messages missing!", expectedCount-totalAccountedFor)
|
||||
t.Errorf("DATA LOSS in concurrent scenario: %d messages missing!", expectedCount-totalAccountedFor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,7 +345,7 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
messages []*filer_pb.LogEntry
|
||||
}
|
||||
var flushMu sync.Mutex
|
||||
|
||||
|
||||
flushFn := func(logBuffer *LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
|
||||
// Parse messages from buffer
|
||||
messages := []*filer_pb.LogEntry{}
|
||||
@@ -360,7 +361,7 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
}
|
||||
pos += 4 + int(size)
|
||||
}
|
||||
|
||||
|
||||
flushMu.Lock()
|
||||
flushedData = append(flushedData, struct {
|
||||
minOffset int64
|
||||
@@ -368,17 +369,17 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
messages []*filer_pb.LogEntry
|
||||
}{minOffset, maxOffset, messages})
|
||||
flushMu.Unlock()
|
||||
|
||||
|
||||
t.Logf("FLUSH: minOffset=%d maxOffset=%d, parsed %d messages", minOffset, maxOffset, len(messages))
|
||||
}
|
||||
|
||||
|
||||
logBuffer := NewLogBuffer("test", time.Hour, flushFn, nil, nil)
|
||||
defer logBuffer.ShutdownLogBuffer()
|
||||
|
||||
|
||||
// Simulate broker behavior: assign Kafka offsets and add to buffer
|
||||
// This is what PublishWithOffset() does
|
||||
nextKafkaOffset := int64(0)
|
||||
|
||||
|
||||
// Round 1: Add 50 messages with Kafka offsets 0-49
|
||||
t.Logf("\n=== ROUND 1: Adding messages 0-49 ===")
|
||||
for i := 0; i < 50; i++ {
|
||||
@@ -391,7 +392,7 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
logBuffer.AddLogEntryToBuffer(logEntry)
|
||||
nextKafkaOffset++
|
||||
}
|
||||
|
||||
|
||||
// Check buffer state before flush
|
||||
logBuffer.RLock()
|
||||
beforeFlushOffset := logBuffer.offset
|
||||
@@ -399,11 +400,11 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
logBuffer.RUnlock()
|
||||
t.Logf("Before flush: logBuffer.offset=%d, bufferStartOffset=%d, nextKafkaOffset=%d",
|
||||
beforeFlushOffset, beforeFlushStart, nextKafkaOffset)
|
||||
|
||||
|
||||
// Flush
|
||||
logBuffer.ForceFlush()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
|
||||
// Check buffer state after flush
|
||||
logBuffer.RLock()
|
||||
afterFlushOffset := logBuffer.offset
|
||||
@@ -411,7 +412,7 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
logBuffer.RUnlock()
|
||||
t.Logf("After flush: logBuffer.offset=%d, bufferStartOffset=%d",
|
||||
afterFlushOffset, afterFlushStart)
|
||||
|
||||
|
||||
// Round 2: Add another 50 messages with Kafka offsets 50-99
|
||||
t.Logf("\n=== ROUND 2: Adding messages 50-99 ===")
|
||||
for i := 0; i < 50; i++ {
|
||||
@@ -424,29 +425,29 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
logBuffer.AddLogEntryToBuffer(logEntry)
|
||||
nextKafkaOffset++
|
||||
}
|
||||
|
||||
|
||||
logBuffer.ForceFlush()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
|
||||
// Verification: Check if all Kafka offsets are accounted for
|
||||
flushMu.Lock()
|
||||
t.Logf("\n=== VERIFICATION ===")
|
||||
t.Logf("Expected Kafka offsets: 0-%d", nextKafkaOffset-1)
|
||||
|
||||
|
||||
allOffsets := make(map[int64]bool)
|
||||
for flushIdx, flush := range flushedData {
|
||||
t.Logf("Flush #%d: minOffset=%d, maxOffset=%d, messages=%d",
|
||||
flushIdx, flush.minOffset, flush.maxOffset, len(flush.messages))
|
||||
|
||||
|
||||
for _, msg := range flush.messages {
|
||||
if allOffsets[msg.Offset] {
|
||||
t.Errorf(" ❌ DUPLICATE: Offset %d appears multiple times!", msg.Offset)
|
||||
t.Errorf(" DUPLICATE: Offset %d appears multiple times!", msg.Offset)
|
||||
}
|
||||
allOffsets[msg.Offset] = true
|
||||
}
|
||||
}
|
||||
flushMu.Unlock()
|
||||
|
||||
|
||||
// Check for missing offsets
|
||||
missingOffsets := []int64{}
|
||||
for expectedOffset := int64(0); expectedOffset < nextKafkaOffset; expectedOffset++ {
|
||||
@@ -454,9 +455,9 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
missingOffsets = append(missingOffsets, expectedOffset)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if len(missingOffsets) > 0 {
|
||||
t.Errorf("\n❌ MISSING OFFSETS DETECTED: %d offsets missing", len(missingOffsets))
|
||||
t.Errorf("\nMISSING OFFSETS DETECTED: %d offsets missing", len(missingOffsets))
|
||||
if len(missingOffsets) <= 20 {
|
||||
t.Errorf("Missing: %v", missingOffsets)
|
||||
} else {
|
||||
@@ -464,22 +465,22 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
}
|
||||
t.Errorf("\nThis reproduces the production bug!")
|
||||
} else {
|
||||
t.Logf("\n✅ SUCCESS: All %d Kafka offsets accounted for (0-%d)", nextKafkaOffset, nextKafkaOffset-1)
|
||||
t.Logf("\nSUCCESS: All %d Kafka offsets accounted for (0-%d)", nextKafkaOffset, nextKafkaOffset-1)
|
||||
}
|
||||
|
||||
|
||||
// Check buffer offset consistency
|
||||
logBuffer.RLock()
|
||||
finalOffset := logBuffer.offset
|
||||
finalBufferStart := logBuffer.bufferStartOffset
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
t.Logf("\nFinal buffer state:")
|
||||
t.Logf(" logBuffer.offset: %d", finalOffset)
|
||||
t.Logf(" bufferStartOffset: %d", finalBufferStart)
|
||||
t.Logf(" Expected (nextKafkaOffset): %d", nextKafkaOffset)
|
||||
|
||||
|
||||
if finalOffset != nextKafkaOffset {
|
||||
t.Errorf("❌ logBuffer.offset mismatch: expected %d, got %d", nextKafkaOffset, finalOffset)
|
||||
t.Errorf("logBuffer.offset mismatch: expected %d, got %d", nextKafkaOffset, finalOffset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,12 +489,12 @@ func TestFlushOffsetGap_ProductionScenario(t *testing.T) {
|
||||
func TestFlushOffsetGap_ConcurrentReadDuringFlush(t *testing.T) {
|
||||
var flushedOffsets []int64
|
||||
var flushMu sync.Mutex
|
||||
|
||||
|
||||
readFromDiskFn := func(startPosition MessagePosition, stopTsNs int64, eachLogEntryFn EachLogEntryFuncType) (MessagePosition, bool, error) {
|
||||
// Simulate reading from disk - return flushed offsets
|
||||
flushMu.Lock()
|
||||
defer flushMu.Unlock()
|
||||
|
||||
|
||||
for _, offset := range flushedOffsets {
|
||||
if offset >= startPosition.Offset {
|
||||
logEntry := &filer_pb.LogEntry{
|
||||
@@ -510,12 +511,12 @@ func TestFlushOffsetGap_ConcurrentReadDuringFlush(t *testing.T) {
|
||||
}
|
||||
return startPosition, false, nil
|
||||
}
|
||||
|
||||
|
||||
flushFn := func(logBuffer *LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
|
||||
// Parse and store flushed offsets
|
||||
flushMu.Lock()
|
||||
defer flushMu.Unlock()
|
||||
|
||||
|
||||
for pos := 0; pos+4 < len(buf); {
|
||||
size := uint32(buf[pos])<<24 | uint32(buf[pos+1])<<16 | uint32(buf[pos+2])<<8 | uint32(buf[pos+3])
|
||||
if pos+4+int(size) > len(buf) {
|
||||
@@ -528,14 +529,14 @@ func TestFlushOffsetGap_ConcurrentReadDuringFlush(t *testing.T) {
|
||||
}
|
||||
pos += 4 + int(size)
|
||||
}
|
||||
|
||||
|
||||
t.Logf("FLUSH: Stored %d offsets to disk (minOffset=%d, maxOffset=%d)",
|
||||
len(flushedOffsets), minOffset, maxOffset)
|
||||
}
|
||||
|
||||
|
||||
logBuffer := NewLogBuffer("test", time.Hour, flushFn, readFromDiskFn, nil)
|
||||
defer logBuffer.ShutdownLogBuffer()
|
||||
|
||||
|
||||
// Add 100 messages
|
||||
t.Logf("Adding 100 messages...")
|
||||
for i := int64(0); i < 100; i++ {
|
||||
@@ -547,41 +548,41 @@ func TestFlushOffsetGap_ConcurrentReadDuringFlush(t *testing.T) {
|
||||
}
|
||||
logBuffer.AddLogEntryToBuffer(logEntry)
|
||||
}
|
||||
|
||||
|
||||
// Flush (moves data to disk)
|
||||
t.Logf("Flushing...")
|
||||
logBuffer.ForceFlush()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
|
||||
// Now try to read all messages using ReadMessagesAtOffset
|
||||
t.Logf("\nReading messages from offset 0...")
|
||||
messages, nextOffset, hwm, endOfPartition, err := logBuffer.ReadMessagesAtOffset(0, 1000, 1024*1024)
|
||||
|
||||
|
||||
t.Logf("Read result: messages=%d, nextOffset=%d, hwm=%d, endOfPartition=%v, err=%v",
|
||||
len(messages), nextOffset, hwm, endOfPartition, err)
|
||||
|
||||
|
||||
// Verify all offsets can be read
|
||||
readOffsets := make(map[int64]bool)
|
||||
for _, msg := range messages {
|
||||
readOffsets[msg.Offset] = true
|
||||
}
|
||||
|
||||
|
||||
missingOffsets := []int64{}
|
||||
for expectedOffset := int64(0); expectedOffset < 100; expectedOffset++ {
|
||||
if !readOffsets[expectedOffset] {
|
||||
missingOffsets = append(missingOffsets, expectedOffset)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if len(missingOffsets) > 0 {
|
||||
t.Errorf("❌ MISSING OFFSETS after flush: %d offsets cannot be read", len(missingOffsets))
|
||||
t.Errorf("MISSING OFFSETS after flush: %d offsets cannot be read", len(missingOffsets))
|
||||
if len(missingOffsets) <= 20 {
|
||||
t.Errorf("Missing: %v", missingOffsets)
|
||||
} else {
|
||||
t.Errorf("Missing: %v ... and %d more", missingOffsets[:20], len(missingOffsets)-20)
|
||||
}
|
||||
} else {
|
||||
t.Logf("✅ All 100 offsets can be read after flush")
|
||||
t.Logf("All 100 offsets can be read after flush")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -590,29 +591,29 @@ func TestFlushOffsetGap_ConcurrentReadDuringFlush(t *testing.T) {
|
||||
func TestFlushOffsetGap_ForceFlushAdvancesBuffer(t *testing.T) {
|
||||
flushedRanges := []struct{ min, max int64 }{}
|
||||
var flushMu sync.Mutex
|
||||
|
||||
|
||||
flushFn := func(logBuffer *LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
|
||||
flushMu.Lock()
|
||||
flushedRanges = append(flushedRanges, struct{ min, max int64 }{minOffset, maxOffset})
|
||||
flushMu.Unlock()
|
||||
t.Logf("FLUSH: offsets %d-%d", minOffset, maxOffset)
|
||||
}
|
||||
|
||||
|
||||
logBuffer := NewLogBuffer("test", time.Hour, flushFn, nil, nil) // Long interval, manual flush only
|
||||
defer logBuffer.ShutdownLogBuffer()
|
||||
|
||||
|
||||
// Send messages, flush, check state - repeat
|
||||
for round := 0; round < 3; round++ {
|
||||
t.Logf("\n=== ROUND %d ===", round)
|
||||
|
||||
|
||||
// Check state before adding messages
|
||||
logBuffer.RLock()
|
||||
beforeOffset := logBuffer.offset
|
||||
beforeStart := logBuffer.bufferStartOffset
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
t.Logf("Before adding: offset=%d, bufferStartOffset=%d", beforeOffset, beforeStart)
|
||||
|
||||
|
||||
// Add 10 messages
|
||||
for i := 0; i < 10; i++ {
|
||||
logBuffer.AddToBuffer(&mq_pb.DataMessage{
|
||||
@@ -621,60 +622,59 @@ func TestFlushOffsetGap_ForceFlushAdvancesBuffer(t *testing.T) {
|
||||
TsNs: time.Now().UnixNano(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// Check state after adding
|
||||
logBuffer.RLock()
|
||||
afterAddOffset := logBuffer.offset
|
||||
afterAddStart := logBuffer.bufferStartOffset
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
t.Logf("After adding: offset=%d, bufferStartOffset=%d", afterAddOffset, afterAddStart)
|
||||
|
||||
|
||||
// Force flush
|
||||
t.Logf("Forcing flush...")
|
||||
logBuffer.ForceFlush()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
|
||||
// Check state after flush
|
||||
logBuffer.RLock()
|
||||
afterFlushOffset := logBuffer.offset
|
||||
afterFlushStart := logBuffer.bufferStartOffset
|
||||
logBuffer.RUnlock()
|
||||
|
||||
|
||||
t.Logf("After flush: offset=%d, bufferStartOffset=%d", afterFlushOffset, afterFlushStart)
|
||||
|
||||
|
||||
// CRITICAL CHECK: bufferStartOffset should advance to where offset was before flush
|
||||
if afterFlushStart != afterAddOffset {
|
||||
t.Errorf("❌ FLUSH BUG: bufferStartOffset did NOT advance correctly!")
|
||||
t.Errorf("FLUSH BUG: bufferStartOffset did NOT advance correctly!")
|
||||
t.Errorf(" Expected bufferStartOffset=%d (= offset after add)", afterAddOffset)
|
||||
t.Errorf(" Actual bufferStartOffset=%d", afterFlushStart)
|
||||
t.Errorf(" Gap: %d offsets WILL BE LOST", afterAddOffset-afterFlushStart)
|
||||
} else {
|
||||
t.Logf("✅ bufferStartOffset correctly advanced to %d", afterFlushStart)
|
||||
t.Logf("bufferStartOffset correctly advanced to %d", afterFlushStart)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Final verification: check all offset ranges are continuous
|
||||
flushMu.Lock()
|
||||
t.Logf("\n=== FLUSHED RANGES ===")
|
||||
for i, r := range flushedRanges {
|
||||
t.Logf("Flush #%d: offsets %d-%d", i, r.min, r.max)
|
||||
|
||||
|
||||
// Check continuity with previous flush
|
||||
if i > 0 {
|
||||
prevMax := flushedRanges[i-1].max
|
||||
currentMin := r.min
|
||||
gap := currentMin - (prevMax + 1)
|
||||
|
||||
|
||||
if gap > 0 {
|
||||
t.Errorf("❌ GAP between flush #%d and #%d: %d offsets missing!", i-1, i, gap)
|
||||
t.Errorf("GAP between flush #%d and #%d: %d offsets missing!", i-1, i, gap)
|
||||
} else if gap < 0 {
|
||||
t.Errorf("❌ OVERLAP between flush #%d and #%d: %d offsets duplicated!", i-1, i, -gap)
|
||||
t.Errorf("OVERLAP between flush #%d and #%d: %d offsets duplicated!", i-1, i, -gap)
|
||||
} else {
|
||||
t.Logf(" ✅ Continuous with previous flush")
|
||||
t.Logf(" Continuous with previous flush")
|
||||
}
|
||||
}
|
||||
}
|
||||
flushMu.Unlock()
|
||||
}
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
)
|
||||
|
||||
const (
|
||||
// minThroughputBytesPerSecond defines the minimum expected throughput (4KB/s)
|
||||
// Used to calculate timeout scaling based on data transferred
|
||||
minThroughputBytesPerSecond = 4000
|
||||
|
||||
// graceTimeCapMultiplier caps the grace period for slow clients at 3x base timeout
|
||||
// This prevents indefinite connections while allowing time for server-side chunk fetches
|
||||
graceTimeCapMultiplier = 3
|
||||
)
|
||||
|
||||
// Listener wraps a net.Listener, and gives a place to store the timeout
|
||||
// parameters. On Accept, it will wrap the net.Conn with our own Conn for us.
|
||||
type Listener struct {
|
||||
@@ -39,11 +50,28 @@ type Conn struct {
|
||||
isClosed bool
|
||||
bytesRead int64
|
||||
bytesWritten int64
|
||||
lastWrite time.Time
|
||||
}
|
||||
|
||||
// calculateBytesPerTimeout calculates the expected number of bytes that should
|
||||
// be transferred during one timeout period, based on the minimum throughput.
|
||||
// Returns at least 1 to prevent division by zero.
|
||||
func calculateBytesPerTimeout(timeout time.Duration) int64 {
|
||||
bytesPerTimeout := int64(float64(minThroughputBytesPerSecond) * timeout.Seconds())
|
||||
if bytesPerTimeout <= 0 {
|
||||
return 1 // Prevent division by zero
|
||||
}
|
||||
return bytesPerTimeout
|
||||
}
|
||||
|
||||
func (c *Conn) Read(b []byte) (count int, e error) {
|
||||
if c.ReadTimeout != 0 {
|
||||
err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout * time.Duration(c.bytesRead/40000+1)))
|
||||
// Calculate expected bytes per timeout period based on minimum throughput (4KB/s)
|
||||
// Example: with ReadTimeout=30s, bytesPerTimeout = 4000 * 30 = 120KB
|
||||
// After reading 1MB: multiplier = 1,000,000/120,000 + 1 ≈ 9, deadline = 30s * 9 = 270s
|
||||
bytesPerTimeout := calculateBytesPerTimeout(c.ReadTimeout)
|
||||
timeoutMultiplier := time.Duration(c.bytesRead/bytesPerTimeout + 1)
|
||||
err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout * timeoutMultiplier))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -58,8 +86,42 @@ func (c *Conn) Read(b []byte) (count int, e error) {
|
||||
|
||||
func (c *Conn) Write(b []byte) (count int, e error) {
|
||||
if c.WriteTimeout != 0 {
|
||||
// minimum 4KB/s
|
||||
err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout * time.Duration(c.bytesWritten/40000+1)))
|
||||
now := time.Now()
|
||||
// Calculate timeout with two components:
|
||||
// 1. Base timeout scaled by cumulative data (minimum throughput of 4KB/s)
|
||||
// 2. Additional grace period if there was a gap since last write (for chunk fetch delays)
|
||||
|
||||
// Calculate expected bytes per timeout period based on minimum throughput (4KB/s)
|
||||
// Example: with WriteTimeout=30s, bytesPerTimeout = 4000 * 30 = 120KB
|
||||
// After writing 1MB: multiplier = 1,000,000/120,000 + 1 ≈ 9, baseTimeout = 30s * 9 = 270s
|
||||
bytesPerTimeout := calculateBytesPerTimeout(c.WriteTimeout)
|
||||
timeoutMultiplier := time.Duration(c.bytesWritten/bytesPerTimeout + 1)
|
||||
baseTimeout := c.WriteTimeout * timeoutMultiplier
|
||||
|
||||
// If it's been a while since last write, add grace time for server-side chunk fetches
|
||||
// But cap it to avoid keeping slow clients connected indefinitely
|
||||
//
|
||||
// The comparison uses unscaled WriteTimeout intentionally: triggers grace when idle time
|
||||
// exceeds base timeout, independent of throughput scaling.
|
||||
if !c.lastWrite.IsZero() {
|
||||
timeSinceLastWrite := now.Sub(c.lastWrite)
|
||||
if timeSinceLastWrite > c.WriteTimeout {
|
||||
// Add grace time capped at graceTimeCapMultiplier * scaled timeout.
|
||||
// This allows total deadline up to 4x scaled timeout for server-side delays.
|
||||
//
|
||||
// Example: WriteTimeout=30s, 1MB written (multiplier≈9), baseTimeout=270s
|
||||
// If 400s gap occurs fetching chunks: graceTime capped at 270s*3=810s
|
||||
// Final deadline: 270s + 810s = 1080s (~18min) to accommodate slow storage
|
||||
// But if only 50s gap: graceTime = 50s, final deadline = 270s + 50s = 320s
|
||||
graceTime := timeSinceLastWrite
|
||||
if graceTime > baseTimeout*graceTimeCapMultiplier {
|
||||
graceTime = baseTimeout * graceTimeCapMultiplier
|
||||
}
|
||||
baseTimeout += graceTime
|
||||
}
|
||||
}
|
||||
|
||||
err := c.Conn.SetWriteDeadline(now.Add(baseTimeout))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -68,6 +130,7 @@ func (c *Conn) Write(b []byte) (count int, e error) {
|
||||
if e == nil {
|
||||
stats.BytesOut(int64(count))
|
||||
c.bytesWritten += int64(count)
|
||||
c.lastWrite = time.Now()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -44,7 +44,11 @@ func selectIpV4(netInterfaces []net.Interface, isIpV4 bool) string {
|
||||
}
|
||||
} else {
|
||||
if ipNet.IP.To16() != nil {
|
||||
return ipNet.IP.String()
|
||||
// Filter out link-local IPv6 addresses (fe80::/10)
|
||||
// They require zone identifiers and are not suitable for server binding
|
||||
if !ipNet.IP.IsLinkLocalUnicast() {
|
||||
return ipNet.IP.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(3)
|
||||
MINOR_VERSION = int32(98)
|
||||
MINOR_VERSION = int32(99)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
+269
-35
@@ -2,11 +2,17 @@ package wdclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
@@ -29,10 +35,16 @@ type MasterClient struct {
|
||||
masters pb.ServerDiscovery
|
||||
grpcDialOption grpc.DialOption
|
||||
|
||||
*vidMap
|
||||
// vidMap stores volume location mappings
|
||||
// Protected by vidMapLock to prevent race conditions during pointer swaps in resetVidMap
|
||||
vidMap *vidMap
|
||||
vidMapLock sync.RWMutex
|
||||
vidMapCacheSize int
|
||||
OnPeerUpdate func(update *master_pb.ClusterNodeUpdate, startFrom time.Time)
|
||||
OnPeerUpdateLock sync.RWMutex
|
||||
|
||||
// Per-batch in-flight tracking to prevent duplicate lookups for the same set of volumes
|
||||
vidLookupGroup singleflight.Group
|
||||
}
|
||||
|
||||
func NewMasterClient(grpcDialOption grpc.DialOption, filerGroup string, clientType string, clientHost pb.ServerAddress, clientDataCenter string, rack string, masters pb.ServerDiscovery) *MasterClient {
|
||||
@@ -59,39 +71,180 @@ func (mc *MasterClient) GetLookupFileIdFunction() LookupFileIdFunctionType {
|
||||
}
|
||||
|
||||
func (mc *MasterClient) LookupFileIdWithFallback(ctx context.Context, fileId string) (fullUrls []string, err error) {
|
||||
fullUrls, err = mc.vidMap.LookupFileId(ctx, fileId)
|
||||
// Try cache first using the fast path - grab both vidMap and dataCenter in one lock
|
||||
mc.vidMapLock.RLock()
|
||||
vm := mc.vidMap
|
||||
dataCenter := vm.DataCenter
|
||||
mc.vidMapLock.RUnlock()
|
||||
|
||||
fullUrls, err = vm.LookupFileId(ctx, fileId)
|
||||
if err == nil && len(fullUrls) > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
err = pb.WithMasterClient(false, mc.GetMaster(ctx), mc.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.LookupVolume(ctx, &master_pb.LookupVolumeRequest{
|
||||
VolumeOrFileIds: []string{fileId},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("LookupVolume %s failed: %v", fileId, err)
|
||||
// Extract volume ID from file ID (format: "volumeId,needle_id_cookie")
|
||||
parts := strings.Split(fileId, ",")
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("invalid fileId %s", fileId)
|
||||
}
|
||||
volumeId := parts[0]
|
||||
|
||||
// Use shared lookup logic with batching and singleflight
|
||||
vidLocations, err := mc.LookupVolumeIdsWithFallback(ctx, []string{volumeId})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("LookupVolume %s failed: %v", fileId, err)
|
||||
}
|
||||
|
||||
locations, found := vidLocations[volumeId]
|
||||
if !found || len(locations) == 0 {
|
||||
return nil, fmt.Errorf("volume %s not found for fileId %s", volumeId, fileId)
|
||||
}
|
||||
|
||||
// Build HTTP URLs from locations, preferring same data center
|
||||
var sameDcUrls, otherDcUrls []string
|
||||
for _, loc := range locations {
|
||||
httpUrl := "http://" + loc.Url + "/" + fileId
|
||||
if dataCenter != "" && dataCenter == loc.DataCenter {
|
||||
sameDcUrls = append(sameDcUrls, httpUrl)
|
||||
} else {
|
||||
otherDcUrls = append(otherDcUrls, httpUrl)
|
||||
}
|
||||
for vid, vidLocation := range resp.VolumeIdLocations {
|
||||
for _, vidLoc := range vidLocation.Locations {
|
||||
loc := Location{
|
||||
Url: vidLoc.Url,
|
||||
PublicUrl: vidLoc.PublicUrl,
|
||||
GrpcPort: int(vidLoc.GrpcPort),
|
||||
DataCenter: vidLoc.DataCenter,
|
||||
}
|
||||
mc.vidMap.addLocation(uint32(vid), loc)
|
||||
httpUrl := "http://" + loc.Url + "/" + fileId
|
||||
// Prefer same data center
|
||||
if mc.DataCenter != "" && mc.DataCenter == loc.DataCenter {
|
||||
fullUrls = append([]string{httpUrl}, fullUrls...)
|
||||
} else {
|
||||
fullUrls = append(fullUrls, httpUrl)
|
||||
}
|
||||
}
|
||||
|
||||
// Prefer same data center
|
||||
fullUrls = append(sameDcUrls, otherDcUrls...)
|
||||
return fullUrls, nil
|
||||
}
|
||||
|
||||
// LookupVolumeIdsWithFallback looks up volume locations, querying master if not in cache
|
||||
// Uses singleflight to coalesce concurrent requests for the same batch of volumes
|
||||
func (mc *MasterClient) LookupVolumeIdsWithFallback(ctx context.Context, volumeIds []string) (map[string][]Location, error) {
|
||||
result := make(map[string][]Location)
|
||||
var needsLookup []string
|
||||
var lookupErrors []error
|
||||
|
||||
// Check cache first and parse volume IDs once
|
||||
vidStringToUint := make(map[string]uint32, len(volumeIds))
|
||||
|
||||
// Get stable pointer to vidMap with minimal lock hold time
|
||||
vm := mc.getStableVidMap()
|
||||
|
||||
for _, vidString := range volumeIds {
|
||||
vid, err := strconv.ParseUint(vidString, 10, 32)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid volume id %s: %v", vidString, err)
|
||||
}
|
||||
vidStringToUint[vidString] = uint32(vid)
|
||||
|
||||
locations, found := vm.GetLocations(uint32(vid))
|
||||
if found && len(locations) > 0 {
|
||||
result[vidString] = locations
|
||||
} else {
|
||||
needsLookup = append(needsLookup, vidString)
|
||||
}
|
||||
}
|
||||
|
||||
if len(needsLookup) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Batch query all missing volumes using singleflight on the batch key
|
||||
// Sort for stable key to coalesce identical batches
|
||||
sort.Strings(needsLookup)
|
||||
batchKey := strings.Join(needsLookup, ",")
|
||||
|
||||
sfResult, err, _ := mc.vidLookupGroup.Do(batchKey, func() (interface{}, error) {
|
||||
// Double-check cache for volumes that might have been populated while waiting
|
||||
stillNeedLookup := make([]string, 0, len(needsLookup))
|
||||
batchResult := make(map[string][]Location)
|
||||
|
||||
// Get stable pointer with minimal lock hold time
|
||||
vm := mc.getStableVidMap()
|
||||
|
||||
for _, vidString := range needsLookup {
|
||||
vid := vidStringToUint[vidString] // Use pre-parsed value
|
||||
if locations, found := vm.GetLocations(vid); found && len(locations) > 0 {
|
||||
batchResult[vidString] = locations
|
||||
} else {
|
||||
stillNeedLookup = append(stillNeedLookup, vidString)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
if len(stillNeedLookup) == 0 {
|
||||
return batchResult, nil
|
||||
}
|
||||
|
||||
// Query master with batched volume IDs
|
||||
glog.V(2).Infof("Looking up %d volumes from master: %v", len(stillNeedLookup), stillNeedLookup)
|
||||
|
||||
err := pb.WithMasterClient(false, mc.GetMaster(ctx), mc.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.LookupVolume(ctx, &master_pb.LookupVolumeRequest{
|
||||
VolumeOrFileIds: stillNeedLookup,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("master lookup failed: %v", err)
|
||||
}
|
||||
|
||||
for _, vidLoc := range resp.VolumeIdLocations {
|
||||
if vidLoc.Error != "" {
|
||||
glog.V(0).Infof("volume %s lookup error: %s", vidLoc.VolumeOrFileId, vidLoc.Error)
|
||||
continue
|
||||
}
|
||||
|
||||
// Parse volume ID from response
|
||||
parts := strings.Split(vidLoc.VolumeOrFileId, ",")
|
||||
vidOnly := parts[0]
|
||||
vid, err := strconv.ParseUint(vidOnly, 10, 32)
|
||||
if err != nil {
|
||||
glog.Warningf("Failed to parse volume id '%s' from master response '%s': %v", vidOnly, vidLoc.VolumeOrFileId, err)
|
||||
continue
|
||||
}
|
||||
|
||||
var locations []Location
|
||||
for _, masterLoc := range vidLoc.Locations {
|
||||
loc := Location{
|
||||
Url: masterLoc.Url,
|
||||
PublicUrl: masterLoc.PublicUrl,
|
||||
GrpcPort: int(masterLoc.GrpcPort),
|
||||
DataCenter: masterLoc.DataCenter,
|
||||
}
|
||||
mc.addLocation(uint32(vid), loc)
|
||||
locations = append(locations, loc)
|
||||
}
|
||||
|
||||
if len(locations) > 0 {
|
||||
batchResult[vidOnly] = locations
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return batchResult, err
|
||||
}
|
||||
return batchResult, nil
|
||||
})
|
||||
return
|
||||
|
||||
if err != nil {
|
||||
lookupErrors = append(lookupErrors, err)
|
||||
}
|
||||
|
||||
// Merge singleflight batch results
|
||||
if batchLocations, ok := sfResult.(map[string][]Location); ok {
|
||||
for vid, locs := range batchLocations {
|
||||
result[vid] = locs
|
||||
}
|
||||
}
|
||||
|
||||
// Check for volumes that still weren't found
|
||||
for _, vidString := range needsLookup {
|
||||
if _, found := result[vidString]; !found {
|
||||
lookupErrors = append(lookupErrors, fmt.Errorf("volume %s not found", vidString))
|
||||
}
|
||||
}
|
||||
|
||||
// Return aggregated errors using errors.Join to preserve error types
|
||||
return result, errors.Join(lookupErrors...)
|
||||
}
|
||||
|
||||
func (mc *MasterClient) getCurrentMaster() pb.ServerAddress {
|
||||
@@ -210,7 +363,7 @@ func (mc *MasterClient) tryConnectToMaster(ctx context.Context, master pb.Server
|
||||
|
||||
if err = stream.Send(&master_pb.KeepConnectedRequest{
|
||||
FilerGroup: mc.FilerGroup,
|
||||
DataCenter: mc.DataCenter,
|
||||
DataCenter: mc.GetDataCenter(),
|
||||
Rack: mc.rack,
|
||||
ClientType: mc.clientType,
|
||||
ClientAddress: string(mc.clientHost),
|
||||
@@ -341,15 +494,96 @@ func (mc *MasterClient) WithClientCustomGetMaster(getMasterF func() pb.ServerAdd
|
||||
})
|
||||
}
|
||||
|
||||
func (mc *MasterClient) resetVidMap() {
|
||||
tail := &vidMap{
|
||||
vid2Locations: mc.vid2Locations,
|
||||
ecVid2Locations: mc.ecVid2Locations,
|
||||
DataCenter: mc.DataCenter,
|
||||
cache: mc.cache,
|
||||
}
|
||||
// getStableVidMap gets a stable pointer to the vidMap, releasing the lock immediately.
|
||||
// This is safe for read operations as the returned pointer is a stable snapshot,
|
||||
// and the underlying vidMap methods have their own internal locking.
|
||||
func (mc *MasterClient) getStableVidMap() *vidMap {
|
||||
mc.vidMapLock.RLock()
|
||||
vm := mc.vidMap
|
||||
mc.vidMapLock.RUnlock()
|
||||
return vm
|
||||
}
|
||||
|
||||
nvm := newVidMap(mc.DataCenter)
|
||||
// withCurrentVidMap executes a function with the current vidMap under a read lock.
|
||||
// This is for methods that modify vidMap's internal state, ensuring the pointer
|
||||
// is not swapped by resetVidMap during the operation. The actual map mutations
|
||||
// are protected by vidMap's internal mutex.
|
||||
func (mc *MasterClient) withCurrentVidMap(f func(vm *vidMap)) {
|
||||
mc.vidMapLock.RLock()
|
||||
defer mc.vidMapLock.RUnlock()
|
||||
f(mc.vidMap)
|
||||
}
|
||||
|
||||
// Public methods for external packages to access vidMap safely
|
||||
|
||||
// GetLocations safely retrieves volume locations
|
||||
func (mc *MasterClient) GetLocations(vid uint32) (locations []Location, found bool) {
|
||||
return mc.getStableVidMap().GetLocations(vid)
|
||||
}
|
||||
|
||||
// GetLocationsClone safely retrieves a clone of volume locations
|
||||
func (mc *MasterClient) GetLocationsClone(vid uint32) (locations []Location, found bool) {
|
||||
return mc.getStableVidMap().GetLocationsClone(vid)
|
||||
}
|
||||
|
||||
// GetVidLocations safely retrieves volume locations by string ID
|
||||
func (mc *MasterClient) GetVidLocations(vid string) (locations []Location, err error) {
|
||||
return mc.getStableVidMap().GetVidLocations(vid)
|
||||
}
|
||||
|
||||
// LookupFileId safely looks up URLs for a file ID
|
||||
func (mc *MasterClient) LookupFileId(ctx context.Context, fileId string) (fullUrls []string, err error) {
|
||||
return mc.getStableVidMap().LookupFileId(ctx, fileId)
|
||||
}
|
||||
|
||||
// LookupVolumeServerUrl safely looks up volume server URLs
|
||||
func (mc *MasterClient) LookupVolumeServerUrl(vid string) (serverUrls []string, err error) {
|
||||
return mc.getStableVidMap().LookupVolumeServerUrl(vid)
|
||||
}
|
||||
|
||||
// GetDataCenter safely retrieves the data center
|
||||
func (mc *MasterClient) GetDataCenter() string {
|
||||
return mc.getStableVidMap().DataCenter
|
||||
}
|
||||
|
||||
// Thread-safe helpers for vidMap operations
|
||||
|
||||
// addLocation adds a volume location
|
||||
func (mc *MasterClient) addLocation(vid uint32, location Location) {
|
||||
mc.withCurrentVidMap(func(vm *vidMap) {
|
||||
vm.addLocation(vid, location)
|
||||
})
|
||||
}
|
||||
|
||||
// deleteLocation removes a volume location
|
||||
func (mc *MasterClient) deleteLocation(vid uint32, location Location) {
|
||||
mc.withCurrentVidMap(func(vm *vidMap) {
|
||||
vm.deleteLocation(vid, location)
|
||||
})
|
||||
}
|
||||
|
||||
// addEcLocation adds an EC volume location
|
||||
func (mc *MasterClient) addEcLocation(vid uint32, location Location) {
|
||||
mc.withCurrentVidMap(func(vm *vidMap) {
|
||||
vm.addEcLocation(vid, location)
|
||||
})
|
||||
}
|
||||
|
||||
// deleteEcLocation removes an EC volume location
|
||||
func (mc *MasterClient) deleteEcLocation(vid uint32, location Location) {
|
||||
mc.withCurrentVidMap(func(vm *vidMap) {
|
||||
vm.deleteEcLocation(vid, location)
|
||||
})
|
||||
}
|
||||
|
||||
func (mc *MasterClient) resetVidMap() {
|
||||
mc.vidMapLock.Lock()
|
||||
defer mc.vidMapLock.Unlock()
|
||||
|
||||
// Create a shallow clone to preserve in the cache chain
|
||||
tail := mc.vidMap.shallowClone()
|
||||
|
||||
nvm := newVidMap(tail.DataCenter)
|
||||
nvm.cache = tail
|
||||
mc.vidMap = nvm
|
||||
|
||||
|
||||
@@ -53,6 +53,17 @@ func newVidMap(dataCenter string) *vidMap {
|
||||
}
|
||||
}
|
||||
|
||||
// shallowClone creates a shallow copy of the vidMap for use in cache chaining.
|
||||
// The caller is responsible for ensuring thread safety.
|
||||
func (vc *vidMap) shallowClone() *vidMap {
|
||||
return &vidMap{
|
||||
vid2Locations: vc.vid2Locations,
|
||||
ecVid2Locations: vc.ecVid2Locations,
|
||||
DataCenter: vc.DataCenter,
|
||||
cache: vc.cache,
|
||||
}
|
||||
}
|
||||
|
||||
func (vc *vidMap) getLocationIndex(length int) (int, error) {
|
||||
if length <= 0 {
|
||||
return 0, fmt.Errorf("invalid length: %d", length)
|
||||
|
||||
@@ -24,7 +24,7 @@ type GrpcAdminClient struct {
|
||||
workerID string
|
||||
dialOption grpc.DialOption
|
||||
|
||||
cmds chan grpcCommand
|
||||
cmds chan grpcCommand
|
||||
|
||||
// Reconnection parameters
|
||||
maxReconnectAttempts int
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user