Compare commits

..
Author SHA1 Message Date
Chris Lu eed4474e61 master: deprecate legacy seaweedfs/raft
Warn at startup when the legacy raft engine is selected and note the
deprecation in the -raftHashicorp help. The default is unchanged so a
multi-master rolling upgrade is not silently switched to an incompatible
engine mid-cluster; operators opt in, and the identity migration carries
state across.
2026-06-05 14:46:31 -07:00
Chris Lu c5121f3dba master: carry cluster identity from legacy raft into hashicorp raft
On a master's first start on hashicorp raft, import TopologyId and MaxVolumeId
from an existing seaweedfs/raft (legacy) snapshot so the cluster keeps its
identity instead of generating a fresh one. A marker in the hashicorp stable
store makes the import one-time; later restarts skip it. With no legacy state
the marker is still set, so a fresh install never re-scans.
2026-06-05 14:45:33 -07:00
88 changed files with 965 additions and 3579 deletions

No files matched your search

+23 -65
View File
@@ -51,22 +51,22 @@ jobs:
echo "=== Testing default configuration ==="
helm template test $CHART_DIR > /tmp/default.yaml
echo "Default configuration renders successfully"
echo "✓ Default configuration renders successfully"
echo "=== Testing with S3 enabled ==="
helm template test $CHART_DIR --set s3.enabled=true > /tmp/s3.yaml
grep -q "kind: Deployment" /tmp/s3.yaml && grep -q "seaweedfs-s3" /tmp/s3.yaml
echo "S3 deployment renders correctly"
echo "✓ S3 deployment renders correctly"
echo "=== Testing with all-in-one mode ==="
helm template test $CHART_DIR --set allInOne.enabled=true > /tmp/allinone.yaml
grep -q "seaweedfs-all-in-one" /tmp/allinone.yaml
echo "All-in-one deployment renders correctly"
echo "✓ All-in-one deployment renders correctly"
echo "=== Testing with security enabled ==="
helm template test $CHART_DIR --set global.seaweedfs.enableSecurity=true > /tmp/security.yaml
grep -q "security-config" /tmp/security.yaml
echo "Security configuration renders correctly"
echo "✓ Security configuration renders correctly"
echo ""
echo "=== Testing IAM gRPC opt-in path ==="
@@ -121,7 +121,7 @@ jobs:
if configmap(out, "test-seaweedfs-security-config") is not None:
failed.append("defaults: security ConfigMap should not render")
else:
print("defaults: no security-config ConfigMap (unchanged)")
print("✓ defaults: no security-config ConfigMap (unchanged)")
# Case 2: filerWrite=true alone is the documented opt-in for
# the Admin UI Users tab. Configmap must render with
@@ -141,7 +141,7 @@ jobs:
if "[grpc" in toml:
failed.append("filerWrite=true: security.toml unexpectedly has [grpc.*] (would need cert mounts)")
if "[jwt.filer_signing]" in toml and "[grpc" not in toml:
print("filerWrite=true: security.toml has [jwt.filer_signing], no [grpc.*]")
print("✓ filerWrite=true: security.toml has [jwt.filer_signing], no [grpc.*]")
# Case 3: filer + admin pods must MOUNT the security ConfigMap
# under filerWrite=true so the JWT key reaches both processes.
@@ -154,7 +154,7 @@ jobs:
if "security-config" not in vols or "security-config" not in mounts:
failed.append(f"filerWrite=true: {wl} does not mount security-config (IAM gRPC would still fail)")
else:
print(f"filerWrite=true: {wl} mounts security-config")
print(f"✓ filerWrite=true: {wl} mounts security-config")
cert_vols = {v for v in vols if v.endswith("-cert")}
if cert_vols:
failed.append(f"filerWrite=true: {wl} unexpectedly has cert volumes {sorted(cert_vols)}")
@@ -172,7 +172,7 @@ jobs:
if missing:
failed.append(f"enableSecurity=true: security.toml missing {missing}")
else:
print("enableSecurity=true: security.toml has [jwt.signing] + [grpc.*] preserved")
print("✓ enableSecurity=true: security.toml has [jwt.signing] + [grpc.*] preserved")
# Case 5: helper must tolerate explicit nulls (gemini-code-assist
# PR review). securityConfig=null was the parens-pattern crash
@@ -187,7 +187,7 @@ jobs:
if configmap(out, "test-seaweedfs-security-config") is not None:
failed.append(f"{null_path}=null: should not render configmap")
else:
print(f"{null_path}=null: render tolerates explicit null")
print(f"✓ {null_path}=null: render tolerates explicit null")
if failed:
print("\nFAIL:", file=sys.stderr)
@@ -195,14 +195,14 @@ jobs:
print(f" - {f}", file=sys.stderr)
sys.exit(1)
PYEOF
echo "IAM gRPC decoupling tests passed"
echo "✓ IAM gRPC decoupling tests passed"
echo "=== Testing with monitoring enabled ==="
helm template test $CHART_DIR \
--set global.seaweedfs.monitoring.enabled=true \
--set global.seaweedfs.monitoring.gatewayHost=prometheus \
--set global.seaweedfs.monitoring.gatewayPort=9091 > /tmp/monitoring.yaml
echo "Monitoring configuration renders correctly"
echo "✓ Monitoring configuration renders correctly"
echo "=== Testing with PVC storage ==="
helm template test $CHART_DIR \
@@ -210,25 +210,25 @@ jobs:
--set master.data.size=10Gi \
--set master.data.storageClass=standard > /tmp/pvc.yaml
grep -q "PersistentVolumeClaim" /tmp/pvc.yaml
echo "PVC configuration renders correctly"
echo "✓ PVC configuration renders correctly"
echo "=== Testing with custom replicas ==="
helm template test $CHART_DIR \
--set master.replicas=3 \
--set filer.replicas=2 \
--set volume.replicas=3 > /tmp/replicas.yaml
echo "Custom replicas configuration renders correctly"
echo "✓ Custom replicas configuration renders correctly"
echo "=== Testing filer with S3 gateway ==="
helm template test $CHART_DIR \
--set filer.s3.enabled=true \
--set filer.s3.enableAuth=true > /tmp/filer-s3.yaml
echo "Filer S3 gateway renders correctly"
echo "✓ Filer S3 gateway renders correctly"
echo "=== Testing SFTP enabled ==="
helm template test $CHART_DIR --set sftp.enabled=true > /tmp/sftp.yaml
grep -q "seaweedfs-sftp" /tmp/sftp.yaml
echo "SFTP deployment renders correctly"
echo "✓ SFTP deployment renders correctly"
echo "=== Testing ingress configurations ==="
helm template test $CHART_DIR \
@@ -237,12 +237,12 @@ jobs:
--set s3.enabled=true \
--set s3.ingress.enabled=true > /tmp/ingress.yaml
grep -q "kind: Ingress" /tmp/ingress.yaml
echo "Ingress configurations render correctly"
echo "✓ Ingress configurations render correctly"
echo "=== Testing COSI driver ==="
helm template test $CHART_DIR --set cosi.enabled=true > /tmp/cosi.yaml
grep -q "seaweedfs-cosi" /tmp/cosi.yaml
echo "COSI driver renders correctly"
echo "✓ COSI driver renders correctly"
echo ""
echo "=== Testing long release name: service names match DNS references ==="
@@ -285,7 +285,7 @@ jobs:
[ "$MASTER_SVC" = "$MASTER_ADDR_SVC" ] || { echo "FAIL: master service name mismatch"; exit 1; }
[ "$FILER_CLIENT_SVC" = "$FILER_ADDR_SVC" ] || { echo "FAIL: filer-client service name mismatch"; exit 1; }
[ "$FILER_CLIENT_SVC" = "$S3_FILER_SVC" ] || { echo "FAIL: S3 -filer= does not match filer-client service"; exit 1; }
echo "Normal mode: service names match DNS references with long release name"
echo "✓ Normal mode: service names match DNS references with long release name"
# --- All-in-one mode: all-in-one service vs both helper addresses ---
helm template "$LONG_RELEASE" $CHART_DIR \
@@ -305,7 +305,7 @@ jobs:
[ "$AIO_SVC" = "$AIO_MASTER_ADDR_SVC" ] || { echo "FAIL: all-in-one master address mismatch"; exit 1; }
[ "$AIO_SVC" = "$AIO_FILER_ADDR_SVC" ] || { echo "FAIL: all-in-one filer address mismatch"; exit 1; }
echo "All-in-one mode: service names match DNS references with long release name"
echo "✓ All-in-one mode: service names match DNS references with long release name"
echo ""
echo "=== Testing security+S3: no blank lines in shell command blocks ==="
@@ -343,7 +343,7 @@ jobs:
print(f"FAIL: {e}", file=sys.stderr)
print("Rendered with: global.seaweedfs.enableSecurity=true, filer.s3.enabled=true, s3.enabled=true, allInOne.enabled=true", file=sys.stderr)
sys.exit(1)
print("No blank lines in security+S3 command blocks")
print("✓ No blank lines in security+S3 command blocks")
PYEOF
echo ""
@@ -421,7 +421,7 @@ jobs:
f"(got cert={has_cert} key={has_key} https={has_https})", file=sys.stderr)
failed = True
else:
print(f"{label}: cert/key/https args emitted together")
print(f"✓ {label}: cert/key/https args emitted together")
else:
if has_cert or has_key or has_https:
print(f"FAIL: {label}: expected none of {cert_flag}/{key_flag}/{https_flag}; "
@@ -429,7 +429,7 @@ jobs:
f"(got cert={has_cert} key={has_key} https={has_https})", file=sys.stderr)
failed = True
else:
print(f"{label}: no TLS args emitted, main -port stays HTTP")
print(f"✓ {label}: no TLS args emitted, main -port stays HTTP")
# bash -n: pin down that the rendered script parses. Guards against
# a future helper change that leaves a dangling `\` with nothing
@@ -446,49 +446,7 @@ jobs:
sys.exit(1 if failed else 0)
PYEOF
echo ""
echo "=== Testing all-in-one env: a key in both global and component renders once ==="
# Regression: all-in-one looped global and component extraEnvironmentVars
# in two separate ranges, emitting duplicate env entries for any key set
# in both maps. Render a shared key and assert it appears exactly once in
# the all-in-one container, with the component value winning (consistent
# with the merge helper the other components already use). pyyaml is
# installed by the earlier IAM gRPC block in this same step.
helm template test $CHART_DIR \
--set allInOne.enabled=true \
--set global.seaweedfs.extraEnvironmentVars.WEED_SHARED=fromGlobal \
--set allInOne.extraEnvironmentVars.WEED_SHARED=fromComponent > /tmp/aio-env.yaml
python3 - /tmp/aio-env.yaml <<'PYEOF'
import sys, yaml
from collections import Counter
docs = [d for d in yaml.safe_load_all(open(sys.argv[1])) if d]
dep = next(d for d in docs if d.get("kind") == "Deployment"
and d["metadata"]["name"].endswith("all-in-one"))
envs = [e["name"] for c in dep["spec"]["template"]["spec"]["containers"]
for e in c.get("env", [])]
dups = {k: v for k, v in Counter(envs).items() if v > 1}
if dups:
print(f"FAIL: duplicate env entries in all-in-one container: {dups}", file=sys.stderr)
sys.exit(1)
val = next(e.get("value") for c in dep["spec"]["template"]["spec"]["containers"]
for e in c.get("env", []) if e["name"] == "WEED_SHARED")
if val != "fromComponent":
print(f"FAIL: WEED_SHARED should take the component value 'fromComponent', got '{val}'",
file=sys.stderr)
sys.exit(1)
print("all-in-one env: shared key renders once, component value wins")
PYEOF
echo "=== Testing bucket versioning: YAML bool false suspends like string \"false\" ==="
# bool false used to be a silent no-op while string "false" suspended.
BOOL_FALSE=$(helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=verbucket \
--set s3.createBuckets[0].versioning=false | grep 's3.bucket.versioning -name verbucket' || true)
echo "$BOOL_FALSE" | grep -q -- '-status Suspended' || { echo "FAIL: bool false versioning did not Suspend the bucket"; exit 1; }
echo "Bucket versioning: YAML bool false suspends consistently with string \"false\""
echo "All template rendering tests passed!"
echo "✅ All template rendering tests passed!"
- name: Create kind cluster
uses: helm/kind-action@v1.14.0
+12 -43
View File
@@ -66,42 +66,34 @@ jobs:
SEAWEEDFS_COMMIT: ${{ github.sha }}
run: |
cd seaweed-volume
cargo build --release --target ${{ matrix.target }} --target-dir target/large-disk
cargo build --release --target ${{ matrix.target }}
- name: Build Rust volume server (normal)
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
run: |
cd seaweed-volume
cargo build --release --target ${{ matrix.target }} --no-default-features --target-dir target/normal
cargo build --release --target ${{ matrix.target }} --no-default-features
- name: Package binaries
run: |
# Large disk (default, 5bytes feature)
cp seaweed-volume/target/large-disk/${{ matrix.target }}/release/weed-volume weed-volume-large-disk
cp seaweed-volume/target/${{ matrix.target }}/release/weed-volume weed-volume-large-disk
tar czf weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz weed-volume-large-disk
rm weed-volume-large-disk
# Normal volume size
cp seaweed-volume/target/normal/${{ matrix.target }}/release/weed-volume weed-volume-normal
cp seaweed-volume/target/${{ matrix.target }}/release/weed-volume weed-volume-normal
tar czf weed-volume_${{ matrix.asset_suffix }}.tar.gz weed-volume-normal
rm weed-volume-normal
- name: Generate md5 checksums
run: |
for f in weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz weed-volume_${{ matrix.asset_suffix }}.tar.gz; do
md5sum "$f" > "$f.md5"
done
- name: Upload release assets
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v3
with:
files: |
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz.md5
weed-volume_${{ matrix.asset_suffix }}.tar.gz
weed-volume_${{ matrix.asset_suffix }}.tar.gz.md5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -112,9 +104,7 @@ jobs:
name: rust-volume-${{ matrix.asset_suffix }}
path: |
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz.md5
weed-volume_${{ matrix.asset_suffix }}.tar.gz
weed-volume_${{ matrix.asset_suffix }}.tar.gz.md5
build-rust-volume-darwin:
permissions:
@@ -155,40 +145,32 @@ jobs:
SEAWEEDFS_COMMIT: ${{ github.sha }}
run: |
cd seaweed-volume
cargo build --release --target ${{ matrix.target }} --target-dir target/large-disk
cargo build --release --target ${{ matrix.target }}
- name: Build Rust volume server (normal)
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
run: |
cd seaweed-volume
cargo build --release --target ${{ matrix.target }} --no-default-features --target-dir target/normal
cargo build --release --target ${{ matrix.target }} --no-default-features
- name: Package binaries
run: |
cp seaweed-volume/target/large-disk/${{ matrix.target }}/release/weed-volume weed-volume-large-disk
cp seaweed-volume/target/${{ matrix.target }}/release/weed-volume weed-volume-large-disk
tar czf weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz weed-volume-large-disk
rm weed-volume-large-disk
cp seaweed-volume/target/normal/${{ matrix.target }}/release/weed-volume weed-volume-normal
cp seaweed-volume/target/${{ matrix.target }}/release/weed-volume weed-volume-normal
tar czf weed-volume_${{ matrix.asset_suffix }}.tar.gz weed-volume-normal
rm weed-volume-normal
- name: Generate md5 checksums
run: |
for f in weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz weed-volume_${{ matrix.asset_suffix }}.tar.gz; do
md5 -r "$f" > "$f.md5"
done
- name: Upload release assets
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v3
with:
files: |
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz.md5
weed-volume_${{ matrix.asset_suffix }}.tar.gz
weed-volume_${{ matrix.asset_suffix }}.tar.gz.md5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -199,9 +181,7 @@ jobs:
name: rust-volume-${{ matrix.asset_suffix }}
path: |
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz
weed-volume_large_disk_${{ matrix.asset_suffix }}.tar.gz.md5
weed-volume_${{ matrix.asset_suffix }}.tar.gz
weed-volume_${{ matrix.asset_suffix }}.tar.gz.md5
build-rust-volume-windows:
permissions:
@@ -233,42 +213,33 @@ jobs:
SEAWEEDFS_COMMIT: ${{ github.sha }}
run: |
cd seaweed-volume
cargo build --release --target-dir target/large-disk
cargo build --release
- name: Build Rust volume server (normal)
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
run: |
cd seaweed-volume
cargo build --release --no-default-features --target-dir target/normal
cargo build --release --no-default-features
- name: Package binaries
shell: bash
run: |
cp seaweed-volume/target/large-disk/release/weed-volume.exe weed-volume-large-disk.exe
cp seaweed-volume/target/release/weed-volume.exe weed-volume-large-disk.exe
7z a weed-volume_large_disk_windows_amd64.zip weed-volume-large-disk.exe
rm weed-volume-large-disk.exe
cp seaweed-volume/target/normal/release/weed-volume.exe weed-volume-normal.exe
cp seaweed-volume/target/release/weed-volume.exe weed-volume-normal.exe
7z a weed-volume_windows_amd64.zip weed-volume-normal.exe
rm weed-volume-normal.exe
- name: Generate md5 checksums
shell: bash
run: |
for f in weed-volume_large_disk_windows_amd64.zip weed-volume_windows_amd64.zip; do
md5sum "$f" > "$f.md5"
done
- name: Upload release assets
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v3
with:
files: |
weed-volume_large_disk_windows_amd64.zip
weed-volume_large_disk_windows_amd64.zip.md5
weed-volume_windows_amd64.zip
weed-volume_windows_amd64.zip.md5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -279,6 +250,4 @@ jobs:
name: rust-volume-windows_amd64
path: |
weed-volume_large_disk_windows_amd64.zip
weed-volume_large_disk_windows_amd64.zip.md5
weed-volume_windows_amd64.zip
weed-volume_windows_amd64.zip.md5
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.32"
appVersion: "4.31"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.32.0
version: 4.31.0
@@ -81,9 +81,8 @@ spec:
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
env:
{{- /* Determine default cluster alias and the corresponding env var keys to avoid conflicts */}}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.allInOne "target" $mergedExtraEnvironmentVars) }}
{{- $clusterDefault := default "sw" (index $mergedExtraEnvironmentVars "WEED_CLUSTER_DEFAULT") }}
{{- $envMerged := merge (.Values.global.seaweedfs.extraEnvironmentVars | default dict) (.Values.allInOne.extraEnvironmentVars | default dict) }}
{{- $clusterDefault := default "sw" (index $envMerged "WEED_CLUSTER_DEFAULT") }}
{{- $clusterUpper := upper $clusterDefault }}
{{- $clusterMasterKey := printf "WEED_CLUSTER_%s_MASTER" $clusterUpper }}
{{- $clusterFilerKey := printf "WEED_CLUSTER_%s_FILER" $clusterUpper }}
@@ -101,8 +100,8 @@ spec:
fieldPath: metadata.namespace
- name: SEAWEEDFS_FULLNAME
value: "{{ include "seaweedfs.fullname" . }}"
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
{{- $value := index $mergedExtraEnvironmentVars $key }}
{{- if .Values.allInOne.extraEnvironmentVars }}
{{- range $key, $value := .Values.allInOne.extraEnvironmentVars }}
{{- if and (ne $key $clusterMasterKey) (ne $key $clusterFilerKey) }}
- name: {{ $key }}
{{- if kindIs "string" $value }}
@@ -113,6 +112,20 @@ spec:
{{- end }}
{{- end }}
{{- end }}
{{- end }}
{{- if .Values.global.seaweedfs.extraEnvironmentVars }}
{{- range $key, $value := .Values.global.seaweedfs.extraEnvironmentVars }}
{{- if and (ne $key $clusterMasterKey) (ne $key $clusterFilerKey) }}
- name: {{ $key }}
{{- if kindIs "string" $value }}
value: {{ tpl $value $ | quote }}
{{- else }}
valueFrom:
{{ toYaml $value | nindent 16 }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
# Inject computed cluster endpoints for the default cluster
- name: {{ $clusterMasterKey }}
value: {{ include "seaweedfs.cluster.masterAddress" . | quote }}
@@ -143,8 +143,6 @@ spec:
{{- if kindIs "bool" .versioning }}
{{- if .versioning }}
{{- $bucketVersioning = "Enabled" }}
{{- else }}
{{- $bucketVersioning = "Suspended" }}
{{- end }}
{{- else if kindIs "string" .versioning }}
{{- $versioningLower := lower .versioning }}
+3 -3
View File
@@ -919,7 +919,7 @@ filer:
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
# ttl format: [1-255][m|h|d|w|M|y] (e.g., 7d)
# objectLock enables S3 Object Lock (irreversible, forces versioning)
# versioning: Enabled or Suspended (or bool true/false)
# versioning: Enabled or Suspended (or true to enable)
# createBuckets:
# - name: bucket-a
# anonymousRead: true
@@ -972,7 +972,7 @@ s3:
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
# ttl format: [1-255][m|h|d|w|M|y] (e.g., 7d)
# objectLock enables S3 Object Lock (irreversible, forces versioning)
# versioning: Enabled or Suspended (or bool true/false)
# versioning: Enabled or Suspended (or true to enable)
# createBuckets:
# - name: bucket-a
# anonymousRead: true
@@ -1526,7 +1526,7 @@ allInOne:
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
# ttl format: [1-255][m|h|d|w|M|y] (e.g., 7d)
# objectLock enables S3 Object Lock (irreversible, forces versioning)
# versioning: Enabled or Suspended (or bool true/false)
# versioning: Enabled or Suspended (or true to enable)
# createBuckets:
# - name: bucket-a
# anonymousRead: true
+1 -5
View File
@@ -10,11 +10,7 @@ MASTER_PORT := 9333
VOLUME_PORT := 8080
FILER_PORT := 8888
TEST_TIMEOUT := 10m
# Run every test in the suite by default. "TestVersioning" used to leave whole
# tests (bucket creation, suspended delete, directory/version listing) ungated.
# Opt-in stress tests are matched by "." but self-skip without ENABLE_STRESS_TESTS
# (they run with it set in their own targets), so they don't actually execute here.
TEST_PATTERN := .
TEST_PATTERN := TestVersioning
.DEFAULT_GOAL := help
+17 -28
View File
@@ -36,7 +36,7 @@ func TestBucketCreationBehavior(t *testing.T) {
expectedError: "",
},
{
name: "Create existing bucket with same owner - should return BucketAlreadyOwnedByYou",
name: "Create existing bucket with same owner - should return BucketAlreadyExists",
setupFunc: func(t *testing.T, bucketName string) {
// Create bucket first
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{
@@ -46,8 +46,8 @@ func TestBucketCreationBehavior(t *testing.T) {
},
bucketName: "test-same-owner-same-settings-" + fmt.Sprintf("%d", time.Now().Unix()),
objectLockEnabled: nil,
expectedStatusCode: 409, // idempotent recreate by the same owner
expectedError: "BucketAlreadyOwnedByYou",
expectedStatusCode: 409, // SeaweedFS now returns BucketAlreadyExists in all cases
expectedError: "BucketAlreadyExists",
},
{
name: "Create bucket with same owner but different Object Lock settings - should fail",
@@ -71,7 +71,7 @@ func TestBucketCreationBehavior(t *testing.T) {
expectedError: "",
},
{
name: "Create bucket with Object Lock enabled twice - should return BucketAlreadyOwnedByYou",
name: "Create bucket with Object Lock enabled twice - should fail",
setupFunc: func(t *testing.T, bucketName string) {
// Create bucket with Object Lock first
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{
@@ -83,7 +83,7 @@ func TestBucketCreationBehavior(t *testing.T) {
bucketName: "test-object-lock-duplicate-" + fmt.Sprintf("%d", time.Now().Unix()),
objectLockEnabled: aws.Bool(true),
expectedStatusCode: 409,
expectedError: "BucketAlreadyOwnedByYou",
expectedError: "BucketAlreadyExists",
},
}
@@ -130,27 +130,16 @@ func TestBucketCreationBehavior(t *testing.T) {
}
}
// TestBucketCreationWithDifferentUsers tests bucket creation across owners: a
// name taken by one identity is reported as BucketAlreadyExists to another
// (versus BucketAlreadyOwnedByYou for the owner re-creating it).
// TestBucketCreationWithDifferentUsers tests bucket creation with different identity contexts
func TestBucketCreationWithDifferentUsers(t *testing.T) {
ctx := context.Background()
// Tracked prefix + run id so cleanupAllTestBuckets sweeps it if the test leaks.
bucketName := getNewBucketName()
// This test would require setting up different S3 credentials/identities
// For now, we'll skip this as it requires more complex setup
t.Skip("Different user testing requires IAM setup - implement when IAM is configured")
// User A owns the bucket.
clientA := getS3Client(t)
_, err := clientA.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucketName)})
require.NoError(t, err, "User A should create the bucket")
defer cleanupBucketForCreationTest(t, clientA, bucketName)
// User B is a different identity (s3_tests_alt in the test S3 config).
clientB := getS3ClientWithCredentials(t,
"NOPQRSTUVWXYZABCDEFG", "nopqrstuvwxyzabcdefghijklmnabcdefghijklm")
_, err = clientB.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucketName)})
require.Error(t, err, "User B should not be able to create a bucket owned by User A")
assert.Contains(t, err.Error(), "BucketAlreadyExists",
"Different-owner recreate should return BucketAlreadyExists, got: %v", err)
// TODO: Implement when we have proper IAM/user management in test setup
// Should test:
// 1. User A creates bucket
// 2. User B tries to create same bucket -> should fail with BucketAlreadyExists
}
// TestBucketCreationVersioningInteraction tests interaction between bucket creation and versioning
@@ -182,8 +171,8 @@ func TestBucketCreationVersioningInteraction(t *testing.T) {
ObjectLockEnabledForBucket: aws.Bool(true),
})
assert.Error(t, err, "Expected second bucket creation to fail")
assert.Contains(t, err.Error(), "BucketAlreadyOwnedByYou",
"Expected BucketAlreadyOwnedByYou error, got: %v", err)
assert.Contains(t, err.Error(), "BucketAlreadyExists",
"Expected BucketAlreadyExists error, got: %v", err)
}
// TestBucketCreationErrorMessages tests that proper error messages are returned
@@ -208,8 +197,8 @@ func TestBucketCreationErrorMessages(t *testing.T) {
require.Error(t, err, "Expected bucket creation to fail")
// Check that it's the right type of error
assert.Contains(t, err.Error(), "BucketAlreadyOwnedByYou",
"Expected BucketAlreadyOwnedByYou error, got: %v", err)
assert.Contains(t, err.Error(), "BucketAlreadyExists",
"Expected BucketAlreadyExists error, got: %v", err)
}
// cleanupBucketForCreationTest removes a bucket and all its contents
@@ -122,7 +122,7 @@ func TestListObjectVersionsIncludesDirectories(t *testing.T) {
assert.Equal(t, int64(0), *version.Size, "Directory %s should have size 0", expectedDir)
assert.True(t, *version.IsLatest, "Directory %s should be marked as latest", expectedDir)
assert.Equal(t, "\"d41d8cd98f00b204e9800998ecf8427e\"", *version.ETag, "Directory %s should have MD5 of empty string as ETag", expectedDir)
assert.Equal(t, types.ObjectVersionStorageClassStandard, version.StorageClass, "Directory %s should have STANDARD storage class", expectedDir)
assert.Equal(t, types.ObjectStorageClassStandard, version.StorageClass, "Directory %s should have STANDARD storage class", expectedDir)
break
}
}
@@ -537,18 +537,13 @@ func TestSuspendedVersioningDeleteBehavior(t *testing.T) {
})
require.NoError(t, err)
// Verify the null content version is gone and the delete marker stands in.
// Verify the null version was actually deleted (not a delete marker created)
listResp, err = client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucketName),
})
require.NoError(t, err)
assert.Len(t, listResp.Versions, 3, "Should be back to 3 versions after deleting null version")
// A suspended-versioning DELETE removes the null version and records a single
// null delete marker that overwrites any prior one (S3 spec), so the object
// reads as deleted without markers piling up.
require.Len(t, listResp.DeleteMarkers, 1, "Suspended delete should record exactly one null delete marker")
assert.Equal(t, "null", aws.ToString(listResp.DeleteMarkers[0].VersionId), "Suspended delete marker should have version id null")
assert.Equal(t, objectKey, aws.ToString(listResp.DeleteMarkers[0].Key), "Delete marker should be for the deleted object")
assert.Empty(t, listResp.DeleteMarkers, "Should have no delete markers during suspended versioning delete")
// Verify null version is gone
nullVersionFound = false
@@ -601,7 +596,7 @@ func TestSuspendedVersioningDeleteBehavior(t *testing.T) {
Key: aws.String(objectKey),
})
require.NoError(t, err)
assert.True(t, aws.ToBool(deleteResp.DeleteMarker), "Should create delete marker when versioning is enabled")
assert.Equal(t, "true", deleteResp.DeleteMarker, "Should create delete marker when versioning is enabled")
// Verify final state
listResp, err = client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
@@ -609,19 +604,7 @@ func TestSuspendedVersioningDeleteBehavior(t *testing.T) {
})
require.NoError(t, err)
assert.Len(t, listResp.Versions, 4, "Should have 3 original versions + 1 new version")
// The historical null suspended marker plus the new enabled-mode delete marker.
require.Len(t, listResp.DeleteMarkers, 2, "Should have the null suspended marker and the enabled-mode delete marker")
var sawNull, sawEnabled bool
for _, dm := range listResp.DeleteMarkers {
assert.Equal(t, objectKey, aws.ToString(dm.Key), "Delete marker should be for the deleted object")
if aws.ToString(dm.VersionId) == "null" {
sawNull = true
} else {
sawEnabled = true
}
}
assert.True(t, sawNull, "Suspended phase should leave a null delete marker")
assert.True(t, sawEnabled, "Enabled delete should add a real-version-id delete marker")
assert.Len(t, listResp.DeleteMarkers, 1, "Should have 1 delete marker")
t.Logf("Successfully verified suspended versioning delete behavior")
}
@@ -681,8 +664,7 @@ func TestVersionedObjectListBehavior(t *testing.T) {
assert.NotContains(t, *listedObject.Key, versionId, "Object key should not contain version ID")
// Verify object properties
require.NotNil(t, listedObject.Size, "Object size should not be nil")
assert.Equal(t, int64(len(content)), *listedObject.Size, "Object size should match")
assert.Equal(t, int64(len(content)), listedObject.Size, "Object size should match")
assert.NotNil(t, listedObject.ETag, "Object should have ETag")
assert.NotNil(t, listedObject.LastModified, "Object should have LastModified")
@@ -692,7 +674,7 @@ func TestVersionedObjectListBehavior(t *testing.T) {
assert.NotEmpty(t, listedObject.Owner.DisplayName, "Owner DisplayName should not be empty")
t.Logf("Listed object: Key=%s, Size=%d, Owner.ID=%s, Owner.DisplayName=%s",
*listedObject.Key, *listedObject.Size, *listedObject.Owner.ID, *listedObject.Owner.DisplayName)
*listedObject.Key, listedObject.Size, *listedObject.Owner.ID, *listedObject.Owner.DisplayName)
// Test list-objects-v2 operation as well
listV2Resp, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
+3 -25
View File
@@ -36,8 +36,8 @@ type S3TestConfig struct {
// Default test configuration - should match s3tests.conf
var defaultConfig = &S3TestConfig{
Endpoint: firstNonEmpty(os.Getenv("S3_ENDPOINT"), "http://localhost:8333"), // Default SeaweedFS S3 port
MasterEndpoint: firstNonEmpty(os.Getenv("MASTER_ENDPOINT"), "http://127.0.0.1:9333"), // Default SeaweedFS master HTTP port
Endpoint: firstNonEmpty(os.Getenv("S3_ENDPOINT"), "http://localhost:8333"), // Default SeaweedFS S3 port
MasterEndpoint: firstNonEmpty(os.Getenv("MASTER_ENDPOINT"), "http://127.0.0.1:9333"), // Default SeaweedFS master HTTP port
AccessKey: "some_access_key1",
SecretKey: "some_secret_key1",
Region: "us-east-1",
@@ -50,7 +50,7 @@ var defaultConfig = &S3TestConfig{
// cleanupAllTestBuckets uses it to find stale buckets from prior tests/runs.
// Add the new prefix here whenever a test introduces one.
var allTestBucketPrefixes = []string{
"test-versioning-", // covers test-versioning-, test-versioning-directories, test-versioning-interaction-, test-versioned-acl/list
"test-versioning-", // covers test-versioning-, test-versioning-directories, test-versioning-interaction-, test-versioned-acl/list
"test-versioned-",
"test-error-messages-",
"test-delete-markers",
@@ -104,28 +104,6 @@ func getS3Client(t *testing.T) *s3.Client {
})
}
// getS3ClientWithCredentials creates an S3 client authenticating as a specific
// identity, so tests can act as a different owner than the default client.
func getS3ClientWithCredentials(t *testing.T, accessKey, secretKey string) *s3.Client {
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion(defaultConfig.Region),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
config.WithEndpointResolverWithOptions(aws.EndpointResolverWithOptionsFunc(
func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
URL: defaultConfig.Endpoint,
SigningRegion: defaultConfig.Region,
HostnameImmutable: true,
}, nil
})),
)
require.NoError(t, err)
return s3.NewFromConfig(cfg, func(o *s3.Options) {
o.UsePathStyle = true
})
}
// getNewBucketName generates a unique bucket name
func getNewBucketName() string {
timestamp := time.Now().UnixNano()
-51
View File
@@ -30,7 +30,6 @@ type AdminData struct {
VolumeServers []VolumeServer `json:"volume_servers"`
FilerNodes []FilerNode `json:"filer_nodes"`
MessageBrokers []MessageBrokerNode `json:"message_brokers"`
S3Nodes []S3Node `json:"s3_nodes"`
DataCenters []DataCenter `json:"datacenters"`
LastUpdated time.Time `json:"last_updated"`
@@ -116,12 +115,6 @@ type MessageBrokerNode struct {
LastUpdated time.Time `json:"last_updated"`
}
type S3Node struct {
Address string `json:"address"`
DataCenter string `json:"datacenter"`
LastUpdated time.Time `json:"last_updated"`
}
// GetAdminData retrieves admin data as a struct (for reuse by both JSON and HTML handlers)
func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
if username == "" {
@@ -151,9 +144,6 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
// Get message broker nodes status
messageBrokers := s.getMessageBrokerNodesStatus()
// Get S3 nodes status
s3Nodes := s.getS3NodesStatus()
// Get volume size limit from master configuration
var volumeSizeLimitMB uint64 = 30000 // Default to 30GB
err = s.WithMasterClient(func(client master_pb.SeaweedClient) error {
@@ -193,7 +183,6 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
VolumeServers: volumeServersData.VolumeServers,
FilerNodes: filerNodes,
MessageBrokers: messageBrokers,
S3Nodes: s3Nodes,
DataCenters: topology.DataCenters,
LastUpdated: topology.UpdatedAt,
TotalEcVolumes: totalEcVolumes,
@@ -371,43 +360,3 @@ func (s *AdminServer) getMessageBrokerNodesStatus() []MessageBrokerNode {
return messageBrokers
}
// getS3NodesStatus checks status of all S3 nodes using master's ListClusterNodes
func (s *AdminServer) getS3NodesStatus() []S3Node {
var s3Nodes []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,
})
if err != nil {
return err
}
// Process each S3 node
for _, node := range resp.ClusterNodes {
s3Nodes = append(s3Nodes, S3Node{
Address: pb.ServerAddress(node.Address).ToHttpAddress(),
DataCenter: node.DataCenter,
LastUpdated: time.Now(),
})
}
return nil
})
if err != nil {
currentMaster := s.masterClient.GetMaster(context.Background())
glog.Errorf("Failed to get S3 nodes from master %s: %v", currentMaster, err)
// Return empty list if we can't get S3 info from master
return []S3Node{}
}
// Sort S3 nodes by address for consistent ordering on page refresh
sort.Slice(s3Nodes, func(i, j int) bool {
return s3Nodes[i].Address < s3Nodes[j].Address
})
return s3Nodes
}
-46
View File
@@ -1189,52 +1189,6 @@ func (s *AdminServer) GetClusterBrokers() (*ClusterBrokersData, error) {
}, nil
}
// GetClusterS3Servers retrieves cluster S3 servers data
func (s *AdminServer) GetClusterS3Servers() (*ClusterS3ServersData, error) {
var s3Servers []S3ServerInfo
// 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,
})
if err != nil {
return err
}
// Process each S3 server node
for _, node := range resp.ClusterNodes {
createdAt := time.Unix(0, node.CreatedAtNs)
s3ServerInfo := S3ServerInfo{
Address: pb.ServerAddress(node.Address).ToHttpAddress(),
DataCenter: node.DataCenter,
Version: node.Version,
CreatedAt: createdAt,
}
s3Servers = append(s3Servers, s3ServerInfo)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to get S3 server nodes from master: %w", err)
}
// Sort S3 servers by address for consistent ordering on page refresh
sort.Slice(s3Servers, func(i, j int) bool {
return s3Servers[i].Address < s3Servers[j].Address
})
return &ClusterS3ServersData{
S3Servers: s3Servers,
TotalS3Servers: len(s3Servers),
LastUpdated: time.Now(),
}, nil
}
// GetAllFilers method moved to client_management.go
// GetVolumeDetails method moved to volume_management.go
-14
View File
@@ -310,20 +310,6 @@ type ClusterBrokersData struct {
LastUpdated time.Time `json:"last_updated"`
}
type S3ServerInfo struct {
Address string `json:"address"`
DataCenter string `json:"datacenter"`
Version string `json:"version"`
CreatedAt time.Time `json:"created_at"`
}
type ClusterS3ServersData struct {
Username string `json:"username"`
S3Servers []S3ServerInfo `json:"s3_servers"`
TotalS3Servers int `json:"total_s3_servers"`
LastUpdated time.Time `json:"last_updated"`
}
type TopicInfo struct {
Name string `json:"name"`
Partitions int `json:"partitions"`
-1
View File
@@ -125,7 +125,6 @@ func (h *AdminHandlers) registerUIRoutes(r *mux.Router) {
// Cluster management routes
r.HandleFunc("/cluster/masters", h.clusterHandlers.ShowClusterMasters).Methods(http.MethodGet)
r.HandleFunc("/cluster/filers", h.clusterHandlers.ShowClusterFilers).Methods(http.MethodGet)
r.HandleFunc("/cluster/s3", h.clusterHandlers.ShowClusterS3Servers).Methods(http.MethodGet)
r.HandleFunc("/cluster/volume-servers", h.clusterHandlers.ShowClusterVolumeServers).Methods(http.MethodGet)
// Storage management routes
-23
View File
@@ -312,29 +312,6 @@ func (h *ClusterHandlers) ShowClusterFilers(w http.ResponseWriter, r *http.Reque
}
}
// ShowClusterS3Servers renders the cluster S3 servers page
func (h *ClusterHandlers) ShowClusterS3Servers(w http.ResponseWriter, r *http.Request) {
// Get cluster S3 servers data
s3ServersData, err := h.adminServer.GetClusterS3Servers()
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to get cluster S3 servers: "+err.Error())
return
}
username := usernameOrDefault(r)
s3ServersData.Username = username
// Render HTML template
w.Header().Set("Content-Type", "text/html")
s3ServersComponent := app.ClusterS3Servers(*s3ServersData)
viewCtx := layout.NewViewContext(r, username, dash.CSRFTokenFromContext(r.Context()))
layoutComponent := layout.Layout(viewCtx, s3ServersComponent)
if err := layoutComponent.Render(r.Context(), w); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to render template: "+err.Error())
return
}
}
// GetClusterTopology returns the cluster topology as JSON
func (h *ClusterHandlers) GetClusterTopology(w http.ResponseWriter, r *http.Request) {
topology, err := h.adminServer.GetClusterTopology()
+7 -57
View File
@@ -34,66 +34,16 @@ func (mq *MaintenanceQueue) SetPersistence(persistence TaskPersistence) {
glog.V(1).Infof("Maintenance queue configured with task persistence")
}
// LoadTasksFromPersistence is called on startup to restore in-flight tasks
// across an admin restart. Non-terminal tasks (pending/assigned/in_progress)
// are re-queued as pending — the worker that held an in-flight task is gone
// after a restart, and maintenance tasks are idempotent, so re-running a
// partially-done one is safe. Terminal task files are deleted. Anything missed
// is still re-detected by the scanner from live cluster state.
// LoadTasksFromPersistence is called on startup. Previous task states are NOT loaded
// into memory — the maintenance scanner will re-detect current needs from the live
// cluster state. Stale task files from previous runs are deleted from disk.
func (mq *MaintenanceQueue) LoadTasksFromPersistence() error {
if mq.persistence == nil {
glog.Infof("Task queue initialized (no persistence configured)")
return nil
}
tasks, err := mq.persistence.LoadAllTaskStates()
if err != nil {
glog.Warningf("Failed to load persisted task states: %v; starting with an empty queue", err)
return nil
}
var terminal []string
var restored []*MaintenanceTask
mq.mutex.Lock()
requeued := 0
for _, task := range tasks {
if task == nil {
continue
}
switch task.Status {
case TaskStatusPending, TaskStatusAssigned, TaskStatusInProgress:
task.Status = TaskStatusPending
task.WorkerID = ""
task.Progress = 0
mq.tasks[task.ID] = task
mq.pendingTasks = append(mq.pendingTasks, task)
restored = append(restored, snapshotTask(task))
requeued++
default:
terminal = append(terminal, task.ID)
if mq.persistence != nil {
if err := mq.persistence.DeleteAllTaskStates(); err != nil {
glog.Warningf("Failed to clean up old task files: %v", err)
}
}
sort.Slice(mq.pendingTasks, func(i, j int) bool {
if mq.pendingTasks[i].Priority != mq.pendingTasks[j].Priority {
return mq.pendingTasks[i].Priority > mq.pendingTasks[j].Priority
}
return mq.pendingTasks[i].ScheduledAt.Before(mq.pendingTasks[j].ScheduledAt)
})
mq.mutex.Unlock()
// ActiveTopology is in-memory and starts empty, so restored tasks must be
// re-synced or GetNextTask's AssignTask would reject them as unknown and
// they'd sit pending forever. Done outside the lock, like the retry path.
if mq.integration != nil {
for _, task := range restored {
mq.integration.SyncTask(task)
}
}
// Delete stale terminal files outside the lock to avoid blocking on disk I/O.
for _, id := range terminal {
mq.deleteTaskState(id)
}
glog.Infof("Task queue initialized: re-queued %d in-flight task(s) from persistence; scanner will re-detect the rest", requeued)
glog.Infof("Task queue initialized (previous tasks will be re-detected by scanner)")
return nil
}
@@ -697,7 +697,8 @@ func (m *MockPersistence) DeleteAllTaskStates() error
func (m *MockPersistence) CleanupCompletedTasks() error { return nil }
func (m *MockPersistence) SaveTaskPolicy(taskType string, policy *TaskPolicy) error { return nil }
func TestMaintenanceQueue_LoadRequeuesInFlightTasks(t *testing.T) {
func TestMaintenanceQueue_LoadTasksStartsEmpty(t *testing.T) {
// Setup
policy := &MaintenancePolicy{
TaskPolicies: map[string]*worker_pb.TaskPolicy{
"balance": {MaxConcurrent: 1},
@@ -705,30 +706,24 @@ func TestMaintenanceQueue_LoadRequeuesInFlightTasks(t *testing.T) {
}
mq := NewMaintenanceQueue(policy)
// Non-terminal tasks must be re-queued across a restart; an in-progress
// task is reset to pending (its worker is gone). Terminal tasks are dropped.
mq.SetPersistence(&MockPersistence{tasks: []*MaintenanceTask{
{ID: "pending_1", Type: "balance", Status: TaskStatusPending},
{ID: "inprogress_1", Type: "balance", Status: TaskStatusInProgress, WorkerID: "gone", Progress: 42},
{ID: "done_1", Type: "balance", Status: TaskStatusCompleted},
}})
// Setup mock persistence with tasks — these should NOT be loaded
mockTask := &MaintenanceTask{
ID: "old_task_123",
Type: "balance",
Status: TaskStatusPending,
}
mq.SetPersistence(&MockPersistence{tasks: []*MaintenanceTask{mockTask}})
if err := mq.LoadTasksFromPersistence(); err != nil {
// LoadTasksFromPersistence should be a no-op — scanner will re-detect
err := mq.LoadTasksFromPersistence()
if err != nil {
t.Fatalf("LoadTasksFromPersistence failed: %v", err)
}
if stats := mq.GetStats(); stats.TotalTasks != 2 {
t.Errorf("expected 2 re-queued tasks, got %d", stats.TotalTasks)
}
ip := mq.tasks["inprogress_1"]
if ip == nil {
t.Fatal("in-progress task was not re-queued")
}
if ip.Status != TaskStatusPending || ip.WorkerID != "" || ip.Progress != 0 {
t.Errorf("in-progress task not reset to pending: status=%q worker=%q progress=%v", ip.Status, ip.WorkerID, ip.Progress)
}
if mq.tasks["done_1"] != nil {
t.Error("completed task should not be re-queued")
// Queue should be empty — tasks will be re-detected by scanner
stats := mq.GetStats()
if stats.TotalTasks != 0 {
t.Errorf("Expected 0 tasks after startup, got %d", stats.TotalTasks)
}
}
-2
View File
@@ -162,7 +162,6 @@ func (at *ActiveTopology) GetDisksWithEffectiveCapacity(taskType TaskType, exclu
// Create a new DiskInfo with current capacity information
diskCopy := DiskInfo{
NodeID: disk.DiskInfo.NodeID,
Address: disk.DiskInfo.Address,
DiskID: disk.DiskInfo.DiskID,
DiskType: disk.DiskInfo.DiskType,
DataCenter: disk.DiskInfo.DataCenter,
@@ -227,7 +226,6 @@ func (at *ActiveTopology) GetDisksForPlanning(taskType TaskType, excludeNodeID s
// Create a new DiskInfo with planning information
diskCopy := DiskInfo{
NodeID: disk.DiskInfo.NodeID,
Address: disk.DiskInfo.Address,
DiskID: disk.DiskInfo.DiskID,
DiskType: disk.DiskInfo.DiskType,
DataCenter: disk.DiskInfo.DataCenter,
-1
View File
@@ -43,7 +43,6 @@ type taskState struct {
// DiskInfo represents a disk with its current state and ongoing tasks (public for external access)
type DiskInfo struct {
NodeID string `json:"node_id"`
Address string `json:"address"` // volume server ip:port; NodeID may be an opaque id, so this is the source for the physical-machine host
DiskID uint32 `json:"disk_id"`
DiskType string `json:"disk_type"`
DataCenter string `json:"data_center"`
@@ -87,7 +87,6 @@ func (at *ActiveTopology) UpdateTopology(topologyInfo *master_pb.TopologyInfo) e
disk := &activeDisk{
DiskInfo: &DiskInfo{
NodeID: nodeInfo.Id,
Address: nodeInfo.Address,
DiskID: perDisk.DiskId,
DiskType: diskType,
DataCenter: dc.Id,
+4 -64
View File
@@ -204,7 +204,7 @@ templ Admin(data dash.AdminData) {
</div>
<div class="card-body text-center">
<div class="row">
<div class="col">
<div class="col-3">
<div class="card bg-light">
<div class="card-body">
<h5>{fmt.Sprintf("%d", len(data.MasterNodes))}</h5>
@@ -212,7 +212,7 @@ templ Admin(data dash.AdminData) {
</div>
</div>
</div>
<div class="col">
<div class="col-3">
<div class="card bg-light">
<div class="card-body">
<h5>{fmt.Sprintf("%d", len(data.VolumeServers))}</h5>
@@ -220,7 +220,7 @@ templ Admin(data dash.AdminData) {
</div>
</div>
</div>
<div class="col">
<div class="col-3">
<div class="card bg-light">
<div class="card-body">
<h5>{fmt.Sprintf("%d", len(data.FilerNodes))}</h5>
@@ -228,15 +228,7 @@ templ Admin(data dash.AdminData) {
</div>
</div>
</div>
<div class="col">
<div class="card bg-light">
<div class="card-body">
<h5>{fmt.Sprintf("%d", len(data.S3Nodes))}</h5>
<small class="text-muted">S3 Servers</small>
</div>
</div>
</div>
<div class="col">
<div class="col-3">
<div class="card bg-light">
<div class="card-body">
<h5>{fmt.Sprintf("%d", len(data.MessageBrokers))}</h5>
@@ -392,58 +384,6 @@ templ Admin(data dash.AdminData) {
</div>
</div>
<!-- S3 Servers -->
<div class="row mb-4">
<div class="col-12">
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">
<i class="fas fa-cloud me-2"></i>S3 Servers
</h6>
<div class="dropdown no-arrow">
<a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
</a>
<div class="dropdown-menu dropdown-menu-right shadow animated--fade-in">
<div class="dropdown-header">Actions:</div>
<a class="dropdown-item" href={ dash.PUrl(ctx, "/cluster/s3") }>View Details</a>
</div>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover" width="100%" cellspacing="0">
<thead>
<tr>
<th>Address</th>
<th>Data Center</th>
<th>Last Updated</th>
</tr>
</thead>
<tbody>
for _, s3Node := range data.S3Nodes {
<tr>
<td>{s3Node.Address}</td>
<td>{s3Node.DataCenter}</td>
<td>{s3Node.LastUpdated.Format("2006-01-02 15:04:05")}</td>
</tr>
}
if len(data.S3Nodes) == 0 {
<tr>
<td colspan="3" class="text-center text-muted py-4">
<i class="fas fa-info-circle me-2"></i>
No S3 servers found
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Last Updated -->
<div class="row">
<div class="col-12">
+129 -210
View File
@@ -176,7 +176,7 @@ func Admin(data dash.AdminData) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div><!-- System Health --><div class=\"col-lg-8\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-chart-pie me-2\"></i>Cluster</h6></div><div class=\"card-body text-center\"><div class=\"row\"><div class=\"col\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div><!-- System Health --><div class=\"col-lg-8\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-chart-pie me-2\"></i>Cluster</h6></div><div class=\"card-body text-center\"><div class=\"row\"><div class=\"col-3\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -189,7 +189,7 @@ func Admin(data dash.AdminData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</h5><small class=\"text-muted\">Masters</small></div></div></div><div class=\"col\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</h5><small class=\"text-muted\">Masters</small></div></div></div><div class=\"col-3\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -202,7 +202,7 @@ func Admin(data dash.AdminData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</h5><small class=\"text-muted\">Volume Servers</small></div></div></div><div class=\"col\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</h5><small class=\"text-muted\">Volume Servers</small></div></div></div><div class=\"col-3\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -215,303 +215,303 @@ func Admin(data dash.AdminData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</h5><small class=\"text-muted\">Filers</small></div></div></div><div class=\"col\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</h5><small class=\"text-muted\">Filers</small></div></div></div><div class=\"col-3\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.S3Nodes)))
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.MessageBrokers)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 234, Col: 81}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 234, Col: 88}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</h5><small class=\"text-muted\">S3 Servers</small></div></div></div><div class=\"col\"><div class=\"card bg-light\"><div class=\"card-body\"><h5>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</h5><small class=\"text-muted\">Message Brokers</small></div></div></div></div></div></div></div></div><!-- Volume Servers --><div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-database me-2\"></i>Volume Servers</h6><div class=\"dropdown no-arrow\"><a class=\"dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\"><i class=\"fas fa-ellipsis-v fa-sm fa-fw text-gray-400\"></i></a><div class=\"dropdown-menu dropdown-menu-right shadow animated--fade-in\"><div class=\"dropdown-header\">Actions:</div><a class=\"dropdown-item\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.MessageBrokers)))
var templ_7745c5c3_Var15 templ.SafeURL
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/volumes"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 242, Col: 88}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 259, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</h5><small class=\"text-muted\">Message Brokers</small></div></div></div></div></div></div></div></div><!-- Volume Servers --><div class=\"row\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-database me-2\"></i>Volume Servers</h6><div class=\"dropdown no-arrow\"><a class=\"dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\"><i class=\"fas fa-ellipsis-v fa-sm fa-fw text-gray-400\"></i></a><div class=\"dropdown-menu dropdown-menu-right shadow animated--fade-in\"><div class=\"dropdown-header\">Actions:</div><a class=\"dropdown-item\" href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "\">View Details</a> <a class=\"dropdown-item\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var16 templ.SafeURL
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/volumes"))
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/cluster"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 267, Col: 90}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 260, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "\">View Details</a> <a class=\"dropdown-item\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var17 templ.SafeURL
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/cluster"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 268, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "\">Topology View</a></div></div></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\"><thead><tr><th>ID</th><th>Address</th><th>Data Center</th><th>Rack</th><th>Volumes</th><th>EC Shards</th><th>Capacity</th></tr></thead> <tbody>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "\">Topology View</a></div></div></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\"><thead><tr><th>ID</th><th>Address</th><th>Data Center</th><th>Rack</th><th>Volumes</th><th>EC Shards</th><th>Capacity</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, vs := range data.VolumeServers {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<tr><td>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "<tr><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(vs.ID)
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(vs.ID)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 289, Col: 54}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 281, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "</td><td><a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 templ.SafeURL
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", vs.GetDisplayAddress())))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 283, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</td><td><a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\" target=\"_blank\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var19 templ.SafeURL
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", vs.GetDisplayAddress())))
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(vs.GetDisplayAddress())
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 291, Col: 129}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 284, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "\" target=\"_blank\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, " <i class=\"fas fa-external-link-alt ms-1 text-muted\"></i></a></td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(vs.GetDisplayAddress())
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(vs.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 292, Col: 75}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 288, Col: 62}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, " <i class=\"fas fa-external-link-alt ms-1 text-muted\"></i></a></td><td>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(vs.DataCenter)
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(vs.Rack)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 296, Col: 62}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 289, Col: 56}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</td><td>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</td><td><div class=\"progress\" style=\"height: 20px;\"><div class=\"progress-bar\" role=\"progressbar\" style=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(vs.Rack)
templ_7745c5c3_Var22, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(vs.Volumes, vs.MaxVolumes)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 297, Col: 56}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 293, Col: 135}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</td><td><div class=\"progress\" style=\"height: 20px;\"><div class=\"progress-bar\" role=\"progressbar\" style=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(vs.Volumes, vs.MaxVolumes)))
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d/%d", vs.Volumes, vs.MaxVolumes))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 301, Col: 135}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 294, Col: 104}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d/%d", vs.Volumes, vs.MaxVolumes))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 302, Col: 104}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</div></div></td><td>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</div></div></td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if vs.EcShards > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "<span class=\"badge bg-info text-white me-1\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "<span class=\"badge bg-info text-white me-1\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", vs.EcShards))
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", vs.EcShards))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 308, Col: 127}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 300, Col: 127}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</span> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "</span> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if vs.EcVolumes > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "<small class=\"text-muted\">(")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "<small class=\"text-muted\">(")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d vol", vs.EcVolumes))
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d vol", vs.EcVolumes))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 310, Col: 119}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 302, Col: 119}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, ")</small>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, ")</small>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "<span class=\"text-muted\">-</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "<span class=\"text-muted\">-</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</td><td>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(vs.DiskUsage))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 308, Col: 74}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, " / ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(vs.DiskUsage))
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(vs.DiskCapacity))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 316, Col: 74}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 308, Col: 107}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, " / ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(vs.DiskCapacity))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 316, Col: 107}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "</td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.VolumeServers) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "<tr><td colspan=\"7\" class=\"text-center text-muted py-4\"><i class=\"fas fa-info-circle me-2\"></i> No volume servers found</td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "<tr><td colspan=\"7\" class=\"text-center text-muted py-4\"><i class=\"fas fa-info-circle me-2\"></i> No volume servers found</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "</tbody></table></div></div></div></div></div><!-- Filer Nodes --><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-folder me-2\"></i>Filer Nodes</h6><div class=\"dropdown no-arrow\"><a class=\"dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\"><i class=\"fas fa-ellipsis-v fa-sm fa-fw text-gray-400\"></i></a><div class=\"dropdown-menu dropdown-menu-right shadow animated--fade-in\"><div class=\"dropdown-header\">Actions:</div><a class=\"dropdown-item\" href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "</tbody></table></div></div></div></div></div><!-- Filer Nodes --><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-folder me-2\"></i>Filer Nodes</h6><div class=\"dropdown no-arrow\"><a class=\"dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\"><i class=\"fas fa-ellipsis-v fa-sm fa-fw text-gray-400\"></i></a><div class=\"dropdown-menu dropdown-menu-right shadow animated--fade-in\"><div class=\"dropdown-header\">Actions:</div><a class=\"dropdown-item\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var28 templ.SafeURL
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/filer"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 341, Col: 88}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\">File Browser</a> <a class=\"dropdown-item\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var29 templ.SafeURL
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/filer"))
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/cluster"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 349, Col: 88}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 342, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "\">File Browser</a> <a class=\"dropdown-item\" href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var30 templ.SafeURL
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/cluster"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 350, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\">Topology View</a></div></div></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\"><thead><tr><th>Address</th><th>Data Center</th><th>Rack</th><th>Last Updated</th></tr></thead> <tbody>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "\">Topology View</a></div></div></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\"><thead><tr><th>Address</th><th>Data Center</th><th>Rack</th><th>Last Updated</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, filer := range data.FilerNodes {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "<tr><td><a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "<tr><td><a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var31 templ.SafeURL
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s", filer.Address)))
var templ_7745c5c3_Var30 templ.SafeURL
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s", filer.Address)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 369, Col: 106}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 361, Col: 106}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" target=\"_blank\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(filer.Address)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 362, Col: 66}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\" target=\"_blank\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, " <i class=\"fas fa-external-link-alt ms-1 text-muted\"></i></a></td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(filer.Address)
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(filer.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 370, Col: 66}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 366, Col: 65}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, " <i class=\"fas fa-external-link-alt ms-1 text-muted\"></i></a></td><td>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(filer.DataCenter)
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(filer.Rack)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 374, Col: 65}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 367, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil {
@@ -522,120 +522,39 @@ func Admin(data dash.AdminData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(filer.Rack)
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(filer.LastUpdated.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 375, Col: 59}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 368, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(filer.LastUpdated.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 376, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "</td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.FilerNodes) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "<tr><td colspan=\"4\" class=\"text-center text-muted py-4\"><i class=\"fas fa-info-circle me-2\"></i> No filer nodes found</td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "<tr><td colspan=\"4\" class=\"text-center text-muted py-4\"><i class=\"fas fa-info-circle me-2\"></i> No filer nodes found</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "</tbody></table></div></div></div></div></div><!-- S3 Servers --><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow mb-4\"><div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-cloud me-2\"></i>S3 Servers</h6><div class=\"dropdown no-arrow\"><a class=\"dropdown-toggle\" href=\"#\" role=\"button\" data-bs-toggle=\"dropdown\"><i class=\"fas fa-ellipsis-v fa-sm fa-fw text-gray-400\"></i></a><div class=\"dropdown-menu dropdown-menu-right shadow animated--fade-in\"><div class=\"dropdown-header\">Actions:</div><a class=\"dropdown-item\" href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "</tbody></table></div></div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var36 templ.SafeURL
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/cluster/s3"))
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 409, Col: 93}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 392, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\">View Details</a></div></div></div><div class=\"card-body\"><div class=\"table-responsive\"><table class=\"table table-hover\" width=\"100%\" cellspacing=\"0\"><thead><tr><th>Address</th><th>Data Center</th><th>Last Updated</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, s3Node := range data.S3Nodes {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "<tr><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var37 string
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(s3Node.Address)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 426, Col: 63}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(s3Node.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 427, Col: 66}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(s3Node.LastUpdated.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 428, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.S3Nodes) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "<tr><td colspan=\"3\" class=\"text-center text-muted py-4\"><i class=\"fas fa-info-circle me-2\"></i> No S3 servers found</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "</tbody></table></div></div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/admin.templ`, Line: 452, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</small></div></div></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "</small></div></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -1,139 +0,0 @@
package app
import (
"fmt"
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
)
templ ClusterS3Servers(data dash.ClusterS3ServersData) {
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">
<i class="fas fa-cloud me-2"></i>S3 Servers
</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group me-2">
<button type="button" class="btn btn-sm btn-outline-primary" onclick="exportS3Servers()">
<i class="fas fa-download me-1"></i>Export
</button>
</div>
</div>
</div>
<div id="s3-servers-content">
<!-- Summary Cards -->
<div class="row mb-4">
<div class="col-xl-12 col-md-12 mb-4">
<div class="card border-left-primary shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
Total S3 Servers
</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">
{ fmt.Sprintf("%d", data.TotalS3Servers) }
</div>
</div>
<div class="col-auto">
<i class="fas fa-cloud fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- S3 Servers Table -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">
<i class="fas fa-cloud me-2"></i>S3 Servers
</h6>
</div>
<div class="card-body">
if len(data.S3Servers) > 0 {
<div class="table-responsive">
<table class="table table-hover" id="s3ServersTable">
<thead>
<tr>
<th>Address</th>
<th>Version</th>
<th>Data Center</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
for _, s3Server := range data.S3Servers {
<tr>
<td>
{ s3Server.Address }
</td>
<td>
<span class="badge bg-light text-dark">{ s3Server.Version }</span>
</td>
<td>
<span class="badge bg-light text-dark">{ s3Server.DataCenter }</span>
</td>
<td>
if !s3Server.CreatedAt.IsZero() {
{ s3Server.CreatedAt.Format("2006-01-02 15:04:05") }
} else {
<span class="text-muted">N/A</span>
}
</td>
</tr>
}
</tbody>
</table>
</div>
} else {
<div class="text-center py-5">
<i class="fas fa-cloud fa-3x text-muted mb-3"></i>
<h5 class="text-muted">No S3 Servers Found</h5>
<p class="text-muted">No S3 servers are currently available in the cluster.</p>
</div>
}
</div>
</div>
<!-- Last Updated -->
<div class="row">
<div class="col-12">
<small class="text-muted">
<i class="fas fa-clock me-1"></i>
Last updated: { data.LastUpdated.Format("2006-01-02 15:04:05") }
</small>
</div>
</div>
</div>
<script>
function exportS3Servers() {
const table = document.getElementById('s3ServersTable');
if (!table) return;
let csv = 'Address,Version,Data Center,Created At\n';
const rows = table.querySelectorAll('tbody tr');
rows.forEach(row => {
const cells = row.querySelectorAll('td');
if (cells.length >= 4) {
const address = cells[0].textContent.trim();
const version = cells[1].textContent.trim();
const dataCenter = cells[2].textContent.trim();
const createdAt = cells[3].textContent.trim();
csv += `"${address}","${version}","${dataCenter}","${createdAt}"\n`;
}
});
const blob = new Blob([csv], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 's3-servers.csv';
a.click();
window.URL.revokeObjectURL(url);
}
</script>
}
@@ -1,155 +0,0 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1001
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import (
"fmt"
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
)
func ClusterS3Servers(data dash.ClusterS3ServersData) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom\"><h1 class=\"h2\"><i class=\"fas fa-cloud me-2\"></i>S3 Servers</h1><div class=\"btn-toolbar mb-2 mb-md-0\"><div class=\"btn-group me-2\"><button type=\"button\" class=\"btn btn-sm btn-outline-primary\" onclick=\"exportS3Servers()\"><i class=\"fas fa-download me-1\"></i>Export</button></div></div></div><div id=\"s3-servers-content\"><!-- Summary Cards --><div class=\"row mb-4\"><div class=\"col-xl-12 col-md-12 mb-4\"><div class=\"card border-left-primary shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-primary text-uppercase mb-1\">Total S3 Servers</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalS3Servers))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_s3_servers.templ`, Line: 34, Col: 49}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "</div></div><div class=\"col-auto\"><i class=\"fas fa-cloud fa-2x text-gray-300\"></i></div></div></div></div></div></div><!-- S3 Servers Table --><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-cloud me-2\"></i>S3 Servers</h6></div><div class=\"card-body\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(data.S3Servers) > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<div class=\"table-responsive\"><table class=\"table table-hover\" id=\"s3ServersTable\"><thead><tr><th>Address</th><th>Version</th><th>Data Center</th><th>Created At</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, s3Server := range data.S3Servers {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "<tr><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(s3Server.Address)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_s3_servers.templ`, Line: 69, Col: 29}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</td><td><span class=\"badge bg-light text-dark\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(s3Server.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_s3_servers.templ`, Line: 72, Col: 68}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</span></td><td><span class=\"badge bg-light text-dark\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(s3Server.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_s3_servers.templ`, Line: 75, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</span></td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if !s3Server.CreatedAt.IsZero() {
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(s3Server.CreatedAt.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_s3_servers.templ`, Line: 79, Col: 62}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<span class=\"text-muted\">N/A</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</tbody></table></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "<div class=\"text-center py-5\"><i class=\"fas fa-cloud fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No S3 Servers Found</h5><p class=\"text-muted\">No S3 servers are currently available in the cluster.</p></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_s3_servers.templ`, Line: 104, Col: 67}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</small></div></div></div><script>\n\tfunction exportS3Servers() {\n\t\tconst table = document.getElementById('s3ServersTable');\n\t\tif (!table) return;\n\n\t\tlet csv = 'Address,Version,Data Center,Created At\\n';\n\n\t\tconst rows = table.querySelectorAll('tbody tr');\n\t\trows.forEach(row => {\n\t\t\tconst cells = row.querySelectorAll('td');\n\t\t\tif (cells.length >= 4) {\n\t\t\t\tconst address = cells[0].textContent.trim();\n\t\t\t\tconst version = cells[1].textContent.trim();\n\t\t\t\tconst dataCenter = cells[2].textContent.trim();\n\t\t\t\tconst createdAt = cells[3].textContent.trim();\n\n\t\t\t\tcsv += `\"${address}\",\"${version}\",\"${dataCenter}\",\"${createdAt}\"\\n`;\n\t\t\t}\n\t\t});\n\n\t\tconst blob = new Blob([csv], { type: 'text/csv' });\n\t\tconst url = window.URL.createObjectURL(blob);\n\t\tconst a = document.createElement('a');\n\t\ta.href = url;\n\t\ta.download = 's3-servers.csv';\n\t\ta.click();\n\t\twindow.URL.revokeObjectURL(url);\n\t}\n\t</script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
var _ = templruntime.GeneratedTemplate
+1 -6
View File
@@ -32,7 +32,7 @@ templ Layout(view ViewContext, content templ.Component) {
isStoragePage := strings.HasPrefix(currentPath, "/storage/volumes") || strings.HasPrefix(currentPath, "/storage/ec-shards") || strings.HasPrefix(currentPath, "/storage/collections")
// Detect if we're on a cluster page (but not storage page) to keep submenu expanded
isClusterPage := (strings.HasPrefix(currentPath, "/cluster/masters") || strings.HasPrefix(currentPath, "/cluster/volume-servers") || strings.HasPrefix(currentPath, "/cluster/filers") || strings.HasPrefix(currentPath, "/cluster/s3"))
isClusterPage := (strings.HasPrefix(currentPath, "/cluster/masters") || strings.HasPrefix(currentPath, "/cluster/volume-servers") || strings.HasPrefix(currentPath, "/cluster/filers"))
isDefaultWorkerPage := currentPath == "/plugin" ||
strings.HasPrefix(currentPath, "/plugin/configuration") ||
@@ -134,11 +134,6 @@ templ Layout(view ViewContext, content templ.Component) {
<i class="fas fa-folder-open me-2"></i>Filers
</a>
</li>
<li class="nav-item">
<a class="nav-link py-2" href={ view.P("/cluster/s3") }>
<i class="fas fa-cloud me-2"></i>S3 Servers
</a>
</li>
</ul>
</div>
</li>
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -65,7 +65,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.dataDir = cmdAdmin.Flag.String("dataDir", ".", "directory to store admin configuration and data files (default current dir; required for maintenance task state to persist)")
a.dataDir = cmdAdmin.Flag.String("dataDir", "", "directory to store admin configuration and data files")
a.adminUser = cmdAdmin.Flag.String("adminUser", "admin", "admin interface username")
a.adminPassword = cmdAdmin.Flag.String("adminPassword", "", "admin interface password (if empty, auth is disabled)")
@@ -248,6 +248,7 @@ func runAdmin(cmd *Command, args []string) bool {
fmt.Println("WARNING: Admin interface is running without authentication!")
fmt.Println(" Set -adminPassword for production use")
}
fmt.Printf("Starting SeaweedFS Admin Interface on port %d\n", *a.port)
fmt.Printf("Worker gRPC server will run on port %d\n", *a.grpcPort)
fmt.Printf("Masters: %s\n", *a.master)
-1
View File
@@ -335,7 +335,6 @@ func (fo *FilerOptions) startFiler() {
if *fo.bindIp == "" {
*fo.bindIp = *fo.ip
}
util.SetOutboundLocalIP(*fo.bindIp)
if *fo.allowedOrigins == "" {
*fo.allowedOrigins = "*"
}
+26 -25
View File
@@ -63,7 +63,7 @@ func init() {
filerBackupOptions.retentionDays = cmdFilerBackup.Flag.Int("retentionDays", 0, "incremental backup retention days")
filerBackupOptions.disableErrorRetry = cmdFilerBackup.Flag.Bool("disableErrorRetry", false, "disables errors retry, only logs will print")
filerBackupOptions.ignore404Error = cmdFilerBackup.Flag.Bool("ignore404Error", true, "ignore 404 errors from filer")
filerBackupOptions.initialSnapshot = cmdFilerBackup.Flag.Bool("initialSnapshot", false, "before subscribing to metadata updates, walk the live filer tree under -filerPath and seed the destination, then subscribe from the walk-start timestamp so concurrent changes are still captured. Runs on every start when -timeAgo is 0 and overwrites the saved checkpoint, so it also re-seeds a reinitialized destination. Remove it once the backup is caught up, otherwise it re-walks the whole tree on each restart.")
filerBackupOptions.initialSnapshot = cmdFilerBackup.Flag.Bool("initialSnapshot", false, "before subscribing to metadata updates, walk the live filer tree under -filerPath and seed the destination. Only runs on a fresh sync (no prior checkpoint and -timeAgo is 0). After the walk, subscription starts from the walk-start timestamp so concurrent changes are still captured.")
}
var cmdFilerBackup = &Command{
@@ -75,13 +75,12 @@ var cmdFilerBackup = &Command{
and write to the destination. This is to replace filer.replicate command since additional message queue is not needed.
If restarted and "-timeAgo" is not set, the synchronization will resume from the previous checkpoints, persisted every minute.
A fresh sync will start from the earliest metadata logs.
A fresh sync will start from the earliest metadata logs. To reset the checkpoints, just set "-timeAgo" to a high value.
On a fresh sync the metadata event log only re-materializes files that still exist on the source; entries that were
created and later deleted are replayed as a create-then-delete pair and therefore never appear on the destination.
Pass "-initialSnapshot" to walk the live filer tree first and seed the destination with the current tree, then
subscribe from the walk-start timestamp. This also re-seeds a reinitialized destination: it overwrites the saved
checkpoint and re-walks on every start, so remove it once the backup is caught up.
subscribe from the walk-start timestamp. The walk only runs when there is no prior checkpoint.
`,
}
@@ -136,25 +135,27 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
// get start time for the data sink
startFrom := time.Unix(0, 0)
isFreshSync := true
sinkId := util.HashStringToLong(dataSink.GetName() + dataSink.GetSinkToDirectory())
runSnapshot := *backupOption.initialSnapshot && timeAgo == 0
if timeAgo == 0 {
if runSnapshot {
// snapshot below sets the start point; no checkpoint read needed
glog.V(0).Infof("initialSnapshot requested — walking live tree before subscribing")
if timeAgo.Milliseconds() == 0 {
lastOffsetTsNs, err := getOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, int32(sinkId))
if err != nil {
// A KV read failure is ambiguous — a checkpoint may well exist but the
// source filer is temporarily unreachable. Don't treat that as a fresh
// sync; otherwise runFilerBackup's retry loop would redo the full
// -initialSnapshot walk on every transient error.
isFreshSync = false
glog.V(0).Infof("starting from %v (offset read failed: %v)", startFrom, err)
} else if lastOffsetTsNs > 0 {
startFrom = time.Unix(0, lastOffsetTsNs)
isFreshSync = false
glog.V(0).Infof("resuming from %v", startFrom)
} else {
lastOffsetTsNs, err := getOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, int32(sinkId))
if err != nil {
glog.V(0).Infof("starting from %v (offset read failed: %v)", startFrom, err)
} else if lastOffsetTsNs > 0 {
startFrom = time.Unix(0, lastOffsetTsNs)
glog.V(0).Infof("resuming from %v", startFrom)
} else {
glog.V(0).Infof("starting from %v (no prior checkpoint)", startFrom)
}
glog.V(0).Infof("starting from %v (no prior checkpoint)", startFrom)
}
} else {
startFrom = time.Now().Add(-timeAgo)
isFreshSync = false
glog.V(0).Infof("start time is set to %v", startFrom)
}
@@ -173,11 +174,13 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
}
dataSink.SetSourceFiler(filerSource)
// Walk and seed the live tree, then subscribe from the walk-start watermark:
// replaying the event log alone misses entries created-then-deleted before
// the walk. The watermark overwrites any stale checkpoint, re-seeding a wiped
// destination.
if runSnapshot {
// When the destination has no prior checkpoint and the user opted in to an
// initial snapshot, walk the live filer tree first and seed the destination
// with the current entries. This avoids the "only new files appear" pitfall
// of replaying the metadata event log: entries created-then-deleted before
// the walk leave no trace, so a re-backup after wiping the destination
// reflects what is actually live on the source instead of an empty tree.
if *backupOption.initialSnapshot && isFreshSync {
snapshotTsNs, err := runInitialSnapshot(sourceFiler.ToGrpcAddress(), filerSource, sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.ignore404Error)
if err != nil {
return fmt.Errorf("initial snapshot: %w", err)
@@ -190,8 +193,6 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
return fmt.Errorf("persist initial snapshot offset: %w", err)
}
startFrom = time.Unix(0, snapshotTsNs)
// walk once per process; retries resume from the persisted checkpoint
*backupOption.initialSnapshot = false
glog.V(0).Infof("initialSnapshot done; subscribing from %v", startFrom)
}
+2 -2
View File
@@ -103,7 +103,7 @@ func init() {
m.raftResumeState = cmdMaster.Flag.Bool("resumeState", true, "resume previous state on start master server")
m.heartbeatInterval = cmdMaster.Flag.Duration("heartbeatInterval", 300*time.Millisecond, "heartbeat interval of master servers, and will be randomly multiplied by [1, 1.25)")
m.electionTimeout = cmdMaster.Flag.Duration("electionTimeout", 10*time.Second, "election timeout of master servers")
m.raftHashicorp = cmdMaster.Flag.Bool("raftHashicorp", false, "use hashicorp raft")
m.raftHashicorp = cmdMaster.Flag.Bool("raftHashicorp", false, "use hashicorp raft (recommended; legacy seaweedfs/raft is deprecated)")
m.raftBootstrap = cmdMaster.Flag.Bool("raftBootstrap", false, "Whether to bootstrap the Raft cluster")
m.telemetryUrl = cmdMaster.Flag.String("telemetry.url", "https://telemetry.seaweedfs.com/api/collect", "telemetry server URL to send usage statistics")
m.telemetryEnabled = cmdMaster.Flag.Bool("telemetry", false, "enable telemetry reporting")
@@ -188,7 +188,6 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
if *masterOption.ipBind == "" {
*masterOption.ipBind = *masterOption.ip
}
util.SetOutboundLocalIP(*masterOption.ipBind)
myMasterAddress, peers := checkPeers(*masterOption.ip, *masterOption.port, *masterOption.portGrpc, *masterOption.peers)
@@ -230,6 +229,7 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
glog.Fatalf("NewHashicorpRaftServer: %s", err)
}
} else {
glog.Warningf("legacy seaweedfs/raft is deprecated and will be removed; restart with -raftHashicorp to switch (cluster state is migrated automatically)")
raftServer, err = weed_server.NewRaftServer(raftServerOption)
if raftServer == nil {
glog.Fatalf("please verify %s is writable, see https://github.com/seaweedfs/seaweedfs/issues/717: %s", *masterOption.metaFolder, err)
+1 -1
View File
@@ -430,7 +430,7 @@ func initMiniMasterFlags() {
miniMasterOptions.raftResumeState = cmdMini.Flag.Bool("master.resumeState", true, "resume previous state on start master server")
miniMasterOptions.heartbeatInterval = cmdMini.Flag.Duration("master.heartbeatInterval", 300*time.Millisecond, "heartbeat interval of master servers, and will be randomly multiplied by [1, 1.25)")
miniMasterOptions.electionTimeout = cmdMini.Flag.Duration("master.electionTimeout", 10*time.Second, "election timeout of master servers")
miniMasterOptions.raftHashicorp = cmdMini.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft")
miniMasterOptions.raftHashicorp = cmdMini.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft (recommended; legacy seaweedfs/raft is deprecated)")
miniMasterOptions.raftBootstrap = cmdMini.Flag.Bool("master.raftBootstrap", false, "whether to bootstrap the Raft cluster")
miniMasterOptions.telemetryUrl = cmdMini.Flag.String("master.telemetry.url", "https://telemetry.seaweedfs.com/api/collect", "telemetry server URL")
miniMasterOptions.telemetryEnabled = cmdMini.Flag.Bool("master.telemetry", false, "enable telemetry reporting")
-3
View File
@@ -261,9 +261,6 @@ func (s3opt *S3Options) resolvePaths() {
func (s3opt *S3Options) startS3Server() bool {
// Before the first filer dial below; gRPC caches conns and binds at dial time.
util.SetOutboundLocalIP(*s3opt.bindIp)
filerAddresses := pb.ServerAddresses(*s3opt.filer).ToAddresses()
filerBucketsPath := "/buckets"
+1 -4
View File
@@ -103,7 +103,7 @@ func init() {
masterOptions.metricsAddress = cmdServer.Flag.String("master.metrics.address", "", "Prometheus gateway address")
masterOptions.metricsIntervalSec = cmdServer.Flag.Int("master.metrics.intervalSeconds", 15, "Prometheus push interval in seconds")
masterOptions.raftResumeState = cmdServer.Flag.Bool("master.resumeState", true, "resume previous state on start master server")
masterOptions.raftHashicorp = cmdServer.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft")
masterOptions.raftHashicorp = cmdServer.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft (recommended; legacy seaweedfs/raft is deprecated)")
masterOptions.raftBootstrap = cmdServer.Flag.Bool("master.raftBootstrap", false, "Whether to bootstrap the Raft cluster")
masterOptions.heartbeatInterval = cmdServer.Flag.Duration("master.heartbeatInterval", 300*time.Millisecond, "heartbeat interval of master servers, and will be randomly multiplied by [1, 1.25)")
masterOptions.electionTimeout = cmdServer.Flag.Duration("master.electionTimeout", 10*time.Second, "election timeout of master servers")
@@ -274,9 +274,6 @@ func runServer(cmd *Command, args []string) bool {
if *serverBindIp == "" {
serverBindIp = serverIp
}
// Bind outbound connections to the same address up front so every
// component started below inherits it, before any of them dials.
util.SetOutboundLocalIP(*serverBindIp)
if *serverMetricsHttpIp == "" {
*serverMetricsHttpIp = *serverBindIp
-1
View File
@@ -110,7 +110,6 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
if *sftpOpt.bindIp == "" {
*sftpOpt.bindIp = "0.0.0.0"
}
util.SetOutboundLocalIP(*sftpOpt.bindIp)
filerAddress := pb.ServerAddress(*sftpOpt.filer)
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
-1
View File
@@ -380,7 +380,6 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
if *v.bindIp == "" {
*v.bindIp = *v.ip
}
util.SetOutboundLocalIP(*v.bindIp)
if *v.publicPort == 0 {
*v.publicPort = *v.port
-2
View File
@@ -89,8 +89,6 @@ func (wo *WebDavOption) resolvePaths() {
func (wo *WebDavOption) startWebDav() bool {
util.SetOutboundLocalIP(*wo.ipBind)
// detect current user
uid, gid := uint32(0), uint32(0)
if u, err := user.Current(); err == nil {
+19 -22
View File
@@ -17,46 +17,43 @@ type VidInfo struct {
}
type VidCache struct {
sync.RWMutex
cache map[uint32]VidInfo
cache []VidInfo
}
func (vc *VidCache) Get(vid string) ([]Location, error) {
id, err := strconv.ParseUint(vid, 10, 32)
id, err := strconv.Atoi(vid)
if err != nil {
glog.V(1).Infof("Unknown volume id %s", vid)
return nil, err
}
if id == 0 {
return nil, ErrorNotFound
}
vc.RLock()
defer vc.RUnlock()
info, found := vc.cache[uint32(id)]
if !found || info.Locations == nil {
return nil, ErrorNotFound
if 0 < id && id <= len(vc.cache) {
if vc.cache[id-1].Locations == nil {
return nil, errors.New("not set")
}
if vc.cache[id-1].NextRefreshTime.Before(time.Now()) {
return nil, errors.New("expired")
}
return vc.cache[id-1].Locations, nil
}
if info.NextRefreshTime.Before(time.Now()) {
return nil, errors.New("expired")
}
return info.Locations, nil
return nil, ErrorNotFound
}
func (vc *VidCache) Set(vid string, locations []Location, duration time.Duration) {
id, err := strconv.ParseUint(vid, 10, 32)
id, err := strconv.Atoi(vid)
if err != nil {
glog.V(1).Infof("Unknown volume id %s", vid)
return
}
if id == 0 {
return
}
vc.Lock()
defer vc.Unlock()
if vc.cache == nil {
vc.cache = make(map[uint32]VidInfo)
if id > len(vc.cache) {
for i := id - len(vc.cache); i > 0; i-- {
vc.cache = append(vc.cache, VidInfo{})
}
}
vc.cache[uint32(id)] = VidInfo{
Locations: locations,
NextRefreshTime: time.Now().Add(duration),
if id > 0 {
vc.cache[id-1].Locations = locations
vc.cache[id-1].NextRefreshTime = time.Now().Add(duration)
}
}
-22
View File
@@ -24,25 +24,3 @@ func TestCaching(t *testing.T) {
t.Fatal("Not found vid 123")
}
}
// a single large volume id must not allocate an entry per id below it
func TestCachingLargeVolumeId(t *testing.T) {
var vc VidCache
locations := []Location{{Url: "a.com:8080"}}
vc.Set("32000000", locations, time.Minute)
if got := len(vc.cache); got != 1 {
t.Fatalf("expected 1 cached entry, got %d", got)
}
if ret, _ := vc.Get("32000000"); ret == nil {
t.Fatal("Not found vid 32000000")
}
// ids beyond uint32 are not real volume ids and must not wrap into the cache
vc.Set("4294967296", locations, time.Minute)
if got := len(vc.cache); got != 1 {
t.Fatalf("out-of-range id must not be cached, got %d entries", got)
}
if ret, _ := vc.Get("4294967296"); ret != nil {
t.Fatal("out-of-range vid 4294967296 should not be found")
}
}
+2 -17
View File
@@ -73,13 +73,8 @@ type versionedGrpcClient struct {
}
func init() {
t := http.DefaultTransport.(*http.Transport)
t.MaxIdleConnsPerHost = 1024
t.MaxIdleConns = 1024
// Bind outbound HTTP to the -ip.bind source address. Reads the setting
// per dial, so it applies regardless of when SetOutboundLocalIP runs
// relative to this init.
t.DialContext = util.OutboundDialContext
http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1024
http.DefaultTransport.(*http.Transport).MaxIdleConns = 1024
}
// RegisterLocalGrpcSocket registers a Unix socket path for a gRPC service
@@ -212,16 +207,6 @@ func GrpcDial(ctx context.Context, address string, waitForReady bool, opts ...gr
var d net.Dialer
return d.DialContext(ctx, "unix", socketPath)
}))
} else {
// Always install so a conn cached before SetOutboundLocalIP binds once set;
// the stock net.Dialer until then preserves gRPC's default dial behavior.
options = append(options, grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
if util.OutboundLocalAddr() == nil {
var d net.Dialer
return d.DialContext(ctx, "tcp", addr)
}
return util.OutboundDialContext(ctx, "tcp", addr)
}))
}
options = append(options,
+2 -1
View File
@@ -25,7 +25,8 @@ const (
adminScriptDetectTickMinutes = 17
)
const defaultAdminScript = `fs.log.purge -daysAgo=7
const defaultAdminScript = `ec.balance -apply
fs.log.purge -daysAgo=7
volume.deleteEmpty -quietFor=24h -apply
volume.fix.replication -apply
s3.clean.uploads -timeAgo=24h`
-1
View File
@@ -164,7 +164,6 @@ func buildVolumeMetrics(
DataCenter: dc.Id,
Rack: rack.Id,
NodeID: node.Id,
Host: pb.NewServerAddressFromDataNode(node).ToHost(),
})
if collectionRegex != nil && !collectionRegex.MatchString(volume.Collection) {
+1 -2
View File
@@ -239,8 +239,7 @@ func validateV2AuthHeader(v2Auth string) (accessKey string, errCode s3err.ErrorC
// Signature V2 authorization header format:
// Authorization: AWS AKIAIOSFODNN7EXAMPLE:frJIUN8DYpKDtOLCwo//yllqDzg=
const signV2AlgorithmPrefix = signV2Algorithm + " "
if !strings.HasPrefix(v2Auth, signV2AlgorithmPrefix) {
if !strings.HasPrefix(v2Auth, signV2Algorithm) {
return "", s3err.ErrSignatureVersionNotSupported
}
+1 -6
View File
@@ -57,11 +57,6 @@ func TestValidateV2AuthHeader(t *testing.T) {
authHeader: "HMAC AKIAIOSFODNN7EXAMPLE:signature",
expectedError: s3err.ErrSignatureVersionNotSupported,
},
{
name: "algorithm prefix without space",
authHeader: "AWSXAKIAIOSFODNN7EXAMPLE:signature",
expectedError: s3err.ErrSignatureVersionNotSupported,
},
{
name: "missing colon separator",
authHeader: "AWS AKIAIOSFODNN7EXAMPLE",
@@ -237,7 +232,7 @@ func TestDoesSignV2Match(t *testing.T) {
query: "",
headers: map[string]string{"Date": "Mon, 09 Sep 2011 23:36:00 GMT"},
authOverride: "AWSAKIAIOSFODNN7EXAMPLE:signature==",
expectedError: s3err.ErrSignatureVersionNotSupported,
expectedError: s3err.ErrInvalidAccessKeyID,
expectIdent: false,
},
}
-5
View File
@@ -326,11 +326,6 @@ func validateDefaultRetention(retention *DefaultRetention) error {
return ErrInvalidRetentionPeriod
}
// Check for invalid Years value (zero is invalid when explicitly provided)
if retention.YearsSet && retention.Years == 0 {
return ErrInvalidRetentionPeriod
}
// Check for neither Days nor Years being specified
if !retention.DaysSet && !retention.YearsSet {
return ErrDefaultRetentionMissingPeriod
-7
View File
@@ -26,13 +26,6 @@ const (
// the entry's own mtime so legacy data still expires.
ExtNoncurrentSinceNsKey = "Seaweed-X-Amz-Noncurrent-Since-Ns"
// Per-bucket opt-in for the PutObject lifecycle TTL fast path ("true"
// to enable). When on, an Expiration.Days rule is stamped as a volume
// TTL at write time instead of being expired by the worker. Off by
// default: a baked-in TTL can't honor a later policy change (rule
// removed or lengthened) the way worker-driven expiration does.
ExtLifecycleTtlFastPathKey = "Seaweed-X-Amz-Lifecycle-Ttl-Fast-Path"
// S3 checksum storage keys (use x-seaweedfs- prefix to avoid leaking in generic header loop)
ExtChecksumAlgorithm = "x-seaweedfs-checksum-algorithm"
ExtChecksumValue = "x-seaweedfs-checksum-value"
+19 -23
View File
@@ -39,9 +39,9 @@ type BucketConfig struct {
BucketPolicy *policy_engine.PolicyDocument // Cached bucket policy for performance
// LifecycleTTL answers "what volume TTL should this PutObject get?"
// using only fast-path-safe predicates (prefix + size; tags excluded
// because they're mutable post-PUT). nil = no TTL applies (fast path
// not enabled on the bucket, no lifecycle config, versioned bucket,
// or only ineligible rules). The fast path is opt-in per bucket. The
// because they're mutable post-PUT). nil = no TTL applies (no
// lifecycle config, versioned bucket, or only ineligible rules).
// The full canonical rule set lives inside the resolver; the
// lifecycle worker reads bucket entries directly off the meta-log
// rather than this cache.
LifecycleTTL *LifecycleTTLResolver
@@ -438,26 +438,22 @@ func (s3a *S3ApiServer) populateBucketConfigDerivedFields(config *BucketConfig)
}
config.BucketPolicy = loadBucketPolicyFromExtended(entry, bucket)
// The lifecycle TTL fast path is opt-in per bucket: a volume TTL
// stamped at write time can't honor a later policy change (rule
// removed or lengthened) the way worker-driven expiration does,
// so it stays off unless explicitly enabled. Skip the XML parse
// entirely when off. nil on parse error so the PUT path falls
// through to "no TTL" rather than rejecting writes.
if bytes.Equal(entry.Extended[s3_constants.ExtLifecycleTtlFastPathKey], []byte("true")) {
if xmlBytes, ok := entry.Extended[bucketLifecycleConfigurationXMLKey]; ok && len(xmlBytes) > 0 {
if rules, err := lifecycle_xml.ParseCanonical(xmlBytes); err == nil {
// Object Lock requires versioning, so an ObjectLockConfig
// implies the bucket is versioned even when the explicit
// Versioning header was never written. BucketIsVersioned
// in this file uses the same OR — keep them aligned.
versioned := config.Versioning == s3_constants.VersioningEnabled ||
config.Versioning == s3_constants.VersioningSuspended ||
config.ObjectLockConfig != nil
config.LifecycleTTL = NewLifecycleTTLResolver(rules, versioned)
} else {
glog.V(1).Infof("populateBucketConfigDerivedFields: bucket %s lifecycle xml parse: %v", bucket, err)
}
// Pre-parse lifecycle XML so the per-write TTL resolver doesn't
// pay parsing cost on every PutObject. nil on parse error so
// the PUT path falls through to "no TTL" rather than rejecting
// writes.
if xmlBytes, ok := entry.Extended[bucketLifecycleConfigurationXMLKey]; ok && len(xmlBytes) > 0 {
if rules, err := lifecycle_xml.ParseCanonical(xmlBytes); err == nil {
// Object Lock requires versioning, so an ObjectLockConfig
// implies the bucket is versioned even when the explicit
// Versioning header was never written. BucketIsVersioned
// in this file uses the same OR — keep them aligned.
versioned := config.Versioning == s3_constants.VersioningEnabled ||
config.Versioning == s3_constants.VersioningSuspended ||
config.ObjectLockConfig != nil
config.LifecycleTTL = NewLifecycleTTLResolver(rules, versioned)
} else {
glog.V(1).Infof("populateBucketConfigDerivedFields: bucket %s lifecycle xml parse: %v", bucket, err)
}
}
}
+34 -12
View File
@@ -444,11 +444,8 @@ func cloneProtoEntry(entry *filer_pb.Entry) *filer_pb.Entry {
return proto.Clone(entry).(*filer_pb.Entry)
}
func copyEntryETag(entry *filer_pb.Entry) string {
if entry == nil {
return ""
}
if entry.Extended != nil {
func copyEntryETag(fullPath util.FullPath, entry *filer_pb.Entry) string {
if entry != nil && entry.Extended != nil {
if etag, ok := entry.Extended[s3_constants.ExtETagKey]; ok && len(etag) > 0 {
return string(etag)
}
@@ -464,10 +461,11 @@ func copyEntryETag(entry *filer_pb.Entry) string {
}
}
return filer.ETagEntry(&filer.Entry{
Attr: attr,
Chunks: entry.Chunks,
Content: entry.Content,
Remote: entry.RemoteEntry,
FullPath: fullPath,
Attr: attr,
Chunks: entry.Chunks,
Content: entry.Content,
Remote: entry.RemoteEntry,
})
}
@@ -496,7 +494,7 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
dstEntry.Extended = make(map[string][]byte)
}
etag = copyEntryETag(dstEntry)
etag = copyEntryETag(dstPath, dstEntry)
switch dstVersioningState {
case s3_constants.VersioningEnabled:
@@ -989,7 +987,19 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
}
// Calculate ETag for the part
etag := copyEntryETag(dstEntry)
partPath := util.FullPath(uploadDir + "/" + partName)
filerEntry := &filer.Entry{
FullPath: partPath,
Attr: filer.Attr{
FileSize: dstEntry.Attributes.FileSize,
Mtime: time.Unix(dstEntry.Attributes.Mtime, 0),
Crtime: time.Unix(dstEntry.Attributes.Crtime, 0),
Mime: dstEntry.Attributes.Mime,
},
Chunks: dstEntry.Chunks,
}
etag := filer.ETagEntry(filerEntry)
setEtag(w, etag)
response := CopyPartResult{
@@ -1419,7 +1429,19 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e
// validateConditionalCopyHeaders validates the conditional copy headers against the source entry
func (s3a *S3ApiServer) validateConditionalCopyHeaders(r *http.Request, entry *filer_pb.Entry) s3err.ErrorCode {
sourceETag := copyEntryETag(entry)
// Calculate ETag for the source entry. ETagEntry derives the tag from the
// chunks/Md5/remote-etag only, so no path is needed here.
filerEntry := &filer.Entry{
Attr: filer.Attr{
FileSize: entry.Attributes.FileSize,
Mtime: time.Unix(entry.Attributes.Mtime, 0),
Crtime: time.Unix(entry.Attributes.Crtime, 0),
Mime: entry.Attributes.Mime,
Md5: entry.Attributes.Md5,
},
Chunks: entry.Chunks,
}
sourceETag := filer.ETagEntry(filerEntry)
// Check X-Amz-Copy-Source-If-Match
if ifMatch := r.Header.Get(s3_constants.AmzCopySourceIfMatch); ifMatch != "" {
@@ -1,65 +0,0 @@
package s3api
import (
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
func TestCopyEntryETagPrefersStoredExtendedETag(t *testing.T) {
storedETag := "11111111111111111111111111111111-2"
entry := newCopyETagTestEntry(t, storedETag, "22222222222222222222222222222222")
if got := copyEntryETag(entry); got != storedETag {
t.Fatalf("copyEntryETag() = %q, want stored extended ETag %q", got, storedETag)
}
}
func TestCopyEntryETagFallsBackToFilerETag(t *testing.T) {
computedETag := "33333333333333333333333333333333"
entry := newCopyETagTestEntry(t, "", computedETag)
if got := strings.Trim(copyEntryETag(entry), `"`); got != computedETag {
t.Fatalf("copyEntryETag() = %q, want fallback filer ETag %q", got, computedETag)
}
}
func TestValidateConditionalCopyHeadersUsesStoredExtendedETag(t *testing.T) {
storedETag := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-2"
entry := newCopyETagTestEntry(t, storedETag, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
s3a := &S3ApiServer{}
matchReq := httptest.NewRequest("PUT", "/dst", nil)
matchReq.Header.Set(s3_constants.AmzCopySourceIfMatch, `"`+storedETag+`"`)
if got := s3a.validateConditionalCopyHeaders(matchReq, entry); got != s3err.ErrNone {
t.Fatalf("validateConditionalCopyHeaders(If-Match stored ETag) = %v, want %v", got, s3err.ErrNone)
}
noneMatchReq := httptest.NewRequest("PUT", "/dst", nil)
noneMatchReq.Header.Set(s3_constants.AmzCopySourceIfNoneMatch, storedETag)
if got := s3a.validateConditionalCopyHeaders(noneMatchReq, entry); got != s3err.ErrPreconditionFailed {
t.Fatalf("validateConditionalCopyHeaders(If-None-Match stored ETag) = %v, want %v", got, s3err.ErrPreconditionFailed)
}
}
func newCopyETagTestEntry(t *testing.T, storedETag, computedETag string) *filer_pb.Entry {
t.Helper()
entry := &filer_pb.Entry{
Name: "object",
Attributes: &filer_pb.FuseAttributes{
FileSize: 5,
Md5: mustDecodeHexETagForTest(t, computedETag),
},
}
if storedETag != "" {
entry.Extended = map[string][]byte{
s3_constants.ExtETagKey: []byte(storedETag),
}
}
return entry
}
+4 -5
View File
@@ -152,13 +152,12 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
glog.Errorf("deleteVersionedObject: failed to delete null version for %s/%s: %v", bucket, object, err)
return result, s3err.ErrInternalError
}
// Suspended versioning overwrites the null version with a single null delete
// marker (S3 spec), so the marker replaces any prior one instead of piling up.
if err := s3a.createNullDeleteMarker(bucket, object); err != nil {
glog.Errorf("deleteVersionedObject: failed to create null delete marker for suspended versioning %s/%s: %v", bucket, object, err)
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
if err != nil {
glog.Errorf("deleteVersionedObject: failed to create delete marker for suspended versioning %s/%s: %v", bucket, object, err)
return result, s3err.ErrInternalError
}
result.versionId = "null"
result.versionId = deleteMarkerVersionId
result.deleteMarker = true
return result, s3err.ErrNone
}
+1 -28
View File
@@ -205,9 +205,7 @@ func TestPopulateBucketConfigDerivedFields_RefreshesLifecycleTTL(t *testing.T) {
xmlAdd := []byte(`<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><ID>r</ID><Status>Enabled</Status><Filter><Prefix>logs/</Prefix></Filter><Expiration><Days>7</Days></Expiration></Rule></LifecycleConfiguration>`)
xmlReplace := []byte(`<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><ID>r</ID><Status>Enabled</Status><Filter><Prefix>logs/</Prefix></Filter><Expiration><Days>30</Days></Expiration></Rule></LifecycleConfiguration>`)
cfg := &BucketConfig{Name: "bk", Entry: &filer_pb.Entry{Extended: map[string][]byte{
s3_constants.ExtLifecycleTtlFastPathKey: []byte("true"),
}}}
cfg := &BucketConfig{Name: "bk", Entry: &filer_pb.Entry{Extended: map[string][]byte{}}}
// 1) No XML yet → no resolver.
s.populateBucketConfigDerivedFields(cfg)
@@ -251,7 +249,6 @@ func TestPopulateBucketConfigDerivedFields_ObjectLockTreatedAsVersioned(t *testi
Name: "bk",
Entry: &filer_pb.Entry{Extended: map[string][]byte{
s3_constants.ExtObjectLockEnabledKey: []byte(s3_constants.ObjectLockEnabled),
s3_constants.ExtLifecycleTtlFastPathKey: []byte("true"),
bucketLifecycleConfigurationXMLKey: xml,
}},
}
@@ -263,27 +260,3 @@ func TestPopulateBucketConfigDerivedFields_ObjectLockTreatedAsVersioned(t *testi
t.Fatalf("ObjectLock buckets must skip the fast-path resolver, got %v", cfg.LifecycleTTL)
}
}
func TestPopulateBucketConfigDerivedFields_TtlFastPathOptIn(t *testing.T) {
// The fast path is opt-in per bucket: lifecycle XML alone must not
// stamp volume TTL on writes. Only the explicit flag builds the
// resolver.
s := &S3ApiServer{}
xml := []byte(`<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><ID>r</ID><Status>Enabled</Status><Filter><Prefix>logs/</Prefix></Filter><Expiration><Days>7</Days></Expiration></Rule></LifecycleConfiguration>`)
// XML present but flag off → nil resolver (worker drives expiration).
cfg := &BucketConfig{Name: "bk", Entry: &filer_pb.Entry{Extended: map[string][]byte{
bucketLifecycleConfigurationXMLKey: xml,
}}}
s.populateBucketConfigDerivedFields(cfg)
if cfg.LifecycleTTL != nil {
t.Fatalf("fast path off must yield nil resolver, got %v", cfg.LifecycleTTL)
}
// Flag on → resolver applies the rule.
cfg.Entry.Extended[s3_constants.ExtLifecycleTtlFastPathKey] = []byte("true")
s.populateBucketConfigDerivedFields(cfg)
if got := cfg.LifecycleTTL.Resolve("logs/foo", 1); got != 7*86400 {
t.Fatalf("fast path on, want 7d, got %d", got)
}
}
-10
View File
@@ -786,16 +786,6 @@ func TestValidateDefaultRetention(t *testing.T) {
expectError: true,
errorMsg: "default retention must specify either Days or Years",
},
{
name: "Zero years",
retention: &DefaultRetention{
Mode: "GOVERNANCE",
Years: 0,
YearsSet: true,
},
expectError: true,
errorMsg: "invalid retention period specified",
},
}
for _, tt := range tests {
+33 -143
View File
@@ -257,56 +257,6 @@ func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, error
return versionId, nil
}
// createNullDeleteMarker records a suspended-versioning delete as a single "null"
// delete marker. Unlike createDeleteMarker (enabled versioning, where each delete is
// a distinct historical marker), a suspended delete overwrites the null version per
// the S3 spec, so this reuses the "null" version id and its fixed file name (v_null):
// repeated suspended deletes collapse onto one marker instead of accumulating, and a
// later suspended PUT removes it via putSuspendedVersioningObject's null-version
// cleanup. The latest-version pointer is set explicitly (not recomputed) because
// "null" does not sort as the newest version id.
func (s3a *S3ApiServer) createNullDeleteMarker(bucket, object string) error {
cleanObject := strings.TrimPrefix(object, "/")
bucketDir := s3a.bucketDir(bucket)
versionsDir := bucketDir + "/" + cleanObject + s3_constants.VersionsFolder
versionFileName := s3a.getVersionFileName("null")
mtime := time.Now().Unix()
markerExtended := map[string][]byte{
s3_constants.ExtVersionIdKey: []byte("null"),
s3_constants.ExtDeleteMarkerKey: []byte("true"),
}
if err := s3a.mkFile(versionsDir, versionFileName, nil, func(entry *filer_pb.Entry) {
entry.IsDirectory = false
if entry.Attributes == nil {
entry.Attributes = &filer_pb.FuseAttributes{}
}
entry.Attributes.Mtime = mtime
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
for k, v := range markerExtended {
entry.Extended[k] = v
}
}); err != nil {
return fmt.Errorf("failed to create null delete marker in .versions directory: %w", err)
}
markerEntry := &filer_pb.Entry{
Name: versionFileName,
IsDirectory: false,
Attributes: &filer_pb.FuseAttributes{Mtime: mtime},
Extended: markerExtended,
}
if err := s3a.updateLatestVersionInDirectory(bucket, cleanObject, "null", versionFileName, markerEntry); err != nil {
return fmt.Errorf("failed to point latest at null delete marker for %s/%s: %w", bucket, object, err)
}
glog.V(2).Infof("createNullDeleteMarker: recorded null delete marker for %s/%s", bucket, object)
return nil
}
// versionListItem represents an item in the unified version/prefix list
type versionListItem struct {
key string
@@ -852,11 +802,8 @@ func (vc *versionCollector) collectVersions(currentPath, relativePath string) er
// processDirectory handles directory entries
func (vc *versionCollector) processDirectory(currentPath, entryPath string, entry *filer_pb.Entry) error {
// Handle explicit S3 directory object. Match ListObjectsV2's
// IsDirectoryKeyObject (any non-empty mime), not just FolderMimeType:
// an SDK PutObject of "dir/" carries a default Content-Type, so the two
// listings must agree on what counts as a directory key.
if entry.IsDirectoryKeyObject() {
// Handle explicit S3 directory object
if entry.Attributes.Mime == s3_constants.FolderMimeType {
vc.processExplicitDirectory(entryPath, entry)
}
@@ -1882,35 +1829,6 @@ func selectLatestVersion(entries []*filer_pb.Entry) (latestEntry *filer_pb.Entry
return
}
// scanLatestVersionEntry paginates a .versions/ directory and returns the
// chronologically newest version entry (including delete markers; see
// selectLatestVersion). A single-shot list would miss the true latest when
// old-format (raw timestamp) version ids spill past one page, since filesystem
// order is lexicographic-ascending = oldest-first for that format. latestEntry
// is nil when the directory holds no version entries.
func (s3a *S3ApiServer) scanLatestVersionEntry(versionsDir string) (latestEntry *filer_pb.Entry, latestVersionId, latestVersionFileName string, isDeleteMarker bool, err error) {
startFrom := ""
for {
entries, isLast, listErr := s3a.list(versionsDir, "", startFrom, false, filer.PaginationSize)
if listErr != nil {
return nil, "", "", false, fmt.Errorf("list %s: %w", versionsDir, listErr)
}
if pageEntry, pageId, pageFile, pageDM := selectLatestVersion(entries); pageEntry != nil {
if latestEntry == nil || compareVersionIds(pageId, latestVersionId) < 0 {
latestEntry = pageEntry
latestVersionId = pageId
latestVersionFileName = pageFile
isDeleteMarker = pageDM
}
}
if isLast || len(entries) == 0 {
break
}
startFrom = entries[len(entries)-1].Name
}
return
}
// healStaleLatestVersionPointer is invoked when the .versions directory metadata
// points to a version file that no longer exists. It paginates the directory,
// picks the chronologically newest remaining entry (content version or delete
@@ -1936,9 +1854,30 @@ func (s3a *S3ApiServer) healStaleLatestVersionPointer(bucket, normalizedObject s
// and the caller renders NoSuchKey (with x-amz-delete-marker) from the
// returned entry. Restricting to content versions here would "undelete"
// the object by promoting an older content version over a newer marker.
latestEntry, latestVersionId, latestVersionFileName, isDeleteMarker, scanErr := s3a.scanLatestVersionEntry(versionsDir)
if scanErr != nil {
return nil, scanErr
var (
latestEntry *filer_pb.Entry
latestVersionId string
latestVersionFileName string
isDeleteMarker bool
startFrom string
)
for {
entries, isLast, err := s3a.list(versionsDir, "", startFrom, false, filer.PaginationSize)
if err != nil {
return nil, fmt.Errorf("list %s: %w", versionsDir, err)
}
if pageEntry, pageId, pageFile, pageDM := selectLatestVersion(entries); pageEntry != nil {
if latestEntry == nil || compareVersionIds(pageId, latestVersionId) < 0 {
latestEntry = pageEntry
latestVersionId = pageId
latestVersionFileName = pageFile
isDeleteMarker = pageDM
}
}
if isLast || len(entries) == 0 {
break
}
startFrom = entries[len(entries)-1].Name
}
if latestEntry == nil {
@@ -1993,15 +1932,14 @@ func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object s
normalizedObject := s3_constants.NormalizeObjectKey(object)
// The latest-version pointer is normally cached on the .versions directory
// entry, giving a single-scan listing. In a multi-filer deployment the pointer
// is written on the key's owner filer and may be absent on the filer serving
// this list, so recover by rescanning .versions/ rather than dropping the
// object from the listing entirely (the version files themselves replicate
// here). Indexing a nil Extended map is safe and yields !ok.
// Check if the directory entry has latest version metadata
if versionsDirEntry.Extended == nil {
return nil, fmt.Errorf("no Extended metadata in .versions directory entry")
}
latestVersionIdBytes, hasLatestVersionId := versionsDirEntry.Extended[s3_constants.ExtLatestVersionIdKey]
if !hasLatestVersionId {
return s3a.recoverLatestListEntryByScan(bucket, normalizedObject)
return nil, fmt.Errorf("missing latest version ID metadata in .versions directory entry")
}
// Check if this is a delete marker (should not be shown in regular list)
@@ -2060,7 +1998,7 @@ func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object s
// Fallback: fetch version file if cached metadata not available (for older versions)
latestVersionFileBytes, hasLatestVersionFile := versionsDirEntry.Extended[s3_constants.ExtLatestVersionFileNameKey]
if !hasLatestVersionFile {
return s3a.recoverLatestListEntryByScan(bucket, normalizedObject)
return nil, fmt.Errorf("missing latest version file name metadata in .versions directory entry")
}
latestVersionFile := string(latestVersionFileBytes)
@@ -2093,54 +2031,6 @@ func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object s
return logicalEntry, nil
}
// recoverLatestListEntryByScan rebuilds an object's current-version list entry by
// rescanning .versions/ when the cached latest-version pointer is missing on the
// filer serving the list. This is the listing-path counterpart to the read path's
// recoverLatestVersionWithoutPointer, and the cure for a multi-filer undercount:
// the pointer is written on the key's owner filer and may not be present on the
// serving filer, but the version files themselves replicate, so a local rescan
// resolves the current version. It is read-only on purpose — a single list can
// touch many objects, so it does not persist a pointer (which would amplify into
// a write per diverged object); convergence is handled on the write/replication
// side. Returns ErrDeleteMarker when the current version is a delete marker
// (excluded from a regular listing) and filer_pb.ErrNotFound when nothing remains.
func (s3a *S3ApiServer) recoverLatestListEntryByScan(bucket, normalizedObject string) (*filer_pb.Entry, error) {
bucketDir := s3a.bucketDir(bucket)
versionsDir := bucketDir + "/" + normalizedObject + s3_constants.VersionsFolder
latestEntry, latestVersionId, _, isDeleteMarker, err := s3a.scanLatestVersionEntry(versionsDir)
if err != nil {
return nil, err
}
if latestEntry == nil {
// No version files remain. A pre-versioning / suspended "null" object at the
// base path is the current version if one exists.
if regularEntry, regularErr := s3a.getEntry(bucketDir, normalizedObject); regularErr == nil {
return regularEntry, nil
}
return nil, fmt.Errorf("%w: no current version for %s/%s", filer_pb.ErrNotFound, bucket, normalizedObject)
}
if isDeleteMarker {
return nil, ErrDeleteMarker
}
// Present the version file as a logical entry at the object's base path,
// matching the cached fast path's output shape. Copy Extended rather than
// share the scanned entry's map, since we stamp the version id onto it.
extended := make(map[string][]byte, len(latestEntry.Extended)+1)
for k, v := range latestEntry.Extended {
extended[k] = v
}
extended[s3_constants.ExtVersionIdKey] = []byte(latestVersionId)
return &filer_pb.Entry{
Name: path.Base(normalizedObject),
IsDirectory: false,
Attributes: latestEntry.Attributes,
Extended: extended,
Chunks: latestEntry.Chunks,
}, nil
}
// getObjectOwnerFromVersion extracts object owner information from version metadata
func (s3a *S3ApiServer) getObjectOwnerFromVersion(version *ObjectVersion, bucket, objectKey string) CanonicalUser {
// First try to get owner from the version's OwnerID field (extracted during listing)
+1 -1
View File
@@ -173,7 +173,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
if clientHost == "0.0.0.0" || clientHost == "" {
clientHost = util.DetectedHostAddress()
}
masterClient = wdclient.NewMasterClient(option.GrpcDialOption, option.FilerGroup, cluster.S3Type, pb.ServerAddress(util.JoinHostPort(clientHost, option.GrpcPort)), option.DataCenter, "", *pb.NewServiceDiscoveryFromMap(masterMap))
masterClient = wdclient.NewMasterClient(option.GrpcDialOption, option.FilerGroup, cluster.S3Type, pb.ServerAddress(util.JoinHostPort(clientHost, option.GrpcPort)), "", "", *pb.NewServiceDiscoveryFromMap(masterMap))
// Build the object-write lock client and subscribe to the master's
// lock-ring updates BEFORE starting the master loop, so the initial
// LockRingUpdate sent on connect isn't dropped (the master only delivers
+4 -26
View File
@@ -425,7 +425,7 @@ func (fs *FilerServer) applyObjectMutation(ctx context.Context, m *filer_pb.Obje
return nil
case filer_pb.ObjectMutation_RECOMPUTE_LATEST:
return fs.applyRecomputeLatest(ctx, m, fromOtherCluster, signatures)
return fs.applyRecomputeLatest(ctx, m)
default:
return fmt.Errorf("unknown mutation type %v", m.Type)
@@ -439,7 +439,7 @@ func (fs *FilerServer) applyObjectMutation(ctx context.Context, m *filer_pb.Obje
// name_to_key. When the scanned directory is empty the pointer keys are cleared.
// The caller, which knows the versioning scheme, supplies the direction and the
// key mappings. A missing pointer entry is a no-op (idempotent on replay).
func (fs *FilerServer) applyRecomputeLatest(ctx context.Context, m *filer_pb.ObjectMutation, fromOtherCluster bool, signatures []int32) error {
func (fs *FilerServer) applyRecomputeLatest(ctx context.Context, m *filer_pb.ObjectMutation) error {
rc := m.Recompute
if rc == nil {
return fmt.Errorf("RECOMPUTE_LATEST requires recompute parameters")
@@ -452,15 +452,6 @@ func (fs *FilerServer) applyRecomputeLatest(ctx context.Context, m *filer_pb.Obj
if err != nil {
return err
}
// Capture the pre-update image so the metadata notification carries a correct
// diff; pointer.Extended is mutated in place below.
oldPointer := pointer.ShallowClone()
oldPointer.Extended = make(map[string][]byte, len(pointer.Extended))
for k, v := range pointer.Extended {
oldPointer.Extended[k] = v
}
if pointer.Extended == nil {
pointer.Extended = make(map[string][]byte)
}
@@ -521,13 +512,9 @@ func (fs *FilerServer) applyRecomputeLatest(ctx context.Context, m *filer_pb.Obj
}
}
if err := fs.filer.UpdateEntry(ctx, oldPointer, pointer); err != nil {
if err := fs.filer.UpdateEntry(ctx, pointer, pointer); err != nil {
return err
}
// Replicate the recomputed pointer to peer filers and subscribers. Without
// this the latest-version pointer stays in this filer's store only, so other
// filers never learn the current version and ListObjects undercounts.
fs.filer.NotifyUpdateEvent(ctx, oldPointer, pointer, false, fromOtherCluster, signatures)
// Stamp the displaced prior child (e.g. NoncurrentSinceNs for lifecycle).
newName := ""
@@ -542,20 +529,11 @@ func (fs *FilerServer) applyRecomputeLatest(ctx context.Context, m *filer_pb.Obj
if perr != nil {
return perr
}
oldPrior := priorEntry.ShallowClone()
oldPrior.Extended = make(map[string][]byte, len(priorEntry.Extended))
for k, v := range priorEntry.Extended {
oldPrior.Extended[k] = v
}
if priorEntry.Extended == nil {
priorEntry.Extended = make(map[string][]byte)
}
priorEntry.Extended[rc.DemoteKey] = rc.DemoteValue
if err := fs.filer.UpdateEntry(ctx, oldPrior, priorEntry); err != nil {
return err
}
fs.filer.NotifyUpdateEvent(ctx, oldPrior, priorEntry, false, fromOtherCluster, signatures)
return nil
return fs.filer.UpdateEntry(ctx, priorEntry, priorEntry)
}
return nil
@@ -1,140 +0,0 @@
package weed_server
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// RECOMPUTE_LATEST must emit a metadata notification for the pointer it writes.
// Without it the recomputed latest-version pointer lives only in the filer that
// processed the mutation, so peer filers never learn the current version and
// their ListObjects undercount versioned buckets.
func TestRecomputeLatestEmitsPointerUpdateEvent(t *testing.T) {
store := newRenameTestStore()
store.entries["/buckets/b/obj.versions"] = newDirectoryEntry("/buckets/b/obj.versions", 10)
version := newFileEntry("/buckets/b/obj.versions/v_123", 11)
version.Extended = map[string][]byte{"vid": []byte("123")}
store.entries["/buckets/b/obj.versions/v_123"] = version
queue := &captureQueue{}
swapNotificationQueue(t, queue)
server := &FilerServer{filer: newRenameTestFiler(store)}
m := &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_RECOMPUTE_LATEST,
Directory: "/buckets/b",
Name: "obj.versions",
Recompute: &filer_pb.Recompute{
ScanDir: "/buckets/b/obj.versions",
Descending: true,
NameToKey: "latest-file",
CopyExtended: map[string]string{"latest-vid": "vid"},
},
}
if err := server.applyObjectMutation(context.Background(), m, false, nil); err != nil {
t.Fatalf("applyObjectMutation: %v", err)
}
// Pointer is persisted locally.
ptr, err := store.FindEntry(context.Background(), "/buckets/b/obj.versions")
if err != nil {
t.Fatalf("find pointer: %v", err)
}
if got := string(ptr.Extended["latest-vid"]); got != "123" {
t.Fatalf("pointer latest-vid = %q, want 123", got)
}
// ...and it is announced so peers replicate it.
events := queue.snapshot()
if len(events) != 1 {
t.Fatalf("event count = %d, want 1", len(events))
}
e := events[0]
if e.notification.NewEntry == nil || e.notification.NewEntry.Name != "obj.versions" {
t.Fatalf("event new entry = %+v, want obj.versions", e.notification.NewEntry)
}
if got := string(e.notification.NewEntry.Extended["latest-vid"]); got != "123" {
t.Fatalf("event latest-vid = %q, want 123", got)
}
if e.notification.OldEntry != nil && len(e.notification.OldEntry.Extended["latest-vid"]) != 0 {
t.Fatalf("event old entry already had pointer: %+v", e.notification.OldEntry)
}
}
// A pointer flip that demotes the prior latest must announce both the pointer
// update and the demote stamp, so a peer's view of both entries stays correct.
func TestRecomputeLatestDemoteEmitsEvent(t *testing.T) {
store := newRenameTestStore()
pointer := newDirectoryEntry("/buckets/b/obj.versions", 10)
pointer.Extended = map[string][]byte{"latest-file": []byte("v_100"), "latest-vid": []byte("100")}
store.entries["/buckets/b/obj.versions"] = pointer
prior := newFileEntry("/buckets/b/obj.versions/v_100", 11)
prior.Extended = map[string][]byte{"vid": []byte("100")}
store.entries["/buckets/b/obj.versions/v_100"] = prior
latest := newFileEntry("/buckets/b/obj.versions/v_200", 12)
latest.Extended = map[string][]byte{"vid": []byte("200")}
store.entries["/buckets/b/obj.versions/v_200"] = latest
queue := &captureQueue{}
swapNotificationQueue(t, queue)
server := &FilerServer{filer: newRenameTestFiler(store)}
m := &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_RECOMPUTE_LATEST,
Directory: "/buckets/b",
Name: "obj.versions",
Recompute: &filer_pb.Recompute{
ScanDir: "/buckets/b/obj.versions",
Descending: true,
NameToKey: "latest-file",
CopyExtended: map[string]string{"latest-vid": "vid"},
DemoteKey: "noncurrent-since",
DemoteValue: []byte("999"),
},
}
if err := server.applyObjectMutation(context.Background(), m, false, nil); err != nil {
t.Fatalf("applyObjectMutation: %v", err)
}
gotPtr, err := store.FindEntry(context.Background(), "/buckets/b/obj.versions")
if err != nil {
t.Fatalf("find pointer: %v", err)
}
if got := string(gotPtr.Extended["latest-file"]); got != "v_200" {
t.Fatalf("pointer latest-file = %q, want v_200", got)
}
gotPrior, err := store.FindEntry(context.Background(), "/buckets/b/obj.versions/v_100")
if err != nil {
t.Fatalf("find prior: %v", err)
}
if got := string(gotPrior.Extended["noncurrent-since"]); got != "999" {
t.Fatalf("prior noncurrent-since = %q, want 999", got)
}
var sawPointer, sawDemote bool
for _, e := range queue.snapshot() {
if e.notification.NewEntry == nil {
continue
}
switch e.notification.NewEntry.Name {
case "obj.versions":
if string(e.notification.NewEntry.Extended["latest-file"]) == "v_200" {
sawPointer = true
}
case "v_100":
if string(e.notification.NewEntry.Extended["noncurrent-since"]) == "999" {
sawDemote = true
}
}
}
if !sawPointer {
t.Fatalf("missing pointer-flip event: %+v", queue.snapshot())
}
if !sawDemote {
t.Fatalf("missing demote event: %+v", queue.snapshot())
}
}
+17 -6
View File
@@ -3,6 +3,7 @@ package weed_server
import (
"context"
"fmt"
"math"
"math/rand/v2"
"strings"
"sync"
@@ -88,12 +89,22 @@ func (ms *MasterServer) ProcessGrowRequest() {
if err != nil {
glog.V(0).Infof("volume grow request failed: %+v", err)
}
for _, plan := range vl.PlanRackAwareGrowth(dcs, lastGrowCount, volumeGrowStepCount) {
vgr.DataCenter = plan.DataCenter
vgr.Rack = plan.Rack
vgr.WritableVolumeCount = plan.WritableVolumeCount
if _, err = ms.VolumeGrow(ctx, vgr); err != nil {
glog.V(0).Infof("volume grow request for dc:%s rack:%s failed: %+v", plan.DataCenter, plan.Rack, err)
writableVolumes := vl.CloneWritableVolumes()
for dcId, racks := range dcs {
for _, rackId := range racks {
if vl.ShouldGrowVolumesByDcAndRack(&writableVolumes, dcId, rackId) {
vgr.DataCenter = string(dcId)
vgr.Rack = string(rackId)
if lastGrowCount > 0 {
vgr.WritableVolumeCount = uint32(math.Ceil(float64(lastGrowCount) / float64(len(dcs)*len(racks))))
} else {
vgr.WritableVolumeCount = volumeGrowStepCount
}
if _, err = ms.VolumeGrow(ctx, vgr); err != nil {
glog.V(0).Infof("volume grow request for dc:%s rack:%s failed: %+v", dcId, rackId, err)
}
}
}
}
}
+55
View File
@@ -24,6 +24,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/topology"
"github.com/seaweedfs/seaweedfs/weed/util/version"
"google.golang.org/grpc"
)
@@ -31,8 +32,57 @@ const (
ldbFile = "logs.dat"
sdbFile = "stable.dat"
updatePeersTimeout = 15 * time.Minute
// legacyMigrationKey marks, in the hashicorp stable store, that this
// master's hashicorp raft state has already absorbed any pre-existing
// legacy seaweedfs/raft state. Its presence makes the import one-time so
// later restarts never re-read stale legacy state.
legacyMigrationKey = "seaweedfs.legacy.raft.migrated"
)
// migrateLegacyRaftStateIfNeeded performs the one-time legacy -> hashicorp raft
// migration. It first checks the migration marker in the hashicorp stable
// store; if already migrated it does nothing. Otherwise, when a legacy
// seaweedfs/raft state is present, it imports the cluster identity
// (TopologyId) and MaxVolumeId from it, then marks the migration done. With no
// legacy state it just records the marker. Either way the master ends up
// marked migrated, so the import runs at most once per cluster.
func migrateLegacyRaftStateIfNeeded(sdb *boltdb.BoltStore, dataDir string, topo *topology.Topology) {
if _, err := sdb.Get([]byte(legacyMigrationKey)); err == nil {
return // marker present: already migrated
}
if legacyRaftStateExists(dataDir) {
glog.V(0).Infof("first hashicorp-raft start with legacy raft state in %s; migrating", dataDir)
importLegacyRaftState(dataDir, topo)
}
if err := sdb.Set([]byte(legacyMigrationKey), []byte(version.Version())); err != nil {
glog.Warningf("failed to record legacy raft migration marker: %v", err)
}
}
// importLegacyRaftState seeds TopologyId and MaxVolumeId from the latest legacy
// snapshot. TopologyId is the cluster identity and must survive the engine
// switch; MaxVolumeId is otherwise rebuilt from volume heartbeats, but carrying
// it avoids reusing an id whose volume was deleted before the migration.
func importLegacyRaftState(dataDir string, topo *topology.Topology) {
state, ok := readLegacyRaftSnapshotState(dataDir)
if !ok {
glog.V(0).Infof("legacy raft state present but no readable snapshot; " +
"TopologyId/MaxVolumeId will be rebuilt from volume heartbeats")
return
}
var cmd topology.MaxVolumeIdCommand
if err := json.Unmarshal(state, &cmd); err != nil {
glog.Warningf("failed to parse legacy raft snapshot state: %v", err)
return
}
topo.UpAdjustMaxVolumeId(cmd.MaxVolumeId)
if cmd.TopologyId != "" {
topo.SetTopologyId(cmd.TopologyId)
}
glog.V(0).Infof("migrated legacy raft state: MaxVolumeId=%d TopologyId=%s", cmd.MaxVolumeId, cmd.TopologyId)
}
func getPeerIdx(self pb.ServerAddress, mapPeers map[string]pb.ServerAddress) int {
peerIDs := make([]string, 0, len(mapPeers))
seen := make(map[string]struct{}, len(mapPeers))
@@ -212,6 +262,11 @@ func NewHashicorpRaftServer(option *RaftServerOption) (*RaftServer, error) {
return nil, fmt.Errorf("boltdb.NewBoltStore(%q): %v", filepath.Join(baseDir, "stable.dat"), err)
}
// Carry cluster identity forward when upgrading from legacy seaweedfs/raft.
// Runs once, before raft starts, so the seeded TopologyId is in place
// before ensureTopologyId would otherwise generate a fresh one.
migrateLegacyRaftStateIfNeeded(sdb, baseDir, option.Topo)
fss, err := raft.NewFileSnapshotStore(baseDir, 3, os.Stderr)
if err != nil {
return nil, fmt.Errorf("raft.NewFileSnapshotStore(%q, ...): %v", baseDir, err)
+116
View File
@@ -0,0 +1,116 @@
package weed_server
import (
"encoding/json"
"fmt"
"hash/crc32"
"os"
"path"
"path/filepath"
"testing"
boltdb "github.com/hashicorp/raft-boltdb/v2"
"github.com/seaweedfs/seaweedfs/weed/sequence"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/topology"
)
// writeLegacySnapshot writes a seaweedfs/raft (legacy) snapshot carrying the
// given FSM state, in the on-disk format readLegacyRaftSnapshotState expects.
func writeLegacySnapshot(t *testing.T, dataDir string, maxVolumeId needle.VolumeId, topologyId string) {
t.Helper()
snapshotDir := path.Join(dataDir, "snapshot")
if err := os.MkdirAll(snapshotDir, 0755); err != nil {
t.Fatal(err)
}
state, err := json.Marshal(topology.MaxVolumeIdCommand{MaxVolumeId: maxVolumeId, TopologyId: topologyId})
if err != nil {
t.Fatal(err)
}
body, err := json.Marshal(struct {
State json.RawMessage `json:"state"`
}{State: state})
if err != nil {
t.Fatal(err)
}
f, err := os.Create(path.Join(snapshotDir, "0_1.ss"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := fmt.Fprintf(f, "%08x\n", crc32.ChecksumIEEE(body)); err != nil {
t.Fatal(err)
}
if _, err := f.Write(body); err != nil {
t.Fatal(err)
}
}
func openStableStore(t *testing.T, dataDir string) *boltdb.BoltStore {
t.Helper()
sdb, err := boltdb.NewBoltStore(filepath.Join(dataDir, sdbFile))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { sdb.Close() })
return sdb
}
func newTestTopology() *topology.Topology {
return topology.NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5, false)
}
func TestMigrateLegacyRaftState_ImportsIdentityOnce(t *testing.T) {
dir := t.TempDir()
writeLegacySnapshot(t, dir, 4242, "cluster-abc")
sdb := openStableStore(t, dir)
topo := newTestTopology()
migrateLegacyRaftStateIfNeeded(sdb, dir, topo)
if got := topo.GetTopologyId(); got != "cluster-abc" {
t.Fatalf("TopologyId = %q, want cluster-abc", got)
}
if got := topo.GetMaxVolumeId(); got != needle.VolumeId(4242) {
t.Fatalf("MaxVolumeId = %d, want 4242", got)
}
if v, err := sdb.Get([]byte(legacyMigrationKey)); err != nil || len(v) == 0 {
t.Fatalf("migration marker not set: v=%q err=%v", v, err)
}
// Second run on a fresh topology must NOT re-import: the marker gates it.
topo2 := newTestTopology()
migrateLegacyRaftStateIfNeeded(sdb, dir, topo2)
if got := topo2.GetTopologyId(); got != "" {
t.Fatalf("re-import after marker set: TopologyId = %q, want empty", got)
}
}
func TestMigrateLegacyRaftState_NoLegacyJustMarks(t *testing.T) {
dir := t.TempDir()
sdb := openStableStore(t, dir)
topo := newTestTopology()
migrateLegacyRaftStateIfNeeded(sdb, dir, topo)
if got := topo.GetTopologyId(); got != "" {
t.Fatalf("TopologyId = %q, want empty (nothing to import)", got)
}
if v, err := sdb.Get([]byte(legacyMigrationKey)); err != nil || len(v) == 0 {
t.Fatalf("migration marker not set on fresh install: v=%q err=%v", v, err)
}
}
func TestLegacyRaftStateExists(t *testing.T) {
dir := t.TempDir()
if legacyRaftStateExists(dir) {
t.Fatal("empty dir reported as having legacy state")
}
if err := os.WriteFile(path.Join(dir, "log"), []byte("x"), 0644); err != nil {
t.Fatal(err)
}
if !legacyRaftStateExists(dir) {
t.Fatal("legacy log file not detected")
}
}
+30 -10
View File
@@ -249,35 +249,47 @@ func (s *RaftServer) Peers() (members []string) {
return
}
// recoverTopologyIdFromSnapshot reads the TopologyId from the latest
// seaweedfs/raft snapshot before state cleanup.
func recoverTopologyIdFromSnapshot(dataDir string, topo *topology.Topology) {
// legacyRaftStateExists reports whether a seaweedfs/raft (legacy) state is
// present in dataDir. The legacy engine writes these names; hashicorp raft
// uses logs.dat/stable.dat/snapshots, so there is no overlap.
func legacyRaftStateExists(dataDir string) bool {
for _, name := range []string{"snapshot", "log", "conf", "state"} {
if _, err := os.Stat(path.Join(dataDir, name)); err == nil {
return true
}
}
return false
}
// readLegacyRaftSnapshotState returns the raw FSM state JSON from the latest
// seaweedfs/raft (legacy) snapshot, if a valid one exists.
func readLegacyRaftSnapshotState(dataDir string) (json.RawMessage, bool) {
snapshotDir := path.Join(dataDir, "snapshot")
dir, err := os.Open(snapshotDir)
if err != nil {
return
return nil, false
}
defer dir.Close()
filenames, err := dir.Readdirnames(-1)
if err != nil || len(filenames) == 0 {
return
return nil, false
}
sort.Strings(filenames)
file, err := os.Open(path.Join(snapshotDir, filenames[len(filenames)-1]))
if err != nil {
return
return nil, false
}
defer file.Close()
// Snapshot format: 8-hex-digit CRC32 checksum, newline, JSON body.
var checksum uint32
if _, err := fmt.Fscanf(file, "%08x\n", &checksum); err != nil {
return
return nil, false
}
b, err := io.ReadAll(file)
if err != nil || crc32.ChecksumIEEE(b) != checksum {
return
return nil, false
}
// The snapshot JSON wraps the FSM state in a "state" field.
@@ -285,9 +297,17 @@ func recoverTopologyIdFromSnapshot(dataDir string, topo *topology.Topology) {
State json.RawMessage `json:"state"`
}
if err := json.Unmarshal(b, &snap); err != nil || len(snap.State) == 0 {
return
return nil, false
}
return snap.State, true
}
// recoverTopologyIdFromSnapshot reads the TopologyId from the latest
// seaweedfs/raft snapshot before state cleanup.
func recoverTopologyIdFromSnapshot(dataDir string, topo *topology.Topology) {
if state, ok := readLegacyRaftSnapshotState(dataDir); ok {
recoverTopologyIdFromState(state, topo)
}
recoverTopologyIdFromState(snap.State, topo)
}
// HasExistingState returns true when the raft log already contains entries,
-3
View File
@@ -802,9 +802,6 @@ func toBalancerTopology(ecNodes []*EcNode, collections []string, diskType types.
for _, en := range ecNodes {
rackKey := string(en.dc) + ":" + string(en.rack)
node := topo.AddNode(en.info.Id, string(en.dc), rackKey, en.freeEcSlot)
// Group by physical machine (host) so shards spread across machines, not just
// nodes; the id stays the node identity used for moves.
node.SetHost(pb.NewServerAddressFromDataNode(en.info).ToHost())
for diskId, d := range en.disks {
node.AddDisk(diskId, d.diskType, d.freeEcSlots, d.ecShardCount)
}
@@ -1,118 +0,0 @@
package shell
import (
"context"
"flag"
"fmt"
"io"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
)
func init() {
Commands = append(Commands, &commandS3BucketLifecycleFastpath{})
}
type commandS3BucketLifecycleFastpath struct {
}
func (c *commandS3BucketLifecycleFastpath) Name() string {
return "s3.bucket.lifecycle.fastpath"
}
func (c *commandS3BucketLifecycleFastpath) Help() string {
return `view or toggle the per-bucket lifecycle TTL fast path
When enabled, an Expiration.Days lifecycle rule is stamped as a volume
TTL at PutObject time, so the volume server reclaims the data on its own
and the lifecycle worker skips per-chunk deletes. Off by default: a
volume TTL is baked into the object at write time and can't honor a later
policy change (rule removed or lengthened), unlike worker-driven
expiration. The fast path never applies to versioned or object-locked
buckets regardless of this flag.
Example:
# Show the current setting
s3.bucket.lifecycle.fastpath -name <bucket_name>
# Enable
s3.bucket.lifecycle.fastpath -name <bucket_name> -enable
# Disable
s3.bucket.lifecycle.fastpath -name <bucket_name> -disable
`
}
func (c *commandS3BucketLifecycleFastpath) HasTag(CommandTag) bool {
return false
}
func (c *commandS3BucketLifecycleFastpath) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
bucketCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
bucketName := bucketCommand.String("name", "", "bucket name")
enable := bucketCommand.Bool("enable", false, "enable the lifecycle TTL fast path")
disable := bucketCommand.Bool("disable", false, "disable the lifecycle TTL fast path")
if err = bucketCommand.Parse(args); err != nil {
return err
}
if *bucketName == "" {
return fmt.Errorf("empty bucket name")
}
if err := s3bucket.VerifyS3BucketName(*bucketName); err != nil {
return fmt.Errorf("invalid bucket name %q: %w", *bucketName, err)
}
if *enable && *disable {
return fmt.Errorf("only one of -enable or -disable can be set")
}
return commandEnv.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer configuration: %w", err)
}
filerBucketsPath := resp.DirBuckets
lookupResp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
Directory: filerBucketsPath,
Name: *bucketName,
})
if err != nil {
return fmt.Errorf("lookup bucket %s: %w", *bucketName, err)
}
entry := lookupResp.Entry
if !*enable && !*disable {
state := "disabled"
if string(entry.Extended[s3_constants.ExtLifecycleTtlFastPathKey]) == "true" {
state = "enabled"
}
fmt.Fprintf(writer, "Bucket: %s\n", *bucketName)
fmt.Fprintf(writer, "Lifecycle TTL fast path: %s\n", state)
return nil
}
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
state := "disabled"
if *enable {
entry.Extended[s3_constants.ExtLifecycleTtlFastPathKey] = []byte("true")
state = "enabled"
} else {
delete(entry.Extended, s3_constants.ExtLifecycleTtlFastPathKey)
}
if _, err := client.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: filerBucketsPath,
Entry: entry,
}); err != nil {
return fmt.Errorf("failed to update bucket: %w", err)
}
fmt.Fprintf(writer, "Bucket %s lifecycle TTL fast path %s\n", *bucketName, state)
return nil
})
}
-10
View File
@@ -553,16 +553,6 @@ func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*Vol
}
}
// Don't move a replica onto a machine (host) that already holds one of this
// volume's replicas: servers sharing a host are one fault domain, so both would
// die together. Best-effort -- skip and let balancing try the next target.
targetHost := pb.NewServerAddressFromDataNode(targetNode.info).ToHost()
for _, replica := range existingReplicasExceptSourceNode {
if pb.NewServerAddressFromDataNode(replica.location.dataNode).ToHost() == targetHost {
return false
}
}
// target location
targetLocation := location{
dc: targetNode.dc,
-35
View File
@@ -227,41 +227,6 @@ func TestIsGoodMove(t *testing.T) {
targetLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn4"}},
expected: false,
},
{
// rep 001 allows two copies in one rack; replica-placement alone would
// permit this, but the target shares a host with another replica, so the
// machine anti-affinity must reject it.
name: "test 001 reject move onto a machine already holding a replica",
replication: "001",
replicas: []*VolumeReplica{
{
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.1:8080"}},
},
{
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.2:8080"}},
},
},
sourceLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.2:8080"}},
targetLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.1:8081"}},
expected: false,
},
{
name: "test 001 allow move onto a different machine in the rack",
replication: "001",
replicas: []*VolumeReplica{
{
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.1:8080"}},
},
{
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.2:8080"}},
},
},
sourceLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.2:8080"}},
targetLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "10.0.0.3:8080"}},
expected: true,
},
}
for _, tt := range tests {
@@ -32,11 +32,9 @@ type volKey struct {
// Node is a volume server in the snapshot. Fields are set through the builder
// methods; only its identity is read back (via Move).
type Node struct {
id string
host string // physical machine (host/IP); nodes sharing a host are one fault domain
dc string
rack string // composite rack key (e.g. "dc1:rack1")
id string
dc string
rack string // composite rack key (e.g. "dc1:rack1")
freeSlots int
disks map[uint32]*disk
shards map[volKey]*volumeShards
@@ -118,7 +116,6 @@ func NewTopology() *Topology {
func (t *Topology) AddNode(id, dc, rackKey string, freeSlots int) *Node {
n := &Node{
id: id,
host: id, // default: each node is its own machine until SetHost overrides
dc: dc,
rack: rackKey,
freeSlots: freeSlots,
@@ -129,14 +126,6 @@ func (t *Topology) AddNode(id, dc, rackKey string, freeSlots int) *Node {
return n
}
// SetHost sets the physical machine (host/IP) a node runs on; nodes sharing a host
// are one fault domain. Defaults to the node id (one machine per node) if unset.
func (n *Node) SetHost(host string) {
if host != "" {
n.host = host
}
}
// AddDisk registers a physical disk. shardCount is the disk's total EC shard
// count across all volumes (used for disk scoring); freeSlots is the per-disk
// free EC shard slots.
@@ -199,13 +188,11 @@ func Plan(topo *Topology, opts Options) []Move {
}
collections := make([]string, 0, len(byCollection))
dataShardsByCollection := make(map[string]int)
parityShardsByCollection := make(map[string]int)
for c := range byCollection {
collections = append(collections, c)
sort.Slice(byCollection[c], func(i, j int) bool { return byCollection[c][i].vid < byCollection[c][j].vid })
d, p := ratio(c)
d, _ := ratio(c)
dataShardsByCollection[c] = d
parityShardsByCollection[c] = p
}
sort.Strings(collections)
@@ -230,7 +217,7 @@ func Plan(topo *Topology, opts Options) []Move {
}
}
all = append(all, detectGlobalImbalance(nodes, racks, opts.DiskType, opts.ImbalanceThreshold, dataShardsByCollection, parityShardsByCollection, opts.GlobalMaxMovesPerRack, opts.GlobalUtilizationBased)...)
all = append(all, detectGlobalImbalance(nodes, racks, opts.DiskType, opts.ImbalanceThreshold, dataShardsByCollection, opts.GlobalMaxMovesPerRack, opts.GlobalUtilizationBased)...)
out := make([]Move, 0, len(all))
for _, m := range all {
@@ -418,15 +405,10 @@ func balanceShardTypeAcrossRacks(vk volKey, nodes map[string]*Node, racks map[st
}
func pickNodeInRack(r *rack, vk volKey, rp *super_block.ReplicaPlacement) *Node {
return pickBestNodeForVolume(sortedNodeSlice(r.nodes), vk, rp)
}
// pickBestNodeForVolume returns the node with the fewest shards of the volume that
// has a free slot and is under the SameRackCount cap, or nil.
func pickBestNodeForVolume(nodes []*Node, vk volKey, rp *super_block.ReplicaPlacement) *Node {
var best *Node
bestCount := -1
for _, node := range nodes {
for _, id := range sortedNodeKeys(r.nodes) {
node := r.nodes[id]
if node.freeSlots <= 0 {
continue
}
@@ -441,152 +423,43 @@ func pickBestNodeForVolume(nodes []*Node, vk volKey, rp *super_block.ReplicaPlac
return best
}
// detectWithinRackImbalance spreads a volume's shards within each rack, data then
// parity with anti-affinity. It spreads across machines (the fault domain) only when
// the rack has enough that each can stay within EC's parity tolerance; otherwise
// machine spreading buys no durability and would only fight capacity (e.g. cramming
// a 2-server box while a 12-server box sits idle), so it spreads across nodes and
// lets capacity/global balancing decide.
// The imbalance threshold gates only the node fallback (cosmetic load distribution
// that should defer to the global utilization phase). Machine spreading bypasses it:
// the even cap is a durability bound, and a relative-skew gate would skip e.g. a
// 5/4/3 machine layout for a 10+4 volume ((5-3)/4 = 0.5), leaving 5 shards -- past
// parity -- on one machine.
// detectWithinRackImbalance spreads a volume's shards across the nodes of each
// rack, again data then parity with anti-affinity.
func detectWithinRackImbalance(vk volKey, nodes map[string]*Node, racks map[string]*rack, diskType string, threshold float64, dataShards, parityShards int, rp *super_block.ReplicaPlacement) []*move {
var moves []*move
for _, rackID := range sortedKeys(racks) {
r := racks[rackID]
machines := buildMachines(r)
numMachines, numNodes := len(machines), len(r.nodes)
// Feasibility is about this rack's share of the volume (cross-rack spreading
// already moved the rest elsewhere), not the whole volume: a rack holding 7 of
// a 10+4 volume's shards can keep each of 2 machines within parity even though
// all 14 could not.
rackShards := rackVolumeShardCount(r, vk)
if numMachines > 1 && numMachines < numNodes && parityShards > 0 && ceilDivide(rackShards, numMachines) <= parityShards {
moves = append(moves, withinRackMachineSpread(vk, r, machines, diskType, dataShards, rp)...)
} else if numNodes > 1 {
moves = append(moves, withinRackNodeSpread(vk, r, diskType, threshold, dataShards, rp)...)
if len(r.nodes) <= 1 {
continue
}
numNodes := len(r.nodes)
// Gate on per-type spread across the rack's nodes (see cross-rack phase).
gateData, gateParity := shardsByGroup(vk, r.nodes, dataShards, func(n *Node) string { return n.id })
if !typeImbalanced(gateData, numNodes, threshold) && !typeImbalanced(gateParity, numNodes, threshold) {
continue
}
nodeShardCount := countShardsByNode(vk, r.nodes)
dataPerNode, _ := shardsByGroup(vk, r.nodes, dataShards, func(n *Node) string { return n.id })
moves = append(moves, balanceShardTypeAcrossNodes(vk, r, diskType, dataShards,
dataPerNode, nodeShardCount, ceilDivide(sumLens(dataPerNode), numNodes), nil, rp)...)
dataPerNode, parityPerNode := shardsByGroup(vk, r.nodes, dataShards, func(n *Node) string { return n.id })
antiAffinity := make(map[string]bool)
for nodeID, shards := range dataPerNode {
if len(shards) > 0 {
antiAffinity[nodeID] = true
}
}
moves = append(moves, balanceShardTypeAcrossNodes(vk, r, diskType, dataShards,
parityPerNode, nodeShardCount, ceilDivide(sumLens(parityPerNode), numNodes), antiAffinity, rp)...)
}
return moves
}
// withinRackMachineSpread spreads a volume's shards across a rack's machines so no
// machine holds more than ceil(rackShards/numMachines). EC recovers from any loss
// within parity regardless of shard type, so what matters per machine is the
// combined count, not data and parity separately: spreading the two independently
// can stack their remainders onto one machine (ceil(d/M)+ceil(p/M) > ceil(total/M))
// and push it past parity. Data/parity anti-affinity is kept at the disk level by
// pickBestDiskOnNode. With one node per machine this reduces to the node spread.
func withinRackMachineSpread(vk volKey, r *rack, machines map[string][]*Node, diskType string, dataShards int, rp *super_block.ReplicaPlacement) []*move {
machineKeys := sortedKeys(machines)
shardsPerMachine := make(map[string][]int, len(machines))
total := 0
for _, host := range machineKeys {
for _, n := range machines[host] {
if info, ok := n.shards[vk]; ok {
for sid := range info.shardBits.All() {
shardsPerMachine[host] = append(shardsPerMachine[host], int(sid))
}
}
}
sort.Ints(shardsPerMachine[host])
total += len(shardsPerMachine[host])
}
if total == 0 {
return nil
}
// Cap = even share. The move loop below sheds only what exceeds it, so a balanced
// rack is a no-op while any machine over the cap (a parity risk) is always fixed.
maxPerMachine := ceilDivide(total, len(machines))
if maxPerMachine < 1 {
maxPerMachine = 1
}
type pending struct {
shardID int
src *Node
}
var toMove []pending
for _, host := range machineKeys {
shards := shardsPerMachine[host]
for i := 0; i < len(shards)-maxPerMachine; i++ {
if src := nodeHoldingShard(machines[host], vk, shards[i]); src != nil {
toMove = append(toMove, pending{shards[i], src})
}
}
}
var moves []*move
for _, pm := range toMove {
// A machine is a viable target only if a node on it can actually take the
// shard (free slot, under SameRackCount), so a capped machine is skipped
// rather than settled on and the move dropped.
destHost, ok := pickTarget(machineKeys, shardsPerMachine, maxPerMachine, nil,
func(h string) bool { return h != pm.src.host && pickBestNodeForVolume(machines[h], vk, rp) != nil },
func(string) bool { return true })
if !ok {
continue
}
destNode := pickBestNodeForVolume(machines[destHost], vk, rp)
if destNode == nil {
continue
}
destDisk := pickBestDiskOnNode(destNode, vk, diskType, pm.shardID, dataShards)
moves = append(moves, &move{
volumeID: vk.vid,
shardID: pm.shardID,
collection: vk.collection,
source: pm.src,
sourceDisk: shardDiskID(pm.src, vk, pm.shardID),
target: destNode,
targetDisk: destDisk,
phase: "within_rack",
})
releaseShard(pm.src, vk, pm.shardID)
reserveShard(destNode, vk, pm.shardID, destDisk)
shardsPerMachine[destHost] = append(shardsPerMachine[destHost], pm.shardID)
shardsPerMachine[pm.src.host] = removeInt(shardsPerMachine[pm.src.host], pm.shardID)
pm.src.freeSlots++
destNode.freeSlots--
}
return moves
}
// withinRackNodeSpread spreads a volume's shards evenly across a rack's nodes (data
// then parity, parity anti-affine to data-bearing nodes). This fallback runs when
// machine fault tolerance is unachievable, so it is cosmetic load distribution:
// honor the imbalance threshold and defer to the global utilization phase rather than
// churning a count-balancing move that can worsen utilization (machine spreading,
// which is durability, bypasses the threshold instead).
func withinRackNodeSpread(vk volKey, r *rack, diskType string, threshold float64, dataShards int, rp *super_block.ReplicaPlacement) []*move {
numNodes := len(r.nodes)
gateData, gateParity := shardsByGroup(vk, r.nodes, dataShards, func(n *Node) string { return n.id })
if !typeImbalanced(gateData, numNodes, threshold) && !typeImbalanced(gateParity, numNodes, threshold) {
return nil
}
nodeShardCount := countShardsByNode(vk, r.nodes)
dataPerNode, _ := shardsByGroup(vk, r.nodes, dataShards, func(n *Node) string { return n.id })
moves := balanceShardTypeAcrossNodes(vk, r, diskType, dataShards,
dataPerNode, nodeShardCount, ceilDivide(sumLens(dataPerNode), numNodes), nil, rp)
dataPerNode, parityPerNode := shardsByGroup(vk, r.nodes, dataShards, func(n *Node) string { return n.id })
antiAffinity := make(map[string]bool)
for nodeID, shards := range dataPerNode {
if len(shards) > 0 {
antiAffinity[nodeID] = true
}
}
return append(moves, balanceShardTypeAcrossNodes(vk, r, diskType, dataShards,
parityPerNode, nodeShardCount, ceilDivide(sumLens(parityPerNode), numNodes), antiAffinity, rp)...)
}
// balanceShardTypeAcrossNodes spreads one shard type of a volume across a rack's
// nodes, moving from nodes over maxPerNode to under-loaded ones.
func balanceShardTypeAcrossNodes(vk volKey, r *rack, diskType string, dataShards int, shardsPerNode map[string][]int, nodeShardCount map[string]int, maxPerNode int, antiAffinity map[string]bool, rp *super_block.ReplicaPlacement) []*move {
if maxPerNode < 1 {
maxPerNode = 1
@@ -650,7 +523,7 @@ func balanceShardTypeAcrossNodes(vk volKey, r *rack, diskType string, dataShards
// detectGlobalImbalance balances total EC shard load across the nodes of each
// rack (across all volumes), using utilization ratios so heterogeneous-capacity
// nodes are compared fairly.
func detectGlobalImbalance(nodes map[string]*Node, racks map[string]*rack, diskType string, threshold float64, dataShardsByCollection, parityShardsByCollection map[string]int, maxMovesPerRack int, byUtilization bool) []*move {
func detectGlobalImbalance(nodes map[string]*Node, racks map[string]*rack, diskType string, threshold float64, dataShardsByCollection map[string]int, maxMovesPerRack int, byUtilization bool) []*move {
var moves []*move
for _, rackID := range sortedKeys(racks) {
@@ -658,7 +531,6 @@ func detectGlobalImbalance(nodes map[string]*Node, racks map[string]*rack, diskT
if len(r.nodes) <= 1 {
continue
}
rackMachineCount := len(buildMachines(r))
nodeShardCounts := make(map[string]int)
totalShards := 0
@@ -730,8 +602,9 @@ func detectGlobalImbalance(nodes map[string]*Node, racks map[string]*rack, diskT
break
}
// Prefer a volume absent from the destination's machine (pass 0) before
// adding to one already there (pass 1), to keep volumes spread.
// Prefer moving a shard of a volume the destination does not hold at
// all (pass 0) before adding another shard of an already-present volume
// (pass 1), to keep each volume's shards spread across nodes.
moved := false
for pass := 0; pass < 2 && !moved; pass++ {
for _, vk := range sortedVolumeKeys(maxNode.shards) {
@@ -740,26 +613,12 @@ func detectGlobalImbalance(nodes map[string]*Node, racks map[string]*rack, diskT
}
info := maxNode.shards[vk]
minInfo := minNode.shards[vk]
volumeOnMinMachine := machineHoldsVolume(r, minNode.host, vk)
if pass == 0 && volumeOnMinMachine {
continue // pass 0: only volumes absent from the destination machine
volumeOnMin := minInfo != nil && minInfo.shardBits != 0
if pass == 0 && volumeOnMin {
continue // pass 0: only volumes absent from the destination
}
if pass == 1 {
if !volumeOnMinMachine {
continue
}
// Protect the volume's machine spread only where it's achievable
// (enough machines for this rack's shards to each stay within
// parity); there a cross-machine load move is allowed only if it
// doesn't raise the destination machine's count past the source's.
// Where it isn't achievable, capacity rules and any leveling move
// is fine. Feasibility uses the rack's shards, not the whole volume.
parity := parityShardsByCollection[vk.collection]
spreadFeasible := parity > 0 && rackMachineCount >= ceilDivide(rackVolumeShardCount(r, vk), parity)
if spreadFeasible && minNode.host != maxNode.host &&
machineVolumeCount(r, minNode.host, vk) >= machineVolumeCount(r, maxNode.host, vk) {
continue
}
if pass == 1 && !volumeOnMin {
continue // pass 1: only volumes already on the destination
}
// Walk the volume's actual shard bitmap so custom ratios with more
// than the standard total (ids 14..MaxShardCount-1) are candidates too.
@@ -1034,19 +893,12 @@ func volumeShardCount(node *Node, vk volKey) int {
}
func nodeInRackHoldingShard(nodes map[string]*Node, rackID string, vk volKey, shardID int) *Node {
var inRack []*Node
for _, id := range sortedNodeKeys(nodes) {
if nodes[id].rack == rackID {
inRack = append(inRack, nodes[id])
}
}
return nodeHoldingShard(inRack, vk, shardID)
}
// nodeHoldingShard returns the first node holding the given shard of the volume, or nil.
func nodeHoldingShard(nodes []*Node, vk volKey, shardID int) *Node {
sid := erasure_coding.ShardId(shardID)
for _, node := range nodes {
for _, id := range sortedNodeKeys(nodes) {
node := nodes[id]
if node.rack != rackID {
continue
}
if info, ok := node.shards[vk]; ok && info.shardBits.Has(sid) {
return node
}
@@ -1054,52 +906,6 @@ func nodeHoldingShard(nodes []*Node, vk volKey, shardID int) *Node {
return nil
}
// buildMachines groups a rack's nodes by host, each slice sorted by node id.
func buildMachines(r *rack) map[string][]*Node {
machines := make(map[string][]*Node)
for _, n := range sortedNodeSlice(r.nodes) {
machines[n.host] = append(machines[n.host], n)
}
return machines
}
// rackVolumeShardCount returns how many of the volume's shards the whole rack holds.
func rackVolumeShardCount(r *rack, vk volKey) int {
count := 0
for _, n := range r.nodes {
count += volumeShardCount(n, vk)
}
return count
}
// machineVolumeCount returns how many of the volume's shards the machine (host) holds.
func machineVolumeCount(r *rack, host string, vk volKey) int {
count := 0
for _, n := range r.nodes {
if n.host != host {
continue
}
if info, ok := n.shards[vk]; ok {
count += info.shardBits.Count()
}
}
return count
}
// machineHoldsVolume reports whether any node on the machine holds a shard of the volume.
func machineHoldsVolume(r *rack, host string, vk volKey) bool {
return machineVolumeCount(r, host, vk) > 0
}
func sortedNodeSlice(nodes map[string]*Node) []*Node {
ids := sortedNodeKeys(nodes)
out := make([]*Node, 0, len(ids))
for _, id := range ids {
out = append(out, nodes[id])
}
return out
}
func countShardsByRack(vk volKey, nodes map[string]*Node) map[string]int {
m := make(map[string]int)
for _, node := range nodes {
@@ -1110,25 +916,6 @@ func countShardsByRack(vk volKey, nodes map[string]*Node) map[string]int {
return m
}
func countShardsByHost(vk volKey, nodes map[string]*Node) map[string]int {
m := make(map[string]int)
for _, node := range nodes {
if info, ok := node.shards[vk]; ok {
m[node.host] += info.shardBits.Count()
}
}
return m
}
// freeSlotsByHost sums each machine's free EC shard slots.
func freeSlotsByHost(nodes map[string]*Node) map[string]int {
m := make(map[string]int)
for _, node := range nodes {
m[node.host] += node.freeSlots
}
return m
}
func countShardsByNode(vk volKey, nodes map[string]*Node) map[string]int {
m := make(map[string]int)
for id, node := range nodes {
@@ -260,87 +260,6 @@ func allBits(n int) erasure_coding.ShardBits {
return b
}
// TestPlanConvergesToBalancedLoadOverRounds starts skewed -- machine 10.0.0.1 holds
// 4 shards of every volume, the others 2 -- and runs repeated worker-style balance
// passes (capped moves per pass). It must converge to an even per-machine shard load.
func TestPlanConvergesToBalancedLoadOverRounds(t *testing.T) {
topo := NewTopology()
hosts := []string{"10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.4", "10.0.0.5", "10.0.0.6"}
for _, h := range hosts {
for _, p := range []string{":8080", ":8081"} {
n := topo.AddNode(h+p, "dc1", "dc1:rack1", 4000)
n.SetHost(h)
n.AddDisk(0, "", 4000, 0)
}
}
add := func(id string, vid uint32, ids ...int) {
n := topo.nodes[id]
n.AddShards(vid, "c1", 0, bits(ids...))
n.disks[0].shardCount += len(ids)
n.disks[0].freeSlots -= len(ids)
n.freeSlots -= len(ids)
}
const volumes = 60
for v := 0; v < volumes; v++ {
vid := uint32(v)
add("10.0.0.1:8080", vid, 0, 1) // machine 10.0.0.1 gets 4 shards/volume
add("10.0.0.1:8081", vid, 2, 3)
add("10.0.0.2:8080", vid, 4)
add("10.0.0.2:8081", vid, 5)
add("10.0.0.3:8080", vid, 6)
add("10.0.0.3:8081", vid, 7)
add("10.0.0.4:8080", vid, 8)
add("10.0.0.4:8081", vid, 9)
add("10.0.0.5:8080", vid, 10)
add("10.0.0.5:8081", vid, 11)
add("10.0.0.6:8080", vid, 12)
add("10.0.0.6:8081", vid, 13)
}
perMachine := func() map[string]int {
m := map[string]int{}
for _, h := range hosts {
m[h] = 0 // seed every host so a fully drained one still counts
}
for _, n := range topo.nodes {
for _, info := range n.shards {
m[n.host] += info.shardBits.Count()
}
}
return m
}
opts := Options{Ratio: ratio(10, 4), GlobalUtilizationBased: true, GlobalMaxMovesPerRack: 8}
rounds, converged := 0, false
for ; rounds < 200; rounds++ {
if len(Plan(topo, opts)) == 0 {
converged = true
break
}
}
if !converged {
t.Fatalf("balance did not converge within %d rounds", rounds)
}
pm := perMachine()
min, max := 1<<30, 0
for _, c := range pm {
if c < min {
min = c
}
if c > max {
max = c
}
}
t.Logf("converged after %d rounds: %v", rounds, pm)
if rounds < 2 {
t.Errorf("expected convergence to take multiple rounds (capped moves), took %d", rounds)
}
if float64(max) > 1.1*float64(min) {
t.Errorf("did not converge to balanced load: min=%d max=%d %v", min, max, pm)
}
}
func TestGlobalImbalanceMovesFromFullToEmpty(t *testing.T) {
topo := NewTopology()
n1 := topo.AddNode("node1", "dc1", "dc1:rack1", 5)
@@ -349,7 +268,7 @@ func TestGlobalImbalanceMovesFromFullToEmpty(t *testing.T) {
n2 := topo.AddNode("node2", "dc1", "dc1:rack1", 30)
n2.AddShards(300, "col1", 0, allBits(2))
moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, nil, 0, true)
moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, 0, true)
if len(moves) == 0 {
t.Fatal("expected global balance moves")
}
@@ -369,7 +288,7 @@ func TestGlobalImbalanceHeterogeneousCapacity(t *testing.T) {
n2 := topo.AddNode("node2", "dc1", "dc1:rack1", 2)
n2.AddShards(200, "col1", 0, allBits(3))
moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, nil, 0, true)
moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, 0, true)
if len(moves) == 0 {
t.Fatal("expected moves from high-util node2 to low-util node1")
}
@@ -393,7 +312,7 @@ func TestGlobalImbalanceSkipsFullNodes(t *testing.T) {
n2 := topo.AddNode("node2", "dc1", "dc1:rack1", 0) // full, cannot receive
n2.AddShards(200, "col1", 0, allBits(2))
if moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, nil, 0, true); len(moves) != 0 {
if moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, 0, true); len(moves) != 0 {
t.Fatalf("expected 0 moves (node2 full), got %d", len(moves))
}
}
@@ -442,7 +361,7 @@ func TestGlobalPrefersVolumeAbsentFromDestination(t *testing.T) {
n2 := topo.AddNode("node2", "dc1", "dc1:rack1", 3)
n2.AddShards(100, "col1", 0, bits(2))
moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, nil, 0, true)
moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, 0, true)
if len(moves) == 0 {
t.Fatal("expected a global move from the full node")
}
@@ -510,300 +429,3 @@ func TestDedupFreesCapacityForLaterPhases(t *testing.T) {
t.Error("slot freed by dedup on node2 was not usable by a later phase")
}
}
// TestWithinRackSpreadsAcrossMachines: a 10+4 volume's 14 shards all sit on boxA
// (two of its servers), with three other machines free. Four machines is enough for
// the spread to stay within parity, so the within-rack phase must move shards out
// until no machine holds more than ceil(14/4)=4, even though they looked spread
// across boxA's two nodes.
func TestWithinRackSpreadsAcrossMachines(t *testing.T) {
topo := NewTopology()
mk := func(id, host string) *Node {
n := topo.AddNode(id, "dc1", "dc1:rack1", 100)
n.SetHost(host)
n.AddDisk(0, "", 100, 0)
return n
}
a1 := mk("a1", "boxA")
a2 := mk("a2", "boxA")
mk("b1", "boxB")
mk("c1", "boxC")
mk("d1", "boxD")
a1.AddShards(100, "col1", 0, bits(0, 1, 2, 3, 4, 5, 6)) // 7 shards on boxA
a2.AddShards(100, "col1", 0, bits(7, 8, 9, 10, 11, 12, 13)) // 7 shards on boxA (all 14)
detectWithinRackImbalance(volKey{"col1", 100}, topo.nodes, buildRacks(topo.nodes), "", 0, 10, 4, nil)
perHost := map[string]int{}
for _, n := range topo.nodes {
if info, ok := n.shards[volKey{"col1", 100}]; ok {
perHost[n.host] += info.shardBits.Count()
}
}
if len(perHost) < 3 {
t.Fatalf("shards not spread across machines: %v", perHost)
}
for h, c := range perHost {
if c > 4 {
t.Errorf("machine %s holds %d shards, want <=4 (ceil(14/4), within parity)", h, c)
}
}
}
// TestWithinRackMachineSpreadBalancesCombinedOccupancy: a 5+5 volume on two machines
// where each shard type is already within its own per-type cap (boxA 3 data + 3
// parity = 6, boxB 2 data + 2 parity = 4). Spreading data and parity independently
// would leave boxA at 6, past parity; balancing the combined count must move one
// shard to reach 5/5 so a machine loss stays recoverable.
func TestWithinRackMachineSpreadBalancesCombinedOccupancy(t *testing.T) {
topo := NewTopology()
mk := func(id, host string) *Node {
n := topo.AddNode(id, "dc1", "dc1:rack1", 100)
n.SetHost(host)
n.AddDisk(0, "", 100, 0)
return n
}
a1 := mk("a1", "boxA")
a2 := mk("a2", "boxA") // two nodes on boxA -> numMachines(2) < numNodes(3)
b1 := mk("b1", "boxB")
a1.AddShards(100, "col1", 0, bits(0, 1, 2)) // 3 data
a2.AddShards(100, "col1", 0, bits(5, 6, 7)) // 3 parity (ids >= 5)
b1.AddShards(100, "col1", 0, bits(3, 4, 8, 9)) // 2 data + 2 parity
// dataShards=5, parityShards=5: feasibility ceil(10/2)=5 <= 5, so machine spread runs.
detectWithinRackImbalance(volKey{"col1", 100}, topo.nodes, buildRacks(topo.nodes), "", 0, 5, 5, nil)
perHost := map[string]int{}
for _, n := range topo.nodes {
if info, ok := n.shards[volKey{"col1", 100}]; ok {
perHost[n.host] += info.shardBits.Count()
}
}
if perHost["boxA"] > 5 {
t.Errorf("boxA holds %d shards, want <=5 (parity); data and parity spread independently", perHost["boxA"])
}
}
// TestWithinRackMachineSpreadActsOnExactlyHalfSkew: a 5/4/3 machine layout for a 10+4
// volume is only 50% skewed ((5-3)/4 = 0.5), which a 0.5 relative-imbalance threshold
// would skip -- but the 5-shard machine is already past parity. The spread must act
// regardless (the even cap, not a skew threshold, is the bound) and bring every
// machine to <=ceil(12/3)=4.
func TestWithinRackMachineSpreadActsOnExactlyHalfSkew(t *testing.T) {
topo := NewTopology()
mk := func(id, host string) *Node {
n := topo.AddNode(id, "dc1", "dc1:rack1", 100)
n.SetHost(host)
n.AddDisk(0, "", 100, 0)
return n
}
a1 := mk("a1", "boxA")
a2 := mk("a2", "boxA")
b1 := mk("b1", "boxB")
b2 := mk("b2", "boxB")
c1 := mk("c1", "boxC")
c2 := mk("c2", "boxC")
a1.AddShards(100, "col1", 0, bits(0, 1, 2))
a2.AddShards(100, "col1", 0, bits(3, 4)) // boxA = 5
b1.AddShards(100, "col1", 0, bits(5, 6))
b2.AddShards(100, "col1", 0, bits(7, 8)) // boxB = 4
c1.AddShards(100, "col1", 0, bits(9, 10))
c2.AddShards(100, "col1", 0, bits(11)) // boxC = 3
detectWithinRackImbalance(volKey{"col1", 100}, topo.nodes, buildRacks(topo.nodes), "", 0, 10, 4, nil)
perHost := map[string]int{}
for _, n := range topo.nodes {
if info, ok := n.shards[volKey{"col1", 100}]; ok {
perHost[n.host] += info.shardBits.Count()
}
}
for h, c := range perHost {
if c > 4 {
t.Errorf("machine %s holds %d shards, want <=4 (ceil(12/3)); a 50%% skew was skipped", h, c)
}
}
}
// TestWithinRackSpreadUsesRackLocalShardCount: a rack holds only 7 shards of a 10+4
// volume (cross-rack spreading moved the rest to other racks). Two machines can hold
// those 7 within parity (ceil(7/2)=4), so machine spread must apply -- gating on the
// full 14-shard total would wrongly fall back to node spread and pile 6 onto boxA's
// two nodes, exceeding parity.
func TestWithinRackSpreadUsesRackLocalShardCount(t *testing.T) {
topo := NewTopology()
mk := func(id, host string) *Node {
n := topo.AddNode(id, "dc1", "dc1:rack1", 100)
n.SetHost(host)
n.AddDisk(0, "", 100, 0)
return n
}
a1 := mk("a1", "boxA")
a2 := mk("a2", "boxA")
mk("b1", "boxB")
a1.AddShards(100, "col1", 0, bits(0, 1, 2, 3))
a2.AddShards(100, "col1", 0, bits(4, 5, 6)) // boxA holds all 7 of this rack's shards
detectWithinRackImbalance(volKey{"col1", 100}, topo.nodes, buildRacks(topo.nodes), "", 0, 10, 4, nil)
perHost := map[string]int{}
for _, n := range topo.nodes {
if info, ok := n.shards[volKey{"col1", 100}]; ok {
perHost[n.host] += info.shardBits.Count()
}
}
if perHost["boxA"] > 4 {
t.Errorf("boxA holds %d shards, want <=4 (parity); rack-local feasibility not used", perHost["boxA"])
}
if perHost["boxB"] == 0 {
t.Error("no shards moved to boxB; machine spread did not apply")
}
}
// TestWithinRackNodeFallbackHonorsThreshold: one server per host with a 6/4 data
// split is the cosmetic node fallback (a 2-node rack can't be machine-fault-tolerant
// for a 10+4 volume). At 40% skew it's below the 0.5 threshold, so it must be left to
// the global utilization phase rather than churned -- a count move here can worsen
// utilization on unequal-capacity nodes.
func TestWithinRackNodeFallbackHonorsThreshold(t *testing.T) {
topo := NewTopology()
mk := func(id string) *Node {
n := topo.AddNode(id, "dc1", "dc1:rack1", 100)
n.AddDisk(0, "", 100, 0)
return n
}
n1 := mk("n1") // distinct hosts (default host = id) -> node fallback
n2 := mk("n2")
n1.AddShards(100, "col1", 0, bits(0, 1, 2, 3, 4, 5)) // 6 data
n2.AddShards(100, "col1", 0, bits(6, 7, 8, 9)) // 4 data
moves := detectWithinRackImbalance(volKey{"col1", 100}, topo.nodes, buildRacks(topo.nodes), "", 0.5, 10, 4, nil)
if len(moves) != 0 {
t.Errorf("node fallback moved %d shards on a 40%%-skewed 6/4 layout at threshold 0.5; want 0", len(moves))
}
}
// TestWithinRackSpreadDefaultsToNodes: with no SetHost each node is its own
// machine, so the within-rack phase still spreads a volume off an overloaded node
// exactly as before (machine grouping reduces to node grouping).
func TestWithinRackSpreadDefaultsToNodes(t *testing.T) {
topo := NewTopology()
mk := func(id string) *Node {
n := topo.AddNode(id, "dc1", "dc1:rack1", 100)
n.AddDisk(0, "", 100, 0)
return n
}
n1 := mk("n1")
mk("n2")
mk("n3")
n1.AddShards(100, "col1", 0, allBits(14)) // all 14 piled on one node
detectWithinRackImbalance(volKey{"col1", 100}, topo.nodes, buildRacks(topo.nodes), "", 0, 10, 4, nil)
perNode := map[string]int{}
for id, n := range topo.nodes {
if info, ok := n.shards[volKey{"col1", 100}]; ok {
perNode[id] = info.shardBits.Count()
}
}
if perNode["n1"] == 14 {
t.Fatal("no within-rack spread happened with one server per host")
}
if len(perNode) < 3 {
t.Errorf("shards not spread across all three nodes: %v", perNode)
}
// Per-type even caps: ceil(10/3) data + ceil(4/3) parity = 4+2 per node.
for id, c := range perNode {
if c > 6 {
t.Errorf("node %s holds %d shards, want <=6 (dataCap+parityCap)", id, c)
}
}
}
// TestGlobalDoesNotConcentrateVolumeAcrossMachines: when the volume's machine spread
// is achievable (here 2 machines, a 2+2 volume, one machine can hold <= parity), a
// load move must not raise a machine's shard count of the volume past the source's.
// boxA's only volume is also on boxB, so pass 0 finds nothing and the sole pass-1
// option is the cross-machine boxA->boxB move, which must be rejected (boxB already
// holds as many shards as boxA). Same-machine node rebalancing would still be fine.
func TestGlobalDoesNotConcentrateVolumeAcrossMachines(t *testing.T) {
topo := NewTopology()
a1 := topo.AddNode("a1", "dc1", "dc1:rack1", 0) // full -> high util, the max node
a1.SetHost("boxA")
a1.AddShards(100, "col1", 0, bits(0, 1))
b1 := topo.AddNode("b1", "dc1", "dc1:rack1", 0) // full -> cannot receive
b1.SetHost("boxB")
b1.AddShards(100, "col1", 0, bits(2, 3))
b2 := topo.AddNode("b2", "dc1", "dc1:rack1", 10) // empty -> low util, the min node
b2.SetHost("boxB")
data := map[string]int{"col1": 2}
parity := map[string]int{"col1": 2}
for _, m := range detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, data, parity, 0, true) {
if m.source.host != m.target.host {
t.Errorf("cross-machine global move %d.%d from %s to %s concentrates the volume on a machine",
m.volumeID, m.shardID, m.source.host, m.target.host)
}
}
}
// TestWithinRackMachineSkipsCappedMachine: a machine whose only node is already at
// the per-node SameRackCount cap is not a viable target, and the within-rack spread
// must move shards to the next machine that is, rather than picking the capped one
// and skipping the move. Four machines (boxA has two nodes) make the spread active;
// boxB's node holds two parity shards (== SameRackCount), so boxA's over-concentrated
// data shards must land on the viable boxC/boxD.
func TestWithinRackMachineSkipsCappedMachine(t *testing.T) {
rp, _ := super_block.NewReplicaPlacementFromString("002") // SameRackCount=2
topo := NewTopology()
mk := func(id, host string) *Node {
n := topo.AddNode(id, "dc1", "dc1:rack1", 100)
n.SetHost(host)
n.AddDisk(0, "", 100, 0)
return n
}
a1 := mk("a1", "boxA")
mk("a2", "boxA") // boxA's second node makes numMachines(4) < numNodes(5)
b1 := mk("b1", "boxB")
c1 := mk("c1", "boxC")
d1 := mk("d1", "boxD")
a1.AddShards(100, "col1", 0, bits(0, 1, 2, 3)) // 4 data shards, over-concentrated on boxA
b1.AddShards(100, "col1", 0, bits(10, 11)) // 2 parity -> b1 at SameRackCount cap
detectWithinRackImbalance(volKey{"col1", 100}, topo.nodes, buildRacks(topo.nodes), "", 0, 10, 4, rp)
moved := 0
for _, n := range []*Node{c1, d1} {
if info, ok := n.shards[volKey{"col1", 100}]; ok {
moved += info.shardBits.Count()
}
}
if moved == 0 {
t.Error("data shards were not moved to the viable machines boxC/boxD; the capped boxB blocked the move")
}
}
// TestGlobalPrefersVolumeAbsentFromDestinationMachine: the global load phase must
// judge "volume already present" at the machine level. boxB's sibling node holds
// vol100, so draining boxA onto boxB's empty node should move a vol200 shard first
// (vol200 is absent from boxB) rather than piling a second vol100 copy onto boxB.
func TestGlobalPrefersVolumeAbsentFromDestinationMachine(t *testing.T) {
topo := NewTopology()
n1 := topo.AddNode("n1", "dc1", "dc1:rack1", 0)
n1.SetHost("boxA")
n1.AddShards(100, "col1", 0, bits(0, 1, 2, 3))
n1.AddShards(200, "col1", 0, bits(0, 1, 2, 3))
n2 := topo.AddNode("n2", "dc1", "dc1:rack1", 5)
n2.SetHost("boxB")
n2.AddShards(100, "col1", 0, bits(4)) // vol100 already on boxB (sibling node)
n3 := topo.AddNode("n3", "dc1", "dc1:rack1", 5)
n3.SetHost("boxB") // empty destination node, but its machine holds vol100
moves := detectGlobalImbalance(topo.nodes, buildRacks(topo.nodes), "", 0.01, nil, nil, 0, true)
if len(moves) == 0 {
t.Fatal("expected a global move from the full node")
}
if moves[0].volumeID != 200 {
t.Errorf("first global move is volume %d, want 200 (vol100 already on the destination machine)", moves[0].volumeID)
}
}
@@ -388,16 +388,9 @@ func rackHasFreeDisk(r *rack, eligible func(*disk) bool) bool {
// pickNodeInRackEligible is pickNodeInRack restricted to nodes that have a free
// eligible disk. FromActiveTopology keeps all disk types/tags in the snapshot, so
// without this a node with free volume slots but no eligible disk could be chosen.
//
// Among eligible nodes it ranks by fewest shards of the volume per machine, then per
// node, with free capacity breaking ties. The free-capacity tie-break (not sorted id)
// keeps the lowest-id machine from winning every volume's first shard against the
// shared encode snapshot and piling up load.
func pickNodeInRackEligible(r *rack, vk volKey, rp *super_block.ReplicaPlacement, eligible func(*disk) bool) *Node {
machineShards := countShardsByHost(vk, r.nodes)
machineFree := freeSlotsByHost(r.nodes)
var best *Node
var bestMCount, bestMFree, bestNCount, bestNFree int
bestCount := -1
for _, id := range sortedNodeKeys(r.nodes) {
node := r.nodes[id]
if node.freeSlots <= 0 {
@@ -410,22 +403,8 @@ func pickNodeInRackEligible(r *rack, vk volKey, rp *super_block.ReplicaPlacement
if rp != nil && rp.SameRackCount > 0 && count >= rp.SameRackCount {
continue
}
mCount, mFree := machineShards[node.host], machineFree[node.host]
better := false
switch {
case best == nil:
better = true
case mCount != bestMCount:
better = mCount < bestMCount
case mFree != bestMFree:
better = mFree > bestMFree
case count != bestNCount:
better = count < bestNCount
default:
better = node.freeSlots > bestNFree
}
if better {
best, bestMCount, bestMFree, bestNCount, bestNFree = node, mCount, mFree, count, node.freeSlots
if best == nil || count < bestCount {
best, bestCount = node, count
}
}
return best
@@ -73,86 +73,6 @@ func TestPlaceStrictSpreadAndCaps(t *testing.T) {
}
}
// TestPlaceDistributesEvenlyAcrossManyVolumes: placing many volumes against the shared
// encode snapshot must not pile shards onto the sorted-first machine.
func TestPlaceDistributesEvenlyAcrossManyVolumes(t *testing.T) {
topo := NewTopology()
hosts := []string{"10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.4", "10.0.0.5", "10.0.0.6"}
for _, h := range hosts {
for _, port := range []string{":8080", ":8081"} {
n := topo.AddNode(h+port, "dc1", "dc1:rack1", 1000)
n.SetHost(h)
n.AddDisk(0, "", 1000, 0)
}
}
const volumes = 120
for v := 0; v < volumes; v++ {
if _, err := topo.Place(uint32(v), "c1", allShards(), Constraints{}, PlaceDurabilityFirst); err != nil {
t.Fatalf("Place volume %d: %v", v, err)
}
}
perMachine := map[string]int{}
for _, n := range topo.nodes {
for _, d := range n.disks {
perMachine[n.host] += d.shardCount
}
}
min, max := 1<<30, 0
for _, c := range perMachine {
if c < min {
min = c
}
if c > max {
max = c
}
}
// Even distribution is 120*14/6 = 280 shards/machine. Catch a lopsided pileup
// (the production symptom was the first machine at ~1.7x the rest).
if float64(max) > 1.25*float64(min) {
t.Errorf("EC shards piled unevenly across machines: min=%d max=%d %v", min, max, perMachine)
}
}
// TestPlaceSpreadsAcrossMachines: one rack runs two physical machines (each with
// four volume servers). Placing a 10+4 volume must spread its shards across both
// machines so no single machine holds more than ceil(14/2)=7, otherwise losing one
// box would take out more shards than EC can recover even though they look spread
// across distinct nodes.
func TestPlaceSpreadsAcrossMachines(t *testing.T) {
topo := NewTopology()
host := map[string]string{}
add := func(id, h string) {
n := topo.AddNode(id, "dc1", "dc1:rack0", 50)
n.SetHost(h)
n.AddDisk(0, "", 50, 0)
host[id] = h
}
for i := 0; i < 4; i++ {
add(fmt.Sprintf("a%d", i), "10.0.0.1")
add(fmt.Sprintf("b%d", i), "10.0.0.2")
}
res, err := topo.Place(1, "c1", allShards(), Constraints{}, PlaceStrict)
if err != nil {
t.Fatalf("Place: %v", err)
}
perMachine := map[string]int{}
for _, d := range res.Destinations {
perMachine[host[d.Node]]++
}
if len(perMachine) < 2 {
t.Fatalf("shards not spread across machines: %v", perMachine)
}
maxPerMachine := ceilDivide(erasure_coding.TotalShardsCount, 2)
for h, c := range perMachine {
if c > maxPerMachine {
t.Errorf("machine %s holds %d shards, want <=%d (ceil(14/2))", h, c, maxPerMachine)
}
}
}
// TestPlaceStrictFailsAndRollsBack: a single tiny disk cannot hold 14 shards, so
// strict Place fails and leaves the snapshot untouched.
func TestPlaceStrictFailsAndRollsBack(t *testing.T) {
@@ -2,7 +2,6 @@ package ecbalancer
import (
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
)
@@ -33,7 +32,6 @@ func FromActiveTopology(at *topology.ActiveTopology, dataShards int) *Topology {
nodeFree := make(map[string]int)
nodeDC := make(map[string]string)
nodeRack := make(map[string]string)
nodeAddr := make(map[string]string)
byNode := make(map[string][]*topology.DiskInfo)
for _, d := range disks {
if d == nil || d.DiskInfo == nil {
@@ -44,19 +42,11 @@ func FromActiveTopology(at *topology.ActiveTopology, dataShards int) *Topology {
}
nodeDC[d.NodeID] = d.DataCenter
nodeRack[d.NodeID] = d.DataCenter + ":" + d.Rack
nodeAddr[d.NodeID] = d.Address
byNode[d.NodeID] = append(byNode[d.NodeID], d)
}
for nodeID, ds := range byNode {
node := topo.AddNode(nodeID, nodeDC[nodeID], nodeRack[nodeID], nodeFree[nodeID])
// Group by physical machine: derive the host from the address (NodeID may be
// an opaque id), falling back to the id when no address is recorded.
addr := nodeAddr[nodeID]
if addr == "" {
addr = nodeID
}
node.SetHost(pb.ServerAddress(addr).ToHost())
for _, d := range ds {
free := perDiskFreeECSlots(at, d, dataShards)
if free < 0 {
@@ -102,47 +102,6 @@ func TestFromActiveTopology(t *testing.T) {
}
}
// TestFromActiveTopologyGroupsByAddressHost verifies the snapshot derives a node's
// machine from its address, not its (possibly opaque) id: two volume servers with
// distinct ids but the same host must land on one machine so EC placement spreads
// shards across boxes even when explicit node ids are configured.
func TestFromActiveTopologyGroupsByAddressHost(t *testing.T) {
at := topology.NewActiveTopology(10)
mk := func(id, addr string) *master_pb.DataNodeInfo {
return &master_pb.DataNodeInfo{
Id: id,
Address: addr,
DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {DiskId: 0, MaxVolumeCount: 100, VolumeCount: 0}},
}
}
// vs-a and vs-b are two servers on the same physical host; vs-c is another box.
nodes := []*master_pb.DataNodeInfo{
mk("vs-a", "10.0.0.9:8080"),
mk("vs-b", "10.0.0.9:8081"),
mk("vs-c", "10.0.0.10:8080"),
}
if err := at.UpdateTopology(&master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: nodes}},
}},
}); err != nil {
t.Fatalf("UpdateTopology: %v", err)
}
topo := FromActiveTopology(at, 0)
if topo.nodes["vs-a"].host != topo.nodes["vs-b"].host {
t.Errorf("vs-a host %q != vs-b host %q; same-machine servers not grouped",
topo.nodes["vs-a"].host, topo.nodes["vs-b"].host)
}
if topo.nodes["vs-a"].host == topo.nodes["vs-c"].host {
t.Errorf("vs-a and vs-c share host %q but are different machines", topo.nodes["vs-a"].host)
}
if got := topo.nodes["vs-a"].host; got != "10.0.0.9" {
t.Errorf("vs-a host = %q, want 10.0.0.9", got)
}
}
// TestEcShardSlotsOnDiskRoundsUp covers the mixed-ratio (targetDataShards <
// existingDataShards) conversion: an existing shard's fractional footprint must
// round up so it is never floored to zero, which would overstate free capacity.
+1 -1
View File
@@ -208,7 +208,7 @@ func parseUpload(r *http.Request, sizeLimit int64, pu *ParsedUpload) (e error) {
// update
pu.Data = pu.bytesBuffer.Bytes()
pu.FileName = util.CleanWindowsPathBase(fName)
contentType = part2.Header.Get("Content-Type")
contentType = part.Header.Get("Content-Type")
pu.ContentMd5 = part2.Header.Get("Content-MD5")
part = part2
break
@@ -76,50 +76,6 @@ func TestParseUpload_GzipStreamCount(t *testing.T) {
}
}
func TestParseUploadUsesDiscoveredFilePartContentType(t *testing.T) {
var body bytes.Buffer
mw := multipart.NewWriter(&body)
fieldHeader := make(textproto.MIMEHeader)
fieldHeader.Set("Content-Disposition", `form-data; name="description"`)
fieldHeader.Set("Content-Type", "text/plain")
field, err := mw.CreatePart(fieldHeader)
if err != nil {
t.Fatalf("create field part: %v", err)
}
if _, err := field.Write([]byte("metadata")); err != nil {
t.Fatalf("write field part: %v", err)
}
fileHeader := make(textproto.MIMEHeader)
fileHeader.Set("Content-Disposition", `form-data; name="file"; filename="file.dat"`)
fileHeader.Set("Content-Type", "application/x-seaweed-test")
filePart, err := mw.CreatePart(fileHeader)
if err != nil {
t.Fatalf("create file part: %v", err)
}
if _, err := filePart.Write([]byte("payload")); err != nil {
t.Fatalf("write file part: %v", err)
}
if err := mw.Close(); err != nil {
t.Fatalf("close multipart writer: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(body.Bytes()))
req.Header.Set("Content-Type", mw.FormDataContentType())
pu, err := ParseUpload(req, 1024, &bytes.Buffer{})
if err != nil {
t.Fatalf("ParseUpload: %v", err)
}
if pu.FileName != "file.dat" {
t.Fatalf("FileName = %q, want file.dat", pu.FileName)
}
if pu.MimeType != "application/x-seaweed-test" {
t.Fatalf("MimeType = %q, want application/x-seaweed-test", pu.MimeType)
}
}
func gzipBytes(t *testing.T, in []byte) []byte {
t.Helper()
var buf bytes.Buffer
+9 -46
View File
@@ -144,11 +144,11 @@ type Node interface {
}
type NodeImpl struct {
diskUsages *DiskUsages
id NodeId
parent Node
diskUsages *DiskUsages
id NodeId
parent Node
sync.RWMutex // lock children
children map[NodeId]Node
children map[NodeId]Node
// maxVolumeId uses atomic ops so UpAdjustMaxVolumeId (called from the
// volume server heartbeat path) and GetMaxVolumeId (called from the
// master's assign / warmup checks) can run concurrently without a
@@ -167,38 +167,6 @@ func (n *NodeImpl) GetDiskUsages() *DiskUsages {
return n.diskUsages
}
// nodeHost returns the host a node runs on, or "" for non-data-node tiers (data
// centers, racks).
func nodeHost(node Node) string {
if dn, ok := node.(*DataNode); ok {
return dn.Ip
}
return ""
}
// preferDistinctHosts reorders candidates so the first node of each not-yet-used
// host comes first (preserving weighted order), then the same-host leftovers, so a
// prefix covers the most distinct machines. usedHost seeds the set. No-op when
// hosts are empty (non-data-node tiers).
func preferDistinctHosts(usedHost string, candidates []Node) []Node {
used := map[string]bool{}
if usedHost != "" {
used[usedHost] = true
}
distinct := make([]Node, 0, len(candidates))
dup := make([]Node, 0, len(candidates))
for _, node := range candidates {
h := nodeHost(node)
if h != "" && !used[h] {
used[h] = true
distinct = append(distinct, node)
} else {
dup = append(dup, node)
}
}
return append(distinct, dup...)
}
// the first node must satisfy filterFirstNodeFn(), the rest nodes must have one free slot
func (n *NodeImpl) PickNodesByWeight(numberOfNodes int, option *VolumeGrowOption, filterFirstNodeFn func(dn Node) error) (firstNode Node, restNodes []Node, err error) {
var totalWeights int64
@@ -247,17 +215,12 @@ func (n *NodeImpl) PickNodesByWeight(numberOfNodes int, option *VolumeGrowOption
for k, node := range sortedCandidates {
if err := filterFirstNodeFn(node); err == nil {
firstNode = node
// Fill the rest preferring not-yet-used hosts, so replicas spread across
// machines; falls back to same-host when too few. No-op for dc/rack tiers
// (empty host), which keep the weighted order.
pool := make([]Node, 0, len(sortedCandidates)-1)
pool = append(pool, sortedCandidates[:k]...)
pool = append(pool, sortedCandidates[k+1:]...)
pool = preferDistinctHosts(nodeHost(firstNode), pool)
if len(pool) > numberOfNodes-1 {
pool = pool[:numberOfNodes-1]
if k >= numberOfNodes-1 {
restNodes = sortedCandidates[:numberOfNodes-1]
} else {
restNodes = append(restNodes, sortedCandidates[:k]...)
restNodes = append(restNodes, sortedCandidates[k+1:numberOfNodes]...)
}
restNodes = pool
ret = true
break
} else {
+4 -13
View File
@@ -240,12 +240,9 @@ func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float
vid := needle.VolumeId(volumeId)
volumeLayout.accessLock.RLock()
locationList, ok := volumeLayout.vid2location[vid]
if ok {
locationList = locationList.Copy()
}
volumeLayout.accessLock.RUnlock()
if ok {
t.vacuumOneVolumeId(grpcDialOption, volumeLayout, c, garbageThreshold, locationList, vid, preallocate, false)
t.vacuumOneVolumeId(grpcDialOption, volumeLayout, c, garbageThreshold, locationList, vid, preallocate)
}
} else {
t.vacuumOneVolumeLayout(grpcDialOption, volumeLayout, c, garbageThreshold, maxParallelVacuumPerServer, preallocate, automatic)
@@ -314,7 +311,7 @@ func (t *Topology) vacuumOneVolumeLayout(grpcDialOption grpc.DialOption, volumeL
wg.Add(1)
executor.Execute(func() {
defer wg.Done()
t.vacuumOneVolumeId(grpcDialOption, volumeLayout, c, garbageThreshold, locationList, vid, preallocate, true)
t.vacuumOneVolumeId(grpcDialOption, volumeLayout, c, garbageThreshold, locationList, vid, preallocate)
// credit the quota
for _, dn := range locationList.list {
limiterLock.Lock()
@@ -339,20 +336,14 @@ func (t *Topology) vacuumOneVolumeLayout(grpcDialOption grpc.DialOption, volumeL
}
// skipReadOnly is set by the background scan and all-volumes sweep, where a
// read-only flag usually means an unhealthy disk. An explicit volumeId clears
// it so a benignly read-only (full/oversized) volume can be reclaimed.
func (t *Topology) vacuumOneVolumeId(grpcDialOption grpc.DialOption, volumeLayout *VolumeLayout, c *Collection, garbageThreshold float64, locationList *VolumeLocationList, vid needle.VolumeId, preallocate int64, skipReadOnly bool) {
func (t *Topology) vacuumOneVolumeId(grpcDialOption grpc.DialOption, volumeLayout *VolumeLayout, c *Collection, garbageThreshold float64, locationList *VolumeLocationList, vid needle.VolumeId, preallocate int64) {
volumeLayout.accessLock.RLock()
isReadOnly := volumeLayout.readonlyVolumes.IsTrue(vid)
isEnoughCopies := volumeLayout.enoughCopies(vid)
volumeLayout.accessLock.RUnlock()
if isReadOnly {
if skipReadOnly {
return
}
glog.V(0).Infof("vacuuming read-only volume %d on explicit request", vid)
return
}
if !isEnoughCopies {
glog.Warningf("skip vacuuming: not enough copies for volume:%d", vid)
+11 -16
View File
@@ -98,25 +98,20 @@ func NewDefaultVolumeGrowth() *VolumeGrowth {
return &VolumeGrowth{}
}
// VolumeGrowthCountForCopies returns the configured number of logical volumes
// to create at once for a given replica copy count (master.volume_growth.copy_N).
func VolumeGrowthCountForCopies(copyCount int) uint32 {
switch copyCount {
case 1:
return VolumeGrowStrategy.Copy1Count
case 2:
return VolumeGrowStrategy.Copy2Count
case 3:
return VolumeGrowStrategy.Copy3Count
default:
return VolumeGrowStrategy.CopyOtherCount
}
}
// one replication type may need rp.GetCopyCount() actual volumes
// given copyCount, how many logical volumes to create
func (vg *VolumeGrowth) findVolumeCount(copyCount int) (count uint32) {
return VolumeGrowthCountForCopies(copyCount)
switch copyCount {
case 1:
count = VolumeGrowStrategy.Copy1Count
case 2:
count = VolumeGrowStrategy.Copy2Count
case 3:
count = VolumeGrowStrategy.Copy3Count
default:
count = VolumeGrowStrategy.CopyOtherCount
}
return
}
func (vg *VolumeGrowth) AutomaticGrowByType(option *VolumeGrowOption, grpcDialOption grpc.DialOption, topo *Topology, targetCount uint32) (result []*master_pb.VolumeLocation, err error) {
-37
View File
@@ -475,40 +475,3 @@ func TestPickForWrite(t *testing.T) {
}
}
}
// TestPickNodesByWeightPrefersDistinctHosts: a rack runs two physical machines
// with two volume servers each. Picking two nodes (e.g. for a same-rack replica
// pair) must land them on distinct hosts so a single machine failure cannot take
// out both replicas, even though the four data nodes are independent.
func TestPickNodesByWeightPrefersDistinctHosts(t *testing.T) {
rack := NewRack("rack1")
mk := func(id, ip string, maxVol int64) *DataNode {
dn := NewDataNode(id)
dn.Ip = ip
rack.LinkChildNode(dn)
disk := dn.getOrCreateDisk("")
disk.UpAdjustDiskUsageDelta("", &DiskUsageCounts{maxVolumeCount: maxVol})
return dn
}
mk("s1a", "10.0.0.1", 10)
mk("s1b", "10.0.0.1", 10)
mk("s2a", "10.0.0.2", 10)
mk("s2b", "10.0.0.2", 10)
option := &VolumeGrowOption{DiskType: types.HardDriveType}
// Selection is weighted-random, so exercise it repeatedly: with two machines
// available the chosen pair must always span both.
for i := 0; i < 50; i++ {
first, rest, err := rack.PickNodesByWeight(2, option, func(node Node) error { return nil })
if err != nil {
t.Fatalf("PickNodesByWeight: %v", err)
}
if len(rest) != 1 {
t.Fatalf("got %d rest nodes, want 1", len(rest))
}
if nodeHost(first) == nodeHost(rest[0]) {
t.Errorf("both picks on host %s; expected distinct machines", nodeHost(first))
}
}
}
-64
View File
@@ -696,70 +696,6 @@ func (vl *VolumeLayout) ShouldGrowVolumesByDcAndRack(writables *[]needle.VolumeI
return true
}
// RackGrowPlan is one volume grow action produced by the periodic rack-aware
// growth scan. An empty Rack means the grow is DC-wide.
type RackGrowPlan struct {
DataCenter string
Rack string
WritableVolumeCount uint32
}
// PlanRackAwareGrowth returns the grow actions needed so every location that
// can serve writes keeps a non-crowded writable volume. stepCount is the
// default per-event increment.
//
// For rack-spanning replication (DiffRackCount > 0) a single logical volume
// already covers the racks the placement requires, so ShouldGrowVolumesByDcAndRack
// returns the same result for every rack in a DC. Planning one grow per rack
// would create racks×count too many volumes; plan one DC-wide grow instead.
// The default increment is capped at the configured copy_N so lowering
// master.volume_growth.copy_N reduces periodic growth.
func (vl *VolumeLayout) PlanRackAwareGrowth(dcs map[NodeId][]NodeId, lastGrowCount, stepCount uint32) (plans []RackGrowPlan) {
writables := vl.CloneWritableVolumes()
if c := VolumeGrowthCountForCopies(vl.rp.GetCopyCount()); c < stepCount {
stepCount = c
}
growOncePerDc := vl.rp.DiffRackCount > 0
// Spread lastGrowCount evenly across all grow targets. Summing every rack
// up front keeps the divisor global, so DCs with different rack counts do
// not each over-grow from a per-DC divisor.
var rackPairs uint32
for _, racks := range dcs {
rackPairs += uint32(len(racks))
}
for dcId, racks := range dcs {
if growOncePerDc {
if !vl.ShouldGrowVolumesByDcAndRack(&writables, dcId, "") {
continue
}
count := stepCount
if lastGrowCount > 0 {
count = ceilDiv(lastGrowCount, uint32(len(dcs)))
}
plans = append(plans, RackGrowPlan{DataCenter: string(dcId), WritableVolumeCount: count})
continue
}
for _, rackId := range racks {
if !vl.ShouldGrowVolumesByDcAndRack(&writables, dcId, rackId) {
continue
}
count := stepCount
if lastGrowCount > 0 {
count = ceilDiv(lastGrowCount, rackPairs)
}
plans = append(plans, RackGrowPlan{DataCenter: string(dcId), Rack: string(rackId), WritableVolumeCount: count})
}
}
return plans
}
func ceilDiv(a, b uint32) uint32 {
if b == 0 {
return 0
}
return (a + b - 1) / b
}
func (vl *VolumeLayout) GetWritableVolumeCount() (active, crowded int) {
vl.accessLock.RLock()
defer vl.accessLock.RUnlock()
-167
View File
@@ -77,170 +77,3 @@ func TestShouldGrowVolumesByDcAndRack_Issue8986(t *testing.T) {
t.Error("rack3 should NOT need growth — the DC already has non-crowded writable volumes that can serve writes")
}
}
// Topology from https://github.com/seaweedfs/seaweedfs/issues/9832
// 1 DC, 2 racks, 1 server each, replication 010, one crowded volume (28.65 GB)
// near the 30 GB size limit.
var topologyLayout9832 = `
{
"datacenter1":{
"rack1":{
"node-a":{
"ip":"10.0.0.1",
"volumes":[ {"id":12, "size":28650, "replication":"010", "collection":"bucket-nexus"} ],
"limit":30
}
},
"rack2":{
"node-b":{
"ip":"10.0.0.2",
"volumes":[ {"id":12, "size":28650, "replication":"010", "collection":"bucket-nexus"} ],
"limit":30
}
}
}
}
`
// Reproduces https://github.com/seaweedfs/seaweedfs/issues/9832
//
// A crowded "010" volume made the periodic rack-aware scan return true for
// every rack in the DC, so it grew once per rack with a hardcoded step of 2 —
// 2 racks × 2 = 4 logical volumes (8 physical) — and ignored a lowered
// master.volume_growth.copy_2. PlanRackAwareGrowth now plans a single DC-wide
// grow capped at copy_N.
func TestPlanRackAwareGrowth_Issue9832(t *testing.T) {
defer restoreCopyCounts(VolumeGrowStrategy.Copy1Count, VolumeGrowStrategy.Copy2Count)
VolumeGrowStrategy.Copy2Count = 1 // user's master.volume_growth.copy_2
topo := setupWithLimit(t, topologyLayout9832, 30000)
rp, _ := super_block.NewReplicaPlacementFromString("010")
vl := topo.GetVolumeLayout("bucket-nexus", rp, needle.EMPTY_TTL, types.HardDriveType)
if writables := vl.CloneWritableVolumes(); len(writables) != 1 {
t.Fatalf("expected 1 writable volume, got %d", len(writables))
}
// The crowded volume makes both racks report "should grow" — the source of
// the old per-rack multiplication.
writables := vl.CloneWritableVolumes()
if !vl.ShouldGrowVolumesByDcAndRack(&writables, "datacenter1", "rack1") ||
!vl.ShouldGrowVolumesByDcAndRack(&writables, "datacenter1", "rack2") {
t.Fatal("expected both racks to report should-grow for the crowded volume")
}
plans := vl.PlanRackAwareGrowth(topo.ListDCAndRacks(), 0, 2)
if len(plans) != 1 {
t.Fatalf("expected 1 DC-wide grow, got %d: %+v", len(plans), plans)
}
if plans[0].Rack != "" {
t.Errorf("expected DC-wide grow (empty rack), got rack %q", plans[0].Rack)
}
if plans[0].WritableVolumeCount != 1 {
t.Errorf("expected copy_2=1 logical volume, got %d", plans[0].WritableVolumeCount)
}
}
// With the default copy_2 the per-event step is preserved (not increased): the
// fix only removes the per-rack multiplication.
func TestPlanRackAwareGrowth_DefaultStepNotMultiplied(t *testing.T) {
defer restoreCopyCounts(VolumeGrowStrategy.Copy1Count, VolumeGrowStrategy.Copy2Count)
VolumeGrowStrategy.Copy2Count = 6 // default
topo := setupWithLimit(t, topologyLayout9832, 30000)
rp, _ := super_block.NewReplicaPlacementFromString("010")
vl := topo.GetVolumeLayout("bucket-nexus", rp, needle.EMPTY_TTL, types.HardDriveType)
plans := vl.PlanRackAwareGrowth(topo.ListDCAndRacks(), 0, 2)
if len(plans) != 1 {
t.Fatalf("expected 1 DC-wide grow, got %d: %+v", len(plans), plans)
}
if plans[0].WritableVolumeCount != 2 {
t.Errorf("expected step count 2 (min of step 2 and copy_2 6), got %d", plans[0].WritableVolumeCount)
}
}
// A non-crowded "010" volume needs no growth at all.
func TestPlanRackAwareGrowth_NotCrowdedNoGrowth(t *testing.T) {
layout := `
{
"datacenter1":{
"rack1":{ "node-a":{ "ip":"10.0.0.1", "volumes":[ {"id":12, "size":1000, "replication":"010", "collection":"c"} ], "limit":30 } },
"rack2":{ "node-b":{ "ip":"10.0.0.2", "volumes":[ {"id":12, "size":1000, "replication":"010", "collection":"c"} ], "limit":30 } }
}
}
`
topo := setupWithLimit(t, layout, 30000)
rp, _ := super_block.NewReplicaPlacementFromString("010")
vl := topo.GetVolumeLayout("c", rp, needle.EMPTY_TTL, types.HardDriveType)
if plans := vl.PlanRackAwareGrowth(topo.ListDCAndRacks(), 0, 2); len(plans) != 0 {
t.Fatalf("expected no growth for non-crowded volume, got %+v", plans)
}
}
// Non-rack-spanning replication ("000") still grows per rack: a rack without a
// writable volume gets its own grow.
func TestPlanRackAwareGrowth_PerRackForNonRackSpanning(t *testing.T) {
layout := `
{
"datacenter1":{
"rack1":{ "node-a":{ "ip":"10.0.0.1", "volumes":[ {"id":1, "size":1000, "replication":"000", "collection":"c"} ], "limit":30 } },
"rack2":{ "node-b":{ "ip":"10.0.0.2", "volumes":[], "limit":30 } }
}
}
`
topo := setupWithLimit(t, layout, 30000)
rp, _ := super_block.NewReplicaPlacementFromString("000")
vl := topo.GetVolumeLayout("c", rp, needle.EMPTY_TTL, types.HardDriveType)
plans := vl.PlanRackAwareGrowth(topo.ListDCAndRacks(), 0, 2)
if len(plans) != 1 {
t.Fatalf("expected 1 per-rack grow, got %d: %+v", len(plans), plans)
}
if plans[0].Rack != "rack2" {
t.Errorf("expected grow pinned to empty rack2, got %q", plans[0].Rack)
}
}
// lastGrowCount is spread evenly across all grow targets even when DCs have
// different rack counts: each crowded "000" rack gets ceilDiv(lastGrowCount,
// totalRacks), so the total matches the request rather than over-growing per DC.
func TestPlanRackAwareGrowth_EvenDistributionAcrossUnevenDCs(t *testing.T) {
layout := `
{
"dc1":{
"rack1":{ "node-a":{ "ip":"10.0.0.1", "volumes":[ {"id":1, "size":28650, "replication":"000", "collection":"c"} ], "limit":30 } },
"rack2":{ "node-b":{ "ip":"10.0.0.2", "volumes":[ {"id":2, "size":28650, "replication":"000", "collection":"c"} ], "limit":30 } }
},
"dc2":{
"rack3":{ "node-c":{ "ip":"10.0.0.3", "volumes":[ {"id":3, "size":28650, "replication":"000", "collection":"c"} ], "limit":30 } },
"rack4":{ "node-d":{ "ip":"10.0.0.4", "volumes":[ {"id":4, "size":28650, "replication":"000", "collection":"c"} ], "limit":30 } },
"rack5":{ "node-e":{ "ip":"10.0.0.5", "volumes":[ {"id":5, "size":28650, "replication":"000", "collection":"c"} ], "limit":30 } }
}
}
`
topo := setupWithLimit(t, layout, 30000)
rp, _ := super_block.NewReplicaPlacementFromString("000")
vl := topo.GetVolumeLayout("c", rp, needle.EMPTY_TTL, types.HardDriveType)
plans := vl.PlanRackAwareGrowth(topo.ListDCAndRacks(), 10, 2)
if len(plans) != 5 {
t.Fatalf("expected a grow per crowded rack (5), got %d: %+v", len(plans), plans)
}
total := uint32(0)
for _, p := range plans {
if p.WritableVolumeCount != 2 { // ceilDiv(10, 5 racks)
t.Errorf("expected even per-rack count 2, got %d for %s/%s", p.WritableVolumeCount, p.DataCenter, p.Rack)
}
total += p.WritableVolumeCount
}
if total != 10 {
t.Errorf("expected total grow 10, got %d", total)
}
}
func restoreCopyCounts(copy1, copy2 uint32) {
VolumeGrowStrategy.Copy1Count = copy1
VolumeGrowStrategy.Copy2Count = copy2
}
-4
View File
@@ -165,8 +165,6 @@ func NewHttpClient(clientName ClientName, opts ...HttpClientOpt) (*HTTPClient, e
MaxIdleConns: 1024,
MaxIdleConnsPerHost: 1024,
TLSClientConfig: tlsConfig,
// Bind outbound HTTP to the -ip.bind source address.
DialContext: util.OutboundDialContext,
}
httpClient.Client = &http.Client{
Transport: httpClient.Transport,
@@ -281,8 +279,6 @@ func NewHttpClientWithTLS(certFile, keyFile, caFile string, insecureSkipVerify b
MaxIdleConns: 1024,
MaxIdleConnsPerHost: 1024,
TLSClientConfig: tlsConfig,
// Bind outbound HTTP to the -ip.bind source address.
DialContext: util.OutboundDialContext,
}
httpClient.Client = &http.Client{
Transport: httpClient.Transport,
-100
View File
@@ -1,100 +0,0 @@
package util
import (
"context"
"net"
"strings"
"sync/atomic"
"time"
)
// outboundLocalAddr is the optional source address that outbound TCP
// connections initiated by this process bind to. It mirrors the -ip.bind
// setting so connections this process opens leave from the configured
// address instead of one the OS picks arbitrarily, which may not even be able
// to reach the target. A nil value keeps the historical behavior of letting
// the OS choose the source address.
var (
outboundLocalAddr atomic.Pointer[net.TCPAddr]
outboundLocalAddrSet atomic.Bool
)
// SetOutboundLocalIP records ip as the source address for outbound TCP
// connections. An empty, wildcard (0.0.0.0 / ::), or unparseable value leaves
// the source address to the OS.
//
// The first call wins. `weed server` applies the top-level -ip.bind before its
// embedded master/volume/filer/s3/... start, so a component's own (possibly
// different) bind setting can't later clobber the process-wide source address
// the others already dial from.
func SetOutboundLocalIP(ip string) {
if !outboundLocalAddrSet.CompareAndSwap(false, true) {
return
}
parsed := net.ParseIP(ip)
if parsed == nil || parsed.IsUnspecified() {
return
}
outboundLocalAddr.Store(&net.TCPAddr{IP: parsed})
}
// OutboundLocalAddr returns the configured source address for outbound TCP
// connections, or nil if none is configured.
func OutboundLocalAddr() *net.TCPAddr {
return outboundLocalAddr.Load()
}
// OutboundDialContext dials network/address with the standard library's
// default timeouts, binding the local (source) address to the configured
// -ip.bind value for non-loopback tcp targets. Loopback targets and non-tcp
// networks (e.g. unix sockets) keep the OS-chosen source address: a routable
// bind IP cannot originate a packet on the loopback interface.
func OutboundDialContext(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
if localAddr := outboundLocalAddrForDial(network, address); localAddr != nil {
d.LocalAddr = localAddr
}
return d.DialContext(ctx, network, address)
}
// outboundLocalAddrForDial returns the source address to bind for a dial to
// network/address, or nil to leave the source address to the OS.
func outboundLocalAddrForDial(network, address string) *net.TCPAddr {
localAddr := OutboundLocalAddr()
if localAddr == nil || !strings.HasPrefix(network, "tcp") || isLoopbackHost(address) {
return nil
}
// A source address can only originate a connection to a target of the same
// IP family. When the target is a literal IP of the other family, leave the
// source to the OS rather than forcing a dial that is bound to fail.
if host, _, err := net.SplitHostPort(address); err == nil {
if targetIP := net.ParseIP(host); targetIP != nil && isIPv4(targetIP) != isIPv4(localAddr.IP) {
return nil
}
}
return localAddr
}
// isIPv4 reports whether ip is an IPv4 (or IPv4-mapped) address.
func isIPv4(ip net.IP) bool {
return ip.To4() != nil
}
// isLoopbackHost reports whether the host part of a "host:port" (or bare host)
// address refers to the loopback interface.
func isLoopbackHost(address string) bool {
host, _, err := net.SplitHostPort(address)
if err != nil {
host = address
}
if strings.EqualFold(host, "localhost") {
return true
}
if ip := net.ParseIP(host); ip != nil {
return ip.IsLoopback()
}
return false
}
-129
View File
@@ -1,129 +0,0 @@
package util
import (
"testing"
)
// resetOutbound clears the process-global outbound source address so each test
// starts from a clean slate (SetOutboundLocalIP is otherwise first-write-wins).
func resetOutbound() {
outboundLocalAddrSet.Store(false)
outboundLocalAddr.Store(nil)
}
func TestSetOutboundLocalIP(t *testing.T) {
t.Cleanup(resetOutbound)
cases := []struct {
name string
ip string
wantIP string // empty means no binding
}{
{"ipv4", "10.0.0.5", "10.0.0.5"},
{"ipv6", "fe80::1", "fe80::1"},
{"empty", "", ""},
{"wildcard v4", "0.0.0.0", ""},
{"wildcard v6", "::", ""},
{"garbage", "not-an-ip", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
resetOutbound()
SetOutboundLocalIP(tc.ip)
got := OutboundLocalAddr()
if tc.wantIP == "" {
if got != nil {
t.Fatalf("expected no bound address, got %v", got)
}
return
}
if got == nil {
t.Fatalf("expected bound address %s, got nil", tc.wantIP)
}
if got.IP.String() != tc.wantIP {
t.Fatalf("bound address = %s, want %s", got.IP.String(), tc.wantIP)
}
if got.Port != 0 {
t.Fatalf("bound port = %d, want 0 (ephemeral)", got.Port)
}
})
}
}
// TestSetOutboundLocalIPFirstWins guards the behavior that keeps `weed server`
// from letting a component's own bind setting clobber the process-wide address.
func TestSetOutboundLocalIPFirstWins(t *testing.T) {
t.Cleanup(resetOutbound)
resetOutbound()
SetOutboundLocalIP("10.0.0.5") // server-level bind, applied first
SetOutboundLocalIP("10.0.0.9") // a component's own bind: must be ignored
SetOutboundLocalIP("") // a component clearing: must not unbind
got := OutboundLocalAddr()
if got == nil || got.IP.String() != "10.0.0.5" {
t.Fatalf("first call should win, got %v", got)
}
}
func TestOutboundLocalAddrForDial(t *testing.T) {
t.Cleanup(resetOutbound)
// No bind configured: never binds a source address.
resetOutbound()
if got := outboundLocalAddrForDial("tcp", "10.0.0.9:8080"); got != nil {
t.Fatalf("unconfigured dial should not bind, got %v", got)
}
resetOutbound()
SetOutboundLocalIP("10.0.0.5")
cases := []struct {
name string
network string
address string
wantBind bool
}{
{"remote tcp binds", "tcp", "10.0.0.9:8080", true},
{"tcp4 binds", "tcp4", "example.com:443", true},
{"hostname binds", "tcp", "filer.internal:8888", true},
{"loopback ip skipped", "tcp", "127.0.0.1:9333", false},
{"loopback name skipped", "tcp", "localhost:9333", false},
{"ipv6 loopback skipped", "tcp", "[::1]:9333", false},
{"ipv6 literal target skipped", "tcp", "[2001:db8::1]:8080", false},
{"unix network skipped", "unix", "/tmp/x.sock", false},
{"udp network skipped", "udp", "10.0.0.9:53", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := outboundLocalAddrForDial(tc.network, tc.address)
if tc.wantBind && got == nil {
t.Fatalf("%s/%s: expected source binding, got nil", tc.network, tc.address)
}
if !tc.wantBind && got != nil {
t.Fatalf("%s/%s: expected no source binding, got %v", tc.network, tc.address, got)
}
})
}
}
func TestOutboundLocalAddrFamilyMismatch(t *testing.T) {
t.Cleanup(resetOutbound)
resetOutbound()
SetOutboundLocalIP("10.0.0.5") // IPv4 source
if got := outboundLocalAddrForDial("tcp", "[2001:db8::1]:8080"); got != nil {
t.Fatalf("IPv4 source to IPv6 literal target should skip binding, got %v", got)
}
if got := outboundLocalAddrForDial("tcp", "10.0.0.9:8080"); got == nil {
t.Fatalf("IPv4 source to IPv4 literal target should bind")
}
resetOutbound()
SetOutboundLocalIP("2001:db8::5") // IPv6 source
if got := outboundLocalAddrForDial("tcp", "10.0.0.9:8080"); got != nil {
t.Fatalf("IPv6 source to IPv4 literal target should skip binding, got %v", got)
}
if got := outboundLocalAddrForDial("tcp", "[2001:db8::1]:8080"); got == nil {
t.Fatalf("IPv6 source to IPv6 literal target should bind")
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
var (
MAJOR_VERSION = int32(4)
MINOR_VERSION = int32(32)
MINOR_VERSION = int32(31)
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
VERSION = util.SizeLimit + " " + VERSION_NUMBER
COMMIT = ""
-2
View File
@@ -662,7 +662,6 @@ func planBalanceDestination(activeTopology *topology.ActiveTopology, selectedVol
DataCenter: disk.DataCenter,
Rack: disk.Rack,
NodeID: disk.NodeID,
Host: hostFromAddress(disk.Address, disk.NodeID),
}
if !IsGoodMove(rp, replicas, selectedVolume.Server, target) {
continue
@@ -772,7 +771,6 @@ func isValidBalanceDestination(plan *topology.DestinationPlan, allowedServers ma
DataCenter: plan.TargetDC,
Rack: plan.TargetRack,
NodeID: plan.TargetNode,
Host: hostFromAddress(plan.TargetAddress, plan.TargetNode),
}
return IsGoodMove(rp, replicas, sourceNodeID, target)
}
@@ -3,21 +3,10 @@ package balance
import (
"slices"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
)
// hostFromAddress returns the physical machine (host/IP) of a server address,
// falling back to the node id (== ip:port in the common case) when no address is
// known. Servers sharing a host are one fault domain.
func hostFromAddress(address, nodeID string) string {
if address == "" {
address = nodeID
}
return pb.ServerAddress(address).ToHost()
}
// rackKey uniquely identifies a rack within a data center.
type rackKey struct {
DataCenter string
@@ -55,17 +44,6 @@ func IsGoodMove(rp *super_block.ReplicaPlacement, existingReplicas []types.Repli
return false
}
// Best-effort machine anti-affinity: don't move a replica onto a host that
// already holds another replica of this volume, so a single machine failure
// can't take out two replicas.
if target.Host != "" {
for _, r := range afterMove {
if r.Host == target.Host {
return false
}
}
}
return satisfyReplicaPlacement(rp, afterMove, target)
}
@@ -29,24 +29,6 @@ func TestIsGoodMove_NoReplication(t *testing.T) {
}
}
func TestIsGoodMove_MachineAntiAffinity(t *testing.T) {
// rep 001 allows two copies in one rack, so replica placement alone would permit
// moving onto another port of a host that already holds a replica; machine
// anti-affinity must reject that and allow a distinct host.
existing := []types.ReplicaLocation{
{DataCenter: "dc1", Rack: "r1", NodeID: "10.0.0.1:8080", Host: "10.0.0.1"},
{DataCenter: "dc1", Rack: "r1", NodeID: "10.0.0.2:8080", Host: "10.0.0.2"},
}
onSameMachine := types.ReplicaLocation{DataCenter: "dc1", Rack: "r1", NodeID: "10.0.0.1:8081", Host: "10.0.0.1"}
if IsGoodMove(rp(t, "001"), existing, "10.0.0.2:8080", onSameMachine) {
t.Error("move onto a machine already holding a replica should be rejected")
}
onOtherMachine := types.ReplicaLocation{DataCenter: "dc1", Rack: "r1", NodeID: "10.0.0.3:8080", Host: "10.0.0.3"}
if !IsGoodMove(rp(t, "001"), existing, "10.0.0.2:8080", onOtherMachine) {
t.Error("move onto a distinct machine should be allowed")
}
}
func TestIsGoodMove_001_SameRack(t *testing.T) {
// 001 = 1 replica on same rack (2 total on same rack)
existing := []types.ReplicaLocation{
@@ -6,7 +6,6 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
@@ -199,9 +198,6 @@ func buildBalancerTopology(topoInfo *master_pb.TopologyInfo, config *Config) (*e
}
node := topo.AddNode(dn.Id, dc.Id, rackKey, freeSlots)
// Group servers sharing a host so a volume's shards spread across
// machines, not just nodes (servers on one host are one fault domain).
node.SetHost(pb.NewServerAddressFromDataNode(dn).ToHost())
perDiskFree := 0
if diskCount := len(diskTypeOf); diskCount > 0 && freeSlots > 0 {
@@ -2,7 +2,6 @@ package ec_balance
import (
"context"
"net"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
@@ -51,51 +50,6 @@ func TestBuildBalancerTopology(t *testing.T) {
}
}
// TestBuildBalancerTopologyGroupsByHost: two volume servers on host 10.0.0.1
// (different ports) plus three other hosts, a 10+4 volume concentrated on the
// 10.0.0.1 machine. Four machines is enough to spread within parity, so after
// planning the 10.0.0.1 machine must hold <=4 shards of the volume -- which only
// holds if its two ports are grouped into one machine (host wired into the build).
func TestBuildBalancerTopologyGroupsByHost(t *testing.T) {
mkNode := func(id string, bits uint32) *master_pb.DataNodeInfo {
di := &master_pb.DiskInfo{Type: "", MaxVolumeCount: 100}
if bits != 0 {
di.EcShardInfos = []*master_pb.VolumeEcShardInformationMessage{{Id: 100, Collection: "col1", DiskId: 0, EcIndexBits: bits}}
}
return &master_pb.DataNodeInfo{Id: id, DiskInfos: map[string]*master_pb.DiskInfo{"": di}}
}
topoInfo := &master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: []*master_pb.DataNodeInfo{
mkNode("10.0.0.1:8080", 0x007F), // shards 0-6 on host 10.0.0.1
mkNode("10.0.0.1:8081", 0x3F80), // shards 7-13 on host 10.0.0.1
mkNode("10.0.0.2:8080", 0),
mkNode("10.0.0.3:8080", 0),
mkNode("10.0.0.4:8080", 0),
}}},
}},
}
topo, _ := buildBalancerTopology(topoInfo, NewDefaultConfig())
moves := ecbalancer.Plan(topo, ecbalancer.Options{ImbalanceThreshold: 0.01})
host := func(nodeID string) string { h, _, _ := net.SplitHostPort(nodeID); return h }
count := map[string]int{"10.0.0.1": 14}
for _, m := range moves {
if m.VolumeID != 100 {
continue
}
count[host(m.SourceNode)]--
if m.SourceNode != m.TargetNode { // non-dedup move
count[host(m.TargetNode)]++
}
}
if count["10.0.0.1"] > 4 {
t.Errorf("machine 10.0.0.1 holds %d shards of the volume after balancing, want <=4 (host grouping not applied)", count["10.0.0.1"])
}
}
func TestBuildBalancerTopologyCollectionFilter(t *testing.T) {
config := NewDefaultConfig()
config.CollectionFilter = "other" // does not match the volume's collection
@@ -12,7 +12,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
"github.com/seaweedfs/seaweedfs/weed/worker/types/base"
"google.golang.org/grpc"
@@ -99,16 +98,6 @@ func (t *ECBalanceTask) Execute(ctx context.Context, params *worker_pb.TaskParam
return fmt.Errorf("copy and mount shard: %v", err)
}
// Step 1.5: confirm the destination actually registered the shard(s)
// before removing them from the source. A copy/mount RPC can return OK
// while the shard isn't loadable on the destination; deleting the source
// then would lose the shard. On a mismatch we keep the source so the
// scanner retries (the move is reported failed).
t.reportProgress(40.0, "Verifying EC shard(s) on destination")
if err := t.verifyShardsOnDestination(ctx, params.VolumeId, targetAddr, source.ShardIds); err != nil {
return err
}
// Step 2: Unmount shard on source
t.reportProgress(50.0, "Unmounting EC shard from source")
if err := t.unmountShard(ctx, params.VolumeId, sourceAddr, source.ShardIds); err != nil {
@@ -190,25 +179,6 @@ func (t *ECBalanceTask) unmountShard(ctx context.Context, volumeID uint32, addr
})
}
// verifyShardsOnDestination confirms targetAddr has registered every shard in
// shardIDs for volumeID, so the caller can safely delete the source copies.
func (t *ECBalanceTask) verifyShardsOnDestination(ctx context.Context, volumeID uint32, targetAddr pb.ServerAddress, shardIDs []uint32) error {
_, perServer := erasure_coding.VerifyShardsAcrossServers(ctx, volumeID, []string{string(targetAddr)}, t.grpcDialOption)
inv, ok := perServer[string(targetAddr)]
if !ok {
return fmt.Errorf("verify shard(s) on destination %s for volume %d: no inventory returned", targetAddr, volumeID)
}
if inv.QueryError != nil {
return fmt.Errorf("verify shard(s) on destination %s for volume %d: %v", targetAddr, volumeID, inv.QueryError)
}
for _, sid := range shardIDs {
if !inv.Bits.Has(erasure_coding.ShardId(sid)) {
return fmt.Errorf("destination %s missing EC shard %d.%d after copy/mount; keeping source", targetAddr, volumeID, sid)
}
}
return nil
}
// deleteShard deletes EC shards from a server
func (t *ECBalanceTask) deleteShard(ctx context.Context, volumeID uint32, collection string, addr pb.ServerAddress, shardIDs []uint32) error {
return operation.WithVolumeServerClient(false, addr, t.grpcDialOption,
-1
View File
@@ -12,7 +12,6 @@ type ReplicaLocation struct {
DataCenter string
Rack string
NodeID string
Host string // physical machine (host/IP); servers sharing a host are one fault domain
}
// ClusterInfo contains cluster information for task detection