mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1fe294fd44 | ||
|
|
57246c345b | ||
|
|
77694d3a93 | ||
|
|
9b1ff91949 | ||
|
|
b0d1786c28 | ||
|
|
01406e661a | ||
|
|
292abfae33 | ||
|
|
0ead130bfc | ||
|
|
c46526822b | ||
|
|
cc4043c9d2 | ||
|
|
ece4f42ecd | ||
|
|
155140bed8 | ||
|
|
cf64cafc3b | ||
|
|
f6032cf23d | ||
|
|
746ed82662 | ||
|
|
9d75048594 | ||
|
|
ebeab4b6ec | ||
|
|
e6441d84e0 | ||
|
|
05b4b5bf56 | ||
|
|
b872d5e683 | ||
|
|
430d4b5394 | ||
|
|
36e51e5542 | ||
|
|
bdcc3154ed | ||
|
|
ce3ba31bcd | ||
|
|
b4a99b996d | ||
|
|
9550b830d0 | ||
|
|
d02ee6d5df | ||
|
|
bea1357d38 | ||
|
|
77bf2a3ab0 | ||
|
|
41d6c821ba | ||
|
|
a9c0ed91b5 | ||
|
|
a653a7f72a | ||
|
|
424cd164e9 | ||
|
|
803c5a8dca | ||
|
|
8f2a2abae4 | ||
|
|
a85318111c | ||
|
|
bb5e6e40df |
No files matched your search
@@ -93,11 +93,11 @@ require (
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.46.0
|
||||
golang.org/x/crypto v0.52.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.41.0
|
||||
golang.org/x/image v0.43.0
|
||||
golang.org/x/net v0.55.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sys v0.46.0
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/text v0.38.0 // indirect
|
||||
golang.org/x/tools v0.45.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
google.golang.org/api v0.278.0
|
||||
@@ -513,10 +513,12 @@ require (
|
||||
|
||||
// replace github.com/seaweedfs/raft => /Users/chrislu/go/src/github.com/seaweedfs/raft
|
||||
|
||||
// apache/thrift v0.23.0 uses math.MaxUint32 as an untyped int constant in
|
||||
// lib/go/thrift/framed_transport.go, which overflows int on 32-bit GOARCHes
|
||||
// (e.g. openbsd/arm, linux/arm). Pin to v0.22.0 until upstream fixes it.
|
||||
replace github.com/apache/thrift => github.com/apache/thrift v0.22.0
|
||||
// apache/thrift v0.23.0 fixes CVE-2026-41602 but compares int against the
|
||||
// untyped math.MaxUint32 in lib/go/thrift/framed_transport.go, which overflows
|
||||
// int on 32-bit GOARCHes (e.g. openbsd/arm, linux/arm) and fails to compile.
|
||||
// Upstream fixed the range check post-release; pin to that commit until the
|
||||
// next tagged release carries both the CVE fix and the 32-bit fix.
|
||||
replace github.com/apache/thrift => github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58
|
||||
|
||||
// tyler-smith/go-bip39 was deleted from GitHub, so `go mod download` fails for
|
||||
// anyone resolving it directly (GOPROXY=direct). It only reaches us transitively
|
||||
|
||||
@@ -694,8 +694,8 @@ github.com/apache/cassandra-gocql-driver/v2 v2.1.2 h1:lu/p0Db2av18enHJvWJQoChLss
|
||||
github.com/apache/cassandra-gocql-driver/v2 v2.1.2/go.mod h1:QH/asJjB3mHvY6Dot6ZKMMpTcOrWJ8i9GhsvG1g0PK4=
|
||||
github.com/apache/iceberg-go v0.6.0 h1:tOVhC5BhBOEgPTowo5AVrPnAgsDo00qEbUPprFcLd4s=
|
||||
github.com/apache/iceberg-go v0.6.0/go.mod h1:kESfDlyaW/6hK0WW6TzA4EWps+0NMhhrDYE4qajVjlo=
|
||||
github.com/apache/thrift v0.22.0 h1:r7mTJdj51TMDe6RtcmNdQxgn9XcyfGDOzegMDRg47uc=
|
||||
github.com/apache/thrift v0.22.0/go.mod h1:1e7J/O1Ae6ZQMTYdy9xa3w9k+XHWPfRvdPyJeynQ+/g=
|
||||
github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58 h1:rDLE+tSW60VzRD7v5I+DU22Mjhmm+mfLc5Xl5dHkx6w=
|
||||
github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58/go.mod h1:zPt6WxgvTOM6hF92y8C+MkEM5LMxZuk4JcQOiU4Esvs=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3 h1:WZaTKNHCfcw7fWSR6/RKnCldVzvYZC+Y20Su4lffEIg=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3/go.mod h1:OMVSB21p9+xQUIqlGizHPZfjK+SHws1ht+ZytVDoz9U=
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er+LKDHDUfU5tRvFwxH0LjPpZN8OoG8Ll+liGU=
|
||||
@@ -2211,8 +2211,8 @@ golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeap
|
||||
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
|
||||
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
|
||||
golang.org/x/image v0.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
|
||||
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
@@ -2514,8 +2514,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
|
||||
@@ -29,6 +29,11 @@ spec:
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.certificates.ipAddresses }}
|
||||
ipAddresses:
|
||||
{{- range .Values.certificates.ipAddresses }}
|
||||
|
||||
@@ -23,6 +23,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -28,6 +28,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -28,6 +28,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -28,6 +28,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -29,6 +29,11 @@ spec:
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.certificates.ipAddresses }}
|
||||
ipAddresses:
|
||||
{{- range .Values.certificates.ipAddresses }}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{{- /* Filer ingress works for both normal mode (filer.enabled) and all-in-one mode (allInOne.enabled) */}}
|
||||
{{- /* Filer ingresses work for both normal mode (filer.enabled) and all-in-one mode (allInOne.enabled) */}}
|
||||
{{- $filerEnabled := or .Values.filer.enabled .Values.allInOne.enabled }}
|
||||
{{- if and $filerEnabled .Values.filer.ingress.enabled }}
|
||||
|
||||
{{- /* HTTP Ingress */}}
|
||||
{{- if and $filerEnabled .Values.filer.ingresses.http.enabled }}
|
||||
{{- /* Determine service name based on deployment mode */}}
|
||||
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
@@ -12,10 +14,13 @@ apiVersion: extensions/v1beta1
|
||||
{{- end }}
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: ingress-{{ include "seaweedfs.fullname" . }}-filer
|
||||
name: ingress-{{ include "seaweedfs.fullname" . }}-filer-http
|
||||
namespace: {{ .Release.Namespace }}
|
||||
{{- with .Values.filer.ingress.annotations }}
|
||||
annotations:
|
||||
{{- if and (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) .Values.filer.ingresses.http.className }}
|
||||
kubernetes.io/ingress.class: {{ .Values.filer.ingresses.http.className }}
|
||||
{{- end }}
|
||||
{{- with .Values.filer.ingresses.http.annotations }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
labels:
|
||||
@@ -25,14 +30,21 @@ metadata:
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/component: filer
|
||||
spec:
|
||||
ingressClassName: {{ .Values.filer.ingress.className | quote }}
|
||||
{{- if and (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) .Values.filer.ingresses.http.className }}
|
||||
ingressClassName: {{ .Values.filer.ingresses.http.className | quote }}
|
||||
{{- end }}
|
||||
tls:
|
||||
{{ .Values.filer.ingress.tls | default list | toYaml | nindent 6}}
|
||||
{{ .Values.filer.ingresses.http.tls | default list | toYaml | nindent 6}}
|
||||
rules:
|
||||
- http:
|
||||
- {{- if .Values.filer.ingresses.http.host }}
|
||||
host: {{ .Values.filer.ingresses.http.host | quote }}
|
||||
{{- end }}
|
||||
http:
|
||||
paths:
|
||||
- path: {{ .Values.filer.ingress.path | quote }}
|
||||
pathType: {{ .Values.filer.ingress.pathType | quote }}
|
||||
- path: {{ .Values.filer.ingresses.http.path | quote }}
|
||||
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
pathType: {{ .Values.filer.ingresses.http.pathType | quote }}
|
||||
{{- end }}
|
||||
backend:
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
service:
|
||||
@@ -43,7 +55,62 @@ spec:
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ .Values.filer.port }}
|
||||
{{- end }}
|
||||
{{- if .Values.filer.ingress.host }}
|
||||
host: {{ .Values.filer.ingress.host }}
|
||||
{{- end }}
|
||||
|
||||
---
|
||||
|
||||
{{- /* gRPC Ingress */}}
|
||||
{{- if and $filerEnabled .Values.filer.ingresses.grpc.enabled }}
|
||||
{{- /* Determine service name based on deployment mode */}}
|
||||
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
apiVersion: networking.k8s.io/v1beta1
|
||||
{{- else }}
|
||||
apiVersion: extensions/v1beta1
|
||||
{{- end }}
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: ingress-{{ include "seaweedfs.fullname" . }}-filer-grpc
|
||||
namespace: {{ .Release.Namespace }}
|
||||
annotations:
|
||||
{{- if and (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) .Values.filer.ingresses.grpc.className }}
|
||||
kubernetes.io/ingress.class: {{ .Values.filer.ingresses.grpc.className }}
|
||||
{{- end }}
|
||||
{{- with .Values.filer.ingresses.grpc.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
|
||||
spec:
|
||||
{{- if and (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) .Values.filer.ingresses.grpc.className }}
|
||||
ingressClassName: {{ .Values.filer.ingresses.grpc.className | quote }}
|
||||
{{- end }}
|
||||
tls:
|
||||
{{ .Values.filer.ingresses.grpc.tls | default list | toYaml | nindent 6}}
|
||||
rules:
|
||||
- {{- if .Values.filer.ingresses.grpc.host }}
|
||||
host: {{ .Values.filer.ingresses.grpc.host | quote }}
|
||||
{{- end }}
|
||||
http:
|
||||
paths:
|
||||
- path: {{ .Values.filer.ingresses.grpc.path | quote }}
|
||||
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
pathType: {{ .Values.filer.ingresses.grpc.pathType | quote }}
|
||||
{{- end }}
|
||||
backend:
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
service:
|
||||
name: {{ $serviceName }}
|
||||
port:
|
||||
number: {{ .Values.filer.grpcPort }}
|
||||
{{- else }}
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ .Values.filer.grpcPort }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -824,30 +824,50 @@ filer:
|
||||
# allowPrivilegeEscalation: false
|
||||
containerSecurityContext: {}
|
||||
|
||||
ingress:
|
||||
enabled: false
|
||||
className: ""
|
||||
# host: false for "*" hostname
|
||||
host: "seaweedfs.cluster.local"
|
||||
path: "/sw-filer/?(.*)"
|
||||
pathType: ImplementationSpecific
|
||||
annotations: {}
|
||||
# nginx.ingress.kubernetes.io/backend-protocol: GRPC
|
||||
# nginx.ingress.kubernetes.io/auth-type: "basic"
|
||||
# nginx.ingress.kubernetes.io/auth-secret: "default/ingress-basic-auth-secret"
|
||||
# nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - SW-Filer'
|
||||
# nginx.ingress.kubernetes.io/service-upstream: "true"
|
||||
# nginx.ingress.kubernetes.io/rewrite-target: /$1
|
||||
# nginx.ingress.kubernetes.io/use-regex: "true"
|
||||
# nginx.ingress.kubernetes.io/enable-rewrite-log: "true"
|
||||
# nginx.ingress.kubernetes.io/ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/configuration-snippet: |
|
||||
# sub_filter '<head>' '<head> <base href="/sw-filer/">'; #add base url
|
||||
# sub_filter '="/' '="./'; #make absolute paths to relative
|
||||
# sub_filter '=/' '=./';
|
||||
# sub_filter '/seaweedfsstatic' './seaweedfsstatic';
|
||||
# sub_filter_once off;
|
||||
ingresses:
|
||||
http:
|
||||
enabled: false
|
||||
className: ""
|
||||
# host: false for "*" hostname
|
||||
host: "seaweedfs.cluster.local"
|
||||
path: "/sw-filer/?(.*)"
|
||||
pathType: ImplementationSpecific
|
||||
annotations: {}
|
||||
# nginx.ingress.kubernetes.io/backend-protocol: GRPC
|
||||
# nginx.ingress.kubernetes.io/auth-type: "basic"
|
||||
# nginx.ingress.kubernetes.io/auth-secret: "default/ingress-basic-auth-secret"
|
||||
# nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - SW-Filer'
|
||||
# nginx.ingress.kubernetes.io/service-upstream: "true"
|
||||
# nginx.ingress.kubernetes.io/rewrite-target: /$1
|
||||
# nginx.ingress.kubernetes.io/use-regex: "true"
|
||||
# nginx.ingress.kubernetes.io/enable-rewrite-log: "true"
|
||||
# nginx.ingress.kubernetes.io/ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/configuration-snippet: |
|
||||
# sub_filter '<head>' '<head> <base href="/sw-filer/">'; #add base url
|
||||
# sub_filter '="/' '="./'; #make absolute paths to relative
|
||||
# sub_filter '=/' '=./';
|
||||
# sub_filter '/seaweedfsstatic' './seaweedfsstatic';
|
||||
# sub_filter_once off;
|
||||
tls: []
|
||||
grpc:
|
||||
enabled: false
|
||||
className: ""
|
||||
host: "seaweedfs.cluster.local"
|
||||
# gRPC methods are called at /<package>.<Service>/<Method>, so route the
|
||||
# whole host, not the HTTP UI's regex path.
|
||||
path: "/"
|
||||
pathType: Prefix
|
||||
annotations:
|
||||
# Ingress terminates TLS and re-originates gRPC (HTTP/2) to the filer.
|
||||
nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
|
||||
# For end-to-end mTLS (the filer's own TLS reaches the client, not
|
||||
# terminated at the edge), drop backend-protocol above and use TLS
|
||||
# passthrough instead:
|
||||
# nginx.ingress.kubernetes.io/ssl-passthrough: "true"
|
||||
# Passthrough routes by SNI (set `host` above), ignores `path`, and
|
||||
# requires ingress-nginx to run with --enable-ssl-passthrough.
|
||||
tls: []
|
||||
|
||||
# extraEnvVars is a list of extra environment variables to set with the stateful set.
|
||||
extraEnvironmentVars:
|
||||
@@ -1745,6 +1765,7 @@ cosi:
|
||||
|
||||
certificates:
|
||||
commonName: "SeaweedFS CA"
|
||||
dnsNames: []
|
||||
ipAddresses: []
|
||||
keyAlgorithm: RSA
|
||||
keySize: 2048
|
||||
|
||||
@@ -64,6 +64,9 @@ service Seaweed {
|
||||
message DiskTag {
|
||||
uint32 disk_id = 1;
|
||||
repeated string tags = 2;
|
||||
// Physical disk descriptor, reported for every location including empty ones.
|
||||
string type = 3;
|
||||
int64 max_volume_count = 4;
|
||||
}
|
||||
|
||||
message Heartbeat {
|
||||
@@ -96,6 +99,10 @@ message Heartbeat {
|
||||
volume_server_pb.VolumeServerState state = 23;
|
||||
|
||||
repeated DiskTag disk_tags = 24;
|
||||
|
||||
// physical disk capacity per disk type, in bytes, from the underlying filesystem
|
||||
map<string, uint64> disk_total_bytes = 25;
|
||||
map<string, uint64> disk_free_bytes = 26;
|
||||
}
|
||||
|
||||
message HeartbeatResponse {
|
||||
@@ -206,6 +213,17 @@ message ClusterNodeUpdate {
|
||||
message KeepConnectedResponse {
|
||||
VolumeLocation volume_location = 1;
|
||||
ClusterNodeUpdate cluster_node_update = 2;
|
||||
LockRingUpdate lock_ring_update = 3;
|
||||
}
|
||||
|
||||
// LockRingUpdate is sent by the master to all filers when the lock ring
|
||||
// membership changes. The master batches rapid changes (e.g., node drop + join)
|
||||
// and sends the complete member list atomically, avoiding intermediate ring
|
||||
// states that would cause unnecessary lock churn.
|
||||
message LockRingUpdate {
|
||||
string filer_group = 1;
|
||||
repeated string servers = 2;
|
||||
int64 version = 3;
|
||||
}
|
||||
|
||||
message LookupVolumeRequest {
|
||||
@@ -308,8 +326,18 @@ message DiskInfo {
|
||||
repeated VolumeInformationMessage volume_infos = 6;
|
||||
repeated VolumeEcShardInformationMessage ec_shard_infos = 7;
|
||||
int64 remote_volume_count = 8;
|
||||
// On a per-physical-disk DiskInfo (from SplitByPhysicalDisk) this is the disk's
|
||||
// identity; on the type-keyed aggregate it is only a representative fallback
|
||||
// (the first volume's disk id).
|
||||
uint32 disk_id = 9;
|
||||
repeated string tags = 10;
|
||||
// Max volume count for every physical disk of this type, keyed by disk id,
|
||||
// including disks with no volumes or EC shards; recovers empty disks that
|
||||
// carry no per-volume/per-shard records.
|
||||
map<uint32, int64> max_volume_count_by_disk = 11;
|
||||
// physical disk capacity in bytes, from the underlying filesystem (0 if unknown)
|
||||
uint64 disk_total_bytes = 12;
|
||||
uint64 disk_free_bytes = 13;
|
||||
}
|
||||
message DataNodeInfo {
|
||||
string id = 1;
|
||||
@@ -360,11 +388,13 @@ message VacuumVolumeResponse {
|
||||
}
|
||||
|
||||
message DisableVacuumRequest {
|
||||
bool by_plugin = 1;
|
||||
}
|
||||
message DisableVacuumResponse {
|
||||
}
|
||||
|
||||
message EnableVacuumRequest {
|
||||
bool by_plugin = 1;
|
||||
}
|
||||
message EnableVacuumResponse {
|
||||
}
|
||||
|
||||
@@ -442,6 +442,7 @@ message VolumeEcShardsCopyRequest {
|
||||
bool copy_ecj_file = 6;
|
||||
bool copy_vif_file = 7;
|
||||
uint32 disk_id = 8; // Target disk ID for storing EC shards
|
||||
bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
|
||||
}
|
||||
message VolumeEcShardsCopyResponse {
|
||||
}
|
||||
@@ -587,6 +588,29 @@ message EcShardConfig {
|
||||
uint32 parity_shards = 2; // Number of parity shards (e.g., 4)
|
||||
int64 encode_ts_ns = 3; // encode time (unix nanos); a read served from a shard of a different encode run is rejected
|
||||
}
|
||||
// EcBitrotProtection is the entire content of a bitrot checksum sidecar
|
||||
// (<base>.ecsum for the legacy generation, <base>.ecsum.v<N> for vacuum
|
||||
// generation N): per-shard, per-block CRC32C so a CHECKSUM scrub can detect
|
||||
// silent bit rot in any shard (including parity) without decoding. Field
|
||||
// numbers and types match weed/pb/volume_server.proto byte-for-byte so the
|
||||
// serialized sidecar payload is wire-identical across the Go and Rust binaries.
|
||||
message EcBitrotProtection {
|
||||
ChecksumAlgorithm algorithm = 1; // CRC32C (Castagnoli)
|
||||
uint32 block_size = 2; // bytes per checksum block; default 16777216 (16 MiB), a power-of-two multiple of 1 MiB
|
||||
uint32 generation = 3; // EC vacuum generation these checksums describe (0 = legacy/fresh); must match the sidecar filename version
|
||||
EcShardConfig ec_shard_config = 4; // data/parity shard counts at encode time
|
||||
repeated EcShardChecksums shards = 5; // one entry per shard id in the active layout
|
||||
bytes encode_uuid = 6; // random per-encode identity, for stale-sidecar detection across in-place re-encodes
|
||||
}
|
||||
message EcShardChecksums {
|
||||
uint32 shard_id = 1; // 0..MaxShardCount-1 (custom EC ratios go up to 32)
|
||||
int64 covered_size = 2; // shard byte length these checksums cover (must equal the on-disk shard length)
|
||||
bytes block_crc32c = 3; // packed little-endian uint32[] = ceil(covered_size/block_size) entries
|
||||
}
|
||||
enum ChecksumAlgorithm {
|
||||
CHECKSUM_NONE = 0;
|
||||
CHECKSUM_CRC32C = 1;
|
||||
}
|
||||
message OldVersionVolumeInfo {
|
||||
repeated RemoteFile files = 1;
|
||||
uint32 version = 2;
|
||||
@@ -664,6 +688,7 @@ enum VolumeScrubMode {
|
||||
INDEX = 1;
|
||||
FULL = 2;
|
||||
LOCAL = 3;
|
||||
CHECKSUM = 4; // EC only: verify each local shard's raw bytes against the bitrot checksum sidecar
|
||||
}
|
||||
|
||||
message ScrubVolumeRequest {
|
||||
@@ -683,6 +708,7 @@ message ScrubEcVolumeRequest {
|
||||
VolumeScrubMode mode = 1;
|
||||
// optional list of volume IDs to scrub. if empty, all EC volumes for the server are scrubbed.
|
||||
repeated uint32 volume_ids = 2;
|
||||
bool force_deleted_needles_check = 3; // FULL mode only; may report false positives when EC indexes disagree
|
||||
}
|
||||
message ScrubEcVolumeResponse {
|
||||
uint64 total_volumes = 1;
|
||||
|
||||
@@ -37,6 +37,7 @@ fn scrub_mode_label(mode: i32) -> &'static str {
|
||||
1 => "INDEX",
|
||||
2 => "FULL",
|
||||
3 => "LOCAL",
|
||||
4 => "CHECKSUM",
|
||||
_ => "UNKNOWN",
|
||||
}
|
||||
}
|
||||
@@ -1515,9 +1516,16 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.find_volume(vid)
|
||||
.ok_or_else(|| Status::not_found(format!("not found volume id {}", vid)))?;
|
||||
|
||||
// Check compaction revision
|
||||
// Check compaction revision. Compare against the volume's live
|
||||
// super_block.compaction_revision (matching Go's v.CompactionRevision,
|
||||
// which is the embedded SuperBlock field). last_compact_revision() is
|
||||
// a separate bookkeeping value recorded just before a compaction starts
|
||||
// (for makeup-diff catch-up) and is intentionally left behind the live
|
||||
// revision afterward — it is not interchangeable with the live value and
|
||||
// must not be used here, or this check spuriously fails on every volume
|
||||
// that has ever been compacted even once.
|
||||
if req.compaction_revision != u32::MAX
|
||||
&& v.last_compact_revision() != req.compaction_revision as u16
|
||||
&& u32::from(v.super_block.compaction_revision) != req.compaction_revision
|
||||
{
|
||||
return Err(Status::failed_precondition(format!(
|
||||
"volume {} is compacted",
|
||||
@@ -2765,6 +2773,58 @@ impl VolumeServer for VolumeGrpcService {
|
||||
}
|
||||
}
|
||||
|
||||
// Copy the generation-0 bitrot checksum sidecar (.ecsum) when requested, so
|
||||
// protection travels with the shards. Tolerant of a missing source (no-op):
|
||||
// this non-2PC path has no Prepare backstop, and an unprotected source
|
||||
// simply leaves the copy unprotected.
|
||||
if req.copy_ecsum_file {
|
||||
let copy_req = volume_server_pb::CopyFileRequest {
|
||||
volume_id: req.volume_id,
|
||||
collection: req.collection.clone(),
|
||||
is_ec_volume: true,
|
||||
ext: ".ecsum".to_string(),
|
||||
compaction_revision: u32::MAX,
|
||||
stop_offset: i64::MAX as u64,
|
||||
ignore_source_file_not_found: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut stream = client
|
||||
.copy_file(copy_req)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Status::internal(format!(
|
||||
"VolumeEcShardsCopy volume {} copy .ecsum: {}",
|
||||
vid, e
|
||||
))
|
||||
})?
|
||||
.into_inner();
|
||||
|
||||
let file_path = {
|
||||
let base =
|
||||
crate::storage::volume::volume_file_name(&dest_dir, &req.collection, vid);
|
||||
format!("{}.ecsum", base)
|
||||
};
|
||||
let mut file = std::fs::File::create(&file_path)
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
let mut written: u64 = 0;
|
||||
while let Some(chunk) = stream
|
||||
.message()
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("recv .ecsum: {}", e)))?
|
||||
{
|
||||
use std::io::Write;
|
||||
file.write_all(&chunk.file_content)
|
||||
.map_err(|e| Status::internal(format!("write {}: {}", file_path, e)))?;
|
||||
written += chunk.file_content.len() as u64;
|
||||
}
|
||||
// A missing source yields an empty stream; drop the 0-byte file so mount
|
||||
// sees no sidecar (protection Off) rather than a truncated/invalid one.
|
||||
if written == 0 {
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(&file_path);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Response::new(
|
||||
volume_server_pb::VolumeEcShardsCopyResponse {},
|
||||
))
|
||||
@@ -3911,7 +3971,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// Validate mode
|
||||
let mode = req.mode;
|
||||
match mode {
|
||||
1 | 2 | 3 => {} // INDEX=1, FULL=2, LOCAL=3
|
||||
1 | 2 | 3 | 4 => {} // INDEX=1, FULL=2, LOCAL=3, CHECKSUM=4
|
||||
_ => {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"unsupported EC volume scrub mode {}",
|
||||
@@ -3962,22 +4022,75 @@ impl VolumeServer for VolumeGrpcService {
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
// FULL: verify every needle across local AND remote shards.
|
||||
{
|
||||
// Match Go: a missing requested volume is a hard error.
|
||||
// FULL: Go-parity per-needle local+remote walk, PLUS a TEMPORARY
|
||||
// local Reed-Solomon parity check. The needle walk only reads
|
||||
// DATA-shard intervals of LIVE needles, so on its own it can't
|
||||
// catch silent bitrot in a PARITY shard or an unwalked cold
|
||||
// region. Go closes that gap with a separate CHECKSUM mode over
|
||||
// .ecsum, which Rust does not have yet; running both here is a
|
||||
// deliberate divergence from Go FULL to preserve coverage. Drop
|
||||
// verify_ec_shards from this arm once mode 4 (CHECKSUM) lands.
|
||||
//
|
||||
// The RS recompute needs every shard co-located, so only run it
|
||||
// when this node holds all data+parity shards (single-node EC);
|
||||
// on a distributed layout it would report every non-local shard
|
||||
// as missing. Snapshot under a brief lock; release before await.
|
||||
let (dir, collection, data_shards, parity_shards, all_local) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
if store.find_ec_volume(vid).is_none() {
|
||||
return Err(Status::not_found(format!(
|
||||
"EC volume id {} not found",
|
||||
vid.0
|
||||
)));
|
||||
}
|
||||
}
|
||||
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
|
||||
Status::not_found(format!("EC volume id {} not found", vid.0))
|
||||
})?;
|
||||
let total = (ecv.data_shards + ecv.parity_shards) as usize;
|
||||
let local = ecv.shards.iter().filter(|s| s.is_some()).count();
|
||||
(
|
||||
ecv.dir.clone(),
|
||||
ecv.collection.clone(),
|
||||
ecv.data_shards as usize,
|
||||
ecv.parity_shards as usize,
|
||||
local == total,
|
||||
)
|
||||
};
|
||||
total_volumes += 1;
|
||||
let (files, shard_infos, errs) =
|
||||
|
||||
// (1) Per-needle local+remote walk (Go ScrubEcVolume parity).
|
||||
let (files, mut shard_infos, mut errs) =
|
||||
crate::server::store_ec::scrub_ec_volume_distributed(&self.state, vid, false)
|
||||
.await;
|
||||
total_files += files as u64;
|
||||
total_files += files as u64; // count comes from the needle walk only
|
||||
|
||||
// (2) Local parity check, gated on all-shards-local. Blocking RS
|
||||
// verify -> spawn_blocking; inputs are owned, no lock held.
|
||||
if all_local && !dir.is_empty() {
|
||||
let collection_pc = collection.clone();
|
||||
let (parity_broken, parity_details) = tokio::task::spawn_blocking(move || {
|
||||
crate::storage::erasure_coding::ec_encoder::verify_ec_shards(
|
||||
&dir,
|
||||
&collection_pc,
|
||||
vid,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("verify_ec_shards join: {}", e)))?
|
||||
.unwrap_or_else(|e| (Vec::new(), vec![format!("verify_ec_shards: {}", e)]));
|
||||
|
||||
let mut seen: std::collections::HashSet<u32> =
|
||||
shard_infos.iter().map(|s| s.shard_id).collect();
|
||||
for sid in parity_broken {
|
||||
if seen.insert(sid) {
|
||||
shard_infos.push(volume_server_pb::EcShardInfo {
|
||||
shard_id: sid,
|
||||
collection: collection.clone(),
|
||||
volume_id: vid.0,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
shard_infos.sort_by_key(|s| s.shard_id);
|
||||
errs.extend(parity_details);
|
||||
}
|
||||
|
||||
if !errs.is_empty() || !shard_infos.is_empty() {
|
||||
broken_volume_ids.push(vid.0);
|
||||
broken_shard_infos.extend(shard_infos);
|
||||
@@ -4005,6 +4118,36 @@ impl VolumeServer for VolumeGrpcService {
|
||||
}
|
||||
}
|
||||
}
|
||||
4 => {
|
||||
// CHECKSUM: verify each local shard's raw bytes against the
|
||||
// bitrot checksum sidecar, exercising cold parity shards.
|
||||
// Read-only. Mirrors Go's v.ChecksumScrub().
|
||||
let (blocks_scanned, broken, errs, collection) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
|
||||
Status::not_found(format!("EC volume id {} not found", vid.0))
|
||||
})?;
|
||||
let collection = ecv.collection.clone();
|
||||
let (blocks, broken, errs) = ecv.checksum_scrub();
|
||||
(blocks, broken, errs, collection)
|
||||
};
|
||||
total_volumes += 1;
|
||||
total_files += blocks_scanned;
|
||||
if !errs.is_empty() || !broken.is_empty() {
|
||||
broken_volume_ids.push(vid.0);
|
||||
for b in broken {
|
||||
broken_shard_infos.push(volume_server_pb::EcShardInfo {
|
||||
volume_id: vid.0,
|
||||
collection: collection.clone(),
|
||||
shard_id: b,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
for msg in errs {
|
||||
details.push(format!("ecvol {}: {}", vid.0, msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => unreachable!(), // validated above
|
||||
}
|
||||
}
|
||||
@@ -5522,6 +5665,105 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for comparing the wrong compaction-revision field.
|
||||
// last_compact_revision() is bookkeeping recorded just before a compaction
|
||||
// starts (for makeup-diff catch-up) and is intentionally left behind
|
||||
// super_block.compaction_revision once the compaction commits. copy_file's
|
||||
// precondition check must compare against the live super_block value
|
||||
// (matching Go's v.CompactionRevision), not the stale bookkeeping one, or
|
||||
// it fails "volume N is compacted" on every volume that has ever been
|
||||
// compacted even once.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_copy_file_accepts_live_revision_after_compaction() {
|
||||
let (service, _tmp) = make_local_service_with_volume("", None);
|
||||
|
||||
// Drive a real compaction to completion so the two revision fields
|
||||
// actually diverge the way they do in production, rather than poking
|
||||
// the struct fields directly.
|
||||
let (revision_before, revision_after, last_compact_revision_after) = {
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
let (_, v) = store.find_volume_mut(VolumeId(1)).unwrap();
|
||||
let before = v.super_block.compaction_revision;
|
||||
|
||||
v.compact_by_index(0, 0, |_| true).unwrap();
|
||||
v.commit_compact().unwrap();
|
||||
|
||||
(before, v.super_block.compaction_revision, v.last_compact_revision())
|
||||
};
|
||||
|
||||
assert_eq!(revision_before, 0, "fresh volume starts at revision 0");
|
||||
assert_eq!(
|
||||
revision_after, 1,
|
||||
"live super_block.compaction_revision must advance after commit_compact"
|
||||
);
|
||||
assert_eq!(
|
||||
last_compact_revision_after, 0,
|
||||
"last_compact_revision() is recorded pre-compaction and must stay \
|
||||
behind the live revision — this divergence is exactly what made \
|
||||
the old check fail permanently"
|
||||
);
|
||||
|
||||
// The live revision (1) must be accepted: this is what
|
||||
// read_volume_file_status would report to a caller right now.
|
||||
let response = service
|
||||
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
|
||||
volume_id: 1,
|
||||
ext: ".dat".to_string(),
|
||||
compaction_revision: revision_after as u32,
|
||||
stop_offset: u64::MAX,
|
||||
collection: String::new(),
|
||||
is_ec_volume: false,
|
||||
ignore_source_file_not_found: false,
|
||||
}))
|
||||
.await;
|
||||
assert!(
|
||||
response.is_ok(),
|
||||
"copy_file must accept the live compaction_revision, got: {:?}",
|
||||
response.err()
|
||||
);
|
||||
|
||||
// A genuinely stale/wrong revision must still be rejected — the fix
|
||||
// corrects which field is compared, it does not disable the check.
|
||||
let stale_response = service
|
||||
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
|
||||
volume_id: 1,
|
||||
ext: ".dat".to_string(),
|
||||
compaction_revision: 99,
|
||||
stop_offset: u64::MAX,
|
||||
collection: String::new(),
|
||||
is_ec_volume: false,
|
||||
ignore_source_file_not_found: false,
|
||||
}))
|
||||
.await;
|
||||
let err = match stale_response {
|
||||
Ok(_) => panic!("a genuinely stale revision must be rejected"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
|
||||
assert!(err.message().contains("is compacted"));
|
||||
|
||||
// A request revision that only collides after truncating to u16 must be
|
||||
// rejected: 65537 as u16 == 1 == the live revision, but as u32 they differ.
|
||||
// Compare in u32 space (matching Go) so this cannot spuriously pass.
|
||||
let truncating_response = service
|
||||
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
|
||||
volume_id: 1,
|
||||
ext: ".dat".to_string(),
|
||||
compaction_revision: u32::from(revision_after) + (1 << 16),
|
||||
stop_offset: u64::MAX,
|
||||
collection: String::new(),
|
||||
is_ec_volume: false,
|
||||
ignore_source_file_not_found: false,
|
||||
}))
|
||||
.await;
|
||||
let err = match truncating_response {
|
||||
Ok(_) => panic!("a revision that only matches after u16 truncation must be rejected"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
|
||||
assert!(err.message().contains("is compacted"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_volume_ec_shards_generate_persists_expire_at_sec() {
|
||||
let ttl = crate::storage::needle::ttl::TTL::read("3m").unwrap();
|
||||
|
||||
@@ -546,6 +546,23 @@ async fn do_replicated_request(
|
||||
.await
|
||||
.map_err(|e| format!("lookup volume failed: {}", e))?;
|
||||
|
||||
// Mirror Go's GetWritableRemoteReplications: reject when the master reports fewer replicas than
|
||||
// the copy count. lookup_volume is uncached, so recovery is immediate once the replica re-registers.
|
||||
let copy_count = {
|
||||
let store = state.store.read().unwrap();
|
||||
store.find_volume(VolumeId(vid)).map_or(1, |(_, v)| {
|
||||
v.super_block.replica_placement.get_copy_count()
|
||||
})
|
||||
};
|
||||
if locations.len() < copy_count as usize {
|
||||
return Err(format!(
|
||||
"replicating operations [{}] is less than volume {} replication copy count [{}]",
|
||||
locations.len(),
|
||||
vid,
|
||||
copy_count
|
||||
));
|
||||
}
|
||||
|
||||
let self_http = to_http_address(&state.self_url);
|
||||
let remote_locations: Vec<_> = locations
|
||||
.into_iter()
|
||||
@@ -1262,7 +1279,9 @@ async fn get_or_head_handler_inner(
|
||||
&query,
|
||||
&etag,
|
||||
&last_modified_str,
|
||||
) {
|
||||
)
|
||||
.await
|
||||
{
|
||||
return resp;
|
||||
}
|
||||
// If manifest expansion fails (invalid JSON etc.), fall through to raw data
|
||||
@@ -3179,12 +3198,11 @@ struct ChunkManifest {
|
||||
struct ChunkInfo {
|
||||
fid: String,
|
||||
offset: i64,
|
||||
#[allow(dead_code)]
|
||||
size: i64,
|
||||
}
|
||||
|
||||
/// Try to expand a chunk manifest needle. Returns None if manifest can't be parsed.
|
||||
fn try_expand_chunk_manifest(
|
||||
async fn try_expand_chunk_manifest(
|
||||
state: &Arc<VolumeServerState>,
|
||||
n: &Needle,
|
||||
_headers: &HeaderMap,
|
||||
@@ -3224,29 +3242,26 @@ fn try_expand_chunk_manifest(
|
||||
return None;
|
||||
}
|
||||
|
||||
// Read and concatenate all chunks
|
||||
// Read and concatenate all chunks. Each chunk is resolved to wherever it
|
||||
// lives — a local regular volume, a local EC volume (reconstruct-on-read),
|
||||
// or a peer via master lookup — mirroring Go's ChunkedFileReader, which
|
||||
// never assumes chunks are local regular needles.
|
||||
let mut result = vec![0u8; manifest.size as usize];
|
||||
let store = state.store.read().unwrap();
|
||||
for chunk in &manifest.chunks {
|
||||
let (chunk_vid, chunk_nid, chunk_cookie) = match parse_url_path(&chunk.fid) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
return Some(
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("invalid chunk fid: {}", chunk.fid),
|
||||
)
|
||||
.into_response(),
|
||||
// Validate the attacker-controlled chunk offset before indexing: a
|
||||
// negative value would wrap to a huge usize, and an out-of-range one has
|
||||
// nowhere to land.
|
||||
if chunk.offset < 0 || chunk.size < 0 {
|
||||
return Some(
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("invalid negative chunk offset/size in {}", chunk.fid),
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut chunk_needle = Needle {
|
||||
id: chunk_nid,
|
||||
cookie: chunk_cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
match store.read_volume_needle(chunk_vid, &mut chunk_needle) {
|
||||
Ok(_) => {}
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
let data = match read_chunk_needle(state, &chunk.fid).await {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
return Some(
|
||||
(
|
||||
@@ -3256,56 +3271,16 @@ fn try_expand_chunk_manifest(
|
||||
.into_response(),
|
||||
)
|
||||
}
|
||||
}
|
||||
// Validate the attacker-controlled chunk offset before indexing: a
|
||||
// negative value would wrap to a huge usize, and an out-of-range one has
|
||||
// nowhere to land.
|
||||
if chunk.offset < 0 {
|
||||
return Some(
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("invalid negative chunk offset in {}", chunk.fid),
|
||||
)
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
};
|
||||
let offset = chunk.offset as usize;
|
||||
if offset >= result.len() {
|
||||
continue;
|
||||
}
|
||||
// Write the chunk into its window in `result`. Compressed chunks inflate
|
||||
// directly into the destination slice (bounded by the remaining window),
|
||||
// so a chunk never allocates a second large buffer — peak memory stays at
|
||||
// ~manifest.size instead of doubling. Bytes past the window are dropped,
|
||||
// matching the prior truncation behavior.
|
||||
if chunk_needle.is_compressed() {
|
||||
use flate2::read::GzDecoder;
|
||||
use std::io::Read as _;
|
||||
let mut decoder = GzDecoder::new(&chunk_needle.data[..]);
|
||||
let window = &mut result[offset..];
|
||||
let mut written = 0usize;
|
||||
let mut decode_failed = false;
|
||||
while written < window.len() {
|
||||
match decoder.read(&mut window[written..]) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => written += n,
|
||||
Err(_) => {
|
||||
decode_failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// On any decode failure, drop the partial output and fall back to the
|
||||
// chunk's raw bytes (truncated to the window), preserving prior behavior.
|
||||
if decode_failed {
|
||||
window[..written].fill(0);
|
||||
let copy_len = chunk_needle.data.len().min(window.len());
|
||||
window[..copy_len].copy_from_slice(&chunk_needle.data[..copy_len]);
|
||||
}
|
||||
} else {
|
||||
let copy_len = chunk_needle.data.len().min(result.len() - offset);
|
||||
result[offset..offset + copy_len].copy_from_slice(&chunk_needle.data[..copy_len]);
|
||||
}
|
||||
// Clamp to the chunk's declared size so an over-long chunk can't bleed
|
||||
// into the next chunk's window; also drop bytes past the buffer end.
|
||||
let bound = (chunk.size as usize).min(result.len() - offset);
|
||||
let copy_len = data.len().min(bound);
|
||||
result[offset..offset + copy_len].copy_from_slice(&data[..copy_len]);
|
||||
}
|
||||
|
||||
// Determine filename: URL path filename, then manifest name
|
||||
@@ -3451,6 +3426,136 @@ fn try_expand_chunk_manifest(
|
||||
Some((StatusCode::OK, response_headers, result).into_response())
|
||||
}
|
||||
|
||||
/// Read one chunk-manifest chunk's final (decompressed) content bytes from
|
||||
/// wherever it lives: a local regular volume, a local EC volume
|
||||
/// (reconstruct-on-read from surviving shards), or a peer resolved via the
|
||||
/// master. Mirrors Go's ChunkedFileReader, which looks every chunk up through
|
||||
/// the master instead of assuming a local regular needle.
|
||||
async fn read_chunk_needle(
|
||||
state: &Arc<VolumeServerState>,
|
||||
fid: &str,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let (vid, nid, cookie) =
|
||||
parse_url_path(fid).ok_or_else(|| format!("invalid chunk fid: {}", fid))?;
|
||||
|
||||
// Decide where the chunk lives under one store read lock; drop it before any
|
||||
// await (the EC and remote paths are async).
|
||||
enum Placement {
|
||||
Ec,
|
||||
Remote,
|
||||
}
|
||||
let placement = {
|
||||
let store = state.store.read().unwrap();
|
||||
if store.find_volume(vid).is_some() {
|
||||
let mut n = Needle {
|
||||
id: nid,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
return store
|
||||
.read_volume_needle(vid, &mut n)
|
||||
.map_err(|e| format!("{}", e))
|
||||
.and_then(|_| cookie_checked_chunk(n, cookie));
|
||||
} else if store.find_ec_volume(vid).is_some() {
|
||||
Placement::Ec
|
||||
} else {
|
||||
Placement::Remote
|
||||
}
|
||||
};
|
||||
|
||||
match placement {
|
||||
Placement::Ec => {
|
||||
match crate::server::store_ec::read_ec_shard_needle_distributed(state, vid, nid).await {
|
||||
Ok(Some(n)) => cookie_checked_chunk(n, cookie),
|
||||
Ok(None) => Err("not found".to_string()),
|
||||
Err(e) => Err(format!("{}", e)),
|
||||
}
|
||||
}
|
||||
// The peer serves through its own GET handler, which validates the cookie.
|
||||
Placement::Remote => read_remote_chunk_needle(state, vid, fid).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a locally-read chunk's cookie against the one in its fid, then return
|
||||
/// its content bytes. The main GET paths check the cookie after a read; a chunk
|
||||
/// read must do the same so a stale/guessed id can't serve another needle's data.
|
||||
fn cookie_checked_chunk(n: Needle, cookie: Cookie) -> Result<Vec<u8>, String> {
|
||||
if n.cookie != cookie {
|
||||
return Err("not found".to_string());
|
||||
}
|
||||
decompress_chunk(n)
|
||||
}
|
||||
|
||||
/// Return a needle's content bytes, decompressing gzip payloads the way the read
|
||||
/// handler does for a client that did not ask for gzip.
|
||||
fn decompress_chunk(n: Needle) -> Result<Vec<u8>, String> {
|
||||
if n.is_compressed() {
|
||||
match maybe_decompress_gzip(&n.data) {
|
||||
Ok(d) => Ok(d),
|
||||
Err(GunzipError::TooLarge) => {
|
||||
Err("compressed chunk exceeds decompression limit".to_string())
|
||||
}
|
||||
// Not valid gzip; keep the raw bytes, matching the prior fallback.
|
||||
Err(GunzipError::Decode) => Ok(n.data),
|
||||
}
|
||||
} else {
|
||||
Ok(n.data)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch a chunk that is not hosted locally from a peer volume server. The peer
|
||||
/// serves the final (decompressed) bytes whether the chunk is on a regular or EC
|
||||
/// volume, so a chunk whose EC shards live elsewhere is still reconstructed on
|
||||
/// the holder's side. Mirrors Go's ChunkedFileReader.readChunkNeedle.
|
||||
async fn read_remote_chunk_needle(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
fid: &str,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let locations = lookup_volume(
|
||||
&state.http_client,
|
||||
&state.outgoing_http_scheme,
|
||||
&state.master_url,
|
||||
vid.0,
|
||||
)
|
||||
.await?;
|
||||
if locations.is_empty() {
|
||||
return Err("not found".to_string());
|
||||
}
|
||||
|
||||
let mut last_err = String::new();
|
||||
for loc in &locations {
|
||||
// Skip self: the local paths already ruled this server out.
|
||||
if loc.url.contains(&state.self_url) {
|
||||
continue;
|
||||
}
|
||||
let target_http = to_http_address(&loc.url);
|
||||
let url = match normalize_outgoing_http_url(
|
||||
&state.outgoing_http_scheme,
|
||||
&format!("{}/{}?proxied=true", target_http, fid),
|
||||
) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
last_err = e;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match state.http_client.get(&url).send().await {
|
||||
Ok(resp) if resp.status().is_success() => match resp.bytes().await {
|
||||
Ok(b) => return Ok(b.to_vec()),
|
||||
Err(e) => last_err = format!("read body from {}: {}", url, e),
|
||||
},
|
||||
Ok(resp) => last_err = format!("{} returned {}", url, resp.status()),
|
||||
Err(e) => last_err = format!("request to {} failed: {}", url, e),
|
||||
}
|
||||
}
|
||||
Err(if last_err.is_empty() {
|
||||
"not found".to_string()
|
||||
} else {
|
||||
last_err
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helpers
|
||||
// ============================================================================
|
||||
|
||||
@@ -625,7 +625,8 @@ async fn send_deregister_heartbeat(
|
||||
) {
|
||||
let empty = {
|
||||
let store = state.store.read().unwrap();
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(&store);
|
||||
// Deregister: no effective max computed, fall back to configured max.
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(&store, &[]);
|
||||
master_pb::Heartbeat {
|
||||
id: store.id.clone(),
|
||||
ip: config.ip.clone(),
|
||||
@@ -747,7 +748,10 @@ fn collect_heartbeat(
|
||||
)
|
||||
}
|
||||
|
||||
fn collect_location_metadata(store: &Store) -> (Vec<String>, Vec<master_pb::DiskTag>) {
|
||||
fn collect_location_metadata(
|
||||
store: &Store,
|
||||
disk_max_by_id: &[i32],
|
||||
) -> (Vec<String>, Vec<master_pb::DiskTag>) {
|
||||
let location_uuids = store
|
||||
.locations
|
||||
.iter()
|
||||
@@ -757,9 +761,17 @@ fn collect_location_metadata(store: &Store) -> (Vec<String>, Vec<master_pb::Disk
|
||||
.locations
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(disk_id, loc)| master_pb::DiskTag {
|
||||
disk_id: disk_id as u32,
|
||||
tags: loc.tags.clone(),
|
||||
.map(|(disk_id, loc)| {
|
||||
let max_volume_count = disk_max_by_id
|
||||
.get(disk_id)
|
||||
.copied()
|
||||
.unwrap_or_else(|| loc.max_volume_count.load(Ordering::Relaxed));
|
||||
master_pb::DiskTag {
|
||||
disk_id: disk_id as u32,
|
||||
tags: loc.tags.clone(),
|
||||
r#type: loc.disk_type.to_string(),
|
||||
max_volume_count: max_volume_count as i64,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(location_uuids, disk_tags)
|
||||
@@ -790,6 +802,8 @@ fn build_heartbeat_with_ec_status(
|
||||
let mut volumes = Vec::new();
|
||||
let mut max_file_key = NeedleId(0);
|
||||
let mut max_volume_counts: HashMap<String, u32> = HashMap::new();
|
||||
let mut disk_total_bytes: HashMap<String, u64> = HashMap::new();
|
||||
let mut disk_free_bytes: HashMap<String, u64> = HashMap::new();
|
||||
|
||||
// Collect per-collection disk size and read-only counts for metrics
|
||||
let mut disk_sizes: HashMap<String, (u64, u64)> = HashMap::new(); // (normal, deleted)
|
||||
@@ -797,6 +811,9 @@ fn build_heartbeat_with_ec_status(
|
||||
|
||||
let volume_size_limit = store.volume_size_limit.load(Ordering::Relaxed);
|
||||
|
||||
// Per-disk effective max for DiskTag, captured alongside the per-type sum.
|
||||
let mut disk_max_by_id = vec![0i32; store.locations.len()];
|
||||
|
||||
for (disk_id, loc) in store.locations.iter_mut().enumerate() {
|
||||
let disk_type_str = loc.disk_type.to_string();
|
||||
let mut effective_max_count = loc.max_volume_count.load(Ordering::Relaxed);
|
||||
@@ -812,7 +829,15 @@ fn build_heartbeat_with_ec_status(
|
||||
if effective_max_count < 0 {
|
||||
effective_max_count = 0;
|
||||
}
|
||||
*max_volume_counts.entry(disk_type_str).or_insert(0) += effective_max_count as u32;
|
||||
*max_volume_counts.entry(disk_type_str.clone()).or_insert(0) += effective_max_count as u32;
|
||||
disk_max_by_id[disk_id] = effective_max_count;
|
||||
// Sum capacity per disk type; assumes one location per filesystem. Locations
|
||||
// sharing a mount over-report absolute bytes but not the used ratio the gate
|
||||
// uses. Mirrors weed/storage/store.go.
|
||||
*disk_total_bytes.entry(disk_type_str.clone()).or_insert(0) +=
|
||||
loc.disk_total_bytes.load(Ordering::Relaxed);
|
||||
*disk_free_bytes.entry(disk_type_str).or_insert(0) +=
|
||||
loc.disk_free_bytes.load(Ordering::Relaxed);
|
||||
|
||||
let mut delete_vids = Vec::new();
|
||||
for (_, vol) in loc.iter_volumes() {
|
||||
@@ -861,7 +886,7 @@ fn build_heartbeat_with_ec_status(
|
||||
replica_placement: vol.super_block.replica_placement.to_byte() as u32,
|
||||
version: vol.super_block.version.0 as u32,
|
||||
ttl: vol.super_block.ttl.to_u32(),
|
||||
compact_revision: vol.last_compact_revision() as u32,
|
||||
compact_revision: vol.super_block.compaction_revision as u32,
|
||||
modified_at_second: vol.last_modified_ts() as i64,
|
||||
disk_type: loc.disk_type.to_string(),
|
||||
disk_id: disk_id as u32,
|
||||
@@ -930,7 +955,7 @@ fn build_heartbeat_with_ec_status(
|
||||
crate::metrics::MAX_VOLUMES.set(total_max);
|
||||
|
||||
let has_no_volumes = volumes.is_empty();
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(store);
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(store, &disk_max_by_id);
|
||||
|
||||
master_pb::Heartbeat {
|
||||
id: store.id.clone(),
|
||||
@@ -946,6 +971,8 @@ fn build_heartbeat_with_ec_status(
|
||||
has_no_volumes,
|
||||
has_no_ec_shards,
|
||||
max_volume_counts,
|
||||
disk_total_bytes,
|
||||
disk_free_bytes,
|
||||
grpc_port: config.grpc_port as u32,
|
||||
location_uuids,
|
||||
disk_tags,
|
||||
@@ -1153,6 +1180,46 @@ mod tests {
|
||||
heartbeat.disk_tags[0].tags,
|
||||
vec!["fast".to_string(), "ssd".to_string()]
|
||||
);
|
||||
assert_eq!(heartbeat.disk_tags[0].r#type, DiskType::HardDrive.to_string());
|
||||
assert_eq!(heartbeat.disk_tags[0].max_volume_count, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_disk_tag_reflects_disk_space_low_override() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
3,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(7),
|
||||
"pics",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Low disk space caps the per-disk max at used slots (1 volume, 0 EC).
|
||||
store.locations[0]
|
||||
.is_disk_space_low
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(heartbeat.disk_tags[0].max_volume_count, 1);
|
||||
assert_eq!(heartbeat.max_volume_counts[&DiskType::HardDrive.to_string()], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1262,6 +1329,43 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_reports_disk_bytes() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
8,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
// Populate the cached physical-capacity fields from a real statvfs probe.
|
||||
store.locations[0].check_disk_space();
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
let disk_type = store.locations[0].disk_type.to_string();
|
||||
|
||||
assert!(
|
||||
heartbeat
|
||||
.disk_total_bytes
|
||||
.get(&disk_type)
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
> 0,
|
||||
"expected nonzero disk_total_bytes for the temp filesystem"
|
||||
);
|
||||
assert!(
|
||||
heartbeat.disk_free_bytes.contains_key(&disk_type),
|
||||
"expected a disk_free_bytes entry for the disk type"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_collect_ec_heartbeat_sets_go_metadata_and_ec_metrics() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -115,8 +115,13 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
{
|
||||
match cached_lookup_ec_shard_locations(state, vid).await {
|
||||
Ok(fresh) => {
|
||||
shard_locations = fresh.clone();
|
||||
write_back_shard_locations(state, vid, fresh);
|
||||
// A complete reply merges into the cache; an incomplete one
|
||||
// (< data_shards) is left unwritten — keep the prior cache.
|
||||
if let Some(merged) =
|
||||
write_back_shard_locations(state, vid, fresh, snapshot.data_shards as usize)
|
||||
{
|
||||
shard_locations = merged;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Lookup failed — proceed with cached values. If cache
|
||||
@@ -144,7 +149,7 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
shard_offset,
|
||||
size,
|
||||
} => {
|
||||
let buf = fetch_one_interval(
|
||||
let (buf, is_deleted) = fetch_one_interval(
|
||||
state,
|
||||
vid,
|
||||
needle_id,
|
||||
@@ -157,6 +162,12 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
snapshot.encode_ts_ns,
|
||||
)
|
||||
.await?;
|
||||
// A peer reports the needle deleted (a cross-server window where the
|
||||
// local index still shows it live): treat as not-found rather than
|
||||
// serving zeros, mirroring Go's ErrorDeleted.
|
||||
if is_deleted {
|
||||
return Ok(None);
|
||||
}
|
||||
assembled.push(buf);
|
||||
}
|
||||
}
|
||||
@@ -241,11 +252,23 @@ pub async fn scrub_ec_volume_distributed(
|
||||
let mut errs = seed_errs;
|
||||
|
||||
// Refresh the shard-location cache once up front (mirrors Go's
|
||||
// cachedLookupEcShardLocations); a failed lookup is a hard error rather than
|
||||
// a per-needle connect storm against a down master.
|
||||
// cachedLookupEcShardLocations). A partial reply (< data_shards locations, a
|
||||
// master mid-recovery) or a failed lookup is a hard, retryable error — never
|
||||
// overwrite a good cache with a partial map or storm a down master per needle.
|
||||
if needs_refresh(&cached_locations, cache_refreshed_at, data_shards, total_shards) {
|
||||
match cached_lookup_ec_shard_locations(state, vid).await {
|
||||
Ok(fresh) => write_back_shard_locations(state, vid, fresh),
|
||||
Ok(fresh) => {
|
||||
if write_back_shard_locations(state, vid, fresh, data_shards).is_none() {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!(
|
||||
"failed to locate shard via master grpc: fewer than {} data-shard locations returned",
|
||||
data_shards
|
||||
)],
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
return (
|
||||
0,
|
||||
@@ -256,6 +279,24 @@ pub async fn scrub_ec_volume_distributed(
|
||||
}
|
||||
}
|
||||
|
||||
// Hoist the post-refresh shard-location map once; it is stable for the whole
|
||||
// walk, so per-needle snapshots no longer clone it.
|
||||
let locations: HashMap<ShardId, Vec<String>> = {
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = match store.find_ec_volume(vid) {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!("EC volume id {} not found", vid.0)],
|
||||
)
|
||||
}
|
||||
};
|
||||
let map = ecv.shard_locations.read().unwrap().clone();
|
||||
map
|
||||
};
|
||||
|
||||
// Walk the .ecx (private fd, no lock) for the row count + live (id, offset, size).
|
||||
let mut count: i64 = 0;
|
||||
let mut needles: Vec<(NeedleId, Offset, Size)> = Vec::new();
|
||||
@@ -263,7 +304,12 @@ pub async fn scrub_ec_volume_distributed(
|
||||
Ok(mut f) => {
|
||||
if let Err(e) = crate::storage::idx::walk_index_file(&mut f, 0, |id, offset, size| {
|
||||
count += 1;
|
||||
if !size.is_tombstone() {
|
||||
// Skip ALL deleted entries: -1 tombstones (runtime delete folded
|
||||
// into .ecx) and -originalSize entries (a needle deleted on the
|
||||
// regular volume before EC encode). get_actual_size uses the raw
|
||||
// signed size, so a negative would yield empty intervals
|
||||
// (false-positive) or an under-16-byte buffer (parse panic).
|
||||
if !size.is_deleted() {
|
||||
needles.push((id, offset, size));
|
||||
}
|
||||
Ok(())
|
||||
@@ -281,8 +327,13 @@ pub async fn scrub_ec_volume_distributed(
|
||||
// Per-needle snapshot under the lock from the RAW .ecx (offset, size) so
|
||||
// logically-deleted needles are still verified; lock dropped before await.
|
||||
let snapshot = match scrub_snapshot_under_lock(state, vid, offset, size) {
|
||||
Ok(Some(s)) => s,
|
||||
Ok(None) => continue, // volume gone since the walk
|
||||
Ok(s) => s,
|
||||
// Volume unmounted mid-scan: abort with an error rather than skipping
|
||||
// every remaining needle, which would report a false-CLEAN result.
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
errs.push(format!("EC volume {} unmounted during scrub: {}", vid.0, e));
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
errs.push(format!("needle {} on EC volume {}: {}", id.0, vid.0, e));
|
||||
continue;
|
||||
@@ -301,14 +352,11 @@ pub async fn scrub_ec_volume_distributed(
|
||||
shard_offset,
|
||||
size: ssize,
|
||||
} => {
|
||||
let sources = snapshot
|
||||
.cached_locations
|
||||
.get(shard_id)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let sources: &[String] =
|
||||
locations.get(shard_id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
match read_remote_ec_shard_interval(
|
||||
state,
|
||||
&sources,
|
||||
sources,
|
||||
vid,
|
||||
id,
|
||||
*shard_id,
|
||||
@@ -318,7 +366,11 @@ pub async fn scrub_ec_volume_distributed(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(buf) => data.extend_from_slice(&buf),
|
||||
// A deleted shard yields no bytes; zero-fill the interval so
|
||||
// the assembled needle reaches read_bytes -> SizeMismatch{0}
|
||||
// -> the delete-state suppression (mirrors Go's pre-zeroed buffer).
|
||||
Ok((_, true)) => data.resize(data.len() + *ssize, 0),
|
||||
Ok((buf, false)) => data.extend_from_slice(&buf),
|
||||
Err(_) => {
|
||||
errs.push(format!(
|
||||
"failed to read EC shard {} for needle {} on volume {} (interval {}/{})",
|
||||
@@ -408,33 +460,52 @@ fn scrub_snapshot_under_lock(
|
||||
vid: VolumeId,
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
) -> io::Result<Option<Snapshot>> {
|
||||
) -> io::Result<ScrubSnapshot> {
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = match store.find_ec_volume(vid) {
|
||||
Some(v) => v,
|
||||
None => return Ok(None),
|
||||
// Volume unmounted mid-scan: a distinct NotFound so the caller aborts
|
||||
// with an error rather than silently skipping (which would false-CLEAN).
|
||||
None => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("EC volume {} not found (unmounted mid-scan)", vid.0),
|
||||
))
|
||||
}
|
||||
};
|
||||
let intervals = ecv.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
|
||||
build_snapshot(ecv, offset, size, &intervals).map(Some)
|
||||
}
|
||||
|
||||
/// Read any locally-held shard intervals and assemble the rest as `NeedRemote`,
|
||||
/// then snapshot the scalars + shard-location cache so the caller can drop the
|
||||
/// store lock before awaiting remote reads. Shared by the read and scrub paths.
|
||||
fn build_snapshot(
|
||||
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
|
||||
) -> io::Result<Snapshot> {
|
||||
if intervals.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"no intervals for needle",
|
||||
));
|
||||
}
|
||||
let actual = get_actual_size(size, ecv.version);
|
||||
Ok(ScrubSnapshot {
|
||||
version: ecv.version,
|
||||
actual_size: get_actual_size(size, ecv.version) as usize,
|
||||
size_for_parse: size,
|
||||
intervals: read_local_intervals(ecv, &intervals),
|
||||
encode_ts_ns: ecv.encode_ts_ns,
|
||||
})
|
||||
}
|
||||
|
||||
/// Scalars + locally-read intervals for the FULL scrub. Unlike `Snapshot` it
|
||||
/// omits the shard-location cache: the scrub hoists the refreshed map once up
|
||||
/// front instead of cloning it per needle.
|
||||
struct ScrubSnapshot {
|
||||
version: Version,
|
||||
actual_size: usize,
|
||||
size_for_parse: Size,
|
||||
intervals: Vec<IntervalResult>,
|
||||
encode_ts_ns: i64,
|
||||
}
|
||||
|
||||
/// Read any locally-held shard intervals, marking the rest `NeedRemote`. Shared
|
||||
/// by the read-path `build_snapshot` and the scrub snapshot.
|
||||
fn read_local_intervals(
|
||||
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
|
||||
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
|
||||
) -> Vec<IntervalResult> {
|
||||
let mut interval_results = Vec::with_capacity(intervals.len());
|
||||
for interval in intervals {
|
||||
let (shard_id, shard_offset) = interval.to_shard_id_and_offset(ecv.data_shards);
|
||||
@@ -459,7 +530,25 @@ fn build_snapshot(
|
||||
}),
|
||||
}
|
||||
}
|
||||
interval_results
|
||||
}
|
||||
|
||||
/// Read local intervals, then snapshot the scalars + shard-location cache so the
|
||||
/// read path can drop the store lock before awaiting remote reads.
|
||||
fn build_snapshot(
|
||||
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
|
||||
) -> io::Result<Snapshot> {
|
||||
if intervals.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"no intervals for needle",
|
||||
));
|
||||
}
|
||||
let actual = get_actual_size(size, ecv.version);
|
||||
let interval_results = read_local_intervals(ecv, intervals);
|
||||
let cached_locations = ecv.shard_locations.read().unwrap().clone();
|
||||
let cache_refreshed_at = *ecv.shard_locations_refresh_time.lock().unwrap();
|
||||
|
||||
@@ -555,19 +644,29 @@ async fn cached_lookup_ec_shard_locations(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Merge a fresh `LookupEcVolume` reply into the per-EcVolume shard-location
|
||||
/// cache. Returns the merged map on success, or `None` when the reply is
|
||||
/// incomplete (and was therefore NOT written) or the volume is gone.
|
||||
///
|
||||
/// Completeness guard (mirrors Go's `cachedLookupEcShardLocations`): a reply
|
||||
/// carrying fewer than `data_shards` shard locations is a master-mid-recovery
|
||||
/// partial, not ground truth — Go aborts the lookup with a retryable error and
|
||||
/// leaves the cache + refresh time untouched. Returning `None` without writing
|
||||
/// does the same, so a previously-complete cache is never clobbered with a
|
||||
/// partial map. On a complete reply the write is a per-shard MERGE (see
|
||||
/// `merge_shard_locations`), not a full replace.
|
||||
fn write_back_shard_locations(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
locations: HashMap<ShardId, Vec<String>>,
|
||||
) {
|
||||
let store = state.store.read().unwrap();
|
||||
if let Some(ecv) = store.find_ec_volume(vid) {
|
||||
// Atomic swap + freshness stamp so a concurrent reader sees
|
||||
// either the prior cache or the fresh one — never an
|
||||
// intermediate half-replaced map with the freshness flag
|
||||
// already flipped.
|
||||
ecv.replace_shard_locations(locations);
|
||||
data_shards: usize,
|
||||
) -> Option<HashMap<ShardId, Vec<String>>> {
|
||||
if locations.len() < data_shards {
|
||||
return None;
|
||||
}
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = store.find_ec_volume(vid)?;
|
||||
Some(ecv.merge_shard_locations(locations))
|
||||
}
|
||||
|
||||
/// Build a SeaweedFS-style `host:httpPort.grpcPort` address from a
|
||||
@@ -599,7 +698,7 @@ async fn fetch_one_interval(
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
expected_encode_ts_ns: i64,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
) -> io::Result<(Vec<u8>, bool)> {
|
||||
// Direct peer read against the cached locations for this shard.
|
||||
if let Some(sources) = shard_locations.get(&shard_id) {
|
||||
if !sources.is_empty() {
|
||||
@@ -615,7 +714,9 @@ async fn fetch_one_interval(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(buf) => return Ok(buf),
|
||||
// A deleted needle short-circuits: don't reconstruct (every shard
|
||||
// would report deleted), let the caller return "deleted".
|
||||
Ok((buf, is_deleted)) => return Ok((buf, is_deleted)),
|
||||
Err(e) => {
|
||||
tracing::debug!(
|
||||
"direct read ec shard {}.{} from {:?} failed: {} — will reconstruct",
|
||||
@@ -631,7 +732,7 @@ async fn fetch_one_interval(
|
||||
|
||||
// Reconstruct: fan-out reads to every other shard at the same
|
||||
// (shard_offset, size). Mirrors `recoverOneRemoteEcShardInterval`.
|
||||
recover_one_remote_ec_shard_interval(
|
||||
let buf = recover_one_remote_ec_shard_interval(
|
||||
state,
|
||||
vid,
|
||||
needle_id,
|
||||
@@ -643,7 +744,8 @@ async fn fetch_one_interval(
|
||||
parity_shards,
|
||||
expected_encode_ts_ns,
|
||||
)
|
||||
.await
|
||||
.await?;
|
||||
Ok((buf, false))
|
||||
}
|
||||
|
||||
async fn read_remote_ec_shard_interval(
|
||||
@@ -655,7 +757,7 @@ async fn read_remote_ec_shard_interval(
|
||||
shard_offset: i64,
|
||||
size: usize,
|
||||
expected_encode_ts_ns: i64,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
) -> io::Result<(Vec<u8>, bool)> {
|
||||
let mut last_err: Option<io::Error> = None;
|
||||
for src in sources {
|
||||
match do_read_remote_ec_shard_interval(
|
||||
@@ -670,7 +772,7 @@ async fn read_remote_ec_shard_interval(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(buf) => return Ok(buf),
|
||||
Ok(res) => return Ok(res),
|
||||
Err(e) => last_err = Some(e),
|
||||
}
|
||||
}
|
||||
@@ -691,7 +793,7 @@ async fn do_read_remote_ec_shard_interval(
|
||||
shard_offset: i64,
|
||||
size: usize,
|
||||
expected_encode_ts_ns: i64,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
) -> io::Result<(Vec<u8>, bool)> {
|
||||
let grpc_addr =
|
||||
parse_grpc_address(source).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
|
||||
let endpoint = build_grpc_endpoint(&grpc_addr, state.outgoing_grpc_tls.as_ref())
|
||||
@@ -740,6 +842,7 @@ async fn do_read_remote_ec_shard_interval(
|
||||
let mut stream = resp.into_inner();
|
||||
|
||||
let mut out = Vec::with_capacity(size);
|
||||
let mut is_deleted = false;
|
||||
while let Some(msg) = stream
|
||||
.message()
|
||||
.await
|
||||
@@ -757,10 +860,23 @@ async fn do_read_remote_ec_shard_interval(
|
||||
),
|
||||
));
|
||||
}
|
||||
if msg.is_deleted {
|
||||
is_deleted = true;
|
||||
}
|
||||
if !msg.data.is_empty() {
|
||||
out.extend_from_slice(&msg.data);
|
||||
}
|
||||
}
|
||||
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
|
||||
// at read time and answers is_deleted with no payload. Signal the deletion to
|
||||
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
|
||||
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
|
||||
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
|
||||
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
|
||||
// into Reed-Solomon. Exempt from the short-read guard below.
|
||||
if is_deleted {
|
||||
return Ok((Vec::new(), true));
|
||||
}
|
||||
if out.len() < size {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
@@ -775,7 +891,7 @@ async fn do_read_remote_ec_shard_interval(
|
||||
));
|
||||
}
|
||||
out.truncate(size);
|
||||
Ok(out)
|
||||
Ok((out, false))
|
||||
}
|
||||
|
||||
async fn recover_one_remote_ec_shard_interval(
|
||||
@@ -859,8 +975,11 @@ async fn recover_one_remote_ec_shard_interval(
|
||||
|
||||
for (sid, res) in results {
|
||||
match res {
|
||||
Ok(buf) => {
|
||||
if (sid as usize) < total_shards {
|
||||
// Exclude a deleted shard from reconstruction (Go gates on a full
|
||||
// read): feeding the empty/zero buffer into Reed-Solomon would
|
||||
// corrupt the recovered shard.
|
||||
Ok((buf, is_deleted)) => {
|
||||
if !is_deleted && (sid as usize) < total_shards {
|
||||
bufs[sid as usize] = Some(buf);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,10 @@ pub struct DiskLocation {
|
||||
ec_volumes: HashMap<VolumeId, EcVolume>,
|
||||
pub is_disk_space_low: Arc<AtomicBool>,
|
||||
pub available_space: AtomicU64,
|
||||
// Physical filesystem capacity from the latest check_disk_space probe, reported
|
||||
// to the master so balancing can see real disk fullness, not just slot counts.
|
||||
pub disk_total_bytes: AtomicU64,
|
||||
pub disk_free_bytes: AtomicU64,
|
||||
pub min_free_space: MinFreeSpace,
|
||||
}
|
||||
|
||||
@@ -74,6 +78,8 @@ impl DiskLocation {
|
||||
ec_volumes: HashMap::new(),
|
||||
is_disk_space_low: Arc::new(AtomicBool::new(false)),
|
||||
available_space: AtomicU64::new(0),
|
||||
disk_total_bytes: AtomicU64::new(0),
|
||||
disk_free_bytes: AtomicU64::new(0),
|
||||
min_free_space,
|
||||
})
|
||||
}
|
||||
@@ -395,6 +401,12 @@ impl DiskLocation {
|
||||
for i in 0..MAX_SHARD_COUNT {
|
||||
rm_if_present(format!("{}.ec{:02}", base, i))?;
|
||||
}
|
||||
|
||||
// Remove the bitrot checksum sidecars from both the data and idx dirs.
|
||||
remove_bitrot_sidecars(&base)?;
|
||||
if self.idx_directory != self.directory {
|
||||
remove_bitrot_sidecars(&idx_base)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -655,6 +667,8 @@ impl DiskLocation {
|
||||
};
|
||||
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
|
||||
self.available_space.store(free, Ordering::Relaxed);
|
||||
self.disk_total_bytes.store(total, Ordering::Relaxed);
|
||||
self.disk_free_bytes.store(free, Ordering::Relaxed);
|
||||
|
||||
// Update resource gauges
|
||||
crate::metrics::RESOURCE_GAUGE
|
||||
@@ -1081,6 +1095,49 @@ fn rm_if_present(path: String) -> io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the bitrot checksum sidecars for a base file name: the legacy
|
||||
/// `<base>.ecsum` (generation 0) and any versioned `<base>.ecsum.v<N>`.
|
||||
/// Already-gone is success; returns the first real removal failure (and surfaces
|
||||
/// a directory-scan error) so a stale sidecar left behind is not reported as
|
||||
/// cleaned. Mirrors Go's removeBitrotSidecars.
|
||||
fn remove_bitrot_sidecars(base: &str) -> io::Result<()> {
|
||||
use crate::storage::erasure_coding::ec_bitrot::BITROT_SIDECAR_EXT;
|
||||
let rm = |path: std::path::PathBuf| -> io::Result<()> {
|
||||
match fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
};
|
||||
let mut first_err: Option<io::Error> = None;
|
||||
let mut record = |res: io::Result<()>| {
|
||||
if let Err(e) = res {
|
||||
if first_err.is_none() {
|
||||
first_err = Some(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
record(rm(format!("{}{}", base, BITROT_SIDECAR_EXT).into()));
|
||||
let path = std::path::Path::new(base);
|
||||
if let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) {
|
||||
let prefix = format!("{}{}.v", fname.to_string_lossy(), BITROT_SIDECAR_EXT);
|
||||
match fs::read_dir(parent) {
|
||||
Ok(entries) => {
|
||||
for entry in entries.flatten() {
|
||||
if entry.file_name().to_string_lossy().starts_with(&prefix) {
|
||||
record(rm(entry.path()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => record(Err(e)),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
match first_err {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ec_data_shards_from_vif(directory: &str, idx_directory: &str, collection: &str, vid: VolumeId) -> usize {
|
||||
for dir in [directory, idx_directory] {
|
||||
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
|
||||
|
||||
@@ -0,0 +1,840 @@
|
||||
//! EC bitrot detection — checksum sidecar.
|
||||
//!
|
||||
//! A per-volume sidecar file stores a CRC32C (Castagnoli) checksum for every
|
||||
//! fixed-size block of every EC shard, so a scrub (and the reconstruction path)
|
||||
//! can detect silent disk corruption in any shard — including cold parity shards
|
||||
//! that are never read during normal serving.
|
||||
//!
|
||||
//! The sidecar is OPTIONAL: an absent or generation-mismatched sidecar simply
|
||||
//! means "feature off" for that generation, so old binaries, JSON-only nodes,
|
||||
//! and rollback deployments ignore it and degrade gracefully.
|
||||
//!
|
||||
//! On-disk layout of `<base>.ecsum` (legacy/generation 0) and `<base>.ecsum.v<N>`:
|
||||
//!
|
||||
//! ```text
|
||||
//! [ magic(4) | format_version(2) | payload_len(4) | payload_crc32c(4) ] [ proto payload ]
|
||||
//! ```
|
||||
//!
|
||||
//! All header fields are BIG-ENDIAN. The header's `payload_crc32c` lets a loader
|
||||
//! detect corruption of the sidecar itself BEFORE trusting any contents, so a
|
||||
//! rotted sidecar can never be mistaken for shard corruption. This format is
|
||||
//! byte-identical to the Go implementation in
|
||||
//! `weed/storage/erasure_coding/ec_bitrot.go`.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
use prost::Message;
|
||||
|
||||
use crate::pb::volume_server_pb::{
|
||||
ChecksumAlgorithm, EcBitrotProtection, EcShardChecksums, EcShardConfig,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_shard::MAX_SHARD_COUNT;
|
||||
use crate::storage::needle::crc::CRC;
|
||||
|
||||
/// Canonical extension for the checksum sidecar. Generation 0 (legacy/fresh
|
||||
/// encode) uses `<base>.ecsum`; vacuum generation N uses `<base>.ecsum.v<N>`,
|
||||
/// mirroring the `.vif`/`.ecx` versioned convention.
|
||||
pub const BITROT_SIDECAR_EXT: &str = ".ecsum";
|
||||
|
||||
/// Default checksum granularity (16 MiB). It is a power-of-two multiple of
|
||||
/// `ERASURE_CODING_SMALL_BLOCK_SIZE` (1 MiB) and keeps the sidecar tiny
|
||||
/// (~11 KB for a 30 GB volume) while localizing corruption to a 16 MiB region.
|
||||
pub const DEFAULT_BITROT_BLOCK_SIZE: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// Caps the block granularity so a loaded sidecar cannot force a huge
|
||||
/// scrub/verify scratch buffer. Power-of-two multiple of 1 MiB.
|
||||
pub const MAX_BITROT_BLOCK_SIZE: u32 = 64 * 1024 * 1024;
|
||||
|
||||
/// Magic "ECSU".
|
||||
pub const BITROT_MAGIC: u32 = 0x4543_5355;
|
||||
/// On-disk format version.
|
||||
pub const BITROT_FORMAT_VERSION: u16 = 1;
|
||||
/// Header size: magic(4) + version(2) + payload_len(4) + payload_crc32c(4).
|
||||
pub const BITROT_HEADER_SIZE: usize = 14;
|
||||
|
||||
/// Resolved protection state of an EC volume's active generation after loading
|
||||
/// and validating its sidecar.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BitrotStatus {
|
||||
/// No sidecar, or a sidecar that does not describe the active generation.
|
||||
/// The generation is unprotected; this is NOT corruption.
|
||||
Off,
|
||||
/// A complete, well-formed, generation-matching sidecar is loaded.
|
||||
On,
|
||||
/// A generation-matching sidecar that is malformed, incomplete, or
|
||||
/// self-integrity-failed. The generation is unprotected pending repair of
|
||||
/// the sidecar, and an integrity alarm should fire. The rebuild path treats
|
||||
/// this as fail-closed.
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BitrotStatus {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let s = match self {
|
||||
BitrotStatus::On => "on",
|
||||
BitrotStatus::Invalid => "invalid",
|
||||
BitrotStatus::Off => "off",
|
||||
};
|
||||
f.write_str(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Error returned by [`load_bitrot_sidecar`]. A self-integrity failure is a
|
||||
/// sidecar-integrity problem (the caller maps it to [`BitrotStatus::Invalid`]),
|
||||
/// never a shard-corruption signal.
|
||||
#[derive(Debug)]
|
||||
pub enum BitrotLoadError {
|
||||
/// File missing or other underlying I/O error.
|
||||
Io(io::Error),
|
||||
/// File shorter than the fixed header.
|
||||
TooShort(usize),
|
||||
/// Header magic did not match.
|
||||
BadMagic(u32),
|
||||
/// Header format version is unsupported.
|
||||
UnsupportedVersion(u16),
|
||||
/// Header payload_len disagrees with the actual payload length.
|
||||
LengthMismatch { header: u32, actual: usize },
|
||||
/// Header payload_crc32c disagrees with the computed CRC32C of the payload.
|
||||
CrcMismatch { header: u32, computed: u32 },
|
||||
/// Protobuf payload failed to decode.
|
||||
Decode(prost::DecodeError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BitrotLoadError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
BitrotLoadError::Io(e) => write!(f, "bitrot sidecar io error: {}", e),
|
||||
BitrotLoadError::TooShort(n) => {
|
||||
write!(f, "bitrot sidecar too short ({} bytes)", n)
|
||||
}
|
||||
BitrotLoadError::BadMagic(m) => write!(f, "bitrot sidecar bad magic {:#x}", m),
|
||||
BitrotLoadError::UnsupportedVersion(v) => {
|
||||
write!(f, "bitrot sidecar unsupported format version {}", v)
|
||||
}
|
||||
BitrotLoadError::LengthMismatch { header, actual } => write!(
|
||||
f,
|
||||
"bitrot sidecar length mismatch: header {}, actual {}",
|
||||
header, actual
|
||||
),
|
||||
BitrotLoadError::CrcMismatch { header, computed } => write!(
|
||||
f,
|
||||
"bitrot sidecar self-integrity CRC mismatch: header {:#x}, computed {:#x}",
|
||||
header, computed
|
||||
),
|
||||
BitrotLoadError::Decode(e) => write!(f, "unmarshal bitrot sidecar: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for BitrotLoadError {}
|
||||
|
||||
impl From<io::Error> for BitrotLoadError {
|
||||
fn from(e: io::Error) -> Self {
|
||||
BitrotLoadError::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the sidecar path for a base file name and EC generation. Generation
|
||||
/// 0 is the un-suffixed legacy path; generation N>0 is the versioned path,
|
||||
/// consistent with how `.vif`/`.ecx` are versioned by the 2PC switch.
|
||||
pub fn bitrot_sidecar_path(base: &str, generation: u32) -> String {
|
||||
if generation == 0 {
|
||||
format!("{}{}", base, BITROT_SIDECAR_EXT)
|
||||
} else {
|
||||
format!("{}{}.v{}", base, BITROT_SIDECAR_EXT, generation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a fresh random per-encode identity used to detect a stale sidecar
|
||||
/// left behind by an in-place re-encode.
|
||||
pub fn new_encode_uuid() -> Vec<u8> {
|
||||
use rand::RngCore;
|
||||
let mut b = vec![0u8; 16];
|
||||
rand::thread_rng().fill_bytes(&mut b);
|
||||
b
|
||||
}
|
||||
|
||||
/// Reports whether `block_size` is a power of two in [1 MiB, MAX_BITROT_BLOCK_SIZE].
|
||||
pub fn is_pow2_multiple_of_1mib(block_size: u32) -> bool {
|
||||
block_size >= (1 << 20) && block_size <= MAX_BITROT_BLOCK_SIZE && block_size.count_ones() == 1
|
||||
}
|
||||
|
||||
/// Returns ceil(covered_size / block_size).
|
||||
fn expected_block_count(covered_size: i64, block_size: i64) -> usize {
|
||||
if block_size <= 0 {
|
||||
return 0;
|
||||
}
|
||||
((covered_size + block_size - 1) / block_size) as usize
|
||||
}
|
||||
|
||||
/// Packs a slice of u32 into little-endian bytes.
|
||||
fn pack_u32_le(vals: &[u32]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(vals.len() * 4);
|
||||
for v in vals {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Unpacks little-endian bytes into a Vec<u32>. Trailing bytes (len % 4) are
|
||||
/// ignored, matching the Go implementation's `len(b)/4` truncation.
|
||||
fn unpack_u32_le(b: &[u8]) -> Vec<u32> {
|
||||
let n = b.len() / 4;
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
out.push(u32::from_le_bytes([
|
||||
b[i * 4],
|
||||
b[i * 4 + 1],
|
||||
b[i * 4 + 2],
|
||||
b[i * 4 + 3],
|
||||
]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Accumulates the per-block CRC32C of a single shard's byte stream as it is
|
||||
/// written. Tolerates arbitrary chunk sizes that cross block boundaries, so it
|
||||
/// works for both small encode buffers and the larger rebuild buffers.
|
||||
pub struct ShardChecksumBuilder {
|
||||
block_size: i64,
|
||||
cur: CRC,
|
||||
cur_len: i64,
|
||||
total: i64,
|
||||
blocks: Vec<u32>,
|
||||
}
|
||||
|
||||
impl ShardChecksumBuilder {
|
||||
/// Creates a builder over a given block size in bytes.
|
||||
pub fn new(block_size: i64) -> Self {
|
||||
ShardChecksumBuilder {
|
||||
block_size,
|
||||
cur: CRC(0),
|
||||
cur_len: 0,
|
||||
total: 0,
|
||||
blocks: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds a chunk of arbitrary size, splitting it across block boundaries.
|
||||
pub fn write(&mut self, mut p: &[u8]) {
|
||||
while !p.is_empty() {
|
||||
let room = self.block_size - self.cur_len;
|
||||
let n = (p.len() as i64).min(room) as usize;
|
||||
self.cur = self.cur.update(&p[..n]);
|
||||
self.cur_len += n as i64;
|
||||
self.total += n as i64;
|
||||
p = &p[n..];
|
||||
if self.cur_len == self.block_size {
|
||||
self.blocks.push(self.cur.0);
|
||||
self.cur = CRC(0);
|
||||
self.cur_len = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Flushes any partial last block and returns the covered size and the
|
||||
/// packed little-endian u32 CRC array.
|
||||
pub fn finalize(mut self) -> (i64, Vec<u8>) {
|
||||
if self.cur_len > 0 {
|
||||
self.blocks.push(self.cur.0);
|
||||
self.cur = CRC(0);
|
||||
self.cur_len = 0;
|
||||
}
|
||||
(self.total, pack_u32_le(&self.blocks))
|
||||
}
|
||||
}
|
||||
|
||||
/// Atomically writes `prot` to `path`, wrapped in the on-disk header with a
|
||||
/// CRC32C over the serialized payload (temp file + rename).
|
||||
pub fn save_bitrot_sidecar(path: &str, prot: &EcBitrotProtection) -> io::Result<()> {
|
||||
// The header records payload_len as a uint32 and the buffer allocation below
|
||||
// adds it to a constant. Bound the payload well under any overflow (a real
|
||||
// manifest is a few KB) so neither the length field nor the buffer can wrap.
|
||||
// Check the encoded length BEFORE serializing so an oversized manifest never
|
||||
// allocates a huge buffer. Mirrors Go's SaveBitrotSidecar maxBitrotPayloadSize.
|
||||
const MAX_BITROT_PAYLOAD_SIZE: usize = 1 << 30; // 1 GiB, vastly above any real sidecar
|
||||
let payload_len = prot.encoded_len();
|
||||
if payload_len > MAX_BITROT_PAYLOAD_SIZE {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("bitrot sidecar payload too large: {} bytes", payload_len),
|
||||
));
|
||||
}
|
||||
let payload = prot.encode_to_vec();
|
||||
let mut buf = Vec::with_capacity(BITROT_HEADER_SIZE + payload.len());
|
||||
buf.extend_from_slice(&BITROT_MAGIC.to_be_bytes());
|
||||
buf.extend_from_slice(&BITROT_FORMAT_VERSION.to_be_bytes());
|
||||
buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
|
||||
buf.extend_from_slice(&CRC::new(&payload).0.to_be_bytes());
|
||||
buf.extend_from_slice(&payload);
|
||||
|
||||
let tmp = format!("{}.tmp", path);
|
||||
{
|
||||
let mut f = File::create(&tmp)?;
|
||||
f.write_all(&buf)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
if let Err(e) = std::fs::rename(&tmp, path) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads and self-integrity-checks a sidecar file. Returns the parsed message,
|
||||
/// or an error if the file is missing, truncated, has a bad magic/version, or
|
||||
/// fails the payload CRC. A self-integrity failure is a sidecar-integrity
|
||||
/// problem (caller maps it to [`BitrotStatus::Invalid`]), never a shard
|
||||
/// corruption signal.
|
||||
pub fn load_bitrot_sidecar(path: &str) -> Result<EcBitrotProtection, BitrotLoadError> {
|
||||
let mut data = Vec::new();
|
||||
File::open(path)?.read_to_end(&mut data)?;
|
||||
if data.len() < BITROT_HEADER_SIZE {
|
||||
return Err(BitrotLoadError::TooShort(data.len()));
|
||||
}
|
||||
let magic = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
|
||||
if magic != BITROT_MAGIC {
|
||||
return Err(BitrotLoadError::BadMagic(magic));
|
||||
}
|
||||
let ver = u16::from_be_bytes([data[4], data[5]]);
|
||||
if ver != BITROT_FORMAT_VERSION {
|
||||
return Err(BitrotLoadError::UnsupportedVersion(ver));
|
||||
}
|
||||
let payload_len = u32::from_be_bytes([data[6], data[7], data[8], data[9]]);
|
||||
let want_crc = u32::from_be_bytes([data[10], data[11], data[12], data[13]]);
|
||||
let payload = &data[BITROT_HEADER_SIZE..];
|
||||
if payload_len as usize != payload.len() {
|
||||
return Err(BitrotLoadError::LengthMismatch {
|
||||
header: payload_len,
|
||||
actual: payload.len(),
|
||||
});
|
||||
}
|
||||
let got = CRC::new(payload).0;
|
||||
if got != want_crc {
|
||||
return Err(BitrotLoadError::CrcMismatch {
|
||||
header: want_crc,
|
||||
computed: got,
|
||||
});
|
||||
}
|
||||
EcBitrotProtection::decode(payload).map_err(BitrotLoadError::Decode)
|
||||
}
|
||||
|
||||
/// Performs the disk-free manifest/syntax checks that every loader runs:
|
||||
/// supported algorithm, valid block size, exactly one entry per shard id in the
|
||||
/// active layout (no duplicates, no out-of-range ids), positive covered_size,
|
||||
/// and a packed-CRC count consistent with covered_size.
|
||||
///
|
||||
/// It does NOT compare covered_size against on-disk shard lengths — that is a
|
||||
/// per-node physical check done only for locally-held shards.
|
||||
pub fn validate_manifest(
|
||||
prot: &EcBitrotProtection,
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> Result<(), String> {
|
||||
if prot.algorithm != ChecksumAlgorithm::ChecksumCrc32c as i32 {
|
||||
return Err(format!("unsupported checksum algorithm {}", prot.algorithm));
|
||||
}
|
||||
if !is_pow2_multiple_of_1mib(prot.block_size) {
|
||||
return Err(format!(
|
||||
"invalid block_size {} (must be a power-of-two multiple of 1 MiB, at most {})",
|
||||
prot.block_size, MAX_BITROT_BLOCK_SIZE
|
||||
));
|
||||
}
|
||||
let bs = prot.block_size as i64;
|
||||
let total = data_shards + parity_shards;
|
||||
if total == 0 || total > MAX_SHARD_COUNT {
|
||||
return Err(format!(
|
||||
"invalid active layout: data={} parity={}",
|
||||
data_shards, parity_shards
|
||||
));
|
||||
}
|
||||
if prot.shards.len() != total {
|
||||
return Err(format!(
|
||||
"incomplete manifest: {} shard entries, expected {}",
|
||||
prot.shards.len(),
|
||||
total
|
||||
));
|
||||
}
|
||||
let mut seen = vec![false; MAX_SHARD_COUNT];
|
||||
for s in &prot.shards {
|
||||
if s.shard_id >= total as u32 {
|
||||
return Err(format!(
|
||||
"shard id {} out of range [0,{})",
|
||||
s.shard_id, total
|
||||
));
|
||||
}
|
||||
if seen[s.shard_id as usize] {
|
||||
return Err(format!("duplicate shard id {}", s.shard_id));
|
||||
}
|
||||
seen[s.shard_id as usize] = true;
|
||||
if s.covered_size <= 0 {
|
||||
return Err(format!(
|
||||
"shard {} has non-positive covered_size {}",
|
||||
s.shard_id, s.covered_size
|
||||
));
|
||||
}
|
||||
let want_count = expected_block_count(s.covered_size, bs);
|
||||
if s.block_crc32c.len() != want_count * 4 {
|
||||
return Err(format!(
|
||||
"shard {} crc count mismatch: {} bytes, expected {} (covered_size={} block_size={})",
|
||||
s.shard_id,
|
||||
s.block_crc32c.len(),
|
||||
want_count * 4,
|
||||
s.covered_size,
|
||||
prot.block_size
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolves the protection status of a loaded-or-missing sidecar against the
|
||||
/// active generation and layout. `loaded` is the result of attempting to load
|
||||
/// the sidecar at the active generation's path.
|
||||
///
|
||||
/// - missing sidecar (NotFound) => [`BitrotStatus::Off`]
|
||||
/// - load/self-integrity failure => [`BitrotStatus::Invalid`]
|
||||
/// - generation mismatch => [`BitrotStatus::Off`]
|
||||
/// - manifest validation failure => [`BitrotStatus::Invalid`]
|
||||
/// - otherwise => [`BitrotStatus::On`]
|
||||
pub fn resolve_status(
|
||||
loaded: &Result<EcBitrotProtection, BitrotLoadError>,
|
||||
active_generation: u32,
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> BitrotStatus {
|
||||
match loaded {
|
||||
Err(BitrotLoadError::Io(e)) if e.kind() == io::ErrorKind::NotFound => BitrotStatus::Off,
|
||||
Err(_) => BitrotStatus::Invalid,
|
||||
Ok(prot) => {
|
||||
if prot.generation != active_generation {
|
||||
return BitrotStatus::Off;
|
||||
}
|
||||
if validate_manifest(prot, data_shards, parity_shards).is_err() {
|
||||
return BitrotStatus::Invalid;
|
||||
}
|
||||
BitrotStatus::On
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the [`EcShardChecksums`] entry for a shard id, or `None`.
|
||||
pub fn shard_checksums(prot: &EcBitrotProtection, shard_id: u32) -> Option<&EcShardChecksums> {
|
||||
prot.shards.iter().find(|s| s.shard_id == shard_id)
|
||||
}
|
||||
|
||||
/// Reads a shard file at `path` in `block_size` chunks and compares each block's
|
||||
/// CRC32C against the manifest entry. Returns the list of mismatching block
|
||||
/// indices (empty == clean), or a fatal `io::Error` for genuine I/O problems.
|
||||
///
|
||||
/// A length mismatch (truncation or unexpected trailing bytes) is itself shard
|
||||
/// corruption: every block index is reported as mismatched so the caller treats
|
||||
/// the shard as bad. It does not interpret the result — the caller (scrub /
|
||||
/// rebuild) arbitrates shard-vs-sidecar via Reed-Solomon before acting.
|
||||
pub fn verify_shard_file_blocks(
|
||||
path: &str,
|
||||
entry: &EcShardChecksums,
|
||||
block_size: i64,
|
||||
) -> io::Result<Vec<usize>> {
|
||||
let f = File::open(path)?;
|
||||
let file_size = f.metadata()?.len() as i64;
|
||||
let want = unpack_u32_le(&entry.block_crc32c);
|
||||
|
||||
if file_size != entry.covered_size {
|
||||
// Length drift is shard corruption: report every block as mismatched.
|
||||
return Ok((0..want.len()).collect());
|
||||
}
|
||||
|
||||
let mut mismatched = Vec::new();
|
||||
let mut buf = vec![0u8; block_size.max(1) as usize];
|
||||
let mut offset: i64 = 0;
|
||||
for (i, want_crc) in want.iter().enumerate() {
|
||||
let to_read = (entry.covered_size - offset).min(block_size);
|
||||
if to_read <= 0 {
|
||||
break;
|
||||
}
|
||||
let to_read = to_read as usize;
|
||||
read_full_at(&f, &mut buf[..to_read], offset as u64)?;
|
||||
if CRC::new(&buf[..to_read]).0 != *want_crc {
|
||||
mismatched.push(i);
|
||||
}
|
||||
offset += to_read as i64;
|
||||
}
|
||||
Ok(mismatched)
|
||||
}
|
||||
|
||||
/// Reads exactly `buf.len()` bytes from `f` at `offset`, erroring on early EOF.
|
||||
fn read_full_at(f: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
|
||||
let mut total = 0usize;
|
||||
while total < buf.len() {
|
||||
#[cfg(unix)]
|
||||
let n = {
|
||||
use std::os::unix::fs::FileExt;
|
||||
f.read_at(&mut buf[total..], offset + total as u64)?
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let n = {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut fc = f.try_clone()?;
|
||||
fc.seek(SeekFrom::Start(offset + total as u64))?;
|
||||
fc.read(&mut buf[total..])?
|
||||
};
|
||||
if n == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"short read on shard block",
|
||||
));
|
||||
}
|
||||
total += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Builds the `EcShardConfig` proto for the given layout. The bitrot sidecar
|
||||
/// carries its own top-level encode_uuid, so the nested config leaves it empty.
|
||||
pub fn ec_shard_config(data_shards: u32, parity_shards: u32) -> EcShardConfig {
|
||||
EcShardConfig {
|
||||
data_shards,
|
||||
parity_shards,
|
||||
encode_ts_ns: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Cross-binary byte-exact proof: CANONICAL_HEX equals `canonicalInteropHex`
|
||||
/// in weed/storage/erasure_coding/ec_bitrot_interop_test.go (the Go reference
|
||||
/// asserts the same constant). Both binaries port the same format, so a
|
||||
/// sidecar written by either must be byte-identical; this pins the Rust side
|
||||
/// of that guarantee. If you change the format, regenerate and update BOTH.
|
||||
#[test]
|
||||
fn test_byte_exact_go_interop() {
|
||||
const CANONICAL_HEX: &str = "45435355000100000039cc1b826a080110808080082204080a10042a0a108080401a04040302012a0c0801108080401a04080706053210000102030405060708090a0b0c0d0e0f";
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(EcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
encode_ts_ns: 0,
|
||||
}),
|
||||
shards: vec![
|
||||
EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: 1024 * 1024,
|
||||
block_crc32c: pack_u32_le(&[0x0102_0304]),
|
||||
},
|
||||
EcShardChecksums {
|
||||
shard_id: 1,
|
||||
covered_size: 1024 * 1024,
|
||||
block_crc32c: pack_u32_le(&[0x0506_0708]),
|
||||
},
|
||||
],
|
||||
encode_uuid: (0..16u8).collect(),
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("ecsum_interop_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("v1.ecsum");
|
||||
let path = path.to_str().unwrap();
|
||||
save_bitrot_sidecar(path, &prot).unwrap();
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
|
||||
assert_eq!(hex, CANONICAL_HEX, "Rust .ecsum bytes drifted from the Go canonical form");
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sidecar_path_generations() {
|
||||
assert_eq!(bitrot_sidecar_path("/d/1", 0), "/d/1.ecsum");
|
||||
assert_eq!(bitrot_sidecar_path("/d/1", 3), "/d/1.ecsum.v3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_pow2_multiple_of_1mib() {
|
||||
assert!(is_pow2_multiple_of_1mib(1 << 20)); // 1 MiB
|
||||
assert!(is_pow2_multiple_of_1mib(16 * 1024 * 1024)); // 16 MiB default
|
||||
assert!(is_pow2_multiple_of_1mib(1 << 25));
|
||||
assert!(is_pow2_multiple_of_1mib(MAX_BITROT_BLOCK_SIZE)); // 64 MiB boundary
|
||||
assert!(!is_pow2_multiple_of_1mib(0));
|
||||
assert!(!is_pow2_multiple_of_1mib(1 << 19)); // 512 KiB, too small
|
||||
assert!(!is_pow2_multiple_of_1mib(3 << 20)); // 3 MiB, not pow2
|
||||
assert!(!is_pow2_multiple_of_1mib(128 * 1024 * 1024)); // pow2 but > MAX_BITROT_BLOCK_SIZE
|
||||
assert!(!is_pow2_multiple_of_1mib(DEFAULT_BITROT_BLOCK_SIZE as u32 + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expected_block_count() {
|
||||
assert_eq!(expected_block_count(0, 16), 0);
|
||||
assert_eq!(expected_block_count(1, 16), 1);
|
||||
assert_eq!(expected_block_count(16, 16), 1);
|
||||
assert_eq!(expected_block_count(17, 16), 2);
|
||||
assert_eq!(expected_block_count(32, 16), 2);
|
||||
assert_eq!(expected_block_count(100, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pack_unpack_roundtrip() {
|
||||
let vals = vec![0x0102_0304u32, 0xdead_beef, 0, u32::MAX];
|
||||
let packed = pack_u32_le(&vals);
|
||||
assert_eq!(packed.len(), 16);
|
||||
// Verify little-endian byte order of the first entry.
|
||||
assert_eq!(&packed[0..4], &[0x04, 0x03, 0x02, 0x01]);
|
||||
assert_eq!(unpack_u32_le(&packed), vals);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builder_block_boundaries() {
|
||||
// block_size = 4; feed 10 bytes in chunks that cross boundaries.
|
||||
let mut b = ShardChecksumBuilder::new(4);
|
||||
let data = b"0123456789";
|
||||
b.write(&data[0..3]); // partial block 0
|
||||
b.write(&data[3..7]); // completes block 0 (idx 3), fills block 1
|
||||
b.write(&data[7..10]); // partial block 2
|
||||
let (covered, packed) = b.finalize();
|
||||
assert_eq!(covered, 10);
|
||||
let crcs = unpack_u32_le(&packed);
|
||||
// ceil(10/4) = 3 blocks
|
||||
assert_eq!(crcs.len(), 3);
|
||||
// Compare against direct per-block CRCs.
|
||||
assert_eq!(crcs[0], CRC::new(&data[0..4]).0);
|
||||
assert_eq!(crcs[1], CRC::new(&data[4..8]).0);
|
||||
assert_eq!(crcs[2], CRC::new(&data[8..10]).0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builder_exact_block_multiple() {
|
||||
let mut b = ShardChecksumBuilder::new(4);
|
||||
b.write(b"01234567"); // exactly 2 blocks, no partial
|
||||
let (covered, packed) = b.finalize();
|
||||
assert_eq!(covered, 8);
|
||||
assert_eq!(unpack_u32_le(&packed).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_save_load_roundtrip() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp
|
||||
.path()
|
||||
.join("vol.ecsum")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
|
||||
let mut builder = ShardChecksumBuilder::new(DEFAULT_BITROT_BLOCK_SIZE as i64);
|
||||
builder.write(b"hello world");
|
||||
let (covered, packed) = builder.finalize();
|
||||
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_shard_config(10, 4)),
|
||||
shards: vec![EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: covered,
|
||||
block_crc32c: packed,
|
||||
}],
|
||||
encode_uuid: new_encode_uuid(),
|
||||
};
|
||||
|
||||
save_bitrot_sidecar(&path, &prot).unwrap();
|
||||
let loaded = load_bitrot_sidecar(&path).unwrap();
|
||||
assert_eq!(loaded, prot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_rejects_bad_magic() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp.path().join("bad.ecsum").to_str().unwrap().to_string();
|
||||
std::fs::write(&path, vec![0u8; BITROT_HEADER_SIZE + 4]).unwrap();
|
||||
match load_bitrot_sidecar(&path) {
|
||||
Err(BitrotLoadError::BadMagic(_)) => {}
|
||||
other => panic!("expected BadMagic, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_rejects_corrupted_payload() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp
|
||||
.path()
|
||||
.join("corrupt.ecsum")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_shard_config(10, 4)),
|
||||
shards: vec![EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: 5,
|
||||
block_crc32c: pack_u32_le(&[CRC::new(b"hello").0]),
|
||||
}],
|
||||
encode_uuid: vec![0u8; 16],
|
||||
};
|
||||
save_bitrot_sidecar(&path, &prot).unwrap();
|
||||
|
||||
// Flip a byte in the payload (after the 14-byte header).
|
||||
let mut data = std::fs::read(&path).unwrap();
|
||||
let last = data.len() - 1;
|
||||
data[last] ^= 0xff;
|
||||
std::fs::write(&path, &data).unwrap();
|
||||
|
||||
match load_bitrot_sidecar(&path) {
|
||||
Err(BitrotLoadError::CrcMismatch { .. }) => {}
|
||||
other => panic!("expected CrcMismatch, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_missing_is_notfound() {
|
||||
let res = load_bitrot_sidecar("/nonexistent/path/x.ecsum");
|
||||
match res {
|
||||
Err(BitrotLoadError::Io(e)) => assert_eq!(e.kind(), io::ErrorKind::NotFound),
|
||||
other => panic!("expected Io(NotFound), got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
fn good_manifest() -> EcBitrotProtection {
|
||||
let mut shards = Vec::new();
|
||||
for id in 0..14u32 {
|
||||
shards.push(EcShardChecksums {
|
||||
shard_id: id,
|
||||
covered_size: 5,
|
||||
block_crc32c: pack_u32_le(&[CRC::new(b"hello").0]),
|
||||
});
|
||||
}
|
||||
EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_shard_config(10, 4)),
|
||||
shards,
|
||||
encode_uuid: vec![0u8; 16],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_manifest_ok() {
|
||||
assert!(validate_manifest(&good_manifest(), 10, 4).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_wrong_algorithm() {
|
||||
let mut m = good_manifest();
|
||||
m.algorithm = ChecksumAlgorithm::ChecksumNone as i32;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_bad_block_size() {
|
||||
let mut m = good_manifest();
|
||||
m.block_size = 3 << 20;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_incomplete() {
|
||||
let mut m = good_manifest();
|
||||
m.shards.pop();
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_duplicate_shard_id() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[1].shard_id = 0;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_out_of_range_id() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[13].shard_id = 14;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_nonpositive_covered_size() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[0].covered_size = 0;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_crc_count_mismatch() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[0].block_crc32c = vec![0u8; 8]; // 2 entries but covered_size=5 => want 1
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_status() {
|
||||
// Missing => Off.
|
||||
let notfound: Result<EcBitrotProtection, BitrotLoadError> = Err(BitrotLoadError::Io(
|
||||
io::Error::new(io::ErrorKind::NotFound, "x"),
|
||||
));
|
||||
assert_eq!(resolve_status(¬found, 0, 10, 4), BitrotStatus::Off);
|
||||
|
||||
// Integrity failure => Invalid.
|
||||
let bad: Result<EcBitrotProtection, BitrotLoadError> =
|
||||
Err(BitrotLoadError::BadMagic(0));
|
||||
assert_eq!(resolve_status(&bad, 0, 10, 4), BitrotStatus::Invalid);
|
||||
|
||||
// Generation mismatch => Off.
|
||||
let mut m = good_manifest();
|
||||
m.generation = 7;
|
||||
let ok: Result<EcBitrotProtection, BitrotLoadError> = Ok(m);
|
||||
assert_eq!(resolve_status(&ok, 0, 10, 4), BitrotStatus::Off);
|
||||
|
||||
// Matching + valid => On.
|
||||
let ok2: Result<EcBitrotProtection, BitrotLoadError> = Ok(good_manifest());
|
||||
assert_eq!(resolve_status(&ok2, 0, 10, 4), BitrotStatus::On);
|
||||
|
||||
// Matching generation but invalid manifest => Invalid.
|
||||
let mut bad_m = good_manifest();
|
||||
bad_m.shards.pop();
|
||||
let ok3: Result<EcBitrotProtection, BitrotLoadError> = Ok(bad_m);
|
||||
assert_eq!(resolve_status(&ok3, 0, 10, 4), BitrotStatus::Invalid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_shard_file_blocks() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp.path().join("s.ec00").to_str().unwrap().to_string();
|
||||
let block_size: i64 = 4;
|
||||
let data = b"0123456789"; // 10 bytes, 3 blocks
|
||||
std::fs::write(&path, data).unwrap();
|
||||
|
||||
let mut b = ShardChecksumBuilder::new(block_size);
|
||||
b.write(data);
|
||||
let (covered, packed) = b.finalize();
|
||||
let entry = EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: covered,
|
||||
block_crc32c: packed,
|
||||
};
|
||||
|
||||
// Clean file => no mismatches.
|
||||
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
|
||||
assert!(mm.is_empty());
|
||||
|
||||
// Corrupt block index 1 (bytes 4..8).
|
||||
let mut corrupt = data.to_vec();
|
||||
corrupt[5] ^= 0xff;
|
||||
std::fs::write(&path, &corrupt).unwrap();
|
||||
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
|
||||
assert_eq!(mm, vec![1]);
|
||||
|
||||
// Truncation => all blocks mismatched.
|
||||
std::fs::write(&path, b"012").unwrap();
|
||||
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
|
||||
assert_eq!(mm, vec![0, 1, 2]);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,12 @@ use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
use reed_solomon_erasure::galois_8::ReedSolomon;
|
||||
|
||||
use crate::pb::volume_server_pb::{
|
||||
ChecksumAlgorithm, EcBitrotProtection, EcShardChecksums,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_bitrot::{
|
||||
self, ShardChecksumBuilder, DEFAULT_BITROT_BLOCK_SIZE,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_shard::*;
|
||||
use crate::storage::idx;
|
||||
use crate::storage::types::*;
|
||||
@@ -52,12 +58,21 @@ pub fn write_ec_files(
|
||||
shard.create()?;
|
||||
}
|
||||
|
||||
// Per-shard bitrot checksum builders: accumulate a CRC32C for every
|
||||
// DEFAULT_BITROT_BLOCK_SIZE block of each shard's byte stream as it is
|
||||
// written, so the resulting `.ecsum` sidecar can later detect silent
|
||||
// corruption in any shard (including cold parity).
|
||||
let mut builders: Vec<ShardChecksumBuilder> = (0..total_shards)
|
||||
.map(|_| ShardChecksumBuilder::new(DEFAULT_BITROT_BLOCK_SIZE as i64))
|
||||
.collect();
|
||||
|
||||
// Encode in large blocks, then small blocks
|
||||
encode_dat_file(
|
||||
&dat_file,
|
||||
dat_size,
|
||||
&rs,
|
||||
&mut shards,
|
||||
&mut builders,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)?;
|
||||
@@ -67,6 +82,42 @@ pub fn write_ec_files(
|
||||
shard.close();
|
||||
}
|
||||
|
||||
// Write the generation-0 bitrot sidecar (`<base>.ecsum`). Finalizing each
|
||||
// builder yields covered_size (== total bytes written to that shard) and
|
||||
// the packed little-endian CRC32C array.
|
||||
let mut shard_checksums: Vec<EcShardChecksums> = Vec::with_capacity(total_shards);
|
||||
for (i, builder) in builders.into_iter().enumerate() {
|
||||
let (covered_size, packed) = builder.finalize();
|
||||
shard_checksums.push(EcShardChecksums {
|
||||
shard_id: i as u32,
|
||||
covered_size,
|
||||
block_crc32c: packed,
|
||||
});
|
||||
}
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_bitrot::ec_shard_config(
|
||||
data_shards as u32,
|
||||
parity_shards as u32,
|
||||
)),
|
||||
shards: shard_checksums,
|
||||
encode_uuid: ec_bitrot::new_encode_uuid(),
|
||||
};
|
||||
let sidecar_path = ec_bitrot::bitrot_sidecar_path(&base, 0);
|
||||
if let Err(e) = ec_bitrot::save_bitrot_sidecar(&sidecar_path, &prot) {
|
||||
// A failed sidecar must not fail the encode — the shards are already
|
||||
// written and valid. The volume simply runs with bitrot protection
|
||||
// off for this generation until the sidecar is regenerated.
|
||||
tracing::warn!(
|
||||
volume_id = volume_id.0,
|
||||
path = %sidecar_path,
|
||||
error = %e,
|
||||
"ec encode: failed to write bitrot sidecar; protection off for this generation",
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -207,13 +258,12 @@ pub fn rebuild_ec_files(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify EC shards by computing parity against the existing data and identifying corrupted shards.
|
||||
///
|
||||
/// No longer wired to a scrub mode: FULL is now Go's per-needle local+remote walk
|
||||
/// (`store_ec::scrub_ec_volume_distributed`). Retained as a standalone Reed-Solomon
|
||||
/// parity check — the only parity/cold-region verification available until the
|
||||
/// `.ecsum` bitrot CHECKSUM path lands.
|
||||
#[allow(dead_code)]
|
||||
/// Reed-Solomon parity check over the locally-held shards: recompute parity from
|
||||
/// the data shards and flag any shard whose bytes disagree. Wired into FULL
|
||||
/// (scrub mode 2) as a TEMPORARY local parity/cold-region check — the per-needle
|
||||
/// FULL walk only reads live data-shard intervals, so on its own it can't catch
|
||||
/// bitrot in a parity shard or an unwalked region. Move to mode 4 (CHECKSUM) and
|
||||
/// drop it from mode 2 once the `.ecsum` subsystem lands.
|
||||
pub fn verify_ec_shards(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
@@ -537,6 +587,7 @@ fn encode_dat_file(
|
||||
dat_size: i64,
|
||||
rs: &ReedSolomon,
|
||||
shards: &mut [EcVolumeShard],
|
||||
builders: &mut [ShardChecksumBuilder],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> io::Result<()> {
|
||||
@@ -554,6 +605,7 @@ fn encode_dat_file(
|
||||
large_block_size,
|
||||
rs,
|
||||
shards,
|
||||
builders,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)?;
|
||||
@@ -573,6 +625,7 @@ fn encode_dat_file(
|
||||
small_block_size,
|
||||
rs,
|
||||
shards,
|
||||
builders,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)?;
|
||||
@@ -590,6 +643,7 @@ fn encode_one_batch(
|
||||
block_size: usize,
|
||||
rs: &ReedSolomon,
|
||||
shards: &mut [EcVolumeShard],
|
||||
builders: &mut [ShardChecksumBuilder],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> io::Result<()> {
|
||||
@@ -643,9 +697,11 @@ fn encode_one_batch(
|
||||
)
|
||||
})?;
|
||||
|
||||
// Write all shard buffers to files
|
||||
// Write all shard buffers to files and feed the same bytes to each
|
||||
// shard's bitrot checksum builder, keeping covered_size == on-disk length.
|
||||
for (i, buf) in buffers.iter().enumerate() {
|
||||
shards[i].write_all(buf)?;
|
||||
builders[i].write(buf);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -713,6 +769,84 @@ mod tests {
|
||||
assert!(std::path::Path::new(&ecx_path).exists());
|
||||
}
|
||||
|
||||
fn make_volume_with_needles(n: u64) -> TempDir {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=n {
|
||||
// Larger payloads so encoded shards span multiple bitrot blocks
|
||||
// would require huge data; small payloads are fine for correctness.
|
||||
let data = format!("test data for needle {} {}", i, "x".repeat(64));
|
||||
let mut needle = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut needle, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
tmp
|
||||
}
|
||||
|
||||
/// Encode-time capture writes a valid generation-0 `.ecsum` sidecar whose
|
||||
/// recorded checksums match the actual on-disk shards.
|
||||
#[test]
|
||||
fn test_encode_writes_valid_bitrot_sidecar() {
|
||||
use crate::storage::erasure_coding::ec_bitrot;
|
||||
|
||||
let tmp = make_volume_with_needles(5);
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
write_ec_files(dir, dir, "", VolumeId(1), 10, 4).unwrap();
|
||||
|
||||
let base = format!("{}/1", dir);
|
||||
let sidecar_path = ec_bitrot::bitrot_sidecar_path(&base, 0);
|
||||
assert!(
|
||||
std::path::Path::new(&sidecar_path).exists(),
|
||||
"generation-0 .ecsum sidecar should exist after encode"
|
||||
);
|
||||
|
||||
let prot = ec_bitrot::load_bitrot_sidecar(&sidecar_path).unwrap();
|
||||
ec_bitrot::validate_manifest(&prot, 10, 4).unwrap();
|
||||
assert_eq!(prot.generation, 0);
|
||||
assert_eq!(prot.shards.len(), 14);
|
||||
assert_eq!(prot.encode_uuid.len(), 16);
|
||||
assert_eq!(prot.block_size, ec_bitrot::DEFAULT_BITROT_BLOCK_SIZE as u32);
|
||||
|
||||
// Every shard's recorded covered_size must equal its on-disk length and
|
||||
// its block CRCs must verify clean.
|
||||
let bs = prot.block_size as i64;
|
||||
for entry in &prot.shards {
|
||||
let path = format!("{}.ec{:02}", base, entry.shard_id);
|
||||
let on_disk = std::fs::metadata(&path).unwrap().len() as i64;
|
||||
assert_eq!(
|
||||
entry.covered_size, on_disk,
|
||||
"covered_size must equal on-disk length for shard {}",
|
||||
entry.shard_id
|
||||
);
|
||||
let mm = ec_bitrot::verify_shard_file_blocks(&path, entry, bs).unwrap();
|
||||
assert!(
|
||||
mm.is_empty(),
|
||||
"shard {} should verify clean, got mismatches {:?}",
|
||||
entry.shard_id,
|
||||
mm
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// encode_sample_volume writes a small volume and EC-encodes it, returning
|
||||
// the dir path so a test can drop/truncate shards and rebuild.
|
||||
fn encode_sample_volume(tmp: &TempDir) -> String {
|
||||
|
||||
@@ -61,6 +61,13 @@ pub struct EcVolume {
|
||||
/// served from a shard of a different encode run is rejected (server- and
|
||||
/// client-side); 0 for a pre-feature volume, which is treated leniently.
|
||||
pub encode_ts_ns: i64,
|
||||
/// Active-generation EC bitrot checksum sidecar (`<base>.ecsum`), loaded and
|
||||
/// validated at mount. `None` unless `bitrot_status == On`.
|
||||
pub(crate) bitrot: Option<crate::pb::volume_server_pb::EcBitrotProtection>,
|
||||
/// Resolved protection state of the loaded sidecar. Cached alongside `bitrot`
|
||||
/// so `bitrot_protection()` can return the `Off`/`Invalid` distinction without
|
||||
/// re-reading, mirroring Go's `EcVolume.bitrotStatus`.
|
||||
pub(crate) bitrot_status: crate::storage::erasure_coding::ec_bitrot::BitrotStatus,
|
||||
}
|
||||
|
||||
/// Locate the `.vif` for a (collection, vid) by preferring the data dir
|
||||
@@ -191,6 +198,8 @@ impl EcVolume {
|
||||
shard_locations_refresh_time: std::sync::Mutex::new(None),
|
||||
expire_at_sec,
|
||||
encode_ts_ns,
|
||||
bitrot: None,
|
||||
bitrot_status: crate::storage::erasure_coding::ec_bitrot::BitrotStatus::Off,
|
||||
};
|
||||
|
||||
// Open .ecx file (sorted index) in read/write mode for in-place deletion marking.
|
||||
@@ -237,9 +246,189 @@ impl EcVolume {
|
||||
// Seed the in-memory deleted set from the journal.
|
||||
vol.load_deleted_needles_from_ecj()?;
|
||||
|
||||
// Load the generation-0 EC bitrot checksum sidecar (optional; best-effort).
|
||||
vol.load_active_bitrot_sidecar();
|
||||
|
||||
Ok(vol)
|
||||
}
|
||||
|
||||
/// Load the generation-0 checksum sidecar into `self.bitrot`/`self.bitrot_status`.
|
||||
/// OSS only produces generation-0 (fresh-encode) sidecars, mirroring Go's
|
||||
/// `loadActiveBitrotSidecar`.
|
||||
fn load_active_bitrot_sidecar(&mut self) {
|
||||
self.load_bitrot_for_generation(0);
|
||||
}
|
||||
|
||||
/// Load and validate the sidecar describing `generation`, setting
|
||||
/// `self.bitrot`/`self.bitrot_status`. Absent or generation/config-mismatched
|
||||
/// => `Off` (protection off, not corruption); self-integrity or manifest
|
||||
/// failure => `Invalid` with a warning (protection off pending repair); usable
|
||||
/// => `On`. Mirrors Go's `loadBitrotForGeneration`.
|
||||
fn load_bitrot_for_generation(&mut self, generation: u32) {
|
||||
use crate::storage::erasure_coding::ec_bitrot;
|
||||
let base = self.base_name();
|
||||
let path = ec_bitrot::bitrot_sidecar_path(&base, generation);
|
||||
let loaded = ec_bitrot::load_bitrot_sidecar(&path);
|
||||
let status = ec_bitrot::resolve_status(
|
||||
&loaded,
|
||||
generation,
|
||||
self.data_shards as usize,
|
||||
self.parity_shards as usize,
|
||||
);
|
||||
self.bitrot = None;
|
||||
self.bitrot_status = status;
|
||||
match status {
|
||||
ec_bitrot::BitrotStatus::On => self.bitrot = loaded.ok(),
|
||||
ec_bitrot::BitrotStatus::Off => {}
|
||||
ec_bitrot::BitrotStatus::Invalid => {
|
||||
tracing::warn!(
|
||||
volume_id = self.volume_id.0,
|
||||
path = %path,
|
||||
generation,
|
||||
"ec volume: bitrot sidecar present but invalid; protection off pending repair",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The active-generation bitrot protection AND its status (cached at mount),
|
||||
/// mirroring Go's `EcVolume.BitrotProtection()`. Preserves the distinction
|
||||
/// `checksum_scrub` needs: an absent/generation-mismatched sidecar is `Off`
|
||||
/// (a clean no-op), a present-but-malformed one is `Invalid` (a real integrity
|
||||
/// error). Returns `Some(prot)` only for `On`.
|
||||
pub(crate) fn bitrot_protection(
|
||||
&self,
|
||||
) -> (
|
||||
Option<crate::pb::volume_server_pb::EcBitrotProtection>,
|
||||
crate::storage::erasure_coding::ec_bitrot::BitrotStatus,
|
||||
) {
|
||||
(self.bitrot.clone(), self.bitrot_status)
|
||||
}
|
||||
|
||||
/// Read-only EC bitrot checksum scrub of the LOCAL shards of this volume's
|
||||
/// active generation.
|
||||
///
|
||||
/// Loads the active-generation `.ecsum` sidecar and, for each locally-held
|
||||
/// shard, reads the on-disk shard file in `block_size` chunks and compares
|
||||
/// each block's CRC32C against the sidecar. Returns
|
||||
/// `(blocks_scanned, mismatched_shards, errors)`.
|
||||
///
|
||||
/// If more than `parity_shards` shards mismatch wholesale (i.e. every block
|
||||
/// of those shards is wrong — the signature of a stale/wrong sidecar rather
|
||||
/// than localized disk rot), the result is classified as a suspect sidecar:
|
||||
/// `mismatched_shards` is cleared and an integrity note is added to `errors`
|
||||
/// instead. A genuine multi-shard disk failure of that magnitude is
|
||||
/// already unrecoverable, so treating it as a sidecar-integrity issue avoids
|
||||
/// raising false shard-corruption alarms.
|
||||
///
|
||||
/// This method NEVER deletes or mutates anything — it is purely diagnostic.
|
||||
pub fn checksum_scrub(&self) -> (u64, Vec<u32>, Vec<String>) {
|
||||
use crate::storage::erasure_coding::ec_bitrot;
|
||||
use crate::storage::erasure_coding::ec_bitrot::BitrotStatus;
|
||||
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
|
||||
// Resolve the active-generation protection AND its status, mirroring
|
||||
// Go's `ChecksumScrub` (`prot, status := ecv.BitrotProtection()`):
|
||||
// - BitrotOff => sidecars are OPTIONAL; an absent (or generation/
|
||||
// config-mismatched) sidecar simply means protection is not enabled
|
||||
// for this generation. Return a CLEAN, EMPTY result — NOT an error —
|
||||
// so legacy/intentionally-unprotected volumes are never reported
|
||||
// broken. (Go: `case BitrotOff: return 0, nil, nil`.)
|
||||
// - BitrotInvalid => the sidecar is PRESENT but malformed/unverifiable
|
||||
// (self-integrity or manifest failure). That is the only status that
|
||||
// yields an integrity error here.
|
||||
// - BitrotOn => scan local shards against it.
|
||||
let prot = match self.bitrot_protection() {
|
||||
(_, BitrotStatus::Off) => {
|
||||
// Unprotected generation: nothing to verify. Not an error.
|
||||
return (0, Vec::new(), Vec::new());
|
||||
}
|
||||
(_, BitrotStatus::Invalid) => {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!(
|
||||
"EC volume {} bitrot sidecar is malformed/unverifiable (sidecar integrity)",
|
||||
self.volume_id.0
|
||||
)],
|
||||
);
|
||||
}
|
||||
(Some(p), BitrotStatus::On) => p,
|
||||
(None, BitrotStatus::On) => {
|
||||
// Unreachable: BitrotOn always carries a loaded sidecar. Treat a
|
||||
// missing payload defensively as protection off (clean no-op).
|
||||
return (0, Vec::new(), Vec::new());
|
||||
}
|
||||
};
|
||||
|
||||
let block_size = prot.block_size as i64;
|
||||
let generation = prot.generation;
|
||||
let base = self.base_name();
|
||||
|
||||
let mut blocks_scanned: u64 = 0;
|
||||
let mut mismatched_shards: Vec<u32> = Vec::new();
|
||||
// Track shards whose blocks ALL mismatch (wholesale) to detect a
|
||||
// stale/wrong sidecar.
|
||||
let mut wholesale_mismatch = 0usize;
|
||||
|
||||
for (i, slot) in self.shards.iter().enumerate() {
|
||||
if slot.is_none() {
|
||||
continue; // not local
|
||||
}
|
||||
let shard_id = i as u32;
|
||||
let Some(entry) = ec_bitrot::shard_checksums(&prot, shard_id) else {
|
||||
errors.push(format!(
|
||||
"EC volume {} shard {} present but missing from sidecar manifest",
|
||||
self.volume_id.0, shard_id
|
||||
));
|
||||
continue;
|
||||
};
|
||||
|
||||
// Resolve the on-disk shard file path for the active generation,
|
||||
// mirroring EcVolumeShard::reopen_against_generation's convention.
|
||||
let path = if generation == 0 {
|
||||
format!("{}.ec{:02}", base, shard_id)
|
||||
} else {
|
||||
format!("{}.ec{:02}.v{}", base, shard_id, generation)
|
||||
};
|
||||
|
||||
let expected_blocks = entry.block_crc32c.len() / 4;
|
||||
match ec_bitrot::verify_shard_file_blocks(&path, entry, block_size) {
|
||||
Ok(mismatched) => {
|
||||
blocks_scanned += expected_blocks as u64;
|
||||
if !mismatched.is_empty() {
|
||||
mismatched_shards.push(shard_id);
|
||||
if expected_blocks > 0 && mismatched.len() == expected_blocks {
|
||||
wholesale_mismatch += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
errors.push(format!(
|
||||
"EC volume {} shard {} scrub read error: {}",
|
||||
self.volume_id.0, shard_id, e
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If more shards mismatch wholesale than parity can mask, the sidecar
|
||||
// itself is the likely culprit (stale generation / wrong volume), so
|
||||
// suppress the shard-corruption verdict and flag a sidecar-integrity
|
||||
// issue instead.
|
||||
if wholesale_mismatch > self.parity_shards as usize {
|
||||
errors.push(format!(
|
||||
"EC volume {}: {} shards mismatch wholesale (> {} parity); suspect stale/wrong sidecar, not shard corruption",
|
||||
self.volume_id.0, wholesale_mismatch, self.parity_shards
|
||||
));
|
||||
mismatched_shards.clear();
|
||||
}
|
||||
|
||||
mismatched_shards.sort_unstable();
|
||||
(blocks_scanned, mismatched_shards, errors)
|
||||
}
|
||||
|
||||
/// Walk the .ecj journal and populate `deleted_needles`. Called once
|
||||
/// from `new()` under exclusive ownership of the just-constructed
|
||||
/// EcVolume, so locking is not strictly required — but we take the
|
||||
@@ -464,10 +653,10 @@ impl EcVolume {
|
||||
/// against a half-populated cache and return NotFound for the
|
||||
/// not-yet-inserted shards.
|
||||
///
|
||||
/// Callers populating the whole cache atomically should use
|
||||
/// [`Self::replace_shard_locations`] instead — it swaps the
|
||||
/// entire map under the write lock and advances the refresh
|
||||
/// timestamp in one step.
|
||||
/// Callers writing back a whole `LookupEcVolume` reply should use
|
||||
/// [`Self::merge_shard_locations`] instead — it upserts the reply's
|
||||
/// shards under the write lock and advances the refresh timestamp in
|
||||
/// one step, retaining cached shards the reply omits.
|
||||
pub fn set_shard_locations(&self, shard_id: ShardId, locations: Vec<String>) {
|
||||
self.shard_locations
|
||||
.write()
|
||||
@@ -486,6 +675,29 @@ impl EcVolume {
|
||||
*self.shard_locations_refresh_time.lock().unwrap() = Some(std::time::Instant::now());
|
||||
}
|
||||
|
||||
/// Merge a fresh `LookupEcVolume` reply into the shard-locations cache and
|
||||
/// stamp the refresh time, returning a clone of the resulting map.
|
||||
///
|
||||
/// Per-shard upsert (mirrors Go's `cachedLookupEcShardLocations`): each shard
|
||||
/// id present in the reply overwrites its cached entry, while shard ids absent
|
||||
/// from the reply keep their previously-cached locations — so a reply that
|
||||
/// passes the data-shard completeness guard but omits a shard already in cache
|
||||
/// does not drop that shard's known location (unlike a full replace).
|
||||
pub fn merge_shard_locations(
|
||||
&self,
|
||||
locations: HashMap<ShardId, Vec<String>>,
|
||||
) -> HashMap<ShardId, Vec<String>> {
|
||||
let merged = {
|
||||
let mut guard = self.shard_locations.write().unwrap();
|
||||
for (shard_id, addrs) in locations {
|
||||
guard.insert(shard_id, addrs);
|
||||
}
|
||||
guard.clone()
|
||||
};
|
||||
*self.shard_locations_refresh_time.lock().unwrap() = Some(std::time::Instant::now());
|
||||
merged
|
||||
}
|
||||
|
||||
/// Get a cloned list of server addresses for a given shard ID.
|
||||
pub fn get_shard_locations(&self, shard_id: ShardId) -> Vec<String> {
|
||||
self.shard_locations
|
||||
@@ -1251,6 +1463,118 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// Mounting an EC volume loads and validates its generation-0 `.ecsum`
|
||||
/// sidecar, so `bitrot_protection()` reports `On` with the parsed manifest.
|
||||
#[test]
|
||||
fn test_mount_loads_bitrot_sidecar() {
|
||||
use crate::storage::erasure_coding::ec_bitrot::BitrotStatus;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::volume::Volume;
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=5 {
|
||||
let data = format!("test data for needle {}", 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()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
crate::storage::erasure_coding::ec_encoder::write_ec_files(dir, dir, "", VolumeId(1), 10, 4)
|
||||
.unwrap();
|
||||
|
||||
let vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
assert!(
|
||||
vol.bitrot.is_some(),
|
||||
"mount should load the generation-0 .ecsum sidecar"
|
||||
);
|
||||
let (prot, status) = vol.bitrot_protection();
|
||||
assert_eq!(status, BitrotStatus::On);
|
||||
assert_eq!(prot.unwrap().shards.len(), 14);
|
||||
}
|
||||
|
||||
/// CHECKSUM scrub verifies clean shards against the sidecar and flags a shard
|
||||
/// whose bytes are corrupted after encode.
|
||||
#[test]
|
||||
fn test_checksum_scrub_clean_and_detects_corruption() {
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::volume::Volume;
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=8 {
|
||||
let data = format!("test data for needle {} with a bit more length", 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()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
crate::storage::erasure_coding::ec_encoder::write_ec_files(dir, dir, "", VolumeId(1), 10, 4)
|
||||
.unwrap();
|
||||
|
||||
let mut vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
for id in 0..14u8 {
|
||||
vol.add_shard(EcVolumeShard::new(dir, "", VolumeId(1), id))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Clean scrub: no mismatches, no errors, blocks scanned > 0.
|
||||
let (scanned, broken, errs) = vol.checksum_scrub();
|
||||
assert!(errs.is_empty(), "unexpected scrub errors: {:?}", errs);
|
||||
assert!(broken.is_empty(), "unexpected mismatches: {:?}", broken);
|
||||
assert!(scanned > 0, "scrub should scan at least one block");
|
||||
|
||||
// Corrupt one byte of shard 3 on disk; re-scrub must report shard 3.
|
||||
let shard3 = format!("{}/1.ec03", dir);
|
||||
let mut bytes = std::fs::read(&shard3).unwrap();
|
||||
assert!(!bytes.is_empty());
|
||||
bytes[0] ^= 0xFF;
|
||||
std::fs::write(&shard3, &bytes).unwrap();
|
||||
|
||||
let (_, broken2, _) = vol.checksum_scrub();
|
||||
assert!(
|
||||
broken2.contains(&3),
|
||||
"corrupted shard 3 should be flagged, got {:?}",
|
||||
broken2
|
||||
);
|
||||
}
|
||||
|
||||
fn write_ecx_file(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Encodes a volume's .dat file into 10 data + 4 parity shards using
|
||||
//! Reed-Solomon erasure coding. Can reconstruct from any 10 of 14 shards.
|
||||
|
||||
pub mod ec_bitrot;
|
||||
pub mod ec_decoder;
|
||||
pub mod ec_encoder;
|
||||
pub mod ec_locate;
|
||||
|
||||
@@ -834,3 +834,103 @@ async fn replicate_write_does_not_re_replicate() {
|
||||
"plain write to a multi-copy volume must attempt replication"
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Chunk-manifest expansion resolves chunks on EC volumes
|
||||
//
|
||||
// A chunked object whose data chunks live on an EC-encoded volume must expand
|
||||
// by reconstruct-on-read from the shards, not by a local regular-volume lookup
|
||||
// (which finds nothing once the volume is EC-encoded). Mirrors Go's
|
||||
// ChunkedFileReader, which resolves every chunk through the master.
|
||||
// ============================================================================
|
||||
|
||||
#[tokio::test]
|
||||
async fn chunk_manifest_expands_chunk_stored_on_ec_volume() {
|
||||
use seaweed_volume::storage::erasure_coding::ec_encoder::write_ec_files;
|
||||
use seaweed_volume::storage::needle::needle::{FileId, Needle};
|
||||
use seaweed_volume::storage::types::{Cookie, NeedleId};
|
||||
use seaweed_volume::storage::volume::Volume;
|
||||
|
||||
let (state, tmp) = test_state();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
// A chunk large enough to be worth EC-encoding; its bytes are the payload we
|
||||
// expect the manifest GET to return.
|
||||
let chunk_data: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
|
||||
let chunk_nid = NeedleId(0x2a);
|
||||
let chunk_cookie = Cookie(0x1234abcd);
|
||||
|
||||
// Build regular volume 2 holding the chunk, then EC-encode it and mount all
|
||||
// 14 shards locally so reconstruct-on-read is a pure local read.
|
||||
{
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(2),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut n = Needle {
|
||||
id: chunk_nid,
|
||||
cookie: chunk_cookie,
|
||||
data: chunk_data.clone(),
|
||||
data_size: chunk_data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
}
|
||||
write_ec_files(dir, dir, "", VolumeId(2), 10, 4).unwrap();
|
||||
// Volume 2 was built standalone (never registered in the store), so it only
|
||||
// exists as EC shards — the chunk resolves through the EC path, as it would
|
||||
// after ec.encode retired the regular volume.
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
let shard_ids: Vec<u32> = (0..14).collect();
|
||||
store.mount_ec_shards(VolumeId(2), "", &shard_ids).unwrap();
|
||||
}
|
||||
|
||||
// Write the chunk-manifest needle to regular volume 1.
|
||||
let chunk_fid = FileId::new(VolumeId(2), chunk_nid, chunk_cookie).to_string();
|
||||
let manifest = format!(
|
||||
r#"{{"name":"big.bin","mime":"application/octet-stream","size":{},"chunks":[{{"fid":"{}","offset":0,"size":{}}}]}}"#,
|
||||
chunk_data.len(),
|
||||
chunk_fid,
|
||||
chunk_data.len()
|
||||
);
|
||||
let manifest_nid = NeedleId(0x7);
|
||||
let manifest_cookie = Cookie(0x55667788);
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
let mut n = Needle {
|
||||
id: manifest_nid,
|
||||
cookie: manifest_cookie,
|
||||
data: manifest.into_bytes(),
|
||||
..Needle::default()
|
||||
};
|
||||
n.data_size = n.data.len() as u32;
|
||||
n.set_is_chunk_manifest();
|
||||
store.write_volume_needle(VolumeId(1), &mut n).unwrap();
|
||||
}
|
||||
|
||||
// GET the manifest object; expect the reconstructed chunk bytes.
|
||||
let manifest_fid = FileId::new(VolumeId(1), manifest_nid, manifest_cookie).to_string();
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(format!("/{}", manifest_fid))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(body_bytes(response).await, chunk_data);
|
||||
}
|
||||
@@ -333,11 +333,19 @@ func (f *FuseTestFramework) waitForService(addr string, timeout time.Duration) e
|
||||
return fmt.Errorf("service at %s not ready within timeout", addr)
|
||||
}
|
||||
|
||||
// waitForMount waits for the FUSE mount to be ready
|
||||
// waitForMount waits for the FUSE mount to be ready. A stat/ReadDir probe
|
||||
// alone is not enough: the bare mount point directory passes both before the
|
||||
// mount process finishes starting, letting tests race ahead and write to the
|
||||
// local disk underneath the mount. The mount point's device ID differing from
|
||||
// its parent's confirms a filesystem is actually mounted there.
|
||||
func (f *FuseTestFramework) waitForMount(timeout time.Duration) error {
|
||||
parentDev, err := deviceID(filepath.Dir(f.mountPoint))
|
||||
if err != nil {
|
||||
return fmt.Errorf("stat mount point parent: %v", err)
|
||||
}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, err := os.Stat(f.mountPoint); err == nil {
|
||||
if dev, err := deviceID(f.mountPoint); err == nil && dev != parentDev {
|
||||
if _, err := os.ReadDir(f.mountPoint); err == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -347,6 +355,15 @@ func (f *FuseTestFramework) waitForMount(timeout time.Duration) error {
|
||||
return fmt.Errorf("mount point not ready within timeout")
|
||||
}
|
||||
|
||||
// deviceID returns the device ID of the filesystem containing path.
|
||||
func deviceID(path string) (uint64, error) {
|
||||
var st syscall.Stat_t
|
||||
if err := syscall.Stat(path, &st); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uint64(st.Dev), nil
|
||||
}
|
||||
|
||||
// findWeedBinary locates the weed binary.
|
||||
func findWeedBinary() string {
|
||||
if p, err := exec.LookPath("weed"); err == nil {
|
||||
|
||||
@@ -88,13 +88,9 @@ func writeBufferCapConfig(debugPort int) *TestConfig {
|
||||
"-writeBufferSizeMB=16",
|
||||
"-debug=true",
|
||||
fmt.Sprintf("-debug.port=%d", debugPort),
|
||||
// Route glog to stderr so the framework's process log
|
||||
// capture actually contains something — by default weed
|
||||
// sends glog to /tmp/weed.* files which the CI artifact
|
||||
// upload step never sees. Critical for diagnosing
|
||||
// upload/saveToStorage errors on Linux runs.
|
||||
"-logtostderr=true",
|
||||
"-v=2",
|
||||
// NOTE: glog flags (-logtostderr, -v) are globals parsed
|
||||
// before the subcommand; passing them here makes weed
|
||||
// mount exit with a usage error before ever mounting.
|
||||
},
|
||||
SkipCleanup: false,
|
||||
}
|
||||
|
||||
@@ -311,9 +311,7 @@ func (s *AdminServer) getFilerNodesStatus() []FilerNode {
|
||||
|
||||
// Get filer nodes from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -352,9 +350,7 @@ func (s *AdminServer) getMessageBrokerNodesStatus() []MessageBrokerNode {
|
||||
|
||||
// Get message broker nodes from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -393,9 +389,7 @@ func (s *AdminServer) getS3NodesStatus() []S3Node {
|
||||
|
||||
// Get S3 nodes from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.S3Type,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -85,6 +85,7 @@ type AdminServer struct {
|
||||
masterClient *wdclient.MasterClient
|
||||
templateFS http.FileSystem
|
||||
dataDir string
|
||||
filerGroup string
|
||||
grpcDialOption grpc.DialOption
|
||||
cacheExpiration time.Duration
|
||||
lastCacheUpdate time.Time
|
||||
@@ -134,13 +135,13 @@ type AdminServer struct {
|
||||
|
||||
// Type definitions moved to types.go
|
||||
|
||||
func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string, icebergPort int) *AdminServer {
|
||||
func NewAdminServer(masters string, filerGroup string, templateFS http.FileSystem, dataDir string, icebergPort int) *AdminServer {
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.admin")
|
||||
|
||||
// Create master client with multiple master support
|
||||
masterClient := wdclient.NewMasterClient(
|
||||
grpcDialOption,
|
||||
"", // filerGroup - not needed for admin
|
||||
filerGroup,
|
||||
"admin", // clientType
|
||||
"", // clientHost - not needed for admin
|
||||
"", // dataCenter - not needed for admin
|
||||
@@ -162,6 +163,7 @@ func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string,
|
||||
masterClient: masterClient,
|
||||
templateFS: templateFS,
|
||||
dataDir: dataDir,
|
||||
filerGroup: filerGroup,
|
||||
grpcDialOption: grpcDialOption,
|
||||
cacheExpiration: defaultCacheTimeout,
|
||||
filerCacheExpiration: defaultFilerCacheTimeout,
|
||||
@@ -293,6 +295,13 @@ func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string,
|
||||
return server
|
||||
}
|
||||
|
||||
func (s *AdminServer) listClusterNodesRequest(clientType string) *master_pb.ListClusterNodesRequest {
|
||||
return &master_pb.ListClusterNodesRequest{
|
||||
ClientType: clientType,
|
||||
FilerGroup: s.filerGroup,
|
||||
}
|
||||
}
|
||||
|
||||
// vacuumToggler abstracts the master's vacuum enable/disable for testing.
|
||||
type vacuumToggler interface {
|
||||
disableVacuum() error
|
||||
@@ -1112,9 +1121,7 @@ func (s *AdminServer) GetClusterFilers() (*ClusterFilersData, error) {
|
||||
|
||||
// Get filer information from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1159,9 +1166,7 @@ func (s *AdminServer) GetClusterBrokers() (*ClusterBrokersData, error) {
|
||||
|
||||
// Get broker information from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1206,9 +1211,7 @@ func (s *AdminServer) GetClusterS3Servers() (*ClusterS3ServersData, error) {
|
||||
|
||||
// Get S3 server information from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.S3Type,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1642,9 +1645,7 @@ func (s *AdminServer) UpdateTopicRetention(namespace, name string, enabled bool,
|
||||
// Get broker information from master
|
||||
var brokerAddress string
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
)
|
||||
|
||||
func TestListClusterNodesRequestIncludesFilerGroup(t *testing.T) {
|
||||
server := &AdminServer{filerGroup: "tenant-a"}
|
||||
|
||||
req := server.listClusterNodesRequest(cluster.FilerType)
|
||||
|
||||
if req.ClientType != cluster.FilerType {
|
||||
t.Fatalf("ClientType = %q, want %q", req.ClientType, cluster.FilerType)
|
||||
}
|
||||
if req.FilerGroup != "tenant-a" {
|
||||
t.Fatalf("FilerGroup = %q, want %q", req.FilerGroup, "tenant-a")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListClusterNodesRequestKeepsDefaultFilerGroupEmpty(t *testing.T) {
|
||||
server := &AdminServer{}
|
||||
|
||||
req := server.listClusterNodesRequest(cluster.FilerType)
|
||||
|
||||
if req.FilerGroup != "" {
|
||||
t.Fatalf("FilerGroup = %q, want empty", req.FilerGroup)
|
||||
}
|
||||
}
|
||||
@@ -76,9 +76,7 @@ func (s *AdminServer) getDiscoveredFilers() []string {
|
||||
// Discover filers from masters
|
||||
var filers []string
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -150,10 +150,19 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
var totalMaxVolumes int64
|
||||
var totalSize int64
|
||||
var totalFiles int64
|
||||
// Prefer the real physical disk capacity the volume server
|
||||
// reports per disk; the slot-based estimate overstates capacity
|
||||
// when maxVolumeCount is configured higher than the disk holds.
|
||||
var diskCapacity int64
|
||||
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
totalVolumes += diskInfo.VolumeCount
|
||||
totalMaxVolumes += diskInfo.MaxVolumeCount
|
||||
if diskInfo.DiskTotalBytes > 0 {
|
||||
diskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
} else {
|
||||
diskCapacity += diskInfo.MaxVolumeCount * int64(resp.VolumeSizeLimitMb) * 1024 * 1024
|
||||
}
|
||||
|
||||
// Sum up individual volume information
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
@@ -198,7 +207,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
Volumes: int(totalVolumes),
|
||||
MaxVolumes: int(totalMaxVolumes),
|
||||
DiskUsage: totalSize,
|
||||
DiskCapacity: totalMaxVolumes * int64(resp.VolumeSizeLimitMb) * 1024 * 1024,
|
||||
DiskCapacity: diskCapacity,
|
||||
LastHeartbeat: time.Now(),
|
||||
}
|
||||
|
||||
|
||||
@@ -494,9 +494,7 @@ func (s *AdminServer) findBrokerLeader() (string, error) {
|
||||
// First, try to find any broker from the cluster
|
||||
var brokers []string
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -524,7 +522,7 @@ func (s *AdminServer) findBrokerLeader() (string, error) {
|
||||
|
||||
// Try to find broker leader
|
||||
_, err := client.FindBrokerLeader(ctx, &mq_pb.FindBrokerLeaderRequest{
|
||||
FilerGroup: "",
|
||||
FilerGroup: s.filerGroup,
|
||||
})
|
||||
if err == nil {
|
||||
return nil // This broker is the leader
|
||||
|
||||
@@ -805,9 +805,7 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
|
||||
|
||||
s3Seen := map[string]struct{}{}
|
||||
if err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.S3Type,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -471,7 +471,14 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
|
||||
// Process disk information
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
vs.MaxVolumes += int(diskInfo.MaxVolumeCount)
|
||||
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024 // Use actual volume size limit
|
||||
// Prefer the real physical disk capacity the volume server
|
||||
// reports; the slot-based estimate overstates capacity when
|
||||
// maxVolumeCount is configured higher than the disk holds.
|
||||
if diskInfo.DiskTotalBytes > 0 {
|
||||
vs.DiskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
} else {
|
||||
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024
|
||||
}
|
||||
|
||||
// Count regular volumes and calculate disk usage
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
|
||||
@@ -154,11 +154,11 @@ func (s *WorkerGrpcServer) Stop() error {
|
||||
s.running = false
|
||||
close(s.stopChan)
|
||||
|
||||
// Close all worker connections
|
||||
// Close all worker connections. Cancelling the context stops each
|
||||
// handleOutgoingMessages goroutine; the outgoing channel is never closed.
|
||||
s.connMutex.Lock()
|
||||
for _, conn := range s.connections {
|
||||
conn.cancel()
|
||||
s.safeCloseOutgoingChannel(conn, "Stop")
|
||||
}
|
||||
s.connections = make(map[string]*WorkerConnection)
|
||||
s.connMutex.Unlock()
|
||||
@@ -227,10 +227,9 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
s.connMutex.Lock()
|
||||
if oldConn, exists := s.connections[workerID]; exists {
|
||||
glog.Infof("Worker %s reconnected, cleaning up old connection", workerID)
|
||||
// Cancel old connection to stop its goroutines
|
||||
// Cancel old connection to stop its goroutines. Its handleOutgoingMessages
|
||||
// exits on the cancelled context; the outgoing channel is never closed.
|
||||
oldConn.cancel()
|
||||
// Don't close oldConn.outgoing here as it may cause panic in handleOutgoingMessages
|
||||
// Let the goroutine exit naturally when it detects context cancellation
|
||||
}
|
||||
s.connections[workerID] = conn
|
||||
s.connMutex.Unlock()
|
||||
@@ -255,11 +254,8 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- regResponse:
|
||||
if s.sendToWorker(conn, regResponse, 5*time.Second, "registration response") {
|
||||
glog.V(1).Infof("Registration response sent to worker %s", workerID)
|
||||
case <-time.After(5 * time.Second):
|
||||
glog.Errorf("Failed to send registration response to worker %s", workerID)
|
||||
}
|
||||
|
||||
// Handle incoming messages
|
||||
@@ -384,11 +380,7 @@ func (s *WorkerGrpcServer) handleHeartbeat(conn *WorkerConnection, heartbeat *wo
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- response:
|
||||
case <-time.After(time.Second):
|
||||
glog.Warningf("Failed to send heartbeat response to worker %s", conn.workerID)
|
||||
}
|
||||
s.sendToWorker(conn, response, time.Second, "heartbeat response")
|
||||
}
|
||||
|
||||
// handleTaskRequest processes task requests from workers
|
||||
@@ -435,11 +427,7 @@ func (s *WorkerGrpcServer) handleTaskRequest(conn *WorkerConnection, request *wo
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- assignment:
|
||||
case <-time.After(time.Second):
|
||||
glog.Warningf("Failed to send task assignment to worker %s", conn.workerID)
|
||||
}
|
||||
s.sendToWorker(conn, assignment, time.Second, "task assignment")
|
||||
} else {
|
||||
// Send explicit "No Task" response to prevent worker timeout
|
||||
// Workers expect a TaskAssignment message but will sleep if TaskId is empty
|
||||
@@ -452,11 +440,8 @@ func (s *WorkerGrpcServer) handleTaskRequest(conn *WorkerConnection, request *wo
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- noTaskAssignment:
|
||||
if s.sendToWorker(conn, noTaskAssignment, time.Second, "no-task response") {
|
||||
glog.V(4).Infof("Sent 'No Task' response to worker %s", conn.workerID)
|
||||
case <-time.After(time.Second):
|
||||
// If we can't send, the worker will eventually time out and reconnect, which is fine
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -596,14 +581,22 @@ func (s *WorkerGrpcServer) handleTaskLogResponse(conn *WorkerConnection, respons
|
||||
s.logRequestsMutex.Unlock()
|
||||
}
|
||||
|
||||
// safeCloseOutgoingChannel safely closes the outgoing channel for a worker connection.
|
||||
func (s *WorkerGrpcServer) safeCloseOutgoingChannel(conn *WorkerConnection, source string) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
glog.V(1).Infof("%s: recovered from panic closing outgoing channel for worker %s: %v", source, conn.workerID, r)
|
||||
}
|
||||
}()
|
||||
close(conn.outgoing)
|
||||
// sendToWorker queues a message on conn.outgoing, which is deliberately never
|
||||
// closed: it has multiple concurrent senders, so closing it could panic one of
|
||||
// them with "send on closed channel". Teardown is signaled via conn.ctx instead;
|
||||
// handleOutgoingMessages drains the channel until that context is cancelled.
|
||||
// Returns false if the connection closed or the send timed out.
|
||||
func (s *WorkerGrpcServer) sendToWorker(conn *WorkerConnection, msg *worker_pb.AdminMessage, timeout time.Duration, description string) bool {
|
||||
select {
|
||||
case conn.outgoing <- msg:
|
||||
return true
|
||||
case <-conn.ctx.Done():
|
||||
glog.V(2).Infof("Dropped %s for worker %s: connection closed", description, conn.workerID)
|
||||
return false
|
||||
case <-time.After(timeout):
|
||||
glog.Warningf("Failed to send %s to worker %s: timeout", description, conn.workerID)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// unregisterWorker removes a worker connection
|
||||
@@ -628,12 +621,11 @@ func (s *WorkerGrpcServer) unregisterWorker(conn *WorkerConnection, event string
|
||||
s.connMutex.Unlock()
|
||||
stats_collect.AdminWorkerEventsTotal.WithLabelValues(event).Inc()
|
||||
|
||||
// Cancel context to signal goroutines to stop
|
||||
// Cancel context to signal goroutines to stop. The outgoing channel is
|
||||
// never closed (it has multiple senders); handleOutgoingMessages exits on
|
||||
// the cancelled context.
|
||||
conn.cancel()
|
||||
|
||||
// Safely close the outgoing channel with recover to handle potential double-close
|
||||
s.safeCloseOutgoingChannel(conn, "unregisterWorker")
|
||||
|
||||
glog.V(1).Infof("Unregistered worker %s", conn.workerID)
|
||||
}
|
||||
|
||||
@@ -732,6 +724,13 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries i
|
||||
select {
|
||||
case conn.outgoing <- logRequest:
|
||||
glog.V(1).Infof("Log request sent to worker %s for task %s", workerID, taskID)
|
||||
case <-conn.ctx.Done():
|
||||
s.logRequestsMutex.Lock()
|
||||
if s.pendingLogRequests[requestKey] == requestContext {
|
||||
delete(s.pendingLogRequests, requestKey)
|
||||
}
|
||||
s.logRequestsMutex.Unlock()
|
||||
return nil, fmt.Errorf("worker %s connection closed", workerID)
|
||||
case <-time.After(logSendTimeout):
|
||||
// Clean up pending request on timeout
|
||||
s.logRequestsMutex.Lock()
|
||||
@@ -750,6 +749,13 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries i
|
||||
}
|
||||
glog.V(1).Infof("Received %d log entries for task %s from worker %s", len(response.LogEntries), taskID, workerID)
|
||||
return response.LogEntries, nil
|
||||
case <-conn.ctx.Done():
|
||||
s.logRequestsMutex.Lock()
|
||||
if s.pendingLogRequests[requestKey] == requestContext {
|
||||
delete(s.pendingLogRequests, requestKey)
|
||||
}
|
||||
s.logRequestsMutex.Unlock()
|
||||
return nil, fmt.Errorf("worker %s connection closed", workerID)
|
||||
case <-time.After(logResponseTimeout):
|
||||
// Clean up pending request on timeout
|
||||
s.logRequestsMutex.Lock()
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
)
|
||||
|
||||
func newTestWorkerConn(bufferSize int) *WorkerConnection {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &WorkerConnection{
|
||||
workerID: "w-test",
|
||||
outgoing: make(chan *worker_pb.AdminMessage, bufferSize),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendToWorkerDropsOnCancelledContext verifies a send bails out via the
|
||||
// connection context instead of blocking for the full timeout once the
|
||||
// connection is torn down and its buffer is full.
|
||||
func TestSendToWorkerDropsOnCancelledContext(t *testing.T) {
|
||||
s := &WorkerGrpcServer{adminServer: &AdminServer{}}
|
||||
conn := newTestWorkerConn(1)
|
||||
|
||||
// Fill the buffer so the next send cannot enqueue.
|
||||
conn.outgoing <- &worker_pb.AdminMessage{}
|
||||
conn.cancel()
|
||||
|
||||
start := time.Now()
|
||||
if s.sendToWorker(conn, &worker_pb.AdminMessage{}, 5*time.Second, "heartbeat response") {
|
||||
t.Fatal("expected send to be dropped when context cancelled and buffer full")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("send blocked for %v; expected an immediate context-cancelled bail", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHeartbeatDuringUnregisterDoesNotPanic is a regression test for the
|
||||
// "panic: send on closed channel" crash: unregisterWorker (called from the
|
||||
// stale-connection cleanup routine) used to close conn.outgoing while the
|
||||
// WorkerStream goroutine was still sending heartbeat responses to it.
|
||||
func TestHeartbeatDuringUnregisterDoesNotPanic(t *testing.T) {
|
||||
s := &WorkerGrpcServer{
|
||||
adminServer: &AdminServer{},
|
||||
connections: make(map[string]*WorkerConnection),
|
||||
}
|
||||
conn := newTestWorkerConn(100)
|
||||
s.connections[conn.workerID] = conn
|
||||
|
||||
// Drain outgoing like handleOutgoingMessages would, until teardown.
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-conn.ctx.Done():
|
||||
return
|
||||
case <-conn.outgoing:
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
s.handleHeartbeat(conn, &worker_pb.WorkerHeartbeat{})
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.unregisterWorker(conn, "test")
|
||||
}()
|
||||
|
||||
// Under the old close()-based teardown this would panic the sender goroutine
|
||||
// and crash the test binary.
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -459,6 +459,83 @@ func TestECPlannerSeesEachPhysicalDisk(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeIndexResolvesPhysicalDiskZero pins that a volume genuinely on
|
||||
// physical disk 0 resolves to its own disk via GetVolumeLocations even when the
|
||||
// aggregate DiskInfo.DiskId is seeded from a non-zero sibling (as ToDiskInfo
|
||||
// does from volumes[0]). Re-deriving the per-record disk id would fold disk 0
|
||||
// onto the sibling, then the lookup would find no matching volume and drop it.
|
||||
func TestVolumeIndexResolvesPhysicalDiskZero(t *testing.T) {
|
||||
topology := NewActiveTopology(10)
|
||||
|
||||
require.NoError(t, topology.UpdateTopology(&master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{{
|
||||
Id: "127.0.0.1:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"hdd": {
|
||||
DiskId: 6, // seeded from volumes[0].DiskId
|
||||
MaxVolumeCount: 200,
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{
|
||||
{Id: 11, DiskId: 6, DiskType: "hdd"},
|
||||
{Id: 10, DiskId: 0, DiskType: "hdd"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}},
|
||||
}))
|
||||
|
||||
loc10 := topology.GetVolumeLocations(10, "")
|
||||
require.Len(t, loc10, 1, "volume on physical disk 0 must resolve to one disk")
|
||||
assert.Equal(t, uint32(0), loc10[0].DiskID, "volume 10 lives on physical disk 0")
|
||||
|
||||
loc11 := topology.GetVolumeLocations(11, "")
|
||||
require.Len(t, loc11, 1)
|
||||
assert.Equal(t, uint32(6), loc11[0].DiskID, "volume 11 lives on physical disk 6")
|
||||
}
|
||||
|
||||
// TestECShardIndexResolvesPhysicalDiskZero is the EC-shard twin of
|
||||
// TestVolumeIndexResolvesPhysicalDiskZero: rebuildIndexes builds ecShardIndex
|
||||
// the same way, so an EC shard on physical disk 0 must resolve via
|
||||
// GetECShardLocations rather than being folded onto a non-zero sibling.
|
||||
func TestECShardIndexResolvesPhysicalDiskZero(t *testing.T) {
|
||||
topology := NewActiveTopology(10)
|
||||
|
||||
require.NoError(t, topology.UpdateTopology(&master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{{
|
||||
Id: "127.0.0.1:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"hdd": {
|
||||
DiskId: 6, // seeded from a non-zero sibling
|
||||
MaxVolumeCount: 200,
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
|
||||
{Id: 21, DiskId: 6, Collection: "c1", EcIndexBits: 0b1},
|
||||
{Id: 20, DiskId: 0, Collection: "c1", EcIndexBits: 0b1},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}},
|
||||
}))
|
||||
|
||||
loc20 := topology.GetECShardLocations(20, "c1")
|
||||
require.Len(t, loc20, 1, "EC shard on physical disk 0 must resolve to one disk")
|
||||
assert.Equal(t, uint32(0), loc20[0].DiskID, "shard 20 lives on physical disk 0")
|
||||
|
||||
loc21 := topology.GetECShardLocations(21, "c1")
|
||||
require.Len(t, loc21, 1)
|
||||
assert.Equal(t, uint32(6), loc21[0].DiskID, "shard 21 lives on physical disk 6")
|
||||
}
|
||||
|
||||
// TestPublicInterfaces tests the public interface methods
|
||||
func TestPublicInterfaces(t *testing.T) {
|
||||
topology := NewActiveTopology(10)
|
||||
|
||||
@@ -181,6 +181,8 @@ func (at *ActiveTopology) GetDisksWithEffectiveCapacity(taskType TaskType, exclu
|
||||
ActiveVolumeCount: disk.DiskInfo.DiskInfo.ActiveVolumeCount,
|
||||
FreeVolumeCount: disk.DiskInfo.DiskInfo.FreeVolumeCount,
|
||||
Tags: append([]string(nil), disk.DiskInfo.DiskInfo.Tags...),
|
||||
DiskTotalBytes: disk.DiskInfo.DiskInfo.DiskTotalBytes,
|
||||
DiskFreeBytes: disk.DiskInfo.DiskInfo.DiskFreeBytes,
|
||||
}
|
||||
diskCopy.DiskInfo = diskInfoCopy
|
||||
diskCopy.DiskInfo.MaxVolumeCount = disk.DiskInfo.DiskInfo.MaxVolumeCount // Ensure Max is set
|
||||
@@ -246,6 +248,8 @@ func (at *ActiveTopology) GetDisksForPlanning(taskType TaskType, excludeNodeID s
|
||||
ActiveVolumeCount: disk.DiskInfo.DiskInfo.ActiveVolumeCount,
|
||||
FreeVolumeCount: disk.DiskInfo.DiskInfo.FreeVolumeCount,
|
||||
Tags: append([]string(nil), disk.DiskInfo.DiskInfo.Tags...),
|
||||
DiskTotalBytes: disk.DiskInfo.DiskInfo.DiskTotalBytes,
|
||||
DiskFreeBytes: disk.DiskInfo.DiskInfo.DiskFreeBytes,
|
||||
}
|
||||
diskCopy.DiskInfo = diskInfoCopy
|
||||
|
||||
|
||||
@@ -216,27 +216,22 @@ func (at *ActiveTopology) rebuildIndexes() {
|
||||
at.volumeIndex = make(map[uint32][]string)
|
||||
at.ecShardIndex = make(map[uint32][]string)
|
||||
|
||||
// Index by the per-record DiskId (not the outer DiskInfo.DiskId) so the
|
||||
// keys match the per-physical-disk activeDisk entries — see #9369.
|
||||
// Derive index keys from the same SplitByPhysicalDisk reconstruction that
|
||||
// builds at.disks, so every volume/EC lookup resolves to a real activeDisk
|
||||
// entry. Re-deriving the per-record disk id here would diverge on physical
|
||||
// disk 0, which the raw DiskId cannot tell apart from the "unset" default.
|
||||
for _, dc := range at.topologyInfo.DataCenterInfos {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for _, nodeInfo := range rack.DataNodeInfos {
|
||||
for _, diskInfo := range nodeInfo.DiskInfos {
|
||||
for _, volumeInfo := range diskInfo.VolumeInfos {
|
||||
diskID := volumeInfo.DiskId
|
||||
if diskID == 0 && diskInfo.DiskId != 0 {
|
||||
diskID = diskInfo.DiskId
|
||||
for _, perDisk := range diskInfo.SplitByPhysicalDisk() {
|
||||
diskKey := fmt.Sprintf("%s:%d", nodeInfo.Id, perDisk.DiskId)
|
||||
for _, volumeInfo := range perDisk.VolumeInfos {
|
||||
at.volumeIndex[volumeInfo.Id] = append(at.volumeIndex[volumeInfo.Id], diskKey)
|
||||
}
|
||||
diskKey := fmt.Sprintf("%s:%d", nodeInfo.Id, diskID)
|
||||
at.volumeIndex[volumeInfo.Id] = append(at.volumeIndex[volumeInfo.Id], diskKey)
|
||||
}
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
diskID := ecShardInfo.DiskId
|
||||
if diskID == 0 && diskInfo.DiskId != 0 {
|
||||
diskID = diskInfo.DiskId
|
||||
for _, ecShardInfo := range perDisk.EcShardInfos {
|
||||
at.ecShardIndex[ecShardInfo.Id] = append(at.ecShardIndex[ecShardInfo.Id], diskKey)
|
||||
}
|
||||
diskKey := fmt.Sprintf("%s:%d", nodeInfo.Id, diskID)
|
||||
at.ecShardIndex[ecShardInfo.Id] = append(at.ecShardIndex[ecShardInfo.Id], diskKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -588,11 +588,6 @@ templ ClusterVolumes(data dash.ClusterVolumesData) {
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
|
||||
function exportVolumes() {
|
||||
// TODO: Implement volume export functionality
|
||||
alert('Export functionality to be implemented');
|
||||
}
|
||||
|
||||
function viewVolumeDetails(volumeId) {
|
||||
// Get the server from the current row - works for both buttons and volume ID links
|
||||
const clickedElement = event.target;
|
||||
@@ -724,4 +719,4 @@ func maxInt(a, b int) int {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
}
|
||||
@@ -1048,7 +1048,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, "</small></div></div></div><!-- JavaScript for pagination and sorting --><script>\n // Initialize pagination links when page loads\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n \n // Add click handlers to view details buttons\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to volume ID links\n document.querySelectorAll('.volume-id-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to vacuum buttons\n document.querySelectorAll('.vacuum-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n const server = this.getAttribute('data-server');\n performVacuum(volumeId, server, this);\n });\n });\n });\n \n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n \n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function exportVolumes() {\n // TODO: Implement volume export functionality\n alert('Export functionality to be implemented');\n }\n \n function viewVolumeDetails(volumeId) {\n // Get the server from the current row - works for both buttons and volume ID links\n const clickedElement = event.target;\n const row = clickedElement.closest('tr');\n const serverCell = row.querySelector('td:nth-child(2) a');\n const server = serverCell ? serverCell.textContent.trim() : 'unknown';\n \n window.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${encodeURIComponent(server)}`;\n }\n\n function performVacuum(volumeId, server, button) {\n // Disable button and show loading state\n const originalHTML = button.innerHTML;\n button.disabled = true;\n button.innerHTML = '<i class=\"fas fa-spinner fa-spin\"></i>';\n\n // Send vacuum request\n fetch((window.__BASE_PATH__ || '') + `/api/volumes/${volumeId}/${encodeURIComponent(server)}/vacuum`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showMessage(data.error, 'error');\n } else {\n showMessage(data.message || 'Volume vacuum started successfully', 'success');\n // Optionally refresh the page after a delay to show updated vacuum status\n setTimeout(() => {\n Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, "</small></div></div></div><!-- JavaScript for pagination and sorting --><script>\n // Initialize pagination links when page loads\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n \n // Add click handlers to view details buttons\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to volume ID links\n document.querySelectorAll('.volume-id-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to vacuum buttons\n document.querySelectorAll('.vacuum-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n const server = this.getAttribute('data-server');\n performVacuum(volumeId, server, this);\n });\n });\n });\n \n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n \n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function viewVolumeDetails(volumeId) {\n // Get the server from the current row - works for both buttons and volume ID links\n const clickedElement = event.target;\n const row = clickedElement.closest('tr');\n const serverCell = row.querySelector('td:nth-child(2) a');\n const server = serverCell ? serverCell.textContent.trim() : 'unknown';\n \n window.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${encodeURIComponent(server)}`;\n }\n\n function performVacuum(volumeId, server, button) {\n // Disable button and show loading state\n const originalHTML = button.innerHTML;\n button.disabled = true;\n button.innerHTML = '<i class=\"fas fa-spinner fa-spin\"></i>';\n\n // Send vacuum request\n fetch((window.__BASE_PATH__ || '') + `/api/volumes/${volumeId}/${encodeURIComponent(server)}/vacuum`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showMessage(data.error, 'error');\n } else {\n showMessage(data.message || 'Volume vacuum started successfully', 'success');\n // Optionally refresh the page after a delay to show updated vacuum status\n setTimeout(() => {\n window.location.reload();\n }, 2000);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ type AdminOptions struct {
|
||||
grpcPort *int
|
||||
master *string
|
||||
masters *string // deprecated, for backward compatibility
|
||||
filerGroup *string
|
||||
adminUser *string
|
||||
adminPassword *string
|
||||
readOnlyUser *string
|
||||
@@ -65,6 +66,7 @@ func init() {
|
||||
a.grpcPort = cmdAdmin.Flag.Int("port.grpc", 0, "gRPC server port for worker connections (default: http port + 10000)")
|
||||
a.master = cmdAdmin.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
a.masters = cmdAdmin.Flag.String("masters", "", "comma-separated master servers (deprecated, use -master instead)")
|
||||
a.filerGroup = cmdAdmin.Flag.String("filerGroup", "", "filerGroup for the filers, brokers, and S3 servers")
|
||||
a.dataDir = cmdAdmin.Flag.String("dataDir", ".", "directory to store admin configuration and data files (default current dir; required for maintenance task state to persist)")
|
||||
|
||||
a.adminUser = cmdAdmin.Flag.String("adminUser", "admin", "admin interface username")
|
||||
@@ -82,7 +84,7 @@ func init() {
|
||||
}
|
||||
|
||||
var cmdAdmin = &Command{
|
||||
UsageLine: "admin -port=23646 -master=localhost:9333 [-port.grpc=33646] [-dataDir=/path/to/data]",
|
||||
UsageLine: "admin -port=23646 -master=localhost:9333 [-filerGroup=group] [-port.grpc=33646] [-dataDir=/path/to/data]",
|
||||
Short: "start SeaweedFS web admin interface",
|
||||
Long: `Start a web admin interface for SeaweedFS cluster management.
|
||||
|
||||
@@ -99,6 +101,7 @@ var cmdAdmin = &Command{
|
||||
|
||||
Example Usage:
|
||||
weed admin -port=23646 -master="master1:9333,master2:9333"
|
||||
weed admin -port=23646 -master="localhost:9333" -filerGroup="tenant-a"
|
||||
weed admin -port=23646 -master="localhost:9333" -dataDir="/var/lib/seaweedfs-admin"
|
||||
weed admin -port=23646 -port.grpc=33646 -master="localhost:9333" -dataDir="~/seaweedfs-admin"
|
||||
weed admin -port=9900 -port.grpc=19900 -master="localhost:9333"
|
||||
@@ -383,7 +386,7 @@ func startAdminServer(ctx context.Context, options AdminOptions, enableUI bool,
|
||||
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", admin.StaticHandler()))
|
||||
|
||||
// Create admin server (plugin is always enabled)
|
||||
adminServer := dash.NewAdminServer(*options.master, nil, dataDir, icebergPort)
|
||||
adminServer := dash.NewAdminServer(*options.master, *options.filerGroup, nil, dataDir, icebergPort)
|
||||
|
||||
// Show discovered filers
|
||||
filers := adminServer.GetAllFilers()
|
||||
|
||||
@@ -371,9 +371,6 @@ func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) err
|
||||
MimeType: mimeType,
|
||||
PairMap: nil,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
},
|
||||
util.NewBytesReader(data),
|
||||
)
|
||||
if flushErr != nil {
|
||||
@@ -456,9 +453,6 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File,
|
||||
MimeType: "",
|
||||
PairMap: nil,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
},
|
||||
io.NewSectionReader(f, i*chunkSize, chunkSize),
|
||||
)
|
||||
|
||||
@@ -576,9 +570,6 @@ func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, off
|
||||
MimeType: "",
|
||||
PairMap: nil,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
},
|
||||
reader,
|
||||
)
|
||||
|
||||
|
||||
@@ -58,6 +58,12 @@ var cmdFilerSyncVerify = &Command{
|
||||
-modifiedTimeAgo to skip recently-modified files (sync-lag tolerance) and
|
||||
-isActivePassive for unidirectional comparison.
|
||||
|
||||
A chunk-derived ETag (no stored attr.Md5) can differ between clusters only
|
||||
because the chunk slice was assembled in a different order, since ETagChunks
|
||||
does not sort by offset. Such files are byte-identical and reported as
|
||||
CHUNK_REORDER: not counted as errors, always counted in the summary, listed
|
||||
only at -v=1.
|
||||
|
||||
Exits with code 0 on agreement, 2 on differences or operational errors.
|
||||
|
||||
`,
|
||||
@@ -123,6 +129,7 @@ type VerifyResult struct {
|
||||
missingCount atomic.Int64
|
||||
sizeMismatch atomic.Int64
|
||||
etagMismatch atomic.Int64
|
||||
chunkReorder atomic.Int64 // content-equal; chunks differ only in slice order
|
||||
onlyInB atomic.Int64
|
||||
skippedRecent atomic.Int64
|
||||
|
||||
@@ -139,6 +146,7 @@ const (
|
||||
diffOnlyInB // in B but not in A
|
||||
diffSizeMismatch // size differs
|
||||
diffETagMismatch // etag differs
|
||||
diffChunkReorder // etag differs but content is equal (chunk slice order only)
|
||||
)
|
||||
|
||||
// diffRecord is the JSON Lines schema for a single diff entry.
|
||||
@@ -167,6 +175,7 @@ type summaryRecord struct {
|
||||
Missing int64 `json:"missing"`
|
||||
SizeMismatch int64 `json:"sizeMismatch"`
|
||||
ETagMismatch int64 `json:"etagMismatch"`
|
||||
ChunkReorder int64 `json:"chunkReorder"`
|
||||
OnlyInB int64 `json:"onlyInB"`
|
||||
TotalErrors int64 `json:"totalErrors"`
|
||||
}
|
||||
@@ -236,6 +245,7 @@ func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string,
|
||||
Missing: result.missingCount.Load(),
|
||||
SizeMismatch: result.sizeMismatch.Load(),
|
||||
ETagMismatch: result.etagMismatch.Load(),
|
||||
ChunkReorder: result.chunkReorder.Load(),
|
||||
OnlyInB: result.onlyInB.Load(),
|
||||
TotalErrors: totalErrors,
|
||||
}
|
||||
@@ -250,6 +260,9 @@ func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string,
|
||||
fmt.Fprintf(os.Stdout, " Missing in B: %d\n", result.missingCount.Load())
|
||||
fmt.Fprintf(os.Stdout, " Size mismatch: %d\n", result.sizeMismatch.Load())
|
||||
fmt.Fprintf(os.Stdout, " ETag mismatch: %d\n", result.etagMismatch.Load())
|
||||
if n := result.chunkReorder.Load(); n > 0 {
|
||||
fmt.Fprintf(os.Stdout, " Chunk reorder (equal): %d (content-equal, not an error; use -v=1 to list)\n", n)
|
||||
}
|
||||
if !isActivePassive {
|
||||
fmt.Fprintf(os.Stdout, " Only in B: %d\n", result.onlyInB.Load())
|
||||
}
|
||||
@@ -496,11 +509,88 @@ func compareEntries(dir string, entryA, entryB *filer_pb.Entry, result *VerifyRe
|
||||
etagA := filer.ETag(entryA)
|
||||
etagB := filer.ETag(entryB)
|
||||
if etagA != etagB {
|
||||
reportDiff(diffETagMismatch, dir, entryA, entryB, result)
|
||||
if isChunkReorder(entryA, entryB) {
|
||||
// Same bytes, just a different chunk slice order — not a real diff.
|
||||
reportDiff(diffChunkReorder, dir, entryA, entryB, result)
|
||||
} else {
|
||||
reportDiff(diffETagMismatch, dir, entryA, entryB, result)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// isChunkReorder reports whether two entries with differing file ETags are
|
||||
// byte-identical, differing only in chunk slice order. filer.ETagChunks hashes
|
||||
// per-chunk MD5s in stored order without sorting by offset, so the same bytes
|
||||
// written by different paths (S3 multipart vs filer.backup) can hash
|
||||
// differently. If both chunk lists sorted by offset match element-wise on
|
||||
// (offset, size, ETag), the files cover the same bytes with the same content
|
||||
// and only the slice order differed.
|
||||
//
|
||||
// Applies only when both ETags come from chunks (a stored attr.Md5 is
|
||||
// order-independent, so a mismatch there is a real content difference) and the
|
||||
// chunks form a manifest-free, non-overlapping set whose bytes are fully
|
||||
// determined by the list — overlaps would need timestamp-based visible-interval
|
||||
// resolution, so those stay ETAG_MISMATCH.
|
||||
func isChunkReorder(entryA, entryB *filer_pb.Entry) bool {
|
||||
if !usesChunkETag(entryA) || !usesChunkETag(entryB) {
|
||||
return false
|
||||
}
|
||||
a := sortedSimpleChunks(entryA.GetChunks())
|
||||
b := sortedSimpleChunks(entryB.GetChunks())
|
||||
// nil means overlapping or manifest chunks we do not fast-path; a single
|
||||
// chunk hashes directly and a differing count is a real divergence.
|
||||
if a == nil || b == nil || len(a) != len(b) || len(a) < 2 {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i].Offset != b[i].Offset || a[i].Size != b[i].Size || a[i].ETag != b[i].ETag {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// usesChunkETag reports whether filer.ETag falls back to ETagChunks for entry,
|
||||
// i.e. no stored attr.Md5 whole-content hash is available. Mirrors filer.ETag's
|
||||
// own condition so it agrees with how the compared ETag was computed.
|
||||
func usesChunkETag(entry *filer_pb.Entry) bool {
|
||||
return entry.Attributes == nil || entry.Attributes.Md5 == nil
|
||||
}
|
||||
|
||||
// sortedSimpleChunks returns chunks sorted by (offset, ETag) if they are a
|
||||
// manifest-free, non-overlapping set whose visible bytes are fully determined
|
||||
// by the list and every chunk carries a usable per-chunk ETag; otherwise nil.
|
||||
// Overlapping ranges would require resolving the visible interval by chunk
|
||||
// timestamp, which this fast path does not attempt.
|
||||
func sortedSimpleChunks(chunks []*filer_pb.FileChunk) []*filer_pb.FileChunk {
|
||||
sorted := make([]*filer_pb.FileChunk, len(chunks))
|
||||
copy(sorted, chunks)
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
if sorted[i].Offset != sorted[j].Offset {
|
||||
return sorted[i].Offset < sorted[j].Offset
|
||||
}
|
||||
return sorted[i].ETag < sorted[j].ETag
|
||||
})
|
||||
prevEnd := int64(0)
|
||||
for i, c := range sorted {
|
||||
if c.IsChunkManifest {
|
||||
return nil
|
||||
}
|
||||
// An empty or undecodable ETag is not a content fingerprint, so
|
||||
// element-wise (offset, size, ETag) equality cannot prove the bytes
|
||||
// match — decline rather than assert a false content-equality.
|
||||
if len(util.Base64Md5ToBytes(c.ETag)) == 0 {
|
||||
return nil
|
||||
}
|
||||
if i > 0 && c.Offset < prevEnd {
|
||||
return nil
|
||||
}
|
||||
prevEnd = c.Offset + int64(c.Size)
|
||||
}
|
||||
return sorted
|
||||
}
|
||||
|
||||
// mtimeRelation classifies B.mtime vs A.mtime. Both entries must be non-nil.
|
||||
// Returns relation, absolute delta in seconds, and human-readable string.
|
||||
func mtimeRelation(entryA, entryB *filer_pb.Entry) (relation, deltaStr string, deltaSec int64) {
|
||||
@@ -557,11 +647,19 @@ func reportDiff(diffType verifyDiffType, dir string, entryA, entryB *filer_pb.En
|
||||
result.sizeMismatch.Add(1)
|
||||
case diffETagMismatch:
|
||||
result.etagMismatch.Add(1)
|
||||
case diffChunkReorder:
|
||||
result.chunkReorder.Add(1)
|
||||
}
|
||||
|
||||
if result.jsonOutput {
|
||||
writeJSONDiff(result, diffType, dir, entryA, entryB)
|
||||
} else {
|
||||
// A chunk reorder is content-equal, not a real diff: keep it out of the
|
||||
// default text report and list it only at -v=1. JSON always emits it so
|
||||
// the per-record stream matches the summary count.
|
||||
if diffType == diffChunkReorder && !glog.V(1) {
|
||||
return
|
||||
}
|
||||
writeTextDiff(result, diffType, dir, entryA, entryB)
|
||||
}
|
||||
}
|
||||
@@ -590,6 +688,9 @@ func writeTextDiff(result *VerifyResult, diffType verifyDiffType, dir string, en
|
||||
ann := annotation(entryA, entryB)
|
||||
fmt.Fprintf(os.Stdout, "[ETAG_MISMATCH] %s (a=%s, b=%s%s)\n",
|
||||
entryPath, filer.ETag(entryA), filer.ETag(entryB), ann)
|
||||
case diffChunkReorder:
|
||||
fmt.Fprintf(os.Stdout, "[CHUNK_REORDER] %s (a=%s, b=%s, content-equal: chunks differ only in slice order)\n",
|
||||
entryPath, filer.ETag(entryA), filer.ETag(entryB))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -640,6 +741,14 @@ func writeJSONDiff(result *VerifyResult, diffType verifyDiffType, dir string, en
|
||||
rec.MtimeRelation = relation
|
||||
rec.MtimeDelta = delta
|
||||
rec.Hint = hintFor(relation)
|
||||
case diffChunkReorder:
|
||||
rec.Type = "CHUNK_REORDER"
|
||||
rec.A = toEntryRecord(entryA)
|
||||
rec.B = toEntryRecord(entryB)
|
||||
relation, delta, _ := mtimeRelation(entryA, entryB)
|
||||
rec.MtimeRelation = relation
|
||||
rec.MtimeDelta = delta
|
||||
// no hint: content-equal, no action needed
|
||||
}
|
||||
|
||||
writeJSONLine(result, rec)
|
||||
|
||||
@@ -4,11 +4,14 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
@@ -101,6 +104,34 @@ func verifyDirEntry(name string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name, IsDirectory: true}
|
||||
}
|
||||
|
||||
// verifyChunk builds a FileChunk whose ETag is the base64 MD5 of seed, so
|
||||
// filer.ETagChunks (which base64-decodes each chunk ETag) can hash it. Distinct
|
||||
// seeds yield distinct per-chunk MD5s.
|
||||
func verifyChunk(offset int64, size uint64, seed string) *filer_pb.FileChunk {
|
||||
return &filer_pb.FileChunk{
|
||||
Offset: offset,
|
||||
Size: size,
|
||||
ETag: util.Base64Encode(util.Md5([]byte(seed))),
|
||||
}
|
||||
}
|
||||
|
||||
// verifyChunkedEntry builds a chunk-backed entry with no stored attr.Md5, so
|
||||
// its file ETag is derived from ETagChunks (the order-sensitive path). FileSize
|
||||
// is the max chunk end, matching filer.FileSize, so size comparison passes.
|
||||
func verifyChunkedEntry(name string, chunks []*filer_pb.FileChunk) *filer_pb.Entry {
|
||||
var total uint64
|
||||
for _, c := range chunks {
|
||||
if end := uint64(c.Offset) + c.Size; end > total {
|
||||
total = end
|
||||
}
|
||||
}
|
||||
return &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: total}, // Md5 nil → ETagChunks path
|
||||
Chunks: chunks,
|
||||
}
|
||||
}
|
||||
|
||||
// --- tests ---
|
||||
|
||||
// TestVerifySyncMissingFile confirms that a file present in A but absent in B
|
||||
@@ -280,6 +311,271 @@ func TestVerifySyncETagMismatch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySyncChunkReorder confirms that two entries holding the SAME
|
||||
// chunks (same offsets, same per-chunk MD5s) in a DIFFERENT slice order are
|
||||
// classified as CHUNK_REORDER (content-equal), not ETAG_MISMATCH, and are
|
||||
// therefore not counted as errors. This is the S3-multipart vs filer.backup
|
||||
// reordering false positive.
|
||||
func TestVerifySyncChunkReorder(t *testing.T) {
|
||||
c0 := verifyChunk(0, 100, "chunk-0")
|
||||
c1 := verifyChunk(100, 100, "chunk-1")
|
||||
c2 := verifyChunk(200, 100, "chunk-2")
|
||||
|
||||
// A stores [c0,c1,c2]; B stores a permutation [c2,c0,c1] of the same chunks.
|
||||
clientA := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c0, c1, c2})},
|
||||
},
|
||||
}
|
||||
clientB := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c2, c0, c1})},
|
||||
},
|
||||
}
|
||||
|
||||
result := &VerifyResult{}
|
||||
sem := make(chan struct{}, verifySyncConcurrency)
|
||||
if err := compareDirectory(context.Background(), clientA, clientB,
|
||||
"/root", "/root", false, time.Time{}, sem, result); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := result.chunkReorder.Load(); got != 1 {
|
||||
t.Errorf("chunkReorder = %d, want 1", got)
|
||||
}
|
||||
if got := result.etagMismatch.Load(); got != 0 {
|
||||
t.Errorf("etagMismatch = %d, want 0 (reordered chunks are content-equal)", got)
|
||||
}
|
||||
if got := result.sizeMismatch.Load(); got != 0 {
|
||||
t.Errorf("sizeMismatch = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySyncGenuineChunkDivergence confirms that when one chunk's content
|
||||
// actually differs (same offsets and count, different per-chunk MD5), the file
|
||||
// stays classified as ETAG_MISMATCH and is NOT downgraded to CHUNK_REORDER.
|
||||
func TestVerifySyncGenuineChunkDivergence(t *testing.T) {
|
||||
clientA := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{
|
||||
verifyChunk(0, 100, "chunk-0"),
|
||||
verifyChunk(100, 100, "chunk-1"),
|
||||
verifyChunk(200, 100, "chunk-2"),
|
||||
})},
|
||||
},
|
||||
}
|
||||
clientB := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{
|
||||
verifyChunk(0, 100, "chunk-0"),
|
||||
verifyChunk(100, 100, "chunk-1"),
|
||||
verifyChunk(200, 100, "chunk-2-DIFFERENT"), // real content divergence
|
||||
})},
|
||||
},
|
||||
}
|
||||
|
||||
result := &VerifyResult{}
|
||||
sem := make(chan struct{}, verifySyncConcurrency)
|
||||
if err := compareDirectory(context.Background(), clientA, clientB,
|
||||
"/root", "/root", false, time.Time{}, sem, result); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := result.etagMismatch.Load(); got != 1 {
|
||||
t.Errorf("etagMismatch = %d, want 1 (genuine chunk content divergence)", got)
|
||||
}
|
||||
if got := result.chunkReorder.Load(); got != 0 {
|
||||
t.Errorf("chunkReorder = %d, want 0 (content actually differs)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySyncChunkCountDiffStaysEtagMismatch confirms that a differing chunk
|
||||
// count with an equal file size (e.g. differently split content) is NOT treated
|
||||
// as a reordering — it stays ETAG_MISMATCH.
|
||||
func TestVerifySyncChunkCountDiffStaysEtagMismatch(t *testing.T) {
|
||||
clientA := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{
|
||||
verifyChunk(0, 100, "a"),
|
||||
verifyChunk(100, 100, "b"),
|
||||
verifyChunk(200, 100, "c"),
|
||||
})},
|
||||
},
|
||||
}
|
||||
clientB := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{
|
||||
verifyChunk(0, 150, "x"),
|
||||
verifyChunk(150, 150, "y"),
|
||||
})},
|
||||
},
|
||||
}
|
||||
|
||||
result := &VerifyResult{}
|
||||
sem := make(chan struct{}, verifySyncConcurrency)
|
||||
if err := compareDirectory(context.Background(), clientA, clientB,
|
||||
"/root", "/root", false, time.Time{}, sem, result); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := result.sizeMismatch.Load(); got != 0 {
|
||||
t.Errorf("sizeMismatch = %d, want 0 (both total 300 bytes)", got)
|
||||
}
|
||||
if got := result.etagMismatch.Load(); got != 1 {
|
||||
t.Errorf("etagMismatch = %d, want 1", got)
|
||||
}
|
||||
if got := result.chunkReorder.Load(); got != 0 {
|
||||
t.Errorf("chunkReorder = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySyncDuplicateOffsetStaysEtagMismatch confirms that overlapping
|
||||
// chunks at the same offset — where the visible bytes are resolved by chunk
|
||||
// timestamp, not by the raw chunk list — are NOT fast-pathed to CHUNK_REORDER.
|
||||
// Both sides hold the same two ETags at offset 0 in a different order, so the
|
||||
// file ETags differ; the visible content is ambiguous from the list alone, so
|
||||
// this must stay ETAG_MISMATCH.
|
||||
func TestVerifySyncDuplicateOffsetStaysEtagMismatch(t *testing.T) {
|
||||
c1 := verifyChunk(0, 100, "v1")
|
||||
c2 := verifyChunk(0, 100, "v2") // same offset → overlap
|
||||
|
||||
clientA := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c1, c2})},
|
||||
},
|
||||
}
|
||||
clientB := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c2, c1})},
|
||||
},
|
||||
}
|
||||
|
||||
result := &VerifyResult{}
|
||||
sem := make(chan struct{}, verifySyncConcurrency)
|
||||
if err := compareDirectory(context.Background(), clientA, clientB,
|
||||
"/root", "/root", false, time.Time{}, sem, result); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := result.etagMismatch.Load(); got != 1 {
|
||||
t.Errorf("etagMismatch = %d, want 1 (overlapping offsets are not a safe reorder)", got)
|
||||
}
|
||||
if got := result.chunkReorder.Load(); got != 0 {
|
||||
t.Errorf("chunkReorder = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySyncManifestChunkStaysEtagMismatch confirms that entries containing
|
||||
// a manifest chunk are not fast-pathed to CHUNK_REORDER: manifest chunks
|
||||
// represent compacted, possibly overlapping history that this check does not
|
||||
// resolve.
|
||||
func TestVerifySyncManifestChunkStaysEtagMismatch(t *testing.T) {
|
||||
manifest := func(offset int64, size uint64, seed string) *filer_pb.FileChunk {
|
||||
c := verifyChunk(offset, size, seed)
|
||||
c.IsChunkManifest = true
|
||||
return c
|
||||
}
|
||||
a0, a1 := manifest(0, 100, "m0"), verifyChunk(100, 100, "m1")
|
||||
clientA := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{a0, a1})},
|
||||
},
|
||||
}
|
||||
clientB := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{a1, a0})},
|
||||
},
|
||||
}
|
||||
|
||||
result := &VerifyResult{}
|
||||
sem := make(chan struct{}, verifySyncConcurrency)
|
||||
if err := compareDirectory(context.Background(), clientA, clientB,
|
||||
"/root", "/root", false, time.Time{}, sem, result); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := result.etagMismatch.Load(); got != 1 {
|
||||
t.Errorf("etagMismatch = %d, want 1 (manifest chunks are not fast-pathed)", got)
|
||||
}
|
||||
if got := result.chunkReorder.Load(); got != 0 {
|
||||
t.Errorf("chunkReorder = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySyncEmptyChunkETagStaysEtagMismatch confirms that a chunk with an
|
||||
// empty per-chunk ETag is never fast-pathed to CHUNK_REORDER: an empty ETag is
|
||||
// not a content fingerprint, so (offset, size, ETag) equality cannot prove the
|
||||
// bytes match. The two sides reorder their non-empty chunks so the file ETags
|
||||
// differ and the reorder check is reached, but the empty-ETag chunk in the
|
||||
// middle must keep it ETAG_MISMATCH rather than assert a false content-equality.
|
||||
func TestVerifySyncEmptyChunkETagStaysEtagMismatch(t *testing.T) {
|
||||
c0 := verifyChunk(0, 100, "e0")
|
||||
empty := &filer_pb.FileChunk{Offset: 100, Size: 100} // no ETag → not a fingerprint
|
||||
c2 := verifyChunk(200, 100, "e2")
|
||||
|
||||
clientA := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c0, empty, c2})},
|
||||
},
|
||||
}
|
||||
clientB := &verifyTestFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c2, c0, empty})},
|
||||
},
|
||||
}
|
||||
|
||||
result := &VerifyResult{}
|
||||
sem := make(chan struct{}, verifySyncConcurrency)
|
||||
if err := compareDirectory(context.Background(), clientA, clientB,
|
||||
"/root", "/root", false, time.Time{}, sem, result); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := result.etagMismatch.Load(); got != 1 {
|
||||
t.Errorf("etagMismatch = %d, want 1 (empty per-chunk ETag is not a content fingerprint)", got)
|
||||
}
|
||||
if got := result.chunkReorder.Load(); got != 0 {
|
||||
t.Errorf("chunkReorder = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// captureStdout runs fn with os.Stdout redirected to a pipe and returns what it
|
||||
// wrote. Tests that assert on emitted diff records use it.
|
||||
func captureStdout(t *testing.T, fn func()) string {
|
||||
t.Helper()
|
||||
orig := os.Stdout
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("os.Pipe: %v", err)
|
||||
}
|
||||
os.Stdout = w
|
||||
fn()
|
||||
w.Close()
|
||||
os.Stdout = orig
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
t.Fatalf("read captured stdout: %v", err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// TestVerifySyncChunkReorderJSONEmittedByDefault confirms that in JSON output
|
||||
// mode a CHUNK_REORDER record is emitted at default verbosity: the -v=1 gate
|
||||
// suppresses only the human text report, so the NDJSON per-record stream stays
|
||||
// consistent with the summary count a machine consumer reads.
|
||||
func TestVerifySyncChunkReorderJSONEmittedByDefault(t *testing.T) {
|
||||
c0 := verifyChunk(0, 100, "chunk-0")
|
||||
c1 := verifyChunk(100, 100, "chunk-1")
|
||||
entryA := verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c0, c1})
|
||||
entryB := verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c1, c0})
|
||||
|
||||
result := &VerifyResult{jsonOutput: true}
|
||||
out := captureStdout(t, func() {
|
||||
reportDiff(diffChunkReorder, "/root", entryA, entryB, result)
|
||||
})
|
||||
|
||||
if got := result.chunkReorder.Load(); got != 1 {
|
||||
t.Fatalf("chunkReorder = %d, want 1", got)
|
||||
}
|
||||
if !strings.Contains(out, `"type":"CHUNK_REORDER"`) {
|
||||
t.Errorf("JSON output missing CHUNK_REORDER record at default verbosity; got %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySyncCutoffTime verifies that entries newer than cutoffTime are
|
||||
// skipped in both the A-only (MISSING) and B-only (ONLY_IN_B) branches.
|
||||
func TestVerifySyncCutoffTime(t *testing.T) {
|
||||
|
||||
@@ -543,6 +543,8 @@ func initMiniAdminFlags() {
|
||||
miniAdminOptions.port = cmdMini.Flag.Int("admin.port", 23646, "admin server http listen port")
|
||||
miniAdminOptions.grpcPort = cmdMini.Flag.Int("admin.port.grpc", 0, "admin server grpc listen port (default: admin http port + GrpcPortOffset)")
|
||||
miniAdminOptions.master = cmdMini.Flag.String("admin.master", "", "master server address (automatically set)")
|
||||
// admin discovery must query the same group the co-located filer registers under
|
||||
miniAdminOptions.filerGroup = miniFilerOptions.filerGroup
|
||||
miniAdminOptions.dataDir = cmdMini.Flag.String("admin.dataDir", "", "directory to store admin configuration and data files")
|
||||
miniAdminOptions.adminUser = cmdMini.Flag.String("admin.user", "admin", "admin interface username")
|
||||
miniAdminOptions.adminPassword = cmdMini.Flag.String("admin.password", "", "admin interface password (if empty, auth is disabled)")
|
||||
|
||||
@@ -41,7 +41,7 @@ func NewChunkGroup(lookupFn wdclient.LookupFileIdFunctionType, chunkCache chunk_
|
||||
group := &ChunkGroup{
|
||||
lookupFn: lookupFn,
|
||||
sections: make(map[SectionIndex]*FileChunkSection),
|
||||
readerCache: NewReaderCache(readerCacheLimit, chunkCache, lookupFn),
|
||||
readerCache: NewReaderCache(readerCacheLimit, chunkCache, lookupFn, nil),
|
||||
concurrentReaders: concurrentReaders,
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ type GatewayChunkUploader interface {
|
||||
filerClient filer_pb.FilerClient,
|
||||
assignRequest *filer_pb.AssignVolumeRequest,
|
||||
uploadOption *operation.UploadOption,
|
||||
genFileUrlFn func(host, fileId string) string,
|
||||
reader io.Reader,
|
||||
) (fileId string, uploadResult *operation.UploadResult, err error, data []byte)
|
||||
}
|
||||
@@ -120,11 +119,8 @@ func SaveGatewayDataAsChunk(req GatewayChunkUploadRequest) (*filer_pb.FileChunk,
|
||||
PairMap: req.PairMap,
|
||||
}
|
||||
|
||||
genFileUrlFn := func(host, fileId string) string {
|
||||
if req.VolumeServerAccess == "filerProxy" && req.FilerHTTPAddress != "" {
|
||||
return fmt.Sprintf("http://%s/?proxyChunkId=%s", req.FilerHTTPAddress, fileId)
|
||||
}
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
if req.VolumeServerAccess == "filerProxy" && req.FilerHTTPAddress != "" {
|
||||
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(req.FilerHTTPAddress)
|
||||
}
|
||||
|
||||
assignRequest := &filer_pb.AssignVolumeRequest{
|
||||
@@ -141,7 +137,6 @@ func SaveGatewayDataAsChunk(req GatewayChunkUploadRequest) (*filer_pb.FileChunk,
|
||||
req.FilerClient,
|
||||
assignRequest,
|
||||
uploadOption,
|
||||
genFileUrlFn,
|
||||
req.Reader,
|
||||
)
|
||||
if uploadErr != nil {
|
||||
|
||||
@@ -72,7 +72,7 @@ func (store *MysqlStore) initialize(dsn string, upsertQuery string, enableUpsert
|
||||
}
|
||||
gen := &SqlGenMysql{
|
||||
CreateTableSqlTemplate: "",
|
||||
DropTableSqlTemplate: "DROP TABLE `%s`",
|
||||
DropTableSqlTemplate: "DROP TABLE IF EXISTS `%s`",
|
||||
UpsertQueryTemplate: upsertQuery,
|
||||
}
|
||||
store.SqlGenerator = gen
|
||||
|
||||
@@ -65,7 +65,7 @@ func (store *MysqlStore2) initialize(createTable, upsertQuery string, enableUpse
|
||||
}
|
||||
gen := &mysql.SqlGenMysql{
|
||||
CreateTableSqlTemplate: createTable,
|
||||
DropTableSqlTemplate: "DROP TABLE `%s`",
|
||||
DropTableSqlTemplate: "DROP TABLE IF EXISTS `%s`",
|
||||
UpsertQueryTemplate: upsertQuery,
|
||||
}
|
||||
store.SqlGenerator = gen
|
||||
|
||||
@@ -64,7 +64,7 @@ func (store *PostgresStore) initialize(upsertQuery string, enableUpsert bool, us
|
||||
}
|
||||
gen := &SqlGenPostgres{
|
||||
CreateTableSqlTemplate: "",
|
||||
DropTableSqlTemplate: `drop table "%s"`,
|
||||
DropTableSqlTemplate: `drop table if exists "%s"`,
|
||||
UpsertQueryTemplate: upsertQuery,
|
||||
}
|
||||
store.SqlGenerator = gen
|
||||
|
||||
@@ -70,7 +70,7 @@ func (store *PostgresStore2) initialize(createTable, upsertQuery string, enableU
|
||||
}
|
||||
gen := &postgres.SqlGenPostgres{
|
||||
CreateTableSqlTemplate: createTable,
|
||||
DropTableSqlTemplate: `drop table "%s"`,
|
||||
DropTableSqlTemplate: `drop table if exists "%s"`,
|
||||
UpsertQueryTemplate: upsertQuery,
|
||||
}
|
||||
store.SqlGenerator = gen
|
||||
|
||||
@@ -77,7 +77,7 @@ func TestReaderAt(t *testing.T) {
|
||||
readerAt := &ChunkReadAt{
|
||||
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
|
||||
fileSize: 10,
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
|
||||
readerPattern: NewReaderPattern(),
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ func TestReaderAt0(t *testing.T) {
|
||||
readerAt := &ChunkReadAt{
|
||||
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
|
||||
fileSize: 10,
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
|
||||
readerPattern: NewReaderPattern(),
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ func TestReaderAt1(t *testing.T) {
|
||||
readerAt := &ChunkReadAt{
|
||||
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
|
||||
fileSize: 20,
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
|
||||
readerPattern: NewReaderPattern(),
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ func TestReaderAtGappedChunksDoNotLeak(t *testing.T) {
|
||||
readerAt := &ChunkReadAt{
|
||||
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
|
||||
fileSize: 9,
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
|
||||
readerPattern: NewReaderPattern(),
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ func TestReaderAtSparseFileDoesNotLeak(t *testing.T) {
|
||||
readerAt := &ChunkReadAt{
|
||||
chunkViews: ViewFromVisibleIntervals(NewIntervalList[*VisibleInterval](), 0, math.MaxInt64),
|
||||
fileSize: 3,
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
|
||||
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
|
||||
readerPattern: NewReaderPattern(),
|
||||
}
|
||||
|
||||
|
||||
+92
-25
@@ -14,9 +14,17 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
)
|
||||
|
||||
type CacheInvalidator interface {
|
||||
InvalidateCache(fileId string)
|
||||
}
|
||||
|
||||
type fetchChunkDataFnType func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, fileId string) (n int, err error)
|
||||
|
||||
type ReaderCache struct {
|
||||
chunkCache chunk_cache.ChunkCache
|
||||
lookupFileIdFn wdclient.LookupFileIdFunctionType
|
||||
chunkCache chunk_cache.ChunkCache
|
||||
lookupFileIdFn wdclient.LookupFileIdFunctionType
|
||||
cacheInvalidator CacheInvalidator
|
||||
fetchChunkDataFn fetchChunkDataFnType
|
||||
sync.Mutex
|
||||
downloaders map[string]*SingleChunkCacher
|
||||
limit int
|
||||
@@ -38,12 +46,14 @@ type SingleChunkCacher struct {
|
||||
done chan struct{} // signals when download is complete
|
||||
}
|
||||
|
||||
func NewReaderCache(limit int, chunkCache chunk_cache.ChunkCache, lookupFileIdFn wdclient.LookupFileIdFunctionType) *ReaderCache {
|
||||
func NewReaderCache(limit int, chunkCache chunk_cache.ChunkCache, lookupFileIdFn wdclient.LookupFileIdFunctionType, cacheInvalidator CacheInvalidator) *ReaderCache {
|
||||
return &ReaderCache{
|
||||
limit: limit,
|
||||
chunkCache: chunkCache,
|
||||
lookupFileIdFn: lookupFileIdFn,
|
||||
downloaders: make(map[string]*SingleChunkCacher),
|
||||
limit: limit,
|
||||
chunkCache: chunkCache,
|
||||
lookupFileIdFn: lookupFileIdFn,
|
||||
cacheInvalidator: cacheInvalidator,
|
||||
fetchChunkDataFn: util_http.RetriedFetchChunkData,
|
||||
downloaders: make(map[string]*SingleChunkCacher),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,15 +107,29 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
|
||||
func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
|
||||
rc.Lock()
|
||||
|
||||
if cacher, found := rc.downloaders[fileId]; found {
|
||||
rc.Unlock()
|
||||
n, err := cacher.readChunkAt(ctx, buffer, offset)
|
||||
if n > 0 || err != nil {
|
||||
return n, err
|
||||
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)
|
||||
rc.Unlock()
|
||||
n, err := cacher.readChunkAt(ctx, buffer, offset)
|
||||
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()
|
||||
}
|
||||
// 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))
|
||||
@@ -137,6 +161,7 @@ func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId st
|
||||
go cacher.startCaching()
|
||||
<-cacher.cacheStartedCh
|
||||
rc.downloaders[fileId] = cacher
|
||||
cacher.wg.Add(1)
|
||||
rc.Unlock()
|
||||
|
||||
return cacher.readChunkAt(ctx, buffer, offset)
|
||||
@@ -198,32 +223,74 @@ func (s *SingleChunkCacher) startCaching() {
|
||||
// Lookup file ID without holding the lock
|
||||
urlStrings, err := s.parent.lookupFileIdFn(context.Background(), s.chunkFileId)
|
||||
if err != nil {
|
||||
s.Lock()
|
||||
s.err = fmt.Errorf("operation LookupFileId %s failed, err: %v", s.chunkFileId, err)
|
||||
s.Unlock()
|
||||
s.setError(fmt.Errorf("operation LookupFileId %s failed, err: %v", s.chunkFileId, err))
|
||||
return
|
||||
}
|
||||
if len(urlStrings) == 0 {
|
||||
s.setError(fmt.Errorf("operation LookupFileId %s failed, err: urls not found", s.chunkFileId))
|
||||
return
|
||||
}
|
||||
|
||||
// Allocate buffer and download without holding the lock
|
||||
// This allows multiple downloads to proceed in parallel
|
||||
data := mem.Allocate(s.chunkSize)
|
||||
_, fetchErr := util_http.RetriedFetchChunkData(context.Background(), data, urlStrings, s.cipherKey, s.isGzipped, true, 0, s.chunkFileId)
|
||||
data, fetchErr := s.fetchChunkData(context.Background(), urlStrings)
|
||||
if fetchErr != nil {
|
||||
data, fetchErr = s.retryFetchAfterCacheInvalidation(context.Background(), urlStrings, fetchErr)
|
||||
}
|
||||
|
||||
// Now acquire lock to update state
|
||||
s.Lock()
|
||||
atomic.StoreInt64(&s.completedTimeNew, time.Now().UnixNano())
|
||||
if fetchErr != nil {
|
||||
mem.Free(data)
|
||||
s.err = fetchErr
|
||||
} else {
|
||||
s.data = data
|
||||
if s.shouldCache {
|
||||
s.parent.chunkCache.SetChunk(s.chunkFileId, s.data)
|
||||
}
|
||||
atomic.StoreInt64(&s.completedTimeNew, time.Now().UnixNano())
|
||||
}
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
func (s *SingleChunkCacher) setError(err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.err = err
|
||||
atomic.StoreInt64(&s.completedTimeNew, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
func (s *SingleChunkCacher) hasCompletedError() bool {
|
||||
if atomic.LoadInt64(&s.completedTimeNew) == 0 {
|
||||
return false
|
||||
}
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.err != nil
|
||||
}
|
||||
|
||||
func (s *SingleChunkCacher) fetchChunkData(ctx context.Context, urlStrings []string) ([]byte, error) {
|
||||
// Allocate buffer and download without holding the lock.
|
||||
// This allows multiple downloads to proceed in parallel.
|
||||
data := mem.Allocate(s.chunkSize)
|
||||
_, fetchErr := s.parent.fetchChunkDataFn(ctx, data, urlStrings, s.cipherKey, s.isGzipped, true, 0, s.chunkFileId)
|
||||
if fetchErr != nil {
|
||||
mem.Free(data)
|
||||
return nil, fetchErr
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (s *SingleChunkCacher) retryFetchAfterCacheInvalidation(ctx context.Context, oldUrlStrings []string, originalErr error) ([]byte, error) {
|
||||
var data []byte
|
||||
err := retryFetchWithFreshLocations(ctx, s.parent.cacheInvalidator, s.parent.lookupFileIdFn, s.chunkFileId, oldUrlStrings, originalErr, func(newUrls []string) error {
|
||||
var fetchErr error
|
||||
data, fetchErr = s.fetchChunkData(ctx, newUrls)
|
||||
return fetchErr
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (s *SingleChunkCacher) destroy() {
|
||||
// wait for all reads to finish before destroying the data
|
||||
s.wg.Wait()
|
||||
@@ -240,8 +307,8 @@ func (s *SingleChunkCacher) destroy() {
|
||||
// It waits for the download to complete if it's still in progress.
|
||||
// The ctx parameter allows the reader to cancel its wait (but the download continues
|
||||
// for other readers - see comment in startCaching about shared resource semantics).
|
||||
// The caller must s.wg.Add(1) under the ReaderCache lock before calling; this only releases it.
|
||||
func (s *SingleChunkCacher) readChunkAt(ctx context.Context, buf []byte, offset int64) (int, error) {
|
||||
s.wg.Add(1)
|
||||
defer s.wg.Done()
|
||||
|
||||
// Wait for download to complete, but allow reader cancellation.
|
||||
|
||||
+154
-18
@@ -16,6 +16,25 @@ type mockChunkCacheForReaderCache struct {
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
type mockCacheInvalidatorForReaderCache struct {
|
||||
calls int32
|
||||
mu sync.Mutex
|
||||
fileId string
|
||||
}
|
||||
|
||||
func (m *mockCacheInvalidatorForReaderCache) InvalidateCache(fileId string) {
|
||||
atomic.AddInt32(&m.calls, 1)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.fileId = fileId
|
||||
}
|
||||
|
||||
func (m *mockCacheInvalidatorForReaderCache) lastFileId() string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.fileId
|
||||
}
|
||||
|
||||
func newMockChunkCacheForReaderCache() *mockChunkCacheForReaderCache {
|
||||
return &mockChunkCacheForReaderCache{
|
||||
data: make(map[string][]byte),
|
||||
@@ -60,6 +79,113 @@ func (m *mockChunkCacheForReaderCache) IsInCache(fileId string, lockNeeded bool)
|
||||
return ok
|
||||
}
|
||||
|
||||
func TestReaderCacheRetryAfterCacheInvalidation(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
invalidator := &mockCacheInvalidatorForReaderCache{}
|
||||
fileId := "425141,ef8914e9bdbbe8cb6838191f"
|
||||
staleUrl := "http://fast-volume-1/" + fileId
|
||||
freshUrl := "http://fast-volume-9/" + fileId
|
||||
testData := []byte("fresh chunk data after cache invalidation")
|
||||
|
||||
var lookupCount int32
|
||||
lookupFn := func(ctx context.Context, requestedFileId string) ([]string, error) {
|
||||
if requestedFileId != fileId {
|
||||
return nil, fmt.Errorf("unexpected lookup file id %s", requestedFileId)
|
||||
}
|
||||
atomic.AddInt32(&lookupCount, 1)
|
||||
if atomic.LoadInt32(&invalidator.calls) == 0 {
|
||||
return []string{staleUrl}, nil
|
||||
}
|
||||
return []string{freshUrl}, nil
|
||||
}
|
||||
|
||||
var fetchCount int32
|
||||
fetchFn := func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, requestedFileId string) (int, error) {
|
||||
if requestedFileId != fileId {
|
||||
return 0, fmt.Errorf("unexpected fetch file id %s", requestedFileId)
|
||||
}
|
||||
switch atomic.AddInt32(&fetchCount, 1) {
|
||||
case 1:
|
||||
if len(urlStrings) != 1 || urlStrings[0] != staleUrl {
|
||||
return 0, fmt.Errorf("first fetch should use stale url %v", urlStrings)
|
||||
}
|
||||
return 0, fmt.Errorf("404 Not Found: not found")
|
||||
case 2:
|
||||
if len(urlStrings) != 1 || urlStrings[0] != freshUrl {
|
||||
return 0, fmt.Errorf("retry fetch should use fresh url %v", urlStrings)
|
||||
}
|
||||
return copy(buffer, testData), nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unexpected extra fetch with urls %v", urlStrings)
|
||||
}
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn, invalidator)
|
||||
rc.fetchChunkDataFn = fetchFn
|
||||
defer rc.destroy()
|
||||
|
||||
buffer := make([]byte, len(testData))
|
||||
n, err := rc.ReadChunkAt(context.Background(), buffer, fileId, nil, false, 0, len(testData), true)
|
||||
if err != nil {
|
||||
t.Fatalf("expected successful retry, got %v", err)
|
||||
}
|
||||
if got := string(buffer[:n]); got != string(testData) {
|
||||
t.Fatalf("expected %q, got %q", testData, got)
|
||||
}
|
||||
if got := atomic.LoadInt32(&invalidator.calls); got != 1 {
|
||||
t.Fatalf("expected one cache invalidation, got %d", got)
|
||||
}
|
||||
if got := invalidator.lastFileId(); got != fileId {
|
||||
t.Fatalf("expected invalidated file id %s, got %s", fileId, got)
|
||||
}
|
||||
if got := atomic.LoadInt32(&lookupCount); got != 2 {
|
||||
t.Fatalf("expected lookup before fetch and after invalidation, got %d", got)
|
||||
}
|
||||
if got := atomic.LoadInt32(&fetchCount); got != 2 {
|
||||
t.Fatalf("expected stale fetch and retry fetch, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReaderCacheRemovesFailedDownloader(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
fileId := "425141,failed"
|
||||
url := "http://fast-volume-1/" + fileId
|
||||
|
||||
var lookupCount int32
|
||||
lookupFn := func(ctx context.Context, requestedFileId string) ([]string, error) {
|
||||
if requestedFileId != fileId {
|
||||
return nil, fmt.Errorf("unexpected lookup file id %s", requestedFileId)
|
||||
}
|
||||
atomic.AddInt32(&lookupCount, 1)
|
||||
return []string{url}, nil
|
||||
}
|
||||
|
||||
var fetchCount int32
|
||||
fetchFn := func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, requestedFileId string) (int, error) {
|
||||
atomic.AddInt32(&fetchCount, 1)
|
||||
return 0, fmt.Errorf("fetch failed")
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn, nil)
|
||||
rc.fetchChunkDataFn = fetchFn
|
||||
defer rc.destroy()
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
buffer := make([]byte, 8)
|
||||
_, err := rc.ReadChunkAt(context.Background(), buffer, fileId, nil, false, 0, len(buffer), true)
|
||||
if err == nil {
|
||||
t.Fatalf("read %d should fail", i+1)
|
||||
}
|
||||
}
|
||||
|
||||
if got := atomic.LoadInt32(&lookupCount); got != 2 {
|
||||
t.Fatalf("failed downloader should be removed so the second read re-lookups, got %d lookups", got)
|
||||
}
|
||||
if got := atomic.LoadInt32(&fetchCount); got != 2 {
|
||||
t.Fatalf("failed downloader should be removed so the second read refetches, got %d fetches", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReaderCacheContextCancellation tests that a reader can cancel its wait
|
||||
// while the download continues for other readers
|
||||
func TestReaderCacheContextCancellation(t *testing.T) {
|
||||
@@ -67,7 +193,7 @@ func TestReaderCacheContextCancellation(t *testing.T) {
|
||||
|
||||
// Create a ReaderCache - we can't easily test the full flow without mocking HTTP,
|
||||
// but we can test the context cancellation in readChunkAt
|
||||
rc := NewReaderCache(10, cache, nil)
|
||||
rc := NewReaderCache(10, cache, nil, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
// Pre-populate cache to avoid HTTP calls
|
||||
@@ -106,7 +232,7 @@ func TestReaderCacheFallbackToChunkCache(t *testing.T) {
|
||||
testData := []byte("fallback test data that should be found in chunk cache")
|
||||
cache.SetChunk("fallback-file", testData)
|
||||
|
||||
rc := NewReaderCache(10, cache, nil)
|
||||
rc := NewReaderCache(10, cache, nil, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
// Read should hit the chunk cache
|
||||
@@ -138,7 +264,7 @@ func TestReaderCacheMultipleReadersWaitForSameChunk(t *testing.T) {
|
||||
}
|
||||
cache.SetChunk("shared-chunk", testData)
|
||||
|
||||
rc := NewReaderCache(10, cache, nil)
|
||||
rc := NewReaderCache(10, cache, nil, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
// Launch multiple concurrent readers for the same chunk
|
||||
@@ -184,7 +310,7 @@ func TestReaderCachePartialRead(t *testing.T) {
|
||||
testData := []byte("0123456789ABCDEFGHIJ")
|
||||
cache.SetChunk("partial-read-file", testData)
|
||||
|
||||
rc := NewReaderCache(10, cache, nil)
|
||||
rc := NewReaderCache(10, cache, nil, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
tests := []struct {
|
||||
@@ -222,7 +348,7 @@ func TestReaderCacheCleanup(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
|
||||
// Create cache with limit of 3
|
||||
rc := NewReaderCache(3, cache, nil)
|
||||
rc := NewReaderCache(3, cache, nil, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
// Add data for multiple files
|
||||
@@ -259,7 +385,7 @@ func TestReaderCacheCleanup(t *testing.T) {
|
||||
// TestSingleChunkCacherDoneSignal tests that done channel is always closed
|
||||
func TestSingleChunkCacherDoneSignal(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
rc := NewReaderCache(10, cache, nil)
|
||||
rc := NewReaderCache(10, cache, nil, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
// Test that we can read even when data is in cache (done channel should work)
|
||||
@@ -317,7 +443,7 @@ func TestSingleChunkCacherLookupError(t *testing.T) {
|
||||
return nil, fmt.Errorf("lookup failed for %s", fileId)
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn)
|
||||
rc := NewReaderCache(10, cache, lookupFn, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
buffer := make([]byte, 100)
|
||||
@@ -343,7 +469,7 @@ func TestSingleChunkCacherContextCancellationDuringLookup(t *testing.T) {
|
||||
return nil, fmt.Errorf("lookup completed but reader should have cancelled")
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn)
|
||||
rc := NewReaderCache(10, cache, lookupFn, nil)
|
||||
defer rc.destroy()
|
||||
defer close(lookupCanFinish) // Ensure cleanup
|
||||
|
||||
@@ -391,7 +517,7 @@ func TestSingleChunkCacherMultipleReadersWaitForDownload(t *testing.T) {
|
||||
return nil, fmt.Errorf("simulated lookup error")
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn)
|
||||
rc := NewReaderCache(10, cache, lookupFn, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
numReaders := 5
|
||||
@@ -438,17 +564,25 @@ func TestSingleChunkCacherMultipleReadersWaitForDownload(t *testing.T) {
|
||||
// the downloaders map deduplicates in-flight downloads.
|
||||
func TestReaderCacheDownloaderDedup(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
|
||||
var lookupCount int32
|
||||
lookupGate := make(chan struct{})
|
||||
var fetchCount int32
|
||||
fetchGate := make(chan struct{})
|
||||
testData := []byte("deduplicated data")
|
||||
|
||||
lookupFn := func(ctx context.Context, fileId string) ([]string, error) {
|
||||
atomic.AddInt32(&lookupCount, 1)
|
||||
<-lookupGate
|
||||
// Return an error so we don't need to mock the HTTP fetch.
|
||||
return nil, fmt.Errorf("simulated lookup for %s", fileId)
|
||||
return []string{"http://volume/" + fileId}, nil
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn)
|
||||
fetchFn := func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, fileId string) (int, error) {
|
||||
atomic.AddInt32(&fetchCount, 1)
|
||||
<-fetchGate
|
||||
return copy(buffer, testData), nil
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn, nil)
|
||||
rc.fetchChunkDataFn = fetchFn
|
||||
defer rc.destroy()
|
||||
|
||||
const numReaders = 10
|
||||
@@ -464,13 +598,15 @@ func TestReaderCacheDownloaderDedup(t *testing.T) {
|
||||
}
|
||||
|
||||
// Allow downloads to proceed.
|
||||
close(lookupGate)
|
||||
close(fetchGate)
|
||||
wg.Wait()
|
||||
|
||||
count := atomic.LoadInt32(&lookupCount)
|
||||
if count != 1 {
|
||||
if count := atomic.LoadInt32(&lookupCount); count != 1 {
|
||||
t.Errorf("expected exactly 1 lookup call, got %d", count)
|
||||
}
|
||||
if count := atomic.LoadInt32(&fetchCount); count != 1 {
|
||||
t.Errorf("expected exactly 1 fetch call, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSingleChunkCacherOneReaderCancelsOthersContinue tests that when one reader
|
||||
@@ -487,7 +623,7 @@ func TestSingleChunkCacherOneReaderCancelsOthersContinue(t *testing.T) {
|
||||
return nil, fmt.Errorf("simulated error after delay")
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn)
|
||||
rc := NewReaderCache(10, cache, lookupFn, nil)
|
||||
defer rc.destroy()
|
||||
|
||||
cancelledReaderDone := make(chan error, 1)
|
||||
|
||||
@@ -54,7 +54,7 @@ func (store *SqliteStore) initialize(dbFile, createTable, upsertQuery string) (e
|
||||
store.SupportBucketTable = true
|
||||
store.SqlGenerator = &mysql.SqlGenMysql{
|
||||
CreateTableSqlTemplate: createTable,
|
||||
DropTableSqlTemplate: "drop table `%s`",
|
||||
DropTableSqlTemplate: "drop table if exists `%s`",
|
||||
UpsertQueryTemplate: upsertQuery,
|
||||
}
|
||||
|
||||
|
||||
+38
-29
@@ -102,10 +102,6 @@ func PrepareStreamContent(masterClient wdclient.HasLookupFileIdFunction, jwtFunc
|
||||
|
||||
type VolumeServerJwtFunction func(fileId string) string
|
||||
|
||||
type CacheInvalidator interface {
|
||||
InvalidateCache(fileId string)
|
||||
}
|
||||
|
||||
// urlSlicesEqual checks if two URL slices contain the same URLs (order-independent)
|
||||
func urlSlicesEqual(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
@@ -126,6 +122,36 @@ func urlSlicesEqual(a, b []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// retryFetchWithFreshLocations is the shared self-heal for the read paths: when a chunk fetch
|
||||
// fails, invalidate the cached volume locations, re-lookup, and call refetch only when the
|
||||
// resolved locations actually changed (so we never retry against the same servers). originalErr
|
||||
// is returned unchanged when no retry is attempted, so callers surface the real fetch failure.
|
||||
func retryFetchWithFreshLocations(ctx context.Context, invalidator CacheInvalidator, lookupFn wdclient.LookupFileIdFunctionType, fileId string, oldUrls []string, originalErr error, refetch func(newUrls []string) error) error {
|
||||
if invalidator == nil {
|
||||
return originalErr
|
||||
}
|
||||
|
||||
glog.V(0).InfofCtx(ctx, "read chunk %s failed, invalidating cache and retrying: %v", fileId, originalErr)
|
||||
invalidator.InvalidateCache(fileId)
|
||||
|
||||
newUrls, lookupErr := lookupFn(ctx, fileId)
|
||||
if lookupErr != nil {
|
||||
glog.WarningfCtx(ctx, "failed to re-lookup chunk %s after cache invalidation: %v", fileId, lookupErr)
|
||||
return fmt.Errorf("re-lookup chunk %s after cache invalidation: %w", fileId, lookupErr)
|
||||
}
|
||||
if len(newUrls) == 0 {
|
||||
glog.WarningfCtx(ctx, "re-lookup for chunk %s returned no locations, skipping retry", fileId)
|
||||
return fmt.Errorf("re-lookup chunk %s returned no locations", fileId)
|
||||
}
|
||||
if urlSlicesEqual(oldUrls, newUrls) {
|
||||
glog.V(0).InfofCtx(ctx, "re-lookup returned same locations for chunk %s, skipping retry", fileId)
|
||||
return originalErr
|
||||
}
|
||||
|
||||
glog.V(0).InfofCtx(ctx, "retrying read chunk %s with %d new locations", fileId, len(newUrls))
|
||||
return refetch(newUrls)
|
||||
}
|
||||
|
||||
func PrepareStreamContentWithThrottler(ctx context.Context, masterClient wdclient.HasLookupFileIdFunction, jwtFunc VolumeServerJwtFunction, chunks []*filer_pb.FileChunk, offset int64, size int64, downloadMaxBytesPs int64) (DoStreamContent, error) {
|
||||
glog.V(4).InfofCtx(ctx, "prepare to stream content for chunks: %d", len(chunks))
|
||||
chunkViews := ViewFromChunks(ctx, masterClient.GetLookupFileIdFunction(), chunks, offset, size)
|
||||
@@ -195,32 +221,15 @@ func PrepareStreamContentWithThrottler(ctx context.Context, masterClient wdclien
|
||||
|
||||
// If read failed, try to invalidate cache and re-lookup
|
||||
if err != nil && written == 0 {
|
||||
if invalidator, ok := masterClient.(CacheInvalidator); ok {
|
||||
glog.V(0).InfofCtx(ctx, "read chunk %s failed, invalidating cache and retrying", chunkView.FileId)
|
||||
invalidator.InvalidateCache(chunkView.FileId)
|
||||
|
||||
// Re-lookup
|
||||
newUrlStrings, lookupErr := masterClient.GetLookupFileIdFunction()(ctx, chunkView.FileId)
|
||||
if lookupErr == nil && len(newUrlStrings) > 0 {
|
||||
// Check if new URLs are different from old ones to avoid infinite retry
|
||||
if !urlSlicesEqual(urlStrings, newUrlStrings) {
|
||||
glog.V(0).InfofCtx(ctx, "retrying read chunk %s with new locations: %v", chunkView.FileId, newUrlStrings)
|
||||
_, err = retriedStreamFetchChunkData(ctx, writer, newUrlStrings, jwt, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.OffsetInChunk, int(chunkView.ViewSize))
|
||||
// Update the map so subsequent references use fresh URLs
|
||||
if err == nil {
|
||||
fileId2Url[chunkView.FileId] = newUrlStrings
|
||||
}
|
||||
} else {
|
||||
glog.V(0).InfofCtx(ctx, "re-lookup returned same locations for chunk %s, skipping retry", chunkView.FileId)
|
||||
}
|
||||
} else {
|
||||
if lookupErr != nil {
|
||||
glog.WarningfCtx(ctx, "failed to re-lookup chunk %s after cache invalidation: %v", chunkView.FileId, lookupErr)
|
||||
} else {
|
||||
glog.WarningfCtx(ctx, "re-lookup for chunk %s returned no locations, skipping retry", chunkView.FileId)
|
||||
}
|
||||
invalidator, _ := masterClient.(CacheInvalidator)
|
||||
err = retryFetchWithFreshLocations(ctx, invalidator, masterClient.GetLookupFileIdFunction(), chunkView.FileId, urlStrings, err, func(newUrls []string) error {
|
||||
_, refetchErr := retriedStreamFetchChunkData(ctx, writer, newUrls, jwt, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.OffsetInChunk, int(chunkView.ViewSize))
|
||||
if refetchErr == nil {
|
||||
// Update the map so subsequent references use fresh URLs
|
||||
fileId2Url[chunkView.FileId] = newUrls
|
||||
}
|
||||
}
|
||||
return refetchErr
|
||||
})
|
||||
}
|
||||
|
||||
offset += int64(chunkView.ViewSize)
|
||||
|
||||
@@ -177,7 +177,7 @@ func streamChunksPrefetched(
|
||||
consumeErr = err
|
||||
break
|
||||
}
|
||||
retryErr := retryWithCacheInvalidation(localCtx, writer, chunkView, result.urlStrings, jwtFunc, masterClient)
|
||||
retryErr := retryWithCacheInvalidation(localCtx, writer, chunkView, result.urlStrings, result.fetchErr, jwtFunc, masterClient)
|
||||
if retryErr != nil {
|
||||
stats.FilerHandlerCounter.WithLabelValues("chunkDownloadError").Inc()
|
||||
consumeErr = fmt.Errorf("read chunk: %w", retryErr)
|
||||
@@ -230,45 +230,25 @@ func streamChunksPrefetched(
|
||||
return nil
|
||||
}
|
||||
|
||||
// retryWithCacheInvalidation attempts to re-fetch a chunk after invalidating the URL cache.
|
||||
// This mirrors the retry logic in PrepareStreamContentWithThrottler's sequential path.
|
||||
// retryWithCacheInvalidation re-fetches a chunk via the shared location self-heal after the
|
||||
// initial fetch failed with originalErr.
|
||||
func retryWithCacheInvalidation(
|
||||
ctx context.Context,
|
||||
writer io.Writer,
|
||||
chunkView *ChunkView,
|
||||
oldUrlStrings []string,
|
||||
originalErr error,
|
||||
jwtFunc VolumeServerJwtFunction,
|
||||
masterClient wdclient.HasLookupFileIdFunction,
|
||||
) error {
|
||||
invalidator, ok := masterClient.(CacheInvalidator)
|
||||
if !ok {
|
||||
return fmt.Errorf("read chunk %s failed and no cache invalidator available", chunkView.FileId)
|
||||
}
|
||||
|
||||
glog.V(0).InfofCtx(ctx, "prefetch read chunk %s failed, invalidating cache and retrying", chunkView.FileId)
|
||||
invalidator.InvalidateCache(chunkView.FileId)
|
||||
|
||||
newUrlStrings, lookupErr := masterClient.GetLookupFileIdFunction()(ctx, chunkView.FileId)
|
||||
if lookupErr != nil {
|
||||
glog.WarningfCtx(ctx, "failed to re-lookup chunk %s after cache invalidation: %v", chunkView.FileId, lookupErr)
|
||||
return fmt.Errorf("re-lookup chunk %s: %w", chunkView.FileId, lookupErr)
|
||||
}
|
||||
if len(newUrlStrings) == 0 {
|
||||
glog.WarningfCtx(ctx, "re-lookup for chunk %s returned no locations, skipping retry", chunkView.FileId)
|
||||
return fmt.Errorf("re-lookup chunk %s: no locations", chunkView.FileId)
|
||||
}
|
||||
|
||||
if urlSlicesEqual(oldUrlStrings, newUrlStrings) {
|
||||
glog.V(0).InfofCtx(ctx, "re-lookup returned same locations for chunk %s, skipping retry", chunkView.FileId)
|
||||
return fmt.Errorf("read chunk %s failed, same locations after cache invalidation", chunkView.FileId)
|
||||
}
|
||||
|
||||
glog.V(0).InfofCtx(ctx, "retrying read chunk %s with new locations: %v", chunkView.FileId, newUrlStrings)
|
||||
jwt := jwtFunc(chunkView.FileId)
|
||||
_, err := retriedStreamFetchChunkData(
|
||||
ctx, writer, newUrlStrings, jwt,
|
||||
chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(),
|
||||
chunkView.OffsetInChunk, int(chunkView.ViewSize),
|
||||
)
|
||||
return err
|
||||
invalidator, _ := masterClient.(CacheInvalidator)
|
||||
return retryFetchWithFreshLocations(ctx, invalidator, masterClient.GetLookupFileIdFunction(), chunkView.FileId, oldUrlStrings, originalErr, func(newUrls []string) error {
|
||||
jwt := jwtFunc(chunkView.FileId)
|
||||
_, err := retriedStreamFetchChunkData(
|
||||
ctx, writer, newUrls, jwt,
|
||||
chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(),
|
||||
chunkView.OffsetInChunk, int(chunkView.ViewSize),
|
||||
)
|
||||
return err
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package kms
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"hash"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultDataKeyCacheTTL is used when caching is enabled without an explicit TTL.
|
||||
DefaultDataKeyCacheTTL = time.Hour
|
||||
// DefaultDataKeyCacheSize bounds the number of cached decrypted data keys.
|
||||
DefaultDataKeyCacheSize = 1000
|
||||
)
|
||||
|
||||
// CachedKMSProvider wraps a KMSProvider with an in-memory cache of decrypted
|
||||
// data keys. A KMS Decrypt call is deterministic for a given (ciphertext,
|
||||
// encryption context) pair, so every read of the same SSE-KMS object would
|
||||
// otherwise repeat an identical, network-bound KMS round-trip. Caching the
|
||||
// plaintext data key removes that round-trip on the read hot path — this is
|
||||
// what the cache_enabled / cache_ttl provider settings control.
|
||||
//
|
||||
// Only Decrypt is cached. GenerateDataKey must return a unique key per call,
|
||||
// and DescribeKey / GetKeyID are cheap metadata lookups, so all three pass
|
||||
// straight through to the wrapped provider via the embedded interface.
|
||||
type CachedKMSProvider struct {
|
||||
KMSProvider // wrapped provider; supplies the un-cached methods
|
||||
|
||||
ttl time.Duration
|
||||
maxEntries int
|
||||
|
||||
mu sync.Mutex
|
||||
entries map[string]*dataKeyCacheEntry
|
||||
closed bool
|
||||
}
|
||||
|
||||
type dataKeyCacheEntry struct {
|
||||
keyID string
|
||||
plaintext []byte
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
// NewCachedKMSProvider wraps provider with a decrypted-data-key cache. A
|
||||
// non-positive ttl or maxEntries falls back to the package defaults.
|
||||
func NewCachedKMSProvider(provider KMSProvider, ttl time.Duration, maxEntries int) *CachedKMSProvider {
|
||||
if ttl <= 0 {
|
||||
ttl = DefaultDataKeyCacheTTL
|
||||
}
|
||||
if maxEntries <= 0 {
|
||||
maxEntries = DefaultDataKeyCacheSize
|
||||
}
|
||||
return &CachedKMSProvider{
|
||||
KMSProvider: provider,
|
||||
ttl: ttl,
|
||||
maxEntries: maxEntries,
|
||||
entries: make(map[string]*dataKeyCacheEntry),
|
||||
}
|
||||
}
|
||||
|
||||
// Decrypt returns the plaintext data key from cache when present, otherwise
|
||||
// delegates to the wrapped provider and caches the result.
|
||||
func (c *CachedKMSProvider) Decrypt(ctx context.Context, req *DecryptRequest) (*DecryptResponse, error) {
|
||||
if req == nil || len(req.CiphertextBlob) == 0 {
|
||||
// Let the wrapped provider produce its normal validation error.
|
||||
return c.KMSProvider.Decrypt(ctx, req)
|
||||
}
|
||||
|
||||
cacheKey := dataKeyCacheKey(req)
|
||||
if resp := c.get(cacheKey); resp != nil {
|
||||
glog.V(4).Infof("KMS data key cache hit")
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
resp, err := c.KMSProvider.Decrypt(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Store our own copy, then hand the original back to the caller. The
|
||||
// caller clears the plaintext it receives (ClearSensitiveData); keeping a
|
||||
// private copy means later cache hits still return valid key material.
|
||||
c.set(cacheKey, resp)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// get returns a fresh copy of the cached response, or nil on miss/expiry. The
|
||||
// copy is essential: callers clear the returned plaintext after use, which
|
||||
// would otherwise wipe the cached key material for every subsequent reader.
|
||||
func (c *CachedKMSProvider) get(cacheKey string) *DecryptResponse {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
entry, ok := c.entries[cacheKey]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(entry.expiresAt) {
|
||||
ClearSensitiveData(entry.plaintext)
|
||||
delete(c.entries, cacheKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
plaintext := make([]byte, len(entry.plaintext))
|
||||
copy(plaintext, entry.plaintext)
|
||||
return &DecryptResponse{KeyID: entry.keyID, Plaintext: plaintext}
|
||||
}
|
||||
|
||||
// set stores a private copy of the plaintext data key.
|
||||
func (c *CachedKMSProvider) set(cacheKey string, resp *DecryptResponse) {
|
||||
if resp == nil {
|
||||
return
|
||||
}
|
||||
|
||||
plaintext := make([]byte, len(resp.Plaintext))
|
||||
copy(plaintext, resp.Plaintext)
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if c.closed {
|
||||
// A miss can finish its underlying Decrypt after Close scrubbed the
|
||||
// map; don't repopulate it with key material that won't be cleared.
|
||||
ClearSensitiveData(plaintext)
|
||||
return
|
||||
}
|
||||
|
||||
if old, exists := c.entries[cacheKey]; exists {
|
||||
// Two readers can race on the same miss and both store; wipe the
|
||||
// superseded key material instead of leaving it to linger in memory.
|
||||
ClearSensitiveData(old.plaintext)
|
||||
} else {
|
||||
c.evictIfFullLocked()
|
||||
}
|
||||
c.entries[cacheKey] = &dataKeyCacheEntry{
|
||||
keyID: resp.KeyID,
|
||||
plaintext: plaintext,
|
||||
expiresAt: time.Now().Add(c.ttl),
|
||||
}
|
||||
}
|
||||
|
||||
// evictIfFullLocked drops expired entries and, if still at capacity, the entry
|
||||
// closest to expiry. Callers must hold c.mu.
|
||||
func (c *CachedKMSProvider) evictIfFullLocked() {
|
||||
if len(c.entries) < c.maxEntries {
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
for k, entry := range c.entries {
|
||||
if now.After(entry.expiresAt) {
|
||||
ClearSensitiveData(entry.plaintext)
|
||||
delete(c.entries, k)
|
||||
}
|
||||
}
|
||||
|
||||
if len(c.entries) < c.maxEntries {
|
||||
return
|
||||
}
|
||||
|
||||
// Still full: evict the soonest-to-expire entry.
|
||||
var oldestKey string
|
||||
var oldestAt time.Time
|
||||
for k, entry := range c.entries {
|
||||
if oldestKey == "" || entry.expiresAt.Before(oldestAt) {
|
||||
oldestKey = k
|
||||
oldestAt = entry.expiresAt
|
||||
}
|
||||
}
|
||||
if oldestKey != "" {
|
||||
ClearSensitiveData(c.entries[oldestKey].plaintext)
|
||||
delete(c.entries, oldestKey)
|
||||
}
|
||||
}
|
||||
|
||||
// Close clears cached key material and closes the wrapped provider.
|
||||
func (c *CachedKMSProvider) Close() error {
|
||||
c.mu.Lock()
|
||||
c.closed = true
|
||||
for k, entry := range c.entries {
|
||||
ClearSensitiveData(entry.plaintext)
|
||||
delete(c.entries, k)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return c.KMSProvider.Close()
|
||||
}
|
||||
|
||||
// sha256Pool reuses hash states across cache-key computations so the read hot
|
||||
// path doesn't allocate a fresh one on every Decrypt.
|
||||
var sha256Pool = sync.Pool{
|
||||
New: func() interface{} { return sha256.New() },
|
||||
}
|
||||
|
||||
// dataKeyCacheKey derives a stable cache key from the ciphertext blob and the
|
||||
// encryption context. The context is part of the key because the same
|
||||
// ciphertext decrypted under a different context is a different request, and
|
||||
// caching by ciphertext alone would bypass the provider's context check.
|
||||
func dataKeyCacheKey(req *DecryptRequest) string {
|
||||
h := sha256Pool.Get().(hash.Hash)
|
||||
|
||||
// Length-prefix each field so distinct inputs cannot collide by concatenation.
|
||||
writeLengthPrefixed(h, req.CiphertextBlob)
|
||||
|
||||
keys := make([]string, 0, len(req.EncryptionContext))
|
||||
for k := range req.EncryptionContext {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
writeLengthPrefixed(h, []byte(k))
|
||||
writeLengthPrefixed(h, []byte(req.EncryptionContext[k]))
|
||||
}
|
||||
|
||||
key := string(h.Sum(nil))
|
||||
h.Reset()
|
||||
sha256Pool.Put(h)
|
||||
return key
|
||||
}
|
||||
|
||||
func writeLengthPrefixed(h hash.Hash, b []byte) {
|
||||
var lenBuf [8]byte
|
||||
binary.BigEndian.PutUint64(lenBuf[:], uint64(len(b)))
|
||||
h.Write(lenBuf[:])
|
||||
h.Write(b)
|
||||
}
|
||||
|
||||
// wrapWithCacheIfEnabled returns provider wrapped in a data-key cache when the
|
||||
// configuration enables caching, otherwise provider unchanged.
|
||||
func wrapWithCacheIfEnabled(provider KMSProvider, config *KMSConfig) KMSProvider {
|
||||
if provider == nil || config == nil || !config.CacheEnabled {
|
||||
return provider
|
||||
}
|
||||
// Avoid double-wrapping if a cached provider is somehow reused.
|
||||
if _, ok := provider.(*CachedKMSProvider); ok {
|
||||
return provider
|
||||
}
|
||||
cached := NewCachedKMSProvider(provider, config.CacheTTL, config.MaxCacheSize)
|
||||
glog.V(1).Infof("KMS data key caching enabled (ttl=%s, max=%d)", cached.ttl, cached.maxEntries)
|
||||
return cached
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package kms
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// countingKMSProvider is a minimal KMSProvider that records how many times each
|
||||
// method is invoked so tests can assert the cache actually avoids round-trips.
|
||||
type countingKMSProvider struct {
|
||||
decryptCalls int64
|
||||
generateCalls int64
|
||||
|
||||
mu sync.Mutex
|
||||
store map[string][]byte // ciphertext(string) -> plaintext data key
|
||||
}
|
||||
|
||||
func newCountingKMSProvider() *countingKMSProvider {
|
||||
return &countingKMSProvider{store: make(map[string][]byte)}
|
||||
}
|
||||
|
||||
func (p *countingKMSProvider) GenerateDataKey(ctx context.Context, req *GenerateDataKeyRequest) (*GenerateDataKeyResponse, error) {
|
||||
n := atomic.AddInt64(&p.generateCalls, 1)
|
||||
plaintext := []byte(fmt.Sprintf("datakey-%d-abcdefghijklmnopqrstuv", n))[:32]
|
||||
ciphertext := []byte(fmt.Sprintf("cipher-%d", n))
|
||||
|
||||
p.mu.Lock()
|
||||
p.store[string(ciphertext)] = append([]byte(nil), plaintext...)
|
||||
p.mu.Unlock()
|
||||
|
||||
return &GenerateDataKeyResponse{
|
||||
KeyID: req.KeyID,
|
||||
Plaintext: plaintext,
|
||||
CiphertextBlob: ciphertext,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *countingKMSProvider) Decrypt(ctx context.Context, req *DecryptRequest) (*DecryptResponse, error) {
|
||||
atomic.AddInt64(&p.decryptCalls, 1)
|
||||
|
||||
p.mu.Lock()
|
||||
plaintext, ok := p.store[string(req.CiphertextBlob)]
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("ciphertext not found")
|
||||
}
|
||||
|
||||
// Return a fresh copy, mirroring real providers that allocate per call.
|
||||
return &DecryptResponse{
|
||||
KeyID: "test-key",
|
||||
Plaintext: append([]byte(nil), plaintext...),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *countingKMSProvider) DescribeKey(ctx context.Context, req *DescribeKeyRequest) (*DescribeKeyResponse, error) {
|
||||
return &DescribeKeyResponse{KeyID: req.KeyID, KeyState: KeyStateEnabled, KeyUsage: KeyUsageEncryptDecrypt}, nil
|
||||
}
|
||||
|
||||
func (p *countingKMSProvider) GetKeyID(ctx context.Context, keyIdentifier string) (string, error) {
|
||||
return keyIdentifier, nil
|
||||
}
|
||||
|
||||
func (p *countingKMSProvider) Close() error { return nil }
|
||||
|
||||
// TestCachedProviderDecryptHitsProviderOnce is the regression test for the
|
||||
// reported bug: with caching enabled, repeated Decrypt of the same data key
|
||||
// must consult the underlying KMS only once.
|
||||
func TestCachedProviderDecryptHitsProviderOnce(t *testing.T) {
|
||||
inner := newCountingKMSProvider()
|
||||
cached := NewCachedKMSProvider(inner, time.Hour, 100)
|
||||
|
||||
ctx := context.Background()
|
||||
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateDataKey: %v", err)
|
||||
}
|
||||
|
||||
req := &DecryptRequest{CiphertextBlob: dk.CiphertextBlob}
|
||||
first, err := cached.Decrypt(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("first Decrypt: %v", err)
|
||||
}
|
||||
|
||||
// Emulate the S3 read path clearing the returned plaintext after use. A
|
||||
// correct cache must hand back an independent copy so this does not wipe
|
||||
// the cached key material.
|
||||
ClearSensitiveData(first.Plaintext)
|
||||
|
||||
second, err := cached.Decrypt(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("second Decrypt: %v", err)
|
||||
}
|
||||
|
||||
if got := atomic.LoadInt64(&inner.decryptCalls); got != 1 {
|
||||
t.Fatalf("expected underlying Decrypt to be called once, got %d", got)
|
||||
}
|
||||
|
||||
// The cached result must still be the real data key. If the cache handed
|
||||
// back the same buffer it stored, the ClearSensitiveData above would have
|
||||
// zeroed it.
|
||||
if bytes.Equal(second.Plaintext, make([]byte, len(second.Plaintext))) {
|
||||
t.Fatalf("cached plaintext was zeroed by a previous caller clearing its copy")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedProviderContextSensitivity ensures the encryption context is part
|
||||
// of the cache key: a different context must not return a stale plaintext.
|
||||
func TestCachedProviderContextSensitivity(t *testing.T) {
|
||||
inner := newCountingKMSProvider()
|
||||
cached := NewCachedKMSProvider(inner, time.Hour, 100)
|
||||
ctx := context.Background()
|
||||
|
||||
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateDataKey: %v", err)
|
||||
}
|
||||
|
||||
// Same ciphertext, two different contexts. The counting provider ignores
|
||||
// context, but the cache must still treat these as distinct entries so a
|
||||
// real provider's context check is never short-circuited.
|
||||
if _, err := cached.Decrypt(ctx, &DecryptRequest{CiphertextBlob: dk.CiphertextBlob, EncryptionContext: map[string]string{"a": "1"}}); err != nil {
|
||||
t.Fatalf("Decrypt ctx a: %v", err)
|
||||
}
|
||||
if _, err := cached.Decrypt(ctx, &DecryptRequest{CiphertextBlob: dk.CiphertextBlob, EncryptionContext: map[string]string{"a": "2"}}); err != nil {
|
||||
t.Fatalf("Decrypt ctx b: %v", err)
|
||||
}
|
||||
if got := atomic.LoadInt64(&inner.decryptCalls); got != 2 {
|
||||
t.Fatalf("expected 2 underlying Decrypt calls for distinct contexts, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedProviderTTLExpiry verifies expired entries fall through to the
|
||||
// underlying provider.
|
||||
func TestCachedProviderTTLExpiry(t *testing.T) {
|
||||
inner := newCountingKMSProvider()
|
||||
cached := NewCachedKMSProvider(inner, 20*time.Millisecond, 100)
|
||||
ctx := context.Background()
|
||||
|
||||
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateDataKey: %v", err)
|
||||
}
|
||||
req := &DecryptRequest{CiphertextBlob: dk.CiphertextBlob}
|
||||
|
||||
if _, err := cached.Decrypt(ctx, req); err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
if _, err := cached.Decrypt(ctx, req); err != nil {
|
||||
t.Fatalf("Decrypt after expiry: %v", err)
|
||||
}
|
||||
if got := atomic.LoadInt64(&inner.decryptCalls); got != 2 {
|
||||
t.Fatalf("expected 2 underlying Decrypt calls across TTL expiry, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedProviderMaxEntries verifies the cache is size-bounded.
|
||||
func TestCachedProviderMaxEntries(t *testing.T) {
|
||||
inner := newCountingKMSProvider()
|
||||
cached := NewCachedKMSProvider(inner, time.Hour, 2)
|
||||
ctx := context.Background()
|
||||
|
||||
var blobs [][]byte
|
||||
for i := 0; i < 3; i++ {
|
||||
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateDataKey: %v", err)
|
||||
}
|
||||
blobs = append(blobs, dk.CiphertextBlob)
|
||||
if _, err := cached.Decrypt(ctx, &DecryptRequest{CiphertextBlob: dk.CiphertextBlob}); err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cached.mu.Lock()
|
||||
size := len(cached.entries)
|
||||
cached.mu.Unlock()
|
||||
if size > 2 {
|
||||
t.Fatalf("cache exceeded max entries: got %d, want <= 2", size)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedProviderClearsOverwrittenPlaintext verifies that when an entry is
|
||||
// replaced (two readers racing on the same miss), the superseded key material
|
||||
// is zeroed rather than left lingering in memory.
|
||||
func TestCachedProviderClearsOverwrittenPlaintext(t *testing.T) {
|
||||
inner := newCountingKMSProvider()
|
||||
cached := NewCachedKMSProvider(inner, time.Hour, 10)
|
||||
|
||||
cached.set("dupkey", &DecryptResponse{KeyID: "k", Plaintext: []byte("0123456789abcdef0123456789abcdef")})
|
||||
|
||||
cached.mu.Lock()
|
||||
oldBuf := cached.entries["dupkey"].plaintext
|
||||
cached.mu.Unlock()
|
||||
|
||||
cached.set("dupkey", &DecryptResponse{KeyID: "k", Plaintext: []byte("ffffffffffffffffffffffffffffffff")})
|
||||
|
||||
if !bytes.Equal(oldBuf, make([]byte, len(oldBuf))) {
|
||||
t.Fatalf("superseded cache plaintext was not zeroed: %v", oldBuf)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedProviderNoWriteAfterClose verifies a store that lands after Close
|
||||
// does not repopulate the scrubbed cache with key material.
|
||||
func TestCachedProviderNoWriteAfterClose(t *testing.T) {
|
||||
inner := newCountingKMSProvider()
|
||||
cached := NewCachedKMSProvider(inner, time.Hour, 10)
|
||||
|
||||
if err := cached.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
|
||||
cached.set("k", &DecryptResponse{KeyID: "k", Plaintext: []byte("0123456789abcdef0123456789abcdef")})
|
||||
|
||||
cached.mu.Lock()
|
||||
n := len(cached.entries)
|
||||
cached.mu.Unlock()
|
||||
if n != 0 {
|
||||
t.Fatalf("cache repopulated after Close: %d entries", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddKMSProviderWiresCache is the wiring regression test: a provider
|
||||
// configured with cache_enabled must actually be handed back wrapped in a
|
||||
// caching provider (the bug was that the setting was parsed but never applied).
|
||||
func TestAddKMSProviderWiresCache(t *testing.T) {
|
||||
RegisterProvider("cache-wiring-test", func(config util.Configuration) (KMSProvider, error) {
|
||||
return newCountingKMSProvider(), nil
|
||||
})
|
||||
|
||||
mgr := &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
|
||||
if err := mgr.AddKMSProvider("p-cached", &KMSConfig{
|
||||
Provider: "cache-wiring-test",
|
||||
CacheEnabled: true,
|
||||
CacheTTL: time.Hour,
|
||||
MaxCacheSize: 10,
|
||||
}); err != nil {
|
||||
t.Fatalf("AddKMSProvider (cached): %v", err)
|
||||
}
|
||||
p, err := mgr.GetKMSProviderByName("p-cached")
|
||||
if err != nil {
|
||||
t.Fatalf("GetKMSProviderByName: %v", err)
|
||||
}
|
||||
if _, ok := p.(*CachedKMSProvider); !ok {
|
||||
t.Fatalf("expected *CachedKMSProvider when cache enabled, got %T", p)
|
||||
}
|
||||
|
||||
if err := mgr.AddKMSProvider("p-plain", &KMSConfig{
|
||||
Provider: "cache-wiring-test",
|
||||
CacheEnabled: false,
|
||||
}); err != nil {
|
||||
t.Fatalf("AddKMSProvider (plain): %v", err)
|
||||
}
|
||||
p2, err := mgr.GetKMSProviderByName("p-plain")
|
||||
if err != nil {
|
||||
t.Fatalf("GetKMSProviderByName: %v", err)
|
||||
}
|
||||
if _, ok := p2.(*CachedKMSProvider); ok {
|
||||
t.Fatalf("expected unwrapped provider when cache disabled, got %T", p2)
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,7 @@ func InitializeGlobalKMS(config *KMSConfig) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
provider = wrapWithCacheIfEnabled(provider, config)
|
||||
|
||||
globalKMSMutex.Lock()
|
||||
defer globalKMSMutex.Unlock()
|
||||
@@ -224,6 +225,10 @@ func (km *KMSManager) AddKMSProvider(name string, config *KMSConfig) error {
|
||||
return fmt.Errorf("failed to create KMS provider %s: %w", name, err)
|
||||
}
|
||||
|
||||
// Wrap with a decrypted-data-key cache when enabled so repeated reads of
|
||||
// the same SSE-KMS object avoid a KMS round-trip per read.
|
||||
provider = wrapWithCacheIfEnabled(provider, config)
|
||||
|
||||
// Store provider and configuration
|
||||
km.providers[name] = provider
|
||||
km.configs[name] = config
|
||||
|
||||
@@ -35,12 +35,11 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
|
||||
PairMap: nil,
|
||||
WantMd5: true,
|
||||
}
|
||||
genFileUrlFn := func(host, fileId string) string {
|
||||
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
if wfs.option.VolumeServerAccess == "filerProxy" {
|
||||
fileUrl = fmt.Sprintf("http://%s/?proxyChunkId=%s", wfs.getCurrentFiler(), fileId)
|
||||
if wfs.option.VolumeServerAccess == "filerProxy" {
|
||||
// getCurrentFiler() can change on failover, so read it per attempt.
|
||||
uploadOption.GenUploadUrl = func(host, fileId string) string {
|
||||
return fmt.Sprintf("http://%s/?proxyChunkId=%s", wfs.getCurrentFiler(), fileId)
|
||||
}
|
||||
return fileUrl
|
||||
}
|
||||
|
||||
fileId, uploadResult, err, data := uploader.UploadWithRetry(
|
||||
@@ -54,7 +53,7 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
|
||||
DataCenter: wfs.option.DataCenter,
|
||||
Path: assignPath,
|
||||
},
|
||||
uploadOption, genFileUrlFn, reader,
|
||||
uploadOption, reader,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -161,27 +161,26 @@ func (b *MessageQueueBroker) assignAndUpload(targetFile string, data []byte) (fi
|
||||
return
|
||||
}
|
||||
|
||||
uploadOption := &operation.UploadOption{
|
||||
Cipher: b.option.Cipher,
|
||||
}
|
||||
if b.option.VolumeServerAccess == "filerProxy" {
|
||||
// b.currentFiler can change on failover, so read it per attempt.
|
||||
uploadOption.GenUploadUrl = func(host, fileId string) string {
|
||||
return fmt.Sprintf("http://%s/?proxyChunkId=%s", b.currentFiler, fileId)
|
||||
}
|
||||
}
|
||||
|
||||
fileId, uploadResult, err, _ = uploader.UploadWithRetry(
|
||||
b,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: b.option.DefaultReplication,
|
||||
Collection: "topics",
|
||||
// TtlSec: wfs.option.TtlSec,
|
||||
// DiskType: string(wfs.option.DiskType),
|
||||
DataCenter: b.option.DataCenter,
|
||||
Path: targetFile,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Cipher: b.option.Cipher,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
if b.option.VolumeServerAccess == "filerProxy" {
|
||||
fileUrl = fmt.Sprintf("http://%s/?proxyChunkId=%s", b.currentFiler, fileId)
|
||||
}
|
||||
return fileUrl
|
||||
DataCenter: b.option.DataCenter,
|
||||
Path: targetFile,
|
||||
},
|
||||
uploadOption,
|
||||
reader,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -479,9 +479,6 @@ func saveParquetFileToPartitionDir(filerClient filer_pb.FilerClient, sourceFile
|
||||
MimeType: "application/vnd.apache.parquet",
|
||||
PairMap: nil,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
},
|
||||
io.NewSectionReader(sourceFile, i*chunkSize, chunkSize),
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
@@ -100,7 +100,7 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
|
||||
fileSize := filer.FileSize(entry)
|
||||
visibleIntervals, _ := filer.NonOverlappingVisibleIntervals(context.Background(), lookupFileIdFn, entry.Chunks, 0, int64(fileSize))
|
||||
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, 0, int64(fileSize))
|
||||
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn)
|
||||
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn, nil)
|
||||
readerAt := filer.NewChunkReaderAtFromClient(context.Background(), readerCache, chunkViews, int64(fileSize), filer.DefaultPrefetchCount)
|
||||
|
||||
// create parquet reader
|
||||
|
||||
@@ -61,6 +61,11 @@ func LookupVolumeId(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vid st
|
||||
return results[vid], err
|
||||
}
|
||||
|
||||
// InvalidateVolumeIdLocationCache drops cached locations for vid so the next lookup re-queries the master.
|
||||
func InvalidateVolumeIdLocationCache(vid string) {
|
||||
vc.Delete(vid)
|
||||
}
|
||||
|
||||
// LookupVolumeIds find volume locations by cache and actual lookup
|
||||
func LookupVolumeIds(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vids []string) (map[string]*LookupResult, error) {
|
||||
ret := make(map[string]*LookupResult)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
type fakeLookupServer struct {
|
||||
master_pb.UnimplementedSeaweedServer
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
locations int
|
||||
}
|
||||
|
||||
func (s *fakeLookupServer) LookupVolume(_ context.Context, req *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.calls++
|
||||
resp := &master_pb.LookupVolumeResponse{}
|
||||
for _, vid := range req.VolumeOrFileIds {
|
||||
var locs []*master_pb.Location
|
||||
for i := 0; i < s.locations; i++ {
|
||||
locs = append(locs, &master_pb.Location{Url: fmt.Sprintf("10.0.0.%d:8080", i)})
|
||||
}
|
||||
resp.VolumeIdLocations = append(resp.VolumeIdLocations, &master_pb.LookupVolumeResponse_VolumeIdLocation{
|
||||
VolumeOrFileId: vid,
|
||||
Locations: locs,
|
||||
})
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// TestLookupVolumeIdCacheInvalidation reproduces the stale-lookup scenario: a
|
||||
// volume that briefly reports too few replicas would be cached for the full TTL,
|
||||
// so writes kept failing even after the master re-registered the missing replica.
|
||||
// InvalidateVolumeIdLocationCache forces the next lookup to re-query the master.
|
||||
func TestLookupVolumeIdCacheInvalidation(t *testing.T) {
|
||||
fake := &fakeLookupServer{locations: 1}
|
||||
master := startFakeMasterServer(t, fake)
|
||||
masterFn := func(context.Context) pb.ServerAddress { return master }
|
||||
dial := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
|
||||
const vid = "778899"
|
||||
InvalidateVolumeIdLocationCache(vid)
|
||||
|
||||
// first lookup queries the master and caches the single, under-replicated location
|
||||
r1, err := LookupVolumeId(masterFn, dial, vid)
|
||||
if err != nil {
|
||||
t.Fatalf("first lookup: %v", err)
|
||||
}
|
||||
if len(r1.Locations) != 1 {
|
||||
t.Fatalf("first lookup locations = %d, want 1", len(r1.Locations))
|
||||
}
|
||||
|
||||
// a second lookup is served from cache, so the master is not queried again
|
||||
if _, err := LookupVolumeId(masterFn, dial, vid); err != nil {
|
||||
t.Fatalf("second lookup: %v", err)
|
||||
}
|
||||
fake.mu.Lock()
|
||||
calls := fake.calls
|
||||
fake.locations = 2 // master heals: both replicas are registered again
|
||||
fake.mu.Unlock()
|
||||
if calls != 1 {
|
||||
t.Fatalf("expected a cache hit, master queried %d times", calls)
|
||||
}
|
||||
|
||||
// invalidation drops the stale entry, so the next lookup re-queries and sees both replicas
|
||||
InvalidateVolumeIdLocationCache(vid)
|
||||
r3, err := LookupVolumeId(masterFn, dial, vid)
|
||||
if err != nil {
|
||||
t.Fatalf("third lookup: %v", err)
|
||||
}
|
||||
if len(r3.Locations) != 2 {
|
||||
t.Fatalf("after invalidation locations = %d, want 2", len(r3.Locations))
|
||||
}
|
||||
}
|
||||
@@ -60,3 +60,13 @@ func (vc *VidCache) Set(vid string, locations []Location, duration time.Duration
|
||||
NextRefreshTime: time.Now().Add(duration),
|
||||
}
|
||||
}
|
||||
|
||||
func (vc *VidCache) Delete(vid string) {
|
||||
id, err := strconv.ParseUint(vid, 10, 32)
|
||||
if err != nil || id == 0 {
|
||||
return
|
||||
}
|
||||
vc.Lock()
|
||||
defer vc.Unlock()
|
||||
delete(vc.cache, uint32(id))
|
||||
}
|
||||
@@ -25,6 +25,23 @@ func TestCaching(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// a stale under-replicated result must not linger for the full cache TTL
|
||||
func TestCachingDelete(t *testing.T) {
|
||||
var vc VidCache
|
||||
locations := []Location{{Url: "a.com:8080"}}
|
||||
vc.Set("123", locations, time.Minute)
|
||||
if ret, _ := vc.Get("123"); ret == nil {
|
||||
t.Fatal("expected vid 123 to be cached")
|
||||
}
|
||||
vc.Delete("123")
|
||||
if ret, _ := vc.Get("123"); ret != nil {
|
||||
t.Fatal("expected vid 123 to be evicted after Delete")
|
||||
}
|
||||
// deleting a missing or out-of-range id must not panic
|
||||
vc.Delete("123")
|
||||
vc.Delete("4294967296")
|
||||
}
|
||||
|
||||
// a single large volume id must not allocate an entry per id below it
|
||||
func TestCachingLargeVolumeId(t *testing.T) {
|
||||
var vc VidCache
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
@@ -18,6 +19,11 @@ import (
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// ErrTruncatedBody tags a source read that ended before the expected bytes
|
||||
// arrived, so callers can tell a truncated input (client abort, reverse-proxy
|
||||
// timeout) apart from a volume-server upload fault.
|
||||
var ErrTruncatedBody = errors.New("truncated request body")
|
||||
|
||||
// ChunkedUploadResult contains the result of a chunked upload
|
||||
type ChunkedUploadResult struct {
|
||||
FileChunks []*filer_pb.FileChunk
|
||||
@@ -104,6 +110,9 @@ uploadLoop:
|
||||
// before any data (offset=0,got=0) from mid-stream truncation.
|
||||
// A bare io.ErrUnexpectedEOF is not actionable on its own (see #9149).
|
||||
wrapped := fmt.Errorf("read chunk at offset %d (got %d bytes): %w", chunkOffset, dataSize, err)
|
||||
if errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
wrapped = fmt.Errorf("%w: %w", ErrTruncatedBody, wrapped)
|
||||
}
|
||||
glog.V(2).Infof("UploadReaderInChunks: %v", wrapped)
|
||||
chunkBufferPool.Put(bytesBuffer)
|
||||
<-bytesBufferLimitChan
|
||||
|
||||
@@ -372,3 +372,46 @@ func TestUploadReaderInChunksReaderFailure(t *testing.T) {
|
||||
t.Logf("✓ Got partial result on read failure: chunks=%d, totalSize=%d",
|
||||
len(result.FileChunks), result.TotalSize)
|
||||
}
|
||||
|
||||
// truncatedReader yields some bytes then reports io.ErrUnexpectedEOF, mimicking a
|
||||
// request body cut short by a client abort or reverse-proxy timeout.
|
||||
type truncatedReader struct {
|
||||
data []byte
|
||||
pos int
|
||||
}
|
||||
|
||||
func (r *truncatedReader) Read(p []byte) (int, error) {
|
||||
if r.pos >= len(r.data) {
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
n := copy(p, r.data[r.pos:])
|
||||
r.pos += n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func TestUploadReaderInChunksTagsTruncatedBody(t *testing.T) {
|
||||
reader := &truncatedReader{data: bytes.Repeat([]byte("x"), 10000)}
|
||||
|
||||
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) {
|
||||
return nil, &AssignResult{Fid: "test-fid,1234", Url: "http://test-volume:8080", Count: 1}, nil
|
||||
}
|
||||
uploadFunc := func(ctx context.Context, data []byte, option *UploadOption) (*UploadResult, error) {
|
||||
return &UploadResult{Size: uint32(len(data))}, nil
|
||||
}
|
||||
|
||||
_, err := UploadReaderInChunks(context.Background(), reader, &ChunkedUploadOption{
|
||||
ChunkSize: 8 * 1024,
|
||||
Collection: "test",
|
||||
AssignFunc: assignFunc,
|
||||
UploadFunc: uploadFunc,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for a truncated body")
|
||||
}
|
||||
if !errors.Is(err, ErrTruncatedBody) {
|
||||
t.Errorf("expected ErrTruncatedBody, got %v", err)
|
||||
}
|
||||
if !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
t.Errorf("expected io.ErrUnexpectedEOF to remain in the chain, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,21 @@ import (
|
||||
util_http_client "github.com/seaweedfs/seaweedfs/weed/util/http/client"
|
||||
)
|
||||
|
||||
// GenUploadUrlProxy returns a function that builds a chunk upload URL via the
|
||||
// filer proxy. Identical to the inline logic used by weed mount -filerProxy
|
||||
// and weed filer gateway:
|
||||
//
|
||||
// - without filerProxy: "http://{host}/{fileId}"
|
||||
// - with filerProxy: "http://{filerAddress}/?proxyChunkId={fileId}"
|
||||
func GenUploadUrlProxy(filerAddress string) func(host, fileId string) string {
|
||||
return func(host, fileId string) string {
|
||||
if filerAddress == "" {
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
}
|
||||
return fmt.Sprintf("http://%s/?proxyChunkId=%s", filerAddress, fileId)
|
||||
}
|
||||
}
|
||||
|
||||
type UploadOption struct {
|
||||
UploadUrl string
|
||||
Filename string
|
||||
@@ -43,8 +58,9 @@ type UploadOption struct {
|
||||
Md5 string
|
||||
WantMd5 bool // compute Content-MD5 from the data when Md5 is unset and the upload is not ciphered
|
||||
BytesBuffer *bytes.Buffer
|
||||
SourceUrl string // optional: for logging when reading from a remote source
|
||||
MaxAttempts int // <=0 uses the default
|
||||
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}"
|
||||
}
|
||||
|
||||
type UploadResult struct {
|
||||
@@ -153,7 +169,7 @@ func NewUploaderWithHttpClient(httpClient HTTPClient) *Uploader {
|
||||
}
|
||||
}
|
||||
|
||||
func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, host string, auth security.EncodedJwt, err error), uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, data []byte) (fileId string, uploadResult *UploadResult, err error) {
|
||||
func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, host string, auth security.EncodedJwt, err error), uploadOption *UploadOption, data []byte) (fileId string, uploadResult *UploadResult, err error) {
|
||||
doUploadFunc := func() error {
|
||||
var host string
|
||||
var auth security.EncodedJwt
|
||||
@@ -162,7 +178,11 @@ func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, ho
|
||||
return err
|
||||
}
|
||||
|
||||
uploadOption.UploadUrl = genFileUrlFn(host, fileId)
|
||||
genUrl := uploadOption.GenUploadUrl
|
||||
if genUrl == nil {
|
||||
genUrl = func(host, fileId string) string { return fmt.Sprintf("http://%s/%s", host, fileId) }
|
||||
}
|
||||
uploadOption.UploadUrl = genUrl(host, fileId)
|
||||
uploadOption.Jwt = auth
|
||||
|
||||
uploadResult, err = uploader.retriedUploadData(context.Background(), data, uploadOption)
|
||||
@@ -183,7 +203,7 @@ func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, ho
|
||||
|
||||
// UploadWithRetry will retry both assigning volume request and uploading content
|
||||
// The option parameter does not need to specify UploadUrl and Jwt, which will come from assigning volume.
|
||||
func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assignRequest *filer_pb.AssignVolumeRequest, uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
|
||||
func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assignRequest *filer_pb.AssignVolumeRequest, uploadOption *UploadOption, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
|
||||
bytesReader, ok := reader.(*util.BytesReader)
|
||||
if ok {
|
||||
data = bytesReader.Bytes
|
||||
@@ -234,7 +254,7 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
|
||||
err = fmt.Errorf("filerGrpcAddress assign volume: %w", grpcAssignErr)
|
||||
}
|
||||
return
|
||||
}, uploadOption, genFileUrlFn, data)
|
||||
}, uploadOption, data)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -107,9 +107,7 @@ func TestUploadWithRetryDataReassignsOnVolumeSizeExceeded(t *testing.T) {
|
||||
return "1,first", "volume-a", "", nil
|
||||
}
|
||||
return "2,second", "volume-b", "", nil
|
||||
}, &UploadOption{Filename: "test.bin"}, func(host, fileId string) string {
|
||||
return "http://" + host + "/" + fileId
|
||||
}, []byte("abc"))
|
||||
}, &UploadOption{Filename: "test.bin"}, []byte("abc"))
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("expected success after reassignment, got %v", err)
|
||||
@@ -210,7 +208,6 @@ func TestUploadWithRetryBoundsAssignVolume(t *testing.T) {
|
||||
_, _, err, _ := uploader.UploadWithRetry(client,
|
||||
&filer_pb.AssignVolumeRequest{Count: 1},
|
||||
&UploadOption{Filename: "test.bin"},
|
||||
func(host, fileId string) string { return "http://" + host + "/" + fileId },
|
||||
bytes.NewReader([]byte("abc")),
|
||||
)
|
||||
done <- err
|
||||
|
||||
+99
-148
@@ -2,6 +2,7 @@ package pb
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
@@ -17,6 +18,17 @@ import (
|
||||
// LogFileReaderFn creates an io.ReadCloser for a set of file chunks.
|
||||
type LogFileReaderFn func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error)
|
||||
|
||||
// logEntryChannelSize bounds decoded entries in flight per filer stream.
|
||||
const logEntryChannelSize = 512
|
||||
|
||||
// maxLogEntrySize guards the per-entry allocation against a corrupt size
|
||||
// prefix, mirroring the filer package's unexported constant.
|
||||
const maxLogEntrySize = 1 << 30
|
||||
|
||||
// errReaderStopped signals that the entry consumer asked to stop (the merge
|
||||
// loop aborted or the caller hit a processing error). It is not a read failure.
|
||||
var errReaderStopped = errors.New("log entry reader stopped")
|
||||
|
||||
// PathFilter holds subscription path filtering parameters, matching the
|
||||
// server-side eachEventNotificationFn filtering logic.
|
||||
type PathFilter struct {
|
||||
@@ -30,8 +42,8 @@ type PathFilter struct {
|
||||
// (same algorithm as the server's OrderedLogVisitor), applies path filtering,
|
||||
// and invokes processEventFn for each matching event.
|
||||
//
|
||||
// Filers are read in parallel (one goroutine per filer). Within each filer,
|
||||
// the next file is prefetched while the current file's entries are consumed.
|
||||
// Filers are read in parallel (one goroutine per filer), each streaming
|
||||
// entries through a bounded channel.
|
||||
func ReadLogFileRefs(
|
||||
refs []*filer_pb.LogFileChunkRef,
|
||||
newReader LogFileReaderFn,
|
||||
@@ -61,73 +73,14 @@ func ReadLogFileRefs(
|
||||
return
|
||||
}
|
||||
|
||||
// Single filer fast path: no merge heap needed.
|
||||
if len(filerOrder) == 1 {
|
||||
return readFilerFilesWithPrefetch(perFiler[filerOrder[0]], newReader, startTsNs, stopTsNs, filter, processEventFn)
|
||||
}
|
||||
|
||||
// Multiple filers: read each in parallel with prefetching, merge via min-heap.
|
||||
return readMultiFilersMerged(filerOrder, perFiler, newReader, startTsNs, stopTsNs, filter, processEventFn)
|
||||
return readFilersMerged(filerOrder, perFiler, newReader, startTsNs, stopTsNs, filter, processEventFn)
|
||||
}
|
||||
|
||||
// readFilerFilesWithPrefetch reads files for a single filer, prefetching the
|
||||
// next file while processing entries from the current one.
|
||||
func readFilerFilesWithPrefetch(
|
||||
refs []*filer_pb.LogFileChunkRef,
|
||||
newReader LogFileReaderFn,
|
||||
startTsNs, stopTsNs int64,
|
||||
filter PathFilter,
|
||||
processEventFn ProcessMetadataFunc,
|
||||
) (lastTsNs int64, err error) {
|
||||
|
||||
type prefetchResult struct {
|
||||
entries []*filer_pb.LogEntry
|
||||
err error
|
||||
}
|
||||
|
||||
startPrefetch := func(ref *filer_pb.LogFileChunkRef) chan prefetchResult {
|
||||
ch := make(chan prefetchResult, 1)
|
||||
go func() {
|
||||
entries, readErr := readLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs)
|
||||
ch <- prefetchResult{entries, readErr}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
var pendingCh chan prefetchResult
|
||||
if len(refs) > 0 {
|
||||
pendingCh = startPrefetch(refs[0])
|
||||
}
|
||||
|
||||
for i, ref := range refs {
|
||||
result := <-pendingCh
|
||||
|
||||
// Start prefetching next file while we process current
|
||||
if i+1 < len(refs) {
|
||||
pendingCh = startPrefetch(refs[i+1])
|
||||
}
|
||||
|
||||
if result.err != nil {
|
||||
if isChunkNotFound(result.err) {
|
||||
glog.V(0).Infof("skip log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
|
||||
continue
|
||||
}
|
||||
return lastTsNs, fmt.Errorf("read log file filer=%s ts=%d: %w", ref.FilerId, ref.FileTsNs, result.err)
|
||||
}
|
||||
|
||||
for _, logEntry := range result.entries {
|
||||
lastTsNs, err = processOneLogEntry(logEntry, filter, processEventFn)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// readMultiFilersMerged reads files from multiple filers in parallel (one goroutine
|
||||
// per filer with prefetching), then merges entries in timestamp order via min-heap.
|
||||
func readMultiFilersMerged(
|
||||
// readFilersMerged reads files from each filer in parallel (one producer
|
||||
// goroutine per filer streaming decoded entries through a bounded channel),
|
||||
// then merges entries in timestamp order via min-heap. A single filer is the
|
||||
// degenerate one-stream merge.
|
||||
func readFilersMerged(
|
||||
filerOrder []string,
|
||||
perFiler map[string][]*filer_pb.LogFileChunkRef,
|
||||
newReader LogFileReaderFn,
|
||||
@@ -142,14 +95,19 @@ func readMultiFilersMerged(
|
||||
}
|
||||
|
||||
streams := make([]filerStream, len(filerOrder))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// A genuine (non chunk-not-found) read error must fail the whole replay: the
|
||||
// caller advances its cursor only on success, so a swallowed error leaves a
|
||||
// permanent gap. stop aborts the other readers; fatalErr is read on exit.
|
||||
//
|
||||
// Closing stop is the only cleanup: producers observe it at every send and
|
||||
// every file boundary and exit on their own. An abort must not wait for
|
||||
// them — a producer can be wedged in an uncancellable chunk read, and
|
||||
// joining it would stall the caller's retry loop behind a dead connection.
|
||||
stop := make(chan struct{})
|
||||
var stopOnce sync.Once
|
||||
closeStop := func() { stopOnce.Do(func() { close(stop) }) }
|
||||
defer closeStop()
|
||||
var fatalMu sync.Mutex
|
||||
var fatalErr error
|
||||
setFatal := func(e error) {
|
||||
@@ -160,35 +118,33 @@ func readMultiFilersMerged(
|
||||
fatalMu.Unlock()
|
||||
closeStop()
|
||||
}
|
||||
fatal := func() error {
|
||||
fatalMu.Lock()
|
||||
defer fatalMu.Unlock()
|
||||
return fatalErr
|
||||
}
|
||||
|
||||
for i, filerId := range filerOrder {
|
||||
entryCh := make(chan *filer_pb.LogEntry, 512)
|
||||
entryCh := make(chan *filer_pb.LogEntry, logEntryChannelSize)
|
||||
streams[i] = filerStream{filerId: filerId, entryCh: entryCh}
|
||||
|
||||
wg.Add(1)
|
||||
go func(refs []*filer_pb.LogFileChunkRef, ch chan *filer_pb.LogEntry) {
|
||||
defer wg.Done()
|
||||
defer close(ch)
|
||||
readFilerFilesToChannel(refs, newReader, startTsNs, stopTsNs, ch, stop, setFatal)
|
||||
}(perFiler[filerId], entryCh)
|
||||
}
|
||||
|
||||
// Stop readers, drain channels so none block on a send, then wait for exit.
|
||||
drainAndWait := func() {
|
||||
closeStop()
|
||||
for i := range streams {
|
||||
for range streams[i].entryCh {
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// Seed the min-heap with the first entry from each filer
|
||||
pq := &logEntryHeap{}
|
||||
heap.Init(pq)
|
||||
for i := range streams {
|
||||
if entry, ok := <-streams[i].entryCh; ok {
|
||||
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: i})
|
||||
select {
|
||||
case entry, ok := <-streams[i].entryCh:
|
||||
if ok {
|
||||
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: i})
|
||||
}
|
||||
case <-stop:
|
||||
return lastTsNs, fatal()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,11 +154,7 @@ func readMultiFilersMerged(
|
||||
// aborted; lock-free bail on the hot path.
|
||||
select {
|
||||
case <-stop:
|
||||
drainAndWait()
|
||||
fatalMu.Lock()
|
||||
fe := fatalErr
|
||||
fatalMu.Unlock()
|
||||
return lastTsNs, fe
|
||||
return lastTsNs, fatal()
|
||||
default:
|
||||
}
|
||||
|
||||
@@ -210,20 +162,22 @@ func readMultiFilersMerged(
|
||||
|
||||
lastTsNs, err = processOneLogEntry(item.entry, filter, processEventFn)
|
||||
if err != nil {
|
||||
drainAndWait()
|
||||
return
|
||||
}
|
||||
|
||||
if entry, ok := <-streams[item.filerIdx].entryCh; ok {
|
||||
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: item.filerIdx})
|
||||
select {
|
||||
case entry, ok := <-streams[item.filerIdx].entryCh:
|
||||
if ok {
|
||||
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: item.filerIdx})
|
||||
}
|
||||
case <-stop:
|
||||
return lastTsNs, fatal()
|
||||
}
|
||||
}
|
||||
|
||||
drainAndWait()
|
||||
fatalMu.Lock()
|
||||
fe := fatalErr
|
||||
fatalMu.Unlock()
|
||||
if fe != nil {
|
||||
// All channels closed: every producer has finished (setFatal, if any,
|
||||
// happened before its close).
|
||||
if fe := fatal(); fe != nil {
|
||||
return lastTsNs, fe
|
||||
}
|
||||
return
|
||||
@@ -237,53 +191,45 @@ func readFilerFilesToChannel(
|
||||
stop <-chan struct{},
|
||||
setFatal func(error),
|
||||
) {
|
||||
type prefetchResult struct {
|
||||
entries []*filer_pb.LogEntry
|
||||
err error
|
||||
var sent int
|
||||
sendEntry := func(entry *filer_pb.LogEntry) error {
|
||||
// Prefer stop over a send the buffer could still absorb, so an aborted
|
||||
// producer quits at the next entry instead of filling the channel.
|
||||
select {
|
||||
case <-stop:
|
||||
return errReaderStopped
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case ch <- entry:
|
||||
sent++
|
||||
return nil
|
||||
case <-stop:
|
||||
return errReaderStopped
|
||||
}
|
||||
}
|
||||
|
||||
startPrefetch := func(ref *filer_pb.LogFileChunkRef) chan prefetchResult {
|
||||
resultCh := make(chan prefetchResult, 1)
|
||||
go func() {
|
||||
entries, err := readLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs)
|
||||
resultCh <- prefetchResult{entries, err}
|
||||
}()
|
||||
return resultCh
|
||||
}
|
||||
|
||||
var pendingCh chan prefetchResult
|
||||
if len(refs) > 0 {
|
||||
pendingCh = startPrefetch(refs[0])
|
||||
}
|
||||
|
||||
for i, ref := range refs {
|
||||
var result prefetchResult
|
||||
for _, ref := range refs {
|
||||
select {
|
||||
case result = <-pendingCh:
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
if i+1 < len(refs) {
|
||||
pendingCh = startPrefetch(refs[i+1])
|
||||
}
|
||||
|
||||
if result.err != nil {
|
||||
if isChunkNotFound(result.err) {
|
||||
glog.V(0).Infof("skip log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
|
||||
continue
|
||||
}
|
||||
glog.Errorf("read log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
|
||||
setFatal(fmt.Errorf("read log file filer=%s ts=%d: %w", ref.FilerId, ref.FileTsNs, result.err))
|
||||
sentBefore := sent
|
||||
streamErr := streamLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs, sendEntry)
|
||||
if streamErr == errReaderStopped {
|
||||
return
|
||||
}
|
||||
|
||||
for _, entry := range result.entries {
|
||||
select {
|
||||
case ch <- entry:
|
||||
case <-stop:
|
||||
return
|
||||
if streamErr != nil {
|
||||
if isChunkNotFound(streamErr) {
|
||||
// A mid-file not-found still delivered the readable prefix; say so
|
||||
// rather than pretending the whole file was skipped.
|
||||
glog.V(0).Infof("skip log file filer=%s ts=%d after %d entries: %v", ref.FilerId, ref.FileTsNs, sent-sentBefore, streamErr)
|
||||
continue
|
||||
}
|
||||
setFatal(fmt.Errorf("read log file filer=%s ts=%d: %w", ref.FilerId, ref.FileTsNs, streamErr))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -352,45 +298,50 @@ func (h *logEntryHeap) Pop() any {
|
||||
|
||||
// --- log file parsing (uses io.ReadFull for correct partial-read handling) ---
|
||||
|
||||
func readLogFileEntries(newReader LogFileReaderFn, chunks []*filer_pb.FileChunk, startTsNs, stopTsNs int64) ([]*filer_pb.LogEntry, error) {
|
||||
// streamLogFileEntries reads a log file's chunks and invokes eachFn for every
|
||||
// entry as it is decoded, without buffering the whole file: a multi-GB log
|
||||
// file costs one entry plus the chunk reader's buffer at a time, not O(file
|
||||
// size). An eachFn error stops the read and is propagated verbatim.
|
||||
func streamLogFileEntries(newReader LogFileReaderFn, chunks []*filer_pb.FileChunk, startTsNs, stopTsNs int64, eachFn func(*filer_pb.LogEntry) error) error {
|
||||
reader, err := newReader(chunks)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create reader: %w", err)
|
||||
return fmt.Errorf("create reader: %w", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
sizeBuf := make([]byte, 4)
|
||||
var entries []*filer_pb.LogEntry
|
||||
|
||||
for {
|
||||
_, err := io.ReadFull(reader, sizeBuf)
|
||||
if err != nil {
|
||||
if _, err := io.ReadFull(reader, sizeBuf); err != nil {
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
break
|
||||
return nil
|
||||
}
|
||||
return entries, err
|
||||
return err
|
||||
}
|
||||
|
||||
size := util.BytesToUint32(sizeBuf)
|
||||
if size > maxLogEntrySize {
|
||||
return fmt.Errorf("entry size %d exceeds %d", size, maxLogEntrySize)
|
||||
}
|
||||
entryData := make([]byte, size)
|
||||
_, err = io.ReadFull(reader, entryData)
|
||||
if err != nil {
|
||||
return entries, err
|
||||
if _, err := io.ReadFull(reader, entryData); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logEntry := &filer_pb.LogEntry{}
|
||||
if err = proto.Unmarshal(entryData, logEntry); err != nil {
|
||||
return entries, err
|
||||
if err := proto.Unmarshal(entryData, logEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if logEntry.TsNs <= startTsNs {
|
||||
continue
|
||||
}
|
||||
if stopTsNs != 0 && logEntry.TsNs > stopTsNs {
|
||||
break
|
||||
return nil
|
||||
}
|
||||
|
||||
entries = append(entries, logEntry)
|
||||
if err := eachFn(logEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
@@ -2,8 +2,10 @@ package pb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -145,10 +147,10 @@ func (t *testLogFiles) totalEvents() int {
|
||||
return total
|
||||
}
|
||||
|
||||
// TestReadLogFileRefsMergeOrder verifies that entries from multiple filers are
|
||||
// delivered in correct timestamp order.
|
||||
func TestReadLogFileRefsMergeOrder(t *testing.T) {
|
||||
files := newTestLogFiles(3, 2, 50, 0)
|
||||
// assertOrderedReplay reads all refs and checks every event arrives exactly
|
||||
// once, in timestamp order.
|
||||
func assertOrderedReplay(t *testing.T, files *testLogFiles) {
|
||||
t.Helper()
|
||||
|
||||
var timestamps []int64
|
||||
_, err := ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
|
||||
@@ -161,20 +163,21 @@ func TestReadLogFileRefsMergeOrder(t *testing.T) {
|
||||
t.Fatalf("ReadLogFileRefs: %v", err)
|
||||
}
|
||||
|
||||
expected := files.totalEvents()
|
||||
if len(timestamps) != expected {
|
||||
t.Fatalf("expected %d events, got %d", expected, len(timestamps))
|
||||
if got, want := len(timestamps), files.totalEvents(); got != want {
|
||||
t.Fatalf("expected %d events, got %d", want, got)
|
||||
}
|
||||
|
||||
for i := 1; i < len(timestamps); i++ {
|
||||
if timestamps[i] < timestamps[i-1] {
|
||||
t.Errorf("out of order at index %d: ts[%d]=%d > ts[%d]=%d",
|
||||
t.Fatalf("out of order at index %d: ts[%d]=%d > ts[%d]=%d",
|
||||
i, i-1, timestamps[i-1], i, timestamps[i])
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("Verified %d events from 3 filers in correct timestamp order", len(timestamps))
|
||||
// TestReadLogFileRefsMergeOrder verifies that entries from multiple filers are
|
||||
// delivered in correct timestamp order.
|
||||
func TestReadLogFileRefsMergeOrder(t *testing.T) {
|
||||
assertOrderedReplay(t, newTestLogFiles(3, 2, 50, 0))
|
||||
}
|
||||
|
||||
// TestReadLogFileRefsPathFilter verifies path filtering including system log exclusion.
|
||||
@@ -218,7 +221,7 @@ func TestReadLogFileRefsPathFilter(t *testing.T) {
|
||||
|
||||
// TestDirectReadVsServerSideThroughput compares:
|
||||
// - Server-side: sequential file read → gRPC send per event
|
||||
// - Client direct-read: parallel filers + prefetching + no gRPC
|
||||
// - Client direct-read: parallel filers + streaming + no gRPC
|
||||
func TestDirectReadVsServerSideThroughput(t *testing.T) {
|
||||
const (
|
||||
numFilers = 3
|
||||
@@ -255,7 +258,7 @@ func TestDirectReadVsServerSideThroughput(t *testing.T) {
|
||||
})
|
||||
|
||||
var directRate float64
|
||||
t.Run("client_direct_read_parallel_prefetch", func(t *testing.T) {
|
||||
t.Run("client_direct_read_parallel_streaming", func(t *testing.T) {
|
||||
var processed int64
|
||||
start := time.Now()
|
||||
|
||||
@@ -270,12 +273,12 @@ func TestDirectReadVsServerSideThroughput(t *testing.T) {
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
directRate = float64(processed) / elapsed.Seconds()
|
||||
t.Logf("direct-read: %d events %v %6.0f events/sec (%d filers parallel + prefetch, no gRPC)",
|
||||
t.Logf("direct-read: %d events %v %6.0f events/sec (%d filers parallel + streaming, no gRPC)",
|
||||
processed, elapsed.Round(time.Millisecond), directRate, numFilers)
|
||||
})
|
||||
|
||||
if serverRate > 0 {
|
||||
t.Logf("Speedup: %.1fx (parallel + prefetch + no gRPC vs server-side sequential)", directRate/serverRate)
|
||||
t.Logf("Speedup: %.1fx (parallel + streaming + no gRPC vs server-side sequential)", directRate/serverRate)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,3 +332,120 @@ func TestReadLogFileRefsMultiFilerNotFoundSkips(t *testing.T) {
|
||||
t.Fatalf("expected %d events after skipping one file, got %d", expected, count)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadLogFileRefsSingleFilerOrder covers the single-filer path: every
|
||||
// entry across all files, in order.
|
||||
func TestReadLogFileRefsSingleFilerOrder(t *testing.T) {
|
||||
assertOrderedReplay(t, newTestLogFiles(1, 4, 50, 0))
|
||||
}
|
||||
|
||||
// TestReadLogFileRefsSingleFilerProcessErrorStops verifies that the callback's
|
||||
// own error propagates and aborts the stream promptly, mid-file.
|
||||
func TestReadLogFileRefsSingleFilerProcessErrorStops(t *testing.T) {
|
||||
files := newTestLogFiles(1, 3, 100, 0)
|
||||
|
||||
var count int
|
||||
wantErr := fmt.Errorf("boom")
|
||||
_, err := ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
|
||||
PathFilter{PathPrefix: "/"},
|
||||
func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
count++
|
||||
if count == 5 {
|
||||
return wantErr
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("expected processing error to propagate, got: %v", err)
|
||||
}
|
||||
// Should stop near the failing event, not process the whole 300-event set.
|
||||
if count > 20 {
|
||||
t.Fatalf("expected prompt stop after error, processed %d events", count)
|
||||
}
|
||||
}
|
||||
|
||||
// A corrupt size prefix must fail the replay instead of allocating gigabytes.
|
||||
func TestReadLogFileRefsCorruptSizePrefix(t *testing.T) {
|
||||
data := make([]byte, 4)
|
||||
util.Uint32toBytes(data, 0xFFFFFFF0)
|
||||
refs := []*filer_pb.LogFileChunkRef{{
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: "corrupt"}},
|
||||
FileTsNs: 1,
|
||||
FilerId: "filer00",
|
||||
}}
|
||||
readerFn := func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(data)), nil
|
||||
}
|
||||
|
||||
_, err := ReadLogFileRefs(refs, readerFn, 0, 0, PathFilter{PathPrefix: "/"},
|
||||
func(*filer_pb.SubscribeMetadataResponse) error { return nil })
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Fatalf("expected size-cap error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// blockingReader blocks in Read until released.
|
||||
type blockingReader struct{ release chan struct{} }
|
||||
|
||||
func (r *blockingReader) Read(p []byte) (int, error) { <-r.release; return 0, io.EOF }
|
||||
func (r *blockingReader) Close() error { return nil }
|
||||
|
||||
// An abort (fatal error on one filer) must not wait for another filer's
|
||||
// in-flight chunk read: the replay returns promptly and the wedged producer
|
||||
// exits on its own once its read completes.
|
||||
func TestReadLogFileRefsAbortDoesNotJoinWedgedReader(t *testing.T) {
|
||||
files := newTestLogFiles(2, 1, 10, 0)
|
||||
release := make(chan struct{})
|
||||
t.Cleanup(func() { close(release) })
|
||||
|
||||
wedgedKey := files.refs[0].Chunks[0].FileId // filer00 wedges mid-read
|
||||
failKey := files.refs[1].Chunks[0].FileId // filer01 fails for real
|
||||
base := files.readerFn()
|
||||
readerFn := func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
switch chunks[0].FileId {
|
||||
case wedgedKey:
|
||||
return &blockingReader{release: release}, nil
|
||||
case failKey:
|
||||
return nil, fmt.Errorf("failed to locate %s", failKey)
|
||||
}
|
||||
return base(chunks)
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := ReadLogFileRefs(files.refs, readerFn, 0, 0, PathFilter{PathPrefix: "/"},
|
||||
func(*filer_pb.SubscribeMetadataResponse) error { return nil })
|
||||
done <- err
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil {
|
||||
t.Fatalf("expected the fatal read error to propagate")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("ReadLogFileRefs did not return while a peer reader was wedged")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadLogFileRefsSingleFilerNotFoundSkips confirms a chunk-not-found on the
|
||||
// single-filer path skips just that file, not the whole replay.
|
||||
func TestReadLogFileRefsSingleFilerNotFoundSkips(t *testing.T) {
|
||||
files := newTestLogFiles(1, 3, 10, 0)
|
||||
skipKey := files.refs[1].Chunks[0].FileId // second file
|
||||
readerFn := failingReaderFn(files.readerFn(), skipKey, fmt.Errorf("volume not found: %s", skipKey))
|
||||
|
||||
var count int
|
||||
_, err := ReadLogFileRefs(files.refs, readerFn, 0, 0,
|
||||
PathFilter{PathPrefix: "/"},
|
||||
func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
count++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("chunk-not-found should be skipped, got error: %v", err)
|
||||
}
|
||||
if want := files.totalEvents() - 10; count != want {
|
||||
t.Fatalf("expected %d events after skipping one file, got %d", want, count)
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,9 @@ service Seaweed {
|
||||
message DiskTag {
|
||||
uint32 disk_id = 1;
|
||||
repeated string tags = 2;
|
||||
// Physical disk descriptor, reported for every location including empty ones.
|
||||
string type = 3;
|
||||
int64 max_volume_count = 4;
|
||||
}
|
||||
|
||||
message Heartbeat {
|
||||
@@ -96,6 +99,10 @@ message Heartbeat {
|
||||
volume_server_pb.VolumeServerState state = 23;
|
||||
|
||||
repeated DiskTag disk_tags = 24;
|
||||
|
||||
// physical disk capacity per disk type, in bytes, from the underlying filesystem
|
||||
map<string, uint64> disk_total_bytes = 25;
|
||||
map<string, uint64> disk_free_bytes = 26;
|
||||
}
|
||||
|
||||
message HeartbeatResponse {
|
||||
@@ -319,8 +326,18 @@ message DiskInfo {
|
||||
repeated VolumeInformationMessage volume_infos = 6;
|
||||
repeated VolumeEcShardInformationMessage ec_shard_infos = 7;
|
||||
int64 remote_volume_count = 8;
|
||||
// On a per-physical-disk DiskInfo (from SplitByPhysicalDisk) this is the disk's
|
||||
// identity; on the type-keyed aggregate it is only a representative fallback
|
||||
// (the first volume's disk id).
|
||||
uint32 disk_id = 9;
|
||||
repeated string tags = 10;
|
||||
// Max volume count for every physical disk of this type, keyed by disk id,
|
||||
// including disks with no volumes or EC shards; recovers empty disks that
|
||||
// carry no per-volume/per-shard records.
|
||||
map<uint32, int64> max_volume_count_by_disk = 11;
|
||||
// physical disk capacity in bytes, from the underlying filesystem (0 if unknown)
|
||||
uint64 disk_total_bytes = 12;
|
||||
uint64 disk_free_bytes = 13;
|
||||
}
|
||||
message DataNodeInfo {
|
||||
string id = 1;
|
||||
|
||||
+215
-127
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v6.33.4
|
||||
// protoc v7.35.0
|
||||
// source: master.proto
|
||||
|
||||
package master_pb
|
||||
@@ -23,11 +23,14 @@ const (
|
||||
)
|
||||
|
||||
type DiskTag struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
DiskId uint32 `protobuf:"varint,1,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
|
||||
Tags []string `protobuf:"bytes,2,rep,name=tags,proto3" json:"tags,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
DiskId uint32 `protobuf:"varint,1,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
|
||||
Tags []string `protobuf:"bytes,2,rep,name=tags,proto3" json:"tags,omitempty"`
|
||||
// Physical disk descriptor, reported for every location including empty ones.
|
||||
Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"`
|
||||
MaxVolumeCount int64 `protobuf:"varint,4,opt,name=max_volume_count,json=maxVolumeCount,proto3" json:"max_volume_count,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *DiskTag) Reset() {
|
||||
@@ -74,6 +77,20 @@ func (x *DiskTag) GetTags() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *DiskTag) GetType() string {
|
||||
if x != nil {
|
||||
return x.Type
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *DiskTag) GetMaxVolumeCount() int64 {
|
||||
if x != nil {
|
||||
return x.MaxVolumeCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type Heartbeat struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Ip string `protobuf:"bytes,1,opt,name=ip,proto3" json:"ip,omitempty"`
|
||||
@@ -99,10 +116,13 @@ type Heartbeat struct {
|
||||
LocationUuids []string `protobuf:"bytes,21,rep,name=location_uuids,json=locationUuids,proto3" json:"location_uuids,omitempty"`
|
||||
Id string `protobuf:"bytes,22,opt,name=id,proto3" json:"id,omitempty"` // volume server id, independent of ip:port for stable identification
|
||||
// state flags
|
||||
State *volume_server_pb.VolumeServerState `protobuf:"bytes,23,opt,name=state,proto3" json:"state,omitempty"`
|
||||
DiskTags []*DiskTag `protobuf:"bytes,24,rep,name=disk_tags,json=diskTags,proto3" json:"disk_tags,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
State *volume_server_pb.VolumeServerState `protobuf:"bytes,23,opt,name=state,proto3" json:"state,omitempty"`
|
||||
DiskTags []*DiskTag `protobuf:"bytes,24,rep,name=disk_tags,json=diskTags,proto3" json:"disk_tags,omitempty"`
|
||||
// physical disk capacity per disk type, in bytes, from the underlying filesystem
|
||||
DiskTotalBytes map[string]uint64 `protobuf:"bytes,25,rep,name=disk_total_bytes,json=diskTotalBytes,proto3" json:"disk_total_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
|
||||
DiskFreeBytes map[string]uint64 `protobuf:"bytes,26,rep,name=disk_free_bytes,json=diskFreeBytes,proto3" json:"disk_free_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Heartbeat) Reset() {
|
||||
@@ -282,6 +302,20 @@ func (x *Heartbeat) GetDiskTags() []*DiskTag {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Heartbeat) GetDiskTotalBytes() map[string]uint64 {
|
||||
if x != nil {
|
||||
return x.DiskTotalBytes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Heartbeat) GetDiskFreeBytes() map[string]uint64 {
|
||||
if x != nil {
|
||||
return x.DiskFreeBytes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type HeartbeatResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeSizeLimit uint64 `protobuf:"varint,1,opt,name=volume_size_limit,json=volumeSizeLimit,proto3" json:"volume_size_limit,omitempty"`
|
||||
@@ -2121,10 +2155,20 @@ type DiskInfo struct {
|
||||
VolumeInfos []*VolumeInformationMessage `protobuf:"bytes,6,rep,name=volume_infos,json=volumeInfos,proto3" json:"volume_infos,omitempty"`
|
||||
EcShardInfos []*VolumeEcShardInformationMessage `protobuf:"bytes,7,rep,name=ec_shard_infos,json=ecShardInfos,proto3" json:"ec_shard_infos,omitempty"`
|
||||
RemoteVolumeCount int64 `protobuf:"varint,8,opt,name=remote_volume_count,json=remoteVolumeCount,proto3" json:"remote_volume_count,omitempty"`
|
||||
DiskId uint32 `protobuf:"varint,9,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
|
||||
Tags []string `protobuf:"bytes,10,rep,name=tags,proto3" json:"tags,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
// On a per-physical-disk DiskInfo (from SplitByPhysicalDisk) this is the disk's
|
||||
// identity; on the type-keyed aggregate it is only a representative fallback
|
||||
// (the first volume's disk id).
|
||||
DiskId uint32 `protobuf:"varint,9,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
|
||||
Tags []string `protobuf:"bytes,10,rep,name=tags,proto3" json:"tags,omitempty"`
|
||||
// Max volume count for every physical disk of this type, keyed by disk id,
|
||||
// including disks with no volumes or EC shards; recovers empty disks that
|
||||
// carry no per-volume/per-shard records.
|
||||
MaxVolumeCountByDisk map[uint32]int64 `protobuf:"bytes,11,rep,name=max_volume_count_by_disk,json=maxVolumeCountByDisk,proto3" json:"max_volume_count_by_disk,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
|
||||
// physical disk capacity in bytes, from the underlying filesystem (0 if unknown)
|
||||
DiskTotalBytes uint64 `protobuf:"varint,12,opt,name=disk_total_bytes,json=diskTotalBytes,proto3" json:"disk_total_bytes,omitempty"`
|
||||
DiskFreeBytes uint64 `protobuf:"varint,13,opt,name=disk_free_bytes,json=diskFreeBytes,proto3" json:"disk_free_bytes,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *DiskInfo) Reset() {
|
||||
@@ -2227,6 +2271,27 @@ func (x *DiskInfo) GetTags() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *DiskInfo) GetMaxVolumeCountByDisk() map[uint32]int64 {
|
||||
if x != nil {
|
||||
return x.MaxVolumeCountByDisk
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *DiskInfo) GetDiskTotalBytes() uint64 {
|
||||
if x != nil {
|
||||
return x.DiskTotalBytes
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *DiskInfo) GetDiskFreeBytes() uint64 {
|
||||
if x != nil {
|
||||
return x.DiskFreeBytes
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type DataNodeInfo struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
@@ -4059,7 +4124,7 @@ type SuperBlockExtra_ErasureCoding struct {
|
||||
|
||||
func (x *SuperBlockExtra_ErasureCoding) Reset() {
|
||||
*x = SuperBlockExtra_ErasureCoding{}
|
||||
mi := &file_master_proto_msgTypes[65]
|
||||
mi := &file_master_proto_msgTypes[67]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -4071,7 +4136,7 @@ func (x *SuperBlockExtra_ErasureCoding) String() string {
|
||||
func (*SuperBlockExtra_ErasureCoding) ProtoMessage() {}
|
||||
|
||||
func (x *SuperBlockExtra_ErasureCoding) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[65]
|
||||
mi := &file_master_proto_msgTypes[67]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -4120,7 +4185,7 @@ type LookupVolumeResponse_VolumeIdLocation struct {
|
||||
|
||||
func (x *LookupVolumeResponse_VolumeIdLocation) Reset() {
|
||||
*x = LookupVolumeResponse_VolumeIdLocation{}
|
||||
mi := &file_master_proto_msgTypes[66]
|
||||
mi := &file_master_proto_msgTypes[68]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -4132,7 +4197,7 @@ func (x *LookupVolumeResponse_VolumeIdLocation) String() string {
|
||||
func (*LookupVolumeResponse_VolumeIdLocation) ProtoMessage() {}
|
||||
|
||||
func (x *LookupVolumeResponse_VolumeIdLocation) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[66]
|
||||
mi := &file_master_proto_msgTypes[68]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -4186,7 +4251,7 @@ type LookupEcVolumeResponse_EcShardIdLocation struct {
|
||||
|
||||
func (x *LookupEcVolumeResponse_EcShardIdLocation) Reset() {
|
||||
*x = LookupEcVolumeResponse_EcShardIdLocation{}
|
||||
mi := &file_master_proto_msgTypes[71]
|
||||
mi := &file_master_proto_msgTypes[74]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -4198,7 +4263,7 @@ func (x *LookupEcVolumeResponse_EcShardIdLocation) String() string {
|
||||
func (*LookupEcVolumeResponse_EcShardIdLocation) ProtoMessage() {}
|
||||
|
||||
func (x *LookupEcVolumeResponse_EcShardIdLocation) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[71]
|
||||
mi := &file_master_proto_msgTypes[74]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -4241,7 +4306,7 @@ type ListClusterNodesResponse_ClusterNode struct {
|
||||
|
||||
func (x *ListClusterNodesResponse_ClusterNode) Reset() {
|
||||
*x = ListClusterNodesResponse_ClusterNode{}
|
||||
mi := &file_master_proto_msgTypes[72]
|
||||
mi := &file_master_proto_msgTypes[75]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -4253,7 +4318,7 @@ func (x *ListClusterNodesResponse_ClusterNode) String() string {
|
||||
func (*ListClusterNodesResponse_ClusterNode) ProtoMessage() {}
|
||||
|
||||
func (x *ListClusterNodesResponse_ClusterNode) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[72]
|
||||
mi := &file_master_proto_msgTypes[75]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -4316,7 +4381,7 @@ type RaftListClusterServersResponse_ClusterServers struct {
|
||||
|
||||
func (x *RaftListClusterServersResponse_ClusterServers) Reset() {
|
||||
*x = RaftListClusterServersResponse_ClusterServers{}
|
||||
mi := &file_master_proto_msgTypes[73]
|
||||
mi := &file_master_proto_msgTypes[76]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -4328,7 +4393,7 @@ func (x *RaftListClusterServersResponse_ClusterServers) String() string {
|
||||
func (*RaftListClusterServersResponse_ClusterServers) ProtoMessage() {}
|
||||
|
||||
func (x *RaftListClusterServersResponse_ClusterServers) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_master_proto_msgTypes[73]
|
||||
mi := &file_master_proto_msgTypes[76]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -4376,10 +4441,13 @@ var File_master_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_master_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\fmaster.proto\x12\tmaster_pb\x1a\x13volume_server.proto\"6\n" +
|
||||
"\fmaster.proto\x12\tmaster_pb\x1a\x13volume_server.proto\"t\n" +
|
||||
"\aDiskTag\x12\x17\n" +
|
||||
"\adisk_id\x18\x01 \x01(\rR\x06diskId\x12\x12\n" +
|
||||
"\x04tags\x18\x02 \x03(\tR\x04tags\"\xbc\b\n" +
|
||||
"\x04tags\x18\x02 \x03(\tR\x04tags\x12\x12\n" +
|
||||
"\x04type\x18\x03 \x01(\tR\x04type\x12(\n" +
|
||||
"\x10max_volume_count\x18\x04 \x01(\x03R\x0emaxVolumeCount\"\xe6\n" +
|
||||
"\n" +
|
||||
"\tHeartbeat\x12\x0e\n" +
|
||||
"\x02ip\x18\x01 \x01(\tR\x02ip\x12\x12\n" +
|
||||
"\x04port\x18\x02 \x01(\rR\x04port\x12\x1d\n" +
|
||||
@@ -4407,10 +4475,18 @@ const file_master_proto_rawDesc = "" +
|
||||
"\x0elocation_uuids\x18\x15 \x03(\tR\rlocationUuids\x12\x0e\n" +
|
||||
"\x02id\x18\x16 \x01(\tR\x02id\x129\n" +
|
||||
"\x05state\x18\x17 \x01(\v2#.volume_server_pb.VolumeServerStateR\x05state\x12/\n" +
|
||||
"\tdisk_tags\x18\x18 \x03(\v2\x12.master_pb.DiskTagR\bdiskTags\x1aB\n" +
|
||||
"\tdisk_tags\x18\x18 \x03(\v2\x12.master_pb.DiskTagR\bdiskTags\x12R\n" +
|
||||
"\x10disk_total_bytes\x18\x19 \x03(\v2(.master_pb.Heartbeat.DiskTotalBytesEntryR\x0ediskTotalBytes\x12O\n" +
|
||||
"\x0fdisk_free_bytes\x18\x1a \x03(\v2'.master_pb.Heartbeat.DiskFreeBytesEntryR\rdiskFreeBytes\x1aB\n" +
|
||||
"\x14MaxVolumeCountsEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\rR\x05value:\x028\x01\"\xcd\x02\n" +
|
||||
"\x05value\x18\x02 \x01(\rR\x05value:\x028\x01\x1aA\n" +
|
||||
"\x13DiskTotalBytesEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\x04R\x05value:\x028\x01\x1a@\n" +
|
||||
"\x12DiskFreeBytesEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\x04R\x05value:\x028\x01\"\xcd\x02\n" +
|
||||
"\x11HeartbeatResponse\x12*\n" +
|
||||
"\x11volume_size_limit\x18\x01 \x01(\x04R\x0fvolumeSizeLimit\x12\x16\n" +
|
||||
"\x06leader\x18\x02 \x01(\tR\x06leader\x12'\n" +
|
||||
@@ -4600,7 +4676,7 @@ const file_master_proto_rawDesc = "" +
|
||||
"\vcollections\x18\x01 \x03(\v2\x15.master_pb.CollectionR\vcollections\"-\n" +
|
||||
"\x17CollectionDeleteRequest\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\"\x1a\n" +
|
||||
"\x18CollectionDeleteResponse\"\xbe\x03\n" +
|
||||
"\x18CollectionDeleteResponse\"\xc0\x05\n" +
|
||||
"\bDiskInfo\x12\x12\n" +
|
||||
"\x04type\x18\x01 \x01(\tR\x04type\x12!\n" +
|
||||
"\fvolume_count\x18\x02 \x01(\x03R\vvolumeCount\x12(\n" +
|
||||
@@ -4612,7 +4688,13 @@ const file_master_proto_rawDesc = "" +
|
||||
"\x13remote_volume_count\x18\b \x01(\x03R\x11remoteVolumeCount\x12\x17\n" +
|
||||
"\adisk_id\x18\t \x01(\rR\x06diskId\x12\x12\n" +
|
||||
"\x04tags\x18\n" +
|
||||
" \x03(\tR\x04tags\"\xee\x01\n" +
|
||||
" \x03(\tR\x04tags\x12e\n" +
|
||||
"\x18max_volume_count_by_disk\x18\v \x03(\v2-.master_pb.DiskInfo.MaxVolumeCountByDiskEntryR\x14maxVolumeCountByDisk\x12(\n" +
|
||||
"\x10disk_total_bytes\x18\f \x01(\x04R\x0ediskTotalBytes\x12&\n" +
|
||||
"\x0fdisk_free_bytes\x18\r \x01(\x04R\rdiskFreeBytes\x1aG\n" +
|
||||
"\x19MaxVolumeCountByDiskEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\rR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\x03R\x05value:\x028\x01\"\xee\x01\n" +
|
||||
"\fDataNodeInfo\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x12D\n" +
|
||||
"\tdiskInfos\x18\x02 \x03(\v2&.master_pb.DataNodeInfo.DiskInfosEntryR\tdiskInfos\x12\x1b\n" +
|
||||
@@ -4800,7 +4882,7 @@ func file_master_proto_rawDescGZIP() []byte {
|
||||
return file_master_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 74)
|
||||
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 77)
|
||||
var file_master_proto_goTypes = []any{
|
||||
(*DiskTag)(nil), // 0: master_pb.DiskTag
|
||||
(*Heartbeat)(nil), // 1: master_pb.Heartbeat
|
||||
@@ -4866,17 +4948,20 @@ var file_master_proto_goTypes = []any{
|
||||
(*RaftLeadershipTransferResponse)(nil), // 61: master_pb.RaftLeadershipTransferResponse
|
||||
(*VolumeGrowResponse)(nil), // 62: master_pb.VolumeGrowResponse
|
||||
nil, // 63: master_pb.Heartbeat.MaxVolumeCountsEntry
|
||||
nil, // 64: master_pb.StorageBackend.PropertiesEntry
|
||||
(*SuperBlockExtra_ErasureCoding)(nil), // 65: master_pb.SuperBlockExtra.ErasureCoding
|
||||
(*LookupVolumeResponse_VolumeIdLocation)(nil), // 66: master_pb.LookupVolumeResponse.VolumeIdLocation
|
||||
nil, // 67: master_pb.DataNodeInfo.DiskInfosEntry
|
||||
nil, // 68: master_pb.RackInfo.DiskInfosEntry
|
||||
nil, // 69: master_pb.DataCenterInfo.DiskInfosEntry
|
||||
nil, // 70: master_pb.TopologyInfo.DiskInfosEntry
|
||||
(*LookupEcVolumeResponse_EcShardIdLocation)(nil), // 71: master_pb.LookupEcVolumeResponse.EcShardIdLocation
|
||||
(*ListClusterNodesResponse_ClusterNode)(nil), // 72: master_pb.ListClusterNodesResponse.ClusterNode
|
||||
(*RaftListClusterServersResponse_ClusterServers)(nil), // 73: master_pb.RaftListClusterServersResponse.ClusterServers
|
||||
(*volume_server_pb.VolumeServerState)(nil), // 74: volume_server_pb.VolumeServerState
|
||||
nil, // 64: master_pb.Heartbeat.DiskTotalBytesEntry
|
||||
nil, // 65: master_pb.Heartbeat.DiskFreeBytesEntry
|
||||
nil, // 66: master_pb.StorageBackend.PropertiesEntry
|
||||
(*SuperBlockExtra_ErasureCoding)(nil), // 67: master_pb.SuperBlockExtra.ErasureCoding
|
||||
(*LookupVolumeResponse_VolumeIdLocation)(nil), // 68: master_pb.LookupVolumeResponse.VolumeIdLocation
|
||||
nil, // 69: master_pb.DiskInfo.MaxVolumeCountByDiskEntry
|
||||
nil, // 70: master_pb.DataNodeInfo.DiskInfosEntry
|
||||
nil, // 71: master_pb.RackInfo.DiskInfosEntry
|
||||
nil, // 72: master_pb.DataCenterInfo.DiskInfosEntry
|
||||
nil, // 73: master_pb.TopologyInfo.DiskInfosEntry
|
||||
(*LookupEcVolumeResponse_EcShardIdLocation)(nil), // 74: master_pb.LookupEcVolumeResponse.EcShardIdLocation
|
||||
(*ListClusterNodesResponse_ClusterNode)(nil), // 75: master_pb.ListClusterNodesResponse.ClusterNode
|
||||
(*RaftListClusterServersResponse_ClusterServers)(nil), // 76: master_pb.RaftListClusterServersResponse.ClusterServers
|
||||
(*volume_server_pb.VolumeServerState)(nil), // 77: volume_server_pb.VolumeServerState
|
||||
}
|
||||
var file_master_proto_depIdxs = []int32{
|
||||
3, // 0: master_pb.Heartbeat.volumes:type_name -> master_pb.VolumeInformationMessage
|
||||
@@ -4886,91 +4971,94 @@ var file_master_proto_depIdxs = []int32{
|
||||
5, // 4: master_pb.Heartbeat.new_ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
|
||||
5, // 5: master_pb.Heartbeat.deleted_ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
|
||||
63, // 6: master_pb.Heartbeat.max_volume_counts:type_name -> master_pb.Heartbeat.MaxVolumeCountsEntry
|
||||
74, // 7: master_pb.Heartbeat.state:type_name -> volume_server_pb.VolumeServerState
|
||||
77, // 7: master_pb.Heartbeat.state:type_name -> volume_server_pb.VolumeServerState
|
||||
0, // 8: master_pb.Heartbeat.disk_tags:type_name -> master_pb.DiskTag
|
||||
6, // 9: master_pb.HeartbeatResponse.storage_backends:type_name -> master_pb.StorageBackend
|
||||
64, // 10: master_pb.StorageBackend.properties:type_name -> master_pb.StorageBackend.PropertiesEntry
|
||||
65, // 11: master_pb.SuperBlockExtra.erasure_coding:type_name -> master_pb.SuperBlockExtra.ErasureCoding
|
||||
10, // 12: master_pb.KeepConnectedResponse.volume_location:type_name -> master_pb.VolumeLocation
|
||||
11, // 13: master_pb.KeepConnectedResponse.cluster_node_update:type_name -> master_pb.ClusterNodeUpdate
|
||||
13, // 14: master_pb.KeepConnectedResponse.lock_ring_update:type_name -> master_pb.LockRingUpdate
|
||||
66, // 15: master_pb.LookupVolumeResponse.volume_id_locations:type_name -> master_pb.LookupVolumeResponse.VolumeIdLocation
|
||||
16, // 16: master_pb.AssignResponse.replicas:type_name -> master_pb.Location
|
||||
16, // 17: master_pb.AssignResponse.location:type_name -> master_pb.Location
|
||||
22, // 18: master_pb.CollectionListResponse.collections:type_name -> master_pb.Collection
|
||||
3, // 19: master_pb.DiskInfo.volume_infos:type_name -> master_pb.VolumeInformationMessage
|
||||
5, // 20: master_pb.DiskInfo.ec_shard_infos:type_name -> master_pb.VolumeEcShardInformationMessage
|
||||
67, // 21: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
|
||||
28, // 22: master_pb.RackInfo.data_node_infos:type_name -> master_pb.DataNodeInfo
|
||||
68, // 23: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
|
||||
29, // 24: master_pb.DataCenterInfo.rack_infos:type_name -> master_pb.RackInfo
|
||||
69, // 25: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
|
||||
30, // 26: master_pb.TopologyInfo.data_center_infos:type_name -> master_pb.DataCenterInfo
|
||||
70, // 27: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
|
||||
31, // 28: master_pb.VolumeListResponse.topology_info:type_name -> master_pb.TopologyInfo
|
||||
71, // 29: master_pb.LookupEcVolumeResponse.shard_id_locations:type_name -> master_pb.LookupEcVolumeResponse.EcShardIdLocation
|
||||
6, // 30: master_pb.GetMasterConfigurationResponse.storage_backends:type_name -> master_pb.StorageBackend
|
||||
72, // 31: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode
|
||||
73, // 32: master_pb.RaftListClusterServersResponse.cluster_servers:type_name -> master_pb.RaftListClusterServersResponse.ClusterServers
|
||||
16, // 33: master_pb.LookupVolumeResponse.VolumeIdLocation.locations:type_name -> master_pb.Location
|
||||
27, // 34: master_pb.DataNodeInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
27, // 35: master_pb.RackInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
27, // 36: master_pb.DataCenterInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
27, // 37: master_pb.TopologyInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
16, // 38: master_pb.LookupEcVolumeResponse.EcShardIdLocation.locations:type_name -> master_pb.Location
|
||||
1, // 39: master_pb.Seaweed.SendHeartbeat:input_type -> master_pb.Heartbeat
|
||||
9, // 40: master_pb.Seaweed.KeepConnected:input_type -> master_pb.KeepConnectedRequest
|
||||
14, // 41: master_pb.Seaweed.LookupVolume:input_type -> master_pb.LookupVolumeRequest
|
||||
17, // 42: master_pb.Seaweed.Assign:input_type -> master_pb.AssignRequest
|
||||
17, // 43: master_pb.Seaweed.StreamAssign:input_type -> master_pb.AssignRequest
|
||||
20, // 44: master_pb.Seaweed.Statistics:input_type -> master_pb.StatisticsRequest
|
||||
23, // 45: master_pb.Seaweed.CollectionList:input_type -> master_pb.CollectionListRequest
|
||||
25, // 46: master_pb.Seaweed.CollectionDelete:input_type -> master_pb.CollectionDeleteRequest
|
||||
32, // 47: master_pb.Seaweed.VolumeList:input_type -> master_pb.VolumeListRequest
|
||||
34, // 48: master_pb.Seaweed.LookupEcVolume:input_type -> master_pb.LookupEcVolumeRequest
|
||||
36, // 49: master_pb.Seaweed.VacuumVolume:input_type -> master_pb.VacuumVolumeRequest
|
||||
38, // 50: master_pb.Seaweed.DisableVacuum:input_type -> master_pb.DisableVacuumRequest
|
||||
40, // 51: master_pb.Seaweed.EnableVacuum:input_type -> master_pb.EnableVacuumRequest
|
||||
42, // 52: master_pb.Seaweed.VolumeMarkReadonly:input_type -> master_pb.VolumeMarkReadonlyRequest
|
||||
44, // 53: master_pb.Seaweed.GetMasterConfiguration:input_type -> master_pb.GetMasterConfigurationRequest
|
||||
46, // 54: master_pb.Seaweed.ListClusterNodes:input_type -> master_pb.ListClusterNodesRequest
|
||||
48, // 55: master_pb.Seaweed.LeaseAdminToken:input_type -> master_pb.LeaseAdminTokenRequest
|
||||
50, // 56: master_pb.Seaweed.ReleaseAdminToken:input_type -> master_pb.ReleaseAdminTokenRequest
|
||||
52, // 57: master_pb.Seaweed.Ping:input_type -> master_pb.PingRequest
|
||||
58, // 58: master_pb.Seaweed.RaftListClusterServers:input_type -> master_pb.RaftListClusterServersRequest
|
||||
54, // 59: master_pb.Seaweed.RaftAddServer:input_type -> master_pb.RaftAddServerRequest
|
||||
56, // 60: master_pb.Seaweed.RaftRemoveServer:input_type -> master_pb.RaftRemoveServerRequest
|
||||
60, // 61: master_pb.Seaweed.RaftLeadershipTransfer:input_type -> master_pb.RaftLeadershipTransferRequest
|
||||
18, // 62: master_pb.Seaweed.VolumeGrow:input_type -> master_pb.VolumeGrowRequest
|
||||
2, // 63: master_pb.Seaweed.SendHeartbeat:output_type -> master_pb.HeartbeatResponse
|
||||
12, // 64: master_pb.Seaweed.KeepConnected:output_type -> master_pb.KeepConnectedResponse
|
||||
15, // 65: master_pb.Seaweed.LookupVolume:output_type -> master_pb.LookupVolumeResponse
|
||||
19, // 66: master_pb.Seaweed.Assign:output_type -> master_pb.AssignResponse
|
||||
19, // 67: master_pb.Seaweed.StreamAssign:output_type -> master_pb.AssignResponse
|
||||
21, // 68: master_pb.Seaweed.Statistics:output_type -> master_pb.StatisticsResponse
|
||||
24, // 69: master_pb.Seaweed.CollectionList:output_type -> master_pb.CollectionListResponse
|
||||
26, // 70: master_pb.Seaweed.CollectionDelete:output_type -> master_pb.CollectionDeleteResponse
|
||||
33, // 71: master_pb.Seaweed.VolumeList:output_type -> master_pb.VolumeListResponse
|
||||
35, // 72: master_pb.Seaweed.LookupEcVolume:output_type -> master_pb.LookupEcVolumeResponse
|
||||
37, // 73: master_pb.Seaweed.VacuumVolume:output_type -> master_pb.VacuumVolumeResponse
|
||||
39, // 74: master_pb.Seaweed.DisableVacuum:output_type -> master_pb.DisableVacuumResponse
|
||||
41, // 75: master_pb.Seaweed.EnableVacuum:output_type -> master_pb.EnableVacuumResponse
|
||||
43, // 76: master_pb.Seaweed.VolumeMarkReadonly:output_type -> master_pb.VolumeMarkReadonlyResponse
|
||||
45, // 77: master_pb.Seaweed.GetMasterConfiguration:output_type -> master_pb.GetMasterConfigurationResponse
|
||||
47, // 78: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse
|
||||
49, // 79: master_pb.Seaweed.LeaseAdminToken:output_type -> master_pb.LeaseAdminTokenResponse
|
||||
51, // 80: master_pb.Seaweed.ReleaseAdminToken:output_type -> master_pb.ReleaseAdminTokenResponse
|
||||
53, // 81: master_pb.Seaweed.Ping:output_type -> master_pb.PingResponse
|
||||
59, // 82: master_pb.Seaweed.RaftListClusterServers:output_type -> master_pb.RaftListClusterServersResponse
|
||||
55, // 83: master_pb.Seaweed.RaftAddServer:output_type -> master_pb.RaftAddServerResponse
|
||||
57, // 84: master_pb.Seaweed.RaftRemoveServer:output_type -> master_pb.RaftRemoveServerResponse
|
||||
61, // 85: master_pb.Seaweed.RaftLeadershipTransfer:output_type -> master_pb.RaftLeadershipTransferResponse
|
||||
62, // 86: master_pb.Seaweed.VolumeGrow:output_type -> master_pb.VolumeGrowResponse
|
||||
63, // [63:87] is the sub-list for method output_type
|
||||
39, // [39:63] is the sub-list for method input_type
|
||||
39, // [39:39] is the sub-list for extension type_name
|
||||
39, // [39:39] is the sub-list for extension extendee
|
||||
0, // [0:39] is the sub-list for field type_name
|
||||
64, // 9: master_pb.Heartbeat.disk_total_bytes:type_name -> master_pb.Heartbeat.DiskTotalBytesEntry
|
||||
65, // 10: master_pb.Heartbeat.disk_free_bytes:type_name -> master_pb.Heartbeat.DiskFreeBytesEntry
|
||||
6, // 11: master_pb.HeartbeatResponse.storage_backends:type_name -> master_pb.StorageBackend
|
||||
66, // 12: master_pb.StorageBackend.properties:type_name -> master_pb.StorageBackend.PropertiesEntry
|
||||
67, // 13: master_pb.SuperBlockExtra.erasure_coding:type_name -> master_pb.SuperBlockExtra.ErasureCoding
|
||||
10, // 14: master_pb.KeepConnectedResponse.volume_location:type_name -> master_pb.VolumeLocation
|
||||
11, // 15: master_pb.KeepConnectedResponse.cluster_node_update:type_name -> master_pb.ClusterNodeUpdate
|
||||
13, // 16: master_pb.KeepConnectedResponse.lock_ring_update:type_name -> master_pb.LockRingUpdate
|
||||
68, // 17: master_pb.LookupVolumeResponse.volume_id_locations:type_name -> master_pb.LookupVolumeResponse.VolumeIdLocation
|
||||
16, // 18: master_pb.AssignResponse.replicas:type_name -> master_pb.Location
|
||||
16, // 19: master_pb.AssignResponse.location:type_name -> master_pb.Location
|
||||
22, // 20: master_pb.CollectionListResponse.collections:type_name -> master_pb.Collection
|
||||
3, // 21: master_pb.DiskInfo.volume_infos:type_name -> master_pb.VolumeInformationMessage
|
||||
5, // 22: master_pb.DiskInfo.ec_shard_infos:type_name -> master_pb.VolumeEcShardInformationMessage
|
||||
69, // 23: master_pb.DiskInfo.max_volume_count_by_disk:type_name -> master_pb.DiskInfo.MaxVolumeCountByDiskEntry
|
||||
70, // 24: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
|
||||
28, // 25: master_pb.RackInfo.data_node_infos:type_name -> master_pb.DataNodeInfo
|
||||
71, // 26: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
|
||||
29, // 27: master_pb.DataCenterInfo.rack_infos:type_name -> master_pb.RackInfo
|
||||
72, // 28: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
|
||||
30, // 29: master_pb.TopologyInfo.data_center_infos:type_name -> master_pb.DataCenterInfo
|
||||
73, // 30: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
|
||||
31, // 31: master_pb.VolumeListResponse.topology_info:type_name -> master_pb.TopologyInfo
|
||||
74, // 32: master_pb.LookupEcVolumeResponse.shard_id_locations:type_name -> master_pb.LookupEcVolumeResponse.EcShardIdLocation
|
||||
6, // 33: master_pb.GetMasterConfigurationResponse.storage_backends:type_name -> master_pb.StorageBackend
|
||||
75, // 34: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode
|
||||
76, // 35: master_pb.RaftListClusterServersResponse.cluster_servers:type_name -> master_pb.RaftListClusterServersResponse.ClusterServers
|
||||
16, // 36: master_pb.LookupVolumeResponse.VolumeIdLocation.locations:type_name -> master_pb.Location
|
||||
27, // 37: master_pb.DataNodeInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
27, // 38: master_pb.RackInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
27, // 39: master_pb.DataCenterInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
27, // 40: master_pb.TopologyInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
|
||||
16, // 41: master_pb.LookupEcVolumeResponse.EcShardIdLocation.locations:type_name -> master_pb.Location
|
||||
1, // 42: master_pb.Seaweed.SendHeartbeat:input_type -> master_pb.Heartbeat
|
||||
9, // 43: master_pb.Seaweed.KeepConnected:input_type -> master_pb.KeepConnectedRequest
|
||||
14, // 44: master_pb.Seaweed.LookupVolume:input_type -> master_pb.LookupVolumeRequest
|
||||
17, // 45: master_pb.Seaweed.Assign:input_type -> master_pb.AssignRequest
|
||||
17, // 46: master_pb.Seaweed.StreamAssign:input_type -> master_pb.AssignRequest
|
||||
20, // 47: master_pb.Seaweed.Statistics:input_type -> master_pb.StatisticsRequest
|
||||
23, // 48: master_pb.Seaweed.CollectionList:input_type -> master_pb.CollectionListRequest
|
||||
25, // 49: master_pb.Seaweed.CollectionDelete:input_type -> master_pb.CollectionDeleteRequest
|
||||
32, // 50: master_pb.Seaweed.VolumeList:input_type -> master_pb.VolumeListRequest
|
||||
34, // 51: master_pb.Seaweed.LookupEcVolume:input_type -> master_pb.LookupEcVolumeRequest
|
||||
36, // 52: master_pb.Seaweed.VacuumVolume:input_type -> master_pb.VacuumVolumeRequest
|
||||
38, // 53: master_pb.Seaweed.DisableVacuum:input_type -> master_pb.DisableVacuumRequest
|
||||
40, // 54: master_pb.Seaweed.EnableVacuum:input_type -> master_pb.EnableVacuumRequest
|
||||
42, // 55: master_pb.Seaweed.VolumeMarkReadonly:input_type -> master_pb.VolumeMarkReadonlyRequest
|
||||
44, // 56: master_pb.Seaweed.GetMasterConfiguration:input_type -> master_pb.GetMasterConfigurationRequest
|
||||
46, // 57: master_pb.Seaweed.ListClusterNodes:input_type -> master_pb.ListClusterNodesRequest
|
||||
48, // 58: master_pb.Seaweed.LeaseAdminToken:input_type -> master_pb.LeaseAdminTokenRequest
|
||||
50, // 59: master_pb.Seaweed.ReleaseAdminToken:input_type -> master_pb.ReleaseAdminTokenRequest
|
||||
52, // 60: master_pb.Seaweed.Ping:input_type -> master_pb.PingRequest
|
||||
58, // 61: master_pb.Seaweed.RaftListClusterServers:input_type -> master_pb.RaftListClusterServersRequest
|
||||
54, // 62: master_pb.Seaweed.RaftAddServer:input_type -> master_pb.RaftAddServerRequest
|
||||
56, // 63: master_pb.Seaweed.RaftRemoveServer:input_type -> master_pb.RaftRemoveServerRequest
|
||||
60, // 64: master_pb.Seaweed.RaftLeadershipTransfer:input_type -> master_pb.RaftLeadershipTransferRequest
|
||||
18, // 65: master_pb.Seaweed.VolumeGrow:input_type -> master_pb.VolumeGrowRequest
|
||||
2, // 66: master_pb.Seaweed.SendHeartbeat:output_type -> master_pb.HeartbeatResponse
|
||||
12, // 67: master_pb.Seaweed.KeepConnected:output_type -> master_pb.KeepConnectedResponse
|
||||
15, // 68: master_pb.Seaweed.LookupVolume:output_type -> master_pb.LookupVolumeResponse
|
||||
19, // 69: master_pb.Seaweed.Assign:output_type -> master_pb.AssignResponse
|
||||
19, // 70: master_pb.Seaweed.StreamAssign:output_type -> master_pb.AssignResponse
|
||||
21, // 71: master_pb.Seaweed.Statistics:output_type -> master_pb.StatisticsResponse
|
||||
24, // 72: master_pb.Seaweed.CollectionList:output_type -> master_pb.CollectionListResponse
|
||||
26, // 73: master_pb.Seaweed.CollectionDelete:output_type -> master_pb.CollectionDeleteResponse
|
||||
33, // 74: master_pb.Seaweed.VolumeList:output_type -> master_pb.VolumeListResponse
|
||||
35, // 75: master_pb.Seaweed.LookupEcVolume:output_type -> master_pb.LookupEcVolumeResponse
|
||||
37, // 76: master_pb.Seaweed.VacuumVolume:output_type -> master_pb.VacuumVolumeResponse
|
||||
39, // 77: master_pb.Seaweed.DisableVacuum:output_type -> master_pb.DisableVacuumResponse
|
||||
41, // 78: master_pb.Seaweed.EnableVacuum:output_type -> master_pb.EnableVacuumResponse
|
||||
43, // 79: master_pb.Seaweed.VolumeMarkReadonly:output_type -> master_pb.VolumeMarkReadonlyResponse
|
||||
45, // 80: master_pb.Seaweed.GetMasterConfiguration:output_type -> master_pb.GetMasterConfigurationResponse
|
||||
47, // 81: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse
|
||||
49, // 82: master_pb.Seaweed.LeaseAdminToken:output_type -> master_pb.LeaseAdminTokenResponse
|
||||
51, // 83: master_pb.Seaweed.ReleaseAdminToken:output_type -> master_pb.ReleaseAdminTokenResponse
|
||||
53, // 84: master_pb.Seaweed.Ping:output_type -> master_pb.PingResponse
|
||||
59, // 85: master_pb.Seaweed.RaftListClusterServers:output_type -> master_pb.RaftListClusterServersResponse
|
||||
55, // 86: master_pb.Seaweed.RaftAddServer:output_type -> master_pb.RaftAddServerResponse
|
||||
57, // 87: master_pb.Seaweed.RaftRemoveServer:output_type -> master_pb.RaftRemoveServerResponse
|
||||
61, // 88: master_pb.Seaweed.RaftLeadershipTransfer:output_type -> master_pb.RaftLeadershipTransferResponse
|
||||
62, // 89: master_pb.Seaweed.VolumeGrow:output_type -> master_pb.VolumeGrowResponse
|
||||
66, // [66:90] is the sub-list for method output_type
|
||||
42, // [42:66] is the sub-list for method input_type
|
||||
42, // [42:42] is the sub-list for extension type_name
|
||||
42, // [42:42] is the sub-list for extension extendee
|
||||
0, // [0:42] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_master_proto_init() }
|
||||
@@ -4984,7 +5072,7 @@ func file_master_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_master_proto_rawDesc), len(file_master_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 74,
|
||||
NumMessages: 77,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -6,50 +6,46 @@ func (v *VolumeLocation) IsEmptyUrl() bool {
|
||||
return v.Url == "" || v.Url == ":0"
|
||||
}
|
||||
|
||||
// SplitByPhysicalDisk returns one DiskInfo per physical disk_id observed in
|
||||
// VolumeInfos / EcShardInfos. The wire format keys DataNodeInfo.DiskInfos by
|
||||
// disk type, so multiple same-type physical disks on one DataNode collapse
|
||||
// into a single DiskInfo entry. Per-volume and per-shard records carry the
|
||||
// real physical DiskId; this helper rebuilds a per-physical-disk view from
|
||||
// those records so consumers (topology indexes, shell output) can target
|
||||
// individual disks instead of treating each node as one big disk.
|
||||
//
|
||||
// ActiveVolumeCount and RemoteVolumeCount are computed exactly from each
|
||||
// disk's VolumeInfos (read-only and remote-backed are known per-volume).
|
||||
// MaxVolumeCount and FreeVolumeCount are not derivable from per-volume
|
||||
// records, so they are split across reconstructed disks with the remainder
|
||||
// distributed to the lowest disk ids — the sums are preserved exactly.
|
||||
// SplitByPhysicalDisk returns one DiskInfo per physical disk. The wire format
|
||||
// keys DataNodeInfo.DiskInfos by disk type, collapsing same-type disks into one
|
||||
// entry, so this rebuilds the per-disk view. MaxVolumeCountByDisk, when present,
|
||||
// is the authoritative set (empty disks included) and gives each disk its exact
|
||||
// max; otherwise the set is the DiskIds seen on records with aggregate Max/Free
|
||||
// split evenly.
|
||||
func (d *DiskInfo) SplitByPhysicalDisk() []*DiskInfo {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DiskId 0 is overloaded: it is both the first physical disk (Locations[0])
|
||||
// and the protobuf default for "unset". Only treat 0 as unset when every
|
||||
// record reports 0 (the legacy case where the volume server didn't populate
|
||||
// DiskId). If any record carries a non-zero DiskId, the reporting is real and
|
||||
// a 0 means physical disk 0 — keep it distinct instead of folding it onto
|
||||
// d.DiskId, which would merge two physical disks and drop disk 0 from view.
|
||||
hasNonZero := false
|
||||
for _, vi := range d.VolumeInfos {
|
||||
if vi.DiskId != 0 {
|
||||
hasNonZero = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasNonZero {
|
||||
for _, eci := range d.EcShardInfos {
|
||||
if eci.DiskId != 0 {
|
||||
hasNonZero = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
normalize := func(id uint32) uint32 {
|
||||
if id == 0 && d.DiskId != 0 {
|
||||
if id == 0 && !hasNonZero && d.DiskId != 0 {
|
||||
return d.DiskId
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
diskIDs := make(map[uint32]struct{})
|
||||
for _, vi := range d.VolumeInfos {
|
||||
diskIDs[normalize(vi.DiskId)] = struct{}{}
|
||||
}
|
||||
for _, eci := range d.EcShardInfos {
|
||||
diskIDs[normalize(eci.DiskId)] = struct{}{}
|
||||
}
|
||||
if len(diskIDs) == 0 {
|
||||
diskIDs[d.DiskId] = struct{}{}
|
||||
}
|
||||
|
||||
if len(diskIDs) == 1 {
|
||||
for diskID := range diskIDs {
|
||||
if diskID == d.DiskId {
|
||||
return []*DiskInfo{d}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
perDiskVolumes := make(map[uint32][]*VolumeInformationMessage)
|
||||
for _, vi := range d.VolumeInfos {
|
||||
id := normalize(vi.DiskId)
|
||||
@@ -61,6 +57,35 @@ func (d *DiskInfo) SplitByPhysicalDisk() []*DiskInfo {
|
||||
perDiskShards[id] = append(perDiskShards[id], eci)
|
||||
}
|
||||
|
||||
diskIDs := make(map[uint32]struct{})
|
||||
for id := range perDiskVolumes {
|
||||
diskIDs[id] = struct{}{}
|
||||
}
|
||||
for id := range perDiskShards {
|
||||
diskIDs[id] = struct{}{}
|
||||
}
|
||||
|
||||
// MaxVolumeCountByDisk (when present) is the authoritative set with each
|
||||
// disk's exact max.
|
||||
exactMax := len(d.MaxVolumeCountByDisk) > 0
|
||||
for diskID := range d.MaxVolumeCountByDisk {
|
||||
diskIDs[diskID] = struct{}{}
|
||||
}
|
||||
|
||||
if len(diskIDs) == 0 {
|
||||
diskIDs[d.DiskId] = struct{}{}
|
||||
}
|
||||
|
||||
// A lone disk equal to the aggregate needs no reconstruction; exactMax disks
|
||||
// always reconstruct so they report their own max.
|
||||
if !exactMax && len(diskIDs) == 1 {
|
||||
for diskID := range diskIDs {
|
||||
if diskID == d.DiskId {
|
||||
return []*DiskInfo{d}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort disk IDs so the remainder distribution is deterministic and the
|
||||
// reconstructed slice is in DiskId order, which is what downstream
|
||||
// renderers expect.
|
||||
@@ -94,17 +119,32 @@ func (d *DiskInfo) SplitByPhysicalDisk() []*DiskInfo {
|
||||
remoteCount++
|
||||
}
|
||||
}
|
||||
volumeCount := int64(len(perDiskVolumes[diskID]))
|
||||
maxVolumeCount := share(d.MaxVolumeCount, i)
|
||||
freeVolumeCount := share(d.FreeVolumeCount, i)
|
||||
if exactMax {
|
||||
maxVolumeCount = d.MaxVolumeCountByDisk[diskID]
|
||||
// EC slots aren't subtracted (needs the configurable ratio, outside
|
||||
// this package); planners subtract them from EcShardInfos. Clamp so an
|
||||
// over-allocated disk can't report negative free.
|
||||
freeVolumeCount = maxVolumeCount - (volumeCount - remoteCount)
|
||||
if freeVolumeCount < 0 {
|
||||
freeVolumeCount = 0
|
||||
}
|
||||
}
|
||||
result = append(result, &DiskInfo{
|
||||
Type: d.Type,
|
||||
MaxVolumeCount: share(d.MaxVolumeCount, i),
|
||||
VolumeCount: int64(len(perDiskVolumes[diskID])),
|
||||
FreeVolumeCount: share(d.FreeVolumeCount, i),
|
||||
MaxVolumeCount: maxVolumeCount,
|
||||
VolumeCount: volumeCount,
|
||||
FreeVolumeCount: freeVolumeCount,
|
||||
ActiveVolumeCount: activeCount,
|
||||
RemoteVolumeCount: remoteCount,
|
||||
VolumeInfos: perDiskVolumes[diskID],
|
||||
EcShardInfos: perDiskShards[diskID],
|
||||
DiskId: diskID,
|
||||
Tags: append([]string(nil), d.Tags...),
|
||||
DiskTotalBytes: uint64(share(int64(d.DiskTotalBytes), i)),
|
||||
DiskFreeBytes: uint64(share(int64(d.DiskFreeBytes), i)),
|
||||
})
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -5,6 +5,75 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// MaxVolumeCountByDisk surfaces empty disks and gives each its exact max.
|
||||
func TestDiskInfoSplitByPhysicalDisk_includesEmptyDiskFromPhysicalDisks(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
MaxVolumeCount: 1000, // per-type aggregate
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 10, DiskId: 0},
|
||||
{Id: 11, DiskId: 1},
|
||||
},
|
||||
MaxVolumeCountByDisk: map[uint32]int64{
|
||||
0: 350,
|
||||
1: 350,
|
||||
2: 300, // empty disk, no volumes/shards
|
||||
},
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("want 3 physical disks including the empty one, got %d", len(got))
|
||||
}
|
||||
byID := map[uint32]*DiskInfo{}
|
||||
for _, di := range got {
|
||||
byID[di.DiskId] = di
|
||||
}
|
||||
|
||||
empty, ok := byID[2]
|
||||
if !ok {
|
||||
t.Fatalf("empty disk 2 not surfaced; got %v", byID)
|
||||
}
|
||||
if empty.VolumeCount != 0 {
|
||||
t.Errorf("empty disk: want 0 volumes, got %d", empty.VolumeCount)
|
||||
}
|
||||
if empty.FreeVolumeCount != 300 {
|
||||
t.Errorf("empty disk free: want its full max 300, got %d", empty.FreeVolumeCount)
|
||||
}
|
||||
|
||||
// Exact per-disk max, not the even split (which would give ~334/333/333).
|
||||
if byID[0].MaxVolumeCount != 350 || byID[1].MaxVolumeCount != 350 || byID[2].MaxVolumeCount != 300 {
|
||||
t.Errorf("want exact per-disk max 350/350/300, got %d/%d/%d",
|
||||
byID[0].MaxVolumeCount, byID[1].MaxVolumeCount, byID[2].MaxVolumeCount)
|
||||
}
|
||||
if byID[0].FreeVolumeCount != 349 {
|
||||
t.Errorf("disk 0 free: want 349 (350-1 volume), got %d", byID[0].FreeVolumeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// An over-allocated disk reports zero free, not negative.
|
||||
func TestDiskInfoSplitByPhysicalDisk_clampsNegativeFreeOnOverAllocation(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 1, DiskId: 0},
|
||||
{Id: 2, DiskId: 0},
|
||||
{Id: 3, DiskId: 0},
|
||||
},
|
||||
MaxVolumeCountByDisk: map[uint32]int64{
|
||||
0: 2, // 3 volumes on a max-2 disk
|
||||
},
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 disk, got %d", len(got))
|
||||
}
|
||||
if got[0].FreeVolumeCount != 0 {
|
||||
t.Errorf("over-allocated disk free: want clamped 0, got %d", got[0].FreeVolumeCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_collapsesOnSingleDisk(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
@@ -138,9 +207,9 @@ func TestDiskInfoSplitByPhysicalDisk_countsActiveAndRemoteExactly(t *testing.T)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
id uint32
|
||||
wantActive int64
|
||||
wantRemote int64
|
||||
id uint32
|
||||
wantActive int64
|
||||
wantRemote int64
|
||||
}{
|
||||
{0, 1, 0},
|
||||
{1, 1, 1},
|
||||
@@ -203,6 +272,56 @@ func TestDiskInfoSplitByPhysicalDisk_normalizesZeroToOuterDiskId(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDiskInfoSplitByPhysicalDisk_keepsRealDiskZeroWhenMixed reproduces a
|
||||
// multi-disk node where physical disk 0 (Locations[0]) holds volumes and the
|
||||
// aggregate DiskId is seeded from a non-zero sibling (volumes[0] landed on
|
||||
// disk 6). DiskId 0 must stay its own physical disk, not get folded onto disk
|
||||
// 6 — folding drops a disk from the count and doubles the sibling's volumes.
|
||||
func TestDiskInfoSplitByPhysicalDisk_keepsRealDiskZeroWhenMixed(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
MaxVolumeCount: 30,
|
||||
DiskId: 6, // seeded from volumes[0].DiskId in ToDiskInfo
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 60, DiskId: 6},
|
||||
{Id: 61, DiskId: 6},
|
||||
{Id: 1, DiskId: 0}, // real disk 0, must not be remapped to 6
|
||||
{Id: 2, DiskId: 0},
|
||||
{Id: 30, DiskId: 3},
|
||||
},
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
byID := map[uint32]*DiskInfo{}
|
||||
for _, di := range got {
|
||||
byID[di.DiskId] = di
|
||||
}
|
||||
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("want 3 physical disks (0, 3, 6), got %d: %v", len(got), byID)
|
||||
}
|
||||
if _, ok := byID[0]; !ok {
|
||||
t.Fatalf("physical disk 0 was dropped; got disks %v", byID)
|
||||
}
|
||||
if byID[0].VolumeCount != 2 {
|
||||
t.Errorf("disk 0: want 2 volumes, got %d", byID[0].VolumeCount)
|
||||
}
|
||||
if byID[6].VolumeCount != 2 {
|
||||
t.Errorf("disk 6: want 2 volumes (not merged with disk 0), got %d", byID[6].VolumeCount)
|
||||
}
|
||||
if byID[3].VolumeCount != 1 {
|
||||
t.Errorf("disk 3: want 1 volume, got %d", byID[3].VolumeCount)
|
||||
}
|
||||
|
||||
var sumMax int64
|
||||
for _, di := range got {
|
||||
sumMax += di.MaxVolumeCount
|
||||
}
|
||||
if sumMax != 30 {
|
||||
t.Errorf("sum of MaxVolumeCount = %d, want 30 (lossless split)", sumMax)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_nilSafe(t *testing.T) {
|
||||
var d *DiskInfo
|
||||
if got := d.SplitByPhysicalDisk(); got != nil {
|
||||
|
||||
@@ -711,6 +711,7 @@ message ScrubEcVolumeRequest {
|
||||
VolumeScrubMode mode = 1;
|
||||
// optional list of volume IDs to scrub. if empty, all EC volumes for the server are scrubbed.
|
||||
repeated uint32 volume_ids = 2;
|
||||
bool force_deleted_needles_check = 3; // FULL mode only; may report false positives when EC indexes disagree
|
||||
}
|
||||
message ScrubEcVolumeResponse {
|
||||
uint64 total_volumes = 1;
|
||||
|
||||
@@ -6018,9 +6018,10 @@ type ScrubEcVolumeRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Mode VolumeScrubMode `protobuf:"varint,1,opt,name=mode,proto3,enum=volume_server_pb.VolumeScrubMode" json:"mode,omitempty"`
|
||||
// optional list of volume IDs to scrub. if empty, all EC volumes for the server are scrubbed.
|
||||
VolumeIds []uint32 `protobuf:"varint,2,rep,packed,name=volume_ids,json=volumeIds,proto3" json:"volume_ids,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
VolumeIds []uint32 `protobuf:"varint,2,rep,packed,name=volume_ids,json=volumeIds,proto3" json:"volume_ids,omitempty"`
|
||||
ForceDeletedNeedlesCheck bool `protobuf:"varint,3,opt,name=force_deleted_needles_check,json=forceDeletedNeedlesCheck,proto3" json:"force_deleted_needles_check,omitempty"` // FULL mode only; may report false positives when EC indexes disagree
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *ScrubEcVolumeRequest) Reset() {
|
||||
@@ -6067,6 +6068,13 @@ func (x *ScrubEcVolumeRequest) GetVolumeIds() []uint32 {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ScrubEcVolumeRequest) GetForceDeletedNeedlesCheck() bool {
|
||||
if x != nil {
|
||||
return x.ForceDeletedNeedlesCheck
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ScrubEcVolumeResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
TotalVolumes uint64 `protobuf:"varint,1,opt,name=total_volumes,json=totalVolumes,proto3" json:"total_volumes,omitempty"`
|
||||
@@ -7510,11 +7518,12 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\vtotal_files\x18\x02 \x01(\x04R\n" +
|
||||
"totalFiles\x12*\n" +
|
||||
"\x11broken_volume_ids\x18\x03 \x03(\rR\x0fbrokenVolumeIds\x12\x18\n" +
|
||||
"\adetails\x18\x04 \x03(\tR\adetails\"l\n" +
|
||||
"\adetails\x18\x04 \x03(\tR\adetails\"\xab\x01\n" +
|
||||
"\x14ScrubEcVolumeRequest\x125\n" +
|
||||
"\x04mode\x18\x01 \x01(\x0e2!.volume_server_pb.VolumeScrubModeR\x04mode\x12\x1d\n" +
|
||||
"\n" +
|
||||
"volume_ids\x18\x02 \x03(\rR\tvolumeIds\"\xf0\x01\n" +
|
||||
"volume_ids\x18\x02 \x03(\rR\tvolumeIds\x12=\n" +
|
||||
"\x1bforce_deleted_needles_check\x18\x03 \x01(\bR\x18forceDeletedNeedlesCheck\"\xf0\x01\n" +
|
||||
"\x15ScrubEcVolumeResponse\x12#\n" +
|
||||
"\rtotal_volumes\x18\x01 \x01(\x04R\ftotalVolumes\x12\x1f\n" +
|
||||
"\vtotal_files\x18\x02 \x01(\x04R\n" +
|
||||
|
||||
@@ -1166,7 +1166,7 @@ func (h *HybridMessageScanner) extractParquetFileStats(entry *filer_pb.Entry, lo
|
||||
fileSize := filer.FileSize(entry)
|
||||
visibleIntervals, _ := filer.NonOverlappingVisibleIntervals(context.Background(), lookupFileIdFn, entry.Chunks, 0, int64(fileSize))
|
||||
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, 0, int64(fileSize))
|
||||
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn)
|
||||
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn, nil)
|
||||
readerAt := filer.NewChunkReaderAtFromClient(context.Background(), readerCache, chunkViews, int64(fileSize), filer.DefaultPrefetchCount)
|
||||
|
||||
// Create parquet reader - this only reads metadata, not data
|
||||
|
||||
@@ -283,6 +283,9 @@ func (gcs *gcsRemoteStorageClient) UpdateFileMetadata(loc *remote_pb.RemoteStora
|
||||
func (gcs *gcsRemoteStorageClient) DeleteFile(loc *remote_pb.RemoteStorageLocation) (err error) {
|
||||
key := loc.Path[1:]
|
||||
if err = gcs.client.Bucket(loc.Bucket).Object(key).Delete(context.Background()); err != nil {
|
||||
if errors.Is(err, storage.ErrObjectNotExist) {
|
||||
return remote_storage.ErrRemoteObjectNotFound
|
||||
}
|
||||
return fmt.Errorf("gcs delete %s%s: %v", loc.Bucket, key, err)
|
||||
}
|
||||
return
|
||||
|
||||
@@ -187,6 +187,17 @@ func (fs *FilerSink) uploadManifestChunk(path string, sourceMtimeNs int64, sourc
|
||||
|
||||
retryName := fmt.Sprintf("replicate manifest chunk %s", sourceFileId)
|
||||
err = util.RetryUntil(retryName, func() error {
|
||||
uploadOption := &operation.UploadOption{
|
||||
Filename: "",
|
||||
Cipher: false,
|
||||
IsInputCompressed: false,
|
||||
MimeType: "application/octet-stream",
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
}
|
||||
if fs.writeChunkByFiler {
|
||||
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(fs.address)
|
||||
}
|
||||
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
@@ -198,17 +209,7 @@ func (fs *FilerSink) uploadManifestChunk(path string, sourceMtimeNs int64, sourc
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: "",
|
||||
Cipher: false,
|
||||
IsInputCompressed: false,
|
||||
MimeType: "application/octet-stream",
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
return fs.buildUploadUrl(host, fileId)
|
||||
},
|
||||
uploadOption,
|
||||
bytes.NewReader(manifestData),
|
||||
)
|
||||
if uploadErr != nil {
|
||||
@@ -302,6 +303,18 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string,
|
||||
transferStatus.Status = "uploading"
|
||||
transferStatus.mu.Unlock()
|
||||
|
||||
uploadOption := &operation.UploadOption{
|
||||
Filename: savedFilename,
|
||||
Cipher: false,
|
||||
IsInputCompressed: "gzip" == savedHeader.Get("Content-Encoding"),
|
||||
MimeType: savedHeader.Get("Content-Type"),
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
SourceUrl: savedSourceUrl,
|
||||
}
|
||||
if fs.writeChunkByFiler {
|
||||
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(fs.address)
|
||||
}
|
||||
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
|
||||
fs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
@@ -313,20 +326,7 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string,
|
||||
DiskType: fs.diskType,
|
||||
Path: path,
|
||||
},
|
||||
&operation.UploadOption{
|
||||
Filename: savedFilename,
|
||||
Cipher: false,
|
||||
IsInputCompressed: "gzip" == savedHeader.Get("Content-Encoding"),
|
||||
MimeType: savedHeader.Get("Content-Type"),
|
||||
PairMap: nil,
|
||||
RetryForever: false,
|
||||
SourceUrl: savedSourceUrl,
|
||||
},
|
||||
func(host, fileId string) string {
|
||||
fileUrl := fs.buildUploadUrl(host, fileId)
|
||||
glog.V(4).Infof("replicating %s to %s header:%+v", savedFilename, fileUrl, savedHeader)
|
||||
return fileUrl
|
||||
},
|
||||
uploadOption,
|
||||
util.NewBytesReader(fullData),
|
||||
)
|
||||
if uploadErr != nil {
|
||||
@@ -435,13 +435,6 @@ func validateReplicatedReadSize(sourceChunk *filer_pb.FileChunk, readSize int) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fs *FilerSink) buildUploadUrl(host, fileId string) string {
|
||||
if fs.writeChunkByFiler {
|
||||
return fmt.Sprintf("http://%s/?proxyChunkId=%s", fs.address, fileId)
|
||||
}
|
||||
return fmt.Sprintf("http://%s/%s", host, fileId)
|
||||
}
|
||||
|
||||
// hasSourceNewerVersion reports whether the source's current entry for targetPath
|
||||
// has moved past sourceMtimeNs — gone, or a strictly-newer mtime — meaning the
|
||||
// version being replayed is stale. The lookup runs regardless of sourceMtimeNs so
|
||||
|
||||
@@ -2059,18 +2059,21 @@ func (iam *IdentityAccessManagement) PruneBucketFromConfiguration(ctx context.Co
|
||||
}
|
||||
|
||||
// actionScopedToBucket reports whether a configured action string like
|
||||
// "Read:bucket" or "Write:bucket/prefix" is scoped exclusively to the given
|
||||
// bucket. Wildcard resources are never considered scoped to a single bucket.
|
||||
// "Read:bucket", "Write:bucket/prefix" or "Write:bucket/prefix/*" is scoped
|
||||
// exclusively to the given bucket. A wildcard in the bucket segment (e.g. "*"
|
||||
// or "buck*/x") may cover other buckets and is never single-bucket scoped; a
|
||||
// wildcard confined to the object path stays scoped to this bucket.
|
||||
func actionScopedToBucket(action, bucket string) bool {
|
||||
idx := strings.Index(action, ":")
|
||||
if idx < 0 {
|
||||
return false
|
||||
}
|
||||
resource := action[idx+1:]
|
||||
if strings.ContainsAny(resource, "*?") {
|
||||
bucketSeg, _, _ := strings.Cut(resource, "/")
|
||||
if strings.ContainsAny(bucketSeg, "*?") {
|
||||
return false
|
||||
}
|
||||
return resource == bucket || strings.HasPrefix(resource, bucket+"/")
|
||||
return bucketSeg == bucket
|
||||
}
|
||||
|
||||
// LoadS3ApiConfigurationFromCredentialManager loads configuration using the credential manager
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package s3api
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestActionScopedToBucket(t *testing.T) {
|
||||
cases := []struct {
|
||||
action string
|
||||
bucket string
|
||||
want bool
|
||||
}{
|
||||
{"Read:bucket", "bucket", true},
|
||||
{"Write:bucket/prefix", "bucket", true},
|
||||
{"Write:bucket/prefix/*", "bucket", true},
|
||||
{"Write:bucket/*", "bucket", true},
|
||||
{"Read:other/prefix/*", "bucket", false},
|
||||
{"Write:*", "bucket", false},
|
||||
{"Write:buck*/x", "bucket", false},
|
||||
{"Write:bucketother", "bucket", false},
|
||||
{"Admin", "bucket", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := actionScopedToBucket(c.action, c.bucket); got != c.want {
|
||||
t.Errorf("actionScopedToBucket(%q, %q) = %v, want %v", c.action, c.bucket, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -361,8 +361,12 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
entries, _, err := s3a.list(uploadDirectory, "", "", false, s3_constants.MaxS3MultipartParts+1)
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s %s error: %v", *input.Bucket, *input.UploadId, err)
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, nil, s3err.ErrNoSuchUpload
|
||||
if isFilerListNotFound(err) {
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
// a store error must not read as "upload gone": the client would drop a fully-uploaded object
|
||||
return nil, nil, s3err.ErrInternalError
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
@@ -372,8 +376,11 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
pentry, err := s3a.getEntry(s3a.genUploadsFolder(*input.Bucket), *input.UploadId)
|
||||
if err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s %s error: %v", *input.Bucket, *input.UploadId, err)
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, nil, s3err.ErrNoSuchUpload
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
|
||||
return nil, nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
return nil, nil, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
deleteEntries := make([]*filer_pb.Entry, 0)
|
||||
@@ -882,8 +889,10 @@ func (s3a *S3ApiServer) abortMultipartUpload(input *s3.AbortMultipartUploadInput
|
||||
|
||||
exists, err := s3a.exists(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("bucket %s abort upload %s: %v", *input.Bucket, *input.UploadId, err)
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
// filer_pb.Exists reports not-found as (false, nil), so an error here is
|
||||
// always a store failure; answering NoSuchUpload would leak the parts.
|
||||
glog.Errorf("bucket %s abort upload %s: %v", *input.Bucket, *input.UploadId, err)
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
if exists {
|
||||
err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true, true)
|
||||
@@ -930,8 +939,14 @@ func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput
|
||||
|
||||
entries, _, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), "", *input.UploadIdMarker, false, math.MaxInt32)
|
||||
if err != nil {
|
||||
// A missing .uploads folder normally lists as empty with no error; a
|
||||
// store that reports it as not-found still means an empty list.
|
||||
if isFilerListNotFound(err) {
|
||||
return output, s3err.ErrNone
|
||||
}
|
||||
// surface a real store error; a masked empty 200 makes a resuming client treat the upload as gone
|
||||
glog.Errorf("listMultipartUploads %s error: %v", *input.Bucket, err)
|
||||
return
|
||||
return output, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
uploadsCount := int64(0)
|
||||
@@ -991,8 +1006,13 @@ func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListP
|
||||
|
||||
entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d%s", *input.PartNumberMarker, multipartExt), false, uint32(*input.MaxParts))
|
||||
if err != nil {
|
||||
// A store that reports the missing upload directory as not-found means
|
||||
// the upload is gone (completed or aborted), not a store error.
|
||||
if isFilerListNotFound(err) {
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
}
|
||||
glog.Errorf("listObjectParts %s %s error: %v", *input.Bucket, *input.UploadId, err)
|
||||
return nil, s3err.ErrNoSuchUpload
|
||||
return nil, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
// Note: The upload directory is sort of a marker of the existence of an multipart upload request.
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// isFilerListNotFound reports whether a filer list error is a not-found.
|
||||
// Unlike lookups (normalized in filer_pb.LookupEntry), list errors cross gRPC
|
||||
// as raw status errors, so the sentinel survives only as text. Callers must
|
||||
// pass errors from paths without user-controlled segments that could spoof it.
|
||||
func isFilerListNotFound(err error) bool {
|
||||
return errors.Is(err, filer_pb.ErrNotFound) || strings.Contains(err.Error(), filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
|
||||
// ErrorHandlers provide common error handling patterns for S3 API operations
|
||||
|
||||
// handleMultipartError logs an error and returns the standard multipart error format
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestClassifyCopySourceError(t *testing.T) {
|
||||
deleteMarker := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte("true")},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
entry *filer_pb.Entry
|
||||
err error
|
||||
want s3err.ErrorCode
|
||||
}{
|
||||
{"regular entry", &filer_pb.Entry{Name: "o"}, nil, s3err.ErrNone},
|
||||
{"nil entry", nil, nil, s3err.ErrInvalidCopySource},
|
||||
{"directory entry", &filer_pb.Entry{IsDirectory: true}, nil, s3err.ErrInvalidCopySource},
|
||||
{"delete marker entry", deleteMarker, nil, s3err.ErrNoSuchKey},
|
||||
{"not found sentinel", nil, filer_pb.ErrNotFound, s3err.ErrInvalidCopySource},
|
||||
{"wrapped not found", nil, fmt.Errorf("read %s: %w", "o", filer_pb.ErrNotFound), s3err.ErrInvalidCopySource},
|
||||
{"grpc not found", nil, status.Error(codes.NotFound, "no entry"), s3err.ErrInvalidCopySource},
|
||||
{"invalid version id", nil, errInvalidVersionID, s3err.ErrInvalidCopySource},
|
||||
{"delete marker error", nil, ErrDeleteMarker, s3err.ErrInvalidCopySource},
|
||||
{"transient unavailable", nil, status.Error(codes.Unavailable, "filer down"), s3err.ErrServiceUnavailable},
|
||||
{"store error", nil, errors.New("connection reset"), s3err.ErrInternalError},
|
||||
// A message merely mentioning the sentinel text must not downgrade a store error.
|
||||
{"sentinel text in message", nil, fmt.Errorf("peer said: %s", filer_pb.ErrNotFound.Error()), s3err.ErrInternalError},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := classifyCopySourceError(tt.entry, tt.err); got != tt.want {
|
||||
t.Errorf("classifyCopySourceError() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -989,15 +989,11 @@ func (e *EmbeddedIamApi) getActions(policy *policy_engine.PolicyDocument) ([]str
|
||||
// Bucket-level or bucket/* - use just bucket name
|
||||
actions = append(actions, fmt.Sprintf("%s:%s", statementAction, bucket))
|
||||
} else {
|
||||
// Path-specific: bucket/path/* -> Action:bucket/path
|
||||
// Remove trailing /* if present for cleaner action format
|
||||
objectPath = strings.TrimSuffix(objectPath, "/*")
|
||||
objectPath = strings.TrimSuffix(objectPath, "*")
|
||||
if objectPath == "" {
|
||||
actions = append(actions, fmt.Sprintf("%s:%s", statementAction, bucket))
|
||||
} else {
|
||||
actions = append(actions, fmt.Sprintf("%s:%s/%s", statementAction, bucket, objectPath))
|
||||
}
|
||||
// Path-specific: preserve the object path, including any
|
||||
// trailing wildcard, so CanDo can match objects under the
|
||||
// prefix. Stripping the wildcard yielded a non-wildcard
|
||||
// action that only matched at bucket level.
|
||||
actions = append(actions, fmt.Sprintf("%s:%s/%s", statementAction, bucket, objectPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2095,6 +2095,43 @@ func TestEmbeddedIamGetActionsFromPolicy(t *testing.T) {
|
||||
assert.Contains(t, actions, "Write:mybucket")
|
||||
}
|
||||
|
||||
// TestEmbeddedIamGetActionsPrefixScopedResource verifies that a prefix-scoped
|
||||
// resource keeps its trailing wildcard so CanDo authorizes objects under the
|
||||
// prefix. Stripping the wildcard produced a non-wildcard action that only
|
||||
// matched at bucket level, denying every PutObject under the prefix.
|
||||
func TestEmbeddedIamGetActionsPrefixScopedResource(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
|
||||
policyDoc := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:Get*", "s3:Put*", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::mcp-upload/mcp/TMS/api_keys/example/*"]
|
||||
}]
|
||||
}`
|
||||
|
||||
policy, err := api.GetPolicyDocument(&policyDoc)
|
||||
require.NoError(t, err)
|
||||
|
||||
actions, err := api.getActions(&policy)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, actions, "Read:mcp-upload/mcp/TMS/api_keys/example/*")
|
||||
assert.Contains(t, actions, "Write:mcp-upload/mcp/TMS/api_keys/example/*")
|
||||
|
||||
identity := &Identity{Name: "prefix-user"}
|
||||
for _, a := range actions {
|
||||
identity.Actions = append(identity.Actions, Action(a))
|
||||
}
|
||||
|
||||
assert.True(t, identity.CanDo(ACTION_WRITE, "mcp-upload", "mcp/TMS/api_keys/example/logo.png"),
|
||||
"PutObject under the allowed prefix should be authorized")
|
||||
assert.True(t, identity.CanDo(ACTION_READ, "mcp-upload", "mcp/TMS/api_keys/example/logo.png"),
|
||||
"GetObject under the allowed prefix should be authorized")
|
||||
assert.False(t, identity.CanDo(ACTION_WRITE, "mcp-upload", "other/logo.png"),
|
||||
"PutObject outside the allowed prefix should be denied")
|
||||
}
|
||||
|
||||
// TestEmbeddedIamPutUserPolicyAllResourceWildcard reproduces issue #9209:
|
||||
// an AWS-style policy using "Action":"s3:*" with a bare "Resource":"*" is
|
||||
// valid AWS IAM syntax (meaning "any resource") but was rejected with
|
||||
|
||||
@@ -24,6 +24,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -67,6 +69,31 @@ func hasPrefixFold(s, prefix string) bool {
|
||||
return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
|
||||
}
|
||||
|
||||
// classifyCopySourceError maps a copy-source lookup to an S3 error: a missing,
|
||||
// invalid, or directory source stays a client error, but a transient store
|
||||
// error becomes a retryable 5xx so a resumable copy/commit survives a blip.
|
||||
func classifyCopySourceError(entry *filer_pb.Entry, err error) s3err.ErrorCode {
|
||||
if err == nil {
|
||||
if entry == nil || entry.IsDirectory {
|
||||
return s3err.ErrInvalidCopySource
|
||||
}
|
||||
// The latest-version pointer tracks delete markers too; copying one
|
||||
// must be NoSuchKey like every other handler, not a copy of the stub.
|
||||
if deleteMarker, ok := entry.Extended[s3_constants.ExtDeleteMarkerKey]; ok && string(deleteMarker) == "true" {
|
||||
return s3err.ErrNoSuchKey
|
||||
}
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || status.Code(err) == codes.NotFound ||
|
||||
errors.Is(err, errInvalidVersionID) || errors.Is(err, ErrDeleteMarker) {
|
||||
return s3err.ErrInvalidCopySource
|
||||
}
|
||||
if isTransientFilerError(err) {
|
||||
return s3err.ErrServiceUnavailable
|
||||
}
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request) {
|
||||
t := time.Now().UTC().Truncate(time.Millisecond)
|
||||
|
||||
@@ -144,13 +171,19 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
srcVersioningState, err := s3a.getVersioningState(srcBucket)
|
||||
if err != nil {
|
||||
glog.Errorf("Error checking versioning state for source bucket %s: %v", srcBucket, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
// Only a missing bucket is the client's fault; a store error must stay
|
||||
// retryable, matching the destination-bucket lookup.
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := s3a.resolveCopySourceEntry(srcBucket, srcObject, srcVersionId, srcVersioningState)
|
||||
if err != nil || entry.IsDirectory {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
if errCode := classifyCopySourceError(entry, err); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -216,8 +249,8 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
routeInPlace := owner != "" && dstVersioningState == "" && !mimeChanged
|
||||
selfCopyBody := func() s3err.ErrorCode {
|
||||
currentEntry, currentErr := s3a.resolveCopySourceEntry(srcBucket, srcObject, srcVersionId, srcVersioningState)
|
||||
if currentErr != nil || currentEntry.IsDirectory {
|
||||
return s3err.ErrInvalidCopySource
|
||||
if errCode := classifyCopySourceError(currentEntry, currentErr); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
if errCode := s3a.validateConditionalCopyHeaders(r, currentEntry); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
@@ -828,12 +861,22 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPart)
|
||||
return
|
||||
}
|
||||
if partID < 1 {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPart)
|
||||
return
|
||||
}
|
||||
|
||||
// Get detailed versioning state for source bucket
|
||||
srcVersioningState, err := s3a.getVersioningState(srcBucket)
|
||||
if err != nil {
|
||||
glog.Errorf("Error checking versioning state for source bucket %s: %v", srcBucket, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
// Only a missing bucket is the client's fault; a store error must stay
|
||||
// retryable, matching the destination-bucket lookup.
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -856,8 +899,8 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
entry, err = s3a.getEntry(dir, name)
|
||||
}
|
||||
|
||||
if err != nil || entry.IsDirectory {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
if errCode := classifyCopySourceError(entry, err); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -545,10 +545,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
s3a.deleteOrphanedChunks(chunkResult.FileChunks)
|
||||
}
|
||||
|
||||
if strings.Contains(err.Error(), s3err.ErrMsgPayloadChecksumMismatch) {
|
||||
return "", s3err.ErrInvalidDigest, SSEResponseMetadata{}
|
||||
}
|
||||
return "", s3err.ErrInternalError, SSEResponseMetadata{}
|
||||
return "", mapChunkedUploadErrorToS3Error(err), SSEResponseMetadata{}
|
||||
}
|
||||
|
||||
// Step 3: Calculate MD5 hash and add SSE metadata to chunks
|
||||
@@ -1170,6 +1167,22 @@ func filerErrorToS3Error(err error) s3err.ErrorCode {
|
||||
}
|
||||
}
|
||||
|
||||
// mapChunkedUploadErrorToS3Error classifies a failed streaming upload. A truncated
|
||||
// request body (client abort or reverse-proxy timeout) is a request error, so report
|
||||
// IncompleteBody (400) rather than a 500 a reverse proxy would relay as a confusing
|
||||
// 502. Only the source read is tagged, so a volume-server upload fault still maps to
|
||||
// InternalError.
|
||||
func mapChunkedUploadErrorToS3Error(err error) s3err.ErrorCode {
|
||||
switch {
|
||||
case strings.Contains(err.Error(), s3err.ErrMsgPayloadChecksumMismatch):
|
||||
return s3err.ErrInvalidDigest
|
||||
case errors.Is(err, operation.ErrTruncatedBody):
|
||||
return s3err.ErrIncompleteBody
|
||||
default:
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
}
|
||||
|
||||
// setObjectOwnerFromRequest sets the object owner metadata based on the bucket ownership policy.
|
||||
// When BucketOwnerEnforced (the modern AWS default), the bucket owner owns all objects.
|
||||
// Otherwise, the uploader's account ID is used (ObjectWriter mode).
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
func TestMapChunkedUploadErrorToS3Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
want s3err.ErrorCode
|
||||
}{
|
||||
{
|
||||
// A truncated body (client abort or reverse-proxy timeout) reaches
|
||||
// putToFiler tagged exactly like UploadReaderInChunks reports it.
|
||||
name: "truncated source read maps to IncompleteBody",
|
||||
err: fmt.Errorf("%w: read chunk at offset %d (got %d bytes): %w", operation.ErrTruncatedBody, 0, 8056500, io.ErrUnexpectedEOF),
|
||||
want: s3err.ErrIncompleteBody,
|
||||
},
|
||||
{
|
||||
// A volume-server upload dropping mid-write is a server fault, not a
|
||||
// client truncation, even though it also carries io.ErrUnexpectedEOF.
|
||||
name: "volume upload unexpected EOF maps to InternalError",
|
||||
err: fmt.Errorf("upload chunk: %w", io.ErrUnexpectedEOF),
|
||||
want: s3err.ErrInternalError,
|
||||
},
|
||||
{
|
||||
name: "payload checksum mismatch maps to InvalidDigest",
|
||||
err: errors.New(s3err.ErrMsgPayloadChecksumMismatch),
|
||||
want: s3err.ErrInvalidDigest,
|
||||
},
|
||||
{
|
||||
name: "other errors map to InternalError",
|
||||
err: errors.New("assign volume: no free volumes"),
|
||||
want: s3err.ErrInternalError,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := mapChunkedUploadErrorToS3Error(tt.err); got != tt.want {
|
||||
t.Errorf("mapChunkedUploadErrorToS3Error(%v) = %v, want %v", tt.err, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1849,7 +1849,7 @@ func (s3a *S3ApiServer) recoverLatestVersionWithoutPointer(bucket, normalizedObj
|
||||
return nil, healErr
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("no version metadata in .versions directory and no regular object found for %s/%s", bucket, normalizedObject)
|
||||
return nil, fmt.Errorf("no version metadata in .versions directory and no regular object found for %s/%s: %w", bucket, normalizedObject, filer_pb.ErrNotFound)
|
||||
}
|
||||
|
||||
// versionIdFromEntry returns a .versions child entry's version id, preferring
|
||||
|
||||
@@ -277,7 +277,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
} else {
|
||||
chunkCache = (*chunk_cache.TieredChunkCache)(nil)
|
||||
}
|
||||
readerCache := filer.NewReaderCache(s3ReaderCacheDownloaderLimit, chunkCache, filerClient.GetLookupFileIdFunction())
|
||||
readerCache := filer.NewReaderCache(s3ReaderCacheDownloaderLimit, chunkCache, filerClient.GetLookupFileIdFunction(), filerClient)
|
||||
|
||||
s3ApiServer = &S3ApiServer{
|
||||
option: option,
|
||||
|
||||
@@ -155,6 +155,9 @@ const (
|
||||
ErrKeyTooLongError
|
||||
|
||||
ErrNoSuchConfiguration
|
||||
|
||||
// Truncated request body (fewer bytes than Content-Length)
|
||||
ErrIncompleteBody
|
||||
)
|
||||
|
||||
// Error message constants for checksum validation
|
||||
@@ -297,6 +300,11 @@ var errorCodeResponse = map[ErrorCode]APIError{
|
||||
Description: "We encountered an internal error, please try again.",
|
||||
HTTPStatusCode: http.StatusInternalServerError,
|
||||
},
|
||||
ErrIncompleteBody: {
|
||||
Code: "IncompleteBody",
|
||||
Description: "You did not provide the number of bytes specified by the Content-Length HTTP header.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
|
||||
ErrInvalidPart: {
|
||||
Code: "InvalidPart",
|
||||
|
||||
@@ -173,19 +173,11 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
return &filer_pb.CreateEntryResponse{}, fmt.Errorf("CreateEntry cleanupChunks %s %s: %v", req.Directory, req.Entry.Name, err2)
|
||||
}
|
||||
|
||||
so, err := fs.detectStorageOption(ctx, string(util.NewFullPath(req.Directory, req.Entry.Name)), "", "", 0, "", "", "", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
newEntry := filer.FromPbEntry(req.Directory, req.Entry)
|
||||
newEntry.Chunks = chunks
|
||||
// Don't apply TTL to remote entries - they're managed by remote storage
|
||||
if newEntry.Remote == nil {
|
||||
if newEntry.TtlSec == 0 {
|
||||
newEntry.TtlSec = so.TtlSeconds
|
||||
}
|
||||
} else {
|
||||
newEntry.TtlSec = 0
|
||||
so, err := fs.applyStorageDefaultsToEntry(ctx, newEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Serialize concurrent mutations to the same path on this filer so the
|
||||
@@ -361,6 +353,23 @@ func (fs *FilerServer) ObjectTransactionBatch(ctx context.Context, req *filer_pb
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// applyStorageDefaultsToEntry enforces the path's storage rule (read-only
|
||||
// prefixes reject the write) and fills in the rule TTL when the entry carries
|
||||
// none. Remote entries never expire locally; the remote storage owns their
|
||||
// lifecycle.
|
||||
func (fs *FilerServer) applyStorageDefaultsToEntry(ctx context.Context, entry *filer.Entry) (*operation.StorageOption, error) {
|
||||
so, err := fs.detectStorageOption(ctx, string(entry.FullPath), "", "", 0, "", "", "", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if entry.Remote != nil {
|
||||
entry.TtlSec = 0
|
||||
} else if entry.TtlSec == 0 {
|
||||
entry.TtlSec = so.TtlSeconds
|
||||
}
|
||||
return so, nil
|
||||
}
|
||||
|
||||
// applyObjectMutation applies a single mutation while the transaction's path
|
||||
// lock is held. PUT entries are expected to be fully prepared by the caller
|
||||
// (chunks resolved); mutations here are metadata-scoped. A DELETE of an absent
|
||||
@@ -373,7 +382,11 @@ func (fs *FilerServer) applyObjectMutation(ctx context.Context, m *filer_pb.Obje
|
||||
return fmt.Errorf("PUT requires an entry")
|
||||
}
|
||||
newEntry := filer.FromPbEntry(m.Directory, m.Entry)
|
||||
return fs.filer.CreateEntry(ctx, newEntry, nil, false, fromOtherCluster, signatures, false, fs.filer.MaxFilenameLength)
|
||||
so, err := fs.applyStorageDefaultsToEntry(ctx, newEntry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fs.filer.CreateEntry(ctx, newEntry, nil, false, fromOtherCluster, signatures, false, so.MaxFileNameLength)
|
||||
|
||||
case filer_pb.ObjectMutation_DELETE:
|
||||
fullpath := util.NewFullPath(m.Directory, m.Name)
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func mustSetObjectTxnStorageConf(t *testing.T, fs *FilerServer, conf *filer_pb.FilerConf_PathConf) {
|
||||
t.Helper()
|
||||
|
||||
if err := fs.filer.FilerConf.SetLocationConf(conf); err != nil {
|
||||
t.Fatalf("SetLocationConf(%q): %v", conf.LocationPrefix, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectTransactionPutAppliesConfiguredTTLAndExpires(t *testing.T) {
|
||||
fs, store := newTxnTestServer(nil)
|
||||
|
||||
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/video/",
|
||||
Ttl: "1h",
|
||||
})
|
||||
|
||||
old := time.Now().Add(-2 * time.Hour)
|
||||
|
||||
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: "/buckets/video/expired.mp4",
|
||||
Mutations: []*filer_pb.ObjectMutation{
|
||||
{
|
||||
Type: filer_pb.ObjectMutation_PUT,
|
||||
Directory: "/buckets/video",
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "expired.mp4",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: old.Unix(),
|
||||
Mtime: old.Unix(),
|
||||
FileMode: 0644,
|
||||
FileSize: 123,
|
||||
TtlSec: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ObjectTransaction transport error: %v", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
t.Fatalf("ObjectTransaction response error: %q", resp.Error)
|
||||
}
|
||||
|
||||
entry := store.entries["/buckets/video/expired.mp4"]
|
||||
if entry == nil {
|
||||
t.Fatalf("PUT should create /buckets/video/expired.mp4")
|
||||
}
|
||||
if got := entry.TtlSec; got != 3600 {
|
||||
t.Fatalf("TtlSec = %d, want 3600 from fs.configure storage rule", got)
|
||||
}
|
||||
|
||||
_, err = fs.filer.FindEntry(context.Background(), util.FullPath("/buckets/video/expired.mp4"))
|
||||
if err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("expired entry lookup error = %v, want %v", err, filer_pb.ErrNotFound)
|
||||
}
|
||||
|
||||
if _, ok := store.entries["/buckets/video/expired.mp4"]; ok {
|
||||
t.Fatalf("expired entry should be deleted from metadata store")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectTransactionPutPreservesExplicitTTL(t *testing.T) {
|
||||
fs, store := newTxnTestServer(nil)
|
||||
|
||||
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/video/",
|
||||
Ttl: "1h",
|
||||
})
|
||||
|
||||
now := time.Unix(1700000000, 0)
|
||||
|
||||
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: "/buckets/video/lifecycle.mp4",
|
||||
Mutations: []*filer_pb.ObjectMutation{
|
||||
{
|
||||
Type: filer_pb.ObjectMutation_PUT,
|
||||
Directory: "/buckets/video",
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "lifecycle.mp4",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: now.Unix(),
|
||||
Mtime: now.Unix(),
|
||||
FileMode: 0644,
|
||||
FileSize: 123,
|
||||
TtlSec: 7200,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ObjectTransaction transport error: %v", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
t.Fatalf("ObjectTransaction response error: %q", resp.Error)
|
||||
}
|
||||
|
||||
entry := store.entries["/buckets/video/lifecycle.mp4"]
|
||||
if entry == nil {
|
||||
t.Fatalf("PUT should create /buckets/video/lifecycle.mp4")
|
||||
}
|
||||
if got := entry.TtlSec; got != 7200 {
|
||||
t.Fatalf("TtlSec = %d, want explicit TTL 7200 to win over fs.configure", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectTransactionPutClearsTTLForRemoteEntry(t *testing.T) {
|
||||
fs, store := newTxnTestServer(nil)
|
||||
|
||||
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/video/",
|
||||
Ttl: "1h",
|
||||
})
|
||||
|
||||
now := time.Unix(1700000000, 0)
|
||||
|
||||
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: "/buckets/video/remote",
|
||||
Mutations: []*filer_pb.ObjectMutation{
|
||||
{
|
||||
Type: filer_pb.ObjectMutation_PUT,
|
||||
Directory: "/buckets/video",
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "remote",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: now.Unix(),
|
||||
Mtime: now.Unix(),
|
||||
FileMode: 0644,
|
||||
FileSize: 123,
|
||||
TtlSec: 7200,
|
||||
},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 123},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ObjectTransaction transport error: %v", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
t.Fatalf("ObjectTransaction response error: %q", resp.Error)
|
||||
}
|
||||
|
||||
entry := store.entries["/buckets/video/remote"]
|
||||
if entry == nil {
|
||||
t.Fatalf("remote entry should be created")
|
||||
}
|
||||
if got := entry.TtlSec; got != 0 {
|
||||
t.Fatalf("remote entry TtlSec = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectTransactionPutHonorsMaxFileNameLengthRule(t *testing.T) {
|
||||
fs, store := newTxnTestServer(nil)
|
||||
|
||||
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/video/",
|
||||
MaxFileNameLength: 8,
|
||||
})
|
||||
|
||||
now := time.Unix(1700000000, 0)
|
||||
|
||||
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: "/buckets/video/toolong.mp4",
|
||||
Mutations: []*filer_pb.ObjectMutation{
|
||||
{
|
||||
Type: filer_pb.ObjectMutation_PUT,
|
||||
Directory: "/buckets/video",
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "toolong.mp4",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: now.Unix(),
|
||||
Mtime: now.Unix(),
|
||||
FileMode: 0644,
|
||||
FileSize: 123,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ObjectTransaction transport error: %v", err)
|
||||
}
|
||||
if resp.Error == "" {
|
||||
t.Fatalf("ObjectTransaction should reject a name longer than the rule's max_file_name_length")
|
||||
}
|
||||
|
||||
if _, ok := store.entries["/buckets/video/toolong.mp4"]; ok {
|
||||
t.Fatalf("over-long name must not create the entry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectTransactionPutFailsOnReadOnlyStorageConfig(t *testing.T) {
|
||||
// An explicit TTL must not bypass the read-only rule.
|
||||
for _, ttlSec := range []int32{0, 7200} {
|
||||
fs, store := newTxnTestServer(nil)
|
||||
|
||||
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/video/",
|
||||
ReadOnly: true,
|
||||
})
|
||||
|
||||
now := time.Unix(1700000000, 0)
|
||||
|
||||
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: "/buckets/video/readonly.mp4",
|
||||
Mutations: []*filer_pb.ObjectMutation{
|
||||
{
|
||||
Type: filer_pb.ObjectMutation_PUT,
|
||||
Directory: "/buckets/video",
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "readonly.mp4",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: now.Unix(),
|
||||
Mtime: now.Unix(),
|
||||
FileMode: 0644,
|
||||
FileSize: 123,
|
||||
TtlSec: ttlSec,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("TtlSec=%d: ObjectTransaction transport error: %v", ttlSec, err)
|
||||
}
|
||||
if resp.Error == "" {
|
||||
t.Fatalf("TtlSec=%d: ObjectTransaction should report read-only storage config error", ttlSec)
|
||||
}
|
||||
|
||||
if _, ok := store.entries["/buckets/video/readonly.mp4"]; ok {
|
||||
t.Fatalf("TtlSec=%d: read-only storage config must not create the entry", ttlSec)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -254,5 +254,16 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
func (fs *FilerServer) maybeGetVolumeReadJwtAuthorizationToken(fileId string) string {
|
||||
return string(security.GenJwtForVolumeServer(fs.volumeGuard.ReadSigningKey(), fs.volumeGuard.ReadExpiresAfterSec(), fileId))
|
||||
// Generate a read JWT for volume server access. If the dedicated
|
||||
// read key (jwt.signing.read.key) is not configured, fall back to the
|
||||
// general signing key (jwt.signing.key) so the proxy can still
|
||||
// authenticate to volume servers that require JWT.
|
||||
key := fs.volumeGuard.ReadSigningKey()
|
||||
if len(key) == 0 {
|
||||
key = fs.volumeGuard.SigningKey()
|
||||
}
|
||||
if len(key) == 0 {
|
||||
return ""
|
||||
}
|
||||
return string(security.GenJwtForVolumeServer(key, fs.volumeGuard.ReadExpiresAfterSec(), fileId))
|
||||
}
|
||||
@@ -172,6 +172,7 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
|
||||
}
|
||||
|
||||
dn.AdjustMaxVolumeCounts(heartbeat.MaxVolumeCounts)
|
||||
dn.AdjustDiskUsageBytes(heartbeat.DiskTotalBytes, heartbeat.DiskFreeBytes)
|
||||
dn.UpdateDiskTags(heartbeat.DiskTags)
|
||||
|
||||
glog.V(4).Infof("master received heartbeat %s", heartbeat.String())
|
||||
|
||||
@@ -93,6 +93,13 @@ func (vs *VolumeServer) ScrubVolume(ctx context.Context, req *volume_server_pb.S
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb.ScrubEcVolumeRequest) (*volume_server_pb.ScrubEcVolumeResponse, error) {
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.GetForceDeletedNeedlesCheck() && req.GetMode() != volume_server_pb.VolumeScrubMode_FULL {
|
||||
return nil, fmt.Errorf("deleted needle checks are only supported for FULL scrubs")
|
||||
}
|
||||
|
||||
vids := []needle.VolumeId{}
|
||||
if len(req.GetVolumeIds()) == 0 {
|
||||
for _, l := range vs.store.Locations {
|
||||
@@ -124,8 +131,7 @@ func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb
|
||||
case volume_server_pb.VolumeScrubMode_LOCAL:
|
||||
files, shardInfos, serrs = v.ScrubLocal()
|
||||
case volume_server_pb.VolumeScrubMode_FULL:
|
||||
// TODO: expose force_deleted_needles_check in the RPC and weed shell.
|
||||
files, shardInfos, serrs = vs.store.ScrubEcVolume(v.VolumeId, false)
|
||||
files, shardInfos, serrs = vs.store.ScrubEcVolume(v.VolumeId, req.GetForceDeletedNeedlesCheck())
|
||||
case volume_server_pb.VolumeScrubMode_CHECKSUM:
|
||||
// Verify each local shard's raw bytes against the bitrot sidecar,
|
||||
// exercising cold parity shards. Read-only. ChecksumScrub's first
|
||||
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user