Compare commits

..
Author SHA1 Message Date
Chris LuandDevin dd73e00391 test: stop the compat server even when startup fails
test-with-server depended on start-server as a prerequisite, so a failed
startup skipped the recipe and the spawned weed mini kept the port.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 10:05:54 -07:00
Chris LuandDevin 2291d18b84 test: fail a case when its side-effect check reports a regression
A non-empty check note now fails the case, so a deleted bucket or an
object created by a malformed request cannot slip through behind a
passing status check.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 05:54:42 -07:00
Chris LuandDevin a7bf27b976 test: tolerate unset fixture variables in cleanup and cover DELETE ?logging
Cleanup now runs its IAM/multipart steps only when setup reached them, so
an early setup failure still removes the bucket. Added a DELETE
bucket-subresource case asserting NotImplemented and bucket survival.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 05:19:58 -07:00
Chris LuandDevin ab38d6b8f6 s3api: reject unrouted subresources on the DELETE bucket catch-all
PutBucketHandler gained the same guard when the route-level check moved
into the handlers; DeleteBucketHandler was missed, so an authorized
DELETE /bucket?logging could delete the bucket instead of answering
NotImplemented.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 05:19:50 -07:00
Chris LuandDevin 4469774c03 test: register atexit cleanup before setup
A failed setup previously skipped cleanup, leaking the bucket and IAM
user on persistent servers.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 05:10:11 -07:00
Chris LuandDevin d270cbc348 test: stop spawned mini when readiness times out
A slow-starting server otherwise survives the failure path and keeps
the S3 port occupied for the next run.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 05:10:11 -07:00
Chris LuandDevin f9a70da28b s3: return InvalidArgument for malformed x-amz-content-sha256
A header value that decodes to neither 32-byte hex nor base64 is a
malformed argument, not a hash mismatch.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-07 05:10:11 -07:00
Chris Lu 5d67acf5db test/s3: add S3/IAM error-response compatibility harness 2026-10-06 09:25:32 -07:00
Chris LuandDevin 85c706e015 iam: refuse DeleteUser while access keys remain
Deleting a user with live credentials orphaned its access keys; AWS
answers DeleteConflict until they are removed first.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:25:32 -07:00
Chris LuandDevin 3dcc74e93d iam: correct LimitExceeded, InvalidAction and ServiceFailure mappings
LimitExceeded is a conflict (409), an unknown Action is InvalidAction
(404) rather than NotImplemented, and internal failures report the IAM
receiver fault type. Applies to both the embedded IAM endpoint and the
standalone iamapi server.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:25:32 -07:00
Chris LuandDevin d742b5c9ce s3api: InvalidArgument for non-numeric or out-of-range part numbers
partNumber=abc, 0 and >10000 all resolve to InvalidArgument, matching
AWS, instead of InvalidPart.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:37 -07:00
Chris LuandDevin 3c75930d94 s3api: answer DeleteObjects over 1000 keys with MalformedXML
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:37 -07:00
Chris LuandDevin b773170bd3 s3api: reject versionId requests on buckets that never had versioning
GET, HEAD and DELETE carrying a non-empty versionId on an unversioned
bucket now fail with InvalidArgument instead of being answered as a
plain object request.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:37 -07:00
Chris LuandDevin 1afa3da1ac s3api: answer throttling rejections as SlowDown
ErrTooManyRequest and ErrRequestBytesExceed reported made-up codes;
AWS serves these throttling rejections as SlowDown.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:37 -07:00
Chris LuandDevin e23a30ed64 s3api: return 403 AccessDenied when the request has no Date
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:37 -07:00
Chris LuandDevin c05a296ba1 s3api: answer IAM/STS failures in the query-protocol envelope
Embedded IAM and STS routes now report authentication, form-parse and
authorization failures with the IAM ErrorResponse body instead of the
S3 Error envelope, so IAM SDK clients can parse them. Requests signed
for s3 keep the S3 envelope, keyed off the credential scope.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:37 -07:00
Chris LuandDevin e068bd2167 s3api: map truncated SigV4 headers to the error for the missing field
AWS answers an Authorization header missing Credential= with
InvalidArgument and one missing or malformed Signature= with
AuthorizationHeaderMalformed, instead of a generic MissingFields.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:29 -07:00
Chris LuandDevin eb744e71bd s3api: verify x-amz-content-sha256 against the streamed body
A PUT carrying a hex or base64 payload hash now streams through a
verifier that reports a mismatch once the stream is exhausted, instead
of storing an object that does not match its declared hash. The error
is deferred so intermediate reads that drop (n>0, err) results cannot
silently swallow it. Sentinel values (unsigned/streaming payloads)
remain exempt and malformed values fail fast.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:29 -07:00
Chris LuandDevin 06fde6e2f6 s3api: reject malformed copy-source and multipart PUT parameters
A malformed X-Amz-Copy-Source or a non-numeric partNumber fell through
to the plain PutObject route and stored the body as a regular object.
Answer them with InvalidArgument-class errors instead of writing data.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:16:29 -07:00
Chris LuandDevin 564fdf26e1 s3api: answer unrecognized bucket PUT sub-resources with 501
A PUT on a bucket carrying an unrecognized query (logging, metrics,
intelligent-tiering, ...) fell through to the bare CreateBucket route
and returned BucketAlreadyOwnedByYou or re-created the bucket. AWS
answers these with NotImplemented.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 09:04:10 -07:00
Chris LuandDevin 051011758f s3err: add InvalidArgument and AuthorizationHeaderMalformed codes
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-06 08:51:17 -07:00
100 changed files with 1516 additions and 6091 deletions

No files matched your search

-2
View File
@@ -10,5 +10,3 @@ updates:
directory: "/"
schedule:
interval: weekly
ignore:
- dependency-name: "github.com/seaweedfs/goexif"
-17
View File
@@ -133,23 +133,6 @@ jobs:
grep -A 12 "^kind: Ingress" /tmp/s3-ingress-labels.yaml | grep -q "^ external-dns: s3"
echo "S3 ingress renders custom labels"
echo "=== Testing HTTPRoute ==="
helm template test $CHART_DIR --show-only templates/s3/s3-httproute.yaml \
--set s3.enabled=true,s3.httpRoute.enabled=true \
--set 's3.httpRoute.parentRefs[0].name=gateway' > /tmp/s3-httproute.yaml
grep -q "^kind: HTTPRoute" /tmp/s3-httproute.yaml
grep -A 4 -- '- group: ""' /tmp/s3-httproute.yaml | grep -q "name: test-seaweedfs-s3$"
grep -A 4 -- '- group: ""' /tmp/s3-httproute.yaml | grep -q "port: 8333$"
echo "S3 HTTPRoute routes to the s3 service by default"
helm template test $CHART_DIR --show-only templates/s3/s3-httproute.yaml \
--set filer.s3.enabled=true,filer.s3.port=8334,s3.httpRoute.enabled=true > /tmp/filer-s3-httproute.yaml
grep -A 4 -- '- group: ""' /tmp/filer-s3-httproute.yaml | grep -q "port: 8334$"
echo "S3 on filer HTTPRoute uses filer.s3.port"
helm template test $CHART_DIR --show-only templates/master/master-httproute.yaml \
--set allInOne.enabled=true,master.enabled=false,master.httpRoute.enabled=true > /tmp/allinone-master-httproute.yaml
grep -A 4 -- '- group: ""' /tmp/allinone-master-httproute.yaml | grep -q "name: test-seaweedfs-all-in-one$"
echo "All-in-one master HTTPRoute routes to the all-in-one service"
echo "=== Testing with all-in-one mode ==="
helm template test $CHART_DIR --set allInOne.enabled=true > /tmp/allinone.yaml
grep -q "seaweedfs-all-in-one" /tmp/allinone.yaml
-8
View File
@@ -289,10 +289,6 @@ jobs:
s3tests/functional/test_s3.py::test_object_write_check_etag \
s3tests/functional/test_s3.py::test_object_write_cache_control \
s3tests/functional/test_s3.py::test_object_write_expires \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_s3 \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_kms \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_s3_kms \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_bad_enc_kms \
s3tests/functional/test_s3.py::test_object_content_encoding_aws_chunked \
s3tests/functional/test_s3.py::test_object_write_read_update_read_delete \
s3tests/functional/test_s3.py::test_object_metadata_replaced_on_put \
@@ -1155,10 +1151,6 @@ jobs:
s3tests/functional/test_s3.py::test_object_write_check_etag \
s3tests/functional/test_s3.py::test_object_write_cache_control \
s3tests/functional/test_s3.py::test_object_write_expires \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_s3 \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_kms \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_s3_kms \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_bad_enc_kms \
s3tests/functional/test_s3.py::test_object_content_encoding_aws_chunked \
s3tests/functional/test_s3.py::test_object_write_read_update_read_delete \
s3tests/functional/test_s3.py::test_object_metadata_replaced_on_put \
+2 -1
View File
@@ -64,7 +64,7 @@ require (
github.com/prometheus/procfs v0.22.0
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/seaweedfs/goexif v1.0.3
github.com/seaweedfs/goexif v2.0.0+incompatible
github.com/seaweedfs/raft v1.2.1
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/spf13/afero v1.15.0 // indirect
@@ -258,6 +258,7 @@ require (
github.com/rclone/Proton-API-Bridge v1.0.5 // indirect
github.com/rclone/go-proton-api v1.0.4 // indirect
github.com/rogpeppe/go-internal v1.15.0 // indirect
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd // indirect
github.com/ryanuber/go-glob v1.0.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/smarty/assertions v1.15.0 // indirect
+4 -2
View File
@@ -1746,6 +1746,8 @@ github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w=
github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZKsJ8yyVxGRWYNEm9oFB8ieLgKFnamEyDmSA0BRk=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk=
github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc=
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI=
@@ -1764,8 +1766,8 @@ github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564 h1:Tg
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
github.com/seaweedfs/go-fuse/v2 v2.9.4 h1:ACyloiuopdhRSjdLLeSWbsVaemMPskORaRF01TY6GyM=
github.com/seaweedfs/go-fuse/v2 v2.9.4/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/seaweedfs/goexif v2.0.0+incompatible h1:x8pckiT12QQhifwhDQpeISgDfsqmQ6VR4LFPQ64JRps=
github.com/seaweedfs/goexif v2.0.0+incompatible/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/seaweedfs/raft v1.2.1 h1:QgFl/aaPnagpUxYB6Bx+fFss1NyetVVcJmraMmnaQ5Q=
github.com/seaweedfs/raft v1.2.1/go.mod h1:fgs/rAVEzjQ7e04XMzG3eJhwZZRmBW+2uRtjakeCGeU=
github.com/secure-systems-lab/go-securesystemslib v0.11.0 h1:iuCR9kcMFD4QurdKrGvPLoKZLv9YvwPYVr0473BdtFs=
-20
View File
@@ -542,26 +542,6 @@ helm install seaweedfs-worker-vacuum seaweedfs/seaweedfs -f values-worker-vacuum
helm install seaweedfs-worker-balance seaweedfs/seaweedfs -f values-worker-balance.yaml
```
## Gateway API
Every component with an `ingress` block (master, volume, filer, s3 and admin) can also be exposed through a [Gateway API](https://gateway-api.sigs.k8s.io/) `HTTPRoute`, for clusters that route through a Gateway instead of an Ingress controller. `<component>.httpRoute` sits next to `<component>.ingress` and is disabled by default. The chart does not create the Gateway, so point `parentRefs` at one that already exists, and the `gateway.networking.k8s.io/v1` CRDs must be installed.
```yaml
s3:
httpRoute:
enabled: true
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: my-gateway
namespace: gateway-system
sectionName: https
hostnames:
- s3.example.com
```
With `rules` left empty the route sends all traffic to the component's own Service and port. A rule may set `matches`, `filters`, `timeouts` and `backendRefs`, and a rule without `backendRefs` still routes to that Service. In all-in-one mode the master, volume, filer and s3 routes target the all-in-one Service. When S3 runs only on the filer (`filer.s3.enabled` without `s3.enabled`), the s3 route uses `filer.s3.port`.
## Network Policies
In a namespace with a default-deny policy the install hangs: the components cannot resolve each other, and the post-install bucket hook waits on the master and filer until it gives up. `networkPolicy.enabled` renders one `NetworkPolicy` per component, selecting its pods by the standard `app.kubernetes.io/{name,instance,component}` labels and admitting traffic from the other pods of the release on the ports that component listens on.
@@ -1,55 +0,0 @@
{{- if and .Values.admin.enabled .Values.admin.httpRoute.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ include "seaweedfs.componentName" (list . "admin") }}
namespace: {{ .Release.Namespace }}
{{- with .Values.admin.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: admin
{{- with .Values.admin.httpRoute.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.admin.httpRoute.parentRefs }}
parentRefs:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.admin.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.admin.httpRoute.rules | default (list dict) }}
- backendRefs:
{{- with .backendRefs }}
{{- toYaml . | nindent 8 }}
{{- else }}
- group: ""
kind: Service
name: {{ include "seaweedfs.componentName" (list $ "admin") }}
namespace: {{ $.Release.Namespace }}
port: {{ $.Values.admin.port }}
weight: 1
{{- end }}
{{- with .matches }}
matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .timeouts }}
timeouts:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
@@ -1,57 +0,0 @@
{{- $filerEnabled := or .Values.filer.enabled .Values.allInOne.enabled }}
{{- if and $filerEnabled .Values.filer.httpRoute.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ include "seaweedfs.componentName" (list . "filer") }}
namespace: {{ .Release.Namespace }}
{{- with .Values.filer.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: filer
{{- with .Values.filer.httpRoute.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.filer.httpRoute.parentRefs }}
parentRefs:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.filer.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.filer.httpRoute.rules | default (list dict) }}
- backendRefs:
{{- with .backendRefs }}
{{- toYaml . | nindent 8 }}
{{- else }}
- group: ""
kind: Service
name: {{ $serviceName }}
namespace: {{ $.Release.Namespace }}
port: {{ $.Values.filer.port }}
weight: 1
{{- end }}
{{- with .matches }}
matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .timeouts }}
timeouts:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
@@ -1,57 +0,0 @@
{{- $masterEnabled := or .Values.master.enabled .Values.allInOne.enabled }}
{{- if and $masterEnabled .Values.master.httpRoute.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "master")) .Values.allInOne.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ include "seaweedfs.componentName" (list . "master") }}
namespace: {{ .Release.Namespace }}
{{- with .Values.master.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: master
{{- with .Values.master.httpRoute.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.master.httpRoute.parentRefs }}
parentRefs:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.master.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.master.httpRoute.rules | default (list dict) }}
- backendRefs:
{{- with .backendRefs }}
{{- toYaml . | nindent 8 }}
{{- else }}
- group: ""
kind: Service
name: {{ $serviceName }}
namespace: {{ $.Release.Namespace }}
port: {{ $.Values.master.port }}
weight: 1
{{- end }}
{{- with .matches }}
matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .timeouts }}
timeouts:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
@@ -1,64 +0,0 @@
{{- $s3Enabled := or .Values.s3.enabled (and .Values.filer.s3.enabled (not .Values.allInOne.enabled)) (and .Values.allInOne.enabled .Values.allInOne.s3.enabled) }}
{{- if and $s3Enabled .Values.s3.httpRoute.enabled }}
{{- $serviceName := include "seaweedfs.componentName" (list . "s3") }}
{{- $s3Port := .Values.filer.s3.port }}
{{- if and .Values.allInOne.enabled .Values.allInOne.s3.enabled }}
{{- $serviceName = include "seaweedfs.componentName" (list . "all-in-one") }}
{{- $s3Port = .Values.allInOne.s3.port | default .Values.s3.port }}
{{- else if .Values.s3.enabled }}
{{- $s3Port = .Values.s3.port }}
{{- end }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ include "seaweedfs.componentName" (list . "s3") }}
namespace: {{ .Release.Namespace }}
{{- with .Values.s3.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: s3
{{- with .Values.s3.httpRoute.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.s3.httpRoute.parentRefs }}
parentRefs:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.s3.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.s3.httpRoute.rules | default (list dict) }}
- backendRefs:
{{- with .backendRefs }}
{{- toYaml . | nindent 8 }}
{{- else }}
- group: ""
kind: Service
name: {{ $serviceName }}
namespace: {{ $.Release.Namespace }}
port: {{ $s3Port }}
weight: 1
{{- end }}
{{- with .matches }}
matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .timeouts }}
timeouts:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
@@ -1,57 +0,0 @@
{{- $volumeEnabled := or .Values.volume.enabled .Values.allInOne.enabled }}
{{- if and $volumeEnabled .Values.volume.httpRoute.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "volume")) .Values.allInOne.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ include "seaweedfs.componentName" (list . "volume") }}
namespace: {{ .Release.Namespace }}
{{- with .Values.volume.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: volume
{{- with .Values.volume.httpRoute.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.volume.httpRoute.parentRefs }}
parentRefs:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.volume.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.volume.httpRoute.rules | default (list dict) }}
- backendRefs:
{{- with .backendRefs }}
{{- toYaml . | nindent 8 }}
{{- else }}
- group: ""
kind: Service
name: {{ $serviceName }}
namespace: {{ $.Release.Namespace }}
port: {{ $.Values.volume.port }}
weight: 1
{{- end }}
{{- with .matches }}
matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .timeouts }}
timeouts:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
-90
View File
@@ -311,24 +311,6 @@ master:
# sub_filter_once off;
tls: []
# Gateway API HTTPRoute, an alternative to the ingress above.
httpRoute:
enabled: false
labels: {}
annotations: {}
# Gateways this route attaches to, for example:
# - group: gateway.networking.k8s.io
# kind: Gateway
# name: my-gateway
# namespace: gateway-system
# sectionName: https
parentRefs: []
hostnames: []
# Each rule may set matches, filters, timeouts and backendRefs.
# A rule without backendRefs routes to the master service.
# An empty list routes all traffic there.
rules: []
extraEnvironmentVars:
WEED_MASTER_VOLUME_GROWTH_COPY_1: "7"
WEED_MASTER_VOLUME_GROWTH_COPY_2: "6"
@@ -665,24 +647,6 @@ volume:
# sub_filter '/seaweedfsstatic' './seaweedfsstatic';
# sub_filter_once off;
# Gateway API HTTPRoute, an alternative to the ingress above.
httpRoute:
enabled: false
labels: {}
annotations: {}
# Gateways this route attaches to, for example:
# - group: gateway.networking.k8s.io
# kind: Gateway
# name: my-gateway
# namespace: gateway-system
# sectionName: https
parentRefs: []
hostnames: []
# Each rule may set matches, filters, timeouts and backendRefs.
# A rule without backendRefs routes to the volume server service.
# An empty list routes all traffic there.
rules: []
# Map of named volume groups for topology-aware deployments.
# Each key inherits all fields from the `volume` section but can override
# them locally—for example, replicas, nodeSelector, dataCenter, etc.
@@ -975,24 +939,6 @@ filer:
# requires ingress-nginx to run with --enable-ssl-passthrough.
tls: []
# Gateway API HTTPRoute, an alternative to the ingress above.
httpRoute:
enabled: false
labels: {}
annotations: {}
# Gateways this route attaches to, for example:
# - group: gateway.networking.k8s.io
# kind: Gateway
# name: my-gateway
# namespace: gateway-system
# sectionName: https
parentRefs: []
hostnames: []
# Each rule may set matches, filters, timeouts and backendRefs.
# A rule without backendRefs routes to the filer service.
# An empty list routes all traffic there.
rules: []
# extraEnvVars is a list of extra environment variables to set with the stateful set.
extraEnvironmentVars:
# the WEED_MYSQL_* keys and the db credential secret only render while this is "true"
@@ -1318,24 +1264,6 @@ s3:
annotations: {}
tls: []
# Gateway API HTTPRoute, an alternative to the ingress above.
httpRoute:
enabled: false
labels: {}
annotations: {}
# Gateways this route attaches to, for example:
# - group: gateway.networking.k8s.io
# kind: Gateway
# name: my-gateway
# namespace: gateway-system
# sectionName: https
parentRefs: []
hostnames: []
# Each rule may set matches, filters, timeouts and backendRefs.
# A rule without backendRefs routes to the s3 service.
# An empty list routes all traffic there.
rules: []
# Service settings
service:
type: ClusterIP
@@ -1673,24 +1601,6 @@ admin:
annotations: {}
tls: []
# Gateway API HTTPRoute, an alternative to the ingress above.
httpRoute:
enabled: false
labels: {}
annotations: {}
# Gateways this route attaches to, for example:
# - group: gateway.networking.k8s.io
# kind: Gateway
# name: my-gateway
# namespace: gateway-system
# sectionName: https
parentRefs: []
hostnames: []
# Each rule may set matches, filters, timeouts and backendRefs.
# A rule without backendRefs routes to the admin service.
# An empty list routes all traffic there.
rules: []
service:
type: ClusterIP
annotations: {}
+1059 -1061
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

+2 -2
View File
@@ -148,9 +148,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.45"
version = "0.23.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06"
dependencies = [
"aws-lc-rs",
"log",
+20 -225
View File
@@ -1182,10 +1182,6 @@ pub struct Volume {
last_modified_ts_seconds: u64,
last_append_at_ns: u64,
last_write_append_at_ns: u64, // AppendAtNs of the newest write; tombstones don't move it
last_write_needle_key: NeedleId, // the write behind the watermark
last_write_deleted: bool, // that write was deleted, so recovery has to rescan
keep_last_modified_ts_on_load: bool,
pub last_disk_check_ns: Arc<std::sync::atomic::AtomicI64>, // for phantom volume detection cache
last_compact_index_offset: u64,
@@ -1285,10 +1281,6 @@ impl Volume {
location_disk_space_low: Arc::new(AtomicBool::new(false)),
last_modified_ts_seconds: 0,
last_append_at_ns: 0,
last_write_append_at_ns: 0,
last_write_needle_key: NeedleId(0),
last_write_deleted: false,
keep_last_modified_ts_on_load: false,
last_disk_check_ns: Arc::new(std::sync::atomic::AtomicI64::new(0)),
last_compact_index_offset: 0,
last_compact_revision: 0,
@@ -1335,10 +1327,6 @@ impl Volume {
location_disk_space_low: Arc::new(AtomicBool::new(false)),
last_modified_ts_seconds: 0,
last_append_at_ns: 0,
last_write_append_at_ns: 0,
last_write_needle_key: NeedleId(0),
last_write_deleted: false,
keep_last_modified_ts_on_load: false,
last_disk_check_ns: Arc::new(std::sync::atomic::AtomicI64::new(0)),
last_compact_index_offset: 0,
last_compact_revision: 0,
@@ -1454,14 +1442,12 @@ impl Volume {
Err(e) => return Err(e.into()),
}
if !self.keep_last_modified_ts_on_load {
self.last_modified_ts_seconds = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
}
self.last_modified_ts_seconds = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if metadata.len() >= SUPER_BLOCK_SIZE as u64 {
already_has_super_block = true;
@@ -1563,9 +1549,7 @@ impl Volume {
"volumeDataIntegrityChecking failed"
);
}
if !self.keep_last_modified_ts_on_load {
self.recover_last_modified_ts();
}
self.recover_last_modified_ts();
// Structural check: no .idx entry may reference bytes past the
// end of .dat. The needle map's load walk above already
@@ -2355,13 +2339,6 @@ impl Volume {
.collect();
}
self.last_append_at_ns = last_append_at_ns;
for ((n, _), r) in run.iter().zip(&staged) {
if matches!(r, Ok(Some(_))) && n.append_at_ns > self.last_write_append_at_ns {
self.last_write_append_at_ns = n.append_at_ns;
self.last_write_needle_key = n.id;
self.last_write_deleted = false;
}
}
// A durable entry that fails to publish stops the volume taking
// writes, so the entries after it are refused the way a lone
@@ -2544,9 +2521,6 @@ impl Volume {
}
self.last_append_at_ns = n.append_at_ns;
self.last_write_append_at_ns = n.append_at_ns;
self.last_write_needle_key = n.id;
self.last_write_deleted = false;
self.publish_write(n, offset, fsync)?;
@@ -2865,11 +2839,6 @@ impl Volume {
if let Some(nm) = &mut self.nm {
nm.delete(n.id, Offset::from_actual_offset(offset as i64))?;
}
if n.id == self.last_write_needle_key {
self.last_write_append_at_ns = 0;
self.last_write_needle_key = NeedleId(0);
self.last_write_deleted = true;
}
let checkpoint_ok = self.maybe_checkpoint_index(false);
// Clear the EIO streak after a successful delete (tombstone append +
@@ -3137,15 +3106,8 @@ impl Volume {
return;
}
match self.find_last_write_append_at_ns() {
Ok((0, _)) => {}
Ok((append_at_ns, key)) => {
self.last_modified_ts_seconds = append_at_ns / 1_000_000_000;
if append_at_ns > self.last_write_append_at_ns {
self.last_write_append_at_ns = append_at_ns;
self.last_write_needle_key = key;
self.last_write_deleted = false;
}
}
Ok(0) => {}
Ok(append_at_ns) => self.last_modified_ts_seconds = append_at_ns / 1_000_000_000,
Err(e) => warn!(
volume_id = self.id.0,
error = %e,
@@ -3155,8 +3117,7 @@ impl Volume {
}
/// Scan the .idx backwards for the newest write — an entry that is not a
/// deletion tombstone — and return that needle's append timestamp and key.
/// The .idx
/// deletion tombstone — and return that needle's append timestamp. The .idx
/// and the .dat share an order, so an append-ordered volume answers with the
/// first write the scan reaches. Vacuum rewrites both in key order, which
/// tracks write order only because the master issues keys increasing: an
@@ -3165,21 +3126,19 @@ impl Volume {
/// nothing but tombstones, when a vacuumed volume holds more needles than
/// the scan budget, or for a volume older than version 3, whose needles
/// carry no append timestamp. Mirrors Go's findLastWriteAppendAtNs.
fn find_last_write_append_at_ns(&self) -> Result<(u64, NeedleId), VolumeError> {
fn find_last_write_append_at_ns(&self) -> Result<u64, VolumeError> {
let version = self.version();
if version != VERSION_3 {
return Ok((0, NeedleId(0)));
return Ok(0);
}
let idx_path = self.file_name(".idx");
let idx_size = fs::metadata(&idx_path).map(|m| m.len()).unwrap_or(0) as i64;
if idx_size == 0 || idx_size % NEEDLE_MAP_ENTRY_SIZE as i64 != 0 {
return Ok((0, NeedleId(0)));
return Ok(0);
}
let scan_every_write = self.super_block.compaction_revision > 0;
let mut entry_budget = Self::VACUUMED_LAST_WRITE_SCAN_ENTRIES;
let mut last_write_append_at_ns = 0u64;
let mut last_write_key = NeedleId(0);
let mut dead = HashSet::new();
let mut idx_file = File::open(&idx_path)?;
let mut block = vec![0u8; NEEDLE_MAP_ENTRY_SIZE * idx::ROWS_TO_READ];
let mut end = idx_size;
@@ -3190,13 +3149,7 @@ impl Volume {
idx_file.read_exact(entries)?;
for entry in entries.as_chunks::<NEEDLE_MAP_ENTRY_SIZE>().0.iter().rev() {
let (key, offset, size) = idx_entry_from_bytes(entry);
// The first row a key presents is its latest state: a tombstone
// there retires the write rows beneath it.
if dead.contains(&key) {
continue;
}
if offset.is_zero() || size.is_deleted() {
dead.insert(key);
continue;
}
let Some(needle_offset) =
@@ -3204,13 +3157,10 @@ impl Volume {
else {
continue;
};
let append_at_ns = self.read_needle_append_at_ns(needle_offset, size)?;
if append_at_ns > last_write_append_at_ns {
last_write_append_at_ns = append_at_ns;
last_write_key = key;
}
last_write_append_at_ns = last_write_append_at_ns
.max(self.read_needle_append_at_ns(needle_offset, size)?);
if !scan_every_write {
return Ok((last_write_append_at_ns, last_write_key));
return Ok(last_write_append_at_ns);
}
entry_budget -= 1;
if entry_budget == 0 {
@@ -3219,12 +3169,12 @@ impl Volume {
budget = Self::VACUUMED_LAST_WRITE_SCAN_ENTRIES,
"too many needles to scan for the last write, keeping the .dat mtime"
);
return Ok((0, NeedleId(0)));
return Ok(0);
}
}
end = start;
}
Ok((last_write_append_at_ns, last_write_key))
Ok(last_write_append_at_ns)
}
/// The .dat offset holding the needle an .idx entry describes, or None when
@@ -4344,9 +4294,6 @@ impl Volume {
// Update lastAppendAtNs (matches Go L352: v.lastAppendAtNs = appendAtNs)
self.last_append_at_ns = append_at_ns;
self.last_write_append_at_ns = append_at_ns;
self.last_write_needle_key = needle_id;
self.last_write_deleted = false;
// Update needle map index
let offset = Offset::from_actual_offset(dat_size);
@@ -4546,18 +4493,8 @@ impl Volume {
self.write_compact_commit_marker()?;
self.apply_compact_swap()?;
// The write watermark already equals what recover_last_modified_ts
// would rescan, so keep the clock instead of paying for the scan
// under the lock. If its write was itself deleted, the reload
// recovers the newest surviving write instead.
if self.last_write_append_at_ns != 0 {
self.last_modified_ts_seconds = self.last_write_append_at_ns / 1_000_000_000;
}
self.keep_last_modified_ts_on_load =
self.last_modified_ts_seconds != 0 && !self.last_write_deleted;
let load_result = self.load(true, false, 0, self.version());
self.keep_last_modified_ts_on_load = false;
load_result?;
// Reload
self.load(true, false, 0, self.version())?;
Ok(())
}
@@ -6444,7 +6381,6 @@ mod tests {
let prior = v.nm.as_ref().unwrap().get(NeedleId(1)).unwrap().unwrap();
let dat_len_before = dat_len(&v);
let last_append_before = v.last_append_at_ns;
let last_write_append_before = v.last_write_append_at_ns;
let last_modified_before = v.last_modified_ts_seconds;
let file_count_before = v.file_count();
@@ -6466,7 +6402,6 @@ mod tests {
);
assert_eq!(dat_len(&v), dat_len_before, "the run is off the .dat");
assert_eq!(v.last_append_at_ns, last_append_before);
assert_eq!(v.last_write_append_at_ns, last_write_append_before);
assert_eq!(v.last_modified_ts_seconds, last_modified_before);
let now = v.nm.as_ref().unwrap().get(NeedleId(1)).unwrap().unwrap();
assert_eq!((now.offset, now.size), (prior.offset, prior.size));
@@ -7102,146 +7037,6 @@ mod tests {
);
}
// Covers the reload that ends a vacuum commit: the clock must keep the
// last write's append time rather than be re-derived, and the intervening
// delete's tombstone must not freshen it.
#[test]
fn test_ttl_clock_carried_across_vacuum_commit() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let ttl = crate::storage::needle::ttl::TTL::read("5m").unwrap();
let last_write_ns = (SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
- 2 * 60 * 60)
* 1_000_000_000;
let mut v = make_ttl_volume(dir, ttl);
let mut written = Vec::new();
for i in 1..=3u64 {
let data = format!("data {}", i);
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: data.as_bytes().to_vec(),
data_size: data.len() as u32,
..Needle::default()
};
let (offset, _, _) = v.write_needle(&mut n, true, false).unwrap();
written.push((offset, n.size));
}
v.delete_needle(&mut Needle {
id: NeedleId(2),
cookie: Cookie(2),
..Needle::default()
})
.unwrap();
v.sync_to_disk().unwrap();
for (offset, size) in written {
backdate_append_at_ns(&v.dat_path(), offset, size, last_write_ns);
}
// Where a restart's recovery would have left the clock. The delete
// above pushed last_append_at_ns to ~now; the commit must not use it.
v.set_last_modified_ts_for_test(last_write_ns / 1_000_000_000);
v.last_write_append_at_ns = last_write_ns;
v.compact_by_index(0, 0, |_| true).unwrap();
v.commit_compact().unwrap();
assert_eq!(v.last_modified_ts(), last_write_ns / 1_000_000_000);
assert!(
v.is_expired(v.content_size(), 1024 * 1024),
"a TTL volume whose last write is 2h old must stay expired across a vacuum commit"
);
}
// A write's client supplied modified time can lie ahead of or behind when
// it was appended; the commit keeps the server-side write watermark the
// recovery scan would recompute.
#[test]
fn test_ttl_clock_at_commit_uses_append_time() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let ttl = crate::storage::needle::ttl::TTL::read("5m").unwrap();
let future = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
+ 24 * 60 * 60;
let mut v = make_ttl_volume(dir, ttl);
let data = b"data".to_vec();
let mut n = Needle {
id: NeedleId(1),
cookie: Cookie(1),
data,
data_size: 4,
last_modified: future,
..Needle::default()
};
v.write_needle(&mut n, true, false).unwrap();
assert!(v.last_modified_ts() >= future);
let append_watermark_sec = v.last_write_append_at_ns / 1_000_000_000;
v.compact_by_index(0, 0, |_| true).unwrap();
v.commit_compact().unwrap();
assert_eq!(v.last_modified_ts(), append_watermark_sec);
}
// A vacuum commit whose newest write was deleted first: the carried
// watermark belonged to that write, so the commit has to let the reload
// rescan and land on the newest surviving write rather than keep the
// volume alive on a deleted write's time.
#[test]
fn test_ttl_clock_at_commit_skips_deleted_write() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let ttl = crate::storage::needle::ttl::TTL::read("5m").unwrap();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let old_write_ns = (now - 2 * 60 * 60) * 1_000_000_000;
let new_write_ns = (now - 60 * 60) * 1_000_000_000;
let mut v = make_ttl_volume(dir, ttl);
for (id, append_at_ns) in [(1u64, old_write_ns), (2, new_write_ns)] {
let data = format!("data {}", id);
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(id as u32),
data: data.as_bytes().to_vec(),
data_size: data.len() as u32,
..Needle::default()
};
let (offset, _, _) = v.write_needle(&mut n, true, false).unwrap();
v.sync_to_disk().unwrap();
backdate_append_at_ns(&v.dat_path(), offset, n.size, append_at_ns);
}
// The delete lands inside the commit window: makeup_diff replays its
// tombstone into the new .idx behind the write row the copy carried.
v.compact_by_index(0, 0, |_| true).unwrap();
v.delete_needle(&mut Needle {
id: NeedleId(2),
cookie: Cookie(2),
..Needle::default()
})
.unwrap();
assert!(
v.last_write_deleted,
"deleting the newest write must mark the watermark dead"
);
v.commit_compact().unwrap();
assert_eq!(v.last_modified_ts(), old_write_ns / 1_000_000_000);
assert!(
!v.last_write_deleted,
"the reload's rescan must reseed the watermark off the surviving write"
);
}
// Guard the destroy time an EC volume is reclaimed on: it was recomputed as
// now+TTL every time the .vif was written, so a read-only mark, a tier
// upload or an EC encode handed an already expiring volume another full TTL.
+10 -7
View File
@@ -7,20 +7,20 @@ require (
github.com/linkedin/goavro/v2 v2.15.0
github.com/seaweedfs/seaweedfs v0.0.0-00010101000000-000000000000
github.com/segmentio/kafka-go v0.4.49
github.com/stretchr/testify v1.12.1
github.com/stretchr/testify v1.11.1
google.golang.org/grpc v1.85.0-dev.0.20260915183914-4e49413dcab7
)
replace github.com/seaweedfs/seaweedfs => ../../
require (
github.com/andybalholm/brotli v1.2.3 // indirect
github.com/andybalholm/brotli v1.2.2 // indirect
github.com/aws/aws-sdk-go v1.55.8 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cognusion/imaging v1.0.4 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/eapache/go-resiliency v1.7.0 // indirect
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
github.com/eapache/queue v1.1.0 // indirect
@@ -61,15 +61,17 @@ require (
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
github.com/pierrec/lz4/v4 v4.1.29 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // 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.24.1 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.71.0 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.22.0 // indirect
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
github.com/rdleal/intervalst v1.5.0 // indirect
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/seaweedfs/goexif v1.0.3 // indirect
github.com/seaweedfs/goexif v2.0.0+incompatible // indirect
github.com/shirou/gopsutil/v4 v4.26.7 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
@@ -89,8 +91,8 @@ require (
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.57.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.56.0 // indirect
golang.org/x/image v0.46.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sync v0.23.0 // indirect
@@ -99,4 +101,5 @@ require (
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect
google.golang.org/grpc/security/advancedtls v1.0.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+20 -16
View File
@@ -10,8 +10,8 @@ github.com/alecthomas/assert/v2 v2.10.0 h1:jjRCHsj6hBJhkmhznrCzoNpbA3zqy0fYiUcYZ
github.com/alecthomas/assert/v2 v2.10.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/andybalholm/brotli v1.2.3 h1:8H1qwOkl2LPfjf3YezB90JnCliZb6SInJ/OJkEbA5NQ=
github.com/andybalholm/brotli v1.2.3/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/brotli v1.2.2 h1:HzTuoo2ErYQqf5qvcJInB8uvqSVxRttzkFexPWtnceM=
github.com/andybalholm/brotli v1.2.2/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
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/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
@@ -28,8 +28,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/eapache/go-resiliency v1.7.0 h1:n3NRTnBn5N0Cbi/IeOHuQn9s2UwVUH7Ga0ZWcP+9JTA=
github.com/eapache/go-resiliency v1.7.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho=
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws=
@@ -174,8 +174,8 @@ github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59u
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.71.0 h1:9KDAKb7Mj3HEVKyFCK6Dc/HIwlBzZIN2l7/lrHl3KK8=
github.com/prometheus/common v0.71.0/go.mod h1:CLJ5H8TEsGX8bl31BdMkfhIZ+QmZ9tBPPotUxUbfcmk=
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics=
github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
@@ -184,10 +184,12 @@ github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6ha
github.com/rdleal/intervalst v1.5.0/go.mod h1:xO89Z6BC+LQDH+IPQQw/OESt5UADgFD41tYMUINGpxQ=
github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=
github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/seaweedfs/goexif v2.0.0+incompatible h1:x8pckiT12QQhifwhDQpeISgDfsqmQ6VR4LFPQ64JRps=
github.com/seaweedfs/goexif v2.0.0+incompatible/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/segmentio/kafka-go v0.4.49 h1:GJiNX1d/g+kG6ljyJEoi9++PUMdXGAxb7JGPiDCuNmk=
github.com/segmentio/kafka-go v0.4.49/go.mod h1:Y1gn60kzLEEaW28YshXyk2+VCUKbJ3Qr6DrnT3i4+9E=
github.com/shirou/gopsutil/v4 v4.26.7 h1:IXzpHz/dkMRYAhKkOXr1HB6SuzWU3eoyyeWe7g3bNZc=
@@ -214,8 +216,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
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=
@@ -261,15 +263,15 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
@@ -286,8 +288,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -349,6 +351,8 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
+3 -6
View File
@@ -76,12 +76,9 @@ start-server: check-deps
stop-server:
@if [ -f weed-server.pid ]; then \
pid=$$(cat weed-server.pid); \
if ps -p $$pid -o comm= 2>/dev/null | grep -q weed; then \
echo "Stopping SeaweedFS server..."; \
kill $$pid 2>/dev/null || true; \
sleep 2; \
fi; \
echo "Stopping SeaweedFS server..."; \
kill $$(cat weed-server.pid) 2>/dev/null || true; \
sleep 2; \
rm -f weed-server.pid; \
fi
-9
View File
@@ -98,10 +98,6 @@ func (cp *ConfigPersistence) ApplyMaintenanceConfigFromToml(v TomlConfig) error
ecConf.ReplicaPlacement = v.GetString(k)
ecChanged = true
}
if k := "maintenance.erasure_coding.strict_placement"; v.IsSet(k) {
ecConf.StrictPlacement = v.GetBool(k)
ecChanged = true
}
if !maintenanceChanged && !vacuumChanged && !balanceChanged && !ecChanged {
return nil
@@ -228,7 +224,6 @@ var pluginConfigSections = []pluginConfigSection{
"min_size_mb": int64Value,
"preferred_tags": stringListValue,
"replica_placement": stringValue,
"strict_placement": boolValue,
},
// workers read collection_filter from the admin values, not the worker values
adminKeys: map[string]func(v TomlConfig, key string) *plugin_pb.ConfigValue{
@@ -245,10 +240,6 @@ func int64Value(v TomlConfig, key string) *plugin_pb.ConfigValue {
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(v.GetInt(key))}}
}
func boolValue(v TomlConfig, key string) *plugin_pb.ConfigValue {
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: v.GetBool(key)}}
}
func stringValue(v TomlConfig, key string) *plugin_pb.ConfigValue {
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_StringValue{StringValue: v.GetString(key)}}
}
+3 -21
View File
@@ -174,24 +174,17 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
// per-cluster HTTPS clients for volume server connections
var httpClientA, httpClientB *util_http_client.HTTPClient
var jwtForFilerA, jwtForFilerB security.FilerJwtProvider
if *syncOptions.aSecurity != "" {
var err error
if httpClientA, err = security.LoadHTTPClientFromFile(*syncOptions.aSecurity); err != nil {
glog.Fatalf("load HTTPS client config for filer A: %v", err)
}
if jwtForFilerA, err = security.LoadFilerJwtFromFile(*syncOptions.aSecurity); err != nil {
glog.Fatalf("load filer JWT config for filer A: %v", err)
}
}
if *syncOptions.bSecurity != "" {
var err error
if httpClientB, err = security.LoadHTTPClientFromFile(*syncOptions.bSecurity); err != nil {
glog.Fatalf("load HTTPS client config for filer B: %v", err)
}
if jwtForFilerB, err = security.LoadFilerJwtFromFile(*syncOptions.bSecurity); err != nil {
glog.Fatalf("load filer JWT config for filer B: %v", err)
}
}
grace.SetupProfiling(*syncCpuProfile, *syncMemProfile)
@@ -270,9 +263,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
bFilerSignature,
&syncStateA2B,
httpClientA,
httpClientB,
jwtForFilerA,
jwtForFilerB)
httpClientB)
if err != nil {
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
time.Sleep(1747 * time.Millisecond)
@@ -315,9 +306,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
aFilerSignature,
&syncStateB2A,
httpClientB,
httpClientA,
jwtForFilerB,
jwtForFilerA)
httpClientA)
if err != nil {
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
time.Sleep(2147 * time.Millisecond)
@@ -347,8 +336,7 @@ func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAdd
func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceExcludePaths []string, sourceReadChunkFromFiler bool, targetGrpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, targetPath string,
replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, chunkConcurrency int, doDeleteFiles bool, sourceFilerSignature int32, targetFilerSignature int32, statePtr *atomic.Pointer[syncState],
sourceHttpClient *util_http_client.HTTPClient, sinkHttpClient *util_http_client.HTTPClient,
sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider) error {
sourceHttpClient *util_http_client.HTTPClient, sinkHttpClient *util_http_client.HTTPClient) error {
// if first time, start from now
// if has previously synced, resume from that point of time
@@ -369,18 +357,12 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
if sourceHttpClient != nil {
filerSource.SetHttpClient(sourceHttpClient)
}
if sourceJwtProvider != nil {
filerSource.SetFilerJwtProvider(sourceJwtProvider)
}
filerSink := &filersink.FilerSink{}
filerSink.DoInitialize(targetFiler.ToHttpAddress(), targetFiler.ToGrpcAddress(), targetPath, replicationStr, collection, ttlSec, diskType, targetGrpcDialOption, sinkWriteChunkByFiler)
filerSink.SetChunkConcurrency(chunkConcurrency)
if sinkHttpClient != nil {
filerSink.SetUploader(operation.NewUploaderWithHttpClient(sinkHttpClient))
}
if sinkJwtProvider != nil {
filerSink.SetFilerJwtProvider(sinkJwtProvider)
}
filerSink.SetSourceFiler(filerSource)
persistEventFn := genProcessFunction(sourcePath, targetPath, sourceExcludePaths, nil, nil, nil, filerSink, doDeleteFiles, debug)
-2
View File
@@ -64,8 +64,6 @@
# preferred_tags = ["fast", "ssd"]
# EC shard placement constraint, e.g. "020"; empty uses the master default replication
# replica_placement = ""
# fail planning when the placement constraints cannot be met instead of relaxing them
# strict_placement = false
# max retry attempts for a failed erasure coding job
# retry_limit = 1
# seconds to wait between retry attempts
-3
View File
@@ -883,9 +883,6 @@ func (ecb *ecBalancer) balance(collections []string) error {
// nodes fill proportionally (matching the worker). This is identical to raw
// shard count when capacities are uniform.
GlobalUtilizationBased: true,
RackTotalCapRaised: func(collection string, vid uint32, rackCap, evenCap int) {
fmt.Printf("ec volume %d (collection %q): rack-total-cap raised to %d shards per rack, above the even %d: the racks lack room for an even spread\n", vid, collection, rackCap, evenCap)
},
})
if len(ecb.volumeIds) > 0 {
var deletions int
+1 -1
View File
@@ -240,7 +240,7 @@ func (group *ChunkGroup) SetChunks(chunks []*filer_pb.FileChunk) error {
continue
}
resolvedChunks, err := resolveOneChunkManifest(context.Background(), group.lookupFn, chunk, group.cacheInvalidator, group.manifestCache, nil)
resolvedChunks, err := resolveOneChunkManifest(context.Background(), group.lookupFn, chunk, group.cacheInvalidator, group.manifestCache)
if err != nil {
group.resolveErr = err
return err
+9 -35
View File
@@ -16,7 +16,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
@@ -56,16 +55,7 @@ func SeparateManifestChunks(chunks []*filer_pb.FileChunk) (manifestChunks, nonMa
}
func ResolveChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, startOffset, stopOffset int64, invalidator CacheInvalidator) (dataChunks, manifestChunks []*filer_pb.FileChunk, manifestResolveErr error) {
resolver := newChunkManifestResolver(ctx, lookupFileIdFn, invalidator, nil)
defer resolver.close()
return resolver.resolve(chunks, startOffset, stopOffset)
}
// ResolveChunkManifestWithFilerJwt is ResolveChunkManifest that signs proxied
// manifest downloads with filerJwtFn instead of the process-wide filer read
// key, for readers carrying per-source credentials.
func ResolveChunkManifestWithFilerJwt(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, filerJwtFn security.FilerJwtProvider, chunks []*filer_pb.FileChunk, startOffset, stopOffset int64, invalidator CacheInvalidator) (dataChunks, manifestChunks []*filer_pb.FileChunk, manifestResolveErr error) {
resolver := newChunkManifestResolver(ctx, lookupFileIdFn, invalidator, filerJwtFn)
resolver := newChunkManifestResolver(ctx, lookupFileIdFn, invalidator)
defer resolver.close()
return resolver.resolve(chunks, startOffset, stopOffset)
}
@@ -91,7 +81,6 @@ type chunkManifestResolver struct {
cancel context.CancelFunc
lookupFileIdFn wdclient.LookupFileIdFunctionType
invalidator CacheInvalidator
filerJwtFn security.FilerJwtProvider
jobs chan chunkManifestResolveJob
overflowSem chan struct{}
workers sync.WaitGroup
@@ -99,7 +88,7 @@ type chunkManifestResolver struct {
started bool
}
func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator CacheInvalidator, filerJwtFn security.FilerJwtProvider) *chunkManifestResolver {
func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator CacheInvalidator) *chunkManifestResolver {
workCtx, cancel := context.WithCancel(ctx)
resolver := &chunkManifestResolver{
ctx: workCtx,
@@ -107,7 +96,6 @@ func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.Looku
cancel: cancel,
lookupFileIdFn: lookupFileIdFn,
invalidator: invalidator,
filerJwtFn: filerJwtFn,
jobs: make(chan chunkManifestResolveJob, chunkManifestResolveJobBufferSize),
overflowSem: make(chan struct{}, maxChunkManifestResolveWorkers),
}
@@ -115,7 +103,7 @@ func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.Looku
}
func (r *chunkManifestResolver) executeJob(job chunkManifestResolveJob) {
job.result.chunks, job.result.err = resolveOneChunkManifest(job.batchCtx, r.lookupFileIdFn, job.chunk, r.invalidator, nil, r.filerJwtFn)
job.result.chunks, job.result.err = ResolveOneChunkManifest(job.batchCtx, r.lookupFileIdFn, job.chunk, r.invalidator)
if job.result.err != nil && r.parentCtx.Err() == nil {
if job.batchCtx.Err() != nil && errors.Is(job.result.err, context.Canceled) {
job.result.internalCancel = true
@@ -305,23 +293,14 @@ func (r *chunkManifestResolver) resolve(chunks []*filer_pb.FileChunk, startOffse
// Keeping this signature stable preserves the existing four-argument contract
// for external callers.
func ResolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunk *filer_pb.FileChunk, invalidator CacheInvalidator) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
return resolveOneChunkManifest(ctx, lookupFileIdFn, chunk, invalidator, nil, nil)
}
// ResolveOneChunkManifestWithFilerJwt is ResolveOneChunkManifest that signs
// proxied manifest downloads with filerJwtFn instead of the process-wide
// filer read key, for readers carrying per-source credentials.
func ResolveOneChunkManifestWithFilerJwt(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, filerJwtFn security.FilerJwtProvider, chunk *filer_pb.FileChunk, invalidator CacheInvalidator) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
return resolveOneChunkManifest(ctx, lookupFileIdFn, chunk, invalidator, nil, filerJwtFn)
return resolveOneChunkManifest(ctx, lookupFileIdFn, chunk, invalidator, nil)
}
// resolveOneChunkManifest is the cache-aware implementation. cache may be nil,
// in which case the manifest is fetched and validated on every call, matching
// the historical uncached behavior. A non-nil cache is owned by a single mount
// (WFS) and coalesces concurrent cold misses via singleflight. filerJwtFn
// overrides the filer read credential for proxied downloads; nil means the
// process-wide key.
func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunk *filer_pb.FileChunk, invalidator CacheInvalidator, cache *ChunkManifestCache, filerJwtFn security.FilerJwtProvider) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
// (WFS) and coalesces concurrent cold misses via singleflight.
func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunk *filer_pb.FileChunk, invalidator CacheInvalidator, cache *ChunkManifestCache) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
if !chunk.IsChunkManifest {
return
}
@@ -339,7 +318,7 @@ func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.Lookup
bytesBuffer := bytesBufferPool.Get().(*bytes.Buffer)
bytesBuffer.Reset()
defer bytesBufferPool.Put(bytesBuffer)
if err := fetchWholeChunk(ctx, bytesBuffer, lookupFileIdFn, key.fileID, chunk.CipherKey, chunk.IsCompressed, invalidator, filerJwtFn); err != nil {
if err := fetchWholeChunk(ctx, bytesBuffer, lookupFileIdFn, key.fileID, chunk.CipherKey, chunk.IsCompressed, invalidator); err != nil {
return nil, fmt.Errorf("fail to read manifest %s: %w", key.fileID, err)
}
// Copy before the buffer returns to the pool so concurrent callers
@@ -378,18 +357,13 @@ func resolveOneChunkManifest(ctx context.Context, lookupFileIdFn wdclient.Lookup
return m.Chunks, nil
}
func fetchWholeChunk(ctx context.Context, bytesBuffer *bytes.Buffer, lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool, invalidator CacheInvalidator, filerJwtFn security.FilerJwtProvider) error {
func fetchWholeChunk(ctx context.Context, bytesBuffer *bytes.Buffer, lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool, invalidator CacheInvalidator) error {
urlStrings, err := lookupFileIdFn(ctx, fileId)
if err != nil {
glog.ErrorfCtx(ctx, "operation LookupFileId %s failed, err: %v", fileId, err)
return err
}
var jwt string
if filerJwtFn != nil && len(urlStrings) > 0 && util_http.IsProxyChunkUrl(urlStrings[0]) {
jwt = string(filerJwtFn(false))
} else {
jwt = ChunkReadJwt(urlStrings, fileId)
}
jwt := ChunkReadJwt(urlStrings, fileId)
if _, err = retriedStreamFetchChunkData(ctx, bytesBuffer, urlStrings, jwt, cipherKey, isGzipped, true, 0, 0, refreshUrls(ctx, invalidator, lookupFileIdFn, fileId)); err == nil {
return nil
}
@@ -23,7 +23,7 @@ func BenchmarkManifestResolutionRepeatedOpen(b *testing.B) {
}
chunk := newManifestCacheTestChunk("benchmark-cached")
cache := NewChunkManifestCache(MaxMountChunkManifestCacheEntries, MaxMountChunkManifestCacheBytes)
_, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache, nil)
_, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache)
if err != nil {
b.Fatal(err)
}
@@ -33,7 +33,7 @@ func BenchmarkManifestResolutionRepeatedOpen(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache, nil); err != nil {
if _, err := resolveOneChunkManifest(context.Background(), lookup, chunk, nil, cache); err != nil {
b.Fatal(err)
}
}
+3 -3
View File
@@ -258,7 +258,7 @@ func TestResolveOneChunkManifestHonorsCanceledContextOnCacheHit(t *testing.T) {
return nil, errors.New("lookup should not be called")
}
_, err := resolveOneChunkManifest(ctx, lookup, chunk, nil, cache, nil)
_, err := resolveOneChunkManifest(ctx, lookup, chunk, nil, cache)
require.ErrorIs(t, err, context.Canceled)
require.False(t, lookupCalled, "a canceled cache hit must not issue a lookup")
}
@@ -278,7 +278,7 @@ func TestResolveOneChunkManifestCanceledWaiterReturnsDuringCoalescedMiss(t *test
defer leaderCancel()
leaderDone := make(chan error, 1)
go func() {
_, err := resolveOneChunkManifest(leaderCtx, fixture.lookup, chunk, nil, cache, nil)
_, err := resolveOneChunkManifest(leaderCtx, fixture.lookup, chunk, nil, cache)
leaderDone <- err
}()
@@ -287,7 +287,7 @@ func TestResolveOneChunkManifestCanceledWaiterReturnsDuringCoalescedMiss(t *test
// for the leader's result.
waiterCtx, waiterCancel := context.WithCancel(context.Background())
waiterCancel()
_, err := resolveOneChunkManifest(waiterCtx, fixture.lookup, chunk, nil, cache, nil)
_, err := resolveOneChunkManifest(waiterCtx, fixture.lookup, chunk, nil, cache)
require.ErrorIs(t, err, context.Canceled)
// The leader must still complete successfully and populate the cache.
+5 -56
View File
@@ -13,12 +13,9 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
func TestDoMaybeManifestize(t *testing.T) {
@@ -624,7 +621,7 @@ func TestFetchWholeChunkRetriesFreshLocations(t *testing.T) {
inv := &countingInvalidator{}
bytesBuffer := fetchManifestBuffer(t)
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,stale", nil, false, inv, nil))
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,stale", nil, false, inv))
assert.Equal(t, int32(1), inv.invalidations.Load())
assert.Equal(t, int32(2), lookup.calls.Load())
@@ -658,7 +655,7 @@ func TestFetchWholeChunkRefreshesLocationsAfterPartialFailure(t *testing.T) {
inv := &countingInvalidator{}
bytesBuffer := fetchManifestBuffer(t)
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,abc", nil, false, inv, nil))
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup.lookup, "5,abc", nil, false, inv))
assert.Equal(t, int32(1), inv.invalidations.Load())
assert.Equal(t, int32(2), lookup.calls.Load())
decoded := &filer_pb.FileChunkManifest{}
@@ -679,7 +676,7 @@ func TestFetchWholeChunkWithoutInvalidator(t *testing.T) {
freshUrls: []string{"http://unused:8080/5,abc"},
}
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, nil, nil))
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, nil))
assert.Equal(t, int32(1), lookup.calls.Load())
}
@@ -697,7 +694,7 @@ func TestFetchWholeChunkUnchangedLocations(t *testing.T) {
}
inv := &countingInvalidator{}
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv, nil))
assert.Error(t, fetchWholeChunk(context.Background(), fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv))
assert.Equal(t, int32(2), lookup.calls.Load())
assert.Equal(t, int32(1), inv.invalidations.Load())
}
@@ -714,7 +711,7 @@ func TestFetchWholeChunkCancelledKeepsLocations(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := fetchWholeChunk(ctx, fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv, nil)
err := fetchWholeChunk(ctx, fetchManifestBuffer(t), lookup.lookup, "5,abc", nil, false, inv)
assert.ErrorIs(t, err, context.Canceled)
assert.Equal(t, int32(0), inv.invalidations.Load())
assert.Equal(t, int32(1), lookup.calls.Load())
@@ -733,51 +730,3 @@ func TestFetchWholeChunkCancelledKeepsLocations(t *testing.T) {
})
assert.ErrorIs(t, noInvalidator, context.Canceled)
}
// TestFetchWholeChunkUsesProvidedFilerJwt covers a replicating reader whose
// source filer authenticates proxied downloads with its own read key: the
// supplied provider's token must reach the server, not the process-wide one.
func TestFetchWholeChunkUsesProvidedFilerJwt(t *testing.T) {
manifestBytes, err := proto.Marshal(&filer_pb.FileChunkManifest{
Chunks: []*filer_pb.FileChunk{{FileId: "100,abc", Offset: 0, Size: 8}},
})
assert.NoError(t, err)
gotAuth := make(chan string, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case gotAuth <- r.Header.Get("Authorization"):
default:
}
w.Header().Set("Content-Length", strconv.Itoa(len(manifestBytes)))
w.Write(manifestBytes)
}))
t.Cleanup(srv.Close)
lookup := func(ctx context.Context, fileId string) ([]string, error) {
return []string{srv.URL + "/?" + util_http.ProxyChunkIdParam + "=" + fileId}, nil
}
jwtFn := func(isWrite bool) security.EncodedJwt {
assert.False(t, isWrite)
return "side-read-jwt"
}
bytesBuffer := fetchManifestBuffer(t)
require.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, lookup, "5,abc", nil, false, nil, jwtFn))
select {
case auth := <-gotAuth:
assert.Equal(t, security.BearerPrefix+"side-read-jwt", auth)
default:
t.Fatal("the proxied fetch never reached the handler")
}
// non-proxy URLs keep the volume-server credential and never call the provider
volumeURL := manifestServer(t, manifestBytes).URL + "/5,abc"
volumeLookup := func(ctx context.Context, fileId string) ([]string, error) {
return []string{volumeURL}, nil
}
bytesBuffer.Reset()
assert.NoError(t, fetchWholeChunk(context.Background(), bytesBuffer, volumeLookup, "5,abc", nil, false, nil, func(bool) security.EncodedJwt {
t.Fatal("provider must not be consulted for a volume url")
return ""
}))
}
+1 -1
View File
@@ -190,7 +190,7 @@ func loadLogFileEntries(masterClient *wdclient.MasterClient, chunk *filer_pb.Fil
lookupFileIdFn := func(ctx context.Context, fileId string) (targetUrls []string, err error) {
return masterClient.LookupFileId(ctx, fileId)
}
if fetchErr := fetchWholeChunk(context.Background(), bytesBuffer, lookupFileIdFn, chunk.GetFileIdString(), chunk.CipherKey, chunk.IsCompressed, masterClient, nil); fetchErr != nil {
if fetchErr := fetchWholeChunk(context.Background(), bytesBuffer, lookupFileIdFn, chunk.GetFileIdString(), chunk.CipherKey, chunk.IsCompressed, masterClient); fetchErr != nil {
return nil, false, fetchErr
}
return decodeLogRecords(bytesBuffer.Bytes())
+74 -113
View File
@@ -25,7 +25,7 @@ type ReaderCache struct {
lookupFileIdFn wdclient.LookupFileIdFunctionType
cacheInvalidator CacheInvalidator
fetchChunkDataFn fetchChunkDataFnType
sync.RWMutex
sync.Mutex
downloaders map[string]*SingleChunkCacher
limit int
budget *ReaderCacheBudget
@@ -78,13 +78,6 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
count = 1
}
var started []*SingleChunkCacher
defer func() {
for _, cacher := range started {
<-cacher.cacheStartedCh
}
}()
rc.Lock()
defer rc.Unlock()
@@ -120,10 +113,9 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
// cache this chunk if not yet
shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= rc.chunkCache.GetMaxFilePartSizeInCache()
cacher := newSingleChunkCacher(rc, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int(chunkView.ChunkSize), shouldCache)
cacher.wg.Add(1) // the fetch, so destroy() waits even before the goroutine runs
rc.downloaders[chunkView.FileId] = cacher
go cacher.startCaching()
started = append(started, cacher)
<-cacher.cacheStartedCh
rc.downloaders[chunkView.FileId] = cacher
cached++
}
@@ -149,7 +141,6 @@ func (rc *ReaderCache) fetchChunkRange(ctx context.Context, buffer []byte, chunk
// moves elsewhere, so another stream finishing or leaving the same chunk does
// not drop the buffer from under it.
type chunkStream struct {
mu sync.Mutex // guards cacher; concurrent ReadAt calls on one ChunkReadAt share the stream
cacher *SingleChunkCacher
}
@@ -159,56 +150,47 @@ func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId st
func (rc *ReaderCache) readChunkAt(ctx context.Context, stream *chunkStream, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
retry:
rc.RLock()
if cacher, found := rc.downloaders[fileId]; found {
if cacher.hasCompletedError() {
rc.RUnlock()
rc.remove(cacher)
goto retry
}
// Count this read on the cacher before releasing the map lock, so a
// concurrent destroy() (error eviction here, LRU, or UnCache) cannot
// start wg.Wait() on a zero counter while this read is about to register.
cacher.wg.Add(1)
atomic.AddInt32(&cacher.readers, 1)
previous := stream.pin(cacher)
rc.RUnlock()
n, err := rc.readFromCacher(ctx, stream, cacher, previous, buffer, offset, chunkSize)
if n > 0 || err != nil {
return n, err
}
// If n=0 and err=nil, the cacher couldn't provide data for this offset.
// Fall through to try chunkCache.
} else {
rc.RUnlock()
}
rc.Lock()
for {
if cacher, found := rc.downloaders[fileId]; found {
if cacher.hasCompletedError() {
delete(rc.downloaders, fileId)
rc.Unlock()
cacher.destroy()
rc.Lock()
continue
}
// Count this read on the cacher before releasing the map lock, so a
// concurrent destroy() (error eviction here, LRU, or UnCache) cannot
// start wg.Wait() on a zero counter while this read is about to register.
cacher.wg.Add(1)
atomic.AddInt32(&cacher.readers, 1)
previous := stream.pin(cacher)
rc.Unlock()
rc.unpin(previous)
n, err := cacher.readChunkAt(ctx, buffer, offset)
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
if n > 0 || err != nil {
return n, err
}
// If n=0 and err=nil, the cacher couldn't provide data for this offset.
// Fall through to try chunkCache.
rc.Lock()
}
break
}
if shouldCache || rc.lookupFileIdFn == nil {
n, err := rc.chunkCache.ReadChunkAt(buffer, fileId, uint64(offset))
if n > 0 {
// Served from the chunk cache: the stream has left its pinned chunk.
rc.unpin(stream.detach(nil))
previous := stream.unpinLocked()
rc.Unlock()
rc.unpin(previous)
return n, err
}
}
rc.Lock()
// A downloader may have registered between the read lock and this one.
if cacher, found := rc.downloaders[fileId]; found {
if cacher.hasCompletedError() {
delete(rc.downloaders, fileId)
rc.Unlock()
cacher.destroy()
goto retry
}
cacher.wg.Add(1)
atomic.AddInt32(&cacher.readers, 1)
previous := stream.pin(cacher)
rc.Unlock()
n, err := rc.readFromCacher(ctx, stream, cacher, previous, buffer, offset, chunkSize)
return n, err
}
// clean up old downloaders; prefer one no stream is positioned in, but
// fall back to a pinned one so abandoned pins cannot bypass the limit
if len(rc.downloaders) >= rc.limit {
@@ -242,57 +224,40 @@ retry:
// glog.V(4).Infof("cache1 %s", fileId)
cacher := newSingleChunkCacher(rc, fileId, cipherKey, isGzipped, chunkSize, shouldCache)
cacher.wg.Add(2) // the fetch plus this read, so destroy() waits even before the goroutine runs
atomic.AddInt32(&cacher.readers, 1)
rc.downloaders[fileId] = cacher
previous := stream.pin(cacher)
rc.Unlock()
go cacher.startCaching()
<-cacher.cacheStartedCh
n, err := rc.readFromCacher(ctx, stream, cacher, previous, buffer, offset, chunkSize)
rc.downloaders[fileId] = cacher
cacher.wg.Add(1)
atomic.AddInt32(&cacher.readers, 1)
previous := stream.pin(cacher)
rc.Unlock()
rc.unpin(previous)
n, err := cacher.readChunkAt(ctx, buffer, offset)
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
return n, err
}
// readFromCacher serves the read and releases the pin if the stream finished
// the chunk. The caller must have registered the read (wg + readers) and
// pinned the stream under the map lock; previous is the chunk the stream left
// when it pinned.
func (rc *ReaderCache) readFromCacher(ctx context.Context, stream *chunkStream, cacher *SingleChunkCacher, previous *SingleChunkCacher, buffer []byte, offset int64, chunkSize int) (n int, err error) {
rc.unpin(previous)
n, err = cacher.readChunkAt(ctx, buffer, offset)
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
return
}
// pin makes cacher the stream's current chunk and returns the chunk it was
// pinned to before, which the caller unpins.
// pinned to before, which the caller unpins once the ReaderCache lock is
// released. The stream is only touched under the ReaderCache lock, since
// concurrent ReadAt calls on one ChunkReadAt share it.
func (stream *chunkStream) pin(cacher *SingleChunkCacher) (previous *SingleChunkCacher) {
if stream == nil {
if stream == nil || stream.cacher == cacher {
return nil
}
stream.mu.Lock()
defer stream.mu.Unlock()
if stream.cacher == cacher {
return nil
}
atomic.AddInt32(&cacher.pins, 1)
previous = stream.cacher
stream.cacher = cacher
atomic.AddInt32(&cacher.pins, 1)
return previous
}
// detach unpins the stream from its chunk and returns that chunk for the
// caller to unpin. A non-nil expected cacher makes the detach conditional on
// the stream still being positioned in it.
func (stream *chunkStream) detach(expected *SingleChunkCacher) (previous *SingleChunkCacher) {
// unpinLocked detaches the stream from its chunk and returns that chunk for
// the caller to unpin once the ReaderCache lock is released.
func (stream *chunkStream) unpinLocked() (previous *SingleChunkCacher) {
if stream == nil {
return nil
}
stream.mu.Lock()
defer stream.mu.Unlock()
if expected != nil && stream.cacher != expected {
return nil
}
previous = stream.cacher
stream.cacher = nil
return previous
@@ -304,12 +269,24 @@ func (rc *ReaderCache) releaseIfFinished(stream *chunkStream, cacher *SingleChun
if stream == nil || err != nil || offset+int64(n) < int64(chunkSize) {
return
}
rc.unpin(stream.detach(cacher))
var previous *SingleChunkCacher
rc.Lock()
if stream.cacher == cacher {
previous = stream.unpinLocked()
}
rc.Unlock()
rc.unpin(previous)
}
// releaseStream unpins whatever chunk the stream is positioned in.
func (rc *ReaderCache) releaseStream(stream *chunkStream) {
rc.unpin(stream.detach(nil))
if stream == nil {
return
}
rc.Lock()
previous := stream.unpinLocked()
rc.Unlock()
rc.unpin(previous)
}
// unpin drops one stream's pin. Once no stream is positioned in the chunk it
@@ -364,41 +341,26 @@ func (rc *ReaderCache) removeUnpinned(downloader *SingleChunkCacher) (removed bo
return
}
// consumable reports whether the cacher could be dropped: its buffer was
// fully read or every stream positioned in it has left, and no reader is
// attached or pinned. All fields are atomics, so callers can skip the
// ReaderCache lock whenever removal is impossible.
func (s *SingleChunkCacher) consumable() bool {
return atomic.LoadInt32(&s.readers) == 0 &&
atomic.LoadInt32(&s.pins) == 0 &&
(atomic.LoadInt32(&s.consumed) != 0 || atomic.LoadInt32(&s.left) != 0)
}
// removeConsumed drops a cacher once its buffer was fully read, or the
// streams positioned in it have left, and no readers remain attached or
// pinned. The checks run under the ReaderCache lock so a reader attaching
// at the same time either wins (the cacher stays and that reader's detach
// retries the removal) or misses the map and refetches.
func (rc *ReaderCache) removeConsumed(downloader *SingleChunkCacher) {
if !downloader.consumable() {
return
}
rc.Lock()
removed := rc.removeConsumedLocked(downloader)
removed := rc.downloaders[downloader.chunkFileId] == downloader &&
atomic.LoadInt32(&downloader.readers) == 0 &&
atomic.LoadInt32(&downloader.pins) == 0 &&
(atomic.LoadInt32(&downloader.consumed) != 0 || atomic.LoadInt32(&downloader.left) != 0)
if removed {
delete(rc.downloaders, downloader.chunkFileId)
}
rc.Unlock()
if removed {
downloader.destroy()
}
}
func (rc *ReaderCache) removeConsumedLocked(downloader *SingleChunkCacher) (removed bool) {
if rc.downloaders[downloader.chunkFileId] == downloader && downloader.consumable() {
delete(rc.downloaders, downloader.chunkFileId)
return true
}
return false
}
func (rc *ReaderCache) destroy() {
rc.Lock()
downloaders := rc.downloaders
@@ -423,9 +385,8 @@ func newSingleChunkCacher(parent *ReaderCache, fileId string, cipherKey []byte,
}
// startCaching downloads a chunk shared by concurrent readers.
// The caller must s.wg.Add(1) before publishing the cacher in the
// downloaders map, so a removal can never observe the fetch as absent.
func (s *SingleChunkCacher) startCaching() {
s.wg.Add(1)
defer func() {
close(s.done)
s.wg.Done()
-31
View File
@@ -724,34 +724,3 @@ func TestSingleChunkCacherOneReaderCancelsOthersContinue(t *testing.T) {
t.Error("Other reader did not complete")
}
}
// TestReaderCacheBookkeepingOffCacheLock guards the contention fix: pin
// lifecycle calls that cannot remove a cacher must not block on the
// ReaderCache lock.
func TestReaderCacheBookkeepingOffCacheLock(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
rc := NewReaderCache(10, cache, nil, nil)
defer rc.destroy()
cacher := &SingleChunkCacher{parent: rc, chunkFileId: "pinned-chunk"}
atomic.StoreInt32(&cacher.readers, 1) // a read in flight: not consumable
rc.Lock()
started := make(chan struct{})
done := make(chan struct{})
go func() {
close(started)
defer close(done)
var stream chunkStream
stream.pin(cacher)
rc.releaseStream(&stream)
}()
<-started
select {
case <-done:
case <-time.After(time.Second):
rc.Unlock()
t.Fatal("stream pin lifecycle blocked on the cache lock")
}
rc.Unlock()
}
+4 -7
View File
@@ -43,7 +43,7 @@ func (fh *FileHandle) readFromChunksWithContext(ctx context.Context, buff []byte
entry.RUnlock()
if remoteOnly {
glog.V(4).Infof("download remote entry %s", fileFullPath)
err := fh.downloadRemoteEntry(ctx, entry)
err := fh.downloadRemoteEntry(entry)
if err != nil {
glog.V(1).Infof("download remote entry %s: %v", fileFullPath, err)
return 0, 0, err
@@ -111,15 +111,12 @@ func (fh *FileHandle) readFromChunksWithContext(ctx context.Context, buff []byte
return int64(totalRead), ts, err
}
func (fh *FileHandle) downloadRemoteEntry(ctx context.Context, entry *LockedEntry) error {
func (fh *FileHandle) downloadRemoteEntry(entry *LockedEntry) error {
fileFullPath := fh.FullPath()
dir, _ := fileFullPath.DirAndName()
// callWait 0: this RPC streams a whole remote object filer-side, so a
// healthy download can legitimately outlast any metadata-call bound. The
// attempt stays bound to the caller's context instead.
err := fh.wfs.withFilerClient(ctx, false, 0, func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
err := fh.wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
request := &filer_pb.CacheRemoteObjectToLocalClusterRequest{
Directory: string(dir),
@@ -127,7 +124,7 @@ func (fh *FileHandle) downloadRemoteEntry(ctx context.Context, entry *LockedEntr
}
glog.V(4).Infof("download entry: %v", request)
resp, err := client.CacheRemoteObjectToLocalCluster(ctx, request)
resp, err := client.CacheRemoteObjectToLocalCluster(context.Background(), request)
if err != nil {
return fmt.Errorf("CacheRemoteObjectToLocalCluster file %s: %v", fileFullPath, err)
}
+2 -2
View File
@@ -20,8 +20,8 @@ func (wfs *WFS) subscribeFilerConfEvents() (*meta_cache.MetadataFollower, error)
confFullName := filepath.Join(filer.DirectoryEtcSeaweedFS, filer.FilerConfName)
// read current conf
err := wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
content, err := filer.ReadInsideFiler(ctx, client, confDir, confName)
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
content, err := filer.ReadInsideFiler(context.Background(), client, confDir, confName)
if err != nil {
return err
}
+2 -3
View File
@@ -145,7 +145,6 @@ type WFS struct {
manifestCache *filer.ChunkManifestCache
writeBufferAccountant *page_writer.WriteBufferAccountant
signature int32
filerCallTimeout time.Duration // bounds one filer call; tests only, 0 = filerRPCTimeout
concurrentWriters *util.LimitedConcurrentExecutor
copyBufferPool sync.Pool
concurrentCopiersSem chan struct{}
@@ -658,8 +657,8 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, entryVersion,
var entry *filer_pb.Entry
var lookupVersion entryVersion
lookupDir, lookupName := fullpath.DirAndName()
err := wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
resp, lookupErr := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, lookupErr := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
Directory: lookupDir,
Name: lookupName,
})
@@ -84,7 +84,6 @@ type fakeFilerServer struct {
lookupCalls atomic.Int32
lookupStarted chan struct{} // closed when the first lookup arrives
lookupGate chan struct{} // first lookup waits here when non-nil
createCalls atomic.Int32
}
func (s *fakeFilerServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
@@ -126,7 +125,6 @@ func (s *fakeFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream f
}
func (s *fakeFilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
s.createCalls.Add(1)
return &filer_pb.CreateEntryResponse{
MetadataEvent: &filer_pb.SubscribeMetadataResponse{
Directory: req.Directory,
@@ -674,7 +672,7 @@ func TestRemoteCacheResponseVersionFencesUndeliveredEvents(t *testing.T) {
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
}, 0, 0)
if err := fh.downloadRemoteEntry(context.Background(), fh.GetEntry()); err != nil {
if err := fh.downloadRemoteEntry(fh.GetEntry()); err != nil {
t.Fatalf("downloadRemoteEntry: %v", err)
}
if size := fh.GetEntry().GetEntry().Attributes.FileSize; size != 200 {
@@ -1508,7 +1506,7 @@ func TestRemoteDownloadBaseMappedToLocal(t *testing.T) {
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 200},
}, 0, 0)
if err := fh.downloadRemoteEntry(context.Background(), fh.GetEntry()); err != nil {
if err := fh.downloadRemoteEntry(fh.GetEntry()); err != nil {
t.Fatalf("downloadRemoteEntry: %v", err)
}
// The base — and the live entry — must be in local uid form.
@@ -1619,7 +1617,7 @@ func TestStaleRemoteDownloadDoesNotRollBack(t *testing.T) {
})
fh.advanceEntryVersion(3000, 0)
if err := fh.downloadRemoteEntry(context.Background(), fh.GetEntry()); err != nil {
if err := fh.downloadRemoteEntry(fh.GetEntry()); err != nil {
t.Fatalf("downloadRemoteEntry: %v", err)
}
@@ -1646,7 +1644,7 @@ func TestRemoteOnlyHandleTakesUnversionedDownload(t *testing.T) {
}, 0, 0)
fh.advanceEntryVersion(3000, 0)
if err := fh.downloadRemoteEntry(context.Background(), fh.GetEntry()); err != nil {
if err := fh.downloadRemoteEntry(fh.GetEntry()); err != nil {
t.Fatalf("downloadRemoteEntry: %v", err)
}
@@ -1803,7 +1801,7 @@ func TestUnversionedRemoteDownloadDoesNotOverwriteVersioned(t *testing.T) {
})
fh.advanceEntryVersion(3000, 0)
if err := fh.downloadRemoteEntry(context.Background(), fh.GetEntry()); err != nil {
if err := fh.downloadRemoteEntry(fh.GetEntry()); err != nil {
t.Fatalf("downloadRemoteEntry: %v", err)
}
@@ -1933,7 +1931,7 @@ func TestRejectedDownloadDoesNotRollBackCache(t *testing.T) {
}, 0, 0)
fh.advanceEntryVersion(3000, 0)
if err := fh.downloadRemoteEntry(context.Background(), fh.GetEntry()); err != nil {
if err := fh.downloadRemoteEntry(fh.GetEntry()); err != nil {
t.Fatalf("downloadRemoteEntry: %v", err)
}
// The download publishes asynchronously; a synchronous apply behind it
@@ -1968,7 +1966,7 @@ func TestRemoteOnlyHandleRefusesKnownOlderDownload(t *testing.T) {
}, 0, 0)
fh.advanceEntryVersion(3000, 0)
if err := fh.downloadRemoteEntry(context.Background(), fh.GetEntry()); err != nil {
if err := fh.downloadRemoteEntry(fh.GetEntry()); err != nil {
t.Fatalf("downloadRemoteEntry: %v", err)
}
+2 -2
View File
@@ -153,7 +153,7 @@ func posixLockContext(cancel <-chan struct{}) (context.Context, context.CancelFu
func (wfs *WFS) callPosixLock(ctx context.Context, key string, op filer_pb.PosixLockOp, lk posixlock.Range) (*filer_pb.PosixLockResponse, error) {
var resp *filer_pb.PosixLockResponse
err := wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
var e error
resp, e = client.PosixLock(ctx, &filer_pb.PosixLockRequest{
Key: key,
@@ -377,7 +377,7 @@ func (wfs *WFS) callPosixReassert(ctx context.Context, key string, locks []posix
Sid: l.Sid, Owner: l.Owner, Pid: l.Pid, IsFlock: l.IsFlock,
})
}
return wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
return wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
_, e := client.PosixLock(ctx, &filer_pb.PosixLockRequest{
Key: key,
Op: filer_pb.PosixLockOp_KEEP_ALIVE,
+2 -2
View File
@@ -110,7 +110,7 @@ func (wfs *WFS) getQuotaCheckInterval() time.Duration {
}
func (wfs *WFS) checkQuotaOnce() {
err := wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
request := &filer_pb.StatisticsRequest{
Collection: wfs.option.Collection,
@@ -119,7 +119,7 @@ func (wfs *WFS) checkQuotaOnce() {
DiskType: string(wfs.option.DiskType),
}
resp, err := client.Statistics(ctx, request)
resp, err := client.Statistics(context.Background(), request)
if err != nil {
glog.V(0).Infof("reading quota usage %v: %v", request, err)
return err
+2 -34
View File
@@ -6,9 +6,7 @@ import (
"fmt"
"io"
"strings"
"sync/atomic"
"syscall"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/cluster"
@@ -30,28 +28,7 @@ func (wfs *WFS) doRename(ctx context.Context, request *filer_pb.StreamRenameEntr
glog.V(1).Infof("Rename %s => %s: stream failed, falling back to unary: %v", oldPath, newPath, err)
}
return wfs.WithFilerClient(true, func(client filer_pb.SeaweedFilerClient) error {
// The stream is dedicated to this attempt, so cancelling its context
// abandons just this rename. Bound the silence between events the way
// the mutation mux does: a filer that accepts the stream then stalls
// must not hold the failover walk hostage, but a long rename that
// keeps sending events may take as long as it needs. Local event
// work is not wire silence — a directory rename can spend longer
// than the bound migrating a child's DLM lock — so the timer defers
// while the handler runs instead of cancelling a healthy stream.
streamCtx, cancel := context.WithCancel(ctx)
defer cancel()
var inHandler atomic.Bool
var silence *time.Timer
silence = time.AfterFunc(wfs.filerRPCWait(), func() {
if inHandler.Load() {
silence.Reset(wfs.filerRPCWait())
return
}
cancel()
})
defer silence.Stop()
stream, streamErr := client.StreamRenameEntry(streamCtx, request)
stream, streamErr := client.StreamRenameEntry(ctx, request)
if streamErr != nil {
return fmt.Errorf("dir AtomicRenameEntry %s => %s : %v", oldPath, newPath, streamErr)
}
@@ -61,20 +38,11 @@ func (wfs *WFS) doRename(ctx context.Context, request *filer_pb.StreamRenameEntr
if recvErr == io.EOF {
break
}
if ctx.Err() == nil && streamCtx.Err() != nil {
return fmt.Errorf("dir Rename %s => %s: no event for %s", oldPath, newPath, wfs.filerRPCWait())
}
return fmt.Errorf("dir Rename %s => %s receive: %v", oldPath, newPath, recvErr)
}
inHandler.Store(true)
err := wfs.handleRenameResponse(ctx, resp, newPath, newPathLock)
inHandler.Store(false)
if err != nil {
if err := wfs.handleRenameResponse(ctx, resp, newPath, newPathLock); err != nil {
return err
}
// The event just proved the filer alive; the bound covers the
// wait for the next one, not the whole rename.
silence.Reset(wfs.filerRPCWait())
}
return nil
})
+2 -2
View File
@@ -37,7 +37,7 @@ func (wfs *WFS) StatFs(cancel <-chan struct{}, in *fuse.InHeader, out *fuse.Stat
if wfs.stats.lastChecked < time.Now().Unix()-20 {
err := wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
request := &filer_pb.StatisticsRequest{
Collection: wfs.option.Collection,
@@ -47,7 +47,7 @@ func (wfs *WFS) StatFs(cancel <-chan struct{}, in *fuse.InHeader, out *fuse.Stat
}
glog.V(4).Infof("reading filer stats: %+v", request)
resp, err := client.Statistics(ctx, request)
resp, err := client.Statistics(context.Background(), request)
if err != nil {
glog.V(0).Infof("reading filer stats %v: %v", request, err)
return err
+3 -3
View File
@@ -20,7 +20,7 @@ func (wfs *WFS) streamCreateEntry(ctx context.Context, req *filer_pb.CreateEntry
glog.V(1).Infof("streamCreateEntry %s/%s: stream failed, falling back to unary: %v", req.Directory, req.Entry.Name, err)
}
var resp *filer_pb.CreateEntryResponse
err := wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
var err error
resp, err = filer_pb.CreateEntryWithResponse(ctx, client, req)
return err
@@ -39,7 +39,7 @@ func (wfs *WFS) streamUpdateEntry(ctx context.Context, req *filer_pb.UpdateEntry
glog.V(1).Infof("streamUpdateEntry %s/%s: stream failed, falling back to unary: %v", req.Directory, req.Entry.Name, err)
}
var resp *filer_pb.UpdateEntryResponse
err := wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
var err error
resp, err = client.UpdateEntry(ctx, req)
return err
@@ -58,7 +58,7 @@ func (wfs *WFS) streamDeleteEntry(ctx context.Context, req *filer_pb.DeleteEntry
glog.V(1).Infof("streamDeleteEntry %s/%s: stream failed, falling back to unary: %v", req.Directory, req.Name, err)
}
var resp *filer_pb.DeleteEntryResponse
err := wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
var err error
resp, err = client.DeleteEntry(ctx, req)
if err != nil {
+1 -51
View File
@@ -8,7 +8,6 @@ import (
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
@@ -54,7 +53,6 @@ type streamMutateMux struct {
stream filer_pb.SeaweedFiler_StreamMutateEntryClient
cancel context.CancelFunc
grpcConn *grpc.ClientConn // dedicated connection, closed on stream teardown
filerIdx int32 // FilerAddresses index the current stream dialed
closed bool
disabled bool // permanently disabled if filer doesn't support the RPC
stopSend chan struct{} // closed to signal the current sendLoop to exit
@@ -184,41 +182,22 @@ func (m *streamMutateMux) Rename(ctx context.Context, req *filer_pb.StreamRename
case <-ctx.Done():
return ctx.Err()
}
sendTimer := time.NewTimer(m.wfs.filerRPCWait())
select {
case err := <-sendReq.errCh:
sendTimer.Stop()
if err != nil {
return fmt.Errorf("rename send: %w: %v", ErrStreamTransport, err)
}
case <-sendTimer.C:
m.teardownStream(gen)
return fmt.Errorf("rename send: %w: timed out", ErrStreamTransport)
case <-ctx.Done():
sendTimer.Stop()
return ctx.Err()
}
// Collect rename events until is_last=true. The timer bounds silence
// between events, not the whole rename.
respTimer := time.NewTimer(m.wfs.filerRPCWait())
defer respTimer.Stop()
// Collect rename events until is_last=true.
for {
select {
case resp, ok := <-ch:
if !ok {
return fmt.Errorf("rename recv: %w: stream closed", ErrStreamTransport)
}
// Applying an event can legitimately outlast the silence bound —
// a directory rename migrates an open child's DLM lock under
// another writer. The timer bounds wire silence only, so stop it
// for the local work and re-arm it before the next wait.
if !respTimer.Stop() {
select {
case <-respTimer.C:
default:
}
}
if r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_RenameResponse); ok {
if r.RenameResponse != nil && r.RenameResponse.EventNotification != nil {
if err := onEvent(r.RenameResponse); err != nil {
@@ -235,10 +214,6 @@ func (m *streamMutateMux) Rename(ctx context.Context, req *filer_pb.StreamRename
}
return nil
}
respTimer.Reset(m.wfs.filerRPCWait())
case <-respTimer.C:
m.teardownStream(gen)
return fmt.Errorf("rename recv: %w: timed out", ErrStreamTransport)
case <-ctx.Done():
return ctx.Err()
}
@@ -268,29 +243,17 @@ func (m *streamMutateMux) doUnary(ctx context.Context, req *filer_pb.StreamMutat
case <-ctx.Done():
return nil, ctx.Err()
}
// Most callers pass context.Background(), so a stream blocked on Send or
// Recv over a dead transport would never surface an error here. Bound the
// wait and tear the stream down so the call can fall back to a unary RPC
// on another filer.
sendTimer := time.NewTimer(m.wfs.filerRPCWait())
select {
case err := <-sendReq.errCh:
sendTimer.Stop()
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrStreamTransport, err)
}
case <-sendTimer.C:
m.teardownStream(gen)
return nil, fmt.Errorf("%w: send timed out", ErrStreamTransport)
case <-ctx.Done():
sendTimer.Stop()
return nil, ctx.Err()
}
respTimer := time.NewTimer(m.wfs.filerRPCWait())
select {
case resp, ok := <-ch:
respTimer.Stop()
if !ok {
return nil, fmt.Errorf("%w: stream closed", ErrStreamTransport)
}
@@ -305,11 +268,7 @@ func (m *streamMutateMux) doUnary(ctx context.Context, req *filer_pb.StreamMutat
}
}
return resp, nil
case <-respTimer.C:
m.teardownStream(gen)
return nil, fmt.Errorf("%w: response timed out", ErrStreamTransport)
case <-ctx.Done():
respTimer.Stop()
return nil, ctx.Err()
}
}
@@ -405,7 +364,6 @@ func (m *streamMutateMux) openStream(out *filer_pb.SeaweedFiler_StreamMutateEntr
}
atomic.StoreInt32(&m.wfs.option.filerIndex, idx)
m.filerIdx = idx
m.cancel = cancel
m.grpcConn = grpcConn
*out = stream
@@ -470,7 +428,6 @@ func (m *streamMutateMux) teardownStream(gen uint64) {
m.mu.Unlock()
return
}
filerIdx := m.filerIdx
m.stream = nil
if m.stopSend != nil {
close(m.stopSend)
@@ -482,13 +439,6 @@ func (m *streamMutateMux) teardownStream(gen uint64) {
}
conn := m.grpcConn
m.grpcConn = nil
// Rotate while still holding mu: a new generation cannot open until
// teardown releases the lock, so the index advanced here always belongs
// to the stream that just died — never to a successor ensureStream may
// have opened in between.
if n := int32(len(m.wfs.option.FilerAddresses)); n > 0 {
atomic.CompareAndSwapInt32(&m.wfs.option.filerIndex, filerIdx, (filerIdx+1)%n)
}
m.mu.Unlock()
// Do NOT call failAllPending here — recvLoop is the sole owner of
+4 -87
View File
@@ -2,13 +2,9 @@ package mount
import (
"context"
"fmt"
"sync/atomic"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -18,20 +14,6 @@ import (
var _ = filer_pb.FilerClient(&WFS{})
func (wfs *WFS) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) (err error) {
return wfs.withFilerClient(context.Background(), streamingMode, wfs.filerRPCWait(), func(_ context.Context, client filer_pb.SeaweedFilerClient) error {
return fn(client)
})
}
// withFilerClient walks the filer addresses until one answers fn. callWait
// bounds one attempt; callWait <= 0 leaves the attempt to ctx alone, for
// calls whose duration the metadata bound cannot anticipate (a whole-file
// remote download). Streaming calls ignore callWait — their callbacks bound
// themselves (the rename fallback arms its own silence timer). The callback
// must run its RPCs under the supplied context: that is what lets a
// timed-out attempt be cancelled without disturbing the shared cached
// channel's other callers.
func (wfs *WFS) withFilerClient(ctx context.Context, streamingMode bool, callWait time.Duration, fn func(ctx context.Context, client filer_pb.SeaweedFilerClient) error) (err error) {
return util.Retry("filer grpc", func() error {
@@ -40,7 +22,10 @@ func (wfs *WFS) withFilerClient(ctx context.Context, streamingMode bool, callWai
for x := 0; x < n; x++ {
filerGrpcAddress := wfs.option.FilerAddresses[i].ToGrpcAddress()
err = wfs.callFiler(ctx, streamingMode, callWait, filerGrpcAddress, fn)
err = pb.WithGrpcClient(context.Background(), streamingMode, wfs.signature, func(grpcConnection *grpc.ClientConn) error {
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
return fn(client)
}, filerGrpcAddress, false, wfs.option.GrpcDialOption)
if err != nil {
// glog.V(0).Infof("WithFilerClient %d %v: %v", x, filerGrpcAddress, err)
@@ -60,74 +45,6 @@ func (wfs *WFS) withFilerClient(ctx context.Context, streamingMode bool, callWai
}
// filerRPCWait bounds one filer call when the callers' RPCs carry no deadline
// of their own. filerCallTimeout is only settable on the WFS for tests.
func (wfs *WFS) filerRPCWait() time.Duration {
if wfs.filerCallTimeout > 0 {
return wfs.filerCallTimeout
}
return filerRPCTimeout
}
// callFiler runs fn against one filer under a per-attempt context derived
// from ctx, so a filer whose transport silently stalls (stopped peer,
// black-holed connection) cannot block forever and keep the walk from
// reaching the remaining filer addresses. Cancelling the attempt aborts its
// RPCs on the shared cached channel without tearing that channel down.
//
// On timeout the call waits for the attempt's callback to unwind before
// returning: a slow attempt must not overlap the next filer's run of the
// same closure and clobber the caller's shared result variables. A callback
// that ignored the attempt context is forced out by dropping the channel.
func (wfs *WFS) callFiler(ctx context.Context, streamingMode bool, callWait time.Duration, filerGrpcAddress string, fn func(ctx context.Context, client filer_pb.SeaweedFilerClient) error) error {
if streamingMode {
return pb.WithGrpcClient(ctx, streamingMode, wfs.signature, func(grpcConnection *grpc.ClientConn) error {
return fn(ctx, filer_pb.NewSeaweedFilerClient(grpcConnection))
}, filerGrpcAddress, false, wfs.option.GrpcDialOption)
}
attemptCtx, cancel := context.WithCancel(ctx)
if callWait > 0 {
attemptCtx, cancel = context.WithTimeout(ctx, callWait)
}
defer cancel()
done := make(chan error, 1)
go func() {
done <- pb.WithGrpcClient(attemptCtx, streamingMode, wfs.signature, func(grpcConnection *grpc.ClientConn) error {
return fn(attemptCtx, filer_pb.NewSeaweedFilerClient(grpcConnection))
}, filerGrpcAddress, false, wfs.option.GrpcDialOption)
}()
select {
case err := <-done:
if err != nil && ctx.Err() == nil && attemptCtx.Err() == context.DeadlineExceeded {
// fn surfaced the attempt deadline itself; report it like the
// timer path so the failure reads as a filer timeout, not as a
// caller cancellation (which IsTransientError would not retry).
return status.Error(codes.Unavailable, fmt.Sprintf("filer %s: call timed out", filerGrpcAddress))
}
return err
case <-attemptCtx.Done():
// Give the callback one RPC's grace to unwind on its own; only if it
// ignored the attempt context does the cached channel get dropped —
// the collateral is borne by calls to the same unresponsive filer,
// which the walk is abandoning anyway.
drain := time.NewTimer(wfs.filerRPCWait())
defer drain.Stop()
select {
case <-done:
case <-drain.C:
pb.InvalidateGrpcConnection(filerGrpcAddress)
<-done
}
if ctx.Err() != nil {
return ctx.Err()
}
return status.Error(codes.Unavailable, fmt.Sprintf("filer %s: call timed out", filerGrpcAddress))
}
}
func (wfs *WFS) AdjustedUrl(location *filer_pb.Location) string {
if wfs.option.VolumeServerAccess == "publicUrl" {
return location.PublicUrl
-217
View File
@@ -1,217 +0,0 @@
package mount
import (
"context"
"errors"
"net"
"sync/atomic"
"testing"
"time"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// wedgedFiler accepts connections but never answers: LookupDirectoryEntry and
// StreamMutateEntry block until the transport dies. It stands in for a filer
// whose TCP connection black-holes instead of refusing.
type wedgedFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
}
func (s *wedgedFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
<-ctx.Done()
return nil, ctx.Err()
}
func (s *wedgedFiler) StreamMutateEntry(stream filer_pb.SeaweedFiler_StreamMutateEntryServer) error {
<-stream.Context().Done()
return stream.Context().Err()
}
func (s *wedgedFiler) StreamRenameEntry(req *filer_pb.StreamRenameEntryRequest, stream filer_pb.SeaweedFiler_StreamRenameEntryServer) error {
<-stream.Context().Done()
return stream.Context().Err()
}
// StreamRenameEntry ends cleanly with no events: enough for a failover test
// to confirm the walk reached this filer.
func (s *fakeFilerServer) StreamRenameEntry(req *filer_pb.StreamRenameEntryRequest, stream filer_pb.SeaweedFiler_StreamRenameEntryServer) error {
return nil
}
func listenFiler(t *testing.T, fake filer_pb.SeaweedFilerServer) pb.ServerAddress {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
t.Cleanup(func() { _ = listener.Close() })
server := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(server, fake)
go server.Serve(listener)
t.Cleanup(server.Stop)
return pb.NewServerAddressWithGrpcPort("127.0.0.1:1", listener.Addr().(*net.TCPAddr).Port)
}
// A wedged filer must not hold the walk hostage: the call is bounded and the
// walk reaches the next address.
func TestWithFilerClientFailsOverPastWedgedFiler(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.filerCallTimeout = 200 * time.Millisecond
wedged := listenFiler(t, &wedgedFiler{})
live := listenFiler(t, &fakeFilerServer{lookupSize: 42, lookupLogTsNs: 1000})
wfs.option.FilerAddresses = []pb.ServerAddress{wedged, live}
atomic.StoreInt32(&wfs.option.filerIndex, 0)
var entry *filer_pb.Entry
err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
Directory: "/dir",
Name: "file",
})
if err != nil {
return err
}
entry = resp.Entry
return nil
})
if err != nil {
t.Fatalf("WithFilerClient: %v", err)
}
if entry == nil || entry.Attributes.FileSize != 42 {
t.Fatalf("entry = %+v, want lookup served by the live filer", entry)
}
if got := atomic.LoadInt32(&wfs.option.filerIndex); got != 1 {
t.Fatalf("filerIndex = %d, want 1 (the live filer)", got)
}
}
// A mutation stream whose peer never answers must surface as a transport
// error instead of hanging: the sticky index moves off the dead filer and
// streamCreateEntry's unary fallback lands the same mutation on the live one.
func TestStreamMutateTimesOutAndRotatesFiler(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.filerCallTimeout = 200 * time.Millisecond
wedged := listenFiler(t, &wedgedFiler{})
live := &fakeFilerServer{}
liveAddress := listenFiler(t, live)
wfs.option.FilerAddresses = []pb.ServerAddress{wedged, liveAddress}
atomic.StoreInt32(&wfs.option.filerIndex, 0)
wfs.streamMutate = newStreamMutateMux(wfs)
defer wfs.streamMutate.Close()
resp, err := wfs.streamCreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
Directory: "/dir",
Entry: &filer_pb.Entry{Name: "file"},
})
if err != nil {
t.Fatalf("streamCreateEntry: %v, want the unary fallback to succeed", err)
}
if resp == nil {
t.Fatal("streamCreateEntry returned no response")
}
if got := atomic.LoadInt32(&wfs.option.filerIndex); got != 1 {
t.Fatalf("filerIndex = %d, want 1 after teardown of the wedged stream", got)
}
if got := live.createCalls.Load(); got != 1 {
t.Fatalf("live filer createCalls = %d, want 1 (unary fallback ran)", got)
}
}
// A timed-out attempt must unwind before the walk runs the next filer's
// attempt: every attempt runs the same closure, so two in flight at once
// race on the caller's captured result variables.
func TestWithFilerClientDoesNotOverlapAttempts(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.filerCallTimeout = 200 * time.Millisecond
wedged := listenFiler(t, &wedgedFiler{})
live := listenFiler(t, &fakeFilerServer{lookupSize: 42})
wfs.option.FilerAddresses = []pb.ServerAddress{wedged, live}
atomic.StoreInt32(&wfs.option.filerIndex, 0)
var attempts, inside, overlap atomic.Int32
release := make(chan struct{})
done := make(chan error, 1)
go func() {
done <- wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
n := attempts.Add(1)
if !inside.CompareAndSwap(0, 1) {
overlap.Add(1)
}
defer inside.Store(0)
if n == 1 {
// Outlive the attempt deadline on purpose: the walk must
// wait for this callback instead of racing ahead.
<-release
return errors.New("first attempt released")
}
return nil
})
}()
deadline := time.Now().Add(10 * wfs.filerCallTimeout)
for attempts.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if attempts.Load() == 0 {
t.Fatal("first attempt never started")
}
// Past the deadline plus its unwind grace, the blocked callback must
// still be the only attempt: no second run may start alongside it.
time.Sleep(3 * wfs.filerCallTimeout)
if got := attempts.Load(); got != 1 {
t.Fatalf("attempts = %d, want 1 while the timed-out attempt is still unwinding", got)
}
close(release)
if err := <-done; err != nil {
t.Fatalf("WithFilerClient: %v", err)
}
if got := overlap.Load(); got != 0 {
t.Fatalf("attempts overlapped %d times", got)
}
if got := attempts.Load(); got != 2 {
t.Fatalf("attempts = %d, want 2", got)
}
}
// The unary fallback for a streamed rename must bound silence too: a filer
// that accepts StreamRenameEntry then never answers cannot hold the walk.
func TestDoRenameFailsOverPastWedgedFiler(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.filerCallTimeout = 200 * time.Millisecond
wedged := listenFiler(t, &wedgedFiler{})
live := listenFiler(t, &fakeFilerServer{})
wfs.option.FilerAddresses = []pb.ServerAddress{wedged, live}
atomic.StoreInt32(&wfs.option.filerIndex, 0)
var newPathLock *cluster.LiveLock
start := time.Now()
err := wfs.doRename(context.Background(), &filer_pb.StreamRenameEntryRequest{
OldDirectory: "/a",
OldName: "f",
NewDirectory: "/b",
NewName: "f",
}, util.FullPath("/a/f"), util.FullPath("/b/f"), &newPathLock)
if err != nil {
t.Fatalf("doRename: %v", err)
}
if elapsed := time.Since(start); elapsed > 10*wfs.filerCallTimeout {
t.Fatalf("doRename took %v, wedged fallback stream was not bounded", elapsed)
}
if got := atomic.LoadInt32(&wfs.option.filerIndex); got != 1 {
t.Fatalf("filerIndex = %d, want 1 (the live filer)", got)
}
}
+1 -6
View File
@@ -62,7 +62,6 @@ type UploadOption struct {
SourceUrl string // optional: for logging when reading from a remote source
MaxAttempts int // <=0 uses the default
GenUploadUrl func(host, fileId string) string // if nil → fallback "http://{host}/{fileId}"
FilerJwt security.FilerJwtProvider // credential for proxy chunk URLs; nil → process-wide jwt.filer_signing
}
type UploadResult struct {
@@ -218,11 +217,7 @@ func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, ho
// The request addresses the filer, which authorizes it and mints the
// volume credential itself. The AssignVolume token is not a filer
// credential and gets the caller nowhere here.
if uploadOption.FilerJwt != nil {
uploadOption.Jwt = uploadOption.FilerJwt(true)
} else {
uploadOption.Jwt = security.EncodedJwt(util_http.JwtForFilerServer(true))
}
uploadOption.Jwt = security.EncodedJwt(util_http.JwtForFilerServer(true))
}
uploadResult, err = uploader.retriedUploadData(context.Background(), data, uploadOption)
-1
View File
@@ -380,7 +380,6 @@ message ErasureCodingTaskConfig {
string collection_filter = 4; // Only process volumes from specific collections
repeated string preferred_tags = 5; // Disk tags to prioritize for EC shard placement
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
bool strict_placement = 7; // fail planning instead of relaxing placement constraints
}
// BalanceTaskConfig contains balance-specific configuration
+2 -11
View File
@@ -2980,7 +2980,6 @@ type ErasureCodingTaskConfig struct {
CollectionFilter string `protobuf:"bytes,4,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Only process volumes from specific collections
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Disk tags to prioritize for EC shard placement
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
StrictPlacement bool `protobuf:"varint,7,opt,name=strict_placement,json=strictPlacement,proto3" json:"strict_placement,omitempty"` // fail planning instead of relaxing placement constraints
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -3057,13 +3056,6 @@ func (x *ErasureCodingTaskConfig) GetReplicaPlacement() string {
return ""
}
func (x *ErasureCodingTaskConfig) GetStrictPlacement() bool {
if x != nil {
return x.StrictPlacement
}
return false
}
// BalanceTaskConfig contains balance-specific configuration
type BalanceTaskConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -4293,15 +4285,14 @@ const file_worker_proto_rawDesc = "" +
"\x10VacuumTaskConfig\x12+\n" +
"\x11garbage_threshold\x18\x01 \x01(\x01R\x10garbageThreshold\x12/\n" +
"\x14min_volume_age_hours\x18\x02 \x01(\x05R\x11minVolumeAgeHours\x120\n" +
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\xc5\x02\n" +
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\x9a\x02\n" +
"\x17ErasureCodingTaskConfig\x12%\n" +
"\x0efullness_ratio\x18\x01 \x01(\x01R\rfullnessRatio\x12*\n" +
"\x11quiet_for_seconds\x18\x02 \x01(\x05R\x0fquietForSeconds\x12+\n" +
"\x12min_volume_size_mb\x18\x03 \x01(\x05R\x0fminVolumeSizeMb\x12+\n" +
"\x11collection_filter\x18\x04 \x01(\tR\x10collectionFilter\x12%\n" +
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\x12)\n" +
"\x10strict_placement\x18\a \x01(\bR\x0fstrictPlacement\"\x9b\x01\n" +
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"\x9b\x01\n" +
"\x11BalanceTaskConfig\x12/\n" +
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\x12+\n" +
-15
View File
@@ -125,21 +125,6 @@ func ReadIntConfig(values map[string]*plugin_pb.ConfigValue, field string, fallb
return int(v)
}
// ReadBoolConfig reads a bool-valued plugin config field.
func ReadBoolConfig(values map[string]*plugin_pb.ConfigValue, field string, fallback bool) bool {
if values == nil {
return fallback
}
value := values[field]
if value == nil {
return fallback
}
if kind, ok := value.Kind.(*plugin_pb.ConfigValue_BoolValue); ok {
return kind.BoolValue
}
return fallback
}
// ReadBytesConfig reads a bytes-valued plugin config field, returning nil when
// the value is missing or of a different kind.
func ReadBytesConfig(values map[string]*plugin_pb.ConfigValue, field string) []byte {
@@ -195,7 +195,7 @@ func (fs *FilerSink) replicateOneManifestChunk(ctx context.Context, sourceChunk
resolveName := fmt.Sprintf("resolve manifest %s", sourceChunk.GetFileIdString())
missingGate := fs.newMissingSourceChunkGate(sourceChunk.GetFileIdString())
err := util.RetryUntil(resolveName, func() error {
rc, e := filer.ResolveOneChunkManifestWithFilerJwt(ctx, fs.filerSource.LookupFileId, fs.filerSource.FilerJwt(), sourceChunk, nil)
rc, e := filer.ResolveOneChunkManifest(ctx, fs.filerSource.LookupFileId, sourceChunk, nil)
if e != nil {
return e
}
@@ -315,7 +315,6 @@ func (fs *FilerSink) uploadManifestChunk(path string, sourceMtimeNs int64, sourc
}
if fs.writeChunkByFiler {
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(fs.address)
uploadOption.FilerJwt = fs.jwtForFiler
}
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
fs,
@@ -436,7 +435,6 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string,
}
if fs.writeChunkByFiler {
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(fs.address)
uploadOption.FilerJwt = fs.jwtForFiler
}
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
fs,
+4 -11
View File
@@ -62,7 +62,6 @@ type FilerSink struct {
signature int32
activeTransfers sync.Map // chunkFileId -> *ChunkTransferStatus
uploader *operation.Uploader
jwtForFiler security.FilerJwtProvider
// lastServedFileId is the most recent chunk the source did serve, the probe
// sourceStillServesChunks re-checks before writing an entry off.
lastServedFileId atomic.Pointer[string]
@@ -117,12 +116,6 @@ func (fs *FilerSink) SetUploader(uploader *operation.Uploader) {
fs.uploader = uploader
}
// SetFilerJwtProvider sets the filer API credential for proxied chunk writes.
// Must be called during initialization, before any replication goroutines start.
func (fs *FilerSink) SetFilerJwtProvider(provider security.FilerJwtProvider) {
fs.jwtForFiler = provider
}
func (fs *FilerSink) getUploader() (*operation.Uploader, error) {
if fs.uploader != nil {
return fs.uploader, nil
@@ -365,7 +358,7 @@ func (fs *FilerSink) UpdateEntry(key string, oldEntry *filer_pb.Entry, newParent
existingEntry.RemoteEntry = newEntry.RemoteEntry
default:
// source-side chunks resolve via source filer; sink volume IDs may collide.
deletedChunks, newChunks, err := compareChunks(context.Background(), filer.LookupFn(fs.filerSource), fs.filerSource.FilerJwt(), oldEntry, newEntry)
deletedChunks, newChunks, err := compareChunks(context.Background(), filer.LookupFn(fs.filerSource), oldEntry, newEntry)
if err != nil {
return true, fmt.Errorf("replicate %s compare chunks error: %w", key, err)
}
@@ -411,12 +404,12 @@ func (fs *FilerSink) UpdateEntry(key string, oldEntry *filer_pb.Entry, newParent
})
}
func compareChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, filerJwtFn security.FilerJwtProvider, oldEntry, newEntry *filer_pb.Entry) (deletedChunks, newChunks []*filer_pb.FileChunk, err error) {
aData, aMeta, aErr := filer.ResolveChunkManifestWithFilerJwt(ctx, lookupFileIdFn, filerJwtFn, oldEntry.GetChunks(), 0, math.MaxInt64, nil)
func compareChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, oldEntry, newEntry *filer_pb.Entry) (deletedChunks, newChunks []*filer_pb.FileChunk, err error) {
aData, aMeta, aErr := filer.ResolveChunkManifest(ctx, lookupFileIdFn, oldEntry.GetChunks(), 0, math.MaxInt64, nil)
if aErr != nil {
return nil, nil, aErr
}
bData, bMeta, bErr := filer.ResolveChunkManifestWithFilerJwt(ctx, lookupFileIdFn, filerJwtFn, newEntry.GetChunks(), 0, math.MaxInt64, nil)
bData, bMeta, bErr := filer.ResolveChunkManifest(ctx, lookupFileIdFn, newEntry.GetChunks(), 0, math.MaxInt64, nil)
if bErr != nil {
return nil, nil, bErr
}
+1 -16
View File
@@ -34,7 +34,6 @@ type FilerSource struct {
dataCenter string
signature int32
httpClient *util_http_client.HTTPClient
jwtForFiler security.FilerJwtProvider
}
func (fs *FilerSource) Initialize(configuration util.Configuration, prefix string) error {
@@ -68,16 +67,6 @@ func (fs *FilerSource) SetHttpClient(client *util_http_client.HTTPClient) {
fs.httpClient = client
}
func (fs *FilerSource) SetFilerJwtProvider(provider security.FilerJwtProvider) {
fs.jwtForFiler = provider
}
// FilerJwt returns the side-specific filer API credential, or nil when the
// process-wide jwt.filer_signing configuration applies.
func (fs *FilerSource) FilerJwt() security.FilerJwtProvider {
return fs.jwtForFiler
}
func (fs *FilerSource) LookupFileId(ctx context.Context, part string) (fileUrls []string, err error) {
vid2Locations := make(map[string]*filer_pb.Locations)
@@ -137,11 +126,7 @@ func (fs *FilerSource) ReadPart(fileId string, offset int64) (filename string, h
if fs.proxyByFiler {
fileUrl := util_http.ProxyChunkUrl(fs.address, fileId)
jwt := util_http.JwtForFilerServer(false)
if fs.jwtForFiler != nil {
jwt = string(fs.jwtForFiler(false))
}
filename, header, resp, err = downloadFn(fileUrl, jwt, offset)
filename, header, resp, err = downloadFn(fileUrl, util_http.JwtForFilerServer(false), offset)
if err == nil {
err = readPartStatusError(fileUrl, resp)
}
+2 -6
View File
@@ -46,12 +46,8 @@ import (
//
// returns signature, error otherwise if the signature mismatches or any other
// error while parsing and validating.
//
// Only the signature is verified here. The request was already authorized by
// the Auth middleware, which also evaluates bucket policies; re-running the
// permission check here does not, and would deny what the middleware allowed.
func (iam *IdentityAccessManagement) calculateSeedSignature(r *http.Request) (cred *Credential, signature string, region string, service string, date time.Time, errCode s3err.ErrorCode) {
_, credential, calculatedSignature, authInfo, errCode := iam.verifyV4Signature(r, false)
_, credential, calculatedSignature, authInfo, errCode := iam.verifyV4Signature(r, true)
if errCode != s3err.ErrNone {
return nil, "", "", "", time.Time{}, errCode
}
@@ -105,7 +101,7 @@ func (iam *IdentityAccessManagement) newChunkedReader(req *http.Request) (io.Rea
// carry no header seed, and verifyV4Signature would fail parsing them.
if isRequestSignatureV4(req) {
// We do not need to pass the seed signature to the Reader as each chunk is not signed,
// but we do compute it to verify the request's signature.
// but we do compute it to verify the caller has the correct permissions.
_, _, _, _, _, errCode = iam.calculateSeedSignature(req)
if errCode != s3err.ErrNone {
return nil, errCode
@@ -1,89 +0,0 @@
package s3api
import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
"sync"
"testing"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/require"
)
const (
bpcBucket = "policy-bucket"
bpcObject = "incoming/part.bin"
bpcAccessKey = "LOCALPOLICYKEY000001"
bpcSecretKey = "local-policy-secret-for-loopback-only"
bpcIdentityName = "policy-writer"
bpcAccountID = "000000000000"
)
// An identity with credentials and nothing else, plus a bucket policy that lets it put objects.
func newBucketPolicyOnlyIAM(t *testing.T) *IdentityAccessManagement {
t.Helper()
iam := &IdentityAccessManagement{
hashes: make(map[string]*sync.Pool),
hashCounters: make(map[string]*int32),
}
err := iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
Accounts: []*iam_pb.Account{{Id: bpcAccountID, DisplayName: bpcIdentityName}},
Identities: []*iam_pb.Identity{{
Name: bpcIdentityName,
Account: &iam_pb.Account{Id: bpcAccountID, DisplayName: bpcIdentityName},
Credentials: []*iam_pb.Credential{{AccessKey: bpcAccessKey, SecretKey: bpcSecretKey}},
}},
})
require.NoError(t, err)
policy := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:user/%s"},
"Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"}]}`, bpcAccountID, bpcIdentityName, bpcBucket)
engine := NewBucketPolicyEngine()
require.NoError(t, engine.engine.SetBucketPolicy(bpcBucket, policy))
iam.policyEngine = engine
return iam
}
// A SigV4 PutObject whose body is aws-chunked with an unsigned payload and a CRC32 trailer.
func bpcStreamingPut(t *testing.T, secretKey string) *http.Request {
t.Helper()
payload := generateStreamingUnsignedPayloadTrailerPayload(true)
urlStr := fmt.Sprintf("http://127.0.0.1:9000/%s/%s", bpcBucket, bpcObject)
req := mustNewRequest(http.MethodPut, urlStr, int64(len(payload)), bytes.NewReader([]byte(payload)), t)
req.Header.Set("Content-Encoding", "aws-chunked")
req.Header.Set("x-amz-decoded-content-length", "17408")
req.Header.Set("x-amz-content-sha256", streamingUnsignedPayload)
req.Header.Set("x-amz-trailer", "x-amz-checksum-crc32")
require.NoError(t, signRequestV4(req, bpcAccessKey, secretKey))
return mux.SetURLVars(req, map[string]string{"bucket": bpcBucket, "object": bpcObject})
}
func TestChunkedReaderDoesNotReauthorizeBucketPolicyPrincipal(t *testing.T) {
iam := newBucketPolicyOnlyIAM(t)
// The middleware authorizes the write through the bucket policy.
req := bpcStreamingPut(t, bpcSecretKey)
identity, errCode := iam.authRequest(req, s3_constants.ACTION_WRITE)
require.Equal(t, s3err.ErrNone, errCode, "the bucket policy must allow the PutObject")
require.NotNil(t, identity)
require.Empty(t, identity.Actions)
require.Empty(t, identity.PolicyNames)
// The handler then builds the body reader for the same request.
reader, errCode := iam.newChunkedReader(req)
require.Equal(t, s3err.ErrNone, errCode, "the chunked reader must not deny what the middleware allowed")
data, err := io.ReadAll(reader)
require.NoError(t, err)
require.Equal(t, strings.Repeat("a", 17408), string(data))
// The seed signature is still verified.
_, errCode = iam.newChunkedReader(bpcStreamingPut(t, "not-the-secret"))
require.Equal(t, s3err.ErrSignatureDoesNotMatch, errCode)
}
+1 -1
View File
@@ -398,7 +398,7 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
glog.V(1).Infof("Iceberg: failed to cleanup metadata file %s after update failure: %v", newMetadataLocation, cleanupErr)
}
glog.Errorf("Iceberg: CommitTable UpdateTable error: %v", err)
writeManagerError(w, err)
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to commit table update: "+err.Error())
return
}
}
+1 -1
View File
@@ -110,7 +110,7 @@ func (s *Server) handleCommitTransaction(w http.ResponseWriter, r *http.Request)
return
}
glog.Errorf("Iceberg: CommitTransaction UpdateTable error: %v", err)
writeManagerError(w, err)
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to commit table update: "+err.Error())
return
}
}
@@ -58,12 +58,6 @@ func TestWriteManagerError(t *testing.T) {
// say how to name a real one.
wantMessage: []string{"table bucket warehouse not found", "warehouse=s3://<table-bucket>/", "/v1/<table-bucket>/"},
},
{
name: "denied catalog write is forbidden, not a server fault",
err: &s3tables.S3TablesError{Type: s3tables.ErrCodeAccessDenied, Message: "not authorized to update table"},
wantCode: http.StatusForbidden,
wantType: "ForbiddenException",
},
{name: "everything else is a server fault", err: fmt.Errorf("all filers failed, last error: connection refused"), wantCode: http.StatusInternalServerError, wantType: "InternalServerError"},
}
for _, c := range cases {
+16 -71
View File
@@ -1,7 +1,6 @@
package s3api
import (
"errors"
"fmt"
"net/http"
@@ -116,26 +115,6 @@ func validateSSEKMSCopyRequirements(srcMetadata map[string][]byte, headers http.
// validateEncryptionCompatibility validates that encryption methods are not conflicting
func validateEncryptionCompatibility(headers http.Header) error {
// A repeated header is rejected rather than deduped: the encryption paths
// apply only the first value, so extra values could hide the method the
// client actually asked for.
for _, name := range []string{
s3_constants.AmzServerSideEncryption,
s3_constants.AmzServerSideEncryptionCustomerAlgorithm,
s3_constants.AmzServerSideEncryptionCustomerKey,
s3_constants.AmzServerSideEncryptionCustomerKeyMD5,
s3_constants.AmzServerSideEncryptionAwsKmsKeyId,
s3_constants.AmzServerSideEncryptionContext,
s3_constants.AmzServerSideEncryptionBucketKeyEnabled,
} {
if len(headers.Values(name)) > 1 {
return &CopyValidationError{
Code: s3err.ErrInvalidRequest,
Message: fmt.Sprintf("Multiple %s headers specified - only one is allowed", name),
}
}
}
sseAlgorithm := headers.Get(s3_constants.AmzServerSideEncryption)
hasSSEC := hasSSECHeaders(headers)
hasSSEKMS := sseAlgorithm == s3_constants.SSEAlgorithmKMS
@@ -150,25 +129,19 @@ func validateEncryptionCompatibility(headers http.Header) error {
}
}
// KMS options only apply to aws:kms; with another method or none they name
// no method at all.
if !hasSSEKMS && hasHeaderValue(headers,
s3_constants.AmzServerSideEncryptionAwsKmsKeyId,
s3_constants.AmzServerSideEncryptionContext,
s3_constants.AmzServerSideEncryptionBucketKeyEnabled) {
return &CopyValidationError{
Code: s3err.ErrInvalidRequest,
Message: "KMS encryption options require the aws:kms encryption method",
}
// Count how many encryption methods are specified
encryptionCount := 0
if hasSSEC {
encryptionCount++
}
if hasSSEKMS {
encryptionCount++
}
if hasSSES3 {
encryptionCount++
}
// Only one encryption method should be specified
encryptionCount := 0
for _, specified := range []bool{hasSSEC, hasSSEKMS, hasSSES3} {
if specified {
encryptionCount++
}
}
if encryptionCount > 1 {
return &CopyValidationError{
Code: s3err.ErrInvalidRequest,
@@ -179,21 +152,6 @@ func validateEncryptionCompatibility(headers http.Header) error {
return nil
}
// ValidateRequestEncryption rejects PutObject or CreateMultipartUpload
// encryption headers that no single method can honor, with the InvalidArgument
// codes S3 returns for them.
func ValidateRequestEncryption(headers http.Header) s3err.ErrorCode {
err := validateEncryptionCompatibility(headers)
if err == nil {
return s3err.ErrNone
}
var validationErr *CopyValidationError
if errors.As(err, &validationErr) && validationErr.Code == s3err.ErrInvalidEncryptionAlgorithm {
return s3err.ErrInvalidEncryptionMethod
}
return s3err.ErrIncompatibleEncryptionMethod
}
// validateSSECCopyHeaderCompleteness validates that all required SSE-C copy headers are present
func validateSSECCopyHeaderCompleteness(headers http.Header) error {
algorithm := headers.Get(s3_constants.AmzCopySourceServerSideEncryptionCustomerAlgorithm)
@@ -271,29 +229,16 @@ func validateSSECHeaderCompleteness(headers http.Header) error {
}
// Helper functions for header detection
func hasHeaderValue(headers http.Header, names ...string) bool {
for _, name := range names {
for _, value := range headers.Values(name) {
if value != "" {
return true
}
}
}
return false
}
func hasSSECCopyHeaders(headers http.Header) bool {
return hasHeaderValue(headers,
s3_constants.AmzCopySourceServerSideEncryptionCustomerAlgorithm,
s3_constants.AmzCopySourceServerSideEncryptionCustomerKey,
s3_constants.AmzCopySourceServerSideEncryptionCustomerKeyMD5)
return headers.Get(s3_constants.AmzCopySourceServerSideEncryptionCustomerAlgorithm) != "" ||
headers.Get(s3_constants.AmzCopySourceServerSideEncryptionCustomerKey) != "" ||
headers.Get(s3_constants.AmzCopySourceServerSideEncryptionCustomerKeyMD5) != ""
}
func hasSSECHeaders(headers http.Header) bool {
return hasHeaderValue(headers,
s3_constants.AmzServerSideEncryptionCustomerAlgorithm,
s3_constants.AmzServerSideEncryptionCustomerKey,
s3_constants.AmzServerSideEncryptionCustomerKeyMD5)
return headers.Get(s3_constants.AmzServerSideEncryptionCustomerAlgorithm) != "" ||
headers.Get(s3_constants.AmzServerSideEncryptionCustomerKey) != "" ||
headers.Get(s3_constants.AmzServerSideEncryptionCustomerKeyMD5) != ""
}
// validateEncryptionContext validates the encryption context header format
-107
View File
@@ -1,107 +0,0 @@
package s3api
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
)
// TestValidateRequestEncryption verifies that a PutObject or
// CreateMultipartUpload request asking for an encryption method that cannot be
// honored is rejected instead of being stored unencrypted
func TestValidateRequestEncryption(t *testing.T) {
ssec := map[string]string{
s3_constants.AmzServerSideEncryptionCustomerAlgorithm: "AES256",
s3_constants.AmzServerSideEncryptionCustomerKey: "a2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2s=",
s3_constants.AmzServerSideEncryptionCustomerKeyMD5: "f6OQvGsmFBq4WOqaVcuO5w==",
}
testCases := []struct {
name string
headers map[string]string
sse string
sseValues []string
dup string
want s3err.ErrorCode
}{
{name: "no encryption", want: s3err.ErrNone},
{name: "SSE-S3", sse: s3_constants.SSEAlgorithmAES256, want: s3err.ErrNone},
{name: "SSE-KMS", sse: s3_constants.SSEAlgorithmKMS, want: s3err.ErrNone},
{name: "SSE-C", headers: ssec, want: s3err.ErrNone},
{name: "unknown algorithm", sse: "aes:kms", want: s3err.ErrInvalidEncryptionMethod},
{name: "misspelled AES256", sse: "AES-256", want: s3err.ErrInvalidEncryptionMethod},
{name: "SSE-C and SSE-S3", headers: ssec, sse: s3_constants.SSEAlgorithmAES256, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "SSE-C and SSE-KMS", headers: ssec, sse: s3_constants.SSEAlgorithmKMS, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "repeated algorithm header", sseValues: []string{"AES256", "aws:kms"}, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "repeated identical algorithm", sseValues: []string{"AES256", "AES256"}, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "empty value before KMS", sseValues: []string{"", "aws:kms"}, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "SSE-S3 hidden behind empty value", sseValues: []string{"", "AES256"}, headers: ssec, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "repeated SSE-C key header", headers: ssec, dup: s3_constants.AmzServerSideEncryptionCustomerKey, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "repeated KMS key id", sse: s3_constants.SSEAlgorithmKMS, dup: s3_constants.AmzServerSideEncryptionAwsKmsKeyId, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "SSE-S3 with KMS key id", sse: s3_constants.SSEAlgorithmAES256, headers: map[string]string{s3_constants.AmzServerSideEncryptionAwsKmsKeyId: "key-id"}, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "KMS key id without method", headers: map[string]string{s3_constants.AmzServerSideEncryptionAwsKmsKeyId: "key-id"}, want: s3err.ErrIncompatibleEncryptionMethod},
{name: "KMS key id with aws:kms", sse: s3_constants.SSEAlgorithmKMS, headers: map[string]string{s3_constants.AmzServerSideEncryptionAwsKmsKeyId: "key-id"}, want: s3err.ErrNone},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
h := http.Header{}
for k, v := range tc.headers {
h.Set(k, v)
}
if tc.sse != "" {
h.Set(s3_constants.AmzServerSideEncryption, tc.sse)
}
for _, v := range tc.sseValues {
h.Add(s3_constants.AmzServerSideEncryption, v)
}
if tc.dup != "" {
h.Add(tc.dup, "first")
h.Add(tc.dup, "second")
}
assert.Equal(t, tc.want, ValidateRequestEncryption(h))
})
}
}
// TestDirectoryMarkerSSEC verifies marker content stored under SSE-C encrypts
// on write and decrypts on read through the stored entry metadata
func TestDirectoryMarkerSSEC(t *testing.T) {
ssecHeaders := func(r *http.Request) {
r.Header.Set(s3_constants.AmzServerSideEncryptionCustomerAlgorithm, "AES256")
r.Header.Set(s3_constants.AmzServerSideEncryptionCustomerKey, "a2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2s=")
r.Header.Set(s3_constants.AmzServerSideEncryptionCustomerKeyMD5, "mT2HRsMGJ5IX5C+0rreZ8Q==")
}
plaintext := []byte("directory marker content")
s3a := &S3ApiServer{}
putReq := httptest.NewRequest(http.MethodPut, "/bucket/dir/", nil)
ssecHeaders(putReq)
sseResult, errCode := s3a.handleAllSSEEncryption(putReq, bytes.NewReader(plaintext), 0)
assert.Equal(t, s3err.ErrNone, errCode)
encrypted, err := io.ReadAll(sseResult.DataReader)
assert.NoError(t, err)
assert.NotEqual(t, plaintext, encrypted)
entry := &filer_pb.Entry{Extended: map[string][]byte{}, Content: encrypted}
storeSSEMetadata(entry, sseResult)
sseType := s3a.detectPrimarySSEType(entry)
assert.Equal(t, s3_constants.SSETypeC, sseType)
getReq := httptest.NewRequest(http.MethodGet, "/bucket/dir/", nil)
ssecHeaders(getReq)
decrypted, errCode := s3a.decryptDirectoryContent(getReq, entry, sseType)
assert.Equal(t, s3err.ErrNone, errCode)
assert.Equal(t, plaintext, decrypted)
bareReq := httptest.NewRequest(http.MethodGet, "/bucket/dir/", nil)
_, errCode = s3a.decryptDirectoryContent(bareReq, entry, sseType)
assert.Equal(t, s3err.ErrSSECustomerKeyMissing, errCode)
}
+6 -126
View File
@@ -465,7 +465,7 @@ func (s3a *S3ApiServer) resolveObjectEntry(bucket, object, versionId string) (*f
}
// serveDirectoryContent serves the content of a directory object directly
func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, bucket, object string) {
func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry) {
// Defensive nil checks - entry and attributes should never be nil, but guard against it
if entry == nil || entry.Attributes == nil {
glog.Errorf("serveDirectoryContent: entry or attributes is nil")
@@ -473,52 +473,10 @@ func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Req
return
}
// A directory promoted over an uploaded object still holds that object's
// chunks while entry.Content stays empty; GET streams them like a regular
// object so it delivers the bytes HEAD reports for this entry.
if r.Method != http.MethodHead && len(entry.Content) == 0 && len(entry.Chunks) > 0 {
sseType := s3a.detectPrimarySSEType(entry)
if err := s3a.streamFromVolumeServersWithSSE(w, r, entry, sseType, bucket, object, ""); err != nil {
var streamErr *StreamError
if errors.As(err, &streamErr) && streamErr.ResponseWritten {
return
}
if isCanceledStreamingError(err) {
glog.V(3).Infof("serveDirectoryContent: client disconnected while streaming %s/%s: %v", bucket, object, err)
return
}
glog.Errorf("serveDirectoryContent: failed to stream %s/%s: %v", bucket, object, err)
if errors.Is(err, util_http.ErrTooManyRequests) {
s3err.WriteErrorResponse(w, r, s3err.ErrRequestBytesExceed)
} else if shouldWriteStreamingErrorResponse(err) {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
}
}
return
}
// Set content type - use stored MIME type or default. A directory without a stored
// mime and without data of its own answers application/x-directory, the marker type
// Hadoop-style clients (e.g. flink-s3-fs-presto) require to classify the path as a
// directory; defaulting to octet-stream makes them treat it as a 0-byte file.
// Marker content may be stored encrypted; decrypt before serving. HEAD
// returns no body, so it only checks access and skips decryption — and
// any KMS call — entirely.
content := entry.Content
sseType := s3a.detectPrimarySSEType(entry)
if sseType != "" && sseType != "None" {
var errCode s3err.ErrorCode
if r.Method == http.MethodHead {
errCode = s3a.checkDirectorySSEAccess(r, entry, sseType)
} else {
content, errCode = s3a.decryptDirectoryContent(r, entry, sseType)
}
if errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
}
contentType := entry.Attributes.Mime
if contentType == "" {
if entry.IsDirectoryKeyObject() {
@@ -529,10 +487,8 @@ func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Req
}
w.Header().Set("Content-Type", contentType)
contentLength := int64(len(content))
if r.Method == http.MethodHead && len(entry.Chunks) > 0 {
contentLength = int64(entry.Attributes.FileSize)
}
// Set content length - use FileSize for accuracy, especially for large files
contentLength := int64(entry.Attributes.FileSize)
w.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
// Set last modified
@@ -541,8 +497,6 @@ func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Req
// Set ETag
w.Header().Set("ETag", "\""+filer.ETag(entry)+"\"")
s3a.addSSEResponseHeadersFromEntry(w, r, entry, sseType)
// For HEAD requests, don't write body
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
@@ -551,87 +505,13 @@ func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Req
// Write content
w.WriteHeader(http.StatusOK)
if len(content) > 0 {
if _, err := w.Write(content); err != nil {
if len(entry.Content) > 0 {
if _, err := w.Write(entry.Content); err != nil {
glog.Errorf("serveDirectoryContent: failed to write response: %v", err)
}
}
}
// decryptDirectoryContent returns the plaintext of a directory marker's inline
// entry.Content, which PutObjectHandler stores through the shared SSE path.
func (s3a *S3ApiServer) decryptDirectoryContent(r *http.Request, entry *filer_pb.Entry, sseType string) ([]byte, s3err.ErrorCode) {
var reader io.Reader
var err error
switch sseType {
case s3_constants.SSETypeC:
customerKey, parseErr := ParseSSECHeaders(r)
if parseErr != nil {
return nil, MapSSECErrorToS3Error(parseErr)
}
if customerKey == nil {
return nil, s3err.ErrSSECustomerKeyMissing
}
if storedKeyMD5 := string(entry.Extended[s3_constants.AmzServerSideEncryptionCustomerKeyMD5]); storedKeyMD5 != "" && customerKey.KeyMD5 != storedKeyMD5 {
return nil, s3err.ErrAccessDenied
}
iv, ivErr := GetSSECIVFromMetadata(entry.Extended)
if ivErr != nil {
return nil, s3err.ErrInternalError
}
reader, err = CreateSSECDecryptedReader(bytes.NewReader(entry.Content), customerKey, iv)
case s3_constants.SSETypeKMS:
sseKMSKey, deserErr := DeserializeSSEKMSMetadata(entry.Extended[s3_constants.SeaweedFSSSEKMSKey])
if deserErr != nil {
return nil, s3err.ErrInternalError
}
reader, err = CreateSSEKMSDecryptedReader(bytes.NewReader(entry.Content), sseKMSKey)
case s3_constants.SSETypeS3:
keyManager := GetSSES3KeyManager()
sseS3Key, deserErr := DeserializeSSES3Metadata(entry.Extended[s3_constants.SeaweedFSSSES3Key], keyManager)
if deserErr != nil {
return nil, s3err.ErrInternalError
}
iv, ivErr := GetSSES3IV(entry, sseS3Key, keyManager)
if ivErr != nil {
return nil, s3err.ErrInternalError
}
reader, err = CreateSSES3DecryptedReader(bytes.NewReader(entry.Content), sseS3Key, iv)
default:
return entry.Content, s3err.ErrNone
}
if err != nil {
glog.Errorf("decryptDirectoryContent: %v", err)
return nil, s3err.ErrInternalError
}
content, readErr := io.ReadAll(reader)
if readErr != nil {
glog.Errorf("decryptDirectoryContent: %v", readErr)
return nil, s3err.ErrInternalError
}
return content, s3err.ErrNone
}
// checkDirectorySSEAccess runs the request-level checks a HEAD of an encrypted
// marker needs: SSE-C requires the customer key to parse and to match the key
// the marker was written with; SSE-KMS and SSE-S3 need nothing from the caller.
func (s3a *S3ApiServer) checkDirectorySSEAccess(r *http.Request, entry *filer_pb.Entry, sseType string) s3err.ErrorCode {
if sseType != s3_constants.SSETypeC {
return s3err.ErrNone
}
customerKey, parseErr := ParseSSECHeaders(r)
if parseErr != nil {
return MapSSECErrorToS3Error(parseErr)
}
if customerKey == nil {
return s3err.ErrSSECustomerKeyMissing
}
if storedKeyMD5 := string(entry.Extended[s3_constants.AmzServerSideEncryptionCustomerKeyMD5]); storedKeyMD5 != "" && customerKey.KeyMD5 != storedKeyMD5 {
return s3err.ErrAccessDenied
}
return s3err.ErrNone
}
// handleDirectoryObjectRequest is a helper function that handles directory object requests
// for both GET and HEAD operations, eliminating code duplication
func (s3a *S3ApiServer) handleDirectoryObjectRequest(w http.ResponseWriter, r *http.Request, bucket, object, handlerName string) bool {
@@ -658,7 +538,7 @@ func (s3a *S3ApiServer) handleDirectoryObjectRequest(w http.ResponseWriter, r *h
return true // Request was handled (denied)
}
glog.V(2).Infof("%s: directory object %s/%s found, serving content", handlerName, bucket, object)
s3a.serveDirectoryContent(w, r, dirEntry, bucket, object)
s3a.serveDirectoryContent(w, r, dirEntry)
return true // Request was handled successfully
} else if isDirectoryObject {
// Directory object but doesn't exist
+1 -1
View File
@@ -38,7 +38,7 @@ func TestServeDirectoryContentContentType(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodHead, "/bucket/dir/", nil)
rec := httptest.NewRecorder()
s3a.serveDirectoryContent(rec, req, tt.entry, "bucket", "dir/")
s3a.serveDirectoryContent(rec, req, tt.entry)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
+9 -36
View File
@@ -780,12 +780,6 @@ type ListingCursor struct {
// something to find once a bucket has version history to leave behind.
hideDeletedPrefixes bool
probedEntries int
// probeBudget overrides hiddenProbeBudget for the per-prefix probe; 0 means use
// the package default. Tests set this to a small value to stay fast.
probeBudget int
// probeTotalBudget overrides hiddenProbeTotalBudget for the request-wide probe
// ceiling; 0 means use the package default.
probeTotalBudget int
// retractEntry undoes the listing of a base-path null object once its .versions
// sibling reveals that the current version is a delete marker.
retractEntry func(dir, name string)
@@ -1167,16 +1161,12 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
}
}
// hiddenProbePageSize is the window one probe request asks the filer for.
// hiddenProbeBudget caps how many entries one prefix's probe may scan; it
// resets for every candidate prefix so one large all-deleted subtree cannot
// exhaust the allowance for later prefixes. hiddenProbeTotalBudget caps the
// scanned entries a single listing request spends on probing overall, since a
// page may still walk an unbounded number of all-deleted prefixes.
// hiddenProbePageSize is the window one probe request asks the filer for, and
// hiddenProbeBudget caps how many entries a single list request may look at while
// deciding which directories still stand for a prefix.
const (
hiddenProbePageSize = 64
hiddenProbeBudget = 10000
hiddenProbeTotalBudget = 100000
hiddenProbePageSize = 64
hiddenProbeBudget = 10000
)
// dirHoldsOnlyHiddenEntries reports whether dir holds entries but none that a
@@ -1189,29 +1179,13 @@ const (
//
// The scan stops at the first key it finds, so a populated prefix costs one ListEntries
// answered by its first entry. A subtree that is entirely delete-marked costs a walk of
// that subtree, bounded by hiddenProbeBudget entries per prefix. The budget resets for
// each candidate prefix, so a large all-deleted subtree cannot exhaust the allowance
// for later prefixes in the same request.
// that subtree, bounded by the request's probe budget; once the budget is spent the
// prefix is reported, as it was before this check existed.
func (s3a *S3ApiServer) dirHoldsOnlyHiddenEntries(ctx context.Context, client filer_pb.SeaweedFilerClient, bucket, dir string, cursor *ListingCursor) bool {
if !cursor.hideDeletedPrefixes {
return false
}
budget := hiddenProbeBudget
if cursor.probeBudget > 0 {
budget = cursor.probeBudget
}
totalBudget := hiddenProbeTotalBudget
if cursor.probeTotalBudget > 0 {
totalBudget = cursor.probeTotalBudget
}
return s3a.dirHoldsOnlyHiddenEntriesInner(ctx, client, bucket, dir, &budget, totalBudget, cursor)
}
// dirHoldsOnlyHiddenEntriesInner is the recursive body of dirHoldsOnlyHiddenEntries.
// budget is shared across the recursive descent for one prefix but reset by the
// caller for each top-level prefix, preventing cross-prefix budget exhaustion.
// cursor.probedEntries bounds the total work one listing request spends probing.
func (s3a *S3ApiServer) dirHoldsOnlyHiddenEntriesInner(ctx context.Context, client filer_pb.SeaweedFilerClient, bucket, dir string, budget *int, totalBudget int, cursor *ListingCursor) bool {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
@@ -1253,9 +1227,8 @@ func (s3a *S3ApiServer) dirHoldsOnlyHiddenEntriesInner(ctx context.Context, clie
startFrom = entry.Name
sawEntry = true
*budget--
cursor.probedEntries++
if *budget < 0 || cursor.probedEntries > totalBudget {
if cursor.probedEntries > hiddenProbeBudget {
return false
}
@@ -1296,7 +1269,7 @@ func (s3a *S3ApiServer) dirHoldsOnlyHiddenEntriesInner(ctx context.Context, clie
if entry.IsDirectoryKeyObject() {
return false
}
if !s3a.dirHoldsOnlyHiddenEntriesInner(ctx, client, bucket, dir+"/"+entry.Name, budget, totalBudget, cursor) {
if !s3a.dirHoldsOnlyHiddenEntries(ctx, client, bucket, dir+"/"+entry.Name, cursor) {
return false
}
}
@@ -250,82 +250,3 @@ func TestDeletedPrefixesDoNotConsumeMaxKeys(t *testing.T) {
assert.False(t, cursor.isTruncated, "stepping over deleted prefixes must not truncate the page")
assert.Zero(t, cursor.maxKeys, "only the live prefixes may spend the page budget")
}
// TestPerPrefixBudgetNotShared is a regression test for the bug reported in issue #10847:
// one large all-deleted prefix exhausts the shared probe budget, causing every later
// prefix to be reported as visible even when all its objects are delete-marked.
//
// The fix gives each candidate prefix its own probe budget (hiddenProbeBudget, 10000 by
// default). The test sets cursor.probeBudget = 3 to stay fast without touching the
// package-level constant.
func TestPerPrefixBudgetNotShared(t *testing.T) {
// Build 5 delete-marked objects under "bigdeleted/" – more than the budget of 3.
bigDeletedEntries := make([]*filer_pb.Entry, 0, 5)
for i := 0; i < 5; i++ {
bigDeletedEntries = append(bigDeletedEntries, deleteMarkedVersionsDir(
"obj"+strconv.Itoa(i),
))
}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test": {
newDir("bigdeleted"),
newDir("emptydeleted"),
newDir("live"),
},
"/buckets/test/bigdeleted": bigDeletedEntries,
"/buckets/test/emptydeleted": {deleteMarkedVersionsDir("obj")},
"/buckets/test/live": {liveVersionsDir("obj")},
},
}
// probeBudget: 3 simulates the bug scenario with a tiny dataset; real default is
// hiddenProbeBudget (10000).
seen := listedNames(t, client, listDirectoryRequest{dir: "/buckets/test", delimiter: "/", bucket: "test"},
&ListingCursor{maxKeys: 1000, hideDeletedPrefixes: true, probeBudget: 3})
// "bigdeleted" exhausted its own probe budget, so it is reported rather than
// proven all-deleted.
assert.Contains(t, seen, "bigdeleted", "a prefix whose probe budget ran out must be reported")
// "emptydeleted" must be hidden: all its objects are delete-marked and its probe
// budget was not exhausted by "bigdeleted".
assert.NotContains(t, seen, "emptydeleted", "all-deleted prefix after a budget-exhausting prefix must still be hidden")
// "live" must always appear.
assert.Contains(t, seen, "live", "prefix with a live current version must be listed")
}
// TestPerRequestProbeBudgetStillBoundsWork covers the request-wide ceiling:
// deleted prefixes do not spend maxKeys, so a page can walk an unbounded
// number of them. Once probedEntries exceeds the request total, a later
// all-deleted prefix is reported rather than proven.
func TestPerRequestProbeBudgetStillBoundsWork(t *testing.T) {
deleted := func(n int) []*filer_pb.Entry {
entries := make([]*filer_pb.Entry, 0, n)
for i := 0; i < n; i++ {
entries = append(entries, deleteMarkedVersionsDir("obj"+strconv.Itoa(i)))
}
return entries
}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test": {
newDir("d1"),
newDir("d2"),
},
"/buckets/test/d1": deleted(4),
"/buckets/test/d2": deleted(4),
},
}
// Per-prefix budget (10) can cover either prefix alone, but the request
// total (5) is spent probing "d1", so "d2" is reported without a full scan.
seen := listedNames(t, client, listDirectoryRequest{dir: "/buckets/test", delimiter: "/", bucket: "test"},
&ListingCursor{maxKeys: 1000, hideDeletedPrefixes: true, probeBudget: 10, probeTotalBudget: 5})
assert.NotContains(t, seen, "d1", "a fully probed all-deleted prefix stays hidden")
assert.Contains(t, seen, "d2", "a prefix probed past the request total is reported")
}
@@ -40,12 +40,6 @@ func (s3a *S3ApiServer) NewMultipartUploadHandler(w http.ResponseWriter, r *http
return
}
// Reject before the auto-create check so a refused upload cannot leave a bucket behind
if errCode := ValidateRequestEncryption(r.Header); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
// Check if bucket exists, and create it if it doesn't (auto-create bucket)
if err := s3a.checkBucket(r, bucket); err == s3err.ErrNoSuchBucket {
// Auto-create bucket if it doesn't exist (requires Admin permission)
+27 -32
View File
@@ -127,11 +127,6 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
return
}
if errCode := ValidateRequestEncryption(r.Header); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
if r.Header.Get("Cache-Control") != "" {
if _, err = cacheobject.ParseRequestCacheControl(r.Header.Get("Cache-Control")); err != nil {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
@@ -220,18 +215,6 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
dirMd5 := md5.Sum(dirContent)
dirEtag := fmt.Sprintf("%x", dirMd5)
// SSE applies to marker content too — it is stored in entry.Content
sseResult, sseErrCode := s3a.handleAllSSEEncryption(r, bytes.NewReader(dirContent), 0)
if sseErrCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, sseErrCode)
return
}
if dirContent, err = io.ReadAll(sseResult.DataReader); err != nil {
glog.Errorf("PutObjectHandler: failed to encrypt directory marker content %s/%s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
glog.Infof("PutObjectHandler: explicit directory marker %s/%s (contentType=%q, len=%d)",
bucket, object, objectContentType, r.ContentLength)
// mkdir replaces this entry outright, so a lock recorded on the entry itself
@@ -270,8 +253,6 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
}
entry.Extended[s3_constants.ExtETagKey] = []byte(dirEtag)
storeSSEMetadata(entry, sseResult)
// Set object owner for directory objects (same as regular objects)
s3a.setObjectOwnerFromRequest(r, bucket, entry)
applyPutObjectACL(r, entry)
@@ -288,12 +269,6 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
s3err.WriteErrorResponse(w, r, markerCode)
return
}
sseRespMetadata := SSEResponseMetadata{SSEType: sseResult.SSEType}
if sseResult.SSEKMSKey != nil {
sseRespMetadata.KMSKeyID = sseResult.SSEKMSKey.KeyID
sseRespMetadata.BucketKeyEnabled = sseResult.SSEKMSKey.BucketKeyEnabled
}
s3a.setSSEResponseHeaders(w, r, sseRespMetadata)
setEtag(w, dirEtag)
} else {
// Get detailed versioning state for the bucket
@@ -602,12 +577,6 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
return "", s3err.ErrInternalError, SSEResponseMetadata{}
}
}
sseResult.SSEKMSKey = sseKMSKey
sseResult.SSEKMSMetadata = sseKMSMetadata
sseResult.SSES3Key = sseS3Key
sseResult.SSES3Metadata = sseS3Metadata
sseResult.SSEType = sseType
} else {
glog.V(4).Infof("putToFiler: explicit encryption already applied, skipping bucket default encryption")
}
@@ -943,7 +912,33 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
glog.V(3).Infof("putToFiler: stored %d tags from X-Amz-Tagging header", len(parsedTags))
}
storeSSEMetadata(entry, sseResult)
// Set SSE-C metadata
if customerKey != nil && len(sseIV) > 0 {
// Store IV as RAW bytes (matches filer behavior - filer decodes base64 headers and stores raw bytes)
entry.Extended[s3_constants.SeaweedFSSSEIV] = sseIV
entry.Extended[s3_constants.AmzServerSideEncryptionCustomerAlgorithm] = []byte("AES256")
entry.Extended[s3_constants.AmzServerSideEncryptionCustomerKeyMD5] = []byte(customerKey.KeyMD5)
glog.V(3).Infof("putToFiler: storing SSE-C metadata - IV len=%d", len(sseIV))
}
// Set SSE-KMS metadata
if sseKMSKey != nil {
// Store metadata as RAW bytes (matches filer behavior - filer decodes base64 headers and stores raw bytes)
entry.Extended[s3_constants.SeaweedFSSSEKMSKey] = sseKMSMetadata
// Set standard SSE headers for detection
entry.Extended[s3_constants.AmzServerSideEncryption] = []byte("aws:kms")
entry.Extended[s3_constants.AmzServerSideEncryptionAwsKmsKeyId] = []byte(sseKMSKey.KeyID)
glog.V(3).Infof("putToFiler: storing SSE-KMS metadata - keyID=%s, raw len=%d", sseKMSKey.KeyID, len(sseKMSMetadata))
}
// Set SSE-S3 metadata
if sseS3Key != nil && len(sseS3Metadata) > 0 {
// Store metadata as RAW bytes (matches filer behavior - filer decodes base64 headers and stores raw bytes)
entry.Extended[s3_constants.SeaweedFSSSES3Key] = sseS3Metadata
// Set standard SSE header for detection
entry.Extended[s3_constants.AmzServerSideEncryption] = []byte("AES256")
glog.V(3).Infof("putToFiler: storing SSE-S3 metadata - keyID=%s, raw len=%d", sseS3Key.KeyID, len(sseS3Metadata))
}
// Parts (object == "") stay flat: completion rebases chunk offsets, which
// manifest chunks cannot express.
+28 -119
View File
@@ -26,7 +26,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// ErrDeleteMarker is returned when the latest version is a delete marker (expected condition)
@@ -1851,34 +1850,20 @@ func (s3a *S3ApiServer) clearStaleLatestVersionPointer(bucket, object, bucketDir
// Already cleared by another path.
return true
}
// The live pointer must still be the stale one this clear observed. With an
// empty observed id, any pointer the re-fetch sees was promoted by a
// concurrent writer between the rescan and here — a pointer this clear
// never set out to remove, so leave it alone (the rescan's no-tagged-
// versions result only covered the pre-promotion directory).
if string(currentIdBytes) != observedStaleId {
if observedStaleId != "" && string(currentIdBytes) != observedStaleId {
glog.V(1).Infof("%s: skipping pointer clear for %s/%s, live pointer changed (observed=%s, current=%s)", caller, bucket, object, observedStaleId, string(currentIdBytes))
return false
}
expected := proto.Clone(liveEntry).(*filer_pb.Entry)
updated := proto.Clone(liveEntry).(*filer_pb.Entry)
delete(updated.Extended, s3_constants.ExtLatestVersionIdKey)
delete(updated.Extended, s3_constants.ExtLatestVersionFileNameKey)
clearCachedVersionMetadata(updated.Extended)
updated.Name = versionsObjectPath
if err := s3a.conditionalUpdateEntry(bucketDir, updated, expected); err != nil {
switch status.Code(err) {
case codes.FailedPrecondition:
// A writer moved the pointer after this heal's snapshot; its
// pointer stands.
glog.V(1).Infof("%s: skipping pointer clear for %s/%s, live entry changed", caller, bucket, object)
case codes.NotFound:
// The .versions entry vanished; nothing left to clear.
return true
default:
versioningHealWarningf("clear_failed", "bucket=%s key=%s caller=%s err=%v", bucket, object, caller, err)
}
delete(liveEntry.Extended, s3_constants.ExtLatestVersionIdKey)
delete(liveEntry.Extended, s3_constants.ExtLatestVersionFileNameKey)
clearCachedVersionMetadata(liveEntry.Extended)
if mkErr := s3a.mkFile(bucketDir, versionsObjectPath, liveEntry.Chunks, func(updatedEntry *filer_pb.Entry) {
updatedEntry.Extended = liveEntry.Extended
updatedEntry.Attributes = liveEntry.Attributes
updatedEntry.Chunks = liveEntry.Chunks
}); mkErr != nil {
versioningHealWarningf("clear_failed", "bucket=%s key=%s caller=%s err=%v", bucket, object, caller, mkErr)
return false
}
versioningHealInfof("healed", "bucket=%s key=%s mode=pointer_cleared caller=%s (orphan entries remain in .versions directory)", bucket, object, caller)
@@ -2159,13 +2144,11 @@ func scanLatestVersionEntry(list entryLister, versionsDir string) (latestEntry *
// healStaleLatestVersionPointer is invoked when the .versions directory metadata
// points to a version file that no longer exists. It paginates the directory,
// picks the chronologically newest remaining entry (content version or delete
// marker), updates the directory pointer metadata best-effort — atomically
// guarded by an IF_ENTRY_EQUAL precondition, so a pointer a concurrent writer
// advanced in the meantime is left alone — and returns the rescanned entry.
// Downstream handlers detect ExtDeleteMarkerKey on the returned entry and
// render NoSuchKey, so promoting a delete marker preserves correct S3
// semantics. If no version-tagged entry remains an error is returned and the
// caller surfaces it as not found.
// marker), updates the directory pointer metadata best-effort, and returns the
// rescanned entry. Downstream handlers detect ExtDeleteMarkerKey on the
// returned entry and render NoSuchKey, so promoting a delete marker preserves
// correct S3 semantics. If no version-tagged entry remains an error is
// returned and the caller surfaces it as not found.
func (s3a *S3ApiServer) healStaleLatestVersionPointer(bucket, normalizedObject string, versionsEntry *filer_pb.Entry, stalePointerFile string) (*filer_pb.Entry, error) {
bucketDir := s3a.bucketDir(bucket)
versionsObjectPath := normalizedObject + s3_constants.VersionsFolder
@@ -2211,102 +2194,28 @@ func (s3a *S3ApiServer) healStaleLatestVersionPointer(bucket, normalizedObject s
return nil, fmt.Errorf("%w: no remaining version in %s", filer_pb.ErrNotFound, versionsDir)
}
// The persist is CAS-style (mirroring clearStaleLatestVersionPointer) so a
// stale repair cannot supersede a concurrent writer: the rescan takes time,
// during which a PUT or delete may have atomically advanced the pointer on
// the owner filer. Re-fetch the live .versions entry and require its pointer
// fields to still match the ones this heal observed when it decided the
// pointer was unusable. If they moved, abandon the persist — this read
// still returns the scanned entry, and the winner's pointer needs no
// repair. Write the live Extended map so fields a concurrent writer
// updated between the re-fetch and the persist are preserved.
liveEntry, liveErr := s3a.getEntry(bucketDir, versionsObjectPath)
if liveErr != nil {
// The directory is gone (e.g. a concurrent delete's teardown); nothing
// to repair, and this read still returns the scanned entry.
versioningHealInfof("abandoned", "bucket=%s key=%s mode=versions_dir_gone err=%v", bucket, normalizedObject, liveErr)
return latestEntry, nil
}
observedId := string(versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey])
observedFile := string(versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey])
liveId := string(liveEntry.Extended[s3_constants.ExtLatestVersionIdKey])
liveFile := string(liveEntry.Extended[s3_constants.ExtLatestVersionFileNameKey])
if liveId != observedId || liveFile != observedFile {
// A concurrent writer promoted the pointer between the heal's snapshot
// and this check; rolling it back to the scanned version would make
// older content or ACLs current again.
versioningHealInfof("abandoned", "bucket=%s key=%s mode=pointer_moved observed_id=%s live_id=%s", bucket, normalizedObject, observedId, liveId)
return latestEntry, nil
if versionsEntry.Extended == nil {
versionsEntry.Extended = make(map[string][]byte)
}
versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey] = []byte(latestVersionId)
versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte(latestVersionFileName)
setCachedListMetadata(versionsEntry, latestEntry)
// Clone the live image before any mutation so the precondition compares
// against exactly what the filer stores (nil and empty Extended maps are
// not proto-equal).
expected := proto.Clone(liveEntry).(*filer_pb.Entry)
updated := proto.Clone(liveEntry).(*filer_pb.Entry)
if updated.Extended == nil {
updated.Extended = make(map[string][]byte)
}
updated.Name = versionsObjectPath
updated.Extended[s3_constants.ExtLatestVersionIdKey] = []byte(latestVersionId)
updated.Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte(latestVersionFileName)
setCachedListMetadata(updated, latestEntry)
updateErr := s3a.conditionalUpdateEntry(bucketDir, updated, expected)
switch {
case updateErr == nil:
versioningHealInfof("healed", "bucket=%s key=%s mode=pointer_repaired new_version=%s file=%s delete_marker=%v", bucket, normalizedObject, latestVersionId, latestVersionFileName, isDeleteMarker)
case status.Code(updateErr) == codes.FailedPrecondition, status.Code(updateErr) == codes.NotFound:
// The filer refused the stale repair: the live entry changed between
// the re-fetch and the persist, so the winner's pointer stands.
versioningHealInfof("abandoned", "bucket=%s key=%s mode=entry_changed err=%v", bucket, normalizedObject, updateErr)
default:
if mkErr := s3a.mkFile(bucketDir, versionsObjectPath, versionsEntry.Chunks, func(updatedEntry *filer_pb.Entry) {
updatedEntry.Extended = versionsEntry.Extended
updatedEntry.Attributes = versionsEntry.Attributes
updatedEntry.Chunks = versionsEntry.Chunks
}); mkErr != nil {
// Persisting the repair is best-effort. Surface a warning but still
// return the rescanned entry so the read succeeds; a subsequent write
// on the object will persist a fresh pointer.
versioningHealWarningf("heal_persist_failed", "bucket=%s key=%s err=%v (returning rescanned entry)", bucket, normalizedObject, updateErr)
versioningHealWarningf("heal_persist_failed", "bucket=%s key=%s err=%v (returning rescanned entry)", bucket, normalizedObject, mkErr)
} else {
versioningHealInfof("healed", "bucket=%s key=%s mode=pointer_repaired new_version=%s file=%s delete_marker=%v", bucket, normalizedObject, latestVersionId, latestVersionFileName, isDeleteMarker)
}
return latestEntry, nil
}
// conditionalUpdateEntry persists entry only while the stored image still
// equals expected: the filer evaluates IF_ENTRY_EQUAL under the entry's path
// lock, and conditional writes route to the owner filer, so a writer
// committing between the caller's snapshot and this update fails the
// precondition instead of being rolled back. FailedPrecondition and NotFound
// are authoritative replies, not transport failures — they return without
// retrying or marking the filer down.
func (s3a *S3ApiServer) conditionalUpdateEntry(directory string, entry, expected *filer_pb.Entry) error {
req := &filer_pb.UpdateEntryRequest{
Directory: directory,
Entry: entry,
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL,
ExpectedEntry: expected,
}}},
}
var conditionErr error
update := func(client filer_pb.SeaweedFilerClient) error {
err := filer_pb.UpdateEntry(context.Background(), client, req)
if wrapped := errors.Unwrap(err); wrapped != nil {
// The helper wraps the RPC error ("UpdateEntry: %w"); unwrap so
// the status code below survives the wrapping.
err = wrapped
}
switch status.Code(err) {
case codes.FailedPrecondition, codes.NotFound:
conditionErr = err
return nil
default:
return err
}
}
if err := s3a.WithFilerClient(false, update); err != nil {
return err
}
return conditionErr
}
// getLatestVersionEntryFromDirectoryEntry creates a logical entry for list operations using cached metadata
// from the .versions directory entry. This achieves SINGLE-SCAN efficiency - no additional getEntry calls needed.
//
@@ -1,214 +0,0 @@
package s3api
import (
"context"
"net/http"
"path"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// anonymousReadHealFiler drives the versioned self-heal path for "folder/": it
// serves a real version file from .versions, runs hooks at the heal's rescan
// and at the persist (simulating a writer committing at either point), and
// evaluates the heal's IF_ENTRY_EQUAL precondition like a filer would, so
// tests can inspect the resulting .versions metadata.
type anonymousReadHealFiler struct {
*anonymousReadFiler
onScan func(*anonymousReadHealFiler)
onWrite func(*anonymousReadHealFiler)
}
// ListEntries serves the version files under .versions for the heal's rescan.
func (f *anonymousReadHealFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
f.mu.Lock()
if f.onScan != nil {
onScan := f.onScan
f.onScan = nil
f.mu.Unlock()
onScan(f)
} else {
f.mu.Unlock()
}
f.mu.Lock()
defer f.mu.Unlock()
for _, entry := range f.entries {
if path.Join(req.Directory, entry.Name) == "/buckets/b/folder/.versions/v_v1" {
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}); err != nil {
return err
}
}
}
return nil
}
// UpdateEntry evaluates the heal's IF_ENTRY_EQUAL precondition the way a
// filer does under the path lock: the stored entry must still equal the live
// image the heal re-read, otherwise the stale repair is rejected.
func (f *anonymousReadHealFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
f.mu.Lock()
if f.onWrite != nil {
onWrite := f.onWrite
f.onWrite = nil
f.mu.Unlock()
// A writer commits between the heal's re-fetch and the persist.
onWrite(f)
} else {
f.mu.Unlock()
}
f.mu.Lock()
defer f.mu.Unlock()
fullPath := path.Join(req.Directory, req.Entry.Name)
current := f.entries[fullPath]
for _, clause := range req.Condition.Clauses {
if clause.Kind != filer_pb.WriteCondition_IF_ENTRY_EQUAL {
return nil, status.Error(codes.Unimplemented, "unsupported clause")
}
expected := proto.Clone(clause.ExpectedEntry).(*filer_pb.Entry)
actual := proto.Clone(current).(*filer_pb.Entry)
filer_pb.BeforeEntrySerialization(expected.Chunks)
filer_pb.BeforeEntrySerialization(actual.Chunks)
if !proto.Equal(actual, expected) {
return nil, status.Error(codes.FailedPrecondition, "entry changed")
}
}
f.entries[fullPath] = proto.Clone(req.Entry).(*filer_pb.Entry)
return &filer_pb.UpdateEntryResponse{}, nil
}
// TestAnonymousObjectACLHealPointerConcurrentWriter pins the CAS contract of
// the self-heal persist: a pointer that a concurrent writer promoted while the
// heal was rescanning, or between the heal's re-fetch and its persist, must
// survive, instead of being rolled back to the scanned version, which would
// make older content or ACLs current again.
func TestAnonymousObjectACLHealPointerConcurrentWriter(t *testing.T) {
for _, tc := range []struct {
name string
writerDuringScan bool
writerDuringWrite bool
wantPointer string
wantPointerVersion string
}{
{name: "idle key persists the rescanned pointer", wantPointer: "v1", wantPointerVersion: "v_v1"},
{name: "concurrent writer during scan keeps its promotion", writerDuringScan: true, wantPointer: "v2", wantPointerVersion: "v_v2"},
{name: "concurrent writer during persist keeps its promotion", writerDuringWrite: true, wantPointer: "v3", wantPointerVersion: "v_v3"},
} {
t.Run(tc.name, func(t *testing.T) {
f := &anonymousReadHealFiler{anonymousReadFiler: &anonymousReadFiler{entries: make(map[string]*filer_pb.Entry)}}
// The object is "folder/"; the regular path is a physical parent, so a
// pointerless read falls through to the persistent self-heal.
f.entries["/buckets/b/folder"] = &filer_pb.Entry{Name: "folder", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000}}
f.entries["/buckets/b/folder/child"] = anonymousReadEntry([]byte(`[]`))
f.entries["/buckets/b/folder/.versions"] = &filer_pb.Entry{Name: ".versions", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000}, Extended: map[string][]byte{s3_constants.ExtLatestVersionIdKey: []byte("")}}
v1 := anonymousReadEntry([]byte(`[]`))
v1.Name = "v_v1"
v1.Extended[s3_constants.ExtVersionIdKey] = []byte("v1")
f.entries["/buckets/b/folder/.versions/v_v1"] = v1
promotePointer := func(versionId, fileName string) func(*anonymousReadHealFiler) {
return func(f *anonymousReadHealFiler) {
// A concurrent PUT commits a newer version.
f.mu.Lock()
defer f.mu.Unlock()
f.entries["/buckets/b/folder/.versions"].Extended[s3_constants.ExtLatestVersionIdKey] = []byte(versionId)
f.entries["/buckets/b/folder/.versions"].Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte(fileName)
}
}
if tc.writerDuringScan {
f.onScan = promotePointer("v2", "v_v2")
}
if tc.writerDuringWrite {
f.onWrite = promotePointer("v3", "v_v3")
}
s3a := newPutTestServer(t, startFakeFiler(t, f))
s3a.iam = &IdentityAccessManagement{isAuthEnabled: true}
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b", Ownership: s3_constants.OwnershipObjectWriter, Versioning: "Enabled"})
s3a.policyEngine = NewBucketPolicyEngine()
s3a.iam.policyEngine = s3a.policyEngine
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("b", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject*","Resource":"arn:aws:s3:::b/folder/"}]}`))
rr := serveAnonymousRead(s3a, http.MethodGet, "folder/", "", nil)
require.Equal(t, http.StatusOK, rr.Code, rr.Body.String())
// This read returns the rescanned entry either way.
require.Equal(t, "hello world", rr.Body.String())
// The persisted pointer must reflect the concurrent writer, not the scan.
pointer := f.entries["/buckets/b/folder/.versions"].Extended[s3_constants.ExtLatestVersionIdKey]
require.Equal(t, tc.wantPointer, string(pointer))
pointerFile := f.entries["/buckets/b/folder/.versions"].Extended[s3_constants.ExtLatestVersionFileNameKey]
require.Equal(t, tc.wantPointerVersion, string(pointerFile))
})
}
}
// TestClearStaleLatestVersionPointerConcurrentWriter pins the same CAS
// contract on the pointer clear: a writer that promotes the pointer between
// the clear's re-fetch and its persist must not be rolled back to a cleared
// pointer. A pointerless caller snapshot must not clear a pointer a writer
// promoted after the clear's rescan either — the only live pointer such a
// clear can observe is one that appeared concurrently, never the stale one
// the clear set out to remove.
func TestClearStaleLatestVersionPointerConcurrentWriter(t *testing.T) {
for _, tc := range []struct {
name string
observedEmpty bool
writerDuringScan bool
writerDuringWrite bool
wantCleared bool
wantPointer string
}{
{name: "idle key clears the stale pointer", wantCleared: true, wantPointer: ""},
{name: "concurrent writer during persist keeps its promotion", writerDuringWrite: true, wantCleared: false, wantPointer: "v2"},
{name: "pointerless snapshot keeps a post-rescan promotion", observedEmpty: true, writerDuringScan: true, wantCleared: false, wantPointer: "v2"},
{name: "pointerless snapshot on an idle key is already clear", observedEmpty: true, wantCleared: true, wantPointer: ""},
} {
t.Run(tc.name, func(t *testing.T) {
f := &anonymousReadHealFiler{anonymousReadFiler: &anonymousReadFiler{entries: make(map[string]*filer_pb.Entry)}}
extended := map[string][]byte{
s3_constants.ExtLatestVersionIdKey: []byte("v1"),
s3_constants.ExtLatestVersionFileNameKey: []byte("v_v1"),
}
if tc.observedEmpty {
extended = map[string][]byte{}
}
f.entries["/buckets/b/folder/.versions"] = &filer_pb.Entry{
Name: ".versions",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000},
Extended: extended,
}
promotePointer := func(f *anonymousReadHealFiler) {
f.mu.Lock()
defer f.mu.Unlock()
f.entries["/buckets/b/folder/.versions"].Extended[s3_constants.ExtLatestVersionIdKey] = []byte("v2")
f.entries["/buckets/b/folder/.versions"].Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte("v_v2")
}
if tc.writerDuringScan {
f.onScan = promotePointer
}
if tc.writerDuringWrite {
f.onWrite = promotePointer
}
s3a := newPutTestServer(t, startFakeFiler(t, f))
versionsEntry := proto.Clone(f.entries["/buckets/b/folder/.versions"]).(*filer_pb.Entry)
if versionsEntry.Extended == nil {
// proto.Clone turns an empty Extended map into nil; real callers
// (updateLatestVersionAfterDeletion) hand the clear a non-nil
// snapshot, so mirror that here.
versionsEntry.Extended = map[string][]byte{}
}
cleared := s3a.clearStaleLatestVersionPointer("b", "folder", "/buckets/b", "folder/.versions", versionsEntry, "test")
require.Equal(t, tc.wantCleared, cleared)
pointer := f.entries["/buckets/b/folder/.versions"].Extended[s3_constants.ExtLatestVersionIdKey]
require.Equal(t, tc.wantPointer, string(pointer))
})
}
}
-23
View File
@@ -7,7 +7,6 @@ import (
"strings"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
@@ -226,28 +225,6 @@ func (s3a *S3ApiServer) handleSSES3Encryption(r *http.Request, dataReader io.Rea
return encryptedReader, sseS3Key, sseS3Metadata, s3err.ErrNone
}
// storeSSEMetadata records the encryption result on the entry, in the same
// extended attributes the GET and HEAD handlers read back.
func storeSSEMetadata(entry *filer_pb.Entry, sseResult *PutToFilerEncryptionResult) {
if sseResult == nil {
return
}
if sseResult.CustomerKey != nil && len(sseResult.SSEIV) > 0 {
entry.Extended[s3_constants.SeaweedFSSSEIV] = sseResult.SSEIV
entry.Extended[s3_constants.AmzServerSideEncryptionCustomerAlgorithm] = []byte(s3_constants.SSEAlgorithmAES256)
entry.Extended[s3_constants.AmzServerSideEncryptionCustomerKeyMD5] = []byte(sseResult.CustomerKey.KeyMD5)
}
if sseResult.SSEKMSKey != nil {
entry.Extended[s3_constants.SeaweedFSSSEKMSKey] = sseResult.SSEKMSMetadata
entry.Extended[s3_constants.AmzServerSideEncryption] = []byte(s3_constants.SSEAlgorithmKMS)
entry.Extended[s3_constants.AmzServerSideEncryptionAwsKmsKeyId] = []byte(sseResult.SSEKMSKey.KeyID)
}
if sseResult.SSES3Key != nil && len(sseResult.SSES3Metadata) > 0 {
entry.Extended[s3_constants.SeaweedFSSSES3Key] = sseResult.SSES3Metadata
entry.Extended[s3_constants.AmzServerSideEncryption] = []byte(s3_constants.SSEAlgorithmAES256)
}
}
// handleAllSSEEncryption processes all SSE types in sequence and returns the final encrypted reader
// This eliminates repetitive dataReader assignments and centralizes SSE processing
func (s3a *S3ApiServer) handleAllSSEEncryption(r *http.Request, dataReader io.Reader, partOffset int64) (*PutToFilerEncryptionResult, s3err.ErrorCode) {
-12
View File
@@ -143,8 +143,6 @@ const (
ErrSSECustomerKeyMissing
ErrSSECustomerKeyNotNeeded
ErrSSEEncryptionTypeMismatch
ErrInvalidEncryptionMethod
ErrIncompatibleEncryptionMethod
// SSE-KMS related errors
ErrKMSKeyNotFound
@@ -691,16 +689,6 @@ var errorCodeResponse = map[ErrorCode]APIError{
Description: "The encryption method specified in the request does not match the encryption method used to encrypt the object.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrInvalidEncryptionMethod: {
Code: "InvalidArgument",
Description: "The encryption method specified is not supported",
HTTPStatusCode: http.StatusBadRequest,
},
ErrIncompatibleEncryptionMethod: {
Code: "InvalidArgument",
Description: "Server Side Encryption with Customer provided key is incompatible with the encryption method specified",
HTTPStatusCode: http.StatusBadRequest,
},
// SSE-KMS error responses
ErrKMSKeyNotFound: {
@@ -126,88 +126,3 @@ func TestDeleteTableAuthorizedVersionMismatchStillConflicts(t *testing.T) {
assert.Equal(t, ErrCodeConflict, s3Err.Type)
assert.NotNil(t, fs.Get(GetNamespacePath(renameTestBucket, "ns"), "t"))
}
func runRequestAs(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, operation string, input interface{}, actions []string) s3TablesHTTPError {
t.Helper()
body, err := json.Marshal(input)
require.NoError(t, err)
identity := &testIdentity{Name: "reader", Account: &testIdentityAccount{Id: "reader"}, Actions: actions}
ctx := s3_constants.SetIdentityInContext(context.Background(), identity)
req, err := newManagerRequest(ctx, operation, body, "reader")
require.NoError(t, err)
recorder := httptest.NewRecorder()
m.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client))
result := recorder.Result()
defer result.Body.Close()
var response S3TablesError
if result.StatusCode >= 400 {
require.NoError(t, json.NewDecoder(result.Body).Decode(&response))
}
return s3TablesHTTPError{status: result.StatusCode, body: response}
}
// A principal that may read the table is told the write was refused; the
// not-found veil only hides the entry from callers that cannot see it.
func TestDeniedWritesReportForbiddenToReaders(t *testing.T) {
fs, manager := startRenameManager(t)
manager.SetTrusted(false)
manager.SetDefaultAllow(false)
readActions := []string{"s3tables:GetTable"}
got := runRequestAs(t, manager, fs, "GetTable", &GetTableRequest{
TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t"}, readActions)
assert.Equal(t, 200, got.status)
for _, tc := range []struct {
operation string
request interface{}
}{
{"UpdateTable", &UpdateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t", VersionToken: "any"}},
{"DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t"}},
{"RenameTable", &RenameTableRequest{TableBucketARN: mustBucketARN(t), SourceNamespace: []string{"ns"}, SourceName: "t", DestNamespace: []string{"ns"}, DestName: "t2"}},
} {
t.Run(tc.operation, func(t *testing.T) {
got := runRequestAs(t, manager, fs, tc.operation, tc.request, readActions)
assert.Equal(t, 403, got.status)
assert.Equal(t, ErrCodeAccessDenied, got.body.Type)
})
}
}
// A view stored at a table name is hidden from table operations: a principal
// with only s3tables:GetTable must get the same not-found it would see for a
// genuinely missing name, never a 403 that reveals the entry exists.
func TestDeniedTableWritesDoNotRevealViews(t *testing.T) {
fs, manager := startRenameManager(t)
manager.SetTrusted(false)
manager.SetDefaultAllow(false)
viewMeta, _ := json.Marshal(tableMetadataInternal{
Name: "v",
Namespace: "ns",
OwnerAccountID: DefaultAccountID,
})
fs.Put(GetNamespacePath(renameTestBucket, "ns"), "v", map[string][]byte{
ExtendedKeyMetadata: viewMeta,
ExtendedKeyEntryType: []byte(EntryTypeView),
})
readActions := []string{"s3tables:GetTable"}
for _, tc := range []struct {
operation string
request interface{}
}{
{"GetTable", &GetTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "v"}},
{"UpdateTable", &UpdateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "v", VersionToken: "any"}},
{"DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "v"}},
} {
t.Run(tc.operation, func(t *testing.T) {
got := runRequestAs(t, manager, fs, tc.operation, tc.request, readActions)
assert.Equal(t, 404, got.status)
assert.Equal(t, ErrCodeNoSuchTable, got.body.Type)
})
}
}
+17 -72
View File
@@ -2,7 +2,6 @@ package s3tables
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
@@ -341,10 +340,17 @@ func (h *S3TablesHandler) handleGetTable(w http.ResponseWriter, r *http.Request,
var metadata tableMetadataInternal
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
data, err := h.readTableMetadata(r.Context(), client, tablePath)
entry, err := h.lookupEntry(r.Context(), client, tablePath)
if err != nil {
return err
}
if EntryType(entry.Extended) == EntryTypeView {
return filer_pb.ErrNotFound
}
data, ok := entry.Extended[ExtendedKeyMetadata]
if !ok {
return fmt.Errorf("%w: %s", ErrAttributeNotFound, ExtendedKeyMetadata)
}
if err := json.Unmarshal(data, &metadata); err != nil {
return fmt.Errorf("failed to unmarshal table metadata: %w", err)
}
@@ -883,7 +889,7 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
var tableTags map[string]string
var bucketMetadata tableBucketMetadata
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
data, err := h.readTableMetadata(r.Context(), client, tablePath)
data, err := h.getExtendedAttribute(r.Context(), client, tablePath, ExtendedKeyMetadata)
if err != nil {
return err
}
@@ -968,11 +974,7 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
DefaultAllow: h.defaultAllowFor(r),
})
if !tableAllowed && !bucketAllowed {
if h.canReadEntry("GetTable", principal, metadata.OwnerAccountID, bucketMetadata.OwnerAccountID, tablePolicy, bucketPolicy, tableARN, bucketARN, bucketName, namespaceName, tableName, bucketTags, tableTags, identityActions, r) {
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to delete table")
} else {
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
}
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
return NewAuthError("DeleteTable", principal, "not authorized to delete table")
}
if req.VersionToken != "" && metadata.VersionToken != req.VersionToken {
@@ -1041,15 +1043,10 @@ var renamedTableAttributes = []string{
// catalogEntryKind describes the entry a rename operates on, so tables and
// views share one implementation of the catalog-only move.
type catalogEntryKind struct {
entryType string
noun string
renameOp string
createOp string
readOp string
// tagsForRead mirrors whether the read handler supplies resource tags to
// the policy check, so the denied-write visibility test cannot accept a
// tag-conditioned allow the real read would not evaluate.
tagsForRead bool
entryType string
noun string
renameOp string
createOp string
notFoundCode string
existsCode string
// resourceARN builds the ARN a policy scoped to this entry would name, so a
@@ -1063,8 +1060,6 @@ var (
noun: "table",
renameOp: "RenameTable",
createOp: "CreateTable",
readOp: "GetTable",
tagsForRead: true,
notFoundCode: ErrCodeNoSuchTable,
existsCode: ErrCodeTableAlreadyExists,
resourceARN: func(h *S3TablesHandler, ownerAccountID, bucketName, id string) string {
@@ -1076,8 +1071,6 @@ var (
noun: "view",
renameOp: "RenameView",
createOp: "CreateView",
readOp: "GetView",
tagsForRead: false,
notFoundCode: ErrCodeNoSuchView,
existsCode: ErrCodeViewAlreadyExists,
resourceARN: func(h *S3TablesHandler, ownerAccountID, bucketName, id string) string {
@@ -1086,42 +1079,6 @@ var (
}
)
// readTableMetadata returns the entry's table-metadata xattr. A view stored at
// the same name is reported absent, the way GetTable and the renamer's
// entry-type check already treat kind mismatches.
func (h *S3TablesHandler) readTableMetadata(ctx context.Context, client filer_pb.SeaweedFilerClient, tablePath string) ([]byte, error) {
entry, err := h.lookupEntry(ctx, client, tablePath)
if err != nil {
return nil, err
}
if EntryType(entry.Extended) == EntryTypeView {
return nil, filer_pb.ErrNotFound
}
data, ok := entry.Extended[ExtendedKeyMetadata]
if !ok {
return nil, fmt.Errorf("%w: %s", ErrAttributeNotFound, ExtendedKeyMetadata)
}
return data, nil
}
// canReadEntry reports whether the principal may read the catalog entry a
// denied write would touch. A denied write is then answered with 403 — the
// refusal leaks nothing a reader could not load anyway — while a caller that
// cannot see the entry keeps the not-found veil.
func (h *S3TablesHandler) canReadEntry(readOp, principal, tableOwner, bucketOwner, tablePolicy, bucketPolicy, tableARN, bucketARN, bucketName, namespace, name string, bucketTags, tableTags map[string]string, identityActions []string, r *http.Request) bool {
ctx := &PolicyContext{
TableBucketName: bucketName,
Namespace: namespace,
TableName: name,
TableBucketTags: bucketTags,
ResourceTags: tableTags,
IdentityActions: identityActions,
DefaultAllow: h.defaultAllowFor(r),
}
return CheckPermissionWithContext(readOp, principal, tableOwner, tablePolicy, tableARN, ctx) ||
CheckPermissionWithContext(readOp, principal, bucketOwner, bucketPolicy, bucketARN, ctx)
}
// handleRenameTable moves a table's catalog entry to a new namespace/name within
// the same bucket. It is catalog-only: the metadata.json and data files stay put,
// the destination keeps the source's MetadataLocation, and the source name is
@@ -1309,15 +1266,7 @@ func (h *S3TablesHandler) renameCatalogEntry(w http.ResponseWriter, r *http.Requ
DefaultAllow: h.defaultAllowFor(r),
})
if !tableAllowed && !bucketAllowed {
readTags := tableTags
if !kind.tagsForRead {
readTags = nil
}
if h.canReadEntry(kind.readOp, principal, metadata.OwnerAccountID, bucketMetadata.OwnerAccountID, tablePolicy, bucketPolicy, tableARN, bucketARN, bucketName, srcNamespace, srcName, bucketTags, readTags, identityActions, r) {
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to rename "+kind.noun)
} else {
h.writeError(w, http.StatusNotFound, kind.notFoundCode, fmt.Sprintf("%s %s not found", kind.noun, srcName))
}
h.writeError(w, http.StatusNotFound, kind.notFoundCode, fmt.Sprintf("%s %s not found", kind.noun, srcName))
return NewAuthError(kind.renameOp, principal, "not authorized to rename "+kind.noun)
}
@@ -1513,7 +1462,7 @@ func (h *S3TablesHandler) handleUpdateTable(w http.ResponseWriter, r *http.Reque
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
// 1. Get Table Metadata
data, err := h.readTableMetadata(r.Context(), client, tablePath)
data, err := h.getExtendedAttribute(r.Context(), client, tablePath, ExtendedKeyMetadata)
if err != nil {
return err
}
@@ -1594,11 +1543,7 @@ func (h *S3TablesHandler) handleUpdateTable(w http.ResponseWriter, r *http.Reque
})
if !tableAllowed && !bucketAllowed {
if h.canReadEntry("GetTable", principal, metadata.OwnerAccountID, bucketMetadata.OwnerAccountID, tablePolicy, bucketPolicy, tableARN, bucketARN, bucketName, namespaceName, tableName, bucketTags, tableTags, identityActions, r) {
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to update table")
} else {
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchTable, "table not found")
}
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchTable, "table not found")
return NewAuthError("UpdateTable", principal, "not authorized to update table")
}
-56
View File
@@ -8,8 +8,6 @@ import (
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/spf13/viper"
)
type EncodedJwt string
@@ -153,57 +151,3 @@ func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt, claims jwt.Claims)
return []byte(signingKey), nil
})
}
// FilerJwtProvider signs the credential a filer's HTTP API expects. A nil
// provider means the process-wide jwt.filer_signing configuration applies.
type FilerJwtProvider func(isWrite bool) EncodedJwt
// LoadFilerJwtFromFile reads jwt.filer_signing from a security file the way
// LoadClientTLSFromFile reads the TLS section, honoring the same WEED_
// environment precedence. A nil provider means the file configures no filer
// signing keys and the process-wide configuration applies. A file that sets
// only one access level falls back to the process-wide key for the other.
func LoadFilerJwtFromFile(configFile string) (FilerJwtProvider, error) {
v := viper.New()
v.SetConfigFile(configFile)
v.AutomaticEnv()
v.SetEnvPrefix("weed")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("failed to read security config %s: %v", configFile, err)
}
signingKey := SigningKey(v.GetString("jwt.filer_signing.key"))
readSigningKey := SigningKey(v.GetString("jwt.filer_signing.read.key"))
if len(signingKey) == 0 && len(readSigningKey) == 0 {
return nil, nil
}
signingKeyExpires := v.GetInt("jwt.filer_signing.expires_after_seconds")
readSigningKeyExpires := v.GetInt("jwt.filer_signing.read.expires_after_seconds")
if len(signingKey) == 0 || len(readSigningKey) == 0 {
gv := util.GetViper()
if len(signingKey) == 0 {
signingKey = SigningKey(gv.GetString("jwt.filer_signing.key"))
signingKeyExpires = gv.GetInt("jwt.filer_signing.expires_after_seconds")
}
if len(readSigningKey) == 0 {
readSigningKey = SigningKey(gv.GetString("jwt.filer_signing.read.key"))
readSigningKeyExpires = gv.GetInt("jwt.filer_signing.read.expires_after_seconds")
}
}
if signingKeyExpires < 0 || readSigningKeyExpires < 0 {
return nil, fmt.Errorf("jwt.filer_signing lifetimes must not be negative")
}
if signingKeyExpires == 0 {
signingKeyExpires = 10
}
if readSigningKeyExpires == 0 {
readSigningKeyExpires = 60
}
return func(isWrite bool) EncodedJwt {
if isWrite {
return GenJwtForFilerServer(signingKey, signingKeyExpires)
}
return GenJwtForFilerServer(readSigningKey, readSigningKeyExpires)
}, nil
}
-146
View File
@@ -1,146 +0,0 @@
package security
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestLoadFilerJwtFromFile(t *testing.T) {
configFile := filepath.Join(t.TempDir(), "security.toml")
config := `
[jwt]
[jwt.filer_signing]
key = "side-write-key"
expires_after_seconds = 30
[jwt.filer_signing.read]
key = "side-read-key"
expires_after_seconds = 90
`
if err := os.WriteFile(configFile, []byte(config), 0644); err != nil {
t.Fatal(err)
}
provider, err := LoadFilerJwtFromFile(configFile)
if err != nil {
t.Fatal(err)
}
if provider == nil {
t.Fatal("config with filer signing keys gave a nil provider")
}
for _, tc := range []struct {
name string
isWrite bool
signedBy string
otherKey string
expires int64
}{
{"read", false, "side-read-key", "side-write-key", 90},
{"write", true, "side-write-key", "side-read-key", 30},
} {
t.Run(tc.name, func(t *testing.T) {
before := time.Now()
token := provider(tc.isWrite)
after := time.Now()
claims := &SeaweedFilerClaims{}
if _, err := DecodeJwt(SigningKey(tc.signedBy), token, claims); err != nil {
t.Fatalf("token does not validate against the %s key: %v", tc.name, err)
}
if claims.ExpiresAt == nil {
t.Fatal("token never expires")
}
expiresIn := claims.ExpiresAt.Time
if expiresIn.Before(before.Add(time.Duration(tc.expires-1)*time.Second)) || expiresIn.After(after.Add(time.Duration(tc.expires+1)*time.Second)) {
t.Fatalf("token expires at %v, want %ds after %v", expiresIn, tc.expires, before)
}
if _, err := DecodeJwt(SigningKey(tc.otherKey), token, &SeaweedFilerClaims{}); err == nil {
t.Fatal("token also validates against the other access level's key")
}
})
}
}
func TestLoadFilerJwtFromFileWithoutKeys(t *testing.T) {
configFile := filepath.Join(t.TempDir(), "security.toml")
if err := os.WriteFile(configFile, []byte("[grpc.client]\n"), 0644); err != nil {
t.Fatal(err)
}
provider, err := LoadFilerJwtFromFile(configFile)
if err != nil {
t.Fatal(err)
}
if provider != nil {
t.Fatal("config without filer signing keys gave a provider")
}
}
func TestLoadFilerJwtFromFileMissing(t *testing.T) {
if _, err := LoadFilerJwtFromFile(filepath.Join(t.TempDir(), "none.toml")); err == nil {
t.Fatal("missing config file loaded without error")
}
}
func TestLoadFilerJwtFromFilePartialKeys(t *testing.T) {
configFile := filepath.Join(t.TempDir(), "security.toml")
config := `
[jwt.filer_signing.read]
key = "side-read-key"
`
if err := os.WriteFile(configFile, []byte(config), 0644); err != nil {
t.Fatal(err)
}
gv := util.GetViper()
priorKey := gv.GetString("jwt.filer_signing.key")
gv.Set("jwt.filer_signing.key", "global-write-key")
t.Cleanup(func() { gv.Set("jwt.filer_signing.key", priorKey) })
provider, err := LoadFilerJwtFromFile(configFile)
if err != nil {
t.Fatal(err)
}
if provider == nil {
t.Fatal("config with a filer signing key gave a nil provider")
}
if _, err := DecodeJwt(SigningKey("global-write-key"), provider(true), &SeaweedFilerClaims{}); err != nil {
t.Fatalf("write token does not validate against the global write key: %v", err)
}
if _, err := DecodeJwt(SigningKey("side-read-key"), provider(false), &SeaweedFilerClaims{}); err != nil {
t.Fatalf("read token does not validate against the side read key: %v", err)
}
}
func TestLoadFilerJwtFromFileEnvOverride(t *testing.T) {
configFile := filepath.Join(t.TempDir(), "security.toml")
config := `
[jwt.filer_signing]
key = "side-write-key"
[jwt.filer_signing.read]
key = "side-read-key"
`
if err := os.WriteFile(configFile, []byte(config), 0644); err != nil {
t.Fatal(err)
}
t.Setenv("WEED_JWT_FILER_SIGNING_READ_KEY", "env-read-key")
provider, err := LoadFilerJwtFromFile(configFile)
if err != nil {
t.Fatal(err)
}
if provider == nil {
t.Fatal("config with filer signing keys gave a nil provider")
}
if _, err := DecodeJwt(SigningKey("env-read-key"), provider(false), &SeaweedFilerClaims{}); err != nil {
t.Fatalf("read token does not validate against the env override key: %v", err)
}
if _, err := DecodeJwt(SigningKey("side-write-key"), provider(true), &SeaweedFilerClaims{}); err != nil {
t.Fatalf("write token does not validate against the side write key: %v", err)
}
}
+67 -128
View File
@@ -27,11 +27,6 @@ var (
// (possibly-unflushed) gap, in case the flush notification is missed.
unflushedGapRetryInterval = 2 * time.Second
// aggDiskReprobeInterval paces the aggregated persisted-log re-listing for
// files no watermark signals: a peer past the flush low-watermark can land
// a file without moving the minimum.
aggDiskReprobeInterval = 2 * time.Second
// gapStallWarnInterval paces the warning for a subscriber that stays parked.
gapStallWarnInterval = time.Minute
@@ -671,9 +666,8 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
var lastHeartbeatNs int64
baseEachLogEntryFn := eachLogEntryFn(req, sender, eachEventNotificationFn, &unsyncedEvents)
// heldAtTsNs remembers the entry a read was held at (for the log line);
// diskHeldAtTsNs is the same marker for the disk pass alone: a pending
// disk hold keeps the pass re-reading until the entry is served.
var heldAtTsNs, diskHeldAtTsNs int64
// the rewind target is the last entry actually delivered.
var heldAtTsNs int64
// Each read path holds at its own watermark: persisted logs are complete
// only up to every peer's flush watermark, the ring only up to every
// peer's delivery watermark.
@@ -704,14 +698,7 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
// What the last disk pass proved covered: flushed on every peer AND inside
// the pass's listing, so an empty pass proves (cursor, proven] empty.
var diskPassProvenTsNs int64
diskBaseEachLogEntryFn := guardedEachLogEntryFn(func() int64 { return diskPassHoldTsNs })
diskEachLogEntryFn := func(logEntry *filer_pb.LogEntry) (bool, error) {
isDone, err := diskBaseEachLogEntryFn(logEntry)
if errors.Is(err, errHeldByPeerWatermark) {
diskHeldAtTsNs = logEntry.TsNs
}
return isDone, err
}
diskEachLogEntryFn := guardedEachLogEntryFn(func() int64 { return diskPassHoldTsNs })
memEachLogEntryFn := guardedEachLogEntryFn(holdMemTsNs)
// waitHeld pauses a held read until a peer reports further progress, or
// the retry interval elapses (a peer dropped past its grace, or a log file
@@ -746,11 +733,6 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
var readPersistedLogErr error
var readInMemoryLogErr error
var isDone bool
var lastCheckedFlushTsNs int64 = -1 // Track the last local flush we read the disk under
var lastCheckedFlushLowTsNs int64 = -1 // Track the last peer flush low-watermark we read the disk under
var lastDiskReadTsNs int64 = -1 // Track the last read position we used for disk read
var lastDiskRefsStopTsNs int64 = -1 // Track the last chunk listing bound we read the disk under
var lastDiskPassAt time.Time // Paces re-probes for files no watermark signals
sentRefs := make(map[string]sentRefState)
aggBuffer := fs.filer.MetaAggregator.MetaLogBuffer
@@ -783,110 +765,78 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
// diskPassHoldTsNs above).
diskPassFlushLowTsNs = fs.filer.MetaAggregator.PeerLowFlushWatermarkTsNs()
diskPassHoldTsNs = resolveAggReadHoldTsNs(diskPassFlushLowTsNs, time.Now().UnixNano(), metadataGapSettledHorizon)
diskPassProvenTsNs = diskPassFlushLowTsNs
// Re-read the disk only when something changed it cannot miss: a local
// flush landed, the peers' flush low-watermark moved in either
// direction (a joining peer invalidates what an earlier pass proved),
// the cursor moved, or a disk hold is pending (the ring read after an
// empty pass parks internally, so skipping would strand the held
// entry). A peer past the low-watermark can still land a file without
// moving it, so the listing is also re-probed at a slow cadence;
// chunk listings re-arm as soon as their read bound admits more files.
currentFlushTsNs := fs.filer.LocalMetaLogBuffer.GetLastFlushTsNs()
currentReadTsNs := lastReadTime.Time.UnixNano()
var currentRefsStopTsNs int64
if req.ClientSupportsMetadataChunks {
currentRefsStopTsNs = chunkRefsStopTsNs(diskPassHoldTsNs, req.UntilNs)
}
shouldReadFromDisk := lastCheckedFlushTsNs == -1 ||
currentFlushTsNs > lastCheckedFlushTsNs ||
diskPassFlushLowTsNs != lastCheckedFlushLowTsNs ||
currentReadTsNs != lastDiskReadTsNs ||
currentRefsStopTsNs > lastDiskRefsStopTsNs ||
diskHeldAtTsNs != 0 ||
time.Since(lastDiskPassAt) >= aggDiskReprobeInterval
diskAdvanced := false
if shouldReadFromDisk {
lastCheckedFlushTsNs = currentFlushTsNs
lastCheckedFlushLowTsNs = diskPassFlushLowTsNs
lastDiskReadTsNs = currentReadTsNs
lastDiskRefsStopTsNs = currentRefsStopTsNs
lastDiskPassAt = time.Now()
diskHeldAtTsNs = 0
diskPassProvenTsNs = diskPassFlushLowTsNs
if req.ClientSupportsMetadataChunks {
refsStopTsNs := currentRefsStopTsNs
// Nothing above the listing bound is proven by this pass.
if refsStopTsNs < diskPassProvenTsNs {
diskPassProvenTsNs = refsStopTsNs
}
if refsStopTsNs > lastReadTime.Time.UnixNano() {
processedTsNs, isDone, readPersistedLogErr = fs.chunkDiskPass(ctx, sender, lastReadTime, refsStopTsNs, sentRefs, nil)
} else {
processedTsNs, isDone, readPersistedLogErr = 0, false, nil
}
refsStopTsNs := chunkRefsStopTsNs(diskPassHoldTsNs, req.UntilNs)
// Nothing above the listing bound is proven by this pass.
if refsStopTsNs < diskPassProvenTsNs {
diskPassProvenTsNs = refsStopTsNs
}
if refsStopTsNs > lastReadTime.Time.UnixNano() {
processedTsNs, isDone, readPersistedLogErr = fs.chunkDiskPass(ctx, sender, lastReadTime, refsStopTsNs, sentRefs, nil)
} else {
processedTsNs, isDone, readPersistedLogErr = fs.filer.ReadPersistedLogBuffer(ctx, lastReadTime, req.UntilNs, diskEachLogEntryFn)
processedTsNs, isDone, readPersistedLogErr = 0, false, nil
}
if errors.Is(readPersistedLogErr, errHeldByPeerWatermark) {
// Stay at the last delivered entry; the held entry is re-read (and
// re-checked) by the next pass.
if processedTsNs > 0 {
lastReadTime = log_buffer.NewMessagePosition(processedTsNs, gapResumeCursorOffset)
if processedTsNs > diskAnchorTsNs {
diskAnchorTsNs = processedTsNs
}
}
// A hold is not a gap: clear any stale ResumeFromDiskError so the
// next pass's disk-miss handling cannot skip past the held entry.
readInMemoryLogErr = nil
if !waitHeld("disk", flushChan) {
return nil
}
continue
}
if readPersistedLogErr != nil {
return fmt.Errorf("reading from persisted logs: %w", readPersistedLogErr)
}
if isDone {
return nil
}
glog.V(4).Infof("processed to %v: %v", clientName, processedTsNs)
diskAdvanced = diskReadAdvanced(processedTsNs, lastReadTime)
// Read after the disk read (an eviction landing mid-read must count) and
// in received-ts space: the ring's bumped stopTimes exceed anything on
// any peer's disk, and gating disk cursors on them parks subscribers
// that drained every peer's log.
lastEvictedTsNs := fs.filer.MetaAggregator.MetaLogBuffer.GetLastEvictedOriginalTsNs()
if diskAdvanced {
gapStall.resumed()
reportUnprovenAggregatedCrossing(cursorBeforeDiskTsNs, processedTsNs, lastEvictedTsNs, diskPassFlushLowTsNs, clientName, req.PathPrefix)
} else {
processedTsNs, isDone, readPersistedLogErr = fs.filer.ReadPersistedLogBuffer(ctx, lastReadTime, req.UntilNs, diskEachLogEntryFn)
}
if errors.Is(readPersistedLogErr, errHeldByPeerWatermark) {
// Stay at the last delivered entry; the held entry is re-read (and
// re-checked) by the next pass.
if processedTsNs > 0 {
lastReadTime = log_buffer.NewMessagePosition(processedTsNs, gapResumeCursorOffset)
if processedTsNs > diskAnchorTsNs {
diskAnchorTsNs = processedTsNs
}
} else if readInMemoryLogErr == nil {
// Nothing on disk and memory never spoke: scan forward for the next
// day that has logs.
nextDayTs := util.GetNextDayTsNano(lastReadTime.Time.UnixNano())
// The day jump delivers nothing; stay put until the hold point
// covers the skipped range.
if nextDayTs <= diskPassHoldTsNs {
position := log_buffer.NewMessagePosition(nextDayTs, gapResumeCursorOffset)
found, err := fs.filer.HasPersistedLogFiles(position)
if err != nil {
return fmt.Errorf("checking persisted log files: %w", err)
}
if found {
gapStall.resumed()
reportUnprovenAggregatedCrossing(cursorBeforeDiskTsNs, nextDayTs, lastEvictedTsNs, diskPassFlushLowTsNs, clientName, req.PathPrefix)
lastReadTime = position
if nextDayTs > diskAnchorTsNs {
diskAnchorTsNs = nextDayTs
}
}
// A hold is not a gap: clear any stale ResumeFromDiskError so the
// next pass's disk-miss handling cannot skip past the held entry.
readInMemoryLogErr = nil
if !waitHeld("disk", flushChan) {
return nil
}
continue
}
if readPersistedLogErr != nil {
return fmt.Errorf("reading from persisted logs: %w", readPersistedLogErr)
}
if isDone {
return nil
}
glog.V(4).Infof("processed to %v: %v", clientName, processedTsNs)
diskAdvanced := diskReadAdvanced(processedTsNs, lastReadTime)
// Read after the disk read (an eviction landing mid-read must count) and
// in received-ts space: the ring's bumped stopTimes exceed anything on
// any peer's disk, and gating disk cursors on them parks subscribers
// that drained every peer's log.
lastEvictedTsNs := fs.filer.MetaAggregator.MetaLogBuffer.GetLastEvictedOriginalTsNs()
if diskAdvanced {
gapStall.resumed()
reportUnprovenAggregatedCrossing(cursorBeforeDiskTsNs, processedTsNs, lastEvictedTsNs, diskPassFlushLowTsNs, clientName, req.PathPrefix)
lastReadTime = log_buffer.NewMessagePosition(processedTsNs, gapResumeCursorOffset)
if processedTsNs > diskAnchorTsNs {
diskAnchorTsNs = processedTsNs
}
} else if readInMemoryLogErr == nil {
// Nothing on disk and memory never spoke: scan forward for the next
// day that has logs.
nextDayTs := util.GetNextDayTsNano(lastReadTime.Time.UnixNano())
// The day jump delivers nothing; stay put until the hold point
// covers the skipped range.
if nextDayTs <= diskPassHoldTsNs {
position := log_buffer.NewMessagePosition(nextDayTs, gapResumeCursorOffset)
found, err := fs.filer.HasPersistedLogFiles(position)
if err != nil {
return fmt.Errorf("checking persisted log files: %w", err)
}
if found {
gapStall.resumed()
reportUnprovenAggregatedCrossing(cursorBeforeDiskTsNs, nextDayTs, lastEvictedTsNs, diskPassFlushLowTsNs, clientName, req.PathPrefix)
lastReadTime = position
if nextDayTs > diskAnchorTsNs {
diskAnchorTsNs = nextDayTs
}
}
}
@@ -917,7 +867,6 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
// every event whose original timestamp is at or below this.
preMemDeliveryLowTsNs := fs.filer.MetaAggregator.PeerLowWatermarkTsNs()
diskReprobeDue := false
lastReadTime, isDone, readInMemoryLogErr = fs.filer.MetaAggregator.MetaLogBuffer.LoopProcessLogData(aggReaderName, lastReadTime, req.UntilNs, func() bool {
select {
case <-ctx.Done():
@@ -927,13 +876,6 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
if !fs.hasClient(req.ClientId, req.ClientEpoch) {
return false
}
// Caught-up readers park in the inner wait loop; the outer disk
// gate never runs again unless this read returns, so unwind to
// re-probe the persisted logs on the slow cadence.
if time.Since(lastDiskPassAt) >= aggDiskReprobeInterval {
diskReprobeDue = true
return false
}
// Contiguous and caught up: advance the anchor to the delivery
// low-watermark so long live tails keep eviction rewinds short.
// Only once the run is connected to the ring - the empty-ring
@@ -977,9 +919,6 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
}
}
if isDone {
if diskReprobeDue {
continue
}
return nil
}
if !fs.hasClient(req.ClientId, req.ClientEpoch) {
-79
View File
@@ -1,79 +0,0 @@
package weed_server
// The persisted log may end before a subscriber's start position (a filer
// whose own journal is older than the position a backup client resumes from).
// With nothing on disk and every ring entry held by a peer watermark, the
// aggregated loop used to re-list and re-read the persisted log on every wake
// - about a full CPU core per such subscriber. The disk pass may only re-run
// when something it cannot miss has changed.
import (
"context"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
type countingStore struct {
filer.FilerStore
logLists *atomic.Int64
}
func (s *countingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
if strings.HasPrefix(string(dirPath), filer.SystemLogDir) {
s.logLists.Add(1)
}
return s.FilerStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, eachEntryFunc)
}
func TestSubscribeLoop_AggregatedNoPersistedEntryAfterStart(t *testing.T) {
h := newSubscribeHarness(t)
lists := &atomic.Int64{}
h.f.SetStore(&countingStore{FilerStore: h.f.GetStore(), logLists: lists})
// Persisted log ends at T1: one flushed window, nothing after.
h.append(h.tsAt(0, 0))
h.append(h.tsAt(0, 1))
h.f.LocalMetaLogBuffer.ForceFlush()
waitForFlushedFiles(t, h, h.tsAt(0, 1))
// Client cursor sits just past the last persisted entry.
cursor := h.tsAt(0, 1) + int64(time.Millisecond)
ma := h.startAggregator()
// Aggregated ring holds only much newer entries (peer events).
recent := time.Now().UnixNano()
h.appendAggregated(recent)
h.appendAggregated(recent + int64(time.Millisecond))
// Peers' watermarks are stuck at the old log tail.
reportPeersAt(ma, h.tsAt(0, 1), h.tsAt(0, 1))
r := h.subscribeAggregated(cursor)
// Warm up: the first pass plus the cursor-move re-read after the gap
// machinery re-arms the cursor are legitimate.
time.Sleep(150 * time.Millisecond)
before := lists.Load()
time.Sleep(500 * time.Millisecond)
rate := float64(lists.Load()-before) / 0.5
if rate > 4 {
t.Fatalf("%.1f persisted-log listings per second while parked; the disk pass re-ran on every wake", rate)
}
// Peer progress through the held entries releases the read: the held
// events are delivered without another disk pass.
lists.Store(0)
reportPeersAt(ma, recent+int64(time.Millisecond), h.tsAt(0, 1))
waitForEvents(t, r, []int64{recent, recent + int64(time.Millisecond)}, 3*time.Second)
if got := lists.Load(); got > 4 {
t.Fatalf("%d listings while draining held entries; delivery should come from the ring", got)
}
}
-9
View File
@@ -47,15 +47,6 @@ func (c *commandEcEncode) Help() string {
If you only have less than 4 volume servers, with erasure coding, at least you can afford to
have 4 corrupted shard files.
The guarantee follows from where shards land: a volume survives the loss of any
nodes (or racks) that hold at most parityShards (4) shards between them. Spread
is best-effort; -shardReplicaPlacement requests limits: its rack digit
sets the requested shards per rack, and its node digit the requested shards
per node (the data-center digit is not used for EC). For example
-shardReplicaPlacement=021 requests at most 1 shard per node and 2 per rack.
Only when the final placement meets these limits does losing one rack cost
at most 2 shards; the command does not guarantee that the limits are met.
The -collection parameter is a comma-separated list of collection names, with
"*" and "?" wildcards, and regex patterns:
- One collection: ec.encode -collection="mybucket"
@@ -106,12 +106,6 @@ type Options struct {
// heterogeneous-capacity racks; when false, by raw shard count. Both the worker
// and the shell enable it; the two metrics agree when capacities are uniform.
GlobalUtilizationBased bool
// RackTotalCapRaised, when set, is called for each volume whose
// total-shards-per-rack cap had to be raised above ceil(shards/racks)
// because the racks lack room for an even spread. Losing a rack then loses
// more shards than an even spread would, so callers log it as a degraded
// durability floor. It is called on every Plan while the condition holds.
RackTotalCapRaised func(collection string, vid uint32, rackCap, evenCap int)
}
// move is the internal form carrying node pointers; converted to Move at the end.
@@ -255,7 +249,7 @@ func Plan(topo *Topology, opts Options) []Move {
all = append(all, m...)
}
for _, vk := range byCollection[collection] {
m := detectCrossRackImbalance(vk, nodes, racks, opts.DiskType, opts.ImbalanceThreshold, dataShardsByVolume[vk], parityShardsByVolume[vk], opts.ReplicaPlacement, opts.RackTotalCapRaised)
m := detectCrossRackImbalance(vk, nodes, racks, opts.DiskType, opts.ImbalanceThreshold, dataShardsByVolume[vk], parityShardsByVolume[vk], opts.ReplicaPlacement)
applyMovesToTopology(m, racks)
all = append(all, m...)
}
@@ -349,108 +343,42 @@ func detectDuplicateShards(vk volKey, nodes map[string]*Node) []*move {
}
// detectCrossRackImbalance spreads a volume's shards across racks in two passes
// (data, then parity with anti-affinity to data-bearing racks), keeping each
// rack's total within planRackTotalCap. Returns nil if the overall distribution
// is below the imbalance threshold and no rack is above the total cap.
func detectCrossRackImbalance(vk volKey, nodes map[string]*Node, racks map[string]*rack, diskType string, threshold float64, dataShards, parityShards int, rp *super_block.ReplicaPlacement, onCapRaised func(collection string, vid uint32, rackCap, evenCap int)) []*move {
// (data, then parity with anti-affinity to data-bearing racks). Returns nil if
// the overall distribution is below the imbalance threshold.
func detectCrossRackImbalance(vk volKey, nodes map[string]*Node, racks map[string]*rack, diskType string, threshold float64, dataShards, parityShards int, rp *super_block.ReplicaPlacement) []*move {
numRacks := len(racks)
if numRacks <= 1 {
return nil
}
// The per-type caps below spread data and parity independently, so together
// they can still stack e.g. 2 data + 1 parity on one rack. Cap the TOTAL per
// rack too, at the lowest value the racks' capacity allows.
rackShardCount := countShardsByRack(vk, nodes)
totalShards := 0
for _, n := range rackShardCount {
totalShards += n
}
totalCap := planRackTotalCap(vk, racks, rackShardCount, totalShards, rp)
if evenCap := ceilDivide(totalShards, numRacks); totalCap > evenCap && onCapRaised != nil {
onCapRaised(vk.collection, vk.vid, totalCap, evenCap)
}
aboveTotalCap := func() bool {
for _, n := range rackShardCount {
if n > totalCap {
return true
}
}
return false
}
// Gate on per-type spread: act when data OR parity shards are unevenly
// distributed across racks, even if the per-rack totals happen to be even.
// A rack above the total cap is a durability bound, not skew, so it bypasses
// the threshold.
gateData, gateParity := shardsByGroup(vk, nodes, dataShards, func(n *Node) string { return n.rack })
if !aboveTotalCap() && !typeImbalanced(gateData, numRacks, threshold) && !typeImbalanced(gateParity, numRacks, threshold) {
if !typeImbalanced(gateData, numRacks, threshold) && !typeImbalanced(gateParity, numRacks, threshold) {
return nil
}
rackShardCount := countShardsByRack(vk, nodes)
var moves []*move
// A shard moves at most once per plan: each move runs as its own task,
// possibly in parallel with the others, so a second hop could start before
// the first has landed.
moved := make(map[int]bool)
for {
before := len(moves)
// The data pass leaves the total cap out (0): ceil(data/racks) <= totalCap
// already bounds data, and rackShardCount still includes parity that the
// parity pass is about to shed, so a total bound here would block data
// moves that fit once that parity has gone.
dataPerRack, _ := shardsByGroup(vk, nodes, dataShards, func(n *Node) string { return n.rack })
moves = append(moves, balanceShardTypeAcrossRacks(vk, nodes, racks, diskType, dataShards,
dataPerRack, rackShardCount, ceilDivide(dataShards, numRacks), 0, nil, rp, moved)...)
dataPerRack, _ := shardsByGroup(vk, nodes, dataShards, func(n *Node) string { return n.rack })
moves = append(moves, balanceShardTypeAcrossRacks(vk, nodes, racks, diskType, dataShards,
dataPerRack, rackShardCount, ceilDivide(dataShards, numRacks), nil, rp)...)
dataPerRack, parityPerRack := shardsByGroup(vk, nodes, dataShards, func(n *Node) string { return n.rack })
antiAffinity := make(map[string]bool)
for rackID, shards := range dataPerRack {
if len(shards) > 0 {
antiAffinity[rackID] = true
}
}
moves = append(moves, balanceShardTypeAcrossRacks(vk, nodes, racks, diskType, dataShards,
parityPerRack, rackShardCount, ceilDivide(parityShards, numRacks), totalCap, antiAffinity, rp, moved)...)
// The data pass can run out of destinations before the parity pass frees
// slots on other racks. While a rack is still above the total cap, run
// another round over the shards not moved yet. A round that continues
// moved at least one more shard, so this ends.
if len(moves) == before || !aboveTotalCap() {
return moves
dataPerRack, parityPerRack := shardsByGroup(vk, nodes, dataShards, func(n *Node) string { return n.rack })
antiAffinity := make(map[string]bool)
for rackID, shards := range dataPerRack {
if len(shards) > 0 {
antiAffinity[rackID] = true
}
}
moves = append(moves, balanceShardTypeAcrossRacks(vk, nodes, racks, diskType, dataShards,
parityPerRack, rackShardCount, ceilDivide(parityShards, numRacks), antiAffinity, rp)...)
return moves
}
// planRackTotalCap returns the lowest per-rack total that the racks can hold a
// volume's totalShards under (see rackTotalCap). Plan may move any shard, so a
// rack's shards of the volume count as room there rather than as held in place.
// Moves of the volume shift slots between racks without changing a rack's
// shards-plus-free-slots, so the cap holds for the whole cross-rack phase.
// Under SameRackCount a node's free slots count only up to the shards of the
// volume it may still take, the limit pickBestNodeForVolume enforces.
func planRackTotalCap(vk volKey, racks map[string]*rack, rackShardCount map[string]int, totalShards int, rp *super_block.ReplicaPlacement) int {
room := make(map[string]int, len(racks))
for rk, r := range racks {
room[rk] = rackShardCount[rk]
if rp == nil || rp.SameRackCount <= 0 {
room[rk] += max(r.freeSlots, 0)
continue
}
for _, n := range r.nodes {
room[rk] += min(max(n.freeSlots, 0), max(rp.SameRackCount-volumeShardCount(n, vk), 0))
}
}
return rackTotalCap(sortedKeys(racks), nil, room, totalShards)
}
// balanceShardTypeAcrossRacks spreads one shard type across racks, at most
// maxPerRack of the type per rack. A totalCap > 0 also bounds each rack's TOTAL
// shards of the volume: racks above it shed this type, and no move lands on a
// rack at it. Shards in moved stay put; the ones it moves are added to it.
func balanceShardTypeAcrossRacks(vk volKey, nodes map[string]*Node, racks map[string]*rack, diskType string, dataShards int, shardsPerRack map[string][]int, rackShardCount map[string]int, maxPerRack, totalCap int, antiAffinity map[string]bool, rp *super_block.ReplicaPlacement, moved map[int]bool) []*move {
func balanceShardTypeAcrossRacks(vk volKey, nodes map[string]*Node, racks map[string]*rack, diskType string, dataShards int, shardsPerRack map[string][]int, rackShardCount map[string]int, maxPerRack int, antiAffinity map[string]bool, rp *super_block.ReplicaPlacement) []*move {
if maxPerRack < 1 {
maxPerRack = 1
}
@@ -464,25 +392,14 @@ func balanceShardTypeAcrossRacks(vk volKey, nodes map[string]*Node, racks map[st
var toMove []pending
for _, rackID := range rackKeys {
shards := append([]int(nil), shardsPerRack[rackID]...)
// Shards this plan already moved go last, so the shed takes the others.
sort.Slice(shards, func(i, j int) bool {
if moved[shards[i]] != moved[shards[j]] {
return !moved[shards[i]]
}
return shards[i] < shards[j]
})
sort.Ints(shards)
overflow := max(0, len(shards)-maxPerRack)
if totalCap > 0 {
// A rack above the total cap sheds this type until it fits, even
// when the type is within its own cap there.
overflow = max(overflow, min(len(shards), rackShardCount[rackID]-totalCap))
}
for i := 0; i < len(shards); i++ {
// A parity shard can fit the per-type cap yet share a rack with
// data while a data-free rack is empty; such candidates may only
// move to a rack without data.
avoidDataRack := i >= overflow
if moved[shards[i]] || (avoidDataRack && !antiAffinity[rackID]) {
if avoidDataRack && !antiAffinity[rackID] {
continue
}
if src := nodeInRackHoldingShard(nodes, rackID, vk, shards[i]); src != nil {
@@ -491,32 +408,22 @@ func balanceShardTypeAcrossRacks(vk volKey, nodes map[string]*Node, racks map[st
}
}
withinLimit := func(r string) bool {
if totalCap > 0 && rackShardCount[r] >= totalCap {
return false
}
if rp != nil && rp.DiffRackCount > 0 && rackShardCount[r] >= rp.DiffRackCount {
return false
}
return true
}
var moves []*move
for _, pm := range toMove {
hasRoom := func(r string) bool {
return r != pm.src.rack && racks[r].freeSlots > 0 &&
(!pm.avoidDataRack || !antiAffinity[r])
}
destRack, ok := pickTarget(rackKeys, shardsPerRack, maxPerRack, antiAffinity, hasRoom, withinLimit)
if !ok && totalCap > 0 && rackShardCount[pm.src.rack] > totalCap {
// No rack is under the per-type cap. A shard must not stay on a rack
// above the total cap while another rack is under it, so relax the
// per-type cap up to the total cap; anti-affinity stays a preference
// inside pickTarget. Only a source above the total cap may relax:
// otherwise the destination just takes over the per-type overflow
// and the next Plan moves it back.
destRack, ok = pickTarget(rackKeys, shardsPerRack, totalCap, antiAffinity, hasRoom, withinLimit)
}
destRack, ok := pickTarget(rackKeys, shardsPerRack, maxPerRack, antiAffinity,
func(r string) bool {
return r != pm.src.rack && racks[r].freeSlots > 0 &&
(!pm.avoidDataRack || !antiAffinity[r])
},
func(r string) bool {
if rp == nil {
return true
}
if rp.DiffRackCount > 0 && rackShardCount[r] >= rp.DiffRackCount {
return false
}
return true
})
if !ok {
continue
}
@@ -548,7 +455,6 @@ func balanceShardTypeAcrossRacks(vk volKey, nodes map[string]*Node, racks map[st
// limited-capacity destination across successive moves.
destNode.freeSlots--
pm.src.freeSlots++
moved[pm.shardID] = true
}
return moves
}
@@ -1,314 +0,0 @@
package ecbalancer
import (
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
)
// Total-shards-per-rack cap for Plan.
//
// The per-type caps (ceil(data/racks) data, ceil(parity/racks) parity) spread
// each type evenly on their own, but together they allow e.g. 2 data + 1 parity
// on one rack. When a rack is one physical disk, losing two such racks loses 6
// of a 10+4 volume's shards. Plan also caps the TOTAL per rack, sized like
// Place's rackTotalCap: ceil(shards/racks) unless the racks' capacity forces it
// higher.
const capTestVid = uint32(1)
var capTestVk = volKey{collection: "c1", vid: capTestVid}
// rackCapThresholds are the imbalance thresholds of the shell (0) and the
// worker's default (0.2); both reach Plan.
var rackCapThresholds = []float64{0, 0.2}
// addCapNode adds a node with one disk of `free` slots, before its shards.
func addCapNode(topo *Topology, id, rackKey string, free int) *Node {
n := topo.AddNode(id, "dc1", rackKey, free)
n.AddDisk(0, "", free, 0)
return n
}
// putShards places the volume's shards on the node's disk 0 and takes their slots.
func putShards(n *Node, ids ...int) {
n.AddShards(capTestVid, "c1", 0, bits(ids...))
n.freeSlots -= len(ids)
n.disks[0].freeSlots -= len(ids)
n.disks[0].shardCount += len(ids)
}
func shardTotalsPerRack(topo *Topology) map[string]int {
totals := map[string]int{}
for _, n := range topo.nodes {
totals[n.rack] += volumeShardCount(n, capTestVk)
}
return totals
}
// planAndCheckRackTotals runs Plan, then checks every shard is still placed,
// that no rack holds more than maxPerRack, and that a second Plan is a no-op.
func planAndCheckRackTotals(t *testing.T, topo *Topology, opts Options, maxPerRack int) {
t.Helper()
Plan(topo, opts)
totals := shardTotalsPerRack(topo)
t.Logf("total shards per rack: %v", totals)
sum := 0
for rk, n := range totals {
sum += n
if n > maxPerRack {
t.Errorf("rack %s holds %d shards, want at most %d", rk, n, maxPerRack)
}
}
if sum != erasure_coding.TotalShardsCount {
t.Errorf("%d shards placed, want %d", sum, erasure_coding.TotalShardsCount)
}
if again := Plan(topo, opts); len(again) != 0 {
t.Errorf("second Plan is not a no-op: %+v", again)
}
}
// raisedCaps records Options.RackTotalCapRaised reports.
type raisedCaps []string
func (r *raisedCaps) record(collection string, vid uint32, rackCap, evenCap int) {
*r = append(*r, fmt.Sprintf("%s/%d cap=%d even=%d", collection, vid, rackCap, evenCap))
}
func forEachThreshold(t *testing.T, run func(t *testing.T, threshold float64)) {
for _, th := range rackCapThresholds {
t.Run(fmt.Sprintf("threshold=%v", th), func(t *testing.T) { run(t, th) })
}
}
// TestPlanTotalShardsPerRackCap: 10+4 encoded onto one of 8 racks spreads to at
// most ceil(14/8) = 2 shards per rack, not 2 data + 1 parity.
func TestPlanTotalShardsPerRackCap(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
putShards(addCapNode(topo, "n1", "dc1:rack1", 100), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
for r := 2; r <= 8; r++ {
addCapNode(topo, fmt.Sprintf("n%d", r), fmt.Sprintf("dc1:rack%d", r), 100)
}
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4)}, 2)
})
}
// TestPlanTotalShardsPerRackCapTwoNodesPerRack: the cap is per rack, not per
// node, so two volume servers sharing a rack (one physical disk) hold at most 2
// between them.
func TestPlanTotalShardsPerRackCapTwoNodesPerRack(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
for r := 1; r <= 8; r++ {
for i := 0; i < 2; i++ {
n := addCapNode(topo, fmt.Sprintf("n%d-%d", r, i), fmt.Sprintf("dc1:rack%d", r), 100)
if r == 1 && i == 0 {
putShards(n, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
}
}
}
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4)}, 2)
})
}
// TestPlanTotalCapFromClumpedStart: data 2,2,2,2,2,0,0,0 with all parity on
// rack1. Racks 6-8 take one parity each, after which no rack is under the parity
// cap of 1; the last parity must still leave rack1 (2 data + 1 parity) for a
// data-bearing rack under the total cap rather than stay put.
func TestPlanTotalCapFromClumpedStart(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
layout := [][]int{{0, 1, 10, 11, 12, 13}, {2, 3}, {4, 5}, {6, 7}, {8, 9}, nil, nil, nil}
for r, ids := range layout {
n := addCapNode(topo, fmt.Sprintf("n%d", r+1), fmt.Sprintf("dc1:rack%d", r+1), 100)
if len(ids) > 0 {
putShards(n, ids...)
}
}
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4)}, 2)
})
}
// TestPlanTotalCapAllRacksBearData: every rack holds data, so parity has to
// share a rack with data. Anti-affinity stays a preference and the plan still
// reaches at most 2 per rack.
func TestPlanTotalCapAllRacksBearData(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
layout := [][]int{{0, 1, 10, 11, 12, 13}, {2, 3}, {4}, {5}, {6}, {7}, {8}, {9}}
for r, ids := range layout {
putShards(addCapNode(topo, fmt.Sprintf("n%d", r+1), fmt.Sprintf("dc1:rack%d", r+1), 100), ids...)
}
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4)}, 2)
})
}
// TestPlanTotalCapParityOnDataRacks: each type is within its own cap (2 data,
// 1 parity per rack) yet four racks hold 3. The non-overflow parity shards that
// may only move to a data-free rack find just two of those; the over-cap ones
// that remain must go to a data-bearing rack under the total cap.
func TestPlanTotalCapParityOnDataRacks(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
layout := [][]int{{0, 1, 10}, {2, 3, 11}, {4, 5, 12}, {6, 7, 13}, {8}, {9}, nil, nil}
for r, ids := range layout {
n := addCapNode(topo, fmt.Sprintf("n%d", r+1), fmt.Sprintf("dc1:rack%d", r+1), 100)
if len(ids) > 0 {
putShards(n, ids...)
}
}
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4)}, 2)
})
}
// TestPlanTotalCapIgnoresImbalanceThreshold: a rack above the total cap is a
// durability problem, so a threshold high enough to pass both per-type checks
// must not stop Plan from fixing it.
func TestPlanTotalCapIgnoresImbalanceThreshold(t *testing.T) {
topo := NewTopology()
layout := [][]int{{0, 1, 10}, {2, 3, 11}, {4, 5}, {6, 7}, {8}, {9}, {12}, {13}}
for r, ids := range layout {
putShards(addCapNode(topo, fmt.Sprintf("n%d", r+1), fmt.Sprintf("dc1:rack%d", r+1), 100), ids...)
}
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: 100, Ratio: ratio(10, 4)}, 2)
}
// TestPlanTotalCapWithNearlyFullRack: 8 racks of two volume servers each, plus
// a small, nearly full SSD rack already holding one shard. The SSD rack's lack
// of room must not raise the cap above ceil(14/9) = 2 for the HDD racks. The
// start is the layout Place produced before it capped the total per rack.
func TestPlanTotalCapWithNearlyFullRack(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
layout := [][]int{{0, 1, 10}, {2, 3, 11}, {4, 5}, {6, 7}, {8}, {9}, {12}, nil}
for r, ids := range layout {
for i := 0; i < 2; i++ {
n := addCapNode(topo, fmt.Sprintf("n%d-%d", r, i), fmt.Sprintf("dc1:hdd%d", r), 100)
if i == 0 && len(ids) > 0 {
putShards(n, ids...)
}
}
}
putShards(addCapNode(topo, "nvme", "dc1:ssd", 2), 13)
var raised raisedCaps
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4), RackTotalCapRaised: raised.record}, 2)
if len(raised) != 0 {
t.Errorf("cap reported as raised: %v", raised)
}
})
}
// TestPlanTotalCapRisesWhenRacksAreFull: two of 8 racks are full, so the other
// six can hold at best 3 each. A cap fixed at ceil(14/8) = 2 would block every
// destination and leave all four parity shards on rack1; the capacity-sized cap
// of 3 lets them spread as far as the room allows.
func TestPlanTotalCapRisesWhenRacksAreFull(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
layout := [][]int{{10, 11, 12, 13}, {0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}}
for r, ids := range layout {
putShards(addCapNode(topo, fmt.Sprintf("n%d", r+1), fmt.Sprintf("dc1:rack%d", r+1), 100), ids...)
}
addCapNode(topo, "full7", "dc1:rack7", 0)
addCapNode(topo, "full8", "dc1:rack8", 0)
var raised raisedCaps
planAndCheckRackTotals(t, topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4), RackTotalCapRaised: raised.record}, 3)
// Reported on every Plan (two here) while the cap stays raised.
want := "c1/1 cap=3 even=2"
if len(raised) != 2 || raised[0] != want || raised[1] != want {
t.Errorf("raised-cap reports = %v, want [%s %s]", raised, want, want)
}
})
}
// TestPlanRackTotalCap: Plan may move every shard, so shards already on a rack
// count as room there, not as held in place. All 14 on one rack still gives 2.
func TestPlanRackTotalCap(t *testing.T) {
build := func(free []int, held map[int]int) (map[string]*rack, map[string]int) {
topo := NewTopology()
next := 0
for r, f := range free {
n := addCapNode(topo, fmt.Sprintf("n%d", r), fmt.Sprintf("dc1:rack%d", r), f)
for i := 0; i < held[r]; i++ {
n.AddShards(capTestVid, "c1", 0, bits(next))
next++
}
}
return buildRacks(topo.nodes), countShardsByRack(capTestVk, topo.nodes)
}
cases := []struct {
name string
free []int
held map[int]int
want int
}{
{name: "all on one rack", free: []int{0, 50, 50, 50, 50, 50, 50, 50}, held: map[int]int{0: 14}, want: 2},
{name: "even over 5", free: []int{50, 50, 50, 50, 50}, held: map[int]int{0: 14}, want: 3},
{name: "two full empty racks", free: []int{50, 50, 50, 50, 50, 50, 0, 0}, held: map[int]int{0: 14}, want: 3},
{name: "small nearly full ninth rack", free: []int{50, 50, 50, 50, 50, 50, 50, 50, 1}, held: map[int]int{0: 13, 8: 1}, want: 2},
{name: "only the holding rack has room", free: []int{0, 0}, held: map[int]int{0: 14}, want: 14},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
racks, held := build(tc.free, tc.held)
if got := planRackTotalCap(capTestVk, racks, held, erasure_coding.TotalShardsCount, nil); got != tc.want {
t.Errorf("planRackTotalCap = %d, want %d", got, tc.want)
}
})
}
}
// TestPlanTotalCapDataRackWaitsForParitySlot: the data pass runs out of
// destinations, and the only slots left for rack5's surplus data open up when
// the parity pass moves parity off rack3 and rack4. One Plan must still bring
// every rack within the cap (3), using those freed slots, without moving any
// shard twice.
func TestPlanTotalCapDataRackWaitsForParitySlot(t *testing.T) {
forEachThreshold(t, func(t *testing.T, th float64) {
topo := NewTopology()
layout := [][]int{{0, 1, 2}, {3, 4}, {10, 11}, {12}, {5, 6, 7, 8, 9, 13}}
free := []int{0, 4, 1, 1, 4}
for r, ids := range layout {
n := addCapNode(topo, fmt.Sprintf("n%d", r+1), fmt.Sprintf("dc1:rack%d", r+1), free[r]+len(ids))
putShards(n, ids...)
}
moves := Plan(topo, Options{ImbalanceThreshold: th, Ratio: ratio(10, 4)})
seen := map[int]bool{}
for _, m := range moves {
if seen[m.ShardID] {
t.Errorf("shard %d moved twice in one plan: %+v", m.ShardID, moves)
}
seen[m.ShardID] = true
}
totals := shardTotalsPerRack(topo)
t.Logf("total shards per rack: %v", totals)
for rk, n := range totals {
if n > 3 {
t.Errorf("rack %s holds %d shards, want at most 3", rk, n)
}
}
})
}
// TestPlanTotalCapCountsSameRackCount: with SameRackCount=1 a node takes at
// most one shard of the volume, so racks of one node that already hold a shard
// have no room however many free slots they report. Rack A's seven shards can't
// spread, the cap is 7, and Plan reports it as raised.
func TestPlanTotalCapCountsSameRackCount(t *testing.T) {
topo := NewTopology()
for i := 0; i < 7; i++ {
putShards(addCapNode(topo, fmt.Sprintf("a%d", i), "dc1:rackA", 100), i)
}
for i, rk := range []string{"B", "C", "D", "E", "F", "G", "H"} {
putShards(addCapNode(topo, "n"+rk, "dc1:rack"+rk, 100), 7+i)
}
var raised raisedCaps
rp := &super_block.ReplicaPlacement{SameRackCount: 1}
Plan(topo, Options{ReplicaPlacement: rp, Ratio: ratio(10, 4), RackTotalCapRaised: raised.record})
if want := "c1/1 cap=7 even=2"; len(raised) != 1 || raised[0] != want {
t.Errorf("raised-cap reports = %v, want [%s]", raised, want)
}
}
+2 -6
View File
@@ -54,12 +54,8 @@ type Volume struct {
asyncRequestsChan chan *needle.AsyncRequest
asyncWorkerClosed bool
lastModifiedTsSeconds uint64 // unix time in seconds
lastAppendAtNs uint64 // unix time in nanoseconds
lastWriteAppendAtNs uint64 // AppendAtNs of the newest write; tombstones don't move it
lastWriteNeedleKey types.NeedleId // the write behind the watermark
lastWriteDeleted bool // that write was deleted, so recovery has to rescan
keepLastModifiedTsOnLoad bool
lastModifiedTsSeconds uint64 // unix time in seconds
lastAppendAtNs uint64 // unix time in nanoseconds
lastCompactIndexOffset uint64
lastCompactRevision uint16
+18 -34
View File
@@ -264,7 +264,7 @@ func (v *Volume) recoverLastModifiedTs(indexFile *os.File) {
if err != nil || indexSize == 0 {
return
}
appendAtNs, key, err := findLastWriteAppendAtNs(v, indexFile, indexSize)
appendAtNs, err := findLastWriteAppendAtNs(v, indexFile, indexSize)
if err != nil {
glog.Warningf("volume %d recover last write from %s: %v", v.Id, indexFile.Name(), err)
return
@@ -273,11 +273,6 @@ func (v *Volume) recoverLastModifiedTs(indexFile *os.File) {
return
}
v.lastModifiedTsSeconds = appendAtNs / uint64(time.Second)
if appendAtNs > v.lastWriteAppendAtNs {
v.lastWriteAppendAtNs = appendAtNs
v.lastWriteNeedleKey = key
v.lastWriteDeleted = false
}
}
// vacuumedLastWriteScanEntries bounds the work a vacuumed volume's recovery
@@ -290,27 +285,25 @@ var vacuumedLastWriteScanEntries = 1 << 16
// findLastWriteAppendAtNs scans the .idx backwards for the newest write -- an
// entry that is not a deletion tombstone -- and returns that needle's append
// timestamp and key. The .idx and the .dat share an order, so an
// append-ordered volume answers with the first write the scan reaches. Vacuum
// rewrites both in key order, which tracks write order only because the master
// issues keys increasing: an overwrite keeps its original, lower key, so a
// vacuumed volume has to take the maximum over every write it indexes. Returns
// 0 when the .idx holds nothing but tombstones, when a vacuumed volume holds
// more needles than the scan budget, or for a volume older than version 3,
// whose needles carry no append timestamp.
func findLastWriteAppendAtNs(v *Volume, indexFile *os.File, indexSize int64) (uint64, types.NeedleId, error) {
// timestamp. The .idx and the .dat share an order, so an append-ordered volume
// answers with the first write the scan reaches. Vacuum rewrites both in key
// order, which tracks write order only because the master issues keys
// increasing: an overwrite keeps its original, lower key, so a vacuumed volume
// has to take the maximum over every write it indexes. Returns 0 when the .idx
// holds nothing but tombstones, when a vacuumed volume holds more needles than
// the scan budget, or for a volume older than version 3, whose needles carry no
// append timestamp.
func findLastWriteAppendAtNs(v *Volume, indexFile *os.File, indexSize int64) (uint64, error) {
version := v.Version()
if version != needle.Version3 {
return 0, 0, nil
return 0, nil
}
scanEveryWrite := v.SuperBlock.CompactionRevision > 0
entryBudget := vacuumedLastWriteScanEntries
if scanEveryWrite && !affordableVacuumedScan(indexFile, indexSize, v.Id, v.FileName(".dat")) {
return 0, 0, nil
return 0, nil
}
var lastWriteAppendAtNs uint64
var lastWriteKey types.NeedleId
dead := make(map[types.NeedleId]struct{})
block := make([]byte, types.NeedleMapEntrySize*idx.RowsToRead)
for end := indexSize; end > 0; {
start := max(end-int64(len(block)), 0)
@@ -320,17 +313,11 @@ func findLastWriteAppendAtNs(v *Volume, indexFile *os.File, indexSize int64) (ui
err = nil
}
if err != nil {
return 0, 0, fmt.Errorf("read %s at %d: %v", indexFile.Name(), start, err)
return 0, fmt.Errorf("read %s at %d: %v", indexFile.Name(), start, err)
}
for i := len(entries) - types.NeedleMapEntrySize; i >= 0; i -= types.NeedleMapEntrySize {
key, offset, size := idx.IdxFileEntry(entries[i : i+types.NeedleMapEntrySize])
// The first row a key presents is its latest state: a tombstone
// there retires the write rows beneath it.
if _, gone := dead[key]; gone {
continue
}
if offset.IsZero() || size.IsDeleted() {
dead[key] = struct{}{}
continue
}
needleOffset := findNeedleOffset(v.DataBackend, version, offset.ToActualOffset(), key, size)
@@ -339,24 +326,21 @@ func findLastWriteAppendAtNs(v *Volume, indexFile *os.File, indexSize int64) (ui
}
appendAtNs, err := readNeedleAppendAtNs(v.DataBackend, needleOffset, size)
if err != nil {
return 0, 0, err
}
if appendAtNs > lastWriteAppendAtNs {
lastWriteAppendAtNs = appendAtNs
lastWriteKey = key
return 0, err
}
lastWriteAppendAtNs = max(lastWriteAppendAtNs, appendAtNs)
if !scanEveryWrite {
return lastWriteAppendAtNs, lastWriteKey, nil
return lastWriteAppendAtNs, nil
}
if entryBudget--; entryBudget == 0 {
glog.V(0).Infof("volume %d: more than %d needles to scan for its last write, keeping the %s mtime",
v.Id, vacuumedLastWriteScanEntries, v.FileName(".dat"))
return 0, 0, nil
return 0, nil
}
}
end = start
}
return lastWriteAppendAtNs, lastWriteKey, nil
return lastWriteAppendAtNs, nil
}
// affordableVacuumedScan reports whether a vacuumed volume's recovery scan fits
+3 -7
View File
@@ -172,7 +172,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
return fmt.Errorf("load remote file %v: %w", v.volumeInfo, err)
}
// Set lastModifiedTsSeconds from remote file to prevent premature expiry on startup
if len(v.volumeInfo.GetFiles()) > 0 && !v.keepLastModifiedTsOnLoad {
if len(v.volumeInfo.GetFiles()) > 0 {
remoteFileModifiedTime := v.volumeInfo.GetFiles()[0].GetModifiedTime()
if remoteFileModifiedTime > 0 {
v.lastModifiedTsSeconds = remoteFileModifiedTime
@@ -201,9 +201,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
if err != nil {
return datFileLoadError(v.FileName(".dat"), err)
}
if !v.keepLastModifiedTsOnLoad {
v.lastModifiedTsSeconds = uint64(modifiedTime.Unix())
}
v.lastModifiedTsSeconds = uint64(modifiedTime.Unix())
if fileSize >= super_block.SuperBlockSize {
alreadyHasSuperBlock = true
}
@@ -294,9 +292,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
v.noWriteOrDelete = true
glog.V(0).Infof("volumeDataIntegrityChecking failed %v", err)
}
if !v.keepLastModifiedTsOnLoad {
v.recoverLastModifiedTs(indexFile)
}
v.recoverLastModifiedTs(indexFile)
}
// The post-load structural check below uses the in-memory needle map
+1 -147
View File
@@ -250,7 +250,7 @@ func TestVolumeTtlClockSkipsUnaffordableScanWithoutDatReads(t *testing.T) {
defer func(budget int) { vacuumedLastWriteScanEntries = budget }(vacuumedLastWriteScanEntries)
vacuumedLastWriteScanEntries = 2
appendAtNs, _, err := findLastWriteAppendAtNs(v, indexFile, indexStat.Size())
appendAtNs, err := findLastWriteAppendAtNs(v, indexFile, indexStat.Size())
if err != nil {
t.Fatalf("recover last write: %v", err)
}
@@ -262,152 +262,6 @@ func TestVolumeTtlClockSkipsUnaffordableScanWithoutDatReads(t *testing.T) {
}
}
// TestVolumeTtlClockCarriedAcrossVacuumCommit covers the reload that ends a
// vacuum commit: the clock must keep the last write's append time rather than
// be re-derived, and the intervening delete's tombstone must not freshen it.
func TestVolumeTtlClockCarriedAcrossVacuumCommit(t *testing.T) {
dir := t.TempDir()
ttl, err := needle.ReadTTL("5m")
if err != nil {
t.Fatalf("read ttl: %v", err)
}
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, ttl, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
defer v.Close()
lastWriteNs := uint64(time.Now().Add(-2 * time.Hour).UnixNano())
for i := 1; i <= 3; i++ {
n := newRandomNeedle(uint64(i))
offset, _, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
backdateAppendAtNs(t, v, int64(offset), n.Size, lastWriteNs)
}
if _, err := v.doDeleteRequest(newEmptyNeedle(2)); err != nil {
t.Fatalf("delete needle 2: %v", err)
}
// Where a restart's recovery would have left the clock. The delete above
// pushed lastAppendAtNs to ~now; the commit must not consult it.
v.lastModifiedTsSeconds = lastWriteNs / uint64(time.Second)
v.lastWriteAppendAtNs = lastWriteNs
defer func(budget int) { vacuumedLastWriteScanEntries = budget }(vacuumedLastWriteScanEntries)
vacuumedLastWriteScanEntries = 1
if err := v.CompactByIndex(nil); err != nil {
t.Fatalf("compact: %v", err)
}
if err := v.CommitCompact(); err != nil {
t.Fatalf("commit compact: %v", err)
}
if v.SuperBlock.CompactionRevision == 0 {
t.Fatal("vacuum must bump CompactionRevision for this test to exercise the vacuumed path")
}
if got, want := v.lastModifiedTsSeconds, lastWriteNs/uint64(time.Second); got != want {
t.Errorf("TTL clock after commit is %d, want the last write at %d", got, want)
}
if !v.expired(v.ContentSize(), 1024*1024) {
t.Error("a TTL volume whose last write is 2h old must stay expired across a vacuum commit")
}
}
// TestVolumeTtlClockAtCommitUsesAppendTime covers a write whose client
// supplied modified time does not match when it was appended: the commit
// keeps the server-side append watermark the recovery scan would recompute.
func TestVolumeTtlClockAtCommitUsesAppendTime(t *testing.T) {
dir := t.TempDir()
ttl, err := needle.ReadTTL("5m")
if err != nil {
t.Fatalf("read ttl: %v", err)
}
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, ttl, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
defer v.Close()
future := uint64(time.Now().Add(24 * time.Hour).Unix())
n := newRandomNeedle(1)
n.LastModified = future
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
t.Fatalf("write needle: %v", err)
}
if v.lastModifiedTsSeconds < future {
t.Fatalf("clock %d did not follow the needle's modified time %d", v.lastModifiedTsSeconds, future)
}
appendWatermarkSec := v.lastWriteAppendAtNs / uint64(time.Second)
if err := v.CompactByIndex(nil); err != nil {
t.Fatalf("compact: %v", err)
}
if err := v.CommitCompact(); err != nil {
t.Fatalf("commit compact: %v", err)
}
if got := v.lastModifiedTsSeconds; got != appendWatermarkSec {
t.Errorf("TTL clock after commit is %d, want the append watermark %d", got, appendWatermarkSec)
}
}
// TestVolumeTtlClockAtCommitSkipsDeletedWrite covers a vacuum commit whose
// newest write was deleted first: the carried watermark belonged to that
// write, so the commit has to let the reload rescan and land on the newest
// surviving write rather than keep the volume alive on a deleted write's time.
func TestVolumeTtlClockAtCommitSkipsDeletedWrite(t *testing.T) {
dir := t.TempDir()
ttl, err := needle.ReadTTL("5m")
if err != nil {
t.Fatalf("read ttl: %v", err)
}
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, ttl, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
defer v.Close()
oldWriteNs := uint64(time.Now().Add(-2 * time.Hour).UnixNano())
newWriteNs := uint64(time.Now().Add(-time.Hour).UnixNano())
for _, w := range []struct {
id uint64
ns uint64
}{{1, oldWriteNs}, {2, newWriteNs}} {
n := newRandomNeedle(w.id)
offset, _, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle %d: %v", w.id, err)
}
backdateAppendAtNs(t, v, int64(offset), n.Size, w.ns)
}
// The delete lands inside the commit window: makeupDiff replays its
// tombstone into the new .idx behind the write row the copy carried.
if err := v.CompactByIndex(nil); err != nil {
t.Fatalf("compact: %v", err)
}
if _, err := v.doDeleteRequest(newEmptyNeedle(2)); err != nil {
t.Fatalf("delete needle 2: %v", err)
}
if !v.lastWriteDeleted {
t.Fatal("deleting the newest write must mark the watermark dead")
}
if err := v.CommitCompact(); err != nil {
t.Fatalf("commit compact: %v", err)
}
if got, want := v.lastModifiedTsSeconds, oldWriteNs/uint64(time.Second); got != want {
t.Errorf("TTL clock after commit is %d, want the surviving write at %d", got, want)
}
if v.lastWriteDeleted {
t.Error("the reload's rescan must reseed the watermark off the surviving write")
}
}
// TestVolumeExpireAtSecCountsFromLastWrite guards the destroy time an EC volume
// is reclaimed on (erasure_coding.EcVolume.IsTimeToDestroy). It was recomputed
// as now+TTL on every .vif write, so a read-only mark, a tier upload or an EC
+1 -11
View File
@@ -222,17 +222,7 @@ func (v *Volume) CommitCompact() error {
//time.Sleep(20 * time.Second)
glog.V(3).Infof("Loading volume %d commit file...", v.Id)
// The write watermark already equals what recoverLastModifiedTs would
// rescan, so keep the clock instead of paying for the scan under the lock.
// If its write was itself deleted, the reload recovers the newest
// surviving write instead.
if v.lastWriteAppendAtNs != 0 {
v.lastModifiedTsSeconds = v.lastWriteAppendAtNs / uint64(time.Second)
}
v.keepLastModifiedTsOnLoad = v.lastModifiedTsSeconds != 0 && !v.lastWriteDeleted
e := v.load(true, false, v.needleMapKind, 0, v.Version())
v.keepLastModifiedTsOnLoad = false
if e != nil {
if e := v.load(true, false, v.needleMapKind, 0, v.Version()); e != nil {
return e
}
glog.V(3).Infof("Finish committing volume %d", v.Id)
-20
View File
@@ -329,10 +329,6 @@ func (v *Volume) rollbackUnflushedWrite(n *needle.Needle, offset uint64, end int
}
}
}
if err == nil && n.Id == v.lastWriteNeedleKey {
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
v.lastWriteDeleted = true
}
if err != nil {
recoveryErr = errors.Join(recoveryErr,
fmt.Errorf("roll back the index of needle %d in volume %d: %w", n.Id, v.Id, err))
@@ -413,9 +409,6 @@ func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool, fsync bool)
return
}
v.lastAppendAtNs = n.AppendAtNs
v.lastWriteAppendAtNs = n.AppendAtNs
v.lastWriteNeedleKey = n.Id
v.lastWriteDeleted = false
// add to needle map
if !ok || uint64(nv.Offset.ToActualOffset()) < offset {
@@ -497,10 +490,6 @@ func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
return size, err
}
if n.Id == v.lastWriteNeedleKey {
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
v.lastWriteDeleted = true
}
return size, err
}
return 0, nil
@@ -535,9 +524,6 @@ func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
}
indexEnd := int64(v.nm.IndexFileSize())
batchLastAppendAtNs := v.lastAppendAtNs
batchLastWriteAppendAtNs := v.lastWriteAppendAtNs
batchLastWriteNeedleKey := v.lastWriteNeedleKey
batchLastWriteDeleted := v.lastWriteDeleted
batchLastModifiedTsSeconds := v.lastModifiedTsSeconds
for i := 0; i < len(currentRequests); i++ {
needleID := currentRequests[i].N.Id
@@ -577,9 +563,6 @@ func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
if syncErr := v.DataBackend.Sync(); syncErr != nil {
v.checkReadWriteError(syncErr)
v.lastAppendAtNs = batchLastAppendAtNs
v.lastWriteAppendAtNs = batchLastWriteAppendAtNs
v.lastWriteNeedleKey = batchLastWriteNeedleKey
v.lastWriteDeleted = batchLastWriteDeleted
v.lastModifiedTsSeconds = batchLastModifiedTsSeconds
batchErr := syncErr
if recoveryErr := v.rollbackBatch(end, indexEnd, orderedSnapshots, metricRollbacker, batchMetrics); recoveryErr != nil {
@@ -719,9 +702,6 @@ func (v *Volume) WriteNeedleBlob(needleId NeedleId, needleBlob []byte, size Size
return err
}
v.lastAppendAtNs = appendAtNs
v.lastWriteAppendAtNs = appendAtNs
v.lastWriteNeedleKey = needleId
v.lastWriteDeleted = false
// add to needle map
if err = v.nm.Put(needleId, ToOffset(int64(offset)), size); err != nil {
@@ -87,9 +87,6 @@ func Detection(
GlobalMaxMovesPerRack: 10,
// Balance heterogeneous-capacity racks by fractional fullness.
GlobalUtilizationBased: true,
RackTotalCapRaised: func(collection string, vid uint32, rackCap, evenCap int) {
glog.Warningf("EC volume %d (collection %q): rack-total-cap raised to %d shards per rack, above the even %d: the racks lack room for an even spread", vid, collection, rackCap, evenCap)
},
})
if len(moves) == 0 {
return nil, false, nil
@@ -18,7 +18,6 @@ type Config struct {
MinSizeMB int `json:"min_size_mb"`
PreferredTags []string `json:"preferred_tags"`
ReplicaPlacement string `json:"replica_placement"` // e.g. "020"; empty falls back to the master default replication
StrictPlacement bool `json:"strict_placement"` // fail planning instead of relaxing placement constraints
}
// NewDefaultConfig creates a new default erasure coding configuration
@@ -172,18 +171,6 @@ func GetConfigSpec() base.ConfigSpec {
InputType: "text",
CSSClasses: "form-control",
},
{
Name: "strict_placement",
JSONName: "strict_placement",
Type: config.FieldTypeBool,
DefaultValue: false,
Required: false,
DisplayName: "Strict Placement",
Description: "Refuse to encode a volume when the placement constraints can't be satisfied",
HelpText: "When enabled, a volume is only encoded if every shard can be placed within the per-disk, anti-affinity, replica-placement and per-rack caps, so the configured resilience is preserved. When disabled (default), unsatisfiable constraints are relaxed and noted in the log",
InputType: "checkbox",
CSSClasses: "form-check-input",
},
},
}
}
@@ -205,7 +192,6 @@ func (c *Config) ToTaskPolicy() *worker_pb.TaskPolicy {
CollectionFilter: c.CollectionFilter,
PreferredTags: preferredTagsCopy,
ReplicaPlacement: c.ReplicaPlacement,
StrictPlacement: c.StrictPlacement,
},
},
}
@@ -230,7 +216,6 @@ func (c *Config) FromTaskPolicy(policy *worker_pb.TaskPolicy) error {
c.CollectionFilter = ecConfig.CollectionFilter
c.PreferredTags = append([]string(nil), ecConfig.PreferredTags...)
c.ReplicaPlacement = ecConfig.ReplicaPlacement
c.StrictPlacement = ecConfig.StrictPlacement
}
return nil
+3 -10
View File
@@ -487,11 +487,8 @@ func buildNodeAddressMap(at *topology.ActiveTopology) map[string]string {
//
// Encode is lenient (PlaceDurabilityFirst): it relaxes caps/anti-affinity/RP and,
// last, the total-shards-per-rack cap as needed, failing only when no eligible
// disk has room. ecConfig.StrictPlacement instead fails the volume's planning
// when the constraints cannot be satisfied (PlaceStrict), so a volume is only
// encoded while its configured resilience is preserved. The task prefers the
// source disk type but spills if that type can't hold every shard. rp is the
// resolved replica placement (may be nil).
// disk has room. It prefers the source disk type but spills if that type can't
// hold every shard. rp is the resolved replica placement (may be nil).
func planECDestinations(snap *ecbalancer.Topology, nodeAddresses map[string]string, metric *types.VolumeHealthMetrics, ecConfig *Config, rp *super_block.ReplicaPlacement, dataShards, parityShards int) (*topology.MultiDestinationPlan, [][]uint32, error) {
if snap == nil {
return nil, nil, fmt.Errorf("EC placement snapshot not available")
@@ -514,17 +511,13 @@ func planECDestinations(snap *ecbalancer.Topology, nodeAddresses map[string]stri
for i := range need {
need[i] = i
}
mode := ecbalancer.PlaceDurabilityFirst
if ecConfig.StrictPlacement {
mode = ecbalancer.PlaceStrict
}
res, err := snap.Place(metric.VolumeID, metric.Collection, need, ecbalancer.Constraints{
DiskType: metric.DiskType,
DiskTypePolicy: ecbalancer.DiskTypePrefer,
PreferredTags: ecConfig.PreferredTags,
ReplicaPlacement: rp,
Ratio: func(string) (int, int) { return dataShards, parityShards },
}, mode)
}, ecbalancer.PlaceDurabilityFirst)
if err != nil {
return nil, nil, err
}
@@ -1,50 +0,0 @@
package erasure_coding
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/ecbalancer"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
"github.com/stretchr/testify/require"
)
// StrictPlacement refuses a volume whose configured caps cannot be met,
// rather than relaxing them: here one rack must hold all 14 shards under
// a 2-shards-per-rack replica placement.
func TestPlanECDestinationsStrictPlacement(t *testing.T) {
activeTopology := buildActiveTopology(t, 7, []string{"hdd"}, 100, 0, "")
metric := &types.VolumeHealthMetrics{
VolumeID: 1,
Server: "10.0.0.1:8080",
Size: 100 * 1024 * 1024,
}
rp, err := super_block.NewReplicaPlacementFromString("020")
require.NoError(t, err)
nodeAddresses := buildNodeAddressMap(activeTopology)
snap := ecbalancer.FromActiveTopology(activeTopology, erasure_coding.DataShardsCount)
cfg := NewDefaultConfig()
plan, shardsPerPlan, err := planECDestinations(snap, nodeAddresses, metric, cfg, rp, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
require.NoError(t, err, "lenient placement relaxes the unsatisfiable rack cap")
requireAllShardsPlaced(t, plan, shardsPerPlan)
snap = ecbalancer.FromActiveTopology(activeTopology, erasure_coding.DataShardsCount)
cfg.StrictPlacement = true
_, _, err = planECDestinations(snap, nodeAddresses, metric, cfg, rp, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
require.Error(t, err, "strict placement must refuse rather than weaken the rack cap")
}
func TestStrictPlacementRoundTripsThroughTaskPolicy(t *testing.T) {
cfg := NewDefaultConfig()
cfg.StrictPlacement = true
restored := NewDefaultConfig()
require.NoError(t, restored.FromTaskPolicy(cfg.ToTaskPolicy()))
require.True(t, restored.StrictPlacement, "strict placement must survive the persisted policy round trip")
restored.StrictPlacement = false
require.NoError(t, restored.FromTaskPolicy(restored.ToTaskPolicy()))
require.False(t, restored.StrictPlacement)
}
@@ -146,13 +146,6 @@ func (h *ErasureCodingHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_STRING,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TEXT,
},
{
Name: "strict_placement",
Label: "Strict Placement",
Description: "Fail EC planning when the placement constraints cannot be met instead of relaxing them.",
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_BOOL,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TOGGLE,
},
},
},
},
@@ -172,9 +165,6 @@ func (h *ErasureCodingHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
"replica_placement": {
Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""},
},
"strict_placement": {
Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: false},
},
},
},
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
@@ -634,8 +624,6 @@ func deriveErasureCodingWorkerConfig(values map[string]*plugin_pb.ConfigValue) *
taskConfig.ReplicaPlacement = strings.TrimSpace(pluginworker.ReadStringConfig(values, "replica_placement", taskConfig.ReplicaPlacement))
taskConfig.StrictPlacement = pluginworker.ReadBoolConfig(values, "strict_placement", taskConfig.StrictPlacement)
return &erasureCodingWorkerConfig{
TaskConfig: taskConfig,
}
+7 -90
View File
@@ -189,11 +189,9 @@ func (h *Handler) compactDataFiles(
return "", nil, err
}
// Build compaction bins: group small data files by partition, each bin's
// files in the order of their bounds so the merged file keeps the
// ordering its inputs had.
// Build compaction bins: group small data files by partition.
targetSize := compactionTargetSizeForPlan(config, rewritePlan)
bins := buildCompactionBins(candidateEntries, targetSize, minInputFiles, meta)
bins := buildCompactionBins(candidateEntries, targetSize, minInputFiles)
initialBinCount := len(bins)
bins = filterCompactionBinsByPlan(bins, config, rewritePlan)
if len(bins) == 0 {
@@ -271,11 +269,10 @@ func (h *Handler) compactDataFiles(
var mergedData []byte
var recordCount int64
rowGroupRows := rowsPerRowGroup(bin, config)
if rewritePlan != nil && rewritePlan.strategy == "sort" {
mergedData, recordCount, err = mergeParquetFilesSorted(ctx, filerClient, bucketName, dataPath, bin.Entries, positionDeletes, eqDeleteGroups, schema, rewritePlan, rowGroupRows)
mergedData, recordCount, err = mergeParquetFilesSorted(ctx, filerClient, bucketName, dataPath, bin.Entries, positionDeletes, eqDeleteGroups, schema, rewritePlan)
} else {
mergedData, recordCount, err = mergeParquetFiles(ctx, filerClient, bucketName, dataPath, bin.Entries, positionDeletes, eqDeleteGroups, schema, rowGroupRows)
mergedData, recordCount, err = mergeParquetFiles(ctx, filerClient, bucketName, dataPath, bin.Entries, positionDeletes, eqDeleteGroups, schema)
}
if err != nil {
glog.Warningf("iceberg compact: failed to merge bin %d (%d files): %v", binIdx, len(bin.Entries), err)
@@ -317,14 +314,6 @@ func (h *Handler) compactDataFiles(
}
writtenArtifacts = append(writtenArtifacts, artifact{dir: dataDir, fileName: mergedFileName})
// Record the column statistics readers prune files by; without
// them every scan has to read every compacted file.
if stats, statsErr := collectColumnStats(mergedData, schema); statsErr != nil {
glog.Warningf("iceberg compact: no column statistics for %s: %v", mergedFileName, statsErr)
} else {
stats.applyTo(dfBuilder)
}
mergedDataFile := dfBuilder.Build()
summary.addFile(mergedDataFile)
newEntry := iceberg.NewManifestEntry(
@@ -538,13 +527,7 @@ func (h *Handler) compactDataFiles(
// buildCompactionBins groups small data files by partition for bin-packing.
// A file is "small" if it's below targetSize. A bin must have at least
// minFiles entries to be worth compacting.
//
// With an order, every bin lists its files by their bounds on the ordering
// column and an oversized partition is split into runs of consecutive files,
// so each merged file covers one contiguous range of that column. Without one
// the files keep manifest order and an oversized partition is packed
// largest-first.
func buildCompactionBins(entries []iceberg.ManifestEntry, targetSize int64, minFiles int, meta table.Metadata) []compactionBin {
func buildCompactionBins(entries []iceberg.ManifestEntry, targetSize int64, minFiles int) []compactionBin {
if minFiles < 2 {
minFiles = 2
}
@@ -577,37 +560,14 @@ func buildCompactionBins(entries []iceberg.ManifestEntry, targetSize int64, minF
bin.TotalSize += df.FileSizeBytes()
}
// Filter to bins with enough files, splitting oversized bins. The merge
// order resolves per group over the files that survived the eligibility
// filter, so a file that can never participate (oversized, another
// format) cannot veto ordering for the ones that can.
// Filter to bins with enough files, splitting oversized bins
var result []compactionBin
for _, bin := range groups {
if len(bin.Entries) < minFiles {
continue
}
order := resolveCompactionOrder(meta, bin.Entries)
order.sortEntries(bin.Entries)
if bin.TotalSize <= targetSize {
result = append(result, *bin)
} else if order != nil {
runs, leftover := splitOrderedBin(*bin, targetSize, minFiles)
result = append(result, runs...)
if order.bestEffort && len(leftover) > 0 {
runtBin := compactionBin{PartitionKey: bin.PartitionKey, Partition: bin.Partition, SpecID: bin.SpecID, Entries: leftover}
packed := splitOversizedBin(runtBin, targetSize, minFiles)
if len(packed) == 0 {
// Stragglers cannot merge even with each other; repacking
// the whole bin lets them pair across the ordered runs.
// Only replace the runs when the repack yields bins —
// otherwise the runs stay valid compaction work.
if full := splitOversizedBin(*bin, targetSize, minFiles); len(full) > 0 {
result = result[:len(result)-len(runs)]
packed = full
}
}
result = append(result, packed...)
}
} else {
result = append(result, splitOversizedBin(*bin, targetSize, minFiles)...)
}
@@ -958,46 +918,6 @@ func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, iceberg
return indices, nil
}
const (
// Iceberg's write.parquet.row-group-size-bytes default and PyIceberg's
// write.parquet.row-group-limit default.
defaultRowGroupSizeBytes = 128 * 1024 * 1024
defaultRowGroupRowLimit = 1048576
minRowGroupRows = 1024
)
// rowsPerRowGroup is the most rows one row group of a compacted file holds:
// the row limit, lowered so a row group stays near the byte size, estimated
// from the bin's inputs' bytes per row. parquet-go's writers have no limit of
// their own, so without one every compacted file is a single row group. The
// floor only protects the estimate — a configured row limit always wins.
func rowsPerRowGroup(bin compactionBin, config Config) int64 {
rows, sizeBytes := config.RowGroupRowLimit, config.RowGroupSizeBytes
explicit := rows > 0
if !explicit {
rows = defaultRowGroupRowLimit
}
if sizeBytes <= 0 {
sizeBytes = defaultRowGroupSizeBytes
}
var totalRows int64
for _, entry := range bin.Entries {
totalRows += entry.DataFile().Count()
}
if totalRows > 0 && bin.TotalSize > 0 {
bytesPerRow := max(bin.TotalSize/totalRows, 1)
estimated := sizeBytes / bytesPerRow
if !explicit {
estimated = max(estimated, minRowGroupRows)
}
rows = min(rows, estimated)
}
if !explicit {
rows = max(rows, minRowGroupRows)
}
return rows
}
// mergeParquetFiles reads multiple small Parquet files and merges them into
// a single Parquet file, optionally filtering out rows matching position or
// equality deletes. Files are processed one at a time to keep memory usage
@@ -1010,7 +930,6 @@ func mergeParquetFiles(
positionDeletes map[string][]int64,
eqDeleteGroups []equalityDeleteGroup,
icebergSchema *iceberg.Schema,
rowGroupRows int64,
) ([]byte, int64, error) {
if len(entries) == 0 {
return nil, 0, fmt.Errorf("no entries to merge")
@@ -1035,7 +954,7 @@ func mergeParquetFiles(
}
var outputBuf bytes.Buffer
writer := parquet.NewWriter(&outputBuf, parquetSchema, parquet.MaxRowsPerRowGroup(rowGroupRows))
writer := parquet.NewWriter(&outputBuf, parquetSchema)
drainReader := func(reader *parquet.Reader, source string) (int64, error) {
return visitFilteredParquetRows(ctx, reader, source, bucketName, dataPath, positionDeletes, resolvedEqGroups, func(filtered []parquet.Row) error {
@@ -1200,7 +1119,6 @@ func mergeParquetFilesSorted(
eqDeleteGroups []equalityDeleteGroup,
icebergSchema *iceberg.Schema,
rewritePlan *compactionRewritePlan,
rowGroupRows int64,
) ([]byte, int64, error) {
if len(entries) == 0 {
return nil, 0, fmt.Errorf("no entries to merge")
@@ -1250,7 +1168,6 @@ func mergeParquetFilesSorted(
var outputBuf bytes.Buffer
writer := parquet.NewSortingWriter[any](&outputBuf, sortBufferRows, parquetSchema,
parquet.MaxRowsPerRowGroup(rowGroupRows),
parquet.SortingWriterConfig(
parquet.SortingColumns(sortingColumns...),
parquet.SortingBuffers(parquet.NewFileBufferPool(spillDir, "seaweedfs-iceberg-sort-*")),
-201
View File
@@ -1,201 +0,0 @@
package iceberg
import (
"sort"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
)
// compactionOrder names the column by whose bounds a bin's input files are
// ordered before they are merged: the first identity field of the table's
// sort order when it declares one, otherwise the first column every candidate
// file carries bounds for. Rows are copied file by file, so a merged file is
// as ordered as the sequence of its inputs.
type compactionOrder struct {
fieldID int
typ iceberg.PrimitiveType
descending bool
// bestEffort marks an order inferred from column bounds rather than the
// table's declared sort order; runs it cannot form may still merge by
// size since contiguous ranges are a preference, not a requirement.
bestEffort bool
}
func resolveCompactionOrder(meta table.Metadata, entries []iceberg.ManifestEntry) *compactionOrder {
if meta == nil || meta.CurrentSchema() == nil || len(entries) == 0 {
return nil
}
schema := meta.CurrentSchema()
if sortOrder := meta.SortOrder(); !sortOrder.IsUnsorted() {
for _, sortField := range sortOrder.Fields() {
if _, ok := sortField.Transform.(iceberg.IdentityTransform); !ok {
continue
}
field, ok := schema.FindFieldByID(sortField.SourceID())
if !ok {
continue
}
typ, ok := field.Type.(iceberg.PrimitiveType)
if !ok {
continue
}
candidate := &compactionOrder{fieldID: field.ID, typ: typ, descending: sortField.Direction == table.SortDESC}
// The declared order only holds when every entry carries a bound
// for it; otherwise merging would claim sortedness it cannot
// verify. Fall back to inference instead of ordering by a later
// sort field alone.
if candidate.coversEntries(entries) {
return candidate
}
break
}
}
// A column only orders the merge when every entry in the group carries a
// bound for it. The check is scoped to the entries handed in — a bin's
// eligible files — so an unrelated file without bounds (oversized, a
// different format, or another partition) cannot disable ordering here.
for _, field := range schema.Fields() {
typ, ok := field.Type.(iceberg.PrimitiveType)
if !ok {
continue
}
candidate := &compactionOrder{fieldID: field.ID, typ: typ, bestEffort: true}
if candidate.coversEntries(entries) {
return candidate
}
}
return nil
}
func (o *compactionOrder) coversEntries(entries []iceberg.ManifestEntry) bool {
for _, entry := range entries {
if _, ok := o.key(entry); !ok {
return false
}
}
return true
}
// key is the bound a file is ordered by: its lower bound on the column for an
// ascending order, its upper bound for a descending one.
func (o *compactionOrder) key(entry iceberg.ManifestEntry) (iceberg.Literal, bool) {
df := entry.DataFile()
raw := df.LowerBoundValues()[o.fieldID]
if o.descending {
raw = df.UpperBoundValues()[o.fieldID]
}
if raw == nil {
return nil, false
}
lit, err := iceberg.LiteralFromBytes(o.typ, raw)
return lit, err == nil
}
// sortEntries orders a bin's files by their key. Files without a key sort
// after the rest, in their original order.
func (o *compactionOrder) sortEntries(entries []iceberg.ManifestEntry) {
if o == nil || len(entries) < 2 {
return
}
type keyed struct {
key iceberg.Literal
ok bool
}
keys := make([]keyed, len(entries))
idx := make([]int, len(entries))
for i, entry := range entries {
k, ok := o.key(entry)
keys[i], idx[i] = keyed{k, ok}, i
}
sort.SliceStable(idx, func(i, j int) bool {
a, b := keys[idx[i]], keys[idx[j]]
if a.ok != b.ok {
return a.ok
}
if !a.ok {
return false
}
c, ok := compareLiterals(a.key, b.key)
if o.descending {
c = -c
}
return ok && c < 0
})
sorted := make([]iceberg.ManifestEntry, len(entries))
for i, j := range idx {
sorted[i] = entries[j]
}
copy(entries, sorted)
}
// splitOrderedBin splits a bin whose files are in bound order into runs of
// consecutive files that stay under targetSize, so every output covers one
// contiguous range of the ordering column. The returned entries are the runs
// too short to reach minFiles: the caller can still merge them by size when
// contiguous ranges are only a preference, or leave them for a later pass
// when order must hold.
func splitOrderedBin(bin compactionBin, targetSize int64, minFiles int) (valid []compactionBin, leftover []iceberg.ManifestEntry) {
newBin := func() compactionBin {
return compactionBin{PartitionKey: bin.PartitionKey, Partition: bin.Partition, SpecID: bin.SpecID}
}
current := newBin()
flush := func() {
if len(current.Entries) >= minFiles {
valid = append(valid, current)
} else {
leftover = append(leftover, current.Entries...)
}
current = newBin()
}
for _, entry := range bin.Entries {
size := entry.DataFile().FileSizeBytes()
if current.TotalSize > 0 && current.TotalSize+size > targetSize {
flush()
}
current.Entries = append(current.Entries, entry)
current.TotalSize += size
}
flush()
return valid, leftover
}
// compareLiterals orders two literals of the same type; false when they are
// not comparable.
func compareLiterals(a, b iceberg.Literal) (int, bool) {
switch x := a.(type) {
case iceberg.TypedLiteral[bool]:
return compareTyped(x, b)
case iceberg.TypedLiteral[int32]:
return compareTyped(x, b)
case iceberg.TypedLiteral[int64]:
return compareTyped(x, b)
case iceberg.TypedLiteral[float32]:
return compareTyped(x, b)
case iceberg.TypedLiteral[float64]:
return compareTyped(x, b)
case iceberg.TypedLiteral[iceberg.Date]:
return compareTyped(x, b)
case iceberg.TypedLiteral[iceberg.Time]:
return compareTyped(x, b)
case iceberg.TypedLiteral[iceberg.Timestamp]:
return compareTyped(x, b)
case iceberg.TypedLiteral[iceberg.TimestampNano]:
return compareTyped(x, b)
case iceberg.TypedLiteral[string]:
return compareTyped(x, b)
case iceberg.TypedLiteral[[]byte]:
return compareTyped(x, b)
case iceberg.TypedLiteral[iceberg.Decimal]:
return compareTyped(x, b)
}
return 0, false
}
func compareTyped[T iceberg.LiteralType](a iceberg.TypedLiteral[T], b iceberg.Literal) (int, bool) {
bt, ok := b.(iceberg.TypedLiteral[T])
if !ok {
return 0, false
}
return a.Comparator()(a.Value(), bt.Value()), true
}
@@ -1,388 +0,0 @@
package iceberg
import (
"bytes"
"context"
"encoding/json"
"fmt"
"path"
"strings"
"testing"
"time"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
type boundedFile struct {
Name string
IDs []int64
Lower, Upper int64
SizeBytes int64
NoBounds bool
}
// populateBoundedTable is populateTableWithDeleteFiles narrowed to data
// files whose manifest entries carry bounds on the id column.
func populateBoundedTable(t *testing.T, fs *fakeFilerServer, setup tableSetup, files []boundedFile) {
t.Helper()
populateBoundedTableSorted(t, fs, setup, files, table.UnsortedSortOrder)
}
func populateBoundedTableSorted(t *testing.T, fs *fakeFilerServer, setup tableSetup, files []boundedFile, sortOrder table.SortOrder) {
t.Helper()
schema := newTestSchema()
spec := *iceberg.UnpartitionedSpec
meta, err := table.NewMetadata(schema, &spec, sortOrder, "s3://"+setup.BucketName+"/"+setup.dataPath(), nil)
if err != nil {
t.Fatalf("create metadata: %v", err)
}
bucketPath := path.Join(s3tables.TablesPath, setup.BucketName)
nsPath := path.Join(bucketPath, setup.Namespace)
tableFilerPath := path.Join(bucketPath, setup.dataPath())
metaDir := path.Join(tableFilerPath, "metadata")
dataDir := path.Join(tableFilerPath, "data")
version := meta.Version()
var entries []iceberg.ManifestEntry
for _, f := range files {
rows := make([]struct {
ID int64
Name string
}, len(f.IDs))
for i, id := range f.IDs {
rows[i] = struct {
ID int64
Name string
}{id, fmt.Sprintf("r%d", id)}
}
data := writeTestParquetFile(t, fs, dataDir, f.Name, rows)
size := int64(len(data))
if f.SizeBytes > 0 {
size = f.SizeBytes
}
dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, setup.fileRef("data", f.Name),
iceberg.ParquetFile, map[int]any{}, nil, nil, int64(len(f.IDs)), size)
if err != nil {
t.Fatalf("build data file %s: %v", f.Name, err)
}
if !f.NoBounds {
lo, _ := iceberg.Int64Literal(f.Lower).MarshalBinary()
hi, _ := iceberg.Int64Literal(f.Upper).MarshalBinary()
dfb.LowerBoundValues(map[int][]byte{1: lo}).UpperBoundValues(map[int][]byte{1: hi})
}
snapID := int64(1)
entries = append(entries, iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build()))
}
var manifestBuf bytes.Buffer
mf, err := iceberg.WriteManifest(setup.fileRef("metadata", "data-manifest-1.avro"), &manifestBuf,
version, spec, schema, 1, entries)
if err != nil {
t.Fatalf("write manifest: %v", err)
}
fs.putEntry(metaDir, "data-manifest-1.avro", &filer_pb.Entry{
Name: "data-manifest-1.avro", Content: manifestBuf.Bytes(),
Attributes: &filer_pb.FuseAttributes{Mtime: time.Now().Unix(), FileSize: uint64(manifestBuf.Len())},
})
var mlBuf bytes.Buffer
seqNum := int64(1)
if err := iceberg.WriteManifestList(version, &mlBuf, 1, nil, &seqNum, 0, []iceberg.ManifestFile{mf}); err != nil {
t.Fatalf("write manifest list: %v", err)
}
fs.putEntry(metaDir, "snap-1.avro", &filer_pb.Entry{
Name: "snap-1.avro", Content: mlBuf.Bytes(),
Attributes: &filer_pb.FuseAttributes{Mtime: time.Now().Unix(), FileSize: uint64(mlBuf.Len())},
})
snap := table.Snapshot{SnapshotID: 1, TimestampMs: time.Now().UnixMilli(),
ManifestList: setup.fileRef("metadata", "snap-1.avro")}
builder, err := table.MetadataBuilderFromBase(meta, "s3://"+setup.BucketName+"/"+setup.dataPath())
if err != nil {
t.Fatalf("metadata builder: %v", err)
}
if err := builder.AddSnapshot(&snap); err != nil {
t.Fatalf("add snapshot: %v", err)
}
if err := builder.SetSnapshotRef(table.MainBranch, snap.SnapshotID, table.BranchRef); err != nil {
t.Fatalf("set snapshot ref: %v", err)
}
meta, err = builder.Build()
if err != nil {
t.Fatalf("build metadata: %v", err)
}
fullMetadataJSON, _ := json.Marshal(meta)
xattr, _ := json.Marshal(map[string]interface{}{
"metadataVersion": 1,
"metadataLocation": setup.fileRef("metadata", "v1.metadata.json"),
"metadata": map[string]interface{}{"fullMetadata": json.RawMessage(fullMetadataJSON)},
})
fs.putEntry(path.Join(s3tables.TablesPath), setup.BucketName, &filer_pb.Entry{
Name: setup.BucketName, IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyTableBucket: []byte("true")},
})
fs.putEntry(bucketPath, setup.Namespace, &filer_pb.Entry{Name: setup.Namespace, IsDirectory: true})
fs.putEntry(nsPath, setup.TableName, &filer_pb.Entry{
Name: setup.TableName, IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: xattr},
})
}
// A bin's files are merged in the order of their bounds on the
// ordering column, not manifest order, so a merged file is as ordered
// as the sequence of its inputs.
func TestCompactDataFilesKeepsInputOrderByBounds(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
// manifest order is the reverse of bound order
populateBoundedTable(t, fs, setup, []boundedFile{
{Name: "hi.parquet", IDs: []int64{3, 4}, Lower: 3, Upper: 4},
{Name: "lo.parquet", IDs: []int64{1, 2}, Lower: 1, Upper: 2},
})
handler := NewHandler(nil)
config := Config{TargetFileSizeBytes: 256 * 1024 * 1024, MinInputFiles: 2, MaxCommitRetries: 3}
if _, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil); err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
df := compactedDataFile(t, client, setup)
ids := compactedIDs(t, client, setup, df.FilePath())
want := []int64{1, 2, 3, 4}
if fmt.Sprint(ids) != fmt.Sprint(want) {
t.Errorf("merged rows = %v, want %v", ids, want)
}
}
// An oversized partition is split into runs of consecutive files in
// bound order, so each output covers one contiguous range.
func TestCompactDataFilesSplitsOrderedRuns(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
// four disjoint ranges, each "4 MB": one bin, split into two runs of two
populateBoundedTable(t, fs, setup, []boundedFile{
{Name: "q4.parquet", IDs: []int64{7, 8}, Lower: 7, Upper: 8, SizeBytes: 4 << 20},
{Name: "q1.parquet", IDs: []int64{1, 2}, Lower: 1, Upper: 2, SizeBytes: 4 << 20},
{Name: "q3.parquet", IDs: []int64{5, 6}, Lower: 5, Upper: 6, SizeBytes: 4 << 20},
{Name: "q2.parquet", IDs: []int64{3, 4}, Lower: 3, Upper: 4, SizeBytes: 4 << 20},
})
handler := NewHandler(nil)
config := Config{TargetFileSizeBytes: 8 << 20, MinInputFiles: 2, MaxCommitRetries: 3}
result, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "compacted 4 files into 2") {
t.Fatalf("expected two ordered runs, got %q", result)
}
// each output must cover one contiguous range
state, err := loadCurrentMetadata(context.Background(), client, setup.BucketName, setup.tablePath())
if err != nil {
t.Fatalf("loadCurrentMetadata: %v", err)
}
manifests, err := loadCurrentManifests(context.Background(), client, setup.BucketName, state.DataPath, state.Metadata)
if err != nil {
t.Fatalf("loadCurrentManifests: %v", err)
}
var ranges [][2]int64
for _, mf := range manifests {
if mf.ManifestContent() != iceberg.ManifestContentData {
continue
}
manifestData, err := loadFileByIcebergPath(context.Background(), client, setup.BucketName, state.DataPath, mf.FilePath())
if err != nil {
t.Fatalf("load manifest: %v", err)
}
entries, err := iceberg.ReadManifest(mf, bytes.NewReader(manifestData), true)
if err != nil {
t.Fatalf("read manifest: %v", err)
}
for _, entry := range entries {
if entry.Status() == iceberg.EntryStatusDELETED {
continue
}
lo, _ := iceberg.LiteralFromBytes(iceberg.PrimitiveTypes.Int64, entry.DataFile().LowerBoundValues()[1])
hi, _ := iceberg.LiteralFromBytes(iceberg.PrimitiveTypes.Int64, entry.DataFile().UpperBoundValues()[1])
ranges = append(ranges, [2]int64{int64(lo.(iceberg.Int64Literal)), int64(hi.(iceberg.Int64Literal))})
}
}
if len(ranges) != 2 {
t.Fatalf("expected 2 output files, got %d", len(ranges))
}
// ranges must be contiguous runs, not interleaved: {1..4} and {5..8}
for _, r := range ranges {
if r[1]-r[0] != 3 {
t.Errorf("output covers non-contiguous range %v", r)
}
}
}
// An oversized file without bounds can never join a merge, so it must not
// disable bounds ordering for the files that can.
func TestCompactDataFilesOrdersPastIneligibleFile(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
populateBoundedTable(t, fs, setup, []boundedFile{
{Name: "hi.parquet", IDs: []int64{3, 4}, Lower: 3, Upper: 4},
{Name: "lo.parquet", IDs: []int64{1, 2}, Lower: 1, Upper: 2},
{Name: "huge.parquet", IDs: []int64{9}, SizeBytes: 512 << 20, NoBounds: true},
})
handler := NewHandler(nil)
config := Config{TargetFileSizeBytes: 256 << 20, MinInputFiles: 2, MaxCommitRetries: 3}
result, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "compacted 2 files into 1") {
t.Fatalf("expected only the two eligible files to merge, got %q", result)
}
var merged iceberg.DataFile
for _, df := range liveDataFiles(t, client, setup) {
if !strings.HasSuffix(df.FilePath(), "huge.parquet") {
merged = df
}
}
ids := compactedIDs(t, client, setup, merged.FilePath())
want := []int64{1, 2, 3, 4}
if fmt.Sprint(ids) != fmt.Sprint(want) {
t.Errorf("merged rows = %v, want %v", ids, want)
}
}
// Runs too short to merge in bound order still merge by size, so files that
// cannot form a contiguous run are not stranded for every later pass.
func TestCompactDataFilesMergesStrandedRun(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
populateBoundedTable(t, fs, setup, []boundedFile{
{Name: "r1.parquet", IDs: []int64{1}, Lower: 1, Upper: 2, SizeBytes: 4 << 20},
{Name: "r2.parquet", IDs: []int64{3}, Lower: 3, Upper: 4, SizeBytes: 4 << 20},
{Name: "r3.parquet", IDs: []int64{5}, Lower: 5, Upper: 6, SizeBytes: 6 << 20},
{Name: "r4.parquet", IDs: []int64{7}, Lower: 7, Upper: 8, SizeBytes: 3 << 20},
{Name: "r5.parquet", IDs: []int64{9}, Lower: 9, Upper: 10, SizeBytes: 3 << 20},
})
handler := NewHandler(nil)
config := Config{TargetFileSizeBytes: 10 << 20, MinInputFiles: 3, MaxCommitRetries: 3}
result, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "compacted 3 files into 1") {
t.Fatalf("expected stranded files to merge by size, got %q", result)
}
}
// A declared sort order is preserved at the cost of compaction progress:
// runs too short to merge are left for later passes instead of being
// repacked out of order.
func TestCompactDataFilesKeepsStrandedRunForSortedTable(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
sortOrder, err := table.NewSortOrder(1, []table.SortField{{
SourceIDs: []int{1},
Transform: iceberg.IdentityTransform{},
Direction: table.SortASC,
NullOrder: table.NullsFirst,
}})
if err != nil {
t.Fatalf("new sort order: %v", err)
}
populateBoundedTableSorted(t, fs, setup, []boundedFile{
{Name: "r1.parquet", IDs: []int64{1}, Lower: 1, Upper: 2, SizeBytes: 4 << 20},
{Name: "r2.parquet", IDs: []int64{3}, Lower: 3, Upper: 4, SizeBytes: 4 << 20},
{Name: "r3.parquet", IDs: []int64{5}, Lower: 5, Upper: 6, SizeBytes: 6 << 20},
{Name: "r4.parquet", IDs: []int64{7}, Lower: 7, Upper: 8, SizeBytes: 3 << 20},
{Name: "r5.parquet", IDs: []int64{9}, Lower: 9, Upper: 10, SizeBytes: 3 << 20},
}, sortOrder)
handler := NewHandler(nil)
config := Config{TargetFileSizeBytes: 10 << 20, MinInputFiles: 3, MaxCommitRetries: 3}
result, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "no files eligible for compaction") {
t.Fatalf("expected underfilled ordered runs to be kept, got %q", result)
}
}
// A declared sort order only applies when every file carries a bound for its
// column; a file without one falls back to inference or unordered packing.
func TestResolveCompactionOrderSkipsUncoveredSortField(t *testing.T) {
schema := newTestSchema()
spec := *iceberg.UnpartitionedSpec
sortOrder, err := table.NewSortOrder(1, []table.SortField{{
SourceIDs: []int{1},
Transform: iceberg.IdentityTransform{},
Direction: table.SortASC,
NullOrder: table.NullsFirst,
}})
if err != nil {
t.Fatalf("new sort order: %v", err)
}
meta, err := table.NewMetadata(schema, &spec, sortOrder, "s3://b/p", nil)
if err != nil {
t.Fatalf("create metadata: %v", err)
}
entry := func(name string, bounded bool) iceberg.ManifestEntry {
dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData,
"s3://b/data/"+name, iceberg.ParquetFile, map[int]any{}, nil, nil, 2, 16)
if err != nil {
t.Fatalf("build data file: %v", err)
}
if bounded {
lo, _ := iceberg.Int64Literal(1).MarshalBinary()
hi, _ := iceberg.Int64Literal(2).MarshalBinary()
dfb.LowerBoundValues(map[int][]byte{1: lo}).UpperBoundValues(map[int][]byte{1: hi})
}
snapID := int64(1)
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())
}
if order := resolveCompactionOrder(meta, []iceberg.ManifestEntry{
entry("a.parquet", true), entry("b.parquet", true),
}); order == nil || order.bestEffort {
t.Fatalf("covered sort field: got %+v, want strict order", order)
}
if order := resolveCompactionOrder(meta, []iceberg.ManifestEntry{
entry("a.parquet", true), entry("b.parquet", false),
}); order != nil {
t.Fatalf("uncovered sort field: got %+v, want nil", order)
}
}
// A full-bin repack that produces nothing must not discard the ordered runs
// it was meant to replace — they are still valid compaction work.
func TestCompactDataFilesKeepsRunsWhenRepackFails(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
populateBoundedTable(t, fs, setup, []boundedFile{
{Name: "r1.parquet", IDs: []int64{1}, Lower: 1, Upper: 2, SizeBytes: 4 << 20},
{Name: "r2.parquet", IDs: []int64{3}, Lower: 3, Upper: 4, SizeBytes: 3 << 20},
{Name: "r3.parquet", IDs: []int64{5}, Lower: 5, Upper: 6, SizeBytes: 3 << 20},
{Name: "r4.parquet", IDs: []int64{7}, Lower: 7, Upper: 8, SizeBytes: 6 << 20},
{Name: "r5.parquet", IDs: []int64{9}, Lower: 9, Upper: 10, SizeBytes: 6 << 20},
})
handler := NewHandler(nil)
config := Config{TargetFileSizeBytes: 10 << 20, MinInputFiles: 3, MaxCommitRetries: 3}
result, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
if err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
if !strings.Contains(result, "compacted 3 files into 1") {
t.Fatalf("expected the ordered run to survive the failed repack, got %q", result)
}
}
@@ -1,97 +0,0 @@
package iceberg
import (
"bytes"
"context"
"fmt"
"testing"
"github.com/apache/iceberg-go"
"github.com/parquet-go/parquet-go"
)
// Compacted files get row groups from the table's
// write.parquet.row-group-limit instead of one row group per file.
func TestCompactDataFilesWritesSeveralRowGroups(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
type rowsT = struct {
ID int64
Name string
}
makeRows := func(lo, hi int64) []rowsT {
rows := make([]rowsT, 0, hi-lo)
for i := lo; i < hi; i++ {
rows = append(rows, rowsT{i, fmt.Sprintf("r%d", i)})
}
return rows
}
populateTableWithDeleteFiles(t, fs, setup,
[]struct {
Name string
Rows []rowsT
}{
{"d1.parquet", makeRows(0, 1500)},
{"d2.parquet", makeRows(1500, 3000)},
},
nil, nil,
)
handler := NewHandler(nil)
config := Config{
TargetFileSizeBytes: 256 * 1024 * 1024,
MinInputFiles: 2,
MaxCommitRetries: 3,
RowGroupRowLimit: 2000,
}
if _, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil); err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
state, err := loadCurrentMetadata(context.Background(), client, setup.BucketName, setup.tablePath())
if err != nil {
t.Fatalf("loadCurrentMetadata: %v", err)
}
df := compactedDataFile(t, client, setup)
data, err := loadFileByIcebergPath(context.Background(), client, setup.BucketName, state.DataPath, df.FilePath())
if err != nil {
t.Fatalf("load compacted file: %v", err)
}
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("open compacted file: %v", err)
}
if got := len(f.Metadata().RowGroups); got != 2 {
t.Errorf("row groups = %d, want 2 (3000 rows at row-group-limit 2000)", got)
}
}
// A configured row-group limit is a cap, not a floor: small explicit limits
// are honored instead of being raised to the estimate floor.
func TestRowsPerRowGroupHonorsConfiguredLimit(t *testing.T) {
entries := make([]iceberg.ManifestEntry, 0, 2)
spec := *iceberg.UnpartitionedSpec
for _, name := range []string{"a.parquet", "b.parquet"} {
dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData,
"s3://b/data/"+name, iceberg.ParquetFile, map[int]any{}, nil, nil, 300, 9000)
if err != nil {
t.Fatalf("build data file: %v", err)
}
snapID := int64(1)
entries = append(entries, iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build()))
}
bin := compactionBin{Entries: entries, TotalSize: 18000}
if got := rowsPerRowGroup(bin, Config{RowGroupRowLimit: 128}); got != 128 {
t.Errorf("explicit limit: rowsPerRowGroup = %d, want 128", got)
}
// 30 bytes/row, byte cap 128MB: the estimate of ~4.4M rows exceeds the 2M
// default, so the default holds; the floor lifts a degenerate estimate.
if got := rowsPerRowGroup(bin, Config{RowGroupSizeBytes: 1024}); got != minRowGroupRows {
t.Errorf("floored estimate: rowsPerRowGroup = %d, want %d", got, minRowGroupRows)
}
if got := rowsPerRowGroup(bin, Config{}); got != defaultRowGroupRowLimit {
t.Errorf("default: rowsPerRowGroup = %d, want %d", got, defaultRowGroupRowLimit)
}
}
-231
View File
@@ -1,231 +0,0 @@
package iceberg
import (
"bytes"
"math"
"sort"
"strings"
"time"
"unicode/utf8"
"github.com/apache/iceberg-go"
"github.com/parquet-go/parquet-go"
"github.com/parquet-go/parquet-go/format"
)
// boundTruncateLength is the default metrics mode of the Iceberg reference
// implementation, truncate(16), applied to string and binary bounds.
const boundTruncateLength = 16
// columnStats is what a data file's manifest entry records about its columns,
// keyed by Iceberg field id. Readers plan scans from it.
type columnStats struct {
sizes, values, nulls map[int]int64
lower, upper map[int][]byte
splitOffsets []int64
}
func (s *columnStats) applyTo(b *iceberg.DataFileBuilder) {
b.ColumnSizes(s.sizes).ValueCounts(s.values).NullValueCounts(s.nulls).
LowerBoundValues(s.lower).UpperBoundValues(s.upper).SplitOffsets(s.splitOffsets)
}
// collectColumnStats reads back the footer of a Parquet file the compactor
// wrote. Counts and sizes are summed over the row groups and the bounds are
// the minimum and maximum of the row group statistics, encoded with the
// spec's single-value serialization. A column whose bounds cannot be read
// for every row group, or converted exactly, gets no bounds.
func collectColumnStats(data []byte, schema *iceberg.Schema) (*columnStats, error) {
file, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)),
parquet.SkipPageIndex(true), parquet.SkipBloomFilters(true))
if err != nil {
return nil, err
}
var leaves []*parquet.Column
var walk func(*parquet.Column)
walk = func(c *parquet.Column) {
if c.Leaf() {
leaves = append(leaves, c)
return
}
for _, child := range c.Columns() {
walk(child)
}
}
walk(file.Root())
type bounds struct {
field iceberg.NestedField
typ parquet.Type
min, max parquet.Value
seen bool
invalid bool
}
stats := &columnStats{sizes: map[int]int64{}, values: map[int]int64{}, nulls: map[int]int64{},
lower: map[int][]byte{}, upper: map[int][]byte{}}
agg := map[int]*bounds{}
meta := file.Metadata()
for rgIdx, rg := range file.RowGroups() {
stats.splitOffsets = append(stats.splitOffsets, rowGroupOffset(&meta.RowGroups[rgIdx]))
for col, cc := range rg.ColumnChunks() {
field, ok := icebergFieldOf(leaves[col], schema)
if !ok {
continue
}
stats.sizes[field.ID] += meta.RowGroups[rgIdx].Columns[col].MetaData.TotalCompressedSize
stats.values[field.ID] += cc.NumValues()
b := agg[field.ID]
if b == nil {
b = &bounds{field: field, typ: leaves[col].Type()}
agg[field.ID] = b
}
chunk, ok := cc.(*parquet.FileColumnChunk)
if !ok {
b.invalid = true
continue
}
stats.nulls[field.ID] += chunk.NullCount()
if chunk.NullCount() == chunk.NumValues() {
continue // an all-null chunk constrains nothing
}
lo, hi, ok := chunk.Bounds()
switch {
case !ok:
b.invalid = true
case !b.seen:
b.min, b.max, b.seen = lo.Clone(), hi.Clone(), true
default:
if b.typ.Compare(lo, b.min) < 0 {
b.min = lo.Clone()
}
if b.typ.Compare(hi, b.max) > 0 {
b.max = hi.Clone()
}
}
}
}
for id, b := range agg {
if b.invalid || !b.seen {
continue
}
lo, okLo := boundLiteral(b.min, b.typ, b.field.Type)
hi, okHi := boundLiteral(b.max, b.typ, b.field.Type)
if !okLo || !okHi {
continue
}
lo, hi, okHi = truncateBounds(lo, hi)
if raw, err := lo.MarshalBinary(); err == nil {
stats.lower[id] = raw
}
if raw, err := hi.MarshalBinary(); err == nil && okHi {
stats.upper[id] = raw
}
}
sort.Slice(stats.splitOffsets, func(i, j int) bool { return stats.splitOffsets[i] < stats.splitOffsets[j] })
return stats, nil
}
// icebergFieldOf finds the Iceberg field of a Parquet leaf column by the field
// id the writer stored, or by its dotted path in a file written without ids.
// Only primitive fields outside lists and maps carry statistics.
func icebergFieldOf(leaf *parquet.Column, schema *iceberg.Schema) (iceberg.NestedField, bool) {
var field iceberg.NestedField
var ok bool
if leaf.MaxRepetitionLevel() > 0 {
return field, false
}
if id := leaf.ID(); id > 0 {
field, ok = schema.FindFieldByID(id)
} else {
field, ok = schema.FindFieldByName(strings.Join(leaf.Path(), "."))
}
if !ok {
return field, false
}
_, primitive := field.Type.(iceberg.PrimitiveType)
return field, primitive
}
// rowGroupOffset is where a row group's bytes start: the split offset readers
// plan one task per row group from.
func rowGroupOffset(rg *format.RowGroup) int64 {
if rg.FileOffset > 0 || len(rg.Columns) == 0 {
return rg.FileOffset
}
first := rg.Columns[0].MetaData
if first.DictionaryPageOffset > 0 && first.DictionaryPageOffset < first.DataPageOffset {
return first.DictionaryPageOffset
}
return first.DataPageOffset
}
// boundLiteral converts a Parquet statistics value into a literal of the
// column's Iceberg type, when the conversion is exact. Other types (decimal,
// time, uuid, fixed, timestamps not in the type's unit) get no bound.
func boundLiteral(v parquet.Value, pt parquet.Type, t iceberg.Type) (iceberg.Literal, bool) {
if v.IsNull() {
return nil, false
}
switch t.(type) {
case iceberg.BooleanType:
return iceberg.BoolLiteral(v.Boolean()), v.Kind() == parquet.Boolean
case iceberg.Int32Type:
return iceberg.Int32Literal(v.Int32()), v.Kind() == parquet.Int32
case iceberg.Int64Type:
switch v.Kind() {
case parquet.Int64:
return iceberg.Int64Literal(v.Int64()), true
case parquet.Int32:
return iceberg.Int64Literal(int64(v.Int32())), true
}
case iceberg.Float32Type:
f := v.Float()
return iceberg.Float32Literal(f), v.Kind() == parquet.Float && !math.IsNaN(float64(f))
case iceberg.Float64Type:
f := v.Double()
return iceberg.Float64Literal(f), v.Kind() == parquet.Double && !math.IsNaN(f)
case iceberg.DateType:
return iceberg.DateLiteral(iceberg.Date(v.Int32())), v.Kind() == parquet.Int32
case iceberg.TimestampType, iceberg.TimestampTzType:
return iceberg.TimestampLiteral(iceberg.Timestamp(v.Int64())), v.Kind() == parquet.Int64 && timeUnit(pt) == time.Microsecond
case iceberg.TimestampNsType:
return iceberg.TimestampNsLiteral(iceberg.TimestampNano(v.Int64())), v.Kind() == parquet.Int64 && timeUnit(pt) == time.Nanosecond
case iceberg.StringType:
b := v.ByteArray()
return iceberg.StringLiteral(string(b)), v.Kind() == parquet.ByteArray && utf8.Valid(b)
case iceberg.BinaryType:
return iceberg.BinaryLiteral(bytes.Clone(v.ByteArray())), v.Kind() == parquet.ByteArray
}
return nil, false
}
func timeUnit(pt parquet.Type) time.Duration {
if pt == nil || pt.LogicalType() == nil {
return 0
}
if ts, ok := pt.LogicalType().Value.(*format.TimestampType); ok && ts.Unit.Value != nil {
return ts.Unit.Value.Duration()
}
return 0
}
// truncateBounds applies truncate(16) to string and binary bounds. A prefix is
// still a lower bound; a shortened upper bound is not, so a value longer than
// the limit keeps no upper bound (the reference implementation increments the
// last character instead).
func truncateBounds(lo, hi iceberg.Literal) (iceberg.Literal, iceberg.Literal, bool) {
switch l := lo.(type) {
case iceberg.StringLiteral:
if r := []rune(string(l)); len(r) > boundTruncateLength {
lo = iceberg.StringLiteral(string(r[:boundTruncateLength]))
}
return lo, hi, utf8.RuneCountInString(string(hi.(iceberg.StringLiteral))) <= boundTruncateLength
case iceberg.BinaryLiteral:
if len(l) > boundTruncateLength {
lo = l[:boundTruncateLength]
}
return lo, hi, len(hi.(iceberg.BinaryLiteral)) <= boundTruncateLength
}
return lo, hi, true
}
@@ -1,148 +0,0 @@
package iceberg
import (
"bytes"
"context"
"testing"
"github.com/apache/iceberg-go"
"github.com/parquet-go/parquet-go"
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// compactedDataFile returns the data file the current snapshot's data
// manifest references after a compaction run.
func compactedDataFile(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup) iceberg.DataFile {
t.Helper()
found := liveDataFiles(t, client, setup)
if len(found) != 1 {
t.Fatalf("expected 1 live data file after compaction, got %d", len(found))
}
return found[0]
}
func liveDataFiles(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup) []iceberg.DataFile {
t.Helper()
state, err := loadCurrentMetadata(context.Background(), client, setup.BucketName, setup.tablePath())
if err != nil {
t.Fatalf("loadCurrentMetadata: %v", err)
}
manifests, err := loadCurrentManifests(context.Background(), client, setup.BucketName, state.DataPath, state.Metadata)
if err != nil {
t.Fatalf("loadCurrentManifests: %v", err)
}
var found []iceberg.DataFile
for _, mf := range manifests {
if mf.ManifestContent() != iceberg.ManifestContentData {
continue
}
manifestData, err := loadFileByIcebergPath(context.Background(), client, setup.BucketName, state.DataPath, mf.FilePath())
if err != nil {
t.Fatalf("load manifest: %v", err)
}
entries, err := iceberg.ReadManifest(mf, bytes.NewReader(manifestData), true)
if err != nil {
t.Fatalf("read manifest: %v", err)
}
for _, entry := range entries {
if entry.Status() != iceberg.EntryStatusDELETED {
found = append(found, entry.DataFile())
}
}
}
return found
}
func compactedFileBytes(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup, filePath string) []byte {
t.Helper()
state, err := loadCurrentMetadata(context.Background(), client, setup.BucketName, setup.tablePath())
if err != nil {
t.Fatalf("loadCurrentMetadata: %v", err)
}
data, err := loadFileByIcebergPath(context.Background(), client, setup.BucketName, state.DataPath, filePath)
if err != nil {
t.Fatalf("load compacted file: %v", err)
}
return data
}
func compactedIDs(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup, filePath string) []int64 {
t.Helper()
data := compactedFileBytes(t, client, setup, filePath)
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("open compacted file: %v", err)
}
var ids []int64
for _, rg := range f.RowGroups() {
rows := rg.Rows()
buf := make([]parquet.Row, 8)
for {
n, err := rows.ReadRows(buf)
for _, row := range buf[:n] {
ids = append(ids, row[0].Int64())
}
if err != nil {
break
}
}
rows.Close()
}
return ids
}
// A compacted file's manifest entry carries the column metrics readers
// prune files by: counts, sizes, bounds and split offsets read back
// from the file's own footer.
func TestCompactDataFilesRecordsColumnStatistics(t *testing.T) {
fs, client := startFakeFiler(t)
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "tbl"}
populateTableWithDeleteFiles(t, fs, setup,
[]struct {
Name string
Rows []struct {
ID int64
Name string
}
}{
{"d1.parquet", []struct {
ID int64
Name string
}{{1, "a"}, {2, "b"}}},
{"d2.parquet", []struct {
ID int64
Name string
}{{3, "c"}}},
},
nil, nil,
)
handler := NewHandler(nil)
config := Config{TargetFileSizeBytes: 256 * 1024 * 1024, MinInputFiles: 2, MaxCommitRetries: 3}
if _, _, err := handler.compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil); err != nil {
t.Fatalf("compactDataFiles: %v", err)
}
df := compactedDataFile(t, client, setup)
if df.ValueCounts()[1] != 3 {
t.Errorf("value_counts[1] = %d, want 3", df.ValueCounts()[1])
}
if len(df.LowerBoundValues()) == 0 || len(df.UpperBoundValues()) == 0 {
t.Fatal("compacted file has no bounds")
}
lo, err := iceberg.LiteralFromBytes(iceberg.PrimitiveTypes.Int64, df.LowerBoundValues()[1])
if err != nil {
t.Fatalf("decode lower bound: %v", err)
}
hi, err := iceberg.LiteralFromBytes(iceberg.PrimitiveTypes.Int64, df.UpperBoundValues()[1])
if err != nil {
t.Fatalf("decode upper bound: %v", err)
}
if lo.(iceberg.Int64Literal) != 1 || hi.(iceberg.Int64Literal) != 3 {
t.Errorf("id bounds = %v..%v, want 1..3", lo, hi)
}
if len(df.SplitOffsets()) == 0 {
t.Error("compacted file has no split_offsets")
}
}
-4
View File
@@ -130,10 +130,6 @@ type Config struct {
SortMaxInputBytes int64
SortBufferRows int64
SortSpillDir string
// Row groups of a compacted file, from the table's write.parquet.*
// properties; zero means the default.
RowGroupSizeBytes int64
RowGroupRowLimit int64
}
// ParseConfig extracts an iceberg maintenance Config from plugin config values.
+2 -7
View File
@@ -32,14 +32,9 @@ type deleteRewriteGroup struct {
TotalSize int64
}
// positionDeleteRow is the Iceberg position-delete schema: the spec reserves
// field ids 2147483546 (file_path) and 2147483545 (pos). file_path is
// dictionary-encoded: PyArrow cannot decode parquet-go's default
// DELTA_LENGTH_BYTE_ARRAY into the dictionary PyIceberg asks for, and the
// column repeats one data file's path anyway.
type positionDeleteRow struct {
FilePath string `parquet:"file_path,dict,id(2147483546)"`
Pos int64 `parquet:"pos,id(2147483545)"`
FilePath string `parquet:"file_path"`
Pos int64 `parquet:"pos"`
}
func hasEligibleDeleteRewrite(
@@ -1,54 +0,0 @@
package iceberg
import (
"bytes"
"testing"
"github.com/parquet-go/parquet-go"
"github.com/parquet-go/parquet-go/format"
)
// The position-delete file must carry the spec's field ids and a
// dictionary-encoded file_path: PyIceberg reads delete files with
// file_path as a dictionary column, which PyArrow cannot decode from
// DELTA_LENGTH_BYTE_ARRAY, and by-id readers resolve columns by field id.
func TestPositionDeleteFileHasFieldIDsAndDictionaryPaths(t *testing.T) {
rows := []positionDeleteRow{
{FilePath: "s3://tb/ns/tbl/data/a.parquet", Pos: 0},
{FilePath: "s3://tb/ns/tbl/data/a.parquet", Pos: 7},
{FilePath: "s3://tb/ns/tbl/data/b.parquet", Pos: 3},
}
data, err := writePositionDeleteFile(rows)
if err != nil {
t.Fatal(err)
}
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
want := map[string]int{"file_path": 2147483546, "pos": 2147483545}
for _, field := range f.Schema().Fields() {
if id, ok := want[field.Name()]; !ok || field.ID() != id {
t.Errorf("field %s id = %d, want %d", field.Name(), field.ID(), id)
}
}
for _, rg := range f.Metadata().RowGroups {
for _, col := range rg.Columns {
if col.MetaData.PathInSchema[0] != "file_path" {
continue
}
dict := false
for _, enc := range col.MetaData.Encoding {
if enc == format.DeltaLengthByteArray {
t.Errorf("file_path is DELTA_LENGTH_BYTE_ARRAY: %v", col.MetaData.Encoding)
}
if enc == format.RLEDictionary || enc == format.PlainDictionary {
dict = true
}
}
if !dict {
t.Errorf("file_path is not dictionary-encoded: %v", col.MetaData.Encoding)
}
}
}
}
+1 -1
View File
@@ -477,7 +477,7 @@ func hasEligibleCompaction(
}
targetSize := compactionTargetSizeForPlan(config, rewritePlan)
bins := buildCompactionBins(candidateEntries, targetSize, minInputFiles, meta)
bins := buildCompactionBins(candidateEntries, targetSize, minInputFiles)
bins = filterCompactionBinsByPlan(bins, config, rewritePlan)
return len(bins) > 0, nil
}
+10 -10
View File
@@ -701,7 +701,7 @@ func TestBuildCompactionBins(t *testing.T) {
{path: "data/f3.parquet", size: 4096, partition: map[int]any{}},
})
bins := buildCompactionBins(entries, targetSize, minFiles, nil)
bins := buildCompactionBins(entries, targetSize, minFiles)
if len(bins) != 1 {
t.Fatalf("expected 1 bin, got %d", len(bins))
}
@@ -720,7 +720,7 @@ func TestBuildCompactionBinsFiltersLargeFiles(t *testing.T) {
{path: "data/large.parquet", size: 5000, partition: map[int]any{}},
})
bins := buildCompactionBins(entries, targetSize, minFiles, nil)
bins := buildCompactionBins(entries, targetSize, minFiles)
if len(bins) != 1 {
t.Fatalf("expected 1 bin, got %d", len(bins))
}
@@ -756,7 +756,7 @@ func TestBuildCompactionBinsLowercaseParquetFormat(t *testing.T) {
entries[0] = lowercaseFormatEntry{entries[0]}
entries[1] = lowercaseFormatEntry{entries[1]}
bins := buildCompactionBins(entries, targetSize, minFiles, nil)
bins := buildCompactionBins(entries, targetSize, minFiles)
if len(bins) != 1 {
t.Fatalf("expected 1 bin, got %d", len(bins))
}
@@ -774,7 +774,7 @@ func TestBuildCompactionBinsMinFilesThreshold(t *testing.T) {
{path: "data/f2.parquet", size: 2048, partition: map[int]any{}},
})
bins := buildCompactionBins(entries, targetSize, minFiles, nil)
bins := buildCompactionBins(entries, targetSize, minFiles)
if len(bins) != 0 {
t.Errorf("expected 0 bins (below min threshold), got %d", len(bins))
}
@@ -801,7 +801,7 @@ func TestBuildCompactionBinsMultiplePartitions(t *testing.T) {
{path: "data/b3.parquet", size: 4096, partition: partB, partitionSpec: &partitionSpec},
})
bins := buildCompactionBins(entries, targetSize, minFiles, nil)
bins := buildCompactionBins(entries, targetSize, minFiles)
if len(bins) != 2 {
t.Fatalf("expected 2 bins (one per partition), got %d", len(bins))
}
@@ -977,7 +977,7 @@ func TestBuildCompactionBinsMultipleSpecs(t *testing.T) {
{path: "data/s1-f2.parquet", size: 2048, partition: map[int]any{}, specID: 1},
}, partSpecs)
bins := buildCompactionBins(entries, targetSize, minFiles, nil)
bins := buildCompactionBins(entries, targetSize, minFiles)
if len(bins) != 2 {
t.Fatalf("expected 2 bins (one per spec), got %d", len(bins))
}
@@ -1011,7 +1011,7 @@ func TestBuildCompactionBinsSingleSpec(t *testing.T) {
{path: "data/f3.parquet", size: 4096, partition: map[int]any{}, specID: 0},
}, partSpecs)
bins := buildCompactionBins(entries, targetSize, minFiles, nil)
bins := buildCompactionBins(entries, targetSize, minFiles)
if len(bins) != 1 {
t.Fatalf("expected 1 bin, got %d", len(bins))
}
@@ -1303,7 +1303,7 @@ func TestMergeParquetFilesWithPositionDeletes(t *testing.T) {
merged, count, err := mergeParquetFiles(
context.Background(), client, "test-bucket", "ns/tbl",
entries, posDeletes, nil, nil, 0,
entries, posDeletes, nil, nil,
)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
@@ -1419,7 +1419,7 @@ func TestMergeParquetFilesWithEqualityDeletes(t *testing.T) {
merged, count, err := mergeParquetFiles(
context.Background(), client, "test-bucket", "ns/tbl",
entries, nil, eqGroups, schema, 0,
entries, nil, eqGroups, schema,
)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
@@ -1479,7 +1479,7 @@ func TestMergeParquetFilesDictionaryEncodedInput(t *testing.T) {
merged, count, err := mergeParquetFiles(
context.Background(), client, "test-bucket", "ns/tbl",
entries, nil, nil, nil, 0,
entries, nil, nil, nil,
)
if err != nil {
t.Fatalf("mergeParquetFiles: %v", err)
-6
View File
@@ -345,12 +345,6 @@ func collectOrphanCandidates(
for mle := range meta.PreviousFiles() {
referencedFiles[mle.MetadataFile] = struct{}{}
}
for sf := range meta.Statistics() {
referencedFiles[sf.StatisticsPath] = struct{}{}
}
for psf := range meta.PartitionStatistics() {
referencedFiles[psf.StatisticsPath] = struct{}{}
}
referencedFilerPaths := make(map[string]struct{}, len(referencedFiles))
for ref := range referencedFiles {
@@ -1,78 +0,0 @@
package iceberg
import (
"context"
"encoding/json"
"path"
"testing"
"time"
"github.com/apache/iceberg-go/table"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
)
// Statistics files (Puffin, partition statistics) live under metadata/ and are
// referenced from the table metadata's "statistics" and "partition-statistics"
// lists, not from any snapshot's manifests. Orphan cleanup must count them as
// referenced, or it deletes a table's statistics once they pass the window.
func TestOrphanCleanupKeepsStatisticsFiles(t *testing.T) {
const bucket, namespace, tbl = "stats-bucket", "ns", "tbl"
tableRef := func(name string) string {
return "s3://" + bucket + "/" + namespace + "/" + tbl + "/metadata/" + name
}
base := buildTestMetadata(t, nil, nil, 0, nil, nil, nil)
raw, err := json.Marshal(base)
if err != nil {
t.Fatalf("marshal metadata: %v", err)
}
var doc map[string]any
if err := json.Unmarshal(raw, &doc); err != nil {
t.Fatalf("unmarshal metadata: %v", err)
}
doc["statistics"] = []any{map[string]any{
"snapshot-id": 1, "statistics-path": tableRef("stats-1.puffin"),
"file-size-in-bytes": 10, "file-footer-size-in-bytes": 5, "blob-metadata": []any{},
}}
doc["partition-statistics"] = []any{map[string]any{
"snapshot-id": 1, "statistics-path": tableRef("partition-stats-1.parquet"),
"file-size-in-bytes": 10,
}}
raw, err = json.Marshal(doc)
if err != nil {
t.Fatalf("marshal metadata with statistics: %v", err)
}
meta, err := table.ParseMetadataBytes(raw)
if err != nil {
t.Fatalf("parse metadata with statistics: %v", err)
}
filer := s3tablestest.Start(t)
tablePath := s3tables.GetTablePath(bucket, namespace, tbl)
metaDir := path.Join(tablePath, "metadata")
old := time.Now().Add(-30 * 24 * time.Hour)
filer.Put(tablePath, "metadata", nil)
filer.PutFile(metaDir, "v1.metadata.json", old)
filer.PutFile(metaDir, "stats-1.puffin", old)
filer.PutFile(metaDir, "partition-stats-1.parquet", old)
filer.PutFile(metaDir, "stats-0.puffin", old) // superseded: a real orphan
candidates, err := collectOrphanCandidates(context.Background(), filer.Client, bucket, path.Join(namespace, tbl),
meta, "v1.metadata.json", 1)
if err != nil {
t.Fatalf("collect orphan candidates: %v", err)
}
doomed := map[string]bool{}
for _, c := range candidates {
doomed[c.Entry.Name] = true
}
if !doomed["stats-0.puffin"] {
t.Fatalf("expected the unreferenced stats-0.puffin to be an orphan, got %v", doomed)
}
for _, name := range []string{"stats-1.puffin", "partition-stats-1.parquet", "v1.metadata.json"} {
if doomed[name] {
t.Errorf("%s is referenced by the table metadata and must not be an orphan", name)
}
}
}
@@ -19,8 +19,6 @@ import (
const (
propTargetFileSize = "write.target-file-size-bytes"
propDeleteTargetFileSize = "write.delete.target-file-size-bytes"
propRowGroupSize = "write.parquet.row-group-size-bytes"
propRowGroupRowLimit = "write.parquet.row-group-limit"
propMaxSnapshotAgeMs = "history.expire.max-snapshot-age-ms"
propMinSnapshotsToKeep = "history.expire.min-snapshots-to-keep"
)
@@ -52,12 +50,6 @@ func applyTableProperties(cfg Config, props iceberg.Properties) Config {
if v, ok := propInt64(props, propDeleteTargetFileSize); ok {
cfg.DeleteTargetFileSizeBytes = v
}
if v, ok := propInt64(props, propRowGroupSize); ok {
cfg.RowGroupSizeBytes = v
}
if v, ok := propInt64(props, propRowGroupRowLimit); ok {
cfg.RowGroupRowLimit = v
}
if v, ok := propInt64(props, propMaxSnapshotAgeMs); ok {
cfg.SnapshotRetentionMs = v
}