mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-25 05:37:12 +01:00
Compare commits
132
Commits
pool-globe
...
4.42
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f04da8e9ad | ||
|
|
5c43c03b76 | ||
|
|
f530102c45 | ||
|
|
7522e17b6d | ||
|
|
ec37ef5aaa | ||
|
|
d044839ab2 | ||
|
|
a80259d362 | ||
|
|
5f6dd4d3e5 | ||
|
|
eef6f3d1e6 | ||
|
|
a1d3fe236f | ||
|
|
4c40ec3a9e | ||
|
|
b45f8314c5 | ||
|
|
76a1983c86 | ||
|
|
fbd85d31b0 | ||
|
|
829064af71 | ||
|
|
97a155d14d | ||
|
|
1c926e8fac | ||
|
|
602746f51d | ||
|
|
944d967502 | ||
|
|
f66d6ffc4a | ||
|
|
02b3ec6e90 | ||
|
|
c2ea452b9d | ||
|
|
d713ab49f9 | ||
|
|
9125b9c835 | ||
|
|
94f8e2caf9 | ||
|
|
9386a25a4a | ||
|
|
0de7ff5eb8 | ||
|
|
0481f712b1 | ||
|
|
ae2cc8225e | ||
|
|
7f27c572c4 | ||
|
|
4f50c5b0d4 | ||
|
|
7d0fff32db | ||
|
|
c0f33d599b | ||
|
|
4500bdf88e | ||
|
|
76d3fd0e9d | ||
|
|
abd36cbf92 | ||
|
|
4fb5d15019 | ||
|
|
f7ae2d4dd5 | ||
|
|
8714f42abf | ||
|
|
6408f32232 | ||
|
|
fa48ce20fc | ||
|
|
db5a086d04 | ||
|
|
a0347ca545 | ||
|
|
78e7e04377 | ||
|
|
0799084e98 | ||
|
|
c55ef964d9 | ||
|
|
2a513e71a4 | ||
|
|
3dfe4bdaaa | ||
|
|
65114575eb | ||
|
|
a7d5443125 | ||
|
|
5b519489c1 | ||
|
|
980471c818 | ||
|
|
9fd7075bea | ||
|
|
5b145fe646 | ||
|
|
01e97955f9 | ||
|
|
340f9951ac | ||
|
|
790e8d3fd6 | ||
|
|
214d3599d3 | ||
|
|
c6e1387f59 | ||
|
|
0b1f0cafee | ||
|
|
d4d8e097dd | ||
|
|
365d3e9e87 | ||
|
|
89e6f9a16e | ||
|
|
6d25ccc357 | ||
|
|
3ff6ce3c69 | ||
|
|
2e86dcf725 | ||
|
|
f25e415c7b | ||
|
|
a9bf8d76a7 | ||
|
|
6dd83c823d | ||
|
|
7c87d78ea2 | ||
|
|
753cb8cda8 | ||
|
|
5e9b7833ee | ||
|
|
52d74df4d1 | ||
|
|
46ce8cbe84 | ||
|
|
98f9e67b4d | ||
|
|
65b9ae7704 | ||
|
|
00c5572e8c | ||
|
|
3911e4c548 | ||
|
|
c8cc56be91 | ||
|
|
a2ff9cca27 | ||
|
|
e428b05224 | ||
|
|
f09e8345c6 | ||
|
|
0f7a64c596 | ||
|
|
7d6c55dedb | ||
|
|
e5dc98dcb2 | ||
|
|
567052bfb6 | ||
|
|
38db7e1493 | ||
|
|
923d0bd20c | ||
|
|
2d9ea0285c | ||
|
|
67b0cc0706 | ||
|
|
2dc59c9b51 | ||
|
|
0dd33bd7ec | ||
|
|
a2ffc7aadf | ||
|
|
25d7f62749 | ||
|
|
3a61debaa5 | ||
|
|
37f3dff677 | ||
|
|
9d11278d95 | ||
|
|
344ac7684e | ||
|
|
e9cde3e4b1 | ||
|
|
5b9236c76d | ||
|
|
ce7d388639 | ||
|
|
213eb4c23a | ||
|
|
cab666fca1 | ||
|
|
457277ec9a | ||
|
|
08f0ba5564 | ||
|
|
4527947afc | ||
|
|
0b78381513 | ||
|
|
5ec813b4f1 | ||
|
|
75ae33ade8 | ||
|
|
dd73fee077 | ||
|
|
506ce0850b | ||
|
|
6d08b08f37 | ||
|
|
5532a316c5 | ||
|
|
553bc5ab90 | ||
|
|
12627d376d | ||
|
|
a49cf11e16 | ||
|
|
b46946ece5 | ||
|
|
af7cf6ab8a | ||
|
|
cce3bab0e2 | ||
|
|
228e850da1 | ||
|
|
9f1e21e73f | ||
|
|
0cfca436f1 | ||
|
|
8aa57bef78 | ||
|
|
ee54fd6c08 | ||
|
|
33c36fc7a3 | ||
|
|
4f0322af86 | ||
|
|
1d8d9570eb | ||
|
|
2ec899bdee | ||
|
|
3fce1a938d | ||
|
|
2ff3dda7cd | ||
|
|
fb92d46e2d | ||
|
|
a8c8372b99 |
No files matched your search
@@ -27,7 +27,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.37.4
|
||||
uses: github/codeql-action/init@v4.37.6
|
||||
# Override language selection by uncommenting this and choosing your languages
|
||||
with:
|
||||
languages: go
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below).
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v4.37.4
|
||||
uses: github/codeql-action/autobuild@v4.37.6
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
@@ -49,4 +49,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4.37.4
|
||||
uses: github/codeql-action/analyze@v4.37.6
|
||||
@@ -367,7 +367,7 @@ jobs:
|
||||
output: trivy-results.sarif
|
||||
exit-code: '0'
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
uses: github/codeql-action/upload-sarif@v4.37.4
|
||||
uses: github/codeql-action/upload-sarif@v4.37.6
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
|
||||
@@ -400,7 +400,7 @@ jobs:
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v4.37.4
|
||||
uses: github/codeql-action/upload-sarif@v4.37.6
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
category: trivy-${{ matrix.variant }}
|
||||
|
||||
@@ -43,7 +43,10 @@ jobs:
|
||||
- name: Run EC Integration Tests
|
||||
working-directory: test/erasure_coding
|
||||
run: |
|
||||
go test -v
|
||||
# The suite now includes the interruption matrix and runs close to Go's
|
||||
# default 10m binary timeout on slower runners; bound it by the job's
|
||||
# 30m budget instead.
|
||||
go test -v -timeout 25m
|
||||
|
||||
- name: Collect server logs on failure
|
||||
if: failure()
|
||||
|
||||
@@ -111,6 +111,16 @@ jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
redis:
|
||||
image: redis:8
|
||||
ports:
|
||||
- 6379:6379
|
||||
options: >-
|
||||
--health-cmd "redis-cli ping"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v7
|
||||
@@ -119,6 +129,8 @@ jobs:
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
- name: Test
|
||||
env:
|
||||
RUN_REDIS_TESTS: "1"
|
||||
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
|
||||
|
||||
test-32bit:
|
||||
|
||||
@@ -1296,6 +1296,180 @@ jobs:
|
||||
PYEOF
|
||||
echo "NetworkPolicy rendering tests passed"
|
||||
|
||||
echo ""
|
||||
echo "=== Testing enterprise license mount + master persistence ==="
|
||||
python3 - "$CHART_DIR" <<'PYEOF'
|
||||
import subprocess, sys, yaml
|
||||
chart = sys.argv[1]
|
||||
|
||||
def render(values):
|
||||
args = ["helm", "template", "test", chart]
|
||||
for k, v in values.items():
|
||||
args += ["--set", f"{k}={v}"]
|
||||
return subprocess.check_output(args, text=True)
|
||||
|
||||
def workloads(manifest):
|
||||
for d in yaml.safe_load_all(manifest):
|
||||
if d and d.get("kind") in ("Deployment", "StatefulSet"):
|
||||
yield d
|
||||
|
||||
ALL_ON = {
|
||||
"admin.enabled": "true",
|
||||
"s3.enabled": "true",
|
||||
"sftp.enabled": "true",
|
||||
"worker.enabled": "true",
|
||||
}
|
||||
failed = []
|
||||
|
||||
# Case 1: unconfigured renders nothing, so existing installs are unaffected.
|
||||
out = render(ALL_ON)
|
||||
if "SEAWEED_LICENSE" in out or "seaweedfs-license" in out:
|
||||
failed.append("defaults: license plumbing should not render")
|
||||
else:
|
||||
print("defaults: no license volume/env (unchanged)")
|
||||
|
||||
# Case 2: only the workloads that run a master carry the license.
|
||||
LICENSE_PATH = "/etc/seaweedfs/license/seaweed-license.json"
|
||||
out = render(dict(ALL_ON, **{
|
||||
"global.seaweedfs.license.existingSecret": "lic",
|
||||
}))
|
||||
carrying = set()
|
||||
for d in workloads(out):
|
||||
name = d["metadata"]["name"]
|
||||
pod = d["spec"]["template"]["spec"]
|
||||
vols = [v for v in pod.get("volumes", []) if v.get("name") == "seaweedfs-license"]
|
||||
if not vols:
|
||||
continue
|
||||
carrying.add(name)
|
||||
secret = vols[0].get("secret", {})
|
||||
if secret.get("secretName") != "lic":
|
||||
failed.append(f"{name}: license volume points at {secret.get('secretName')!r}, not the configured Secret")
|
||||
items = [i.get("key") for i in secret.get("items", [])]
|
||||
if items != ["seaweed-license.json"]:
|
||||
failed.append(f"{name}: license volume projects {items}, expected only the license key")
|
||||
for c in pod.get("containers", []):
|
||||
mounts = [m for m in c.get("volumeMounts", []) if m["name"] == "seaweedfs-license"]
|
||||
if not mounts:
|
||||
failed.append(f"{name}/{c['name']}: license volume not mounted")
|
||||
continue
|
||||
# subPath would freeze the file at container start.
|
||||
if any("subPath" in m for m in mounts):
|
||||
failed.append(f"{name}/{c['name']}: license mount uses subPath (renewals would not propagate)")
|
||||
if not all(m.get("readOnly") for m in mounts):
|
||||
failed.append(f"{name}/{c['name']}: license mount is not readOnly")
|
||||
env = {e["name"]: e.get("value") for e in c.get("env", [])}
|
||||
if env.get("SEAWEED_LICENSE") != LICENSE_PATH:
|
||||
failed.append(f"{name}/{c['name']}: SEAWEED_LICENSE not set to the mounted file")
|
||||
if carrying != {"test-seaweedfs-master"}:
|
||||
failed.append(f"license: expected only the master to carry it, got {sorted(carrying)}")
|
||||
else:
|
||||
print("license: master only, key-scoped, readOnly, no subPath, SEAWEED_LICENSE set")
|
||||
|
||||
# all-in-one runs `weed server -master`, so it needs the license too.
|
||||
out = render({
|
||||
"allInOne.enabled": "true",
|
||||
"master.enabled": "false",
|
||||
"volume.enabled": "false",
|
||||
"filer.enabled": "false",
|
||||
"global.seaweedfs.license.existingSecret": "lic",
|
||||
})
|
||||
aio = [d for d in workloads(out) if d["metadata"]["name"].endswith("-all-in-one")]
|
||||
if len(aio) != 1:
|
||||
failed.append(f"all-in-one: expected 1 workload, got {len(aio)}")
|
||||
else:
|
||||
pod = aio[0]["spec"]["template"]["spec"]
|
||||
if not any(v.get("name") == "seaweedfs-license" for v in pod.get("volumes", [])):
|
||||
failed.append("all-in-one: missing the license volume")
|
||||
else:
|
||||
print("all-in-one: carries the license")
|
||||
|
||||
# SEAWEED_LICENSE is reserved on both env paths.
|
||||
out = render({
|
||||
"global.seaweedfs.license.existingSecret": "lic",
|
||||
"global.seaweedfs.extraEnvironmentVars.SEAWEED_LICENSE": "/tmp/bogus.json",
|
||||
})
|
||||
for d in workloads(out):
|
||||
if not d["metadata"]["name"].endswith("-master"):
|
||||
continue
|
||||
for c in d["spec"]["template"]["spec"].get("containers", []):
|
||||
names = [e["name"] for e in c.get("env", [])]
|
||||
if names.count("SEAWEED_LICENSE") != 1:
|
||||
failed.append(f"SEAWEED_LICENSE rendered {names.count('SEAWEED_LICENSE')} times")
|
||||
else:
|
||||
value = next(e.get("value") for e in c["env"] if e["name"] == "SEAWEED_LICENSE")
|
||||
if value != LICENSE_PATH:
|
||||
failed.append(f"SEAWEED_LICENSE overridden to {value!r} by extraEnvironmentVars")
|
||||
else:
|
||||
print("SEAWEED_LICENSE: reserved, rendered once, points at the mount")
|
||||
|
||||
# secretExtraEnvironmentVars is rendered outside the merge helper.
|
||||
out = render({
|
||||
"allInOne.enabled": "true",
|
||||
"master.enabled": "false",
|
||||
"volume.enabled": "false",
|
||||
"filer.enabled": "false",
|
||||
"global.seaweedfs.license.existingSecret": "lic",
|
||||
"allInOne.secretExtraEnvironmentVars.SEAWEED_LICENSE.secretKeyRef.name": "x",
|
||||
"allInOne.secretExtraEnvironmentVars.SEAWEED_LICENSE.secretKeyRef.key": "y",
|
||||
})
|
||||
for d in workloads(out):
|
||||
if not d["metadata"]["name"].endswith("-all-in-one"):
|
||||
continue
|
||||
for c in d["spec"]["template"]["spec"].get("containers", []):
|
||||
names = [e["name"] for e in c.get("env", [])]
|
||||
if names.count("SEAWEED_LICENSE") != 1:
|
||||
failed.append(f"all-in-one: SEAWEED_LICENSE rendered {names.count('SEAWEED_LICENSE')} times via secretExtraEnvironmentVars")
|
||||
elif next(e.get("value") for e in c["env"] if e["name"] == "SEAWEED_LICENSE") != LICENSE_PATH:
|
||||
failed.append("all-in-one: secretExtraEnvironmentVars overrode SEAWEED_LICENSE")
|
||||
else:
|
||||
print("all-in-one: SEAWEED_LICENSE reserved on the secret env path too")
|
||||
|
||||
# Case 3: the default stays hostPath. volumeClaimTemplates is immutable,
|
||||
# so growing one here would break helm upgrade on existing releases.
|
||||
masters = [d for d in workloads(render({})) if d["metadata"]["name"].endswith("-master")]
|
||||
if len(masters) != 1:
|
||||
failed.append(f"master: expected 1 StatefulSet by default, got {len(masters)}")
|
||||
else:
|
||||
d = masters[0]
|
||||
claims = [c["metadata"]["name"] for c in d["spec"].get("volumeClaimTemplates", [])]
|
||||
if any(c.startswith("data-") for c in claims):
|
||||
failed.append(f"master: default grew a data volumeClaimTemplate ({claims}); "
|
||||
"that breaks helm upgrade on existing releases")
|
||||
data_host = [v["name"] for v in d["spec"]["template"]["spec"].get("volumes", [])
|
||||
if v.get("hostPath") and v["name"].startswith("data-")]
|
||||
if not data_host:
|
||||
failed.append("master: default no longer renders a hostPath data volume")
|
||||
else:
|
||||
print("master: default still hostPath (upgrade-compatible)")
|
||||
|
||||
# Case 4: opting into a claim renders one, with the requested size.
|
||||
masters = [d for d in workloads(render({"master.data.type": "persistentVolumeClaim"}))
|
||||
if d["metadata"]["name"].endswith("-master")]
|
||||
if len(masters) != 1:
|
||||
failed.append(f"master.data.type=persistentVolumeClaim: expected 1 StatefulSet, got {len(masters)}")
|
||||
else:
|
||||
d = masters[0]
|
||||
claims = {c["metadata"]["name"]: c["spec"]["resources"]["requests"]["storage"]
|
||||
for c in d["spec"].get("volumeClaimTemplates", [])}
|
||||
data = {k: v for k, v in claims.items() if k.startswith("data-")}
|
||||
if not data:
|
||||
failed.append(f"master.data.type=persistentVolumeClaim: no data claim rendered ({claims})")
|
||||
elif set(data.values()) != {"1Gi"}:
|
||||
failed.append(f"master.data.type=persistentVolumeClaim: unexpected size {data}")
|
||||
else:
|
||||
print(f"master.data.type=persistentVolumeClaim: renders {sorted(data)} at 1Gi")
|
||||
if any(v.get("hostPath") and v["name"].startswith("data-")
|
||||
for v in d["spec"]["template"]["spec"].get("volumes", [])):
|
||||
failed.append("master.data.type=persistentVolumeClaim: data still on a hostPath")
|
||||
|
||||
if failed:
|
||||
print("\nFAIL:", file=sys.stderr)
|
||||
for f in failed:
|
||||
print(f" - {f}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PYEOF
|
||||
echo "License + master persistence tests passed"
|
||||
|
||||
echo "All template rendering tests passed!"
|
||||
|
||||
- name: Create kind cluster
|
||||
|
||||
@@ -8,6 +8,7 @@ on:
|
||||
- 'weed/pb/filer_pb/**'
|
||||
- 'weed/util/log_buffer/**'
|
||||
- 'weed/server/filer_grpc_server_sub_meta.go'
|
||||
- 'weed/server/master_grpc_server.go'
|
||||
- 'weed/command/filer_backup.go'
|
||||
- 'test/metadata_subscribe/**'
|
||||
- '.github/workflows/metadata-subscribe-tests.yml'
|
||||
@@ -18,6 +19,7 @@ on:
|
||||
- 'weed/pb/filer_pb/**'
|
||||
- 'weed/util/log_buffer/**'
|
||||
- 'weed/server/filer_grpc_server_sub_meta.go'
|
||||
- 'weed/server/master_grpc_server.go'
|
||||
- 'weed/command/filer_backup.go'
|
||||
- 'test/metadata_subscribe/**'
|
||||
- '.github/workflows/metadata-subscribe-tests.yml'
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
name: "mount: benchmark"
|
||||
|
||||
# Manual benchmark: native WinFsp mount vs rclone+WebDAV on the same Windows
|
||||
# runner, with a Linux FUSE mount of the same build as a reference. Numbers
|
||||
# from shared runners are noisy; this is for finding factor-of-N gaps, not
|
||||
# regressions of a few percent.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [ 'winfsp-bench**' ]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
bench-windows:
|
||||
name: Windows native vs rclone
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CGO_ENABLED: 0
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install WinFsp and rclone
|
||||
run: choco install winfsp rclone -y --no-progress
|
||||
|
||||
- name: Build weed.exe
|
||||
run: go build -o weed.exe ./weed
|
||||
|
||||
- name: Benchmark both mounts
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Test-Port($port) {
|
||||
$client = New-Object System.Net.Sockets.TcpClient
|
||||
try { $client.Connect('127.0.0.1', $port); return $client.Connected }
|
||||
catch { return $false }
|
||||
finally { $client.Dispose() }
|
||||
}
|
||||
|
||||
function Wait-Drive($drive, $what) {
|
||||
$deadline = (Get-Date).AddMinutes(2)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if (Test-Path "${drive}\") { Write-Host "$what is mounted on $drive"; return }
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
throw "$what never appeared on $drive"
|
||||
}
|
||||
|
||||
function Invoke-Bench($dir, $label, $out) {
|
||||
Write-Host "::group::bench $label"
|
||||
& go run ./test/mount_bench -dir $dir -label $label -filer 127.0.0.1:8888 -out $out
|
||||
$code = $LASTEXITCODE
|
||||
Write-Host "::endgroup::"
|
||||
if ($code -ne 0) { throw "bench $label failed with exit $code" }
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path C:\seaweed-data | Out-Null
|
||||
Start-Process -FilePath .\weed.exe `
|
||||
-ArgumentList '-logtostderr','mini','-dir=C:\seaweed-data','-ip=127.0.0.1' `
|
||||
-RedirectStandardOutput C:\seaweed-mini.log -RedirectStandardError C:\seaweed-mini.err.log
|
||||
|
||||
$deadline = (Get-Date).AddMinutes(3)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ((Test-Port 8888) -and (Test-Port 18888) -and (Test-Port 7333)) { break }
|
||||
Start-Sleep -Seconds 3
|
||||
}
|
||||
if (-not ((Test-Port 8888) -and (Test-Port 18888) -and (Test-Port 7333))) {
|
||||
Get-Content C:\seaweed-mini.log, C:\seaweed-mini.err.log -ErrorAction SilentlyContinue
|
||||
throw "mini cluster never came up"
|
||||
}
|
||||
Write-Host "filer on 8888/18888, webdav on 7333"
|
||||
|
||||
# --- native WinFsp mount ---
|
||||
Start-Process -FilePath .\weed.exe `
|
||||
-ArgumentList '-logtostderr','mount','-filer=127.0.0.1:8888','-dir=S:' `
|
||||
-RedirectStandardOutput C:\seaweed-mount.log -RedirectStandardError C:\seaweed-mount.err.log
|
||||
Wait-Drive 'S:' 'weed mount'
|
||||
|
||||
Invoke-Bench 'S:\bench-native' 'winfsp-native' 'C:\results-native.json'
|
||||
|
||||
Get-CimInstance Win32_Process -Filter "Name = 'weed.exe'" |
|
||||
Where-Object { $_.CommandLine -like '*mount*' } |
|
||||
ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
|
||||
$deadline = (Get-Date).AddMinutes(1)
|
||||
while ((Get-Date) -lt $deadline -and (Test-Path S:\)) { Start-Sleep -Seconds 2 }
|
||||
|
||||
# --- rclone + WebDAV on the same WinFsp ---
|
||||
# rclone serves listings from a directory cache it fills lazily, so the
|
||||
# big-listing files have to exist before it mounts or it never sees them.
|
||||
& go run ./test/mount_bench -filer 127.0.0.1:8888 -seed bench-rclone/biglist
|
||||
if ($LASTEXITCODE -ne 0) { throw "seeding failed" }
|
||||
|
||||
$env:RCLONE_CONFIG_SEAWEED_TYPE = 'webdav'
|
||||
$env:RCLONE_CONFIG_SEAWEED_URL = 'http://127.0.0.1:7333'
|
||||
$env:RCLONE_CONFIG_SEAWEED_VENDOR = 'other'
|
||||
Start-Process -FilePath rclone `
|
||||
-ArgumentList 'mount','seaweed:','T:','--vfs-cache-mode=writes','-v','--log-file=C:\rclone.log'
|
||||
Wait-Drive 'T:' 'rclone mount'
|
||||
|
||||
Invoke-Bench 'T:\bench-rclone' 'rclone-webdav' 'C:\results-rclone.json'
|
||||
|
||||
Stop-Process -Name rclone -Force -ErrorAction SilentlyContinue
|
||||
|
||||
# --- comparison ---
|
||||
$table = & go run ./test/mount_bench -compare C:\results-native.json,C:\results-rclone.json
|
||||
$table | Write-Host
|
||||
"## Windows: native WinFsp vs rclone+WebDAV" | Out-File -Append $env:GITHUB_STEP_SUMMARY
|
||||
$table | Out-File -Append $env:GITHUB_STEP_SUMMARY
|
||||
|
||||
- name: Logs
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
foreach ($f in 'C:\seaweed-mount.log','C:\seaweed-mount.err.log','C:\rclone.log','C:\seaweed-mini.log','C:\seaweed-mini.err.log') {
|
||||
if (Test-Path $f) { Write-Host "===== $f"; Get-Content $f -Tail 100 }
|
||||
}
|
||||
|
||||
- name: Results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: results-windows
|
||||
path: C:\results-*.json
|
||||
if-no-files-found: ignore
|
||||
|
||||
bench-linux:
|
||||
name: Linux FUSE reference
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Repair the fusermount3 setuid bit
|
||||
uses: ./.github/actions/fix-fusermount-setuid
|
||||
|
||||
- name: Allow non-root FUSE mounts with allow_other
|
||||
run: |
|
||||
echo 'user_allow_other' | sudo tee -a /etc/fuse.conf
|
||||
sudo chmod 644 /etc/fuse.conf
|
||||
|
||||
- name: Build weed
|
||||
run: go build -o /tmp/weed ./weed
|
||||
|
||||
- name: Benchmark FUSE mount
|
||||
run: |
|
||||
set -e
|
||||
mkdir -p /tmp/seaweed-data
|
||||
/tmp/weed -logtostderr mini -dir=/tmp/seaweed-data -ip=127.0.0.1 > /tmp/mini.log 2>&1 &
|
||||
|
||||
for i in $(seq 1 60); do
|
||||
if nc -z 127.0.0.1 8888 && nc -z 127.0.0.1 18888; then break; fi
|
||||
sleep 3
|
||||
done
|
||||
nc -z 127.0.0.1 8888 || { cat /tmp/mini.log; echo "filer never came up"; exit 1; }
|
||||
|
||||
mkdir -p "$HOME/mnt"
|
||||
/tmp/weed -logtostderr mount -filer=127.0.0.1:8888 -dir="$HOME/mnt" > /tmp/mount.log 2>&1 &
|
||||
for i in $(seq 1 60); do
|
||||
if mountpoint -q "$HOME/mnt"; then break; fi
|
||||
sleep 2
|
||||
done
|
||||
mountpoint -q "$HOME/mnt" || { cat /tmp/mount.log; echo "mount never appeared"; exit 1; }
|
||||
|
||||
go run ./test/mount_bench -dir "$HOME/mnt/bench-linux" -label linux-fuse -filer 127.0.0.1:8888 -out /tmp/results-linux.json
|
||||
|
||||
{
|
||||
echo "## Linux FUSE reference"
|
||||
go run ./test/mount_bench -compare /tmp/results-linux.json
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Logs
|
||||
if: always()
|
||||
run: |
|
||||
tail -n 100 /tmp/mount.log /tmp/mini.log 2>/dev/null || true
|
||||
|
||||
- name: Results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: results-linux
|
||||
path: /tmp/results-linux.json
|
||||
if-no-files-found: ignore
|
||||
@@ -353,6 +353,91 @@ jobs:
|
||||
path: test/s3tables/catalog_doris/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
clickhouse-iceberg-catalog-tests:
|
||||
name: ClickHouse Iceberg Catalog Integration Tests (${{ matrix.tag }})
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# Pinned baseline, and latest so new ClickHouse releases are
|
||||
# exercised without a code change.
|
||||
- clickhouse-image: clickhouse/clickhouse-server:25.8
|
||||
tag: "25.8"
|
||||
- clickhouse-image: clickhouse/clickhouse-server:latest
|
||||
tag: latest
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
id: go
|
||||
|
||||
- name: Configure Docker Hub mirror
|
||||
run: |
|
||||
echo '{"registry-mirrors": ["https://mirror.gcr.io"]}' | sudo tee /etc/docker/daemon.json
|
||||
sudo systemctl restart docker
|
||||
|
||||
- name: Pre-pull images
|
||||
run: |
|
||||
pull() { for i in 1 2 3; do docker pull "$1" && return 0; sleep 15; done; return 1; }
|
||||
pull ${{ matrix.clickhouse-image }}
|
||||
pull python:3.11-slim
|
||||
|
||||
- name: Run go mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
go install -buildvcs=false ./weed
|
||||
|
||||
- name: Run ClickHouse Iceberg Catalog Integration Tests
|
||||
timeout-minutes: 25
|
||||
working-directory: test/s3tables/catalog_clickhouse
|
||||
env:
|
||||
CLICKHOUSE_IMAGE: ${{ matrix.clickhouse-image }}
|
||||
run: |
|
||||
set -x
|
||||
set -o pipefail
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
docker info
|
||||
echo "=== Starting ClickHouse Iceberg Catalog Tests ==="
|
||||
|
||||
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
|
||||
echo "ClickHouse Iceberg catalog integration tests failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Show test output on failure
|
||||
if: failure()
|
||||
working-directory: test/s3tables/catalog_clickhouse
|
||||
run: |
|
||||
echo "=== Test Output ==="
|
||||
if [ -f test-output.log ]; then
|
||||
tail -200 test-output.log
|
||||
fi
|
||||
|
||||
echo "=== Process information ==="
|
||||
ps aux | grep -E "(weed|test|docker|clickhouse)" || true
|
||||
echo "=== ClickHouse containers ==="
|
||||
docker ps -a --filter "name=seaweed-clickhouse" || true
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: clickhouse-iceberg-catalog-test-logs-${{ matrix.tag }}
|
||||
path: test/s3tables/catalog_clickhouse/test-output.log
|
||||
retention-days: 3
|
||||
|
||||
polaris-integration-tests:
|
||||
name: Polaris Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
@@ -61,7 +61,7 @@ Table of Contents
|
||||
* [Features](#features)
|
||||
* [Additional Features](#additional-features)
|
||||
* [Filer Features](#filer-features)
|
||||
* [Example: Using Seaweed Object Store](#example-using-seaweed-object-store)
|
||||
* [Example: Using Seaweed Blob Store](#example-using-seaweed-blob-store)
|
||||
* [Architecture](#object-store-architecture)
|
||||
* [Compared to Other File Systems](#compared-to-other-file-systems)
|
||||
* [Compared to HDFS](#compared-to-hdfs)
|
||||
|
||||
@@ -11,7 +11,6 @@ require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bwmarrin/snowflake v0.3.0
|
||||
github.com/cenkalti/backoff/v4 v4.3.0
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.6.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
@@ -50,7 +49,7 @@ require (
|
||||
github.com/kurin/blazer v0.5.3
|
||||
github.com/linxGnu/grocksdb v1.10.8
|
||||
github.com/mailru/easyjson v0.9.2 // indirect
|
||||
github.com/mattn/go-isatty v0.0.23 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/olivere/elastic/v7 v7.0.32
|
||||
@@ -108,11 +107,11 @@ require (
|
||||
modernc.org/b v1.0.0 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
modernc.org/sqlite v1.53.0
|
||||
modernc.org/sqlite v1.56.0
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/kms v1.31.0
|
||||
cloud.google.com/go/kms v1.33.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
@@ -123,10 +122,11 @@ require (
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
|
||||
github.com/arangodb/go-driver v1.6.9
|
||||
github.com/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.43.2
|
||||
github.com/aws/aws-sdk-go-v2 v1.43.4
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.33
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.32
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.34
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.105.2
|
||||
github.com/cespare/xxhash/v2 v2.3.0
|
||||
github.com/cognusion/imaging v1.0.4
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
github.com/getsentry/sentry-go v0.44.1
|
||||
@@ -156,7 +156,7 @@ require (
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.146.3
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.147.1
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.12
|
||||
go.uber.org/atomic v1.11.0
|
||||
golang.org/x/sync v0.22.0
|
||||
@@ -183,7 +183,7 @@ require (
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
github.com/apache/arrow-go/v18 v18.7.0 // indirect
|
||||
github.com/apache/thrift v0.24.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.5.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.5.4 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/bazelbuild/rules_go v0.46.0 // indirect
|
||||
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
|
||||
@@ -322,21 +322,21 @@ require (
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.33 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.33 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.33 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.34 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.33 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.33.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.45.2
|
||||
github.com/aws/smithy-go v1.27.5
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.33.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.45.4
|
||||
github.com/aws/smithy-go v1.27.6
|
||||
github.com/boltdb/bolt v1.3.1 // indirect
|
||||
github.com/bradenaw/juniper v0.15.3 // indirect
|
||||
github.com/buengese/sgzip v0.1.1 // indirect
|
||||
@@ -436,7 +436,7 @@ require (
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.27
|
||||
github.com/pierrec/lz4/v4 v4.1.28
|
||||
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
|
||||
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
|
||||
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
|
||||
@@ -502,7 +502,7 @@ require (
|
||||
gopkg.in/validator.v2 v2.0.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.73.4 // indirect
|
||||
modernc.org/libc v1.74.4 // indirect
|
||||
moul.io/http2curl/v2 v2.3.0 // indirect
|
||||
sigs.k8s.io/yaml v1.6.0 // indirect
|
||||
storj.io/common v0.0.0-20260629224719-ba1bff0a7846 // indirect
|
||||
|
||||
@@ -298,8 +298,8 @@ cloud.google.com/go/kms v1.4.0/go.mod h1:fajBHndQ+6ubNw6Ss2sSd+SWvjL26RNo/dr7uxs
|
||||
cloud.google.com/go/kms v1.5.0/go.mod h1:QJS2YY0eJGBg3mnDfuaCyLauWwBJiHRboYxJ++1xJNg=
|
||||
cloud.google.com/go/kms v1.6.0/go.mod h1:Jjy850yySiasBUDi6KFUwUv2n1+o7QZFyuUJg6OgjA0=
|
||||
cloud.google.com/go/kms v1.9.0/go.mod h1:qb1tPTgfF9RQP8e1wq4cLFErVuTJv7UsSC915J8dh3w=
|
||||
cloud.google.com/go/kms v1.31.0 h1:LS8N92OxFDgOLg5NCo3OmbvjtQAIVT5gUHVLKIDHaFE=
|
||||
cloud.google.com/go/kms v1.31.0/go.mod h1:YIyXZym11R5uovJJt4oN5eUL3oPmirF3yKeIh6QAf4U=
|
||||
cloud.google.com/go/kms v1.33.0 h1:pG0X78m212b2pv9N4fdMoUO69LuZGQ9kSvn8sHBOFAo=
|
||||
cloud.google.com/go/kms v1.33.0/go.mod h1:CSGvW6GnMQbY+1nOHcIzhMtHSbExXlOmCKjWtYVjcpA=
|
||||
cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic=
|
||||
cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI=
|
||||
cloud.google.com/go/language v1.7.0/go.mod h1:DJ6dYN/W+SQOjF8e1hLQXMF21AkH2w9wiPzPCJa2MIE=
|
||||
@@ -707,50 +707,50 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+
|
||||
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
|
||||
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.43.2 h1:cl+IXwWb3qazClUcm08tGSsB6OiuV83JVJO9B0jQcPc=
|
||||
github.com/aws/aws-sdk-go-v2 v1.43.2/go.mod h1:WEzLKBh/mEjXvx1FtQMWgSxMSTVqxQzjkRtk5fa3wkg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.43.4 h1:b9FTvbRwy+JCsfp2Wp6wV/KbOx3Aj7nkoFb2cRX0IhE=
|
||||
github.com/aws/aws-sdk-go-v2 v1.43.4/go.mod h1:70vwSy16txshwG+g55WkpgPKDIByzHI8ccBsOteo3bQ=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 h1:3IZY0XAJquT3aHzbkHfPzy4ACPcEjVG0x87KOwtpqGY=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14/go.mod h1:zwM6veDkhGgQFqkBy+uT28AAYpLu+uFMlPl+rCg/73E=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.33 h1:M1m/Q6f0OKDEDGwhiNOqx1OjTdrewe3v+GDbHmKczWk=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.33/go.mod h1:fGj1iQj2QpIZzp7jE4aQQ+71TE8cd4z9K4+xCd6EqmE=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.32 h1:eNE0JnIblBo1NCvd3tqEYuZz9XDefn69R74CHd3nT7U=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.32/go.mod h1:yYJu+6tqKUYZuJSYcpSGjz/6sV/SUaAaKIufnWKx2OU=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.33 h1:MobhiR6KIerWxmO74Zit5I3379+mSc2DOdZ3DeRFB9w=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.33/go.mod h1:xu02847OdZfNr/jAfZpHtyRk0b3v4d0kaoxNHxZGG/w=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.34 h1:y6GkSmcv5myd1ngrYbGmiLlwQqB6TQhOuN/tbSSuWDY=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.34/go.mod h1:w3dTcnDVoQIewjo7JG45hduAToikiIFLC4FIO7fndvw=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35 h1:+S7kbJoLDDQ5tE+lHrUBgMkzC8NLgsaioS2F3dVoFAE=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35/go.mod h1:Ak7xXviIARfFdNUJ9Etb0bdVDt/KAvKjMGJVLWXDzik=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 h1:Pn7OsMwBLbkZ6OnCxWHAjf0L/22H8cnhxZC0uPwtMtg=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34/go.mod h1:eToXR/Gk1uqpn04eSmdgVXwfS0WvH8aG4eBFr8ygbpU=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 h1:w5OoDiMN6x53ROmiIImGzmVcxXv2q1GXY+aKV4WAJYM=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3/go.mod h1:dAhgYp776bX3LuWvnSCFwQEjNs6fuFg7YXIy5PXcP3Q=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.33 h1:HAp1wLFZzch054uh3FK7rcVYg4v7J2FxVf3h3IGNZas=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.33/go.mod h1:mJk5fmqnF+WUlMdPG37pR2Fh3oh6r8F6ZGUgPKvzu0c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.33 h1:0YA0aCKgsJyno6xkFfaIgjE3/wK08+Qxo9nQfe1UrWM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.33/go.mod h1:UZqj4WIdTH+ga8Y/DgpAuy/8cGjM3h7gDCliJYGg2SE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.34 h1:HQYnjFnXpX8EbPW5M1QT8mXzesRPwly0HEPTcFlS02Y=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.34/go.mod h1:tGzj56niKYZBbDIRhwPGDqrULzmWv5b6uBQGqyNaFZw=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.14 h1:SA43nfaY7+1jjMNIc2ywu99JLJLButtIdLP6j+bT870=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.14/go.mod h1:Du3llKcwbQvHsTXSLzTOGQz0DTDBMEzdg7DAGu7inrY=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35 h1:kzVuGlatQtYinwBJEEyLAbggepCoavosiaHHX9+fD+c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35/go.mod h1:0yLx0yEI+SfqeJMPvOtIEFoZbiQYXMGszBueiutQyaI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35 h1:WK6CjihTuLisCjSKKbildJ79sGZZgbBz3iNa7VsKIhU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35/go.mod h1:KYleN57luLoe97R7vTnx8PMcVrr9gAcRECtOjl91DNg=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36 h1:jbGY4CXLzZElOXgGsexlC3Hi+3YM0rSmk4opFXKqg/k=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36/go.mod h1:uBu/9aKsS/UQGc72RAt3y54kjgYQxmhut8ZD2dXCDNE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15 h1:JJLBQxwY+AFwuPAi5ivGc1ChnTdUt4cXMv7e76m2c/Y=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15/go.mod h1:lQknBIe78MVL0cQOQDlag8KGflMbMEVFx9mB6O8ENvk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23 h1:9Fjh6fi/U5JEStVZijmaMpUwE/gvBJj7x2B/PjbO9To=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23/go.mod h1:iMoT2f1tClxrWAAnKCXjZQ6LOmfLrMG14wmnWpM+F14=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.33 h1:mqI7OrxN/DUH85F5OqVn3cIfuZ3+HVcebUm2N8mLlgQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.33/go.mod h1:eZ5jdEpvaaOU8nWWE4cTAJETSEA5FZoWxvNRao4piHY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35 h1:BBEElKh4a+rKshvjrfpajTe9CbpZvrbb4Jkg2PB7RzA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35/go.mod h1:zaZk983w//8beSruBVec/mr4CmDwgZitW/qzGhAAX0g=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31 h1:uao4A3QZ5UmB326V6KF+qRpv9Tjz7IlnlnTbbANntlU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31/go.mod h1:I/1+z0VwL1GhQyLgkoHDlygpUZ+iTAwOQ/NsftiUL2I=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.105.2 h1:5C00eQYpTrgQXnp6V3P6P7zPElna3AXvlukbANE6nJI=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.105.2/go.mod h1:zdmCoFO/dSI7GlrwsPqFJI+WlFnSU4Tc8TJnlXrM1Do=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.5.2 h1:EjI1CZzDcBxPkTa3j1BdtIrUDbqnOGssFMeyUS+6W0I=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.5.2/go.mod h1:vN3eb5H8MEAZ4dx0F5Wc9LT8eb3eW7bZZ5BjGJdbw9k=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.5.4 h1:cOJELVNrq5Q3Udry2GLuHUM7MhwpeaQRdYaoa6GI/yI=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.5.4/go.mod h1:f4LxzKBtaTxD7xh3PiVg3CE1tchQemfmghaJr+NbK2c=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 h1:p8WdWDh5AwSZdp19Haa3XMyPCICi9Z375a/Nu3IIEZY=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14/go.mod h1:NKVY7DER6VXHkt2I/ycmHakALNboi3Rqwt4eEf/1Cnk=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 h1:JP2wjWGmUp8lTCZb13Dv0Eciyc1jbO8pd0HZVMHFlrc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24/go.mod h1:Ql9ziDutk8ERAN9HMaYANCW3lop451ppebkxEJMLCTM=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.33.2 h1:zMP1FDFE08L7sM5f1QqkH/ZgKKg8Uc0Dz7KhSSYqWkw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.33.2/go.mod h1:0LoIZSUKjdo2BleHfT1hv/jlD33LQS00IrBlzoUsoUQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.2 h1:9eTqUYl+SyVmaRPMyBXSO9wwqC6TRwZB82pKENK2hdQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.2/go.mod h1:DThweuz22kiLc7lGHop5vQ9c3bx5W6Azs/YqSHa2fu8=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.45.2 h1:EJd8vZO3E8SE6nmPqxuxlQ1NeSb8as50sf6eGdV4Saw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.45.2/go.mod h1:OgpPvKzsO2Ranjpli/20djMkg6UrV5mw4W3pZpq1Mqo=
|
||||
github.com/aws/smithy-go v1.27.5 h1:d1ro7KpYOYwP6m73YFa+Kc/A130VsAdX68SpsJwARMM=
|
||||
github.com/aws/smithy-go v1.27.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.33.4 h1:AMW7a7S8iQaHjBYZdU3PCq4GKRPijTPRAc7e6XtEThY=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.33.4/go.mod h1:QQNsFV1DVXoXcZt18FS8lI8rtUrlDyAuWZLQ5shunv4=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4 h1:AsbZcJAQPRmHDJG8K1N0pof/1zPWjVT8TFlTWuGLSvo=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4/go.mod h1:6imqztH0//t0mKbl6yWl7swSEl7F/w32oAmqB3vP1ag=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.45.4 h1:w/AryDYMjSUANSQ2uoZxJovUsMTwWJNTv3IMex30Y+4=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.45.4/go.mod h1:WeBiAa67azG7Su9Vf+ChGDBLiAozJCXzdjXiPBUwtbc=
|
||||
github.com/aws/smithy-go v1.27.6 h1:0zjT8jgK3jbrTT7JJ3EE6JsMhX8JTrZ+f1sEndYDXrA=
|
||||
github.com/aws/smithy-go v1.27.6/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
|
||||
@@ -1236,8 +1236,8 @@ github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLe
|
||||
github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
@@ -1511,8 +1511,8 @@ github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stg
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=
|
||||
@@ -1659,8 +1659,8 @@ github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2
|
||||
github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI=
|
||||
github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI=
|
||||
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk=
|
||||
github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pierrec/lz4/v4 v4.1.28 h1:pPEPwRJ4kybBTfGt28q7lQsRJQHhC08axprdLD5Ppio=
|
||||
github.com/pierrec/lz4/v4 v4.1.28/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pierrre/compare v1.0.2 h1:k4IUsHgh+dbcAOIWCfxVa/7G6STjADH2qmhomv+1quc=
|
||||
github.com/pierrre/compare v1.0.2/go.mod h1:8UvyRHH+9HS8Pczdd2z5x/wvv67krDwVxoOndaIIDVU=
|
||||
github.com/pierrre/geohash v1.0.0 h1:f/zfjdV4rVofTCz1FhP07T+EMQAvcMM2ioGZVt+zqjI=
|
||||
@@ -2036,8 +2036,8 @@ github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2 h1:e2nGQPGC5OEPBWlMnLPFpd
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2/go.mod h1:9YzkhlIymWaJGX6KMU3vh5sOf3UKbCXkG/ZdjaI3zNM=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.44.0/go.mod h1:oSLwnuilwIpaF5bJJMAofnGgzPJusoI3zWMNb8I+GnM=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.47.3/go.mod h1:bWnOIcUHd7+Sl7DN+yhyY1H/I61z53GczvwJgXMgvj0=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.146.3 h1:0ybsLjWJ25M8XXGXk7NfjhO+s8bqBcGGWt8iB2DQiHQ=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.146.3/go.mod h1:b9NEO6mgaiqsnOMkS003uS82XsKh6GL+ZTFfPqXWz+c=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.147.1 h1:WRxyl1UdFD6EmFlujwrHm4sX9ktYb/adZ/SW+WWNOEg=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.147.1/go.mod h1:b9NEO6mgaiqsnOMkS003uS82XsKh6GL+ZTFfPqXWz+c=
|
||||
github.com/ydb-platform/ydb-go-yc v0.12.1 h1:qw3Fa+T81+Kpu5Io2vYHJOwcrYrVjgJlT6t/0dOXJrA=
|
||||
github.com/ydb-platform/ydb-go-yc v0.12.1/go.mod h1:t/ZA4ECdgPWjAb4jyDe8AzQZB5dhpGbi3iCahFaNwBY=
|
||||
github.com/ydb-platform/ydb-go-yc-metadata v0.6.1 h1:9E5q8Nsy2RiJMZDNVy0A3KUrIMBPakJ2VgloeWbcI84=
|
||||
@@ -2915,23 +2915,23 @@ modernc.org/b v1.0.0/go.mod h1:uZWcZfRj1BpYzfN9JTerzlNUnnPsV9O2ZA8JsRcubNg=
|
||||
modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
|
||||
modernc.org/cc/v3 v3.36.2/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
|
||||
modernc.org/cc/v3 v3.36.3/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
|
||||
modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c=
|
||||
modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
|
||||
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v3 v3.0.0-20220428102840-41399a37e894/go.mod h1:eI31LL8EwEBKPpNpA4bU1/i+sKOwOrQy8D87zWUcRZc=
|
||||
modernc.org/ccgo/v3 v3.0.0-20220430103911-bc99d88307be/go.mod h1:bwdAnOoaIt8Ax9YdWGjxWsdkPcZyRPHqrOvJxaKAKGw=
|
||||
modernc.org/ccgo/v3 v3.16.4/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ=
|
||||
modernc.org/ccgo/v3 v3.16.6/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ=
|
||||
modernc.org/ccgo/v3 v3.16.8/go.mod h1:zNjwkizS+fIFDrDjIAgBSCLkWbJuHF+ar3QRn+Z9aws=
|
||||
modernc.org/ccgo/v3 v3.16.9/go.mod h1:zNMzC9A9xeNUepy6KuZBbugn3c0Mc9TeiJO4lgvkJDo=
|
||||
modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws=
|
||||
modernc.org/ccgo/v4 v4.34.4/go.mod h1:qdKqE8FNIYyysougB1RX9MxCzp5oJOcQXSobANJ4TuE=
|
||||
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
|
||||
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
|
||||
modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc=
|
||||
modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=
|
||||
@@ -2942,8 +2942,8 @@ modernc.org/libc v1.16.17/go.mod h1:hYIV5VZczAmGZAnG15Vdngn5HSF5cSkbvfz2B7GRuVU=
|
||||
modernc.org/libc v1.16.19/go.mod h1:p7Mg4+koNjc8jkqwcoFBJx7tXkpj00G77X7A72jXPXA=
|
||||
modernc.org/libc v1.17.0/go.mod h1:XsgLldpP4aWlPlsjqKRdHPqCxCjISdHfM/yeWC5GyW0=
|
||||
modernc.org/libc v1.17.1/go.mod h1:FZ23b+8LjxZs7XtFMbSzL/EhPxNbfZbErxEHc7cbD9s=
|
||||
modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
|
||||
modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
|
||||
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
|
||||
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
|
||||
modernc.org/mathutil v1.1.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
@@ -2962,8 +2962,8 @@ modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.18.1/go.mod h1:6ho+Gow7oX5V+OiOQ6Tr4xeqbx13UZ6t+Fw9IRUG4d4=
|
||||
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
|
||||
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
|
||||
modernc.org/sqlite v1.56.0 h1:/D8e2RfFqoy/Zc6PuC76U28zFwmI/sYx1Kjm4yEn9e0=
|
||||
modernc.org/sqlite v1.56.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
|
||||
modernc.org/strutil v1.1.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs=
|
||||
modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw=
|
||||
modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.41"
|
||||
appVersion: "4.42"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.41.0
|
||||
version: 4.42.0
|
||||
@@ -107,6 +107,120 @@ https://github.com/rancher/local-path-provisioner
|
||||
you can use ANY storage class you like, just update the correct storage-class
|
||||
for your deployment.
|
||||
|
||||
### Master data: hostPath vs a claim
|
||||
|
||||
The master's `-mdir` holds its Raft log and snapshots, and with them the
|
||||
cluster's identity (its topology UUID). `master.data.type` defaults to
|
||||
`hostPath`, which does not follow a pod to another node: a master that is
|
||||
rescheduled comes back with an empty data directory and a brand new cluster
|
||||
UUID. With the chart's default of a single master replica there is no peer to
|
||||
recover the identity from either.
|
||||
|
||||
Putting the master's data on a claim avoids that:
|
||||
|
||||
```yaml
|
||||
master:
|
||||
data:
|
||||
type: "persistentVolumeClaim"
|
||||
size: "1Gi"
|
||||
storageClass: "" # empty uses the cluster's default StorageClass
|
||||
```
|
||||
|
||||
Raft state is small, so a modest claim is enough — sizing matters far more for
|
||||
volume and filer.
|
||||
|
||||
The default is left at `hostPath` for backward compatibility:
|
||||
`volumeClaimTemplates` is immutable on a StatefulSet, so flipping the type on a
|
||||
release that already exists fails, whether the chart changes the default or you
|
||||
change it yourself:
|
||||
|
||||
```text
|
||||
StatefulSet.apps "<release>-seaweedfs-master" is invalid: spec: Forbidden:
|
||||
updates to statefulset spec for fields other than 'replicas', ... are forbidden
|
||||
```
|
||||
|
||||
New installs can set the claim from the start. To move an **existing** release
|
||||
onto a claim without losing the cluster UUID, use the migration below. The
|
||||
claim has to be seeded while the master is stopped: a running master rewrites
|
||||
its Raft state, so copying into a live pod is silently undone by the next
|
||||
restart.
|
||||
|
||||
The steps below are for the chart's default of a single master
|
||||
(`master.replicas: 1`). With several master replicas, repeat steps 1, 3 and 4
|
||||
for every ordinal, or migrate one at a time and let the remaining quorum
|
||||
re-replicate.
|
||||
|
||||
Take the names from the cluster rather than assembling them — the release
|
||||
name, `nameOverride` and `fullnameOverride` all feed the chart's fullname
|
||||
helper, so `<release>-seaweedfs` is not always right:
|
||||
|
||||
```bash
|
||||
NS=<namespace>; REL=<release>
|
||||
# scope by instance as well as component: several releases can share a namespace
|
||||
STS=$(kubectl -n $NS get sts \
|
||||
-l app.kubernetes.io/instance=$REL,app.kubernetes.io/component=master \
|
||||
-o jsonpath='{.items[0].metadata.name}')
|
||||
POD=$STS-0
|
||||
# a StatefulSet names its claims <template>-<statefulset>-<ordinal>, and this
|
||||
# chart's template is data-<namespace>
|
||||
PVC=data-$NS-$STS-0
|
||||
|
||||
# 1. back up the master data directory
|
||||
kubectl -n $NS cp $POD:/data ./master-backup
|
||||
|
||||
# 2. stop the master, leaving the rest of the release running
|
||||
kubectl -n $NS delete sts $STS --cascade=orphan
|
||||
kubectl -n $NS delete pod $POD
|
||||
|
||||
# 3. create the claim the new StatefulSet will adopt, and seed it through a
|
||||
# pod that actually mounts it
|
||||
kubectl -n $NS apply -f - <<EOF
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: $PVC
|
||||
spec:
|
||||
accessModes: ["ReadWriteOnce"]
|
||||
resources:
|
||||
requests:
|
||||
storage: 1Gi
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: seed
|
||||
spec:
|
||||
containers:
|
||||
- name: seed
|
||||
image: alpine:3.20
|
||||
command: ["sleep", "600"]
|
||||
volumeMounts:
|
||||
- name: d
|
||||
mountPath: /data
|
||||
volumes:
|
||||
- name: d
|
||||
persistentVolumeClaim:
|
||||
claimName: $PVC
|
||||
EOF
|
||||
kubectl -n $NS wait --for=condition=Ready pod/seed --timeout=120s
|
||||
kubectl -n $NS cp ./master-backup/m9333 seed:/data/
|
||||
kubectl -n $NS exec seed -- ls /data/m9333 # conf, log, snapshot, state
|
||||
kubectl -n $NS delete pod seed
|
||||
|
||||
# 4. upgrade; the StatefulSet adopts the claim you created
|
||||
helm upgrade $REL seaweedfs/seaweedfs -n $NS -f values.yaml
|
||||
```
|
||||
|
||||
Confirm the UUID survived — it must match what the cluster reported before the
|
||||
migration:
|
||||
|
||||
```bash
|
||||
kubectl -n $NS exec $POD -- curl -s localhost:9333/license/status
|
||||
```
|
||||
|
||||
**Or accept a new cluster UUID** and, if you run the enterprise edition, have
|
||||
the license re-issued against it.
|
||||
|
||||
## current instances config (AIO):
|
||||
|
||||
1 instance for each type (master/filer+s3/volume)
|
||||
@@ -426,3 +540,38 @@ helm install seaweedfs seaweedfs/seaweedfs \
|
||||
|
||||
For enterprise users, please visit [seaweedfs.com](https://seaweedfs.com) for the SeaweedFS Enterprise Edition,
|
||||
which has advanced features, including data recovery, self-healing storage, customizable erasure coding, EC vacuum and repair, etc.
|
||||
|
||||
To run it, set the image and point the chart at a Secret holding the license
|
||||
file:
|
||||
|
||||
```bash
|
||||
kubectl create secret generic seaweedfs-license -n <namespace> \
|
||||
--from-file=seaweed-license.json=/path/to/seaweed-license.json
|
||||
```
|
||||
|
||||
```yaml
|
||||
global:
|
||||
seaweedfs:
|
||||
image:
|
||||
name: chrislusf/seaweedfs-enterprise
|
||||
license:
|
||||
existingSecret: seaweedfs-license
|
||||
# secretKey: seaweed-license.json # key within the Secret
|
||||
# mountPath: /etc/seaweedfs/license # directory it is mounted at
|
||||
```
|
||||
|
||||
Set the image globally rather than per component: a per-component
|
||||
`imageOverride` wins, and a cluster that mixes editions comes up looking
|
||||
healthy with enterprise features quietly off.
|
||||
|
||||
Only the master reads the license, so the Secret is mounted read-only there
|
||||
and on all-in-one (which runs `weed server -master`). It is mounted as a
|
||||
directory, not a `subPath`, so a renewed Secret reaches the running master —
|
||||
which re-reads the file periodically — without a restart.
|
||||
|
||||
The license is tied to the cluster UUID kept in the master's Raft state, so put
|
||||
`master.data` on a claim — a master that restarts onto an empty data directory
|
||||
generates a new UUID and the license stops matching. See
|
||||
[Master data](#master-data-hostpath-vs-a-claim). Check the binding with
|
||||
`kubectl exec <master-pod> -- curl -s localhost:9333/license/status`
|
||||
(`cluster_uuid` must equal `license_uuid`).
|
||||
@@ -69,6 +69,9 @@ spec:
|
||||
{{- if .Values.admin.priorityClassName }}
|
||||
priorityClassName: {{ .Values.admin.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.admin.schedulerName }}
|
||||
schedulerName: {{ .Values.admin.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
{{- if .Values.admin.serviceAccountName }}
|
||||
serviceAccountName: {{ .Values.admin.serviceAccountName | quote }}
|
||||
|
||||
@@ -64,6 +64,9 @@ spec:
|
||||
{{- if .Values.allInOne.priorityClassName }}
|
||||
priorityClassName: {{ .Values.allInOne.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.allInOne.schedulerName }}
|
||||
schedulerName: {{ .Values.allInOne.schedulerName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.allInOne.serviceAccountName }}
|
||||
serviceAccountName: {{ .Values.allInOne.serviceAccountName | quote }}
|
||||
{{- end }}
|
||||
@@ -80,6 +83,7 @@ spec:
|
||||
image: {{ template "seaweedfs.master.image" . }}
|
||||
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
|
||||
env:
|
||||
{{- include "seaweedfs.licenseEnv" . | nindent 12 }}
|
||||
{{- /* 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) }}
|
||||
@@ -120,11 +124,13 @@ spec:
|
||||
value: {{ include "seaweedfs.cluster.filerAddress" . | quote }}
|
||||
{{- if .Values.allInOne.secretExtraEnvironmentVars }}
|
||||
{{- range $key, $value := .Values.allInOne.secretExtraEnvironmentVars }}
|
||||
{{- if not (and $key (eq $key "SEAWEED_LICENSE") (include "seaweedfs.licenseEnabled" $)) }}
|
||||
- name: {{ $key }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
command:
|
||||
- "/bin/sh"
|
||||
- "-ec"
|
||||
@@ -352,6 +358,7 @@ spec:
|
||||
{{- include "seaweedfs.s3.tlsVolumeMount" . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.licenseVolumeMount" . | nindent 12 }}
|
||||
{{ tpl .Values.allInOne.extraVolumeMounts . | nindent 12 }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.master.port }}
|
||||
@@ -419,6 +426,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.allInOne.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.licenseVolume" . | nindent 8 }}
|
||||
- name: data
|
||||
{{- if eq .Values.allInOne.data.type "hostPath" }}
|
||||
hostPath:
|
||||
|
||||
@@ -57,6 +57,9 @@ spec:
|
||||
{{- if .Values.cosi.priorityClassName }}
|
||||
priorityClassName: {{ .Values.cosi.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.cosi.schedulerName }}
|
||||
schedulerName: {{ .Values.cosi.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
serviceAccountName: {{ include "seaweedfs.componentName" (list . "objectstorage-provisioner") }}
|
||||
{{- if .Values.cosi.initContainers }}
|
||||
|
||||
@@ -76,6 +76,9 @@ spec:
|
||||
{{- if .Values.filer.priorityClassName }}
|
||||
priorityClassName: {{ .Values.filer.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.filer.schedulerName }}
|
||||
schedulerName: {{ .Values.filer.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
{{- if .Values.filer.initContainers }}
|
||||
initContainers:
|
||||
|
||||
@@ -69,6 +69,9 @@ spec:
|
||||
{{- if .Values.master.priorityClassName }}
|
||||
priorityClassName: {{ .Values.master.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.master.schedulerName }}
|
||||
schedulerName: {{ .Values.master.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
serviceAccountName: {{ .Values.master.serviceAccountName | default (include "seaweedfs.serviceAccountName" .) | quote }} # for deleting statefulset pods after migration
|
||||
{{- if .Values.master.initContainers }}
|
||||
@@ -83,6 +86,7 @@ spec:
|
||||
image: {{ template "seaweedfs.master.image" . }}
|
||||
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
|
||||
env:
|
||||
{{- include "seaweedfs.licenseEnv" . | nindent 12 }}
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
@@ -211,6 +215,7 @@ spec:
|
||||
readOnly: true
|
||||
mountPath: /usr/local/share/ca-certificates/client/
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.licenseVolumeMount" . | nindent 12 }}
|
||||
{{ tpl .Values.master.extraVolumeMounts . | nindent 12 | trim }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.master.port }}
|
||||
@@ -256,6 +261,7 @@ spec:
|
||||
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.master.sidecars "context" $) | nindent 8 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
{{- include "seaweedfs.licenseVolume" . | nindent 8 }}
|
||||
{{- if eq .Values.master.logs.type "hostPath" }}
|
||||
- name: seaweedfs-master-log-volume
|
||||
hostPath:
|
||||
|
||||
@@ -61,6 +61,9 @@ spec:
|
||||
{{- if .Values.s3.priorityClassName }}
|
||||
priorityClassName: {{ .Values.s3.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.s3.schedulerName }}
|
||||
schedulerName: {{ .Values.s3.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
{{- if .Values.s3.serviceAccountName }}
|
||||
serviceAccountName: {{ .Values.s3.serviceAccountName | quote }}
|
||||
|
||||
@@ -61,6 +61,9 @@ spec:
|
||||
{{- if .Values.sftp.priorityClassName }}
|
||||
priorityClassName: {{ .Values.sftp.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.sftp.schedulerName }}
|
||||
schedulerName: {{ .Values.sftp.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
{{- if .Values.sftp.serviceAccountName }}
|
||||
serviceAccountName: {{ .Values.sftp.serviceAccountName | quote }}
|
||||
|
||||
@@ -69,6 +69,11 @@ Inject extra environment vars in the format key:value, if populated
|
||||
{{- range $key, $value := $component }}
|
||||
{{- $_ := set $target $key $value }}
|
||||
{{- end }}
|
||||
{{/* the license block owns SEAWEED_LICENSE; letting one through here too would
|
||||
render the key twice in one container */}}
|
||||
{{- if ((.global | default dict).license | default dict).existingSecret }}
|
||||
{{- $_ := unset $target "SEAWEED_LICENSE" }}
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{/* Return the proper filer image */}}
|
||||
@@ -450,6 +455,47 @@ true
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{/* True when an enterprise license Secret is configured. */}}
|
||||
{{- define "seaweedfs.licenseEnabled" -}}
|
||||
{{- if ((.Values.global.seaweedfs).license).existingSecret -}}
|
||||
true
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/* Enterprise license volume. Projects just the license key. */}}
|
||||
{{- define "seaweedfs.licenseVolume" -}}
|
||||
{{- if include "seaweedfs.licenseEnabled" . -}}
|
||||
- name: seaweedfs-license
|
||||
secret:
|
||||
secretName: {{ .Values.global.seaweedfs.license.existingSecret }}
|
||||
defaultMode: 0444
|
||||
items:
|
||||
- key: {{ .Values.global.seaweedfs.license.secretKey | default "seaweed-license.json" | quote }}
|
||||
path: {{ .Values.global.seaweedfs.license.secretKey | default "seaweed-license.json" | quote }}
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{/* Enterprise license volume mount. Never a subPath: that is resolved once at
|
||||
container start, so a renewed Secret would not reach a running master. */}}
|
||||
{{- define "seaweedfs.licenseVolumeMount" -}}
|
||||
{{- if include "seaweedfs.licenseEnabled" . -}}
|
||||
- name: seaweedfs-license
|
||||
readOnly: true
|
||||
mountPath: {{ .Values.global.seaweedfs.license.mountPath | default "/etc/seaweedfs/license" | quote }}
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{/* SEAWEED_LICENSE, set explicitly rather than relying on the binary's search
|
||||
paths, which depend on the working directory. */}}
|
||||
{{- define "seaweedfs.licenseEnv" -}}
|
||||
{{- if include "seaweedfs.licenseEnabled" . -}}
|
||||
- name: SEAWEED_LICENSE
|
||||
value: {{ printf "%s/%s"
|
||||
(.Values.global.seaweedfs.license.mountPath | default "/etc/seaweedfs/license")
|
||||
(.Values.global.seaweedfs.license.secretKey | default "seaweed-license.json") | quote }}
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
|
||||
{{/* Generate a compatible trafficDistribution value due to "PreferClose" fast deprecation in k8s v1.35.
|
||||
Accepts a dict with "value" (the trafficDistribution string) and "Capabilities". */}}
|
||||
{{- define "seaweedfs.trafficDistribution" -}}
|
||||
|
||||
@@ -73,6 +73,9 @@ spec:
|
||||
{{- if $volume.priorityClassName }}
|
||||
priorityClassName: {{ $volume.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if $volume.schedulerName }}
|
||||
schedulerName: {{ $volume.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
serviceAccountName: {{ $volume.serviceAccountName | default (include "seaweedfs.serviceAccountName" $) | quote }} # for deleting statefulset pods after migration
|
||||
{{- $initContainers_exists := include "seaweedfs.volume.initContainers_exists" $ -}}
|
||||
|
||||
@@ -64,6 +64,9 @@ spec:
|
||||
{{- if .Values.worker.priorityClassName }}
|
||||
priorityClassName: {{ .Values.worker.priorityClassName | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.worker.schedulerName }}
|
||||
schedulerName: {{ .Values.worker.schedulerName | quote }}
|
||||
{{- end }}
|
||||
enableServiceLinks: false
|
||||
{{- if .Values.worker.serviceAccountName }}
|
||||
serviceAccountName: {{ .Values.worker.serviceAccountName | quote }}
|
||||
|
||||
@@ -12,7 +12,16 @@ global:
|
||||
image:
|
||||
# if repository is set, it overrides the namespace part of image.name
|
||||
repository: ""
|
||||
# chrislusf/seaweedfs-enterprise for the enterprise edition
|
||||
name: chrislusf/seaweedfs
|
||||
# Enterprise license file, held in a Secret in the release namespace and
|
||||
# mounted read-only on the components that run a master. A renewed Secret
|
||||
# reaches the running master without a restart. SEAWEED_LICENSE is reserved
|
||||
# while this is set: an extraEnvironmentVars entry of that name is dropped.
|
||||
license:
|
||||
existingSecret: ""
|
||||
secretKey: seaweed-license.json
|
||||
mountPath: /etc/seaweedfs/license
|
||||
imagePullPolicy: IfNotPresent
|
||||
restartPolicy: Always
|
||||
loggingLevel: 1
|
||||
@@ -133,8 +142,13 @@ master:
|
||||
# You can also use emptyDir storage:
|
||||
# data:
|
||||
# type: "emptyDir"
|
||||
# -mdir holds the Raft log and snapshots, and with them the cluster's
|
||||
# identity (its topology UUID). A hostPath does not follow a rescheduled pod,
|
||||
# so prefer type "persistentVolumeClaim" for new installs. The default stays
|
||||
# hostPath so existing releases keep upgrading; see the README to switch one.
|
||||
data:
|
||||
type: "hostPath"
|
||||
size: "1Gi"
|
||||
storageClass: ""
|
||||
hostPathPrefix: /ssd
|
||||
|
||||
@@ -228,6 +242,10 @@ master:
|
||||
# ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/
|
||||
priorityClassName: ""
|
||||
|
||||
# used to specify a custom scheduler for master pods
|
||||
# ref: https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/
|
||||
schedulerName: ""
|
||||
|
||||
# used to assign a service account.
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
|
||||
serviceAccountName: ""
|
||||
@@ -521,6 +539,10 @@ volume:
|
||||
# ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/
|
||||
priorityClassName: ""
|
||||
|
||||
# used to specify a custom scheduler for volume pods
|
||||
# ref: https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/
|
||||
schedulerName: ""
|
||||
|
||||
# used to assign a service account.
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
|
||||
serviceAccountName: ""
|
||||
@@ -801,6 +823,10 @@ filer:
|
||||
# ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/
|
||||
priorityClassName: ""
|
||||
|
||||
# used to specify a custom scheduler for filer pods
|
||||
# ref: https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/
|
||||
schedulerName: ""
|
||||
|
||||
# used to assign a service account.
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
|
||||
serviceAccountName: ""
|
||||
@@ -1060,6 +1086,10 @@ s3:
|
||||
# ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/
|
||||
priorityClassName: ""
|
||||
|
||||
# used to assign a custom scheduler to server pods
|
||||
# ref: https://kubernetes.io/docs/tasks/extend-kubernetes/configure-multiple-schedulers/
|
||||
schedulerName: ""
|
||||
|
||||
# used to assign a service account.
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
|
||||
serviceAccountName: ""
|
||||
@@ -1213,6 +1243,7 @@ sftp:
|
||||
tolerations: ""
|
||||
nodeSelector: ""
|
||||
priorityClassName: ""
|
||||
schedulerName: ""
|
||||
serviceAccountName: ""
|
||||
podSecurityContext: {}
|
||||
containerSecurityContext: {}
|
||||
@@ -1337,6 +1368,7 @@ admin:
|
||||
tolerations: ""
|
||||
nodeSelector: ""
|
||||
priorityClassName: ""
|
||||
schedulerName: ""
|
||||
serviceAccountName: ""
|
||||
podSecurityContext: {}
|
||||
containerSecurityContext: {}
|
||||
@@ -1479,6 +1511,7 @@ worker:
|
||||
tolerations: ""
|
||||
nodeSelector: ""
|
||||
priorityClassName: ""
|
||||
schedulerName: ""
|
||||
serviceAccountName: ""
|
||||
podSecurityContext: {}
|
||||
containerSecurityContext: {}
|
||||
@@ -1718,6 +1751,10 @@ allInOne:
|
||||
# ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/
|
||||
priorityClassName: ""
|
||||
|
||||
# Used to assign a custom scheduler to pods
|
||||
# ref: https://kubernetes.io/docs/tasks/extend-kubernetes/configure-multiple-schedulers/
|
||||
schedulerName: ""
|
||||
|
||||
# Used to assign a service account.
|
||||
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
|
||||
serviceAccountName: ""
|
||||
@@ -1780,6 +1817,10 @@ cosi:
|
||||
podSecurityContext: {}
|
||||
containerSecurityContext: {}
|
||||
|
||||
# used to assign a custom scheduler to cosi pods
|
||||
# ref: https://kubernetes.io/docs/tasks/extend-kubernetes/configure-multiple-schedulers/
|
||||
schedulerName: ""
|
||||
|
||||
extraVolumes: ""
|
||||
extraVolumeMounts: ""
|
||||
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -136,6 +136,10 @@ message ListEntriesRequest {
|
||||
bool inclusiveStartFrom = 4;
|
||||
uint32 limit = 5;
|
||||
int64 snapshot_ts_ns = 6;
|
||||
// Leave the chunk list out of every entry in the response. The attributes
|
||||
// still carry the file size, so a listing that only reads attributes can
|
||||
// ask for this and skip the largest part of the payload.
|
||||
bool omit_chunks = 7;
|
||||
}
|
||||
|
||||
message ListEntriesResponse {
|
||||
|
||||
Generated
+7
@@ -4556,6 +4556,7 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"x509-parser",
|
||||
"xxhash-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4989,6 +4990,12 @@ version = "0.13.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4"
|
||||
|
||||
[[package]]
|
||||
name = "xxhash-rust"
|
||||
version = "0.8.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.2"
|
||||
|
||||
@@ -75,6 +75,9 @@ serde_urlencoded = "0.7"
|
||||
crc32c = "0.6"
|
||||
crc32fast = "1"
|
||||
|
||||
# xxhash64 - must match Go's cespare/xxhash for the heartbeat volume digest
|
||||
xxhash-rust = { version = "0.8", features = ["xxh64"] }
|
||||
|
||||
# Memory-mapped files
|
||||
memmap2 = "0.9"
|
||||
|
||||
|
||||
@@ -59,6 +59,8 @@ service Seaweed {
|
||||
}
|
||||
rpc VolumeGrow (VolumeGrowRequest) returns (VolumeGrowResponse) {
|
||||
}
|
||||
rpc CollectionStatistics (CollectionStatisticsRequest) returns (CollectionStatisticsResponse) {
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
@@ -105,6 +107,16 @@ message Heartbeat {
|
||||
// physical disk capacity per disk type, in bytes, from the underlying filesystem
|
||||
map<string, uint64> disk_total_bytes = 25;
|
||||
map<string, uint64> disk_free_bytes = 26;
|
||||
|
||||
// Digest of every volume in this heartbeat's view of the server, letting the
|
||||
// master check its copy is current without being sent the whole list. Absent
|
||||
// from servers that do not compute it, and distinct from a digest of 0, which
|
||||
// is what a server holding no volumes reports.
|
||||
optional uint64 volume_digest = 27;
|
||||
// Volumes whose reported state changed since the last heartbeat, sent in
|
||||
// place of `volumes`. A master that does not understand this never sets
|
||||
// volume_digest_supported, so it keeps being sent the whole list.
|
||||
repeated VolumeInformationMessage changed_volumes = 28;
|
||||
}
|
||||
|
||||
message HeartbeatResponse {
|
||||
@@ -115,6 +127,12 @@ message HeartbeatResponse {
|
||||
repeated StorageBackend storage_backends = 5;
|
||||
repeated string duplicated_uuids = 6;
|
||||
bool preallocate = 7;
|
||||
// The master's view of this server's volumes disagrees with the reported
|
||||
// digest, so it needs the full volume list rather than changes alone.
|
||||
bool resend_full_volume_list = 8;
|
||||
// The master compares volume digests, so a server that reports one may send
|
||||
// changed_volumes in place of its whole list.
|
||||
bool volume_digest_supported = 9;
|
||||
}
|
||||
|
||||
message VolumeInformationMessage {
|
||||
@@ -294,6 +312,11 @@ message StatisticsResponse {
|
||||
uint64 total_size = 4;
|
||||
uint64 used_size = 5;
|
||||
uint64 file_count = 6;
|
||||
// sizes counting one copy of the data: a single replica of a regular volume,
|
||||
// the data shards of an ec volume. logical_total_size scales the free space
|
||||
// by the copies the requested replication makes.
|
||||
uint64 logical_total_size = 7;
|
||||
uint64 logical_used_size = 8;
|
||||
}
|
||||
|
||||
//
|
||||
@@ -310,6 +333,26 @@ message CollectionListResponse {
|
||||
repeated Collection collections = 1;
|
||||
}
|
||||
|
||||
// Summarises what each collection holds, so a caller tracking usage does not
|
||||
// have to be sent every volume in the cluster to add it up itself.
|
||||
message CollectionStatisticsRequest {
|
||||
}
|
||||
message CollectionStatisticsResponse {
|
||||
repeated CollectionStatistics collections = 1;
|
||||
}
|
||||
message CollectionStatistics {
|
||||
string collection = 1;
|
||||
uint64 file_count = 2;
|
||||
uint64 delete_count = 3;
|
||||
uint64 deleted_byte_count = 4;
|
||||
// one copy of the data: a single replica of a regular volume, the data
|
||||
// shards of an ec volume
|
||||
uint64 size = 5;
|
||||
// what is on disk: every replica, and parity shards
|
||||
uint64 physical_size = 6;
|
||||
uint64 volume_count = 7;
|
||||
}
|
||||
|
||||
message CollectionDeleteRequest {
|
||||
string name = 1;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,8 @@ service VolumeServer {
|
||||
}
|
||||
rpc VolumeUnmount (VolumeUnmountRequest) returns (VolumeUnmountResponse) {
|
||||
}
|
||||
rpc VolumeConsolidateIndex (VolumeConsolidateIndexRequest) returns (VolumeConsolidateIndexResponse) {
|
||||
}
|
||||
rpc VolumeDelete (VolumeDeleteRequest) returns (VolumeDeleteResponse) {
|
||||
}
|
||||
rpc VolumeMarkReadonly (VolumeMarkReadonlyRequest) returns (VolumeMarkReadonlyResponse) {
|
||||
@@ -244,6 +246,12 @@ message VolumeUnmountRequest {
|
||||
message VolumeUnmountResponse {
|
||||
}
|
||||
|
||||
message VolumeConsolidateIndexRequest {
|
||||
uint32 volume_id = 1;
|
||||
}
|
||||
message VolumeConsolidateIndexResponse {
|
||||
}
|
||||
|
||||
message VolumeDeleteRequest {
|
||||
uint32 volume_id = 1;
|
||||
bool only_empty = 2;
|
||||
@@ -257,6 +265,8 @@ message VolumeDeleteResponse {
|
||||
message VolumeMarkReadonlyRequest {
|
||||
uint32 volume_id = 1;
|
||||
bool persist = 2;
|
||||
// reject writes but keep accepting deletes, so expiring data can drain the volume
|
||||
bool can_delete = 3;
|
||||
}
|
||||
message VolumeMarkReadonlyResponse {
|
||||
}
|
||||
@@ -594,6 +604,7 @@ message VolumeInfo {
|
||||
uint64 expire_at_sec = 6; // expiration time of ec volume
|
||||
bool read_only = 7;
|
||||
EcShardConfig ec_shard_config = 8; // EC shard configuration (optional, null = use default 10+4)
|
||||
bool read_only_can_delete = 9; // with read_only: writes are rejected but deletes still land
|
||||
}
|
||||
|
||||
// EcShardConfig specifies erasure coding shard configuration
|
||||
|
||||
@@ -256,6 +256,8 @@ pub struct VolumeServerConfig {
|
||||
pub https_client_ca_file: String,
|
||||
pub grpc_cert_file: String,
|
||||
pub grpc_key_file: String,
|
||||
pub grpc_client_cert_file: String,
|
||||
pub grpc_client_key_file: String,
|
||||
pub grpc_ca_file: String,
|
||||
pub grpc_allowed_wildcard_domain: String,
|
||||
pub grpc_volume_allowed_common_names: Vec<String>,
|
||||
@@ -805,6 +807,8 @@ fn resolve_config(cli: Cli) -> VolumeServerConfig {
|
||||
https_client_ca_file: sec.https_client_ca_file,
|
||||
grpc_cert_file: sec.grpc_cert_file,
|
||||
grpc_key_file: sec.grpc_key_file,
|
||||
grpc_client_cert_file: sec.grpc_client_cert_file,
|
||||
grpc_client_key_file: sec.grpc_client_key_file,
|
||||
grpc_ca_file: sec.grpc_ca_file,
|
||||
grpc_allowed_wildcard_domain: sec.grpc_allowed_wildcard_domain,
|
||||
grpc_volume_allowed_common_names: sec.grpc_volume_allowed_common_names,
|
||||
@@ -837,6 +841,8 @@ pub struct SecurityConfig {
|
||||
pub https_client_ca_file: String,
|
||||
pub grpc_cert_file: String,
|
||||
pub grpc_key_file: String,
|
||||
pub grpc_client_cert_file: String,
|
||||
pub grpc_client_key_file: String,
|
||||
pub grpc_ca_file: String,
|
||||
pub grpc_allowed_wildcard_domain: String,
|
||||
pub grpc_volume_allowed_common_names: Vec<String>,
|
||||
@@ -882,6 +888,8 @@ const SECURITY_CONFIG_FILE_NAME: &str = "security.toml";
|
||||
/// [grpc.volume]
|
||||
/// cert = "/path/to/cert.pem"
|
||||
/// key = "/path/to/key.pem"
|
||||
/// client_cert = "/path/to/client-cert.pem"
|
||||
/// client_key = "/path/to/client-key.pem"
|
||||
/// allowed_commonNames = "volume-a.internal,volume-b.internal"
|
||||
/// ```
|
||||
pub fn parse_security_config(path: &str) -> SecurityConfig {
|
||||
@@ -1003,6 +1011,8 @@ pub fn parse_security_config(path: &str) -> SecurityConfig {
|
||||
Section::GrpcVolume => match key {
|
||||
"cert" => cfg.grpc_cert_file = value.to_string(),
|
||||
"key" => cfg.grpc_key_file = value.to_string(),
|
||||
"client_cert" => cfg.grpc_client_cert_file = value.to_string(),
|
||||
"client_key" => cfg.grpc_client_key_file = value.to_string(),
|
||||
// Go only reads CA from [grpc], not [grpc.volume]
|
||||
"allowed_commonNames" => {
|
||||
cfg.grpc_volume_allowed_common_names =
|
||||
@@ -1134,6 +1144,12 @@ fn apply_env_overrides(cfg: &mut SecurityConfig) {
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_KEY") {
|
||||
cfg.grpc_key_file = v;
|
||||
}
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_CLIENT_CERT") {
|
||||
cfg.grpc_client_cert_file = v;
|
||||
}
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_CLIENT_KEY") {
|
||||
cfg.grpc_client_key_file = v;
|
||||
}
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_CA") {
|
||||
cfg.grpc_ca_file = v;
|
||||
} else if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_CA") {
|
||||
@@ -1231,6 +1247,8 @@ mod tests {
|
||||
"WEED_HTTPS_CLIENT_CA",
|
||||
"WEED_GRPC_VOLUME_CERT",
|
||||
"WEED_GRPC_VOLUME_KEY",
|
||||
"WEED_GRPC_VOLUME_CLIENT_CERT",
|
||||
"WEED_GRPC_VOLUME_CLIENT_KEY",
|
||||
"WEED_GRPC_CA",
|
||||
"WEED_GRPC_VOLUME_CA",
|
||||
"WEED_GRPC_ALLOWED_WILDCARD_DOMAIN",
|
||||
@@ -1500,6 +1518,35 @@ key = "/etc/seaweedfs/volume-key.pem"
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_security_config_uses_grpc_volume_client_cert() {
|
||||
let _guard = process_state_lock();
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(
|
||||
tmp.path(),
|
||||
r#"
|
||||
[grpc.volume]
|
||||
cert = "/etc/seaweedfs/volume-cert.pem"
|
||||
key = "/etc/seaweedfs/volume-key.pem"
|
||||
client_cert = "/etc/seaweedfs/volume-client-cert.pem"
|
||||
client_key = "/etc/seaweedfs/volume-client-key.pem"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
with_cleared_security_env(|| {
|
||||
let cfg = parse_security_config(tmp.path().to_str().unwrap());
|
||||
assert_eq!(
|
||||
cfg.grpc_client_cert_file,
|
||||
"/etc/seaweedfs/volume-client-cert.pem"
|
||||
);
|
||||
assert_eq!(
|
||||
cfg.grpc_client_key_file,
|
||||
"/etc/seaweedfs/volume-client-key.pem"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_security_config_uses_grpc_peer_name_policy() {
|
||||
let _guard = process_state_lock();
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! narrow TOCTOU window (a hostname that resolves to a public IP here and then
|
||||
//! flips to a blocked one when the SDK dials) remains as a follow-up.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
/// AWS/Azure/GCP IPv4 instance-metadata-service (IMDS) address. It is
|
||||
/// link-local and thus already covered by [`is_link_local`], but is named
|
||||
@@ -74,9 +74,52 @@ fn is_cgnat(ip: IpAddr) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the IPv4 address carried by an IPv6 transition address -- NAT64
|
||||
/// 64:ff9b::/96 (RFC 6052), 6to4 2002::/16 (RFC 3056), Teredo 2001:0000::/32
|
||||
/// (RFC 4380), and the deprecated IPv4-compatible ::/96 (RFC 4291) -- or None
|
||||
/// when it is not one of those. IPv4-mapped ::ffff:0:0/96 is excluded; it is
|
||||
/// already normalized via `to_ipv4_mapped`.
|
||||
fn embedded_transition_ipv4(v6: Ipv6Addr) -> Option<Ipv4Addr> {
|
||||
let o = v6.octets();
|
||||
if o[0] == 0x00
|
||||
&& o[1] == 0x64
|
||||
&& o[2] == 0xff
|
||||
&& o[3] == 0x9b
|
||||
&& o[4..12].iter().all(|&b| b == 0)
|
||||
{
|
||||
return Some(Ipv4Addr::new(o[12], o[13], o[14], o[15]));
|
||||
}
|
||||
if o[0] == 0x20 && o[1] == 0x02 {
|
||||
return Some(Ipv4Addr::new(o[2], o[3], o[4], o[5]));
|
||||
}
|
||||
if o[0] == 0x20 && o[1] == 0x01 && o[2] == 0x00 && o[3] == 0x00 {
|
||||
// Teredo obfuscates the client IPv4 as its ones' complement.
|
||||
return Some(Ipv4Addr::new(
|
||||
o[12] ^ 0xff,
|
||||
o[13] ^ 0xff,
|
||||
o[14] ^ 0xff,
|
||||
o[15] ^ 0xff,
|
||||
));
|
||||
}
|
||||
if o[..12].iter().all(|&b| b == 0) {
|
||||
// IPv4-compatible ::a.b.c.d; :: and ::1 are already handled by the
|
||||
// unspecified / loopback checks before extraction runs.
|
||||
return Some(Ipv4Addr::new(o[12], o[13], o[14], o[15]));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns an error if `ip` is not safe to dial from a server that can reach
|
||||
/// cluster-internal hosts. Mirrors Go's `checkBlockedIP`.
|
||||
pub fn check_blocked_ip(endpoint: &str, ip: IpAddr) -> Result<(), String> {
|
||||
check_blocked_ip_policy(endpoint, ip, false)
|
||||
}
|
||||
|
||||
/// Like [`check_blocked_ip`], but `allow_private` keeps RFC 1918 / CGNAT
|
||||
/// reachable for callers whose target legitimately sits on an internal network
|
||||
/// (peer volume servers), while still blocking loopback, link-local (IMDS) and
|
||||
/// unspecified. Mirrors Go's `checkBlockedIPPolicy`.
|
||||
pub fn check_blocked_ip_policy(endpoint: &str, ip: IpAddr, allow_private: bool) -> Result<(), String> {
|
||||
// Normalize IPv4-mapped IPv6 (`::ffff:a.b.c.d`) to its IPv4 form so the
|
||||
// IPv4 deny rules apply. The OS routes these to the embedded IPv4 address,
|
||||
// so without this `::ffff:127.0.0.1` / `::ffff:169.254.169.254` would slip
|
||||
@@ -112,17 +155,28 @@ pub fn check_blocked_ip(endpoint: &str, ip: IpAddr) -> Result<(), String> {
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_private(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to private address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
if !allow_private {
|
||||
if is_private(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to private address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_cgnat(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to CGNAT address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
}
|
||||
if is_cgnat(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to CGNAT address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
// IPv6 transition addresses embed an IPv4 destination that routes to the
|
||||
// same host wherever the matching relay exists (common in IPv6-only cloud).
|
||||
// to_ipv4_mapped above only covers ::ffff: mapped addresses, so pull the
|
||||
// embedded IPv4 out of the other forms and re-check it against the rules.
|
||||
if let IpAddr::V6(v6) = ip {
|
||||
if let Some(v4) = embedded_transition_ipv4(v6) {
|
||||
return check_blocked_ip_policy(endpoint, IpAddr::V4(v4), allow_private);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -243,6 +297,59 @@ pub async fn validate_remote_endpoint(endpoint: &str) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an error if `target` could redirect a replica upload away from a peer
|
||||
/// volume server. The target must be a bare `host:port` -- a scheme, userinfo,
|
||||
/// path, query or fragment can smuggle a different destination into the
|
||||
/// formatted upload URL -- whose host is not loopback, link-local (IMDS) or
|
||||
/// unspecified. Cluster peers legitimately sit on private networks, so RFC 1918
|
||||
/// / CGNAT are allowed. Mirrors Go's `validateReplicaTarget`.
|
||||
pub async fn validate_replica_target(target: &str) -> Result<(), String> {
|
||||
let trimmed = target.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("replica target is empty".to_string());
|
||||
}
|
||||
if trimmed.contains("://") || trimmed.contains(['/', '?', '#', '@', '\\']) {
|
||||
return Err(format!("replica target {:?} must be a bare host:port", target));
|
||||
}
|
||||
|
||||
// Require an explicit host:port, handling `[IPv6]:port`. A bracketless IPv6
|
||||
// literal (which carries its own colons) is rejected; peers are addressed as
|
||||
// `[ipv6]:port`, matching Go's net.SplitHostPort.
|
||||
let host = if let Some(rest) = trimmed.strip_prefix('[') {
|
||||
match rest.split_once(']') {
|
||||
Some((h, port)) if port.starts_with(':') && port.len() > 1 => h,
|
||||
_ => return Err(format!("replica target {:?} must be a bare host:port", target)),
|
||||
}
|
||||
} else {
|
||||
match trimmed.rsplit_once(':') {
|
||||
Some((h, port)) if !port.is_empty() && !h.contains(':') => h,
|
||||
_ => return Err(format!("replica target {:?} must be a bare host:port", target)),
|
||||
}
|
||||
};
|
||||
|
||||
if host.is_empty() {
|
||||
return Err(format!("replica target {:?} has no host", target));
|
||||
}
|
||||
if is_blocked_imds_host(&host.to_ascii_lowercase()) {
|
||||
return Err(format!(
|
||||
"replica target {:?} targets instance metadata service",
|
||||
target
|
||||
));
|
||||
}
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
return check_blocked_ip_policy(target, ip, true);
|
||||
}
|
||||
|
||||
let addrs = resolve_host(host).await?;
|
||||
if addrs.is_empty() {
|
||||
return Err(format!("resolve replica target host {:?}: no addresses", host));
|
||||
}
|
||||
for ip in addrs {
|
||||
check_blocked_ip_policy(target, ip, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -333,6 +440,49 @@ mod tests {
|
||||
assert!(check_blocked_ip("e", ip("2606:4700:4700::1111")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ipv6_transition_addresses() {
|
||||
// Every transition form encoding an internal IPv4 must be blocked.
|
||||
assert!(
|
||||
check_blocked_ip("e", ip("64:ff9b::a9fe:a9fe")) // NAT64 -> IMDS
|
||||
.unwrap_err()
|
||||
.contains("metadata")
|
||||
);
|
||||
assert!(
|
||||
check_blocked_ip("e", ip("64:ff9b::7f00:1")) // NAT64 -> loopback
|
||||
.unwrap_err()
|
||||
.contains("loopback")
|
||||
);
|
||||
assert!(
|
||||
check_blocked_ip("e", ip("2002:a00:1::")) // 6to4 -> 10.0.0.1
|
||||
.unwrap_err()
|
||||
.contains("private")
|
||||
);
|
||||
assert!(
|
||||
check_blocked_ip("e", ip("2001:0:4136:e378:8000:63bf:80ff:fffe")) // Teredo -> loopback
|
||||
.unwrap_err()
|
||||
.contains("loopback")
|
||||
);
|
||||
assert!(
|
||||
check_blocked_ip("e", ip("::7f00:1")) // IPv4-compatible -> loopback
|
||||
.unwrap_err()
|
||||
.contains("loopback")
|
||||
);
|
||||
// A NAT64 address outside the 64:ff9b::/96 well-known prefix is not
|
||||
// decoded (its embedded IPv4 lives elsewhere), so it is left as-is.
|
||||
assert!(check_blocked_ip("e", ip("64:ff9b:1::a9fe:a9fe")).is_ok());
|
||||
// Every transition form embedding a public IPv4 (8.8.8.8) still passes:
|
||||
// NAT64, 6to4, Teredo, IPv4-compatible.
|
||||
assert!(check_blocked_ip("e", ip("64:ff9b::808:808")).is_ok());
|
||||
assert!(check_blocked_ip("e", ip("2002:808:808::")).is_ok());
|
||||
assert!(check_blocked_ip("e", ip("2001::f7f7:f7f7")).is_ok());
|
||||
assert!(check_blocked_ip("e", ip("::808:808")).is_ok());
|
||||
// Bracketed transition literal via the full endpoint path.
|
||||
assert!(precheck_endpoint("http://[64:ff9b::a9fe:a9fe]/")
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ipv4_mapped_ipv6() {
|
||||
// IPv4-mapped IPv6 must be unmapped so the IPv4 rules catch it.
|
||||
@@ -356,4 +506,71 @@ mod tests {
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_blocked_ip_policy_allows_private_peers() {
|
||||
// The replica leg targets peer volume servers, which may be private.
|
||||
assert!(check_blocked_ip_policy("e", ip("10.0.0.7"), true).is_ok());
|
||||
assert!(check_blocked_ip_policy("e", ip("192.168.1.5"), true).is_ok());
|
||||
assert!(check_blocked_ip_policy("e", ip("100.64.0.42"), true).is_ok());
|
||||
// Loopback / IMDS / unspecified stay blocked even when private is allowed.
|
||||
assert!(check_blocked_ip_policy("e", ip("127.0.0.1"), true)
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(check_blocked_ip_policy("e", ip("169.254.169.254"), true)
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
assert!(check_blocked_ip_policy("e", ip("0.0.0.0"), true)
|
||||
.unwrap_err()
|
||||
.contains("unspecified"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_replica_target_rejects_and_allows() {
|
||||
// A path plus a trailing ?a= would otherwise swallow ?type=replicate.
|
||||
assert!(validate_replica_target("127.0.0.1:7000/status/x/?a=")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("http://10.0.0.7:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("user@10.0.0.7:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("10.0.0.7")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("peer.example.com")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("127.0.0.1:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(validate_replica_target("[::1]:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(validate_replica_target("169.254.169.254:80")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
assert!(validate_replica_target("metadata:80")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
assert!(validate_replica_target("")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("empty"));
|
||||
// Legitimate peer volume servers on private networks pass.
|
||||
assert!(validate_replica_target("10.0.0.7:8080").await.is_ok());
|
||||
assert!(validate_replica_target("192.168.1.5:8080").await.is_ok());
|
||||
assert!(validate_replica_target("[fd00::1]:8080").await.is_ok());
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ pub mod endpoint_guard;
|
||||
pub mod s3;
|
||||
pub mod s3_tier;
|
||||
|
||||
pub use endpoint_guard::validate_remote_endpoint;
|
||||
pub use endpoint_guard::{validate_remote_endpoint, validate_replica_target};
|
||||
|
||||
use crate::pb::remote_pb::{RemoteConf, RemoteStorageLocation};
|
||||
|
||||
@@ -211,4 +211,19 @@ mod tests {
|
||||
};
|
||||
assert_eq!(s3_compatible_endpoint(&gcs), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn azure_endpoint_has_no_ssrf_path() {
|
||||
// The Go volume server guards the caller-supplied azure endpoint against
|
||||
// SSRF. This server has no azure backend, so there is nothing to dial:
|
||||
// azure is not S3-compatible (the endpoint guard does not apply) and
|
||||
// make_remote_storage_client rejects the type before building a client.
|
||||
let azure = RemoteConf {
|
||||
r#type: "azure".to_string(),
|
||||
azure_endpoint: "https://169.254.169.254/".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s3_compatible_endpoint(&azure), None);
|
||||
assert!(make_remote_storage_client(&azure).is_err());
|
||||
}
|
||||
}
|
||||
@@ -192,6 +192,13 @@ impl Guard {
|
||||
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
|
||||
}
|
||||
|
||||
/// Whether any write-side control is configured: a non-empty whitelist or a
|
||||
/// signing key. Mirrors Go's non-nil `guard` -- when this is false, every
|
||||
/// caller is allowed and admin RPCs need not carry peer info.
|
||||
pub fn is_write_active(&self) -> bool {
|
||||
self.is_write_active
|
||||
}
|
||||
|
||||
/// Check if a remote IP is in the whitelist.
|
||||
/// Returns true if write security is inactive (no whitelist and no signing key),
|
||||
/// if the whitelist is empty, or if the IP matches.
|
||||
|
||||
@@ -33,23 +33,31 @@ impl Error for GrpcClientError {}
|
||||
pub fn load_outgoing_grpc_tls(
|
||||
config: &VolumeServerConfig,
|
||||
) -> Result<Option<OutgoingGrpcTlsConfig>, GrpcClientError> {
|
||||
if config.grpc_cert_file.is_empty()
|
||||
|| config.grpc_key_file.is_empty()
|
||||
|| config.grpc_ca_file.is_empty()
|
||||
// prefer a dedicated client certificate: CAs may issue certs with only one of the serverAuth/clientAuth EKUs
|
||||
let (cert_file, key_file) = if !config.grpc_client_cert_file.is_empty()
|
||||
&& !config.grpc_client_key_file.is_empty()
|
||||
{
|
||||
(&config.grpc_client_cert_file, &config.grpc_client_key_file)
|
||||
} else {
|
||||
if !config.grpc_client_cert_file.is_empty() || !config.grpc_client_key_file.is_empty() {
|
||||
tracing::warn!("grpc.volume.client_cert and grpc.volume.client_key must both be set, falling back to grpc.volume.cert and grpc.volume.key");
|
||||
}
|
||||
(&config.grpc_cert_file, &config.grpc_key_file)
|
||||
};
|
||||
if cert_file.is_empty() || key_file.is_empty() || config.grpc_ca_file.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let cert_pem = std::fs::read_to_string(&config.grpc_cert_file).map_err(|e| {
|
||||
let cert_pem = std::fs::read_to_string(cert_file).map_err(|e| {
|
||||
GrpcClientError(format!(
|
||||
"Failed to read outgoing gRPC cert '{}': {}",
|
||||
config.grpc_cert_file, e
|
||||
cert_file, e
|
||||
))
|
||||
})?;
|
||||
let key_pem = std::fs::read_to_string(&config.grpc_key_file).map_err(|e| {
|
||||
let key_pem = std::fs::read_to_string(key_file).map_err(|e| {
|
||||
GrpcClientError(format!(
|
||||
"Failed to read outgoing gRPC key '{}': {}",
|
||||
config.grpc_key_file, e
|
||||
key_file, e
|
||||
))
|
||||
})?;
|
||||
let ca_pem = std::fs::read_to_string(&config.grpc_ca_file).map_err(|e| {
|
||||
@@ -236,6 +244,8 @@ mod tests {
|
||||
https_client_ca_file: String::new(),
|
||||
grpc_cert_file: String::new(),
|
||||
grpc_key_file: String::new(),
|
||||
grpc_client_cert_file: String::new(),
|
||||
grpc_client_key_file: String::new(),
|
||||
grpc_ca_file: String::new(),
|
||||
grpc_allowed_wildcard_domain: String::new(),
|
||||
grpc_volume_allowed_common_names: vec![],
|
||||
@@ -265,6 +275,45 @@ mod tests {
|
||||
assert!(load_outgoing_grpc_tls(&config).unwrap().is_none());
|
||||
}
|
||||
|
||||
fn write_pem_files(dir: &tempfile::TempDir, config: &mut VolumeServerConfig) {
|
||||
let write = |name: &str, content: &str| {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, content).unwrap();
|
||||
path.to_str().unwrap().to_string()
|
||||
};
|
||||
config.grpc_cert_file = write("server.pem", "server-cert");
|
||||
config.grpc_key_file = write("server.key", "server-key");
|
||||
config.grpc_ca_file = write("ca.pem", "ca");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_outgoing_grpc_tls_prefers_client_cert() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let mut config = sample_config();
|
||||
write_pem_files(&dir, &mut config);
|
||||
let client_cert = dir.path().join("client.pem");
|
||||
let client_key = dir.path().join("client.key");
|
||||
std::fs::write(&client_cert, "client-cert").unwrap();
|
||||
std::fs::write(&client_key, "client-key").unwrap();
|
||||
config.grpc_client_cert_file = client_cert.to_str().unwrap().to_string();
|
||||
config.grpc_client_key_file = client_key.to_str().unwrap().to_string();
|
||||
|
||||
let tls = load_outgoing_grpc_tls(&config).unwrap().unwrap();
|
||||
assert_eq!(tls.cert_pem, "client-cert");
|
||||
assert_eq!(tls.key_pem, "client-key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_outgoing_grpc_tls_falls_back_to_server_cert() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let mut config = sample_config();
|
||||
write_pem_files(&dir, &mut config);
|
||||
|
||||
let tls = load_outgoing_grpc_tls(&config).unwrap().unwrap();
|
||||
assert_eq!(tls.cert_pem, "server-cert");
|
||||
assert_eq!(tls.key_pem, "server-key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_grpc_endpoint_without_tls_uses_http_scheme() {
|
||||
let endpoint = build_grpc_endpoint("127.0.0.1:19333", None).unwrap();
|
||||
|
||||
@@ -155,6 +155,13 @@ impl VolumeGrpcService {
|
||||
/// SocketAddr; if it is somehow None we deny, matching "if we don't
|
||||
/// know who the caller is, refuse."
|
||||
fn check_grpc_admin_auth<T>(&self, request: &Request<T>) -> Result<(), Status> {
|
||||
// Mirror Go's `if vs.guard == nil { return nil }`: with no whitelist and
|
||||
// no signing key, write security is inactive and every caller is allowed.
|
||||
// Real gRPC connections always carry peer info, so requiring it below only
|
||||
// affects in-process callers (tests, upgrades) once a control is enabled.
|
||||
if !self.state.guard.read().unwrap().is_write_active() {
|
||||
return Ok(());
|
||||
}
|
||||
let remote = match request.remote_addr() {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
@@ -237,12 +244,17 @@ impl VolumeGrpcService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shared helper matching Go's `makeVolumeReadonly(ctx, v, persist)`.
|
||||
/// Shared helper matching Go's `makeVolumeReadonly(ctx, v, canDelete, persist)`.
|
||||
/// 1. Check maintenance mode
|
||||
/// 2. Notify master (readonly=true)
|
||||
/// 3. Mark local volume readonly
|
||||
/// 4. Notify master again (cover heartbeat race)
|
||||
async fn make_volume_readonly(&self, vid: VolumeId, persist: bool) -> Result<(), Status> {
|
||||
async fn make_volume_readonly(
|
||||
&self,
|
||||
vid: VolumeId,
|
||||
can_delete: bool,
|
||||
persist: bool,
|
||||
) -> Result<(), Status> {
|
||||
self.state.check_maintenance()?;
|
||||
|
||||
let info = {
|
||||
@@ -268,7 +280,7 @@ impl VolumeGrpcService {
|
||||
{
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
if let Some((_, vol)) = store.find_volume_mut(vid) {
|
||||
vol.set_read_only_persist(persist)
|
||||
vol.set_read_only_persist(can_delete, persist)
|
||||
.map_err(|e| Status::internal(e.to_string()))?;
|
||||
}
|
||||
self.state.volume_state_notify.notify_one();
|
||||
@@ -288,6 +300,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::BatchDeleteRequest>,
|
||||
) -> Result<Response<volume_server_pb::BatchDeleteResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let mut results = Vec::new();
|
||||
@@ -660,10 +673,17 @@ impl VolumeServer for VolumeGrpcService {
|
||||
) -> Result<Response<volume_server_pb::DeleteCollectionResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let collection = &request.into_inner().collection;
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
store
|
||||
.delete_collection(collection)
|
||||
.map_err(|e| Status::internal(e))?;
|
||||
{
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
store
|
||||
.delete_collection(collection)
|
||||
.map_err(|e| Status::internal(e))?;
|
||||
}
|
||||
// The delta the notify path derives is the only thing that tells the
|
||||
// master these slots came free: a heartbeat carries the whole list only
|
||||
// when the master asks, and a volume grown and destroyed between two of
|
||||
// them was never in one at all.
|
||||
self.state.volume_state_notify.notify_one();
|
||||
Ok(Response::new(volume_server_pb::DeleteCollectionResponse {}))
|
||||
}
|
||||
|
||||
@@ -932,6 +952,22 @@ impl VolumeServer for VolumeGrpcService {
|
||||
Ok(Response::new(volume_server_pb::VolumeUnmountResponse {}))
|
||||
}
|
||||
|
||||
async fn volume_consolidate_index(
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeConsolidateIndexRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeConsolidateIndexResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let vid = VolumeId(request.into_inner().volume_id);
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
store
|
||||
.consolidate_volume_index(vid)
|
||||
.map_err(|e| Status::internal(e.to_string()))?;
|
||||
Ok(Response::new(
|
||||
volume_server_pb::VolumeConsolidateIndexResponse {},
|
||||
))
|
||||
}
|
||||
|
||||
async fn volume_delete(
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeDeleteRequest>,
|
||||
@@ -970,7 +1006,8 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.find_volume(vid)
|
||||
.ok_or_else(|| Status::not_found(format!("volume {} not found", vid)))?;
|
||||
}
|
||||
self.make_volume_readonly(vid, req.persist).await?;
|
||||
self.make_volume_readonly(vid, req.can_delete, req.persist)
|
||||
.await?;
|
||||
Ok(Response::new(
|
||||
volume_server_pb::VolumeMarkReadonlyResponse {},
|
||||
))
|
||||
@@ -1122,6 +1159,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::SetStateRequest>,
|
||||
) -> Result<Response<volume_server_pb::SetStateResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
if let Some(new_state) = &req.state {
|
||||
@@ -1174,6 +1212,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeCopyRequest>,
|
||||
) -> Result<Response<Self::VolumeCopyStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -1975,6 +2014,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::ReadAllNeedlesRequest>,
|
||||
) -> Result<Response<Self::ReadAllNeedlesStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let state = self.state.clone();
|
||||
|
||||
@@ -2175,6 +2215,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeTailReceiverRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeTailReceiverResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
@@ -2300,6 +2341,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsGenerateRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsGenerateResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -2400,6 +2442,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsRebuildRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsRebuildResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -2600,6 +2643,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsCopyRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsCopyResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -2982,6 +3026,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsUnmountRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsUnmountResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
@@ -3145,6 +3190,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsToVolumeRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsToVolumeResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3411,6 +3457,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeTierMoveDatToRemoteRequest>,
|
||||
) -> Result<Response<Self::VolumeTierMoveDatToRemoteStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3577,6 +3624,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeTierMoveDatFromRemoteRequest>,
|
||||
) -> Result<Response<Self::VolumeTierMoveDatFromRemoteStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
// Note: Go does NOT check maintenance mode for TierMoveDatFromRemote
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3837,6 +3885,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::FetchAndWriteNeedleRequest>,
|
||||
) -> Result<Response<volume_server_pb::FetchAndWriteNeedleResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3912,6 +3961,21 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.as_secs();
|
||||
n.set_has_last_modified_date();
|
||||
|
||||
// Validate every replica target before writing anything, so a malformed
|
||||
// or internal target fails the request instead of leaving a local write
|
||||
// behind. Mirrors the Go volume server. NOTE: like the Rust S3 endpoint
|
||||
// guard, this validates the up-front DNS answer but does not yet re-check
|
||||
// at connect time, so a rebinding hostname remains a follow-up.
|
||||
if !self.state.allow_untrusted_remote_endpoints {
|
||||
for replica in &req.replicas {
|
||||
crate::remote_storage::validate_replica_target(&replica.url)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Status::invalid_argument(format!("reject replica target: {}", e))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
// Run local write and replica writes concurrently (matches Go's WaitGroup)
|
||||
let mut handles: Vec<tokio::task::JoinHandle<Result<(), String>>> = Vec::new();
|
||||
|
||||
@@ -4060,7 +4124,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
let mut errs: Vec<String> = Vec::new();
|
||||
if req.mark_broken_volumes_readonly {
|
||||
for vid in &broken_vids {
|
||||
match self.make_volume_readonly(*vid, true).await {
|
||||
match self.make_volume_readonly(*vid, false, true).await {
|
||||
Ok(()) => {
|
||||
details.push(format!("volume {} is now read-only", vid.0));
|
||||
}
|
||||
@@ -4092,6 +4156,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::ScrubEcVolumeRequest>,
|
||||
) -> Result<Response<volume_server_pb::ScrubEcVolumeResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
// Validate mode
|
||||
@@ -4449,6 +4514,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeNeedleStatusRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeNeedleStatusResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
let needle_id = NeedleId(req.needle_id);
|
||||
@@ -5381,6 +5447,29 @@ mod tests {
|
||||
(VolumeGrpcService { state }, tmp)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_volume_consolidate_index_rpc() {
|
||||
let (service, _tmp) = make_local_service_with_volume("consolidate_rpc", None);
|
||||
|
||||
// Carry a peer address so the admin gate sees a caller; the test guard
|
||||
// has an empty whitelist, so any peer is accepted.
|
||||
let mut request = Request::new(volume_server_pb::VolumeConsolidateIndexRequest {
|
||||
volume_id: 1,
|
||||
});
|
||||
request.extensions_mut().insert(tonic::transport::server::TcpConnectInfo {
|
||||
local_addr: None,
|
||||
remote_addr: Some("127.0.0.1:65000".parse().unwrap()),
|
||||
});
|
||||
|
||||
service.volume_consolidate_index(request).await.unwrap();
|
||||
|
||||
// Data and index share a directory here, so there is nothing to move;
|
||||
// the volume stays mounted and keeps its needle.
|
||||
let store = service.state.store.read().unwrap();
|
||||
let (_, v) = store.find_volume(VolumeId(1)).unwrap();
|
||||
assert_eq!(v.file_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_volume_incremental_copy_streams_remote_only_volume_data() {
|
||||
let (service, _tmp, shutdown_tx, dat_bytes, super_block_size, _delete_count) =
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::pb::master_pb::seaweed_client::SeaweedClient;
|
||||
use crate::pb::volume_server_pb;
|
||||
use crate::remote_storage::s3_tier::{S3TierBackend, S3TierConfig};
|
||||
use crate::storage::store::Store;
|
||||
use crate::storage::volume_report::VolumeReportKey;
|
||||
use crate::storage::volume_report_hash::report_hash;
|
||||
use crate::storage::types::NeedleId;
|
||||
|
||||
const DUPLICATE_UUID_RETRY_MESSAGE: &str = "duplicate UUIDs detected, retrying connection";
|
||||
@@ -273,6 +275,13 @@ fn duplicate_directories(store: &Store, duplicated_uuids: &[String]) -> Vec<Stri
|
||||
}
|
||||
|
||||
fn apply_master_volume_options(store: &Store, hb_resp: &master_pb::HeartbeatResponse) -> bool {
|
||||
if hb_resp.volume_digest_supported {
|
||||
store.volume_report.accept_deltas();
|
||||
}
|
||||
if hb_resp.resend_full_volume_list {
|
||||
info!("master asked for the full volume list");
|
||||
store.volume_report.request_full_list();
|
||||
}
|
||||
let mut volume_opts_changed = false;
|
||||
if store.get_preallocate() != hb_resp.preallocate {
|
||||
store.set_preallocate(hb_resp.preallocate);
|
||||
@@ -383,13 +392,14 @@ async fn do_heartbeat(
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel::<master_pb::Heartbeat>(32);
|
||||
|
||||
// This master may know nothing about this server, and has not yet said
|
||||
// whether it understands digests, so start from the whole list.
|
||||
state.store.read().unwrap().volume_report.reset();
|
||||
|
||||
// Keep track of what we sent, to generate delta updates
|
||||
let initial_hb = collect_heartbeat(config, state);
|
||||
let mut last_volumes: HashMap<u32, master_pb::VolumeInformationMessage> = initial_hb
|
||||
.volumes
|
||||
.iter()
|
||||
.map(|v| (v.id, v.clone()))
|
||||
.collect();
|
||||
let (initial_hb, initial_volumes) = collect_heartbeat_with_snapshot(config, state);
|
||||
let mut last_volumes: HashMap<u32, master_pb::VolumeInformationMessage> =
|
||||
initial_volumes.iter().map(|v| (v.id, v.clone())).collect();
|
||||
let mut last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
@@ -454,9 +464,10 @@ async fn do_heartbeat(
|
||||
apply_master_volume_options(&s, &hb_resp)
|
||||
};
|
||||
if changed {
|
||||
let adjusted_hb = collect_heartbeat(config, state);
|
||||
let (adjusted_hb, adjusted_volumes) =
|
||||
collect_heartbeat_with_snapshot(config, state);
|
||||
last_volumes =
|
||||
adjusted_hb.volumes.iter().map(|v| (v.id, v.clone())).collect();
|
||||
adjusted_volumes.iter().map(|v| (v.id, v.clone())).collect();
|
||||
last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
@@ -489,8 +500,8 @@ async fn do_heartbeat(
|
||||
let s = state.store.read().unwrap();
|
||||
s.maybe_adjust_volume_max();
|
||||
}
|
||||
let current_hb = collect_heartbeat(config, state);
|
||||
last_volumes = current_hb.volumes.iter().map(|v| (v.id, v.clone())).collect();
|
||||
let (current_hb, current_volumes) = collect_heartbeat_with_snapshot(config, state);
|
||||
last_volumes = current_volumes.iter().map(|v| (v.id, v.clone())).collect();
|
||||
last_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
@@ -518,8 +529,8 @@ async fn do_heartbeat(
|
||||
info!("Heartbeat stopping");
|
||||
return Ok(None);
|
||||
}
|
||||
let current_hb = collect_heartbeat(config, state);
|
||||
let current_volumes: HashMap<u32, _> = current_hb.volumes.iter().map(|v| (v.id, v.clone())).collect();
|
||||
let held_volumes = collect_volume_snapshot(config, state);
|
||||
let current_volumes: HashMap<u32, _> = held_volumes.iter().map(|v| (v.id, v.clone())).collect();
|
||||
let current_ec_shards = {
|
||||
let store = state.store.read().unwrap();
|
||||
collect_ec_shard_delta_messages(&store)
|
||||
@@ -734,10 +745,10 @@ fn parse_bool_property(value: Option<&String>) -> bool {
|
||||
}
|
||||
|
||||
/// Collect volume information into a Heartbeat message.
|
||||
fn collect_heartbeat(
|
||||
fn collect_heartbeat_with_snapshot(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> master_pb::Heartbeat {
|
||||
) -> (master_pb::Heartbeat, Vec<master_pb::VolumeInformationMessage>) {
|
||||
let mut store = state.store.write().unwrap();
|
||||
let (ec_shards, deleted_ec_shards) = store.delete_expired_ec_volumes();
|
||||
build_heartbeat_with_ec_status(
|
||||
@@ -745,9 +756,28 @@ fn collect_heartbeat(
|
||||
&mut store,
|
||||
deleted_ec_shards,
|
||||
ec_shards.is_empty(),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// Lists the volumes the server holds without touching reporting state or
|
||||
/// expiring anything, for callers that only need to diff against a previous
|
||||
/// snapshot and send a message of their own.
|
||||
fn collect_volume_snapshot(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> Vec<master_pb::VolumeInformationMessage> {
|
||||
let mut store = state.store.write().unwrap();
|
||||
build_heartbeat_with_ec_status(config, &mut store, Vec::new(), true, false).1
|
||||
}
|
||||
|
||||
fn collect_heartbeat(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
) -> master_pb::Heartbeat {
|
||||
collect_heartbeat_with_snapshot(config, state).0
|
||||
}
|
||||
|
||||
fn collect_location_metadata(
|
||||
store: &Store,
|
||||
disk_max_by_id: &[i32],
|
||||
@@ -780,15 +810,19 @@ fn collect_location_metadata(
|
||||
#[cfg(test)]
|
||||
fn build_heartbeat(config: &HeartbeatConfig, store: &mut Store) -> master_pb::Heartbeat {
|
||||
let has_no_ec_shards = collect_live_ec_shards(store, false).is_empty();
|
||||
build_heartbeat_with_ec_status(config, store, Vec::new(), has_no_ec_shards)
|
||||
build_heartbeat_with_ec_status(config, store, Vec::new(), has_no_ec_shards, true).0
|
||||
}
|
||||
|
||||
/// Returns the heartbeat to send and, separately, every volume held. The
|
||||
/// caller derives mount and unmount deltas by diffing successive snapshots, so
|
||||
/// it must not be handed the partial list a heartbeat may carry.
|
||||
fn build_heartbeat_with_ec_status(
|
||||
config: &HeartbeatConfig,
|
||||
store: &mut Store,
|
||||
deleted_ec_shards: Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
has_no_ec_shards: bool,
|
||||
) -> master_pb::Heartbeat {
|
||||
commit_report: bool,
|
||||
) -> (master_pb::Heartbeat, Vec<master_pb::VolumeInformationMessage>) {
|
||||
const MAX_TTL_VOLUME_REMOVAL_DELAY: u32 = 10;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -800,6 +834,13 @@ fn build_heartbeat_with_ec_status(
|
||||
}
|
||||
|
||||
let mut volumes = Vec::new();
|
||||
// Covers every volume held, whether or not this heartbeat names it, so the
|
||||
// master can tell whether applying what it was sent leaves it current.
|
||||
// Volumes skipped below -- quarantined, phantom, expired -- are in neither.
|
||||
let mut volume_digest: u64 = 0;
|
||||
let (send_full_list, report_generation) = store.volume_report.begin();
|
||||
let mut reported_hashes: HashMap<VolumeReportKey, u64> = HashMap::new();
|
||||
let mut changed_volumes = Vec::new();
|
||||
let mut max_file_key = NeedleId(0);
|
||||
let mut max_volume_counts: HashMap<String, u32> = HashMap::new();
|
||||
let mut disk_total_bytes: HashMap<String, u64> = HashMap::new();
|
||||
@@ -875,7 +916,7 @@ fn build_heartbeat_with_ec_status(
|
||||
}
|
||||
|
||||
let (remote_storage_name, remote_storage_key) = vol.remote_storage_name_key();
|
||||
volumes.push(master_pb::VolumeInformationMessage {
|
||||
let volume_message = master_pb::VolumeInformationMessage {
|
||||
id: vol.id.0,
|
||||
size: volume_size,
|
||||
collection: vol.collection.clone(),
|
||||
@@ -892,8 +933,15 @@ fn build_heartbeat_with_ec_status(
|
||||
disk_id: disk_id as u32,
|
||||
remote_storage_name,
|
||||
remote_storage_key,
|
||||
..Default::default()
|
||||
});
|
||||
};
|
||||
let hash = report_hash(&volume_message);
|
||||
volume_digest ^= hash;
|
||||
let key: VolumeReportKey = (volume_message.disk_id, volume_message.id);
|
||||
reported_hashes.insert(key, hash);
|
||||
if send_full_list || store.volume_report.changed(key, hash) {
|
||||
changed_volumes.push(volume_message.clone());
|
||||
}
|
||||
volumes.push(volume_message);
|
||||
} else if vol.is_expired_long_enough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
|
||||
delete_vids.push(vol.id);
|
||||
should_delete_volume = true;
|
||||
@@ -954,10 +1002,23 @@ fn build_heartbeat_with_ec_status(
|
||||
let total_max: i64 = max_volume_counts.values().map(|v| *v as i64).sum();
|
||||
crate::metrics::MAX_VOLUMES.set(total_max);
|
||||
|
||||
let has_no_volumes = volumes.is_empty();
|
||||
// Only when this heartbeat is going to be sent: marking volumes reported
|
||||
// and then discarding the message would leave the master never told.
|
||||
if commit_report {
|
||||
store.volume_report.commit(reported_hashes, report_generation);
|
||||
}
|
||||
|
||||
// has_no_volumes says the server holds nothing, so it may only be derived
|
||||
// from a full list. Deriving it from a changed-only heartbeat would make a
|
||||
// quiet one read as an empty server and drop every volume on it.
|
||||
let (heartbeat_volumes, changed_volumes, has_no_volumes) = if send_full_list {
|
||||
(changed_volumes, Vec::new(), volumes.is_empty())
|
||||
} else {
|
||||
(Vec::new(), changed_volumes, false)
|
||||
};
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(store, &disk_max_by_id);
|
||||
|
||||
master_pb::Heartbeat {
|
||||
let heartbeat = master_pb::Heartbeat {
|
||||
id: store.id.clone(),
|
||||
ip: config.ip.clone(),
|
||||
port: config.port as u32,
|
||||
@@ -966,7 +1027,9 @@ fn build_heartbeat_with_ec_status(
|
||||
data_center: config.data_center.clone(),
|
||||
rack: config.rack.clone(),
|
||||
admin_port: config.port as u32,
|
||||
volumes,
|
||||
volumes: heartbeat_volumes,
|
||||
changed_volumes,
|
||||
volume_digest: Some(volume_digest),
|
||||
deleted_ec_shards,
|
||||
has_no_volumes,
|
||||
has_no_ec_shards,
|
||||
@@ -977,7 +1040,8 @@ fn build_heartbeat_with_ec_status(
|
||||
location_uuids,
|
||||
disk_tags,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
(heartbeat, volumes)
|
||||
}
|
||||
|
||||
fn collect_live_ec_shards(
|
||||
@@ -1246,6 +1310,205 @@ mod tests {
|
||||
assert!(heartbeat.has_no_volumes);
|
||||
}
|
||||
|
||||
// The digest must cover exactly the volumes the heartbeat carries. A volume
|
||||
// reported but left out of the digest, or the reverse, makes the master's
|
||||
// comparison disagree forever. An empty store still reports a digest, so
|
||||
// the master can tell it from a server that computes none.
|
||||
fn reporting_store(dir: &str, count: u32) -> Store {
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
16,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
for id in 1..=count {
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(id),
|
||||
"pics",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
store.volume_report.reset();
|
||||
store
|
||||
}
|
||||
|
||||
// Until the master says it compares digests it may be one that reads a
|
||||
// partial list as the whole truth, so it keeps getting the whole list.
|
||||
#[test]
|
||||
fn test_heartbeat_sends_full_list_until_the_master_accepts() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
|
||||
|
||||
for _ in 0..3 {
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(heartbeat.volumes.len(), 2);
|
||||
assert!(heartbeat.changed_volumes.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
// The one that would be catastrophic: a heartbeat with nothing to report
|
||||
// must not look like a server that has lost every volume.
|
||||
#[test]
|
||||
fn test_quiet_heartbeat_does_not_look_like_an_empty_server() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
|
||||
store.volume_report.accept_deltas();
|
||||
let full = build_heartbeat(&test_config(), &mut store);
|
||||
|
||||
let quiet = build_heartbeat(&test_config(), &mut store);
|
||||
assert!(quiet.volumes.is_empty());
|
||||
assert!(quiet.changed_volumes.is_empty());
|
||||
assert!(!quiet.has_no_volumes);
|
||||
// The digest still covers everything held, not just what was sent.
|
||||
assert_eq!(quiet.volume_digest, full.volume_digest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_heartbeat_reports_only_what_changed() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
|
||||
store.volume_report.accept_deltas();
|
||||
build_heartbeat(&test_config(), &mut store);
|
||||
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(3),
|
||||
"pics",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert!(heartbeat.volumes.is_empty());
|
||||
assert_eq!(heartbeat.changed_volumes.len(), 1);
|
||||
assert_eq!(heartbeat.changed_volumes[0].id, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_heartbeat_returns_to_the_full_list_on_request() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
|
||||
store.volume_report.accept_deltas();
|
||||
build_heartbeat(&test_config(), &mut store);
|
||||
|
||||
store.volume_report.request_full_list();
|
||||
let resent = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(resent.volumes.len(), 2);
|
||||
assert!(resent.changed_volumes.is_empty());
|
||||
|
||||
let next = build_heartbeat(&test_config(), &mut store);
|
||||
assert!(next.volumes.is_empty());
|
||||
}
|
||||
|
||||
// A request that lands while a heartbeat is being built asked about a later
|
||||
// state than that heartbeat carries, so it must survive being committed over.
|
||||
#[test]
|
||||
fn test_full_list_request_during_collection_survives() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
|
||||
store.volume_report.accept_deltas();
|
||||
build_heartbeat(&test_config(), &mut store);
|
||||
|
||||
let (full, generation) = store.volume_report.begin();
|
||||
assert!(!full);
|
||||
store.volume_report.request_full_list();
|
||||
store.volume_report.commit(HashMap::new(), generation);
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(heartbeat.volumes.len(), 2);
|
||||
}
|
||||
|
||||
// Taking a snapshot must not mark volumes as told to a master that is
|
||||
// getting a different message.
|
||||
#[test]
|
||||
fn test_snapshot_does_not_mark_volumes_reported() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
|
||||
store.volume_report.accept_deltas();
|
||||
build_heartbeat(&test_config(), &mut store);
|
||||
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(3),
|
||||
"pics",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// What the notify path does: collect a snapshot, send a message of its own.
|
||||
let snapshot =
|
||||
build_heartbeat_with_ec_status(&test_config(), &mut store, Vec::new(), true, false).1;
|
||||
assert_eq!(snapshot.len(), 3);
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(heartbeat.changed_volumes.len(), 1);
|
||||
assert_eq!(heartbeat.changed_volumes[0].id, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_digests_exactly_what_it_reports() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
8,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let empty = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(empty.volume_digest, Some(0));
|
||||
|
||||
for vid in [VolumeId(1), VolumeId(2)] {
|
||||
store
|
||||
.add_volume(
|
||||
vid,
|
||||
"pics",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(heartbeat.volumes.len(), 2);
|
||||
|
||||
let expected = heartbeat
|
||||
.volumes
|
||||
.iter()
|
||||
.fold(0u64, |acc, m| acc ^ crate::storage::volume_report_hash::report_hash(m));
|
||||
assert_eq!(heartbeat.volume_digest, Some(expected));
|
||||
assert_ne!(heartbeat.volume_digest, Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_tracks_go_read_only_labels_and_disk_id() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -163,6 +163,8 @@ mod tests {
|
||||
https_client_ca_file: String::new(),
|
||||
grpc_cert_file: String::new(),
|
||||
grpc_key_file: String::new(),
|
||||
grpc_client_cert_file: String::new(),
|
||||
grpc_client_key_file: String::new(),
|
||||
grpc_ca_file: String::new(),
|
||||
grpc_allowed_wildcard_domain: String::new(),
|
||||
grpc_volume_allowed_common_names: vec![],
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use tracing::warn;
|
||||
|
||||
@@ -122,6 +122,10 @@ impl DiskLocation {
|
||||
// Scan for .dat files
|
||||
let entries = fs::read_dir(&self.directory)?;
|
||||
let mut dat_files: Vec<(String, VolumeId)> = Vec::new();
|
||||
// Every collection claiming an id, in scan order; open_volumes keeps
|
||||
// the first that opens.
|
||||
let mut to_load: Vec<(VolumeId, Vec<String>)> = Vec::new();
|
||||
let mut queued: HashMap<VolumeId, usize> = HashMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
for entry in entries {
|
||||
@@ -201,6 +205,7 @@ impl DiskLocation {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Load existing data only; never create a phantom `.dat`. A lone
|
||||
// `.vif`/`.idx` (e.g. an EC sidecar whose `.ecx` is on a sibling
|
||||
// disk) would otherwise have Volume::new write an 8-byte stub that
|
||||
@@ -221,30 +226,22 @@ impl DiskLocation {
|
||||
continue;
|
||||
}
|
||||
|
||||
match Volume::new(
|
||||
&self.directory,
|
||||
&self.idx_directory,
|
||||
&collection,
|
||||
vid,
|
||||
needle_map_kind,
|
||||
None, // replica placement read from superblock
|
||||
None, // TTL read from superblock
|
||||
0, // no preallocate on load
|
||||
Version::current(),
|
||||
) {
|
||||
Ok(mut v) => {
|
||||
v.location_disk_space_low = self.is_disk_space_low.clone();
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&collection, "volume"])
|
||||
.inc();
|
||||
self.volumes.insert(vid, v);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(volume_id = vid.0, error = %e, "failed to load volume");
|
||||
match queued.get(&vid) {
|
||||
Some(&i) => to_load[i].1.push(collection),
|
||||
None => {
|
||||
queued.insert(vid, to_load.len());
|
||||
to_load.push((vid, vec![collection]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (collection, vid, v) in self.open_volumes(to_load, needle_map_kind) {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&collection, "volume"])
|
||||
.inc();
|
||||
self.volumes.insert(vid, v);
|
||||
}
|
||||
|
||||
// After regular volumes, auto-discover EC shards on disk so a
|
||||
// fresh restart picks up shards without an explicit
|
||||
// VolumeEcShardsMount RPC. Mirrors Go's loadExistingVolumes
|
||||
@@ -257,6 +254,65 @@ impl DiskLocation {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Open the volumes the directory scan selected. Opening one is dominated
|
||||
/// by reading its .idx into the needle map, so a disk holding thousands
|
||||
/// takes thousands of serial index reads to come up; mirrors Go's
|
||||
/// concurrentLoadingVolumes down to the max(cores, 10) worker count, whose
|
||||
/// floor keeps a small-core box off one-at-a-time on IO-bound work.
|
||||
///
|
||||
/// An id is only spoken for once a volume actually loads, so a corrupt
|
||||
/// `colA_5.dat` still leaves `colB_5.dat` a chance.
|
||||
fn open_volumes(
|
||||
&self,
|
||||
to_load: Vec<(VolumeId, Vec<String>)>,
|
||||
needle_map_kind: NeedleMapKind,
|
||||
) -> Vec<(String, VolumeId, Volume)> {
|
||||
if to_load.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let workers = std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(1)
|
||||
.max(10)
|
||||
.min(to_load.len());
|
||||
|
||||
let next = AtomicUsize::new(0);
|
||||
let opened = Mutex::new(Vec::with_capacity(to_load.len()));
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..workers {
|
||||
scope.spawn(|| loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some((vid, collections)) = to_load.get(i) else {
|
||||
return;
|
||||
};
|
||||
for collection in collections {
|
||||
match Volume::new(
|
||||
&self.directory,
|
||||
&self.idx_directory,
|
||||
collection,
|
||||
*vid,
|
||||
needle_map_kind,
|
||||
None, // replica placement read from superblock
|
||||
None, // TTL read from superblock
|
||||
0, // no preallocate on load
|
||||
Version::current(),
|
||||
) {
|
||||
Ok(mut v) => {
|
||||
v.location_disk_space_low = self.is_disk_space_low.clone();
|
||||
opened.lock().unwrap().push((collection.clone(), *vid, v));
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(volume_id = vid.0, error = %e, "failed to load volume");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
opened.into_inner().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Directory pre-pass that recovers interrupted compaction commits. Collects
|
||||
/// every volume id that still has a .cpc commit marker or a leftover
|
||||
/// .cpd/.cpx temp file across the data and idx directories, then rolls the
|
||||
@@ -1493,6 +1549,60 @@ mod tests {
|
||||
assert!(ids.contains(&VolumeId(2)));
|
||||
}
|
||||
|
||||
// Two collections can name the same volume id on one disk; a candidate
|
||||
// that fails to open must not shadow a good one behind it.
|
||||
#[test]
|
||||
fn test_open_volumes_falls_back_past_a_corrupt_candidate() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
{
|
||||
let mut loc = DiskLocation::new(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
loc.create_volume(
|
||||
VolumeId(9),
|
||||
"good",
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
loc.close();
|
||||
}
|
||||
|
||||
// Same id under another collection, unopenable.
|
||||
let mut bad = vec![0u8; 16];
|
||||
bad[0] = 9; // unsupported version
|
||||
std::fs::write(format!("{}/bad_9.dat", dir), &bad).unwrap();
|
||||
|
||||
let loc = DiskLocation::new(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let opened = loc.open_volumes(
|
||||
vec![(VolumeId(9), vec!["bad".to_string(), "good".to_string()])],
|
||||
NeedleMapKind::InMemory,
|
||||
);
|
||||
|
||||
assert_eq!(opened.len(), 1, "the good candidate should still open");
|
||||
assert_eq!(opened[0].0, "good");
|
||||
assert_eq!(opened[0].1, VolumeId(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_disk_location_delete_volume() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -10,3 +10,5 @@ pub mod super_block;
|
||||
pub mod types;
|
||||
pub mod volume;
|
||||
pub mod volume_idx_repair;
|
||||
pub mod volume_report;
|
||||
pub mod volume_report_hash;
|
||||
@@ -31,6 +31,7 @@ pub struct Store {
|
||||
pub public_url: String,
|
||||
pub data_center: String,
|
||||
pub rack: String,
|
||||
pub volume_report: crate::storage::volume_report::VolumeReportState,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
@@ -45,6 +46,7 @@ impl Store {
|
||||
port: 0,
|
||||
grpc_port: 0,
|
||||
public_url: String::new(),
|
||||
volume_report: Default::default(),
|
||||
data_center: String::new(),
|
||||
rack: String::new(),
|
||||
}
|
||||
@@ -154,6 +156,26 @@ impl Store {
|
||||
self.find_volume(vid).is_some()
|
||||
}
|
||||
|
||||
/// Move a volume's index into the configured `-dir.idx` directory, reloading
|
||||
/// the volume in place. A no-op when the location has no separate index
|
||||
/// directory. Mirrors Go's `Store::ConsolidateVolumeIndex`.
|
||||
pub fn consolidate_volume_index(&mut self, vid: VolumeId) -> Result<(), VolumeError> {
|
||||
for loc in self.locations.iter_mut() {
|
||||
let idx_dir = loc.idx_directory.clone();
|
||||
let data_dir = loc.directory.clone();
|
||||
if let Some(v) = loc.find_volume_mut(vid) {
|
||||
if idx_dir == data_dir {
|
||||
return Ok(());
|
||||
}
|
||||
return v.relocate_index_to(&idx_dir);
|
||||
}
|
||||
}
|
||||
Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("volume {} not found on disk", vid),
|
||||
)))
|
||||
}
|
||||
|
||||
// ---- Volume lifecycle ----
|
||||
|
||||
/// Find the location with fewest volumes (load-balance) of the given disk type.
|
||||
@@ -1386,6 +1408,73 @@ mod tests {
|
||||
assert!(deleted.0 > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_consolidate_volume_index_not_found() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut store = make_test_store(&[dir]);
|
||||
let err = store.consolidate_volume_index(VolumeId(9)).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Io(ref e)
|
||||
if e.kind() == std::io::ErrorKind::NotFound));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_consolidate_volume_index_noop_with_separate_idx_dir() {
|
||||
let root = TempDir::new().unwrap();
|
||||
let data_dir = root.path().join("data");
|
||||
let idx_dir = root.path().join("idx");
|
||||
std::fs::create_dir_all(&data_dir).unwrap();
|
||||
std::fs::create_dir_all(&idx_dir).unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
data_dir.to_str().unwrap(),
|
||||
idx_dir.to_str().unwrap(),
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(1),
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(0xaa),
|
||||
data: b"co-located".to_vec(),
|
||||
data_size: 10,
|
||||
..Needle::default()
|
||||
};
|
||||
store.write_volume_needle(VolumeId(1), &mut n).unwrap();
|
||||
|
||||
// add_volume already placed the index in the -dir.idx directory, so
|
||||
// consolidation has nothing to move and leaves the volume readable.
|
||||
store.consolidate_volume_index(VolumeId(1)).unwrap();
|
||||
let idx_file = format!(
|
||||
"{}.idx",
|
||||
volume_file_name(idx_dir.to_str().unwrap(), "", VolumeId(1))
|
||||
);
|
||||
assert!(std::path::Path::new(&idx_file).exists());
|
||||
|
||||
let mut got = Needle {
|
||||
id: NeedleId(1),
|
||||
..Needle::default()
|
||||
};
|
||||
let count = store.read_volume_needle(VolumeId(1), &mut got).unwrap();
|
||||
assert_eq!(count, 10);
|
||||
assert_eq!(got.data, b"co-located");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_store_multi_location() {
|
||||
let tmp1 = TempDir::new().unwrap();
|
||||
|
||||
@@ -17,7 +17,7 @@ use std::sync::Arc;
|
||||
use std::sync::{Condvar, Mutex};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tracing::{info, warn};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::storage::idx;
|
||||
@@ -227,6 +227,7 @@ impl OldVersionVifVolumeInfo {
|
||||
expire_at_sec: self.destroy_time,
|
||||
read_only: self.read_only,
|
||||
ec_shard_config: None,
|
||||
read_only_can_delete: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -255,6 +256,8 @@ pub struct VifVolumeInfo {
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub ec_shard_config: Option<VifEcShardConfig>,
|
||||
#[serde(default, rename = "readOnlyCanDelete")]
|
||||
pub read_only_can_delete: bool,
|
||||
}
|
||||
|
||||
impl VifVolumeInfo {
|
||||
@@ -285,6 +288,7 @@ impl VifVolumeInfo {
|
||||
parity_shards: c.parity_shards,
|
||||
encode_ts_ns: c.encode_ts_ns,
|
||||
}),
|
||||
read_only_can_delete: pb.read_only_can_delete,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,6 +321,7 @@ impl VifVolumeInfo {
|
||||
encode_ts_ns: c.encode_ts_ns,
|
||||
}
|
||||
}),
|
||||
read_only_can_delete: self.read_only_can_delete,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -684,7 +689,11 @@ impl Volume {
|
||||
let has_volume_info_file = self.load_vif()?;
|
||||
|
||||
if self.volume_info.read_only && !self.has_remote_file {
|
||||
self.no_write_or_delete = true;
|
||||
if self.volume_info.read_only_can_delete {
|
||||
self.no_write_can_delete = true;
|
||||
} else {
|
||||
self.no_write_or_delete = true;
|
||||
}
|
||||
}
|
||||
|
||||
if self.has_remote_file {
|
||||
@@ -1970,11 +1979,13 @@ impl Volume {
|
||||
}
|
||||
|
||||
/// Verify the live needle at the .dat tail: its header must match the
|
||||
/// .idx entry and the .dat must end exactly at its on-disk end. Extra
|
||||
/// bytes mean an unindexed trailing record (a torn append); appending
|
||||
/// after one would place the next needle at an offset the 8-byte .idx
|
||||
/// encoding may not represent, so the volume is quarantined read-only
|
||||
/// instead. Mirrors Go's verifyNeedleIntegrity.
|
||||
/// .idx entry and, on v3, the .dat must end exactly at its on-disk end.
|
||||
/// Extra bytes mean an unindexed trailing record (a torn append);
|
||||
/// appending after one would place the next needle at an offset the
|
||||
/// 8-byte .idx encoding may not represent, so the volume is quarantined
|
||||
/// read-only instead. Mirrors Go's verifyNeedleIntegrity, whose tail
|
||||
/// check is v3-only -- a v1/v2 volume Go serves read-write must not go
|
||||
/// read-only here.
|
||||
fn verify_needle_integrity(
|
||||
&mut self,
|
||||
actual_offset: i64,
|
||||
@@ -2013,15 +2024,16 @@ impl Volume {
|
||||
)));
|
||||
}
|
||||
|
||||
if version == VERSION_3 {
|
||||
let ts_offset =
|
||||
checked_offset as u64 + NEEDLE_HEADER_SIZE as u64 + size.0 as u64 + 4; // skip checksum
|
||||
let mut ts_buf = [0u8; 8];
|
||||
self.read_exact_at_backend(&mut ts_buf, ts_offset)?;
|
||||
let ts = u64::from_be_bytes(ts_buf);
|
||||
if ts > 0 {
|
||||
self.last_append_at_ns = ts;
|
||||
}
|
||||
if version != VERSION_3 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let ts_offset = checked_offset as u64 + NEEDLE_HEADER_SIZE as u64 + size.0 as u64 + 4; // skip checksum
|
||||
let mut ts_buf = [0u8; 8];
|
||||
self.read_exact_at_backend(&mut ts_buf, ts_offset)?;
|
||||
let ts = u64::from_be_bytes(ts_buf);
|
||||
if ts > 0 {
|
||||
self.last_append_at_ns = ts;
|
||||
}
|
||||
|
||||
self.verify_dat_ends_at(checked_offset + get_actual_size(size, version))
|
||||
@@ -2296,34 +2308,39 @@ impl Volume {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mark this volume as read-only (no writes or deletes).
|
||||
/// If `persist` is true, the readonly state is saved to the .vif file.
|
||||
/// Mark this volume as read-only (no writes or deletes) and persist.
|
||||
pub fn set_read_only(&mut self) -> Result<(), VolumeError> {
|
||||
self.no_write_or_delete = true;
|
||||
self.save_vif()
|
||||
self.set_read_only_persist(false, true)
|
||||
}
|
||||
|
||||
/// Mark this volume as read-only, optionally persisting to .vif.
|
||||
pub fn set_read_only_persist(&mut self, persist: bool) -> Result<(), VolumeError> {
|
||||
self.no_write_or_delete = true;
|
||||
/// With `can_delete`, deletes still land so expiring data drains the volume.
|
||||
pub fn set_read_only_persist(
|
||||
&mut self,
|
||||
can_delete: bool,
|
||||
persist: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
if can_delete && !self.has_remote_file {
|
||||
// deletes append tombstones to .idx; a read-only boot attached no writer
|
||||
self.attach_idx_writer_if_missing()?;
|
||||
}
|
||||
self.no_write_or_delete = !can_delete;
|
||||
if can_delete {
|
||||
self.no_write_can_delete = true;
|
||||
} else if !self.has_remote_file {
|
||||
// downgrading a canDelete mark; remote volumes keep their derived flag
|
||||
self.no_write_can_delete = false;
|
||||
}
|
||||
if persist {
|
||||
self.save_vif()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mark this volume as writable (allow writes and deletes).
|
||||
///
|
||||
/// If the volume booted with .vif ReadOnly=true, `load_index` built the
|
||||
/// needle map without an .idx writer attached, so subsequent puts would
|
||||
/// silently skip the on-disk append and only mutate in-memory state —
|
||||
/// surviving until the next restart, then vanishing. Re-attach a writer
|
||||
/// here so writes persist again.
|
||||
pub fn set_writable(&mut self) -> Result<(), VolumeError> {
|
||||
// Attach the writer (if missing) before flipping the flag — otherwise
|
||||
// a transient open/metadata failure would leave the volume marked
|
||||
// writable with no .idx writer, and subsequent puts would silently
|
||||
// skip the on-disk append and vanish on the next restart.
|
||||
/// Attach an append-only .idx writer when missing (read-only boot). Runs
|
||||
/// before any flag flips so a failure cannot leave puts silently skipping
|
||||
/// the on-disk append.
|
||||
fn attach_idx_writer_if_missing(&mut self) -> Result<(), VolumeError> {
|
||||
let needs_idx_writer = self
|
||||
.nm
|
||||
.as_ref()
|
||||
@@ -2341,7 +2358,23 @@ impl Volume {
|
||||
nm.set_idx_file(Box::new(write_file), idx_size);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mark this volume as writable (allow writes and deletes).
|
||||
///
|
||||
/// If the volume booted with .vif ReadOnly=true, `load_index` built the
|
||||
/// needle map without an .idx writer attached, so subsequent puts would
|
||||
/// silently skip the on-disk append and only mutate in-memory state —
|
||||
/// surviving until the next restart, then vanishing. Re-attach a writer
|
||||
/// here so writes persist again.
|
||||
pub fn set_writable(&mut self) -> Result<(), VolumeError> {
|
||||
self.attach_idx_writer_if_missing()?;
|
||||
self.no_write_or_delete = false;
|
||||
// Remote-tiered volumes must stay no_write_can_delete regardless of marks.
|
||||
if !self.has_remote_file {
|
||||
self.no_write_can_delete = false;
|
||||
}
|
||||
self.save_vif()
|
||||
}
|
||||
|
||||
@@ -2351,7 +2384,8 @@ impl Volume {
|
||||
if self.has_remote_file {
|
||||
self.no_write_can_delete = true;
|
||||
self.no_write_or_delete = false;
|
||||
} else {
|
||||
} else if !self.volume_info.read_only_can_delete {
|
||||
// only clear the remoteness-derived flag, not an operator mark
|
||||
self.no_write_can_delete = false;
|
||||
}
|
||||
}
|
||||
@@ -2386,7 +2420,11 @@ impl Volume {
|
||||
if let Ok(vif_info) = serde_json::from_str::<VifVolumeInfo>(&content) {
|
||||
let pb_info = vif_info.to_pb();
|
||||
if pb_info.read_only {
|
||||
self.no_write_or_delete = true;
|
||||
if pb_info.read_only_can_delete {
|
||||
self.no_write_can_delete = true;
|
||||
} else {
|
||||
self.no_write_or_delete = true;
|
||||
}
|
||||
}
|
||||
self.volume_info = pb_info;
|
||||
self.refresh_remote_write_mode();
|
||||
@@ -2451,7 +2489,7 @@ impl Volume {
|
||||
|
||||
/// Save volume info to .vif file in protobuf-JSON format (Go-compatible).
|
||||
/// Matches Go's SaveVolumeInfo: checks writability before writing and propagates errors.
|
||||
fn save_vif(&self) -> Result<(), VolumeError> {
|
||||
fn save_vif(&mut self) -> Result<(), VolumeError> {
|
||||
let vif_path = self.vif_path();
|
||||
|
||||
// Match Go: if file exists but is not writable, return an error
|
||||
@@ -2466,8 +2504,13 @@ impl Volume {
|
||||
}
|
||||
}
|
||||
|
||||
// remoteness-derived no_write_can_delete is not an operator mark; sync
|
||||
// volume_info so refresh_remote_write_mode sees a real mark
|
||||
let marked_can_delete =
|
||||
self.no_write_can_delete && !self.has_remote_file && !self.no_write_or_delete;
|
||||
self.volume_info.read_only = self.no_write_or_delete || marked_can_delete;
|
||||
self.volume_info.read_only_can_delete = marked_can_delete;
|
||||
let mut vif = VifVolumeInfo::from_pb(&self.volume_info);
|
||||
vif.read_only = self.no_write_or_delete;
|
||||
|
||||
// Match Go's SaveVolumeInfo: compute ExpireAtSec from TTL
|
||||
let ttl_seconds = self.super_block.ttl.to_seconds();
|
||||
@@ -2488,7 +2531,10 @@ impl Volume {
|
||||
/// Save full VolumeInfo to .vif file (for tiered storage).
|
||||
/// Matches Go's SaveVolumeInfo which computes ExpireAtSec from TTL.
|
||||
pub fn save_volume_info(&mut self) -> Result<(), VolumeError> {
|
||||
self.volume_info.read_only = self.no_write_or_delete;
|
||||
let marked_can_delete =
|
||||
self.no_write_can_delete && !self.has_remote_file && !self.no_write_or_delete;
|
||||
self.volume_info.read_only = self.no_write_or_delete || marked_can_delete;
|
||||
self.volume_info.read_only_can_delete = marked_can_delete;
|
||||
|
||||
// Compute ExpireAtSec from TTL (matches Go's SaveVolumeInfo)
|
||||
let ttl_seconds = self.super_block.ttl.to_seconds();
|
||||
@@ -3466,6 +3512,62 @@ impl Volume {
|
||||
self.nm = None;
|
||||
}
|
||||
|
||||
/// Move this volume's `.idx` (and `.sdx` when present) from its current
|
||||
/// index directory into `new_idx_dir`, then reload in place. Mirrors Go's
|
||||
/// `Volume::RelocateIndexTo`: it is a no-op when the index is already there
|
||||
/// or nothing is co-located to move, and is used to pull an index a decode
|
||||
/// or reconstruct left beside the data back into the configured `-dir.idx`.
|
||||
pub fn relocate_index_to(&mut self, new_idx_dir: &str) -> Result<(), VolumeError> {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
|
||||
if self.dir_idx == new_idx_dir {
|
||||
return Ok(());
|
||||
}
|
||||
let old_base = volume_file_name(&self.dir_idx, &self.collection, self.id);
|
||||
let old_idx = format!("{old_base}.idx");
|
||||
if !Path::new(&old_idx).exists() {
|
||||
return Ok(()); // nothing co-located to move
|
||||
}
|
||||
let new_base = volume_file_name(new_idx_dir, &self.collection, self.id);
|
||||
let new_idx = format!("{new_base}.idx");
|
||||
|
||||
// Close the index and data handles before moving the index file.
|
||||
let version = self.version();
|
||||
self.close();
|
||||
|
||||
if let Err(e) = rename_or_copy(&old_idx, &new_idx) {
|
||||
// Reopen against the old dir so the volume is not left down; surface
|
||||
// a failed reopen since it leaves the volume unusable until reload.
|
||||
if let Err(reopen) = self.load(true, false, 0, version) {
|
||||
error!(
|
||||
"relocate volume {}: reopen after failed .idx move: {}",
|
||||
self.id, reopen
|
||||
);
|
||||
}
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("relocate index for volume {}: move .idx: {e}", self.id),
|
||||
)));
|
||||
}
|
||||
|
||||
// The .sdx is a derived sorted index; move it when present, but a
|
||||
// failure is not fatal — drop the stale copy so a reload rebuilds it.
|
||||
let old_sdx = format!("{old_base}.sdx");
|
||||
if Path::new(&old_sdx).exists() {
|
||||
let new_sdx = format!("{new_base}.sdx");
|
||||
if let Err(e) = rename_or_copy(&old_sdx, &new_sdx) {
|
||||
warn!(
|
||||
"relocate volume {}: move .sdx: {} (will rebuild)",
|
||||
self.id, e
|
||||
);
|
||||
let _ = fs::remove_file(&old_sdx);
|
||||
}
|
||||
}
|
||||
|
||||
self.dir_idx = new_idx_dir.to_string();
|
||||
self.load(true, false, 0, version)
|
||||
}
|
||||
|
||||
/// Remove all volume files from disk.
|
||||
/// Destroy removes everything related to this volume. When keep_remote_data
|
||||
/// is true the cloud-tier object backing the volume is left intact — used
|
||||
@@ -3608,6 +3710,34 @@ pub fn volume_file_name(dir: &str, collection: &str, id: VolumeId) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move `src` to `dst`, falling back to copy+remove when the two live on
|
||||
/// different filesystems (a real `-dir.idx` split). Mirrors Go's
|
||||
/// `RenameOrCopyFile`: any rename error other than cross-device is fatal, and a
|
||||
/// failed copy or a source that cannot be removed rolls the copy back so a
|
||||
/// failure never leaves two divergent files.
|
||||
fn rename_or_copy(src: &str, dst: &str) -> io::Result<()> {
|
||||
match fs::rename(src, dst) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) if e.raw_os_error() != Some(libc::EXDEV) => return Err(e),
|
||||
Err(_) => {}
|
||||
}
|
||||
fs::copy(src, dst)?;
|
||||
// fsync the destination before dropping the source, matching Go's out.Sync().
|
||||
if let Err(e) = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(dst)
|
||||
.and_then(|f| f.sync_all())
|
||||
{
|
||||
let _ = fs::remove_file(dst);
|
||||
return Err(e);
|
||||
}
|
||||
if let Err(e) = fs::remove_file(src) {
|
||||
let _ = fs::remove_file(dst);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate a monotonically increasing append timestamp.
|
||||
fn get_append_at_ns(last: u64) -> u64 {
|
||||
let now = SystemTime::now()
|
||||
@@ -4115,6 +4245,54 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// Go's tail check is v3-only, so it serves a v1/v2 volume with an
|
||||
// unindexed tail read-write. Checking it here flipped whole legacy disks
|
||||
// read-only on their first boot under this server.
|
||||
#[test]
|
||||
fn test_integrity_skips_dat_tail_check_before_v3() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
{
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
VERSION_2,
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=3u64 {
|
||||
let data = format!("data {}", i);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
|
||||
let mut f = OpenOptions::new().append(true).open(&dat_path).unwrap();
|
||||
f.write_all(&[0xFFu8; 96]).unwrap();
|
||||
f.sync_all().unwrap();
|
||||
drop(f);
|
||||
|
||||
let v = reload_volume(dir);
|
||||
assert_eq!(v.version(), VERSION_2, "volume should reload as v2");
|
||||
assert!(
|
||||
!v.is_no_write_or_delete(),
|
||||
"v2 volume with unindexed .dat tail must stay writable, as in Go"
|
||||
);
|
||||
}
|
||||
|
||||
// Same torn tail, but with a deletion tombstone as the last indexed
|
||||
// record — the tombstone path must also verify the .dat ends at it.
|
||||
#[test]
|
||||
@@ -4441,6 +4619,96 @@ mod tests {
|
||||
assert_eq!(std::str::from_utf8(&n.data).unwrap(), "data 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_relocate_index_to_moves_index_and_serves_reads() {
|
||||
let root = TempDir::new().unwrap();
|
||||
let data_dir = root.path().join("data");
|
||||
let idx_dir = root.path().join("idx");
|
||||
fs::create_dir_all(&data_dir).unwrap();
|
||||
fs::create_dir_all(&idx_dir).unwrap();
|
||||
let data = data_dir.to_str().unwrap();
|
||||
let idx = idx_dir.to_str().unwrap();
|
||||
|
||||
// Create the volume with its index co-located in the data dir (the state
|
||||
// an EC reconstruct leaves), write a needle, and flush.
|
||||
let mut v = Volume::new(
|
||||
data,
|
||||
data,
|
||||
"",
|
||||
VolumeId(7),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
let payload = b"payload-across-relocate".to_vec();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(42),
|
||||
cookie: Cookie(0x55),
|
||||
data: payload.clone(),
|
||||
data_size: payload.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let data_idx = format!("{data}/7.idx");
|
||||
let idx_dir_idx = format!("{idx}/7.idx");
|
||||
assert!(
|
||||
Path::new(&data_idx).exists(),
|
||||
"precondition: index co-located with the data"
|
||||
);
|
||||
|
||||
v.relocate_index_to(idx).unwrap();
|
||||
|
||||
assert!(Path::new(&idx_dir_idx).exists(), "index moved to the idx dir");
|
||||
assert!(
|
||||
!Path::new(&data_idx).exists(),
|
||||
"index gone from the data dir"
|
||||
);
|
||||
assert_eq!(v.file_count(), 1);
|
||||
|
||||
// The volume reloaded in place, so the needle still reads back.
|
||||
let mut got = Needle {
|
||||
id: NeedleId(42),
|
||||
..Needle::default()
|
||||
};
|
||||
v.read_needle(&mut got).unwrap();
|
||||
assert_eq!(got.data, payload, "needle content survives the relocate");
|
||||
|
||||
// Relocating again is a no-op: the index is already where asked.
|
||||
v.relocate_index_to(idx).unwrap();
|
||||
assert!(Path::new(&idx_dir_idx).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_relocate_index_to_noop_when_already_in_place() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
data: b"x".to_vec(),
|
||||
data_size: 1,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
// Data and index share a directory, so there is nothing to move.
|
||||
v.relocate_index_to(dir).unwrap();
|
||||
assert!(Path::new(&format!("{dir}/1.idx")).exists());
|
||||
let mut got = Needle {
|
||||
id: NeedleId(1),
|
||||
..Needle::default()
|
||||
};
|
||||
v.read_needle(&mut got).unwrap();
|
||||
assert_eq!(got.data, b"x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_volume_cookie_mismatch() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
@@ -5045,7 +5313,7 @@ mod tests {
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.set_read_only_persist(true).unwrap();
|
||||
v.set_read_only_persist(false, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
@@ -5110,6 +5378,178 @@ mod tests {
|
||||
assert_eq!(std::str::from_utf8(&probe.data).unwrap(), "after-mark-writable");
|
||||
}
|
||||
|
||||
// readOnlyCanDelete rejects writes, keeps accepting deletes, and survives
|
||||
// a restart.
|
||||
#[test]
|
||||
fn test_read_only_can_delete_persists_and_keeps_deletes_working() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
{
|
||||
let mut v = make_test_volume(dir);
|
||||
for id in 1..=2u64 {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
data: b"payload".to_vec(),
|
||||
data_size: 7,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.set_read_only_persist(true, true).unwrap();
|
||||
assert!(v.no_write_can_delete);
|
||||
assert!(!v.no_write_or_delete);
|
||||
assert!(v.is_read_only());
|
||||
|
||||
let err = v
|
||||
.write_needle(
|
||||
&mut Needle {
|
||||
id: NeedleId(3),
|
||||
cookie: Cookie(3),
|
||||
data: b"blocked".to_vec(),
|
||||
data_size: 7,
|
||||
..Needle::default()
|
||||
},
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, VolumeError::ReadOnly));
|
||||
|
||||
let deleted = v
|
||||
.delete_needle(&mut Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
..Needle::default()
|
||||
})
|
||||
.unwrap();
|
||||
assert!(deleted.0 > 0, "deletes must still land");
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(v.no_write_can_delete, "state must survive a restart");
|
||||
assert!(!v.no_write_or_delete);
|
||||
assert!(
|
||||
v.nm.as_ref().unwrap().has_idx_writer(),
|
||||
"canDelete boot must attach an .idx writer for delete tombstones"
|
||||
);
|
||||
|
||||
let err = v
|
||||
.write_needle(
|
||||
&mut Needle {
|
||||
id: NeedleId(4),
|
||||
cookie: Cookie(4),
|
||||
data: b"blocked".to_vec(),
|
||||
data_size: 7,
|
||||
..Needle::default()
|
||||
},
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, VolumeError::ReadOnly));
|
||||
|
||||
let deleted = v
|
||||
.delete_needle(&mut Needle {
|
||||
id: NeedleId(2),
|
||||
cookie: Cookie(2),
|
||||
..Needle::default()
|
||||
})
|
||||
.unwrap();
|
||||
assert!(deleted.0 > 0, "deletes must still land after restart");
|
||||
|
||||
// downgrading to plain readonly clears the canDelete flag
|
||||
v.set_read_only_persist(false, true).unwrap();
|
||||
assert!(v.no_write_or_delete);
|
||||
assert!(!v.no_write_can_delete);
|
||||
|
||||
// -writable clears the state again.
|
||||
v.set_writable().unwrap();
|
||||
assert!(!v.is_read_only());
|
||||
let mut n = Needle {
|
||||
id: NeedleId(5),
|
||||
cookie: Cookie(5),
|
||||
data: b"writable-again".to_vec(),
|
||||
data_size: 14,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
|
||||
// Upgrading a volume that booted plain persisted-readonly to canDelete
|
||||
// must attach the missing .idx writer, or delete tombstones cannot append.
|
||||
#[test]
|
||||
fn test_read_only_can_delete_upgrade_after_readonly_boot() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
{
|
||||
let mut v = make_test_volume(dir);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
data: b"payload".to_vec(),
|
||||
data_size: 7,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.set_read_only_persist(false, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(v.no_write_or_delete);
|
||||
let err = v
|
||||
.delete_needle(&mut Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
..Needle::default()
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, VolumeError::ReadOnly),
|
||||
"plain readonly must reject deletes"
|
||||
);
|
||||
|
||||
v.set_read_only_persist(true, true).unwrap();
|
||||
assert!(!v.no_write_or_delete);
|
||||
assert!(v.no_write_can_delete);
|
||||
assert!(
|
||||
v.nm.as_ref().unwrap().has_idx_writer(),
|
||||
"upgrade to canDelete must attach the .idx writer"
|
||||
);
|
||||
let deleted = v
|
||||
.delete_needle(&mut Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
..Needle::default()
|
||||
})
|
||||
.unwrap();
|
||||
assert!(deleted.0 > 0, "deletes must land once canDelete is set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_vif_defaults_local_version_and_bytes_offset() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Mirror of `weed/storage/store_volume_report.go`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Identifies one reported copy. Keyed by disk as well as id because a volume
|
||||
/// id can be mounted on two disks, and reporting one of them would leave the
|
||||
/// other's changes untold.
|
||||
pub type VolumeReportKey = (u32, u32);
|
||||
|
||||
/// Remembers what the master was last told about each volume, so a heartbeat
|
||||
/// can carry only what moved since.
|
||||
///
|
||||
/// Per-connection: a server that reconnects, or reaches a different master,
|
||||
/// knows nothing about what that master holds and starts again from the full
|
||||
/// list. The default has told no master anything, so it sends the whole list
|
||||
/// until one accepts changes.
|
||||
#[derive(Default)]
|
||||
pub struct VolumeReportState {
|
||||
/// Set once the master says it compares digests. Until then the whole list
|
||||
/// goes every time, which is what an older master needs.
|
||||
deltas_accepted: AtomicBool,
|
||||
full_list_needed: AtomicBool,
|
||||
/// Counts requests for the whole list, so one arriving while a heartbeat is
|
||||
/// being built is not marked satisfied by it.
|
||||
full_list_generation: AtomicU64,
|
||||
last_reported: Mutex<HashMap<VolumeReportKey, u64>>,
|
||||
}
|
||||
|
||||
impl VolumeReportState {
|
||||
/// Drops everything known about the master's view.
|
||||
pub fn reset(&self) {
|
||||
self.deltas_accepted.store(false, Ordering::Relaxed);
|
||||
self.full_list_needed.store(true, Ordering::Relaxed);
|
||||
self.full_list_generation.fetch_add(1, Ordering::Relaxed);
|
||||
self.last_reported.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
pub fn accept_deltas(&self) {
|
||||
self.deltas_accepted.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn request_full_list(&self) {
|
||||
self.full_list_needed.store(true, Ordering::Relaxed);
|
||||
self.full_list_generation.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Reports whether this heartbeat must carry the whole list, and the
|
||||
/// request it answers.
|
||||
pub fn begin(&self) -> (bool, u64) {
|
||||
let full = self.full_list_needed.load(Ordering::Relaxed)
|
||||
|| !self.deltas_accepted.load(Ordering::Relaxed);
|
||||
(full, self.full_list_generation.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Reports whether the master needs telling about this volume, given what
|
||||
/// it was last told.
|
||||
pub fn changed(&self, key: VolumeReportKey, hash: u64) -> bool {
|
||||
self.last_reported.lock().unwrap().get(&key) != Some(&hash)
|
||||
}
|
||||
|
||||
/// Records what this heartbeat told the master. Volumes absent from
|
||||
/// `reported` are forgotten, so one that comes back is reported again.
|
||||
pub fn commit(&self, reported: HashMap<VolumeReportKey, u64>, generation: u64) {
|
||||
*self.last_reported.lock().unwrap() = reported;
|
||||
// A request that arrived while this heartbeat was being built asked
|
||||
// about a later state than it carries, so it stands.
|
||||
if self.full_list_generation.load(Ordering::Relaxed) == generation {
|
||||
self.full_list_needed.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Mirror of `weed/storage/volume_report_hash.go`.
|
||||
//!
|
||||
//! The master compares the digest a volume server reports against one it
|
||||
//! computes itself, so this has to agree with the Go implementation
|
||||
//! byte-for-byte. `report_hash_vectors` pins that against values produced by
|
||||
//! the Go side; do not change the layout without regenerating them there.
|
||||
|
||||
use xxhash_rust::xxh64::xxh64;
|
||||
|
||||
use crate::pb::master_pb;
|
||||
|
||||
/// Digests everything a volume server reports about a volume.
|
||||
///
|
||||
/// It must cover every field of `VolumeInformationMessage`: a change the hash
|
||||
/// misses is a change the master would never be told about.
|
||||
pub fn report_hash(m: &master_pb::VolumeInformationMessage) -> u64 {
|
||||
let mut buf = [0u8; 57];
|
||||
buf[0..4].copy_from_slice(&m.id.to_le_bytes());
|
||||
buf[4..12].copy_from_slice(&m.size.to_le_bytes());
|
||||
buf[12..20].copy_from_slice(&m.file_count.to_le_bytes());
|
||||
buf[20..28].copy_from_slice(&m.delete_count.to_le_bytes());
|
||||
buf[28..36].copy_from_slice(&m.deleted_byte_count.to_le_bytes());
|
||||
// The master stores these narrowed, so hash what it will hold, not what the
|
||||
// wire type could carry.
|
||||
buf[36..40].copy_from_slice(&((m.replica_placement as u8) as u32).to_le_bytes());
|
||||
buf[40..44].copy_from_slice(&((m.version as u8) as u32).to_le_bytes());
|
||||
buf[44..48].copy_from_slice(&normalize_ttl(m.ttl).to_le_bytes());
|
||||
buf[48..52].copy_from_slice(&m.compact_revision.to_le_bytes());
|
||||
buf[52..56].copy_from_slice(&m.disk_id.to_le_bytes());
|
||||
if m.read_only {
|
||||
buf[56] = 1;
|
||||
}
|
||||
let mut h = xxh64(&buf, 0);
|
||||
|
||||
h = fold(h, xxh64(&(m.modified_at_second as u64).to_le_bytes(), 0));
|
||||
h = fold(h, xxh64(m.collection.as_bytes(), 0));
|
||||
h = fold(h, xxh64(m.disk_type.as_bytes(), 0));
|
||||
// Not the remote storage key: the master does not keep it, so a change to
|
||||
// it alters nothing its copy holds.
|
||||
h = fold(h, xxh64(m.remote_storage_name.as_bytes(), 0));
|
||||
h
|
||||
}
|
||||
|
||||
/// A ttl whose count is zero encodes as zero however the unit is set, matching
|
||||
/// what the master stores after decoding it.
|
||||
fn normalize_ttl(ttl: u32) -> u32 {
|
||||
let count = (ttl >> 8) & 0xff;
|
||||
if count == 0 {
|
||||
return 0;
|
||||
}
|
||||
(count << 8) | (ttl & 0xff)
|
||||
}
|
||||
|
||||
/// Combines two hashes order-dependently, so swapping two string fields is not
|
||||
/// invisible.
|
||||
fn fold(h: u64, x: u64) -> u64 {
|
||||
let h = (h ^ x).wrapping_mul(0x9E37_79B9_7F4A_7C15);
|
||||
h ^ (h >> 29)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Produced by the Go implementation. If these drift, every volume server
|
||||
// running this build reports a digest the master can never match, and falls
|
||||
// back to sending its whole volume list forever.
|
||||
#[test]
|
||||
fn report_hash_vectors() {
|
||||
let empty = master_pb::VolumeInformationMessage::default();
|
||||
assert_eq!(report_hash(&empty), 10988706248825469653);
|
||||
|
||||
let mut one = master_pb::VolumeInformationMessage::default();
|
||||
one.id = 1;
|
||||
assert_eq!(report_hash(&one), 2035849960016744285);
|
||||
|
||||
let full = master_pb::VolumeInformationMessage {
|
||||
id: 42,
|
||||
size: 1 << 30,
|
||||
collection: "c".to_string(),
|
||||
file_count: 7,
|
||||
delete_count: 2,
|
||||
deleted_byte_count: 99,
|
||||
read_only: true,
|
||||
replica_placement: 10,
|
||||
version: 3,
|
||||
ttl: 3 << 8,
|
||||
compact_revision: 5,
|
||||
modified_at_second: 1700000000,
|
||||
remote_storage_name: "s3".to_string(),
|
||||
remote_storage_key: "k/1.dat".to_string(),
|
||||
disk_type: "ssd".to_string(),
|
||||
disk_id: 2,
|
||||
};
|
||||
assert_eq!(report_hash(&full), 2748844479819636032);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ttl_with_no_count_is_dropped() {
|
||||
assert_eq!(normalize_ttl(0), 0);
|
||||
assert_eq!(normalize_ttl(3), 0);
|
||||
assert_eq!(normalize_ttl(3 << 8), 3 << 8);
|
||||
assert_eq!(normalize_ttl((3 << 8) | 4), (3 << 8) | 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Parity guard for the gRPC admin-auth gate.
|
||||
//!
|
||||
//! Every `VolumeServer` handler must either call `check_grpc_admin_auth` or be
|
||||
//! listed here as intentionally ungated, with the reason it stays open. Mirrors
|
||||
//! the Go side's `TestVolumeServerAdminAuthCoverage`
|
||||
//! (`weed/server/volume_grpc_admin_auth_coverage_test.go`). The gate had
|
||||
//! silently dropped off 15 handlers on the Rust side; this keeps the two
|
||||
//! implementations from drifting apart again.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Handlers that intentionally run without `check_grpc_admin_auth`, each with
|
||||
/// the reason. Kept in sync with `ungatedVolumeServerRPCs` on the Go side.
|
||||
///
|
||||
/// The split is by caller, not by how destructive the call is: the guard checks
|
||||
/// the peer IP against `-whiteList`, which holds masters, shell hosts and
|
||||
/// workers -- not every peer volume server. Gating a volume-server ->
|
||||
/// volume-server call therefore breaks replication, EC and tiering, so those
|
||||
/// calls stay open and need a cluster-peer identity before they can be closed.
|
||||
fn ungated_handlers() -> HashMap<&'static str, &'static str> {
|
||||
[
|
||||
// Cluster-internal: issued volume server -> volume server.
|
||||
("copy_file", "replica sync and EC task pull whole files from a peer"),
|
||||
("read_needle_blob", "replica sync, vacuum and EC rebuild read needles from a peer"),
|
||||
("read_needle_meta", "replica sync compares needle metadata across peers"),
|
||||
("write_needle_blob", "replica sync repairs a peer's needle"),
|
||||
("receive_file", "EC shard distribution pushes shards to a peer"),
|
||||
("read_volume_file_status", "the copy path queries the source volume server"),
|
||||
("volume_ec_shard_read", "a volume server reads EC shards held by a peer"),
|
||||
("volume_ec_blob_delete", "EC delete is fanned out to the shard holders"),
|
||||
("volume_ec_shards_info", "EC verification polls shard holders"),
|
||||
("volume_ec_shards_mount", "EC shard distribution mounts on the receiving peer"),
|
||||
("volume_incremental_copy", "volume backup pulls increments from a peer"),
|
||||
("volume_sync_status", "sync compares volume state across peers"),
|
||||
("volume_tail_sender", "the tail source streams to the receiving peer"),
|
||||
("volume_status", "replica sync and the master's vacuum loop poll volume status"),
|
||||
// Read-only or liveness: no state change.
|
||||
("ping", "liveness probe"),
|
||||
("get_state", "read-only volume server state"),
|
||||
("query", "read-only data query"),
|
||||
("vacuum_volume_check", "read-only garbage ratio; the vacuum steps that act on it are gated"),
|
||||
("volume_server_status", "read-only status, the gRPC counterpart of the /status page"),
|
||||
]
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a handler body actually invokes the gate. We can't run a real AST
|
||||
/// pass like the Go side without pulling in a parser, so approximate it: drop
|
||||
/// `//` line comments (the realistic way a stray mention would sneak in) and
|
||||
/// look for the call form `check_grpc_admin_auth(`, not the bare identifier, so
|
||||
/// a comment or doc reference can't make an ungated handler pass.
|
||||
fn calls_gate(body: &str) -> bool {
|
||||
body.lines()
|
||||
.map(|line| line.split_once("//").map_or(line, |(code, _)| code))
|
||||
.any(|code| code.contains("check_grpc_admin_auth("))
|
||||
}
|
||||
|
||||
/// Enumerate the `VolumeServer` trait handlers and whether each gates on
|
||||
/// `check_grpc_admin_auth`, by scanning the source of the trait impl block.
|
||||
fn handler_gating(src: &str) -> Vec<(String, bool)> {
|
||||
let impl_start = src
|
||||
.find("impl VolumeServer for VolumeGrpcService {")
|
||||
.expect("locate the VolumeServer trait impl");
|
||||
let after = &src[impl_start..];
|
||||
// rustfmt keeps every method body indented, so the impl's own closing brace
|
||||
// is the first line that begins at column 0.
|
||||
let impl_end = after
|
||||
.match_indices("\n}")
|
||||
.next()
|
||||
.map(|(i, _)| i + 1)
|
||||
.expect("locate the end of the trait impl");
|
||||
let block = &after[..impl_end];
|
||||
|
||||
let marker = "\n async fn ";
|
||||
let starts: Vec<usize> = block.match_indices(marker).map(|(i, _)| i).collect();
|
||||
let mut handlers = Vec::with_capacity(starts.len());
|
||||
for (i, &start) in starts.iter().enumerate() {
|
||||
let name_start = start + marker.len();
|
||||
let name_end = name_start
|
||||
+ block[name_start..]
|
||||
.find('(')
|
||||
.expect("handler signature has an argument list");
|
||||
let name = block[name_start..name_end].to_string();
|
||||
let body_end = starts.get(i + 1).copied().unwrap_or(block.len());
|
||||
let gated = calls_gate(&block[start..body_end]);
|
||||
handlers.push((name, gated));
|
||||
}
|
||||
handlers
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_server_admin_auth_coverage() {
|
||||
let src = std::fs::read_to_string(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/src/server/grpc_server.rs"
|
||||
))
|
||||
.expect("read grpc_server.rs");
|
||||
|
||||
let handlers = handler_gating(&src);
|
||||
assert!(
|
||||
handlers.len() >= 40,
|
||||
"parsed only {} handlers from the trait impl, expected the full service",
|
||||
handlers.len()
|
||||
);
|
||||
|
||||
let ungated = ungated_handlers();
|
||||
let mut problems = Vec::new();
|
||||
for (name, gated) in &handlers {
|
||||
match (gated, ungated.contains_key(name.as_str())) {
|
||||
(true, true) => problems.push(format!(
|
||||
"{name} calls check_grpc_admin_auth but is also listed as intentionally ungated; drop it from ungated_handlers"
|
||||
)),
|
||||
(false, false) => problems.push(format!(
|
||||
"{name} does not call check_grpc_admin_auth and is not listed as intentionally ungated; gate it, or add it with the reason it must stay open"
|
||||
)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the exemption list honest: an entry for a handler that no longer
|
||||
// exists hides the fact that nothing is being exempted.
|
||||
let names: HashSet<&str> = handlers.iter().map(|(n, _)| n.as_str()).collect();
|
||||
for name in ungated.keys() {
|
||||
if !names.contains(name) {
|
||||
problems.push(format!(
|
||||
"ungated_handlers lists \"{name}\", which is not a VolumeServer handler"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
assert!(problems.is_empty(), "admin-auth coverage gaps:\n{}", problems.join("\n"));
|
||||
}
|
||||
@@ -184,6 +184,10 @@ GET /api/history?cluster_id=<uuid>&days=90
|
||||
# Get per-cluster disk usage and volume servers over time, largest first,
|
||||
# the rest summed as "other"
|
||||
GET /api/cluster-sizes?days=30&limit=20
|
||||
|
||||
# Get how many clusters ran each version over time, oldest version first,
|
||||
# the rest summed as "other"
|
||||
GET /api/versions?days=30&limit=8
|
||||
```
|
||||
|
||||
### Monitoring
|
||||
|
||||
@@ -174,6 +174,30 @@ func (h *Handler) GetClusterSizes(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(h.storage.GetClusterSizeSeries(days, limit))
|
||||
}
|
||||
|
||||
func (h *Handler) GetVersions(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
days := 30 // default
|
||||
if daysStr := r.URL.Query().Get("days"); daysStr != "" {
|
||||
if d, err := strconv.Atoi(daysStr); err == nil && d > 0 && d <= 365 {
|
||||
days = d
|
||||
}
|
||||
}
|
||||
|
||||
limit := 8 // default, the number of colours the version stack has
|
||||
if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
|
||||
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 1000 {
|
||||
limit = l
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(h.storage.GetVersionSeries(days, limit))
|
||||
}
|
||||
|
||||
func (h *Handler) GetHistory(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
|
||||
@@ -143,12 +143,24 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">Version Distribution</div>
|
||||
<canvas id="versionChart" width="400" height="200"></canvas>
|
||||
<div style="position: relative; height: 320px;">
|
||||
<canvas id="versionChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">Versions Over Time</div>
|
||||
<div class="chart-subtitle" id="versionSeriesTotal"></div>
|
||||
<div style="position: relative; height: 420px;">
|
||||
<canvas id="versionSeriesChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">Operating System Distribution</div>
|
||||
<canvas id="osChart" width="400" height="200"></canvas>
|
||||
<div style="position: relative; height: 320px;">
|
||||
<canvas id="osChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
@@ -197,12 +209,20 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
|
||||
const sizesResponse = await fetch('/api/cluster-sizes?days=30&limit=20');
|
||||
const sizes = await sizesResponse.json();
|
||||
|
||||
updateStats(stats);
|
||||
updateCharts(stats);
|
||||
updateClusterSizes(sizes);
|
||||
|
||||
// Load the fleet's version make-up over time
|
||||
const versionsResponse = await fetch('/api/versions?days=30&limit=8');
|
||||
const versions = await versionsResponse.json();
|
||||
|
||||
// Show the dashboard before drawing into it: a canvas in a
|
||||
// display:none container measures zero, and a pie sized from
|
||||
// that never grows back.
|
||||
document.getElementById('loading').style.display = 'none';
|
||||
document.getElementById('dashboard').style.display = 'block';
|
||||
|
||||
updateStats(stats);
|
||||
updateCharts(stats);
|
||||
updateVersions(versions);
|
||||
updateClusterSizes(sizes);
|
||||
} catch (error) {
|
||||
console.error('Error loading dashboard:', error);
|
||||
showError('Failed to load telemetry data: ' + error.message);
|
||||
@@ -246,6 +266,9 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
// Without this the canvas keeps its 2:1 attribute ratio at
|
||||
// the card's full width, drawing a pie taller than the card.
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'bottom'
|
||||
@@ -298,6 +321,76 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
|
||||
return (unit === 0 ? value : value.toFixed(value >= 100 ? 0 : 1)) + ' ' + units[unit];
|
||||
}
|
||||
|
||||
// Fixed hues rather than the evenly spaced ones the cluster stacks use:
|
||||
// a handful of versions is a set you read, and evenly spaced hues put
|
||||
// pairs next to each other that colour-blind readers can't separate.
|
||||
const versionColors = ['#2a78d6', '#eb6834', '#1baf7a', '#eda100',
|
||||
'#e87ba4', '#008300', '#4a3aa7', '#e34948'];
|
||||
|
||||
// One stacked band per version: the band is how many clusters ran that
|
||||
// version that day, the top of the stack is the confirmed fleet, so the
|
||||
// chart shows both how it grows and what it upgrades to. The pie above
|
||||
// it is the same fleet on the last of these days.
|
||||
function updateVersions(series) {
|
||||
const versions = series.versions || [];
|
||||
const dates = series.dates || [];
|
||||
const total = series.total_clusters || 0;
|
||||
document.getElementById('versionSeriesTotal').textContent =
|
||||
total + ' cluster' + (total === 1 ? '' : 's') + ' on ' + (dates[dates.length - 1] || 'no data');
|
||||
|
||||
// Newest release on the floor, oldest on top: the current release
|
||||
// is the band being read, and one anchored to the baseline reads
|
||||
// straight off the axis instead of riding on everything below it.
|
||||
// Colours follow the same order, so a release keeps its colour as
|
||||
// older ones age out from the top.
|
||||
const datasets = versions.slice().reverse().map((v, i) =>
|
||||
band(v.version, v.clusters, '#ffffff', versionColors[i % versionColors.length], 2));
|
||||
if (series.other) {
|
||||
datasets.push(band('other (' + series.other.count + ' versions)', series.other.clusters,
|
||||
'#ffffff', '#9a9a94', 2));
|
||||
}
|
||||
|
||||
stackedArea('versionSeriesChart', dates, datasets, value => value, { plugins: [bandLabels] });
|
||||
}
|
||||
|
||||
// Writes each version into its own band, so the chart reads without
|
||||
// matching colours against the legend. Bands too thin to hold the text
|
||||
// keep it, and the halo carries it over whatever it crosses.
|
||||
const bandLabels = {
|
||||
id: 'bandLabels',
|
||||
afterDatasetsDraw(chart) {
|
||||
const ctx = chart.ctx;
|
||||
ctx.save();
|
||||
ctx.font = '600 12px -apple-system, BlinkMacSystemFont, sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.lineJoin = 'round';
|
||||
chart.data.datasets.forEach((dataset, d) => {
|
||||
const meta = chart.getDatasetMeta(d);
|
||||
if (meta.hidden) return;
|
||||
// Label where the band is thickest, so the text has room.
|
||||
let at = -1, thickest = 0;
|
||||
dataset.data.forEach((value, i) => {
|
||||
if (value > thickest) {
|
||||
thickest = value;
|
||||
at = i;
|
||||
}
|
||||
});
|
||||
const point = at >= 0 && meta.data[at];
|
||||
if (!point) return;
|
||||
const below = d === 0 ? chart.scales.y.getPixelForValue(0)
|
||||
: chart.getDatasetMeta(d - 1).data[at].y;
|
||||
if (below - point.y < 18) return;
|
||||
ctx.lineWidth = 3;
|
||||
ctx.strokeStyle = 'rgba(255, 255, 255, 0.85)';
|
||||
ctx.strokeText(dataset.label, point.x, (point.y + below) / 2);
|
||||
ctx.fillStyle = '#1a1a1a';
|
||||
ctx.fillText(dataset.label, point.x, (point.y + below) / 2);
|
||||
});
|
||||
ctx.restore();
|
||||
}
|
||||
};
|
||||
|
||||
// Disk usage and volume servers both drawn as one stacked band per
|
||||
// cluster over time: the band is that cluster's share, the top of the
|
||||
// stack is the fleet total. Clusters beyond the requested limit are
|
||||
@@ -337,6 +430,24 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
|
||||
'#9E9E9E', 'rgba(158, 158, 158, 0.6)'));
|
||||
}
|
||||
|
||||
stackedArea(canvasId, dates, datasets, format, {
|
||||
onClick: (event, elements) => {
|
||||
const id = elements.length && clusterSizeIds[elements[0].datasetIndex];
|
||||
if (id) {
|
||||
document.getElementById('clusterIdInput').value = id;
|
||||
loadClusterHistory();
|
||||
}
|
||||
},
|
||||
// The legend shows shortened ids; the tooltip has room for the
|
||||
// full one to paste into the lookup box.
|
||||
label: item => (clusterSizeIds[item.datasetIndex] || item.dataset.label) + ': ' + format(item.raw)
|
||||
});
|
||||
}
|
||||
|
||||
// Draws the bands as one stack, so their heights add up to the day's
|
||||
// total. hooks.onClick, hooks.label and hooks.plugins are optional.
|
||||
function stackedArea(canvasId, dates, datasets, format, hooks) {
|
||||
hooks = hooks || {};
|
||||
const ctx = document.getElementById(canvasId).getContext('2d');
|
||||
if (charts[canvasId]) {
|
||||
charts[canvasId].destroy();
|
||||
@@ -344,25 +455,17 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
|
||||
charts[canvasId] = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: { labels: dates, datasets: datasets },
|
||||
plugins: hooks.plugins,
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: { mode: 'band', intersect: false },
|
||||
onClick: (event, elements) => {
|
||||
const id = elements.length && clusterSizeIds[elements[0].datasetIndex];
|
||||
if (id) {
|
||||
document.getElementById('clusterIdInput').value = id;
|
||||
loadClusterHistory();
|
||||
}
|
||||
},
|
||||
onClick: hooks.onClick,
|
||||
plugins: {
|
||||
legend: { position: 'bottom', labels: { boxWidth: 12, font: { size: 11 } } },
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
label: item => {
|
||||
const id = clusterSizeIds[item.datasetIndex];
|
||||
return (id || item.dataset.label) + ': ' + format(item.raw);
|
||||
}
|
||||
label: hooks.label || (item => item.dataset.label + ': ' + format(item.raw))
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -396,13 +499,13 @@ func (h *Handler) ServeIndex(w http.ResponseWriter, r *http.Request) {
|
||||
return [];
|
||||
};
|
||||
|
||||
function band(label, data, borderColor, backgroundColor) {
|
||||
function band(label, data, borderColor, backgroundColor, borderWidth) {
|
||||
return {
|
||||
label: label,
|
||||
data: data,
|
||||
borderColor: borderColor,
|
||||
backgroundColor: backgroundColor,
|
||||
borderWidth: 1,
|
||||
borderWidth: borderWidth || 1,
|
||||
pointRadius: 0,
|
||||
pointHitRadius: 8,
|
||||
fill: true,
|
||||
|
||||
@@ -77,6 +77,7 @@ func main() {
|
||||
mux.HandleFunc("/api/metrics", corsMiddleware(logMiddleware(apiHandler.GetMetrics)))
|
||||
mux.HandleFunc("/api/history", corsMiddleware(logMiddleware(apiHandler.GetHistory)))
|
||||
mux.HandleFunc("/api/cluster-sizes", corsMiddleware(logMiddleware(apiHandler.GetClusterSizes)))
|
||||
mux.HandleFunc("/api/versions", corsMiddleware(logMiddleware(apiHandler.GetVersions)))
|
||||
|
||||
// Dashboard (optional)
|
||||
if *enableDashboard {
|
||||
|
||||
@@ -20,6 +20,7 @@ type HistorySample struct {
|
||||
TotalDiskBytes uint64 `json:"disk"`
|
||||
TotalVolumeCount int32 `json:"volumes"`
|
||||
VolumeServerCount int32 `json:"servers"`
|
||||
Version string `json:"ver,omitempty"` // empty in samples written before this was recorded
|
||||
}
|
||||
|
||||
// appendHistory records the report as the cluster's sample for the day,
|
||||
@@ -30,6 +31,7 @@ func (s *PrometheusStorage) appendHistory(data *proto.TelemetryData, receivedAt
|
||||
TotalDiskBytes: data.TotalDiskBytes,
|
||||
TotalVolumeCount: data.TotalVolumeCount,
|
||||
VolumeServerCount: data.VolumeServerCount,
|
||||
Version: data.Version,
|
||||
}
|
||||
h := s.histories[data.TopologyId]
|
||||
if n := len(h); n > 0 && sameUTCDay(h[n-1].Ts, sample.Ts) {
|
||||
@@ -110,16 +112,17 @@ func utcDay(ts int64) time.Time {
|
||||
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func diskBytes(s HistorySample) uint64 { return s.TotalDiskBytes }
|
||||
func serverCount(s HistorySample) uint64 { return uint64(s.VolumeServerCount) }
|
||||
func diskBytes(s HistorySample) uint64 { return s.TotalDiskBytes }
|
||||
func serverCount(s HistorySample) uint64 { return uint64(s.VolumeServerCount) }
|
||||
func sampleVersion(s HistorySample) string { return s.Version }
|
||||
|
||||
// align lays one cluster's history onto the axis, picking `value` out of each
|
||||
// sample. Clusters report roughly once a day at no fixed hour, so a day without
|
||||
// a report carries the previous value forward rather than dropping to zero; a
|
||||
// cluster that stopped reporting altogether ends at its last sample instead of
|
||||
// holding capacity forever. Reports false when the cluster has nothing in range.
|
||||
func (d dailySeries) align(history []HistorySample, activeSince int64, value func(HistorySample) uint64) ([]uint64, bool) {
|
||||
out := make([]uint64, len(d.dates))
|
||||
func align[T any](d dailySeries, history []HistorySample, activeSince int64, value func(HistorySample) T) ([]T, bool) {
|
||||
out := make([]T, len(d.dates))
|
||||
reported := make([]bool, len(d.dates))
|
||||
first, last := -1, -1
|
||||
for _, sample := range history {
|
||||
|
||||
@@ -44,9 +44,18 @@ func (s *PrometheusStorage) LoadState(path string) (int, error) {
|
||||
loaded++
|
||||
}
|
||||
for id, h := range state.Histories {
|
||||
if _, ok := s.instances[id]; ok && len(h) > 0 {
|
||||
s.histories[id] = h
|
||||
instance, ok := s.instances[id]
|
||||
if !ok || len(h) == 0 {
|
||||
continue
|
||||
}
|
||||
// State written before versions were recorded carries none on its
|
||||
// samples. The newest sample is the report the instance record itself
|
||||
// came from, so that day's version is known and the version series can
|
||||
// start there rather than a day after the upgrade.
|
||||
if newest := len(h) - 1; h[newest].Version == "" {
|
||||
h[newest].Version = instance.TelemetryData.Version
|
||||
}
|
||||
s.histories[id] = h
|
||||
}
|
||||
s.updateStats()
|
||||
return loaded, nil
|
||||
|
||||
@@ -72,3 +72,38 @@ func TestStateRoundTrip(t *testing.T) {
|
||||
t.Error("dirty flag set after load")
|
||||
}
|
||||
}
|
||||
|
||||
// State written before versions were recorded still knows the version of the
|
||||
// report its newest sample came from: the instance record's.
|
||||
func TestLoadStateFillsNewestSampleVersion(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "telemetry-state.json")
|
||||
|
||||
s := newPrometheusStorage(prometheus.NewRegistry())
|
||||
report := &proto.TelemetryData{TopologyId: "test-cluster-1", Version: "4.40", Os: "linux/amd64"}
|
||||
if err := s.StoreTelemetry(report); err != nil {
|
||||
t.Fatalf("store: %v", err)
|
||||
}
|
||||
yesterday := time.Now().AddDate(0, 0, -1).Unix()
|
||||
s.histories[report.TopologyId] = []HistorySample{
|
||||
{Ts: yesterday, TotalDiskBytes: 10},
|
||||
{Ts: time.Now().Unix(), TotalDiskBytes: 20},
|
||||
}
|
||||
if err := s.SaveStateIfDirty(path); err != nil {
|
||||
t.Fatalf("save: %v", err)
|
||||
}
|
||||
|
||||
s = newPrometheusStorage(prometheus.NewRegistry())
|
||||
if _, err := s.LoadState(path); err != nil {
|
||||
t.Fatalf("load: %v", err)
|
||||
}
|
||||
loaded := s.histories[report.TopologyId]
|
||||
if len(loaded) != 2 {
|
||||
t.Fatalf("history = %+v, want 2 samples", loaded)
|
||||
}
|
||||
if loaded[1].Version != report.Version {
|
||||
t.Errorf("newest sample version = %q, want %q", loaded[1].Version, report.Version)
|
||||
}
|
||||
if loaded[0].Version != "" {
|
||||
t.Errorf("older sample version = %q, want it left unknown", loaded[0].Version)
|
||||
}
|
||||
}
|
||||
@@ -180,12 +180,12 @@ func (s *PrometheusStorage) GetMetrics(days int) (map[string]interface{}, error)
|
||||
diskUsage := make([]uint64, len(axis.dates))
|
||||
serverCounts := make([]int64, len(axis.dates))
|
||||
for _, history := range histories {
|
||||
if disk, ok := axis.align(history, activeSince, diskBytes); ok {
|
||||
if disk, ok := align(axis, history, activeSince, diskBytes); ok {
|
||||
for i, v := range disk {
|
||||
diskUsage[i] += v
|
||||
}
|
||||
}
|
||||
if servers, ok := axis.align(history, activeSince, serverCount); ok {
|
||||
if servers, ok := align(axis, history, activeSince, serverCount); ok {
|
||||
for i, v := range servers {
|
||||
serverCounts[i] += int64(v)
|
||||
}
|
||||
|
||||
@@ -48,11 +48,11 @@ func (s *PrometheusStorage) GetClusterSizeSeries(days, limit int) ClusterSizeSer
|
||||
series := ClusterSizeSeries{Dates: axis.dates}
|
||||
|
||||
for id, history := range histories {
|
||||
disk, ok := axis.align(history, activeSince, diskBytes)
|
||||
disk, ok := align(axis, history, activeSince, diskBytes)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
servers, _ := axis.align(history, activeSince, serverCount)
|
||||
servers, _ := align(axis, history, activeSince, serverCount)
|
||||
series.Clusters = append(series.Clusters, ClusterSeries{ClusterId: id, Disk: disk, Servers: servers})
|
||||
series.TotalDisk += disk[last]
|
||||
series.TotalServers += servers[last]
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// VersionCounts is how many clusters ran one version per day, aligned to the
|
||||
// shared date axis of the enclosing VersionSeries.
|
||||
type VersionCounts struct {
|
||||
Version string `json:"version"`
|
||||
Clusters []uint64 `json:"clusters"`
|
||||
}
|
||||
|
||||
// OtherVersions is the versions beyond the caller's limit, summed per day so a
|
||||
// stacked chart still adds up to the cluster total.
|
||||
type OtherVersions struct {
|
||||
Count int `json:"count"`
|
||||
Clusters []uint64 `json:"clusters"`
|
||||
}
|
||||
|
||||
// VersionSeries is the version make-up of the fleet over time: one cluster
|
||||
// count per version per day, oldest release first.
|
||||
type VersionSeries struct {
|
||||
Dates []string `json:"dates"`
|
||||
Versions []VersionCounts `json:"versions"`
|
||||
Other *OtherVersions `json:"other,omitempty"`
|
||||
TotalClusters uint64 `json:"total_clusters"` // across all versions on the last day
|
||||
}
|
||||
|
||||
// GetVersionSeries returns the last `days` days of per-version cluster counts
|
||||
// across confirmed clusters. Versions beyond `limit` are folded into Other,
|
||||
// keeping the ones with the most clusters on the last day.
|
||||
func (s *PrometheusStorage) GetVersionSeries(days, limit int) VersionSeries {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
histories := versionedHistories(s.seriesHistories())
|
||||
axis := newDailySeries(days, histories)
|
||||
activeSince := time.Now().UTC().AddDate(0, 0, -activeDays).Unix()
|
||||
last := len(axis.dates) - 1
|
||||
series := VersionSeries{Dates: axis.dates}
|
||||
|
||||
daily := make(map[string][]uint64)
|
||||
for _, history := range histories {
|
||||
versions, ok := align(axis, history, activeSince, sampleVersion)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for i, v := range versions {
|
||||
if v == "" {
|
||||
continue // before the cluster's first day in the window
|
||||
}
|
||||
counts, ok := daily[v]
|
||||
if !ok {
|
||||
counts = make([]uint64, len(axis.dates))
|
||||
daily[v] = counts
|
||||
}
|
||||
counts[i]++
|
||||
}
|
||||
}
|
||||
|
||||
for v, counts := range daily {
|
||||
series.Versions = append(series.Versions, VersionCounts{Version: v, Clusters: counts})
|
||||
series.TotalClusters += counts[last]
|
||||
}
|
||||
// Ordered by release rather than by size: the caller stacks them, and a
|
||||
// stack whose order changes with the counts is unreadable over time.
|
||||
sort.Slice(series.Versions, func(i, j int) bool {
|
||||
return versionLess(series.Versions[i].Version, series.Versions[j].Version)
|
||||
})
|
||||
|
||||
if limit > 0 && len(series.Versions) > limit {
|
||||
// Old releases are a long tail of one-cluster bands; keep the versions
|
||||
// most of the fleet is on now and sum the rest into one band.
|
||||
ranked := append([]VersionCounts(nil), series.Versions...)
|
||||
sort.Slice(ranked, func(i, j int) bool {
|
||||
if ranked[i].Clusters[last] != ranked[j].Clusters[last] {
|
||||
return ranked[i].Clusters[last] > ranked[j].Clusters[last]
|
||||
}
|
||||
return versionLess(ranked[j].Version, ranked[i].Version)
|
||||
})
|
||||
other := OtherVersions{Count: len(ranked) - limit, Clusters: make([]uint64, len(axis.dates))}
|
||||
for _, v := range ranked[limit:] {
|
||||
for i, c := range v.Clusters {
|
||||
other.Clusters[i] += c
|
||||
}
|
||||
}
|
||||
kept := make(map[string]bool, limit)
|
||||
for _, v := range ranked[:limit] {
|
||||
kept[v.Version] = true
|
||||
}
|
||||
versions := series.Versions[:0]
|
||||
for _, v := range series.Versions {
|
||||
if kept[v.Version] {
|
||||
versions = append(versions, v)
|
||||
}
|
||||
}
|
||||
series.Versions = versions
|
||||
series.Other = &other
|
||||
}
|
||||
return series
|
||||
}
|
||||
|
||||
// versionedHistories drops the samples recorded before the reported version was
|
||||
// kept in history, so the version series spans the days it actually knows a
|
||||
// version for instead of climbing out of a run of blank days.
|
||||
func versionedHistories(histories map[string][]HistorySample) map[string][]HistorySample {
|
||||
out := make(map[string][]HistorySample, len(histories))
|
||||
for id, history := range histories {
|
||||
var kept []HistorySample
|
||||
for _, sample := range history {
|
||||
if sample.Version != "" {
|
||||
kept = append(kept, sample)
|
||||
}
|
||||
}
|
||||
if len(kept) > 0 {
|
||||
out[id] = kept
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// versionLess orders release strings like "3.97" and "4.40" by their numeric
|
||||
// components rather than lexically, which would sort "10.02" before "9.99". A
|
||||
// build suffix sits next to the release it was built from. Anything that
|
||||
// doesn't parse, such as the "unknown" a client with no version compiled in
|
||||
// reports, sorts first.
|
||||
func versionLess(a, b string) bool {
|
||||
an, aSuffix, aok := versionParts(a)
|
||||
bn, bSuffix, bok := versionParts(b)
|
||||
if aok != bok {
|
||||
return !aok
|
||||
}
|
||||
if !aok {
|
||||
return a < b
|
||||
}
|
||||
for i := 0; i < len(an) && i < len(bn); i++ {
|
||||
if an[i] != bn[i] {
|
||||
return an[i] < bn[i]
|
||||
}
|
||||
}
|
||||
if len(an) != len(bn) {
|
||||
return len(an) < len(bn)
|
||||
}
|
||||
return aSuffix < bSuffix
|
||||
}
|
||||
|
||||
func versionParts(v string) ([]int, string, bool) {
|
||||
number, suffix, _ := strings.Cut(v, "-")
|
||||
fields := strings.Split(number, ".")
|
||||
parts := make([]int, 0, len(fields))
|
||||
for _, field := range fields {
|
||||
n, err := strconv.Atoi(field)
|
||||
if err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
parts = append(parts, n)
|
||||
}
|
||||
return parts, suffix, len(parts) > 0
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
func TestVersionSeries(t *testing.T) {
|
||||
s := newPrometheusStorage(prometheus.NewRegistry())
|
||||
|
||||
// Upgraded mid-window: its band leaves the old version for the new one.
|
||||
seedSamples(s, "upgraded", HistorySample{Version: "4.39"}, -4, -3)
|
||||
seedSamples(s, "upgraded", HistorySample{Version: "4.40"}, -2, -1, 0)
|
||||
// Reported every day on the same version.
|
||||
seedSamples(s, "steady", HistorySample{Version: "4.40"}, -4, -3, -2, -1, 0)
|
||||
// One day of history only: unconfirmed, so it stays out of the stack.
|
||||
seedSamples(s, "oneshot", HistorySample{Version: "4.40"}, -1)
|
||||
// Confirmed, but its samples predate versions being recorded.
|
||||
seedSamples(s, "versionless", HistorySample{}, -9, -8)
|
||||
|
||||
series := s.GetVersionSeries(10, 0)
|
||||
|
||||
// The versionless days are dropped before the axis is built, so the chart
|
||||
// spans the days a version is known for instead of climbing out of blanks.
|
||||
if len(series.Dates) != 5 {
|
||||
t.Fatalf("dates = %v, want the 5 days with versions", series.Dates)
|
||||
}
|
||||
if len(series.Versions) != 2 ||
|
||||
series.Versions[0].Version != "4.39" || series.Versions[1].Version != "4.40" {
|
||||
t.Fatalf("versions = %+v, want 4.39 then 4.40", series.Versions)
|
||||
}
|
||||
if got := series.Versions[0].Clusters; !equal(got, []uint64{1, 1, 0, 0, 0}) {
|
||||
t.Errorf("4.39 = %v, want the upgraded cluster's first two days", got)
|
||||
}
|
||||
if got := series.Versions[1].Clusters; !equal(got, []uint64{1, 1, 2, 2, 2}) {
|
||||
t.Errorf("4.40 = %v, want steady plus upgraded from day 3", got)
|
||||
}
|
||||
if series.TotalClusters != 2 {
|
||||
t.Errorf("total_clusters = %d, want 2", series.TotalClusters)
|
||||
}
|
||||
if series.Other != nil {
|
||||
t.Errorf("other = %+v, want none without a limit", series.Other)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionSeriesHoldsForwardAndLimits(t *testing.T) {
|
||||
s := newPrometheusStorage(prometheus.NewRegistry())
|
||||
|
||||
// Stopped reporting past the active window: its own days only.
|
||||
seedSamples(s, "gone", HistorySample{Version: "3.97"}, -9, -8)
|
||||
// Reported every day of the window.
|
||||
seedSamples(s, "daily", HistorySample{Version: "4.40"}, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0)
|
||||
// Reported three days ago and not since: still active, so it holds its
|
||||
// version to the right edge instead of dropping out of the stack.
|
||||
seedSamples(s, "lagging", HistorySample{Version: "4.30"}, -3, -2)
|
||||
|
||||
series := s.GetVersionSeries(10, 0)
|
||||
if len(series.Dates) != 10 {
|
||||
t.Fatalf("dates = %v, want 10 days", series.Dates)
|
||||
}
|
||||
byVersion := map[string][]uint64{}
|
||||
for _, v := range series.Versions {
|
||||
byVersion[v.Version] = v.Clusters
|
||||
}
|
||||
if got := byVersion["3.97"]; !equal(got, []uint64{1, 1, 0, 0, 0, 0, 0, 0, 0, 0}) {
|
||||
t.Errorf("3.97 = %v, want nothing after its last report", got)
|
||||
}
|
||||
if got := byVersion["4.30"]; !equal(got, []uint64{0, 0, 0, 0, 0, 0, 1, 1, 1, 1}) {
|
||||
t.Errorf("4.30 = %v, want carried to the right edge", got)
|
||||
}
|
||||
if got := byVersion["4.40"]; !equal(got, []uint64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}) {
|
||||
t.Errorf("4.40 = %v, want 1 every day", got)
|
||||
}
|
||||
if series.TotalClusters != 2 {
|
||||
t.Errorf("total_clusters = %d, want the 2 clusters still reporting", series.TotalClusters)
|
||||
}
|
||||
|
||||
// Past the limit, the versions the fewest clusters are on are summed into
|
||||
// one band; ties on the last day keep the newer version.
|
||||
series = s.GetVersionSeries(10, 1)
|
||||
if len(series.Versions) != 1 || series.Versions[0].Version != "4.40" {
|
||||
t.Fatalf("limited versions = %+v, want just 4.40", series.Versions)
|
||||
}
|
||||
if series.Other == nil || series.Other.Count != 2 {
|
||||
t.Fatalf("other = %+v, want 2 versions", series.Other)
|
||||
}
|
||||
if !equal(series.Other.Clusters, []uint64{1, 1, 0, 0, 0, 0, 1, 1, 1, 1}) {
|
||||
t.Errorf("other = %v, want 3.97+4.30 summed per day", series.Other.Clusters)
|
||||
}
|
||||
if series.TotalClusters != 2 {
|
||||
t.Errorf("limit changed total_clusters: %d, want 2", series.TotalClusters)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionLess(t *testing.T) {
|
||||
// Ordered oldest to newest; every pair must compare in this order.
|
||||
ordered := []string{"unknown", "3.97", "4.02", "4.30", "4.30-enterprise", "9.99", "10.02"}
|
||||
for i := 0; i < len(ordered); i++ {
|
||||
for j := i + 1; j < len(ordered); j++ {
|
||||
if !versionLess(ordered[i], ordered[j]) {
|
||||
t.Errorf("versionLess(%q, %q) = false, want true", ordered[i], ordered[j])
|
||||
}
|
||||
if versionLess(ordered[j], ordered[i]) {
|
||||
t.Errorf("versionLess(%q, %q) = true, want false", ordered[j], ordered[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,410 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/shell"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
// TestMultiDiskECShellLifecycle drives the real shell commands — ec.encode,
|
||||
// ec.balance, ec.rebuild — against a live multi-disk cluster, through the
|
||||
// sequence a production repository goes through, with one invariant checked
|
||||
// after every step: the bytes a client stored come back identical. Shard
|
||||
// counting alone cannot tell a healthy volume from one that was rebuilt out
|
||||
// of the wrong inputs; reading the payload back can.
|
||||
//
|
||||
// The damage step reproduces a support case: shard files removed from disk
|
||||
// while the cluster still lists them, so the subsequent ec.rebuild sees copy
|
||||
// failures ("CopyFile not found ec volume id ...") for locations the master
|
||||
// believes exist, and must recover from the shards that are really there.
|
||||
func TestMultiDiskECShellLifecycle(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping multi-disk EC shell lifecycle test in short mode")
|
||||
}
|
||||
|
||||
testDir := t.TempDir()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 360*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startMultiDiskCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForServer("127.0.0.1:9334", 30*time.Second))
|
||||
for i := 0; i < 3; i++ {
|
||||
require.NoError(t, waitForServer(fmt.Sprintf("127.0.0.1:809%d", i), 30*time.Second))
|
||||
}
|
||||
t.Log("waiting for multi-disk volume servers to register...")
|
||||
time.Sleep(10 * time.Second)
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&shell.ShellOptions{
|
||||
Masters: stringPtr("127.0.0.1:9334"),
|
||||
GrpcDialOption: grpc.WithInsecure(),
|
||||
FilerGroup: stringPtr("default"),
|
||||
})
|
||||
connectToMasterAndSync(ctx, t, commandEnv)
|
||||
|
||||
// A payload with no structure, so a rebuild that assembled the wrong bytes
|
||||
// cannot accidentally reproduce it.
|
||||
payload := make([]byte, 8192)
|
||||
_, err = rand.Read(payload)
|
||||
require.NoError(t, err)
|
||||
|
||||
var volumeId needle.VolumeId
|
||||
var fid string
|
||||
for retry := 0; retry < 5; retry++ {
|
||||
volumeId, fid, err = uploadPayload(payload)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
require.NoError(t, err, "failed to upload payload")
|
||||
for i := 0; i < 40; i++ {
|
||||
if _, _, e := uploadPayload([]byte(strings.Repeat("filler ", 128))); e != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
t.Logf("payload of %d bytes in volume %d as %s", len(payload), volumeId, fid)
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
requirePayload := func(step string) {
|
||||
t.Helper()
|
||||
require.Eventually(t, func() bool {
|
||||
got, err := readFid(fid, uint32(volumeId))
|
||||
return err == nil && bytes.Equal(got, payload)
|
||||
}, 30*time.Second, time.Second, "payload not readable byte-identical after %s", step)
|
||||
t.Logf("payload verified after %s", step)
|
||||
}
|
||||
requirePayload("upload")
|
||||
|
||||
// Spread volumes across each node's disks before encoding; the master only
|
||||
// enumerates disks that already hold data, and shards only spread across
|
||||
// enumerated disks (see TestMultiDiskECBalanceNoShardLoss for the details).
|
||||
require.Eventually(t, func() bool {
|
||||
spread := nodeVolumeDiskCounts(t, commandEnv)
|
||||
if len(spread) == 3 && allAtLeast(spread, 2) {
|
||||
return true
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
server := fmt.Sprintf("127.0.0.1:809%d", i)
|
||||
if spread[server] < 2 {
|
||||
captureCommandOutput(t, shell.Commands[findCommandIndex("volume.grow")],
|
||||
[]string{"-collection", "test", "-dataNode", server, "-count", "4"}, commandEnv)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, 60*time.Second, 2*time.Second, "volumes never spread across >=2 disks on all 3 nodes")
|
||||
|
||||
locked, unlock := tryLockWithTimeout(t, commandEnv, 15*time.Second)
|
||||
require.True(t, locked, "could not acquire shell lock")
|
||||
defer unlock()
|
||||
|
||||
// ── ec.encode ──
|
||||
out, err := captureCommandOutput(t, shell.Commands[findCommandIndex("ec.encode")],
|
||||
[]string{"-volumeId", fmt.Sprintf("%d", volumeId), "-collection", "test", "-force"}, commandEnv)
|
||||
t.Logf("ec.encode output:\n%s", out)
|
||||
require.NoError(t, err, "ec.encode failed")
|
||||
require.Eventually(t, func() bool {
|
||||
return len(collectDistinctShardIDs(testDir, uint32(volumeId))) == erasureShardCount
|
||||
}, 30*time.Second, time.Second, "expected all %d shards after encode", erasureShardCount)
|
||||
requirePayload("ec.encode")
|
||||
|
||||
// ── ec.balance ──
|
||||
out, err = captureCommandOutput(t, shell.Commands[findCommandIndex("ec.balance")],
|
||||
[]string{"-collection", "test", "-force"}, commandEnv)
|
||||
t.Logf("ec.balance output:\n%s", out)
|
||||
require.NoError(t, err, "ec.balance failed")
|
||||
time.Sleep(3 * time.Second)
|
||||
require.Len(t, collectDistinctShardIDs(testDir, uint32(volumeId)), erasureShardCount,
|
||||
"ec.balance lost shards")
|
||||
requirePayload("ec.balance")
|
||||
|
||||
// ── damage: two shard files vanish from disk ──
|
||||
// Removed straight off disk, then the servers are restarted so the master
|
||||
// relearns the shard set from disk rather than from stale heartbeat state.
|
||||
// This is the recoverable form of the support case: the volume drops to 12
|
||||
// of 14 shards, which is still above the 10 needed to read and rebuild.
|
||||
removed := removeTwoShardFiles(t, testDir, uint32(volumeId))
|
||||
t.Logf("removed shard files for shards %v", removed)
|
||||
require.Len(t, collectDistinctShardIDs(testDir, uint32(volumeId)), erasureShardCount-2)
|
||||
|
||||
require.NoError(t, cluster.RestartVolumeServers(ctx))
|
||||
for i := 0; i < 3; i++ {
|
||||
require.NoError(t, waitForServer(fmt.Sprintf("127.0.0.1:809%d", i), 30*time.Second))
|
||||
}
|
||||
requirePayload("shard loss + restart") // 12 of 14 remain; reads must survive
|
||||
|
||||
// The master must now see exactly the 12 shards on disk before any repair
|
||||
// runs. ec.rebuild is driven by the master's view, so a repair planned
|
||||
// while that view still lists the two dead shards would target the wrong
|
||||
// set. Restart-then-relearn is what makes disk truth and the master agree.
|
||||
require.Eventually(t, func() bool {
|
||||
return len(masterEcShardIds(commandEnv, uint32(volumeId))) == erasureShardCount-2
|
||||
}, 60*time.Second, 2*time.Second,
|
||||
"master never relearned the reduced shard set (got %v)",
|
||||
sortedKeysOf(masterEcShardIds(commandEnv, uint32(volumeId))))
|
||||
|
||||
// The shell lock is dropped by the restart's master disconnect; retake it.
|
||||
relocked, reunlock := tryLockWithTimeout(t, commandEnv, 15*time.Second)
|
||||
require.True(t, relocked, "could not reacquire shell lock after restart")
|
||||
defer reunlock()
|
||||
|
||||
// ── ec.rebuild, the command from the support case ──
|
||||
out, err = captureCommandOutput(t, shell.Commands[findCommandIndex("ec.rebuild")],
|
||||
[]string{"-collection", "test", "-apply"}, commandEnv)
|
||||
t.Logf("ec.rebuild output:\n%s", out)
|
||||
require.NoError(t, err, "ec.rebuild failed")
|
||||
require.Eventually(t, func() bool {
|
||||
return len(collectDistinctShardIDs(testDir, uint32(volumeId))) == erasureShardCount
|
||||
}, 60*time.Second, time.Second, "ec.rebuild did not restore all %d shards on disk", erasureShardCount)
|
||||
requirePayload("ec.rebuild")
|
||||
|
||||
// The rebuilt shards are real: master's view and disk truth agree on all 14.
|
||||
require.Eventually(t, func() bool {
|
||||
registered := masterEcShardIds(commandEnv, uint32(volumeId))
|
||||
onDisk := collectDistinctShardIDs(testDir, uint32(volumeId))
|
||||
if len(registered) != len(onDisk) || len(onDisk) != erasureShardCount {
|
||||
return false
|
||||
}
|
||||
for id := range onDisk {
|
||||
if !registered[id] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}, 60*time.Second, 2*time.Second,
|
||||
"master's EC shard view diverged from disk truth after rebuild: master=%v disk=%v",
|
||||
sortedKeysOf(masterEcShardIds(commandEnv, uint32(volumeId))), sortedKeysOf(collectDistinctShardIDs(testDir, uint32(volumeId))))
|
||||
}
|
||||
|
||||
// RestartVolumeServers kills every volume server process and starts fresh ones
|
||||
// over the same directories, so registration is rebuilt purely from disk.
|
||||
func (c *MultiDiskCluster) RestartVolumeServers(ctx context.Context) error {
|
||||
for _, cmd := range c.volumeServers {
|
||||
if cmd != nil && cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
cmd.Wait()
|
||||
}
|
||||
}
|
||||
c.volumeServers = nil
|
||||
time.Sleep(2 * time.Second)
|
||||
return c.startVolumeServers(ctx)
|
||||
}
|
||||
|
||||
// startVolumeServers launches the standard 3-server x 4-disk layout over the
|
||||
// cluster's existing directories, mirroring startMultiDiskCluster's loop so a
|
||||
// restart brings servers back exactly as they first started.
|
||||
func (c *MultiDiskCluster) startVolumeServers(ctx context.Context) error {
|
||||
weedBinary := findWeedBinary()
|
||||
if weedBinary == "" {
|
||||
return fmt.Errorf("weed binary not found")
|
||||
}
|
||||
const numServers = 3
|
||||
const disksPerServer = 4
|
||||
for i := 0; i < numServers; i++ {
|
||||
var diskDirs []string
|
||||
var maxVolumes []string
|
||||
for d := 0; d < disksPerServer; d++ {
|
||||
diskDirs = append(diskDirs, filepath.Join(c.testDir, fmt.Sprintf("server%d_disk%d", i, d)))
|
||||
maxVolumes = append(maxVolumes, "5")
|
||||
}
|
||||
volumeCmd := exec.CommandContext(ctx, weedBinary, "volume",
|
||||
"-port", fmt.Sprintf("809%d", i),
|
||||
"-dir", strings.Join(diskDirs, ","),
|
||||
"-max", strings.Join(maxVolumes, ","),
|
||||
"-master", "127.0.0.1:9334",
|
||||
"-ip", "127.0.0.1",
|
||||
"-dataCenter", "dc1",
|
||||
"-rack", fmt.Sprintf("rack%d", i),
|
||||
)
|
||||
logFile, err := os.OpenFile(filepath.Join(c.testDir, fmt.Sprintf("server%d_logs", i), "volume-restart.log"),
|
||||
os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open restart log for server %d: %w", i, err)
|
||||
}
|
||||
c.logFiles = append(c.logFiles, logFile)
|
||||
volumeCmd.Stdout = logFile
|
||||
volumeCmd.Stderr = logFile
|
||||
if err := volumeCmd.Start(); err != nil {
|
||||
return fmt.Errorf("restart volume server %d: %w", i, err)
|
||||
}
|
||||
c.volumeServers = append(c.volumeServers, volumeCmd)
|
||||
}
|
||||
time.Sleep(8 * time.Second)
|
||||
return nil
|
||||
}
|
||||
|
||||
// uploadPayload stores data in collection "test" and returns the volume id and
|
||||
// fid so the same needle can be read back after every subsequent operation.
|
||||
func uploadPayload(data []byte) (needle.VolumeId, string, error) {
|
||||
assignResult, err := operation.Assign(context.Background(), func(ctx context.Context) pb.ServerAddress {
|
||||
return pb.ServerAddress("127.0.0.1:9334")
|
||||
}, grpc.WithInsecure(), &operation.VolumeAssignRequest{
|
||||
Count: 1,
|
||||
Collection: "test",
|
||||
Replication: "000",
|
||||
})
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
uploadResult, err, _ := uploader.Upload(context.Background(), bytes.NewReader(data), &operation.UploadOption{
|
||||
UploadUrl: "http://" + assignResult.Url + "/" + assignResult.Fid,
|
||||
Filename: "payload.bin",
|
||||
MimeType: "application/octet-stream",
|
||||
})
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
return 0, "", fmt.Errorf("upload error: %s", uploadResult.Error)
|
||||
}
|
||||
fidObj, err := needle.ParseFileIdFromString(assignResult.Fid)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
return fidObj.VolumeId, assignResult.Fid, nil
|
||||
}
|
||||
|
||||
// readFid locates the volume via the master and fetches the needle bytes from
|
||||
// a currently-registered location — the same route a client read takes, for a
|
||||
// plain volume before encoding and for the EC read path after.
|
||||
func readFid(fid string, volumeId uint32) ([]byte, error) {
|
||||
resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:9334/dir/lookup?volumeId=%d", volumeId))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var lookup struct {
|
||||
Locations []struct {
|
||||
Url string `json:"url"`
|
||||
} `json:"locations"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&lookup); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(lookup.Locations) == 0 {
|
||||
return nil, fmt.Errorf("no locations for volume %d", volumeId)
|
||||
}
|
||||
var lastErr error
|
||||
for _, loc := range lookup.Locations {
|
||||
get, err := http.Get(fmt.Sprintf("http://%s/%s", loc.Url, fid))
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
body, err := io.ReadAll(get.Body)
|
||||
get.Body.Close()
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if get.StatusCode != http.StatusOK {
|
||||
lastErr = fmt.Errorf("GET %s from %s: %d", fid, loc.Url, get.StatusCode)
|
||||
continue
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// removeTwoShardFiles deletes the files of two distinct shards straight off
|
||||
// the disks, without telling any server — the divergence between disk truth
|
||||
// and the master's view at the heart of the support case.
|
||||
func removeTwoShardFiles(t *testing.T, testDir string, volumeId uint32) []int {
|
||||
t.Helper()
|
||||
var removed []int
|
||||
for server := 0; server < 3 && len(removed) < 2; server++ {
|
||||
for disk := 0; disk < 4 && len(removed) < 2; disk++ {
|
||||
diskDir := filepath.Join(testDir, fmt.Sprintf("server%d_disk%d", server, disk))
|
||||
files, err := listECShardFiles(diskDir, volumeId)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, f := range files {
|
||||
i := strings.LastIndex(f, ".ec")
|
||||
if i < 0 {
|
||||
continue
|
||||
}
|
||||
var id int
|
||||
if _, err := fmt.Sscanf(f[i+3:], "%d", &id); err != nil {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(filepath.Join(diskDir, f)); err != nil {
|
||||
t.Fatalf("remove shard file %s: %v", f, err)
|
||||
}
|
||||
removed = append(removed, id)
|
||||
break // at most one shard per disk, keep the loss spread out
|
||||
}
|
||||
}
|
||||
}
|
||||
require.Len(t, removed, 2, "could not find two shard files to remove")
|
||||
return removed
|
||||
}
|
||||
|
||||
// masterEcShardIds reports which shard ids the master currently believes exist
|
||||
// for the volume, across all nodes — the view every repair decision runs on.
|
||||
func masterEcShardIds(commandEnv *shell.CommandEnv, volumeId uint32) map[int]bool {
|
||||
ids := map[int]bool{}
|
||||
var resp *master_pb.VolumeListResponse
|
||||
err := commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
|
||||
var e error
|
||||
resp, e = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
return e
|
||||
})
|
||||
if err != nil || resp.GetTopologyInfo() == nil {
|
||||
return ids
|
||||
}
|
||||
for _, dc := range resp.GetTopologyInfo().GetDataCenterInfos() {
|
||||
for _, r := range dc.GetRackInfos() {
|
||||
for _, dn := range r.GetDataNodeInfos() {
|
||||
for _, di := range dn.GetDiskInfos() {
|
||||
for _, eci := range di.GetEcShardInfos() {
|
||||
if eci.GetId() != volumeId {
|
||||
continue
|
||||
}
|
||||
for _, sid := range erasure_coding_ShardIds(eci.GetEcIndexBits()) {
|
||||
ids[sid] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// erasure_coding_ShardIds expands an EC index bitmap into shard ids without
|
||||
// importing the storage package into this test's namespace twice.
|
||||
func erasure_coding_ShardIds(bits uint32) []int {
|
||||
var out []int
|
||||
for i := 0; i < 32; i++ {
|
||||
if bits&(1<<uint(i)) != 0 {
|
||||
out = append(out, i)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/shell"
|
||||
)
|
||||
|
||||
// TestECInterruptionMatrix is the systematic counterpart of the randomized
|
||||
// chaos harness: instead of killing operations at random times, it enumerates
|
||||
// every phase of every interruptible EC operation and kills a real weed shell
|
||||
// exactly when that phase announces itself on the command's output. Each
|
||||
// (operation, phase) pair is one deterministic scenario: prepare the
|
||||
// precondition, kill at the phase marker, run the prescribed recovery, and
|
||||
// verify that every stored byte still reads back identical.
|
||||
//
|
||||
// The phase markers are the progress lines the pipelines print; each marker
|
||||
// below names the code that prints it. A marker is the START of its phase, so
|
||||
// killing on it lands the interruption inside that phase — deterministically
|
||||
// per phase, byte-exact timing within the phase left to the scheduler. Every
|
||||
// scenario REQUIRES its marker to appear: a marker that never prints means a
|
||||
// pipeline refactor renamed or dropped the progress line, and silently
|
||||
// degenerating into a no-interruption run would let CI pass without
|
||||
// exercising the boundary the scenario names. Update the marker with the
|
||||
// pipeline.
|
||||
//
|
||||
// Complementing this, weed/ec's TestECLifecycleModelExhaustive explores every
|
||||
// schedule of the same pipelines — crashes between every step, rollback
|
||||
// paths, restarts — exhaustively on a model whose steps mirror the code.
|
||||
func TestECInterruptionMatrix(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping EC interruption matrix in short mode")
|
||||
}
|
||||
|
||||
testDir := t.TempDir()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startChaosCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForServer(chaosMasterAddr, 30*time.Second))
|
||||
for i := 0; i < chaosServerCount; i++ {
|
||||
require.NoError(t, waitForServer("127.0.0.1:"+chaosVolumePort(i), 30*time.Second))
|
||||
}
|
||||
time.Sleep(8 * time.Second)
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&shell.ShellOptions{
|
||||
Masters: stringPtr(chaosMasterAddr),
|
||||
GrpcDialOption: grpc.WithInsecure(),
|
||||
FilerGroup: stringPtr("default"),
|
||||
})
|
||||
connectToMasterAndSync(ctx, t, commandEnv)
|
||||
|
||||
r := newChaosRun(t, ctx, cluster, commandEnv, testDir, 1)
|
||||
r.relock()
|
||||
defer r.unlockIfHeld()
|
||||
r.seedAndSpread()
|
||||
r.verify("seeding")
|
||||
|
||||
// One scenario per (operation, phase marker). The preparation puts a
|
||||
// dedicated volume into the operation's precondition state, so scenarios
|
||||
// stay independent even though they share the cluster.
|
||||
type scenario struct {
|
||||
op string
|
||||
marker string // printed by ↓
|
||||
printed string // the code that prints it, for the reader
|
||||
}
|
||||
encodeScenarios := []scenario{
|
||||
{"ec.encode", "markVolumeReadonly ", "weed/ec markVolumeReplicaWritable"},
|
||||
{"ec.encode", "generateEcShards ", "weed/ec generateEcShards"},
|
||||
{"ec.encode", "mount ", "weed/ec MountEcShards"},
|
||||
{"ec.encode", "Deleting original volumes", "weed/ec ProcessEcEncodeBatch, the commit boundary"},
|
||||
}
|
||||
decodeScenarios := []scenario{
|
||||
{"ec.decode", " shard locations:", "weed/ec DoEcDecode, before collect"},
|
||||
{"ec.decode", "generateNormalVolume", "weed/ec generateNormalVolume"},
|
||||
{"ec.decode", "unmount ec volume", "weed/ec unmountAndDeleteEcShards, teardown begin"},
|
||||
{"ec.decode", "delete ec volume", "weed/ec unmountAndDeleteEcShards, shard deletion"},
|
||||
}
|
||||
|
||||
for _, sc := range encodeScenarios {
|
||||
sc := sc
|
||||
t.Run(fmt.Sprintf("encode@%s", trimMarker(sc.marker)), func(t *testing.T) {
|
||||
vid := r.ensureRegularVolume()
|
||||
r.unlockIfHeld()
|
||||
out, hit := runShellKillAtMarker(t, r.ctx,
|
||||
fmt.Sprintf("ec.encode -volumeId %d -collection %s -force", vid, chaosCollection), sc.marker)
|
||||
r.t.Logf("killed %s at %q (marker hit: %v); output:\n%s", sc.op, sc.marker, hit, out)
|
||||
r.relock()
|
||||
require.True(t, hit, "marker %q never appeared (printed by %s); update the marker with the pipeline", sc.marker, sc.printed)
|
||||
r.recoverInterruptedEncode(vid)
|
||||
r.verify(fmt.Sprintf("encode killed at %q", sc.marker))
|
||||
})
|
||||
}
|
||||
for _, sc := range decodeScenarios {
|
||||
sc := sc
|
||||
t.Run(fmt.Sprintf("decode@%s", trimMarker(sc.marker)), func(t *testing.T) {
|
||||
vid := r.ensureEncodedVolume()
|
||||
r.unlockIfHeld()
|
||||
out, hit := runShellKillAtMarker(t, r.ctx,
|
||||
fmt.Sprintf("ec.decode -volumeId %d -collection %s -checkMinFreeSpace=false", vid, chaosCollection), sc.marker)
|
||||
r.t.Logf("killed %s at %q (marker hit: %v); output:\n%s", sc.op, sc.marker, hit, out)
|
||||
r.relock()
|
||||
require.True(t, hit, "marker %q never appeared (printed by %s); update the marker with the pipeline", sc.marker, sc.printed)
|
||||
r.recoverInterruptedDecode(vid)
|
||||
r.verify(fmt.Sprintf("decode killed at %q", sc.marker))
|
||||
})
|
||||
}
|
||||
|
||||
// Balance: encode without rebalancing first, so the standalone balance is
|
||||
// guaranteed to plan moves and the marker is guaranteed to print.
|
||||
t.Run("balance@moves", func(t *testing.T) {
|
||||
vid := r.ensureRegularVolume()
|
||||
out, err := r.shellCommand("ec.encode",
|
||||
"-volumeId", fmt.Sprintf("%d", vid), "-collection", chaosCollection, "-force", "-rebalance=false")
|
||||
r.t.Logf("clumped encode v%d output:\n%s", vid, out)
|
||||
require.NoError(t, err, "encode without rebalance")
|
||||
r.volumes[vid].encoded = true
|
||||
|
||||
r.unlockIfHeld()
|
||||
killOut, hit := runShellKillAtMarker(t, r.ctx,
|
||||
fmt.Sprintf("ec.balance -collection %s -apply", chaosCollection), "moves ec shard")
|
||||
r.t.Logf("killed ec.balance at move (marker hit: %v); output:\n%s", hit, killOut)
|
||||
r.relock()
|
||||
require.True(t, hit, "the balance never printed a move; the -rebalance=false setup should have guaranteed one")
|
||||
r.recoverInterruptedBalance()
|
||||
r.verify("balance killed at move")
|
||||
})
|
||||
|
||||
r.verify("final")
|
||||
t.Logf("interruption matrix done: %d payloads live, %d deleted, %d volumes tracked",
|
||||
len(r.payloads), len(r.deleted), len(r.volumes))
|
||||
}
|
||||
|
||||
func trimMarker(m string) string {
|
||||
out := make([]rune, 0, len(m))
|
||||
for _, c := range m {
|
||||
if c == ' ' || c == ':' {
|
||||
continue
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// runShellKillAtMarker feeds "lock" plus the command to a weed shell
|
||||
// subprocess, scans its combined output live, and kills the process the
|
||||
// moment a line containing marker appears. Returns the captured output and
|
||||
// whether the marker was seen before the shell exited on its own.
|
||||
func runShellKillAtMarker(t *testing.T, ctx context.Context, command, marker string) (string, bool) {
|
||||
t.Helper()
|
||||
weedBinary := findWeedBinary()
|
||||
require.NotEmpty(t, weedBinary, "weed binary not found")
|
||||
cmd := exec.CommandContext(ctx, weedBinary, "shell", "-master="+chaosMasterAddr)
|
||||
|
||||
pr, pw, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
cmd.Stdout, cmd.Stderr = pw, pw
|
||||
stdin, err := cmd.StdinPipe()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cmd.Start())
|
||||
pw.Close() // the child keeps its dup; ours would hold the reader open
|
||||
|
||||
var buf bytes.Buffer
|
||||
var mu sync.Mutex
|
||||
markerSeen := make(chan struct{})
|
||||
scanDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(scanDone)
|
||||
signaled := false
|
||||
scanner := bufio.NewScanner(pr)
|
||||
scanner.Buffer(make([]byte, 0, 256*1024), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
mu.Lock()
|
||||
buf.WriteString(line)
|
||||
buf.WriteByte('\n')
|
||||
mu.Unlock()
|
||||
if !signaled && bytesContains(line, marker) {
|
||||
signaled = true
|
||||
close(markerSeen)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
fmt.Fprintf(stdin, "lock\n%s\n", command)
|
||||
// Stdin stays open: the shell must die by kill, never by graceful EOF —
|
||||
// a graceful exit would release the cluster lock cleanly and dodge the
|
||||
// dead-holder cleanup path this test also exercises.
|
||||
hit := false
|
||||
select {
|
||||
case <-markerSeen:
|
||||
hit = true
|
||||
case <-scanDone: // shell exited before printing the marker
|
||||
case <-time.After(90 * time.Second):
|
||||
}
|
||||
if !hit {
|
||||
// A shell that printed the marker and exited immediately can make both
|
||||
// channels ready at once, and select picks between ready cases at
|
||||
// random; a printed marker must never be reported as missed.
|
||||
select {
|
||||
case <-markerSeen:
|
||||
hit = true
|
||||
default:
|
||||
}
|
||||
}
|
||||
cmd.Process.Kill()
|
||||
cmd.Wait()
|
||||
pr.Close()
|
||||
<-scanDone
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return buf.String(), hit
|
||||
}
|
||||
|
||||
func bytesContains(line, marker string) bool {
|
||||
return len(marker) > 0 && strings.Contains(line, marker)
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
//go:build !windows
|
||||
|
||||
package metadata_subscribe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
// A filer drops the metadata subscription to a peer that leaves, and only an
|
||||
// add from the master brings it back. Those updates are broadcast to the
|
||||
// clients connected at that moment, so a filer whose master stream broke while
|
||||
// the peer came back used to stay unsubscribed for good, and metadata written
|
||||
// on the peer never reached it again.
|
||||
func TestFilerResubscribesToPeerAfterMasterReconnect(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
weedBinary := findWeedBinary()
|
||||
require.NotEmpty(t, weedBinary, "weed binary not found")
|
||||
|
||||
testDir, err := os.MkdirTemp("", "seaweedfs_peer_resubscribe_")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
if t.Failed() {
|
||||
t.Logf("logs kept at %s", testDir)
|
||||
return
|
||||
}
|
||||
os.RemoveAll(testDir)
|
||||
})
|
||||
|
||||
ports, err := testutil.AllocateMiniPorts(3)
|
||||
require.NoError(t, err)
|
||||
masterPort, filer1Port, filer2Port := ports[0], ports[1], ports[2]
|
||||
|
||||
master := pb.ServerAddress(fmt.Sprintf("127.0.0.1:%d", masterPort))
|
||||
filer1Address := fmt.Sprintf("127.0.0.1:%d", filer1Port)
|
||||
filer2Address := fmt.Sprintf("127.0.0.1:%d", filer2Port)
|
||||
filer1Log := filepath.Join(testDir, "filer1.log")
|
||||
|
||||
masterArgs := []string{"master",
|
||||
"-ip=127.0.0.1",
|
||||
"-port=" + strconv.Itoa(masterPort),
|
||||
"-mdir=" + mkdir(t, testDir, "master"),
|
||||
"-peers=none"}
|
||||
masterProcess := startProcess(t, weedBinary, filepath.Join(testDir, "master.log"), masterArgs...)
|
||||
require.NoError(t, waitForLeader(masterPort, 60*time.Second))
|
||||
|
||||
// one at a time: a filer bootstraps from the peers the master already knows,
|
||||
// and gives up if one of them is registered but not yet listening
|
||||
filer1 := startFiler(t, weedBinary, testDir, "filer1", filer1Port, masterPort)
|
||||
require.NoError(t, waitForHTTPServer(fmt.Sprintf("http://127.0.0.1:%d/", filer1Port), 30*time.Second))
|
||||
filer2 := startFiler(t, weedBinary, testDir, "filer2", filer2Port, masterPort)
|
||||
require.NoError(t, waitForHTTPServer(fmt.Sprintf("http://127.0.0.1:%d/", filer2Port), 30*time.Second))
|
||||
|
||||
// the peer subscription works to begin with
|
||||
createPeerEntry(t, filer2Address, "baseline")
|
||||
require.NoError(t, waitForPeerEntry(filer1Address, "baseline", 60*time.Second),
|
||||
"filer1 never replicated the baseline entry from filer2")
|
||||
|
||||
// filer2 leaves, and filer1 drops the subscription
|
||||
stopProcess(filer2)
|
||||
require.NoError(t, waitForLog(filer1Log, "stop subscribing peer "+filer2Address, 60*time.Second),
|
||||
"filer1 never dropped the subscription to filer2")
|
||||
|
||||
// filer1 stops reading its master stream, and restarting the master breaks
|
||||
// it, so filer1 hears nothing until it reconnects
|
||||
require.NoError(t, filer1.Process.Signal(syscall.SIGSTOP))
|
||||
stopProcess(masterProcess)
|
||||
startProcess(t, weedBinary, filepath.Join(testDir, "master.log"), masterArgs...)
|
||||
require.NoError(t, waitForLeader(masterPort, 60*time.Second))
|
||||
|
||||
// filer2 comes back and registers while filer1 cannot hear about it
|
||||
filer2 = startFiler(t, weedBinary, testDir, "filer2", filer2Port, masterPort)
|
||||
require.NoError(t, waitForHTTPServer(fmt.Sprintf("http://127.0.0.1:%d/", filer2Port), 30*time.Second))
|
||||
require.NoError(t, waitForClusterNode(master, filer2Address, 60*time.Second),
|
||||
"the master never registered filer2 again")
|
||||
|
||||
require.NoError(t, filer1.Process.Signal(syscall.SIGCONT))
|
||||
require.NoError(t, waitForClusterNode(master, filer1Address, 60*time.Second),
|
||||
"filer1 never reconnected to the master")
|
||||
|
||||
createPeerEntry(t, filer2Address, "after-reconnect")
|
||||
require.NoError(t, waitForPeerEntry(filer1Address, "after-reconnect", 90*time.Second),
|
||||
"filer1 reconnected to the master but never resubscribed to filer2")
|
||||
}
|
||||
|
||||
const peerEntryDir = "/peer-resubscribe"
|
||||
|
||||
func createPeerEntry(t *testing.T, filerAddress, name string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
err := pb.WithFilerClient(false, 0, pb.ServerAddress(filerAddress), grpc.WithTransportCredentials(insecure.NewCredentials()), func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
||||
Directory: peerEntryDir,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
FileMode: 0644,
|
||||
},
|
||||
},
|
||||
})
|
||||
return err
|
||||
})
|
||||
require.NoError(t, err, "create %s/%s on %s", peerEntryDir, name, filerAddress)
|
||||
}
|
||||
|
||||
func waitForPeerEntry(filerAddress, name string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
var lastErr error
|
||||
for time.Now().Before(deadline) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
lastErr = pb.WithFilerClient(false, 0, pb.ServerAddress(filerAddress), grpc.WithTransportCredentials(insecure.NewCredentials()), func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: peerEntryDir,
|
||||
Name: name,
|
||||
})
|
||||
return err
|
||||
})
|
||||
cancel()
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return fmt.Errorf("%s/%s not on %s within %v: %w", peerEntryDir, name, filerAddress, timeout, lastErr)
|
||||
}
|
||||
|
||||
func waitForClusterNode(master pb.ServerAddress, address string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
found := false
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
err := pb.WithMasterClient(ctx, false, master, grpc.WithTransportCredentials(insecure.NewCredentials()), false, func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(ctx, &master_pb.ListClusterNodesRequest{ClientType: cluster.FilerType})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, node := range resp.ClusterNodes {
|
||||
// the master reports the grpc port too, as "host:port.grpcPort"
|
||||
if pb.ServerAddress(node.Address).Equals(pb.ServerAddress(address)) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
cancel()
|
||||
if err == nil && found {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return fmt.Errorf("%s not registered within %v", address, timeout)
|
||||
}
|
||||
|
||||
func waitForLeader(masterPort int, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
url := fmt.Sprintf("http://127.0.0.1:%d/cluster/status", masterPort)
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
for time.Now().Before(deadline) {
|
||||
if resp, err := client.Get(url); err == nil {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if strings.Contains(string(body), `"IsLeader":true`) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return fmt.Errorf("master on %d has no leader within %v", masterPort, timeout)
|
||||
}
|
||||
|
||||
func waitForLog(logFile, message string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
content, err := os.ReadFile(logFile)
|
||||
if err == nil && strings.Contains(string(content), message) {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return fmt.Errorf("%q not in %s within %v", message, logFile, timeout)
|
||||
}
|
||||
|
||||
func mkdir(t *testing.T, dir, name string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(dir, name)
|
||||
require.NoError(t, os.MkdirAll(path, 0755))
|
||||
return path
|
||||
}
|
||||
|
||||
func startFiler(t *testing.T, weedBinary, testDir, name string, port, masterPort int) *exec.Cmd {
|
||||
t.Helper()
|
||||
return startProcess(t, weedBinary, filepath.Join(testDir, name+".log"), "filer",
|
||||
"-ip=127.0.0.1",
|
||||
"-port="+strconv.Itoa(port),
|
||||
"-master=127.0.0.1:"+strconv.Itoa(masterPort),
|
||||
"-defaultStoreDir="+mkdir(t, testDir, name))
|
||||
}
|
||||
|
||||
func startProcess(t *testing.T, weedBinary, logFile string, args ...string) *exec.Cmd {
|
||||
t.Helper()
|
||||
log, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
cmd := exec.Command(weedBinary, args...)
|
||||
cmd.Stdout = log
|
||||
cmd.Stderr = log
|
||||
require.NoError(t, cmd.Start())
|
||||
t.Cleanup(func() {
|
||||
cmd.Process.Signal(syscall.SIGCONT)
|
||||
stopProcess(cmd)
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
// stopProcess kills the process outright: a filer takes seconds to shut down
|
||||
// gracefully, long enough to register with the master again on the way out.
|
||||
func stopProcess(cmd *exec.Cmd) {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return
|
||||
}
|
||||
cmd.Process.Kill()
|
||||
cmd.Wait()
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
// Command mount_bench times common filesystem operations against a mounted
|
||||
// directory and writes the results as JSON, so runs against different mounts
|
||||
// (WinFsp, rclone, libfuse) can be compared with -compare.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
seqFileSize = 256 << 20
|
||||
seqBufSize = 1 << 20
|
||||
randReads = 500
|
||||
randReadSize = 4 << 10
|
||||
smallCount = 400
|
||||
smallSize = 64 << 10
|
||||
overwriteN = 100
|
||||
statRounds = 3
|
||||
listRounds = 10
|
||||
bigListCount = 5000
|
||||
bigListRounds = 3
|
||||
)
|
||||
|
||||
type phaseResult struct {
|
||||
Name string `json:"name"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
Bytes int64 `json:"bytes,omitempty"`
|
||||
Ops int64 `json:"ops,omitempty"`
|
||||
}
|
||||
|
||||
type runResult struct {
|
||||
Label string `json:"label"`
|
||||
Phases []phaseResult `json:"phases"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
dir := flag.String("dir", "", "directory on the mount to benchmark in; created if missing, must be a direct child of the mount root")
|
||||
label := flag.String("label", "bench", "name for this result set")
|
||||
out := flag.String("out", "", "write results as JSON to this file")
|
||||
filer := flag.String("filer", "", "filer http address for out-of-band setup of the big-listing phase")
|
||||
seed := flag.String("seed", "", "seed the big-listing directory at this filer-relative path and exit; for mounts that cache listings and would miss files created behind them")
|
||||
compare := flag.String("compare", "", "comma-separated result JSON files; print a comparison table and exit")
|
||||
flag.Parse()
|
||||
|
||||
if *compare != "" {
|
||||
if err := printComparison(strings.Split(*compare, ",")); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if *seed != "" {
|
||||
if *filer == "" {
|
||||
log.Fatal("-seed requires -filer")
|
||||
}
|
||||
if err := seedFilerDir(*filer, *seed, bigListCount); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if *dir == "" {
|
||||
log.Fatal("either -dir or -compare is required")
|
||||
}
|
||||
if err := os.MkdirAll(*dir, 0755); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
r := &runner{dir: *dir, filer: *filer, result: runResult{Label: *label}}
|
||||
r.run()
|
||||
|
||||
data, err := json.MarshalIndent(r.result, "", " ")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if *out != "" {
|
||||
if err := os.WriteFile(*out, data, 0644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
fmt.Println(string(data))
|
||||
}
|
||||
|
||||
type runner struct {
|
||||
dir string
|
||||
filer string
|
||||
result runResult
|
||||
}
|
||||
|
||||
func (r *runner) phase(name string, bytes, ops int64, fn func() error) {
|
||||
start := time.Now()
|
||||
if err := fn(); err != nil {
|
||||
log.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
r.result.Phases = append(r.result.Phases, phaseResult{
|
||||
Name: name, Seconds: elapsed.Seconds(), Bytes: bytes, Ops: ops,
|
||||
})
|
||||
fmt.Printf("%-14s %10.3fs%s\n", name, elapsed.Seconds(), rateSuffix(bytes, ops, elapsed.Seconds()))
|
||||
}
|
||||
|
||||
func rateSuffix(bytes, ops int64, seconds float64) string {
|
||||
if seconds <= 0 {
|
||||
return ""
|
||||
}
|
||||
var parts []string
|
||||
if bytes > 0 {
|
||||
parts = append(parts, fmt.Sprintf("%8.1f MB/s", float64(bytes)/seconds/1e6))
|
||||
}
|
||||
if ops > 0 {
|
||||
parts = append(parts, fmt.Sprintf("%8.1f ops/s", float64(ops)/seconds))
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
return " " + strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
func (r *runner) run() {
|
||||
buf := make([]byte, seqBufSize)
|
||||
rnd := rand.New(rand.NewSource(42))
|
||||
rnd.Read(buf)
|
||||
|
||||
bigFile := filepath.Join(r.dir, "big.dat")
|
||||
r.phase("seq_write", seqFileSize, 0, func() error {
|
||||
f, err := os.Create(bigFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for written := 0; written < seqFileSize; written += len(buf) {
|
||||
if _, err := f.Write(buf); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
return f.Close()
|
||||
})
|
||||
|
||||
r.phase("seq_read", seqFileSize, 0, func() error {
|
||||
f, err := os.Open(bigFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
n, err := io.CopyBuffer(io.Discard, f, buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != seqFileSize {
|
||||
return fmt.Errorf("read %d bytes, want %d", n, seqFileSize)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
r.phase("rand_read", randReads*randReadSize, randReads, func() error {
|
||||
f, err := os.Open(bigFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
block := make([]byte, randReadSize)
|
||||
for i := 0; i < randReads; i++ {
|
||||
off := rnd.Int63n(seqFileSize - randReadSize)
|
||||
if _, err := f.ReadAt(block, off); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
smallDir := filepath.Join(r.dir, "small")
|
||||
small := buf[:smallSize]
|
||||
r.phase("small_write", smallCount*smallSize, smallCount, func() error {
|
||||
if err := os.MkdirAll(smallDir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < smallCount; i++ {
|
||||
if err := os.WriteFile(filepath.Join(smallDir, fmt.Sprintf("f%04d.dat", i)), small, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
r.phase("small_read", smallCount*smallSize, smallCount, func() error {
|
||||
for i := 0; i < smallCount; i++ {
|
||||
data, err := os.ReadFile(filepath.Join(smallDir, fmt.Sprintf("f%04d.dat", i)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) != smallSize {
|
||||
return fmt.Errorf("file %d: read %d bytes, want %d", i, len(data), smallSize)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
r.phase("stat_files", 0, smallCount*statRounds, func() error {
|
||||
for round := 0; round < statRounds; round++ {
|
||||
for i := 0; i < smallCount; i++ {
|
||||
if _, err := os.Stat(filepath.Join(smallDir, fmt.Sprintf("f%04d.dat", i))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
r.phase("list_dir", 0, listRounds, func() error {
|
||||
for round := 0; round < listRounds; round++ {
|
||||
entries, err := os.ReadDir(smallDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(entries) != smallCount {
|
||||
return fmt.Errorf("listed %d entries, want %d", len(entries), smallCount)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
r.phase("overwrite", overwriteN*smallSize, overwriteN, func() error {
|
||||
for i := 0; i < overwriteN; i++ {
|
||||
if err := os.WriteFile(filepath.Join(smallDir, fmt.Sprintf("f%04d.dat", i)), small, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
r.phase("delete", 0, smallCount, func() error {
|
||||
for i := 0; i < smallCount; i++ {
|
||||
if err := os.Remove(filepath.Join(smallDir, fmt.Sprintf("f%04d.dat", i))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if r.filer != "" {
|
||||
r.bigListPhase()
|
||||
}
|
||||
}
|
||||
|
||||
// bigListPhase enumerates a directory whose files were created directly
|
||||
// against the filer, so the listing is measured on its own rather than after
|
||||
// this process has created (and possibly cached) every entry itself.
|
||||
func (r *runner) bigListPhase() {
|
||||
// The bench dir is a direct child of the mount root, so its base name is
|
||||
// also its path on the filer.
|
||||
mountName := filepath.Base(r.dir)
|
||||
bigDir := filepath.Join(r.dir, "biglist")
|
||||
if err := seedFilerDir(r.filer, mountName+"/biglist", bigListCount); err != nil {
|
||||
log.Fatalf("seeding %d files via filer: %v", bigListCount, err)
|
||||
}
|
||||
|
||||
r.phase("list_5k", 0, bigListCount*bigListRounds, func() error {
|
||||
for round := 0; round < bigListRounds; round++ {
|
||||
entries, err := os.ReadDir(bigDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(entries) != bigListCount {
|
||||
return fmt.Errorf("listed %d entries, want %d", len(entries), bigListCount)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
r.phase("walk_5k", 0, bigListCount, func() error {
|
||||
entries, err := os.ReadDir(bigDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if _, err := entry.Info(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// seedFilerDir creates count tiny files under dir on the filer over plain
|
||||
// HTTP, in parallel, bypassing the mount entirely.
|
||||
func seedFilerDir(filer, dir string, count int) error {
|
||||
content := []byte("x")
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, count)
|
||||
sem := make(chan struct{}, 64)
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
sem <- struct{}{}
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
url := fmt.Sprintf("http://%s/%s/img%05d.jpg", filer, dir, i)
|
||||
if err := uploadOne(client, url, content); err != nil {
|
||||
errs <- fmt.Errorf("%s: %w", url, err)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
return <-errs
|
||||
}
|
||||
|
||||
func uploadOne(client *http.Client, url string, content []byte) error {
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
part, err := writer.CreateFormFile("file", filepath.Base(url))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := part.Write(content); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, url, &body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("status %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// printComparison renders the named result files side by side as a markdown
|
||||
// table, one row per phase, with throughput where the phase moved bytes and
|
||||
// operation rate otherwise.
|
||||
func printComparison(files []string) error {
|
||||
var runs []runResult
|
||||
for _, file := range files {
|
||||
data, err := os.ReadFile(strings.TrimSpace(file))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var run runResult
|
||||
if err := json.Unmarshal(data, &run); err != nil {
|
||||
return fmt.Errorf("%s: %w", file, err)
|
||||
}
|
||||
runs = append(runs, run)
|
||||
}
|
||||
if len(runs) == 0 {
|
||||
return fmt.Errorf("no result files")
|
||||
}
|
||||
|
||||
// Preserve the phase order of the first run, appending any extras.
|
||||
var order []string
|
||||
seen := map[string]bool{}
|
||||
for _, run := range runs {
|
||||
for _, p := range run.Phases {
|
||||
if !seen[p.Name] {
|
||||
seen[p.Name] = true
|
||||
order = append(order, p.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
byName := make([]map[string]phaseResult, len(runs))
|
||||
for i, run := range runs {
|
||||
byName[i] = map[string]phaseResult{}
|
||||
for _, p := range run.Phases {
|
||||
byName[i][p.Name] = p
|
||||
}
|
||||
}
|
||||
|
||||
header := []string{"phase"}
|
||||
for _, run := range runs {
|
||||
header = append(header, run.Label+" (s)", run.Label+" rate")
|
||||
}
|
||||
fmt.Println("| " + strings.Join(header, " | ") + " |")
|
||||
fmt.Println("|" + strings.Repeat("---|", len(header)))
|
||||
for _, name := range order {
|
||||
row := []string{name}
|
||||
for i := range runs {
|
||||
p, ok := byName[i][name]
|
||||
if !ok {
|
||||
row = append(row, "-", "-")
|
||||
continue
|
||||
}
|
||||
row = append(row, fmt.Sprintf("%.2f", p.Seconds), strings.TrimSpace(rateSuffix(p.Bytes, p.Ops, p.Seconds)))
|
||||
}
|
||||
fmt.Println("| " + strings.Join(row, " | ") + " |")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package multi_master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
// A filer only learns about its peers from the cluster node updates on its
|
||||
// KeepConnected stream, and those are broadcast to whoever is connected at that
|
||||
// moment. A filer that reconnects has to be told the membership again, or it
|
||||
// never subscribes to the peers that registered while it was away.
|
||||
func TestKeepConnectedSendsExistingFilers(t *testing.T) {
|
||||
mc := StartMasterCluster(t)
|
||||
|
||||
leaderIdx, leaderAddr := mc.FindLeader()
|
||||
if leaderIdx < 0 {
|
||||
t.Fatal("no leader")
|
||||
}
|
||||
master := pb.ServerAddress(leaderAddr)
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
|
||||
const existingFiler = "127.0.0.1:18888"
|
||||
const joiningFiler = "127.0.0.1:18889"
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), waitTimeout)
|
||||
defer cancel()
|
||||
|
||||
err := pb.WithMasterClient(ctx, true, master, dialOption, false, func(client master_pb.SeaweedClient) error {
|
||||
stream, err := client.KeepConnected(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.Send(&master_pb.KeepConnectedRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
ClientAddress: existingFiler,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := waitForClusterNode(ctx, client, existingFiler); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return pb.WithMasterClient(ctx, true, master, dialOption, false, func(joining master_pb.SeaweedClient) error {
|
||||
joiningCtx, cancelJoining := context.WithTimeout(ctx, waitTimeout)
|
||||
defer cancelJoining()
|
||||
|
||||
joiningStream, err := joining.KeepConnected(joiningCtx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := joiningStream.Send(&master_pb.KeepConnectedRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
ClientAddress: joiningFiler,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; ; i++ {
|
||||
resp, err := joiningStream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// a client only reads the volume locations out of the first
|
||||
// message, an update sent ahead of them would be dropped
|
||||
if i == 0 && resp.VolumeLocation == nil {
|
||||
return fmt.Errorf("first message is not a volume location: %+v", resp)
|
||||
}
|
||||
if update := resp.ClusterNodeUpdate; update != nil && update.IsAdd && update.Address == existingFiler {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
mc.DumpLogs()
|
||||
t.Fatalf("a joining filer was not told about %s: %v", existingFiler, err)
|
||||
}
|
||||
}
|
||||
|
||||
func waitForClusterNode(ctx context.Context, client master_pb.SeaweedClient, address string) error {
|
||||
deadline := time.Now().Add(waitTimeout)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := client.ListClusterNodes(ctx, &master_pb.ListClusterNodesRequest{ClientType: cluster.FilerType})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, node := range resp.ClusterNodes {
|
||||
if node.Address == address {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
time.Sleep(waitTick)
|
||||
}
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
@@ -32,6 +32,7 @@ type VolumeServer struct {
|
||||
|
||||
mu sync.Mutex
|
||||
receivedFiles map[string]uint64
|
||||
readonlyVolumes map[uint32]bool
|
||||
mountRequests []*volume_server_pb.VolumeEcShardsMountRequest
|
||||
deleteRequests []*volume_server_pb.VolumeDeleteRequest
|
||||
markReadonlyCalls int
|
||||
@@ -67,12 +68,13 @@ func NewVolumeServer(t *testing.T, baseDir string) *VolumeServer {
|
||||
grpcPort := listener.Addr().(*net.TCPAddr).Port
|
||||
server := pb.NewGrpcServer()
|
||||
vs := &VolumeServer{
|
||||
t: t,
|
||||
server: server,
|
||||
listener: listener,
|
||||
address: fmt.Sprintf("127.0.0.1:0.%d", grpcPort),
|
||||
baseDir: baseDir,
|
||||
receivedFiles: make(map[string]uint64),
|
||||
t: t,
|
||||
server: server,
|
||||
listener: listener,
|
||||
address: fmt.Sprintf("127.0.0.1:0.%d", grpcPort),
|
||||
baseDir: baseDir,
|
||||
receivedFiles: make(map[string]uint64),
|
||||
readonlyVolumes: make(map[uint32]bool),
|
||||
}
|
||||
|
||||
volume_server_pb.RegisterVolumeServerServer(server, vs)
|
||||
@@ -386,6 +388,9 @@ func (v *VolumeServer) VolumeDelete(ctx context.Context, req *volume_server_pb.V
|
||||
func (v *VolumeServer) VolumeMarkReadonly(ctx context.Context, req *volume_server_pb.VolumeMarkReadonlyRequest) (*volume_server_pb.VolumeMarkReadonlyResponse, error) {
|
||||
v.mu.Lock()
|
||||
v.markReadonlyCalls++
|
||||
if req != nil {
|
||||
v.readonlyVolumes[req.VolumeId] = true
|
||||
}
|
||||
v.mu.Unlock()
|
||||
return &volume_server_pb.VolumeMarkReadonlyResponse{}, nil
|
||||
}
|
||||
@@ -393,10 +398,19 @@ func (v *VolumeServer) VolumeMarkReadonly(ctx context.Context, req *volume_serve
|
||||
func (v *VolumeServer) VolumeMarkWritable(ctx context.Context, req *volume_server_pb.VolumeMarkWritableRequest) (*volume_server_pb.VolumeMarkWritableResponse, error) {
|
||||
v.mu.Lock()
|
||||
v.markWritableCalls++
|
||||
if req != nil {
|
||||
v.readonlyVolumes[req.VolumeId] = false
|
||||
}
|
||||
v.mu.Unlock()
|
||||
return &volume_server_pb.VolumeMarkWritableResponse{}, nil
|
||||
}
|
||||
|
||||
func (v *VolumeServer) VolumeStatus(ctx context.Context, req *volume_server_pb.VolumeStatusRequest) (*volume_server_pb.VolumeStatusResponse, error) {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
return &volume_server_pb.VolumeStatusResponse{IsReadOnly: v.readonlyVolumes[req.GetVolumeId()]}, nil
|
||||
}
|
||||
|
||||
func (v *VolumeServer) ReadVolumeFileStatus(ctx context.Context, req *volume_server_pb.ReadVolumeFileStatusRequest) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
|
||||
v.mu.Lock()
|
||||
v.readFileStatusCalls++
|
||||
|
||||
@@ -146,13 +146,14 @@ func TestVolumeBalanceBatchExecutionIntegration(t *testing.T) {
|
||||
require.True(t, deletedVols[vid], "volume %d should have been deleted from source", vid)
|
||||
}
|
||||
|
||||
// Each move reads source status once before copy and once inside the
|
||||
// target's fake VolumeCopy implementation, then reads target status once
|
||||
// before deleting the source.
|
||||
// Each move reads source status once inside the target's fake VolumeCopy
|
||||
// implementation and once for the pre-delete verification, and reads
|
||||
// target status once probing for a pre-existing copy and once for the
|
||||
// verification.
|
||||
require.Equal(t, len(volumeIDs)*2, source.ReadFileStatusCount(),
|
||||
"each move should read source volume status before copy and during target copy")
|
||||
require.Equal(t, len(volumeIDs), target.ReadFileStatusCount(),
|
||||
"each move should read target volume status before delete")
|
||||
"each move should read source volume status during target copy and at verification")
|
||||
require.Equal(t, len(volumeIDs)*2, target.ReadFileStatusCount(),
|
||||
"each move should probe the target and read its status at verification")
|
||||
|
||||
// Target should have received copy and tail calls for all 3 volumes.
|
||||
copyCalls, _, tailCalls := target.BalanceStats()
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
package copying_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// createRenameSource builds the x-amz-rename-source value the way the AWS CLI,
|
||||
// Java and Rust examples do: the bare source key, URL encoded.
|
||||
func createRenameSource(key string) string {
|
||||
return url.PathEscape(key)
|
||||
}
|
||||
|
||||
// createQualifiedRenameSource builds the alternate bucket/key form the second
|
||||
// AWS CLI example and the boto3 conditional example use.
|
||||
func createQualifiedRenameSource(bucketName, key string) string {
|
||||
return fmt.Sprintf("%s/%s", bucketName, url.PathEscape(key))
|
||||
}
|
||||
|
||||
func renameObject(t *testing.T, client *s3.Client, bucketName, srcKey, dstKey string) {
|
||||
t.Helper()
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(dstKey),
|
||||
RenameSource: aws.String(createRenameSource(srcKey)),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// requireRenameStatus asserts err carries the given HTTP status code.
|
||||
func requireRenameStatus(t *testing.T, err error, status int) {
|
||||
t.Helper()
|
||||
require.Error(t, err)
|
||||
var respErr *smithyhttp.ResponseError
|
||||
require.True(t, errors.As(err, &respErr), "expected an HTTP response error, got %v", err)
|
||||
assert.Equal(t, status, respErr.HTTPStatusCode(), "unexpected error: %v", err)
|
||||
}
|
||||
|
||||
func objectExists(t *testing.T, client *s3.Client, bucketName, key string) bool {
|
||||
t.Helper()
|
||||
_, err := client.HeadObject(context.TODO(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// TestRenameObject renames an object and checks the bytes, metadata and ETag
|
||||
// arrive under the new key while the old key disappears.
|
||||
func TestRenameObject(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
content := "rename me"
|
||||
put := putObjectWithMetadata(t, client, bucketName, "source.txt", content,
|
||||
map[string]string{"origin": "source"}, "text/plain")
|
||||
|
||||
renameObject(t, client, bucketName, "source.txt", "renamed/target.txt")
|
||||
|
||||
assert.False(t, objectExists(t, client, bucketName, "source.txt"), "source should be gone")
|
||||
|
||||
resp := getObject(t, client, bucketName, "renamed/target.txt")
|
||||
assert.Equal(t, content, getObjectBody(t, resp))
|
||||
assert.Equal(t, "text/plain", aws.ToString(resp.ContentType))
|
||||
assert.Equal(t, "source", resp.Metadata["origin"])
|
||||
assert.Equal(t, aws.ToString(put.ETag), aws.ToString(resp.ETag), "ETag must survive the rename")
|
||||
}
|
||||
|
||||
// TestRenameObjectOverwritesDestination: without a conditional header a rename
|
||||
// replaces whatever the destination key held.
|
||||
func TestRenameObjectOverwritesDestination(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "source.txt", "new content")
|
||||
putObject(t, client, bucketName, "target.txt", "old content")
|
||||
|
||||
renameObject(t, client, bucketName, "source.txt", "target.txt")
|
||||
|
||||
resp := getObject(t, client, bucketName, "target.txt")
|
||||
assert.Equal(t, "new content", getObjectBody(t, resp))
|
||||
}
|
||||
|
||||
// TestRenameObjectIfNoneMatch: If-None-Match: * protects an existing destination.
|
||||
func TestRenameObjectIfNoneMatch(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "source.txt", "new content")
|
||||
putObject(t, client, bucketName, "target.txt", "old content")
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createRenameSource("source.txt")),
|
||||
DestinationIfNoneMatch: aws.String("*"),
|
||||
})
|
||||
requireRenameStatus(t, err, 412)
|
||||
|
||||
resp := getObject(t, client, bucketName, "target.txt")
|
||||
assert.Equal(t, "old content", getObjectBody(t, resp))
|
||||
assert.True(t, objectExists(t, client, bucketName, "source.txt"), "a failed rename must leave the source alone")
|
||||
|
||||
// The same rename onto a free key succeeds.
|
||||
_, err = client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("free.txt"),
|
||||
RenameSource: aws.String(createRenameSource("source.txt")),
|
||||
DestinationIfNoneMatch: aws.String("*"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// TestRenameObjectSourceIfMatch gates the rename on the source's ETag.
|
||||
func TestRenameObjectSourceIfMatch(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
put := putObject(t, client, bucketName, "source.txt", "content")
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createRenameSource("source.txt")),
|
||||
SourceIfMatch: aws.String("\"00000000000000000000000000000000\""),
|
||||
})
|
||||
requireRenameStatus(t, err, 412)
|
||||
assert.True(t, objectExists(t, client, bucketName, "source.txt"))
|
||||
|
||||
_, err = client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createRenameSource("source.txt")),
|
||||
SourceIfMatch: put.ETag,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, objectExists(t, client, bucketName, "source.txt"))
|
||||
assert.True(t, objectExists(t, client, bucketName, "target.txt"))
|
||||
}
|
||||
|
||||
// TestRenameObjectOntoDirectory: a key that already holds other objects is a
|
||||
// directory, and an object must not be allowed to replace one.
|
||||
func TestRenameObjectOntoDirectory(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "source.txt", "content")
|
||||
putObject(t, client, bucketName, "target/child.txt", "child")
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target"),
|
||||
RenameSource: aws.String(createRenameSource("source.txt")),
|
||||
})
|
||||
requireRenameStatus(t, err, 409)
|
||||
assert.True(t, objectExists(t, client, bucketName, "source.txt"))
|
||||
assert.True(t, objectExists(t, client, bucketName, "target/child.txt"))
|
||||
}
|
||||
|
||||
// TestRenameObjectDirectorySource: a directory can be named without a trailing
|
||||
// slash, and renaming one would move a whole subtree. It is not an object, so it
|
||||
// is a missing key.
|
||||
func TestRenameObjectDirectorySource(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "source/child.txt", "child")
|
||||
|
||||
for _, src := range []string{"source", "source/"} {
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createRenameSource(src)),
|
||||
})
|
||||
requireRenameStatus(t, err, 404)
|
||||
}
|
||||
assert.True(t, objectExists(t, client, bucketName, "source/child.txt"))
|
||||
assert.False(t, objectExists(t, client, bucketName, "target.txt"))
|
||||
}
|
||||
|
||||
// TestRenameObjectMissingSource reports a missing source as NoSuchKey.
|
||||
func TestRenameObjectMissingSource(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createRenameSource("absent.txt")),
|
||||
})
|
||||
requireRenameStatus(t, err, 404)
|
||||
}
|
||||
|
||||
// TestRenameObjectQualifiedSource: the bucket/key form AWS's second CLI example
|
||||
// and the boto3 conditional example use resolves to the same object as the bare
|
||||
// key.
|
||||
func TestRenameObjectQualifiedSource(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "dir/source.txt", "content")
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createQualifiedRenameSource(bucketName, "dir/source.txt")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, objectExists(t, client, bucketName, "dir/source.txt"))
|
||||
assert.Equal(t, "content", getObjectBody(t, getObject(t, client, bucketName, "target.txt")))
|
||||
}
|
||||
|
||||
// TestRenameObjectSourceShadowingTheBucketName: a key whose own first segment is
|
||||
// the bucket name is a real key, and must win over reading the same value as a
|
||||
// bucket-qualified source.
|
||||
func TestRenameObjectSourceShadowingTheBucketName(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
shadowed := bucketName + "/source.txt"
|
||||
putObject(t, client, bucketName, shadowed, "shadowed")
|
||||
putObject(t, client, bucketName, "source.txt", "bare")
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createQualifiedRenameSource(bucketName, "source.txt")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "shadowed", getObjectBody(t, getObject(t, client, bucketName, "target.txt")))
|
||||
assert.False(t, objectExists(t, client, bucketName, shadowed))
|
||||
assert.True(t, objectExists(t, client, bucketName, "source.txt"), "the bare key must be left alone")
|
||||
}
|
||||
|
||||
// TestRenameObjectSourceShadowedByADirectory: the literal reading of the source
|
||||
// names a directory here, and the bucket-qualified reading names a live object.
|
||||
// Naming a directory is an error about that directory — falling through to the
|
||||
// other reading would rename a different object than the one asked for.
|
||||
func TestRenameObjectSourceShadowedByADirectory(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, bucketName+"/source.txt/child.txt", "child")
|
||||
putObject(t, client, bucketName, "source.txt", "bare")
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createQualifiedRenameSource(bucketName, "source.txt")),
|
||||
})
|
||||
requireRenameStatus(t, err, 404)
|
||||
assert.True(t, objectExists(t, client, bucketName, "source.txt"), "the bare key must be left alone")
|
||||
assert.False(t, objectExists(t, client, bucketName, "target.txt"))
|
||||
}
|
||||
|
||||
// TestRenameObjectCrossBucket: RenameObject moves within one bucket, so another
|
||||
// bucket's name in the source is just part of a key this bucket does not hold.
|
||||
func TestRenameObjectCrossBucket(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
srcBucket := getNewBucketName()
|
||||
createBucket(t, client, srcBucket)
|
||||
defer deleteBucket(t, client, srcBucket)
|
||||
dstBucket := getNewBucketName()
|
||||
createBucket(t, client, dstBucket)
|
||||
defer deleteBucket(t, client, dstBucket)
|
||||
|
||||
putObject(t, client, srcBucket, "source.txt", "content")
|
||||
|
||||
_, err := client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(dstBucket),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createQualifiedRenameSource(srcBucket, "source.txt")),
|
||||
})
|
||||
requireRenameStatus(t, err, 404)
|
||||
assert.True(t, objectExists(t, client, srcBucket, "source.txt"))
|
||||
}
|
||||
|
||||
// TestRenameObjectVersionedBucket: versioned buckets are not supported yet, and
|
||||
// must say so rather than silently dropping versions.
|
||||
func TestRenameObjectVersionedBucket(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
_, err := client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
putObject(t, client, bucketName, "source.txt", "content")
|
||||
|
||||
_, err = client.RenameObject(context.TODO(), &s3.RenameObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("target.txt"),
|
||||
RenameSource: aws.String(createRenameSource("source.txt")),
|
||||
})
|
||||
requireRenameStatus(t, err, 501)
|
||||
assert.True(t, objectExists(t, client, bucketName, "source.txt"))
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Deleting a key whose null version predates versioning records the delete
|
||||
// marker under <key>.versions but leaves the null object at the base path.
|
||||
// The listing must retract that stale entry, on whichever page it lands.
|
||||
|
||||
func deleteObject(t *testing.T, client *s3.Client, bucket, key string) {
|
||||
t.Helper()
|
||||
resp, err := client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, resp.DeleteMarker != nil && *resp.DeleteMarker, "the delete must record a delete marker")
|
||||
}
|
||||
|
||||
func TestPreVersioningNullObjectDeleteHidesKey(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "k.txt", "pre-versioning")
|
||||
enableVersioning(t, client, bucketName)
|
||||
deleteObject(t, client, bucketName, "k.txt")
|
||||
|
||||
assert.Empty(t, listAllKeys(t, client, bucketName, 0), "the deleted key must leave the listing")
|
||||
|
||||
_, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName), Key: aws.String("k.txt"),
|
||||
})
|
||||
assert.Error(t, err, "the deleted key must not be readable")
|
||||
|
||||
versions, err := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versions.DeleteMarkers, 1)
|
||||
assert.True(t, *versions.DeleteMarkers[0].IsLatest, "the delete marker is the current version")
|
||||
require.Len(t, versions.Versions, 1)
|
||||
assert.Equal(t, "null", *versions.Versions[0].VersionId)
|
||||
assert.False(t, *versions.Versions[0].IsLatest, "the null version is shadowed by the marker")
|
||||
}
|
||||
|
||||
func TestPreVersioningNullObjectDeleteAfterOverwriteHidesKey(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "k.txt", "pre-versioning")
|
||||
enableVersioning(t, client, bucketName)
|
||||
putObject(t, client, bucketName, "k.txt", "versioned overwrite")
|
||||
deleteObject(t, client, bucketName, "k.txt")
|
||||
|
||||
assert.Empty(t, listAllKeys(t, client, bucketName, 0), "the deleted key must leave the listing")
|
||||
}
|
||||
|
||||
// The retraction and the replacement must both survive a page boundary landing
|
||||
// between a key and its .versions sibling.
|
||||
func TestPreVersioningNullObjectAcrossPageBoundary(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "a.txt", "old")
|
||||
enableVersioning(t, client, bucketName)
|
||||
deleteObject(t, client, bucketName, "a.txt")
|
||||
putObjectVersioned(t, client, bucketName, "b.txt")
|
||||
|
||||
assert.Equal(t, []string{"b.txt"}, listAllKeys(t, client, bucketName, 1),
|
||||
"a page ending on the stale null object must still retract it")
|
||||
}
|
||||
|
||||
func TestPreVersioningNullObjectMetadataAcrossPageBoundary(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
overwrite := "versioned overwrite"
|
||||
putObject(t, client, bucketName, "a.txt", "old")
|
||||
enableVersioning(t, client, bucketName)
|
||||
putObject(t, client, bucketName, "a.txt", overwrite)
|
||||
putObjectVersioned(t, client, bucketName, "b.txt")
|
||||
|
||||
page, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName), MaxKeys: aws.Int32(1),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, page.Contents, 1)
|
||||
assert.Equal(t, "a.txt", *page.Contents[0].Key)
|
||||
assert.Equal(t, int64(len(overwrite)), *page.Contents[0].Size,
|
||||
"a page ending on the null object must still pick up the current version's metadata")
|
||||
}
|
||||
|
||||
// A key such as "a.txt.bak" sorts between "a.txt" and "a.txt.versions", so the
|
||||
// sibling's outcome arrives entries later, possibly on a later page.
|
||||
func TestPreVersioningInterveningKeyRetraction(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "a.txt", "pre-versioning")
|
||||
putObject(t, client, bucketName, "a.txt!between", "pre-versioning")
|
||||
putObject(t, client, bucketName, "a.txt.bak", "pre-versioning")
|
||||
enableVersioning(t, client, bucketName)
|
||||
deleteObject(t, client, bucketName, "a.txt")
|
||||
|
||||
for _, maxKeys := range []int32{0, 1, 2} {
|
||||
assert.Equal(t, []string{"a.txt!between", "a.txt.bak"}, listAllKeys(t, client, bucketName, maxKeys),
|
||||
"maxKeys=%d must not list the deleted key", maxKeys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreVersioningInterveningKeyMetadata(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
overwrite := "versioned overwrite"
|
||||
putObject(t, client, bucketName, "a.txt", "old")
|
||||
putObject(t, client, bucketName, "a.txt!between", "pre-versioning")
|
||||
putObject(t, client, bucketName, "a.txt.bak", "pre-versioning")
|
||||
enableVersioning(t, client, bucketName)
|
||||
putObject(t, client, bucketName, "a.txt", overwrite)
|
||||
|
||||
for _, maxKeys := range []int32{1, 2} {
|
||||
var keys []string
|
||||
var token *string
|
||||
for {
|
||||
page, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName), MaxKeys: aws.Int32(maxKeys), ContinuationToken: token,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
for _, o := range page.Contents {
|
||||
keys = append(keys, *o.Key)
|
||||
if *o.Key == "a.txt" {
|
||||
assert.Equal(t, int64(len(overwrite)), *o.Size,
|
||||
"maxKeys=%d must list the current version's metadata", maxKeys)
|
||||
}
|
||||
}
|
||||
if page.IsTruncated == nil || !*page.IsTruncated {
|
||||
break
|
||||
}
|
||||
token = page.NextContinuationToken
|
||||
}
|
||||
assert.Equal(t, []string{"a.txt", "a.txt!between", "a.txt.bak"}, keys, "maxKeys=%d", maxKeys)
|
||||
}
|
||||
}
|
||||
|
||||
// CommonPrefixes derive from listable keys, so deleting the only pre-versioning
|
||||
// object under a prefix takes the prefix with it.
|
||||
func TestPreVersioningDeletedPrefixHidesCommonPrefix(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "p/k.txt", "pre-versioning")
|
||||
enableVersioning(t, client, bucketName)
|
||||
deleteObject(t, client, bucketName, "p/k.txt")
|
||||
|
||||
page, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName), Delimiter: aws.String("/"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, page.Contents)
|
||||
assert.Empty(t, page.CommonPrefixes, "no listable key remains under p/")
|
||||
}
|
||||
|
||||
// A non-slash delimiter derives prefixes straight from base-path keys, so a
|
||||
// delete-marked null object must take its prefix along; a live key under the
|
||||
// same prefix brings it back.
|
||||
func TestPreVersioningDeletedKeyHidesCustomDelimiterPrefix(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "group-item", "pre-versioning")
|
||||
putObject(t, client, bucketName, "solo", "pre-versioning")
|
||||
enableVersioning(t, client, bucketName)
|
||||
deleteObject(t, client, bucketName, "group-item")
|
||||
|
||||
listDashed := func() (keys, prefixes []string) {
|
||||
page, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName), Delimiter: aws.String("-"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
for _, o := range page.Contents {
|
||||
keys = append(keys, *o.Key)
|
||||
}
|
||||
for _, p := range page.CommonPrefixes {
|
||||
prefixes = append(prefixes, *p.Prefix)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
keys, prefixes := listDashed()
|
||||
assert.Equal(t, []string{"solo"}, keys)
|
||||
assert.Empty(t, prefixes, "the deleted key was the prefix's only backer")
|
||||
|
||||
putObject(t, client, bucketName, "group-live", "versioned")
|
||||
keys, prefixes = listDashed()
|
||||
assert.Equal(t, []string{"solo"}, keys)
|
||||
assert.Equal(t, []string{"group-"}, prefixes, "a live key restores the prefix")
|
||||
}
|
||||
|
||||
// A delete marker for a version-only key (never a base object) must not debit
|
||||
// the backers of a prefix a live null object still stands behind.
|
||||
func TestVersionOnlyMarkerLeavesForeignPrefixAlone(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
putObject(t, client, bucketName, "group-a", "pre-versioning")
|
||||
enableVersioning(t, client, bucketName)
|
||||
putObjectVersioned(t, client, bucketName, "group-b")
|
||||
deleteObject(t, client, bucketName, "group-b")
|
||||
|
||||
page, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName), Delimiter: aws.String("-"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, page.Contents)
|
||||
require.Len(t, page.CommonPrefixes, 1, "group-a still backs the prefix")
|
||||
assert.Equal(t, "group-", *page.CommonPrefixes[0].Prefix)
|
||||
}
|
||||
|
||||
// Nested names (k, k!, k!!, ...) can hold more unresolved null objects than the
|
||||
// pending cap; the evicted key must still be settled, on any page size.
|
||||
func TestPreVersioningNestedNullObjectsBeyondCap(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
var live []string
|
||||
for i := 0; i < 10; i++ {
|
||||
key := "k" + strings.Repeat("!", i)
|
||||
putObject(t, client, bucketName, key, "pre-versioning")
|
||||
if i > 0 {
|
||||
live = append(live, key)
|
||||
}
|
||||
}
|
||||
enableVersioning(t, client, bucketName)
|
||||
deleteObject(t, client, bucketName, "k")
|
||||
|
||||
sort.Strings(live)
|
||||
for _, maxKeys := range []int32{0, 3, 9} {
|
||||
assert.Equal(t, live, listAllKeys(t, client, bucketName, maxKeys),
|
||||
"maxKeys=%d must not list the deleted key", maxKeys)
|
||||
}
|
||||
}
|
||||
|
||||
// A suspended-versioning write is the current null version; its .versions
|
||||
// sibling (whose latest pointer the write cleared) must not list it a second
|
||||
// time or resurrect an older version's metadata.
|
||||
func TestSuspendedNullObjectListsOnce(t *testing.T) {
|
||||
client := getS3Client(t)
|
||||
bucketName := getNewBucketName()
|
||||
createBucket(t, client, bucketName)
|
||||
defer deleteBucket(t, client, bucketName)
|
||||
|
||||
enableVersioning(t, client, bucketName)
|
||||
putObject(t, client, bucketName, "k.txt", "versioned")
|
||||
suspendVersioning(t, client, bucketName)
|
||||
current := "suspended current"
|
||||
putObject(t, client, bucketName, "k.txt", current)
|
||||
|
||||
page, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucketName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, page.Contents, 1, "one key must list exactly once")
|
||||
assert.Equal(t, int64(len(current)), *page.Contents[0].Size, "the null version is current")
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# Iceberg writer used by the ClickHouse integration test to populate a table
|
||||
# with data files via PyIceberg, so the downstream ClickHouse SELECT verifies
|
||||
# the read path against non-empty results rather than just count() = 0.
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN pip install --no-cache-dir "pyiceberg[s3fs]==0.11.1" "pyarrow==25.0.0"
|
||||
|
||||
COPY append_rows.py read_rows.py /app/
|
||||
|
||||
ENTRYPOINT ["python3", "/app/append_rows.py"]
|
||||
@@ -0,0 +1,98 @@
|
||||
# ClickHouse Iceberg Catalog Integration Test
|
||||
|
||||
This directory contains a ClickHouse integration smoke test for SeaweedFS's
|
||||
Iceberg REST Catalog implementation, using ClickHouse's `DataLakeCatalog`
|
||||
database engine.
|
||||
|
||||
## What It Tests
|
||||
|
||||
`TestClickHouseIcebergCatalog` verifies the ClickHouse path end to end:
|
||||
|
||||
1. Starts a local SeaweedFS mini cluster with S3 Tables and Iceberg REST enabled.
|
||||
2. Creates a SeaweedFS table bucket.
|
||||
3. Creates an Iceberg namespace and an empty table through the SeaweedFS REST
|
||||
catalog OAuth flow.
|
||||
4. Creates a second table and populates it with three rows by running a
|
||||
PyIceberg writer container (`Dockerfile.writer` + `append_rows.py`) before
|
||||
ClickHouse connects, so the snapshot is part of the catalog's first scan.
|
||||
5. Starts the ClickHouse server container (`clickhouse/clickhouse-server:25.8`
|
||||
by default, overridable via `CLICKHOUSE_IMAGE`) and waits for the HTTP
|
||||
interface.
|
||||
6. Attaches the catalog with `CREATE DATABASE ... ENGINE = DataLakeCatalog`
|
||||
(`catalog_type = 'rest'`), authenticating to the catalog via the OAuth2
|
||||
client-credentials flow (`catalog_credential` + `oauth_server_uri`) and to
|
||||
S3 via the engine's access/secret key arguments and `storage_endpoint`.
|
||||
7. Runs subtests against the SeaweedFS-backed Iceberg tables:
|
||||
- `BasicSelect`: ClickHouse is alive and answering SQL.
|
||||
- `DatabaseVisible`: the DataLakeCatalog database exists.
|
||||
- `TableVisible`: seeded tables appear as `namespace.table` entries in
|
||||
`SHOW TABLES` (ClickHouse flattens Iceberg namespaces into table names).
|
||||
- `DescribeTable`: the Iceberg schema mapped to `id Int64` and
|
||||
`label Nullable(String)`. Failure here means ClickHouse could not parse
|
||||
the schema returned by the SeaweedFS catalog.
|
||||
- `CountEmptyTable`: catalog-to-table resolution and a scan of an empty table.
|
||||
- `ReadWrittenDataCount` and `ReadWrittenDataValues`: ClickHouse reads back
|
||||
the three PyIceberg-appended rows and the values match. This exercises the
|
||||
actual data path (parquet reads via S3), not just metadata.
|
||||
- `WriteReadBack`: ClickHouse inserts rows with its experimental Iceberg
|
||||
write support using default settings, which produces manifests without
|
||||
avro field-ids, bucket-relative paths, and parquet without field ids. The
|
||||
SeaweedFS catalog repairs the manifests at commit time and stamps a
|
||||
default name mapping on the table, so PyIceberg (`read_rows.py`, a strict
|
||||
reader) must return the rows ClickHouse wrote.
|
||||
- `CreateTableViaCatalog`: ClickHouse creates a table through the catalog
|
||||
(`CREATE TABLE ... ENGINE = IcebergS3(...)` with
|
||||
`write_full_path_in_iceberg_metadata = 1`), the test verifies it is
|
||||
registered in the REST catalog, inserts rows, reads them back, and has
|
||||
PyIceberg read them too. ClickHouse only issues the catalog createTable
|
||||
from 26.4, so the subtest skips on older servers.
|
||||
|
||||
Queries go through ClickHouse's HTTP interface (port 8123, mapped to a
|
||||
dynamically allocated host port), so the test needs no ClickHouse client
|
||||
driver. Tables are referenced as ``iceberg_catalog.`namespace.table` ``.
|
||||
|
||||
## Running Locally
|
||||
|
||||
Build or install `weed`, then run:
|
||||
|
||||
```bash
|
||||
cd test/s3tables/catalog_clickhouse
|
||||
go test -v -timeout 20m .
|
||||
```
|
||||
|
||||
The ClickHouse image defaults to `clickhouse/clickhouse-server:25.8` and can
|
||||
be overridden:
|
||||
|
||||
```bash
|
||||
CLICKHOUSE_IMAGE=clickhouse/clickhouse-server:latest go test -v -timeout 20m .
|
||||
```
|
||||
|
||||
The test requires Docker. The GitHub Actions job runs on `ubuntu-22.04` and
|
||||
executes the test for pull requests against both the pinned baseline image
|
||||
and `latest`, so new ClickHouse releases are covered as they ship.
|
||||
|
||||
## Configuration
|
||||
|
||||
The test uses these fixed credentials for the local SeaweedFS IAM config:
|
||||
|
||||
- S3 access key: `AKIAIOSFODNN7EXAMPLE`
|
||||
- S3 secret key: `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY`
|
||||
- Region: `us-west-2`
|
||||
- Warehouse bucket: `iceberg-tables`
|
||||
|
||||
ClickHouse ports:
|
||||
|
||||
- Only `8123` (HTTP interface) is mapped to a host port (allocated
|
||||
dynamically) so the Go test can issue queries from the test process.
|
||||
- The Iceberg REST endpoint and the S3 endpoint are reached from inside the
|
||||
ClickHouse container via `host.docker.internal`, matching the Doris, Trino,
|
||||
and Dremio test paths.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Ensure Docker is running: `docker version`
|
||||
- Ensure `weed` is built or available on `PATH`
|
||||
- `DataLakeCatalog` requires `allow_experimental_database_iceberg = 1`; the
|
||||
test passes it as a URL setting on the CREATE DATABASE request.
|
||||
- Container logs are printed in the failure message; you can also check
|
||||
`docker logs <seaweed-clickhouse-...>` while the test is running.
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Append rows to an existing Iceberg table via the SeaweedFS REST catalog.
|
||||
|
||||
Used by the ClickHouse integration test to materialize data files so a
|
||||
downstream SELECT from ClickHouse verifies the read path against non-empty
|
||||
results.
|
||||
|
||||
Usage:
|
||||
python3 append_rows.py \\
|
||||
--catalog-url http://localhost:8181 \\
|
||||
--warehouse s3://my-bucket \\
|
||||
--prefix my-bucket \\
|
||||
--s3-endpoint http://localhost:8333 \\
|
||||
--access-key AKIA... --secret-key wJalr... \\
|
||||
--namespace foo --namespace bar \\
|
||||
--table events
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
import pyarrow as pa
|
||||
from pyiceberg.catalog import load_catalog
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--catalog-url", required=True)
|
||||
p.add_argument("--warehouse", required=True, help="s3://<bucket-name>")
|
||||
p.add_argument("--prefix", required=True, help="REST catalog prefix (table bucket name)")
|
||||
p.add_argument("--s3-endpoint", required=True, help="http://host:port")
|
||||
p.add_argument("--access-key", required=True)
|
||||
p.add_argument("--secret-key", required=True)
|
||||
p.add_argument("--region", default="us-east-1")
|
||||
p.add_argument(
|
||||
"--namespace",
|
||||
action="append",
|
||||
required=True,
|
||||
help="One per level (e.g. --namespace foo --namespace bar for foo.bar).",
|
||||
)
|
||||
p.add_argument("--table", required=True)
|
||||
args = p.parse_args()
|
||||
|
||||
# `credential` triggers OAuth2 client_credentials against
|
||||
# <catalog_uri>/v1/oauth/tokens, matching the helper Go test uses for
|
||||
# REST-API table creation. The s3.* keys are needed for parquet writes.
|
||||
catalog = load_catalog(
|
||||
"rest",
|
||||
**{
|
||||
"type": "rest",
|
||||
"uri": args.catalog_url,
|
||||
"warehouse": args.warehouse,
|
||||
"prefix": args.prefix,
|
||||
"credential": f"{args.access_key}:{args.secret_key}",
|
||||
"s3.access-key-id": args.access_key,
|
||||
"s3.secret-access-key": args.secret_key,
|
||||
"s3.endpoint": args.s3_endpoint,
|
||||
"s3.region": args.region,
|
||||
"s3.path-style-access": "true",
|
||||
},
|
||||
)
|
||||
|
||||
table_id = tuple(args.namespace) + (args.table,)
|
||||
table = catalog.load_table(table_id)
|
||||
|
||||
# Match the Iceberg table schema: id is `required long`, label is
|
||||
# `optional string`. Default pyarrow columns are nullable, which fails
|
||||
# PyIceberg's required-field compatibility check.
|
||||
arrow_schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64(), nullable=False),
|
||||
pa.field("label", pa.string(), nullable=True),
|
||||
]
|
||||
)
|
||||
arrow_table = pa.Table.from_pydict(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"label": ["one", "two", "three"],
|
||||
},
|
||||
schema=arrow_schema,
|
||||
)
|
||||
table.append(arrow_table)
|
||||
print(f"appended {arrow_table.num_rows} rows to {'.'.join(table_id)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,892 @@
|
||||
// Package catalog_clickhouse provides integration tests for ClickHouse with
|
||||
// the SeaweedFS Iceberg REST Catalog.
|
||||
package catalog_clickhouse
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
const (
|
||||
clickhouseDefaultImage = "clickhouse/clickhouse-server:25.8"
|
||||
clickhouseDatabase = "iceberg_catalog"
|
||||
clickhouseHTTPPort = 8123
|
||||
clickhouseStartTimeout = 2 * time.Minute
|
||||
|
||||
// The image's passwordless `default` user only accepts connections from
|
||||
// localhost, and our queries arrive via the mapped port from the Docker
|
||||
// gateway. The entrypoint grants a CLICKHOUSE_USER/CLICKHOUSE_PASSWORD
|
||||
// user access from any host.
|
||||
clickhouseUser = "seaweed"
|
||||
clickhousePassword = "seaweedtest"
|
||||
)
|
||||
|
||||
type TestEnvironment struct {
|
||||
seaweedDir string
|
||||
weedBinary string
|
||||
dataDir string
|
||||
bindIP string
|
||||
s3Port int
|
||||
s3GrpcPort int
|
||||
icebergPort int
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
filerPort int
|
||||
filerGrpcPort int
|
||||
volumePort int
|
||||
volumeGrpcPort int
|
||||
weedProcess *exec.Cmd
|
||||
weedCancel context.CancelFunc
|
||||
clickhouseContainer string
|
||||
clickhouseHostPort int
|
||||
accessKey string
|
||||
secretKey string
|
||||
}
|
||||
|
||||
// TestClickHouseIcebergCatalog brings up SeaweedFS + ClickHouse and validates
|
||||
// that ClickHouse's DataLakeCatalog database engine can discover catalog
|
||||
// metadata served by SeaweedFS's Iceberg REST API and read both empty and
|
||||
// populated tables through the standard S3 data path.
|
||||
//
|
||||
// Subtests:
|
||||
// - BasicSelect: ClickHouse is alive and answering SQL.
|
||||
// - DatabaseVisible: the DataLakeCatalog database exists.
|
||||
// - TableVisible: seeded tables appear as `namespace.table` entries.
|
||||
// - DescribeTable: ClickHouse mapped the Iceberg schema (long -> Int64,
|
||||
// optional string -> Nullable(String)).
|
||||
// - CountEmptyTable: ClickHouse resolves the table and scans an empty
|
||||
// Iceberg snapshot.
|
||||
// - ReadWrittenDataCount / ReadWrittenDataValues: a separate table is
|
||||
// populated by a PyIceberg writer container before ClickHouse connects;
|
||||
// ClickHouse then reads the three rows back, exercising the actual data
|
||||
// path (parquet over S3), not just metadata.
|
||||
func TestClickHouseIcebergCatalog(t *testing.T) {
|
||||
requireClickHouseRuntime(t)
|
||||
|
||||
env := NewTestEnvironment(t)
|
||||
defer env.Cleanup(t)
|
||||
|
||||
fmt.Printf(">>> Starting SeaweedFS...\n")
|
||||
env.StartSeaweedFS(t)
|
||||
fmt.Printf(">>> SeaweedFS started.\n")
|
||||
|
||||
tableBucket := "iceberg-tables"
|
||||
fmt.Printf(">>> Creating table bucket: %s\n", tableBucket)
|
||||
createTableBucket(t, env, tableBucket)
|
||||
fmt.Printf(">>> Table bucket created.\n")
|
||||
|
||||
testIcebergRestAPI(t, env)
|
||||
|
||||
namespace := "clickhouse_" + randomString(6)
|
||||
tableName := "smoke_" + randomString(6)
|
||||
icebergToken := requestIcebergOAuthToken(t, env)
|
||||
createIcebergNamespace(t, env, icebergToken, tableBucket, namespace)
|
||||
createIcebergTable(t, env, icebergToken, tableBucket, namespace, tableName)
|
||||
|
||||
// Seed a populated table by creating an empty one through the REST API
|
||||
// and then appending three rows via PyIceberg, so the snapshot exists
|
||||
// before ClickHouse's first scan.
|
||||
populatedTable := "populated_" + randomString(6)
|
||||
createIcebergTable(t, env, icebergToken, tableBucket, namespace, populatedTable)
|
||||
buildClickHouseWriterImage(t)
|
||||
writeIcebergRows(t, env, tableBucket, []string{namespace}, populatedTable)
|
||||
|
||||
// Empty table that ClickHouse writes into during the WriteReadBack subtest.
|
||||
writeTable := "chwrite_" + randomString(6)
|
||||
createIcebergTable(t, env, icebergToken, tableBucket, namespace, writeTable)
|
||||
|
||||
env.startClickHouseContainer(t)
|
||||
env.waitForClickHouse(t, clickhouseStartTimeout)
|
||||
|
||||
env.createClickHouseCatalogDatabase(t, tableBucket)
|
||||
|
||||
t.Run("BasicSelect", func(t *testing.T) {
|
||||
out := env.mustQuery(t, "SELECT 1")
|
||||
if out != "1" {
|
||||
t.Fatalf("SELECT 1 = %q, want 1", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DatabaseVisible", func(t *testing.T) {
|
||||
out := env.mustQuery(t, "SHOW DATABASES")
|
||||
if !containsLine(out, clickhouseDatabase) {
|
||||
t.Fatalf("SHOW DATABASES did not list %s:\n%s", clickhouseDatabase, out)
|
||||
}
|
||||
})
|
||||
|
||||
// DataLakeCatalog flattens the Iceberg namespace hierarchy into table
|
||||
// names of the form "namespace.table", queried with backtick quoting.
|
||||
emptyRef := fmt.Sprintf("%s.`%s.%s`", clickhouseDatabase, namespace, tableName)
|
||||
populatedRef := fmt.Sprintf("%s.`%s.%s`", clickhouseDatabase, namespace, populatedTable)
|
||||
|
||||
t.Run("TableVisible", func(t *testing.T) {
|
||||
out := env.mustQuery(t, fmt.Sprintf("SHOW TABLES FROM %s", clickhouseDatabase))
|
||||
for _, want := range []string{namespace + "." + tableName, namespace + "." + populatedTable} {
|
||||
if !containsLine(out, want) {
|
||||
t.Fatalf("SHOW TABLES FROM %s did not list %s:\n%s", clickhouseDatabase, want, out)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DescribeTable", func(t *testing.T) {
|
||||
out := env.mustQuery(t, fmt.Sprintf("DESCRIBE TABLE %s", emptyRef))
|
||||
if !strings.Contains(out, "id\tInt64") {
|
||||
t.Fatalf("DESCRIBE %s missing id Int64:\n%s", emptyRef, out)
|
||||
}
|
||||
if !strings.Contains(out, "label\tNullable(String)") {
|
||||
t.Fatalf("DESCRIBE %s missing label Nullable(String):\n%s", emptyRef, out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CountEmptyTable", func(t *testing.T) {
|
||||
out := env.mustQuery(t, fmt.Sprintf("SELECT count() FROM %s", emptyRef))
|
||||
if out != "0" {
|
||||
t.Fatalf("count(%s) = %q, want 0", emptyRef, out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ReadWrittenDataCount", func(t *testing.T) {
|
||||
out := env.mustQuery(t, fmt.Sprintf("SELECT count() FROM %s", populatedRef))
|
||||
if out != "3" {
|
||||
t.Fatalf("count(%s) = %q, want 3", populatedRef, out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ReadWrittenDataValues", func(t *testing.T) {
|
||||
out := env.mustQuery(t, fmt.Sprintf("SELECT id, label FROM %s ORDER BY id", populatedRef))
|
||||
want := "1\tone\n2\ttwo\n3\tthree"
|
||||
if out != want {
|
||||
t.Fatalf("SELECT id, label FROM %s = %q, want %q", populatedRef, out, want)
|
||||
}
|
||||
})
|
||||
|
||||
// ClickHouse's experimental Iceberg writes produce manifests without avro
|
||||
// field-ids, bucket-relative paths, and parquet without field ids. The
|
||||
// catalog repairs the manifests at commit and stamps a name mapping on the
|
||||
// table, so a strict reader (PyIceberg) must see ClickHouse's rows.
|
||||
t.Run("WriteReadBack", func(t *testing.T) {
|
||||
writeRef := fmt.Sprintf("%s.`%s.%s`", clickhouseDatabase, namespace, writeTable)
|
||||
insert := fmt.Sprintf("INSERT INTO %s (id, label) VALUES (1, 'alpha'), (2, 'beta')", writeRef)
|
||||
if _, err := env.query(insert, map[string]string{"allow_experimental_insert_into_iceberg": "1"}); err != nil {
|
||||
t.Fatalf("%s: %v\nContainer logs:\n%s", insert, err, clickhouseContainerLogs(env.clickhouseContainer))
|
||||
}
|
||||
|
||||
out := env.mustQuery(t, fmt.Sprintf("SELECT id, label FROM %s ORDER BY id", writeRef))
|
||||
if want := "1\talpha\n2\tbeta"; out != want {
|
||||
t.Fatalf("ClickHouse read-back = %q, want %q", out, want)
|
||||
}
|
||||
|
||||
rows := readIcebergRows(t, env, tableBucket, []string{namespace}, writeTable)
|
||||
if want := "1,alpha\n2,beta"; rows != want {
|
||||
t.Fatalf("PyIceberg read of ClickHouse-written table = %q, want %q", rows, want)
|
||||
}
|
||||
})
|
||||
|
||||
// From 26.4 ClickHouse registers CREATE TABLE on a DataLakeCatalog database
|
||||
// with the REST catalog; older versions write storage files without a
|
||||
// catalog createTable, so the subtest skips there.
|
||||
t.Run("CreateTableViaCatalog", func(t *testing.T) {
|
||||
version := env.mustQuery(t, "SELECT version()")
|
||||
if !versionAtLeast(version, 26, 4) {
|
||||
t.Skipf("catalog CREATE TABLE requires ClickHouse 26.4+, server is %s", version)
|
||||
}
|
||||
|
||||
ddlTable := "chddl_" + randomString(6)
|
||||
ddlRef := fmt.Sprintf("%s.`%s.%s`", clickhouseDatabase, namespace, ddlTable)
|
||||
location := fmt.Sprintf("http://host.docker.internal:%d/%s/%s/%s/", env.s3Port, tableBucket, namespace, ddlTable)
|
||||
create := fmt.Sprintf("CREATE TABLE %s (id Int64, label Nullable(String)) ENGINE = IcebergS3('%s', '%s', '%s')",
|
||||
ddlRef, location, env.accessKey, env.secretKey)
|
||||
if _, err := env.query(create, map[string]string{
|
||||
"allow_experimental_database_iceberg": "1",
|
||||
// Without this ClickHouse registers a bare "/namespace/table"
|
||||
// location, which the catalog rejects.
|
||||
"write_full_path_in_iceberg_metadata": "1",
|
||||
}); err != nil {
|
||||
t.Fatalf("%s: %v\nContainer logs:\n%s", create, err, clickhouseContainerLogs(env.clickhouseContainer))
|
||||
}
|
||||
|
||||
// The table must exist in the catalog itself, not just in ClickHouse.
|
||||
token := requestIcebergOAuthToken(t, env)
|
||||
listing := doIcebergJSONRequest(t, env, token, http.MethodGet,
|
||||
fmt.Sprintf("/v1/%s/namespaces/%s/tables", url.PathEscape(tableBucket), url.PathEscape(namespace)),
|
||||
nil, http.StatusOK)
|
||||
var tables struct {
|
||||
Identifiers []struct {
|
||||
Namespace []string `json:"namespace"`
|
||||
Name string `json:"name"`
|
||||
} `json:"identifiers"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(listing), &tables); err != nil {
|
||||
t.Fatalf("decode catalog table listing: %v\n%s", err, listing)
|
||||
}
|
||||
registered := false
|
||||
for _, id := range tables.Identifiers {
|
||||
if id.Name == ddlTable && len(id.Namespace) == 1 && id.Namespace[0] == namespace {
|
||||
registered = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !registered {
|
||||
t.Fatalf("catalog table listing is missing %s: %s", ddlTable, listing)
|
||||
}
|
||||
|
||||
insert := fmt.Sprintf("INSERT INTO %s (id, label) VALUES (1, 'alpha'), (2, 'beta')", ddlRef)
|
||||
if _, err := env.query(insert, map[string]string{"allow_experimental_insert_into_iceberg": "1"}); err != nil {
|
||||
t.Fatalf("%s: %v\nContainer logs:\n%s", insert, err, clickhouseContainerLogs(env.clickhouseContainer))
|
||||
}
|
||||
|
||||
out := env.mustQuery(t, fmt.Sprintf("SELECT id, label FROM %s ORDER BY id", ddlRef))
|
||||
if want := "1\talpha\n2\tbeta"; out != want {
|
||||
t.Fatalf("ClickHouse read-back = %q, want %q", out, want)
|
||||
}
|
||||
|
||||
rows := readIcebergRows(t, env, tableBucket, []string{namespace}, ddlTable)
|
||||
if want := "1,alpha\n2,beta"; rows != want {
|
||||
t.Fatalf("PyIceberg read of ClickHouse-created table = %q, want %q", rows, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestVersionAtLeast exercises the gate that decides whether the catalog DDL
|
||||
// subtest runs.
|
||||
func TestVersionAtLeast(t *testing.T) {
|
||||
cases := []struct {
|
||||
version string
|
||||
major, minor int
|
||||
want bool
|
||||
}{
|
||||
{"26.7.3.19", 26, 4, true},
|
||||
{"26.4.5.143", 26, 4, true},
|
||||
{"26.3.17.110", 26, 4, false},
|
||||
{"25.8.29.51", 26, 4, false},
|
||||
{"27.1.1.1", 26, 4, true},
|
||||
{"weird", 26, 4, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := versionAtLeast(c.version, c.major, c.minor); got != c.want {
|
||||
t.Errorf("versionAtLeast(%q, %d, %d) = %v, want %v", c.version, c.major, c.minor, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NewTestEnvironment allocates ports and returns an environment for the test.
|
||||
func NewTestEnvironment(t *testing.T) *TestEnvironment {
|
||||
t.Helper()
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get working directory: %v", err)
|
||||
}
|
||||
|
||||
seaweedDir := wd
|
||||
for i := 0; i < 6; i++ {
|
||||
if _, err := os.Stat(filepath.Join(seaweedDir, "go.mod")); err == nil {
|
||||
break
|
||||
}
|
||||
seaweedDir = filepath.Dir(seaweedDir)
|
||||
}
|
||||
|
||||
weedBinary := filepath.Join(seaweedDir, "weed", "weed")
|
||||
info, err := os.Stat(weedBinary)
|
||||
if err != nil || info.IsDir() {
|
||||
weedBinary = filepath.Join(seaweedDir, "weed", "weed", "weed")
|
||||
info, err = os.Stat(weedBinary)
|
||||
if err != nil || info.IsDir() {
|
||||
weedBinary = "weed"
|
||||
if _, err := exec.LookPath(weedBinary); err != nil {
|
||||
t.Skip("weed binary not found, skipping integration test")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dataDir, err := os.MkdirTemp("", "seaweed-clickhouse-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
|
||||
bindIP := testutil.FindBindIP()
|
||||
// 9 ports for the seaweed mini cluster, plus one for the ClickHouse HTTP
|
||||
// interface mapped on the host.
|
||||
ports := testutil.MustAllocatePorts(t, 10)
|
||||
|
||||
env := &TestEnvironment{
|
||||
seaweedDir: seaweedDir,
|
||||
weedBinary: weedBinary,
|
||||
dataDir: dataDir,
|
||||
bindIP: bindIP,
|
||||
masterPort: ports[0],
|
||||
masterGrpcPort: ports[1],
|
||||
volumePort: ports[2],
|
||||
volumeGrpcPort: ports[3],
|
||||
filerPort: ports[4],
|
||||
filerGrpcPort: ports[5],
|
||||
s3Port: ports[6],
|
||||
s3GrpcPort: ports[7],
|
||||
icebergPort: ports[8],
|
||||
clickhouseHostPort: ports[9],
|
||||
}
|
||||
|
||||
env.accessKey = "AKIAIOSFODNN7EXAMPLE"
|
||||
env.secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
|
||||
|
||||
return env
|
||||
}
|
||||
|
||||
// StartSeaweedFS starts a SeaweedFS mini instance with the Iceberg REST API.
|
||||
func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
iamConfigPath, err := testutil.WriteIAMConfig(env.dataDir, env.accessKey, env.secretKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create IAM config: %v", err)
|
||||
}
|
||||
|
||||
securityToml := filepath.Join(env.dataDir, "security.toml")
|
||||
if err := os.WriteFile(securityToml, []byte("# Empty security config for testing\n"), 0644); err != nil {
|
||||
t.Fatalf("Failed to create security.toml: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
env.weedCancel = cancel
|
||||
|
||||
cmd := exec.CommandContext(ctx, env.weedBinary, "mini",
|
||||
"-master.port", fmt.Sprintf("%d", env.masterPort),
|
||||
"-master.port.grpc", fmt.Sprintf("%d", env.masterGrpcPort),
|
||||
"-volume.port", fmt.Sprintf("%d", env.volumePort),
|
||||
"-volume.port.grpc", fmt.Sprintf("%d", env.volumeGrpcPort),
|
||||
"-filer.port", fmt.Sprintf("%d", env.filerPort),
|
||||
"-filer.port.grpc", fmt.Sprintf("%d", env.filerGrpcPort),
|
||||
"-s3.port", fmt.Sprintf("%d", env.s3Port),
|
||||
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
|
||||
"-s3.port.iceberg", fmt.Sprintf("%d", env.icebergPort),
|
||||
"-s3.config", iamConfigPath,
|
||||
"-ip", env.bindIP,
|
||||
"-ip.bind", "0.0.0.0",
|
||||
"-dir", env.dataDir,
|
||||
)
|
||||
cmd.Dir = env.dataDir
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
cmd.Env = append(os.Environ(),
|
||||
"AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
"ICEBERG_WAREHOUSE=s3://iceberg-tables",
|
||||
"S3TABLES_DEFAULT_BUCKET=iceberg-tables",
|
||||
)
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("Failed to start SeaweedFS: %v", err)
|
||||
}
|
||||
env.weedProcess = cmd
|
||||
|
||||
icebergURL := fmt.Sprintf("http://%s:%d/v1/config", env.bindIP, env.icebergPort)
|
||||
if !env.waitForService(icebergURL, 30*time.Second) {
|
||||
t.Fatalf("Iceberg REST API did not become ready at %s", icebergURL)
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup stops ClickHouse, SeaweedFS, and removes temporary state.
|
||||
func (env *TestEnvironment) Cleanup(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if env.clickhouseContainer != "" {
|
||||
_ = exec.Command("docker", "rm", "-f", env.clickhouseContainer).Run()
|
||||
}
|
||||
|
||||
if env.weedCancel != nil {
|
||||
env.weedCancel()
|
||||
}
|
||||
|
||||
if env.weedProcess != nil {
|
||||
time.Sleep(2 * time.Second)
|
||||
_ = env.weedProcess.Wait()
|
||||
}
|
||||
|
||||
if env.dataDir != "" {
|
||||
_ = os.RemoveAll(env.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
// waitForService polls a URL until it returns a 2xx/401/403 status or timeout.
|
||||
func (env *TestEnvironment) waitForService(url string, timeout time.Duration) bool {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
statusCode := resp.StatusCode
|
||||
resp.Body.Close()
|
||||
if statusCode >= 200 && statusCode < 300 {
|
||||
return true
|
||||
}
|
||||
if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden {
|
||||
return true
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// testIcebergRestAPI verifies the Iceberg REST endpoint is reachable.
|
||||
func testIcebergRestAPI(t *testing.T, env *TestEnvironment) {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/v1/config", env.bindIP, env.icebergPort)
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to connect to Iceberg REST API at %s: %v", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Expected 200 OK from /v1/config, got %d, body: %s", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
// startClickHouseContainer launches the ClickHouse server image and exposes
|
||||
// only the HTTP interface to the host. The Iceberg REST and S3 endpoints are
|
||||
// reached via host.docker.internal, matching the Doris/Trino paths.
|
||||
func (env *TestEnvironment) startClickHouseContainer(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
containerName := "seaweed-clickhouse-" + randomString(8)
|
||||
env.clickhouseContainer = containerName
|
||||
|
||||
cmd := exec.Command("docker", "run", "-d",
|
||||
"--name", containerName,
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-p", fmt.Sprintf("%d:%d", env.clickhouseHostPort, clickhouseHTTPPort),
|
||||
"--ulimit", "nofile=262144:262144",
|
||||
"-e", "CLICKHOUSE_USER="+clickhouseUser,
|
||||
"-e", "CLICKHOUSE_PASSWORD="+clickhousePassword,
|
||||
clickhouseImage(),
|
||||
)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to start ClickHouse container: %v\n%s", err, string(output))
|
||||
}
|
||||
}
|
||||
|
||||
// clickhouseImage returns the server image under test. CI overrides it via
|
||||
// CLICKHOUSE_IMAGE to also run the suite against latest, so new ClickHouse
|
||||
// releases are exercised without a code change.
|
||||
func clickhouseImage() string {
|
||||
if img := os.Getenv("CLICKHOUSE_IMAGE"); img != "" {
|
||||
return img
|
||||
}
|
||||
return clickhouseDefaultImage
|
||||
}
|
||||
|
||||
// versionAtLeast reports whether a "major.minor.*" version string is at least
|
||||
// major.minor.
|
||||
func versionAtLeast(version string, major, minor int) bool {
|
||||
parts := strings.Split(strings.TrimSpace(version), ".")
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
gotMajor, errMajor := strconv.Atoi(parts[0])
|
||||
gotMinor, errMinor := strconv.Atoi(parts[1])
|
||||
if errMajor != nil || errMinor != nil {
|
||||
return false
|
||||
}
|
||||
return gotMajor > major || (gotMajor == major && gotMinor >= minor)
|
||||
}
|
||||
|
||||
// clickhouseContainerLogs returns the tail of the container logs for diagnostics.
|
||||
func clickhouseContainerLogs(containerName string) string {
|
||||
cmd := exec.Command("docker", "logs", "--tail", "200", containerName)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Sprintf("(failed to fetch docker logs: %v)\n%s", err, string(output))
|
||||
}
|
||||
return string(output)
|
||||
}
|
||||
|
||||
// containerRunning returns true if the named container is in `running` state.
|
||||
func containerRunning(containerName string) bool {
|
||||
cmd := exec.Command("docker", "inspect", "--format", "{{.State.Running}}", containerName)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(string(out)) == "true"
|
||||
}
|
||||
|
||||
// waitForClickHouse polls the HTTP /ping endpoint until it answers.
|
||||
func (env *TestEnvironment) waitForClickHouse(t *testing.T, timeout time.Duration) {
|
||||
t.Helper()
|
||||
|
||||
pingURL := fmt.Sprintf("http://127.0.0.1:%d/ping", env.clickhouseHostPort)
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if !containerRunning(env.clickhouseContainer) {
|
||||
t.Fatalf("ClickHouse container exited before becoming ready\nContainer logs:\n%s",
|
||||
clickhouseContainerLogs(env.clickhouseContainer))
|
||||
}
|
||||
resp, err := client.Get(pingURL)
|
||||
if err == nil {
|
||||
statusCode := resp.StatusCode
|
||||
resp.Body.Close()
|
||||
if statusCode == http.StatusOK {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
t.Fatalf("Timed out waiting for ClickHouse to be ready\nContainer logs:\n%s",
|
||||
clickhouseContainerLogs(env.clickhouseContainer))
|
||||
}
|
||||
|
||||
// query sends one SQL statement to ClickHouse's HTTP interface as the default
|
||||
// user and returns the TabSeparated response body with trailing whitespace
|
||||
// trimmed. Settings ride along as URL parameters because SET does not persist
|
||||
// across stateless HTTP requests.
|
||||
func (env *TestEnvironment) query(sqlText string, settings map[string]string) (string, error) {
|
||||
params := url.Values{}
|
||||
params.Set("user", clickhouseUser)
|
||||
params.Set("password", clickhousePassword)
|
||||
params.Set("default_format", "TabSeparated")
|
||||
for k, v := range settings {
|
||||
params.Set(k, v)
|
||||
}
|
||||
queryURL := fmt.Sprintf("http://127.0.0.1:%d/?%s", env.clickhouseHostPort, params.Encode())
|
||||
|
||||
client := &http.Client{Timeout: 120 * time.Second}
|
||||
resp, err := client.Post(queryURL, "text/plain", strings.NewReader(sqlText))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("POST query: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("query returned status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
return strings.TrimRight(string(body), "\n"), nil
|
||||
}
|
||||
|
||||
// mustQuery runs a query and fails the test with container logs on error.
|
||||
func (env *TestEnvironment) mustQuery(t *testing.T, sqlText string) string {
|
||||
t.Helper()
|
||||
|
||||
out, err := env.query(sqlText, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v\nContainer logs:\n%s", sqlText, err, clickhouseContainerLogs(env.clickhouseContainer))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// createClickHouseCatalogDatabase attaches the SeaweedFS Iceberg REST catalog
|
||||
// as a DataLakeCatalog database. The engine arguments carry the S3 storage
|
||||
// credentials; catalog authentication uses the OAuth2 client_credentials flow
|
||||
// against the SeaweedFS token endpoint, matching the PyIceberg writer.
|
||||
func (env *TestEnvironment) createClickHouseCatalogDatabase(t *testing.T, warehouseBucket string) {
|
||||
t.Helper()
|
||||
|
||||
icebergURI := fmt.Sprintf("http://host.docker.internal:%d/v1", env.icebergPort)
|
||||
storageEndpoint := fmt.Sprintf("http://host.docker.internal:%d/%s", env.s3Port, warehouseBucket)
|
||||
oauthURI := icebergURI + "/oauth/tokens"
|
||||
|
||||
createSQL := fmt.Sprintf(`CREATE DATABASE %s
|
||||
ENGINE = DataLakeCatalog('%s', '%s', '%s')
|
||||
SETTINGS catalog_type = 'rest',
|
||||
warehouse = 's3://%s',
|
||||
storage_endpoint = '%s',
|
||||
catalog_credential = '%s:%s',
|
||||
oauth_server_uri = '%s'`,
|
||||
clickhouseDatabase,
|
||||
icebergURI, env.accessKey, env.secretKey,
|
||||
warehouseBucket,
|
||||
storageEndpoint,
|
||||
env.accessKey, env.secretKey,
|
||||
oauthURI,
|
||||
)
|
||||
|
||||
if _, err := env.query(createSQL, map[string]string{"allow_experimental_database_iceberg": "1"}); err != nil {
|
||||
t.Fatalf("CREATE DATABASE %s failed: %v\nContainer logs:\n%s",
|
||||
clickhouseDatabase, err, clickhouseContainerLogs(env.clickhouseContainer))
|
||||
}
|
||||
}
|
||||
|
||||
// containsLine reports whether any line of a TabSeparated result equals want.
|
||||
func containsLine(out, want string) bool {
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if strings.TrimSpace(line) == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// requestIcebergOAuthToken requests an OAuth2 client_credentials token from
|
||||
// the SeaweedFS Iceberg REST catalog. Used to seed the catalog with a
|
||||
// namespace and tables directly through the REST API before ClickHouse connects.
|
||||
func requestIcebergOAuthToken(t *testing.T, env *TestEnvironment) string {
|
||||
t.Helper()
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.PostForm(fmt.Sprintf("http://%s:%d/v1/oauth/tokens", env.bindIP, env.icebergPort), url.Values{
|
||||
"grant_type": {"client_credentials"},
|
||||
"client_id": {env.accessKey},
|
||||
"client_secret": {env.secretKey},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("POST /v1/oauth/tokens: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("OAuth token request failed: status=%d body=%s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var tokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &tokenResp); err != nil {
|
||||
t.Fatalf("decode token response: %v", err)
|
||||
}
|
||||
if tokenResp.AccessToken == "" {
|
||||
t.Fatal("got empty access_token")
|
||||
}
|
||||
return tokenResp.AccessToken
|
||||
}
|
||||
|
||||
// createIcebergNamespace creates a single-level Iceberg namespace through
|
||||
// the REST catalog.
|
||||
func createIcebergNamespace(t *testing.T, env *TestEnvironment, token, bucketName, namespace string) {
|
||||
t.Helper()
|
||||
|
||||
doIcebergJSONRequest(t, env, token, http.MethodPost, fmt.Sprintf("/v1/%s/namespaces", url.PathEscape(bucketName)), map[string]any{
|
||||
"namespace": []string{namespace},
|
||||
}, http.StatusOK, http.StatusConflict)
|
||||
}
|
||||
|
||||
// createIcebergTable creates a table inside a single-level namespace through
|
||||
// the REST catalog. The table is created with the canonical
|
||||
// (id long not null, label string nullable) schema used by all subtests.
|
||||
func createIcebergTable(t *testing.T, env *TestEnvironment, token, bucketName, namespace, tableName string) {
|
||||
t.Helper()
|
||||
|
||||
doIcebergJSONRequest(t, env, token, http.MethodPost,
|
||||
fmt.Sprintf("/v1/%s/namespaces/%s/tables", url.PathEscape(bucketName), url.PathEscape(namespace)),
|
||||
map[string]any{
|
||||
"name": tableName,
|
||||
"schema": map[string]any{
|
||||
"type": "struct",
|
||||
"schema-id": 0,
|
||||
"fields": []map[string]any{
|
||||
{"id": 1, "name": "id", "required": true, "type": "long"},
|
||||
{"id": 2, "name": "label", "required": false, "type": "string"},
|
||||
},
|
||||
},
|
||||
}, http.StatusOK)
|
||||
}
|
||||
|
||||
const clickhouseWriterImage = "seaweedfs-clickhouse-writer"
|
||||
|
||||
// buildClickHouseWriterImage builds the local PyIceberg writer image. Layer
|
||||
// caching makes repeat invocations cheap; the first build pulls
|
||||
// python:3.11-slim and pip-installs pyiceberg+pyarrow (~1-2 min in CI).
|
||||
func buildClickHouseWriterImage(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get working directory: %v", err)
|
||||
}
|
||||
|
||||
cmd := exec.Command("docker", "build",
|
||||
"-t", clickhouseWriterImage,
|
||||
"-f", filepath.Join(wd, "Dockerfile.writer"),
|
||||
wd,
|
||||
)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to build %s image: %v\n%s", clickhouseWriterImage, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// writeIcebergRows runs the PyIceberg writer container, which loads the
|
||||
// already-created table and appends three rows.
|
||||
func writeIcebergRows(t *testing.T, env *TestEnvironment, bucketName string, namespace []string, tableName string) {
|
||||
t.Helper()
|
||||
|
||||
args := []string{
|
||||
"run", "--rm",
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
clickhouseWriterImage,
|
||||
"--catalog-url", fmt.Sprintf("http://host.docker.internal:%d", env.icebergPort),
|
||||
"--warehouse", "s3://" + bucketName,
|
||||
"--prefix", bucketName,
|
||||
"--s3-endpoint", fmt.Sprintf("http://host.docker.internal:%d", env.s3Port),
|
||||
"--access-key", env.accessKey,
|
||||
"--secret-key", env.secretKey,
|
||||
"--region", "us-west-2",
|
||||
"--table", tableName,
|
||||
}
|
||||
for _, level := range namespace {
|
||||
args = append(args, "--namespace", level)
|
||||
}
|
||||
|
||||
cmd := exec.Command("docker", args...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("PyIceberg writer failed: %v\n%s", err, out)
|
||||
}
|
||||
t.Logf("PyIceberg writer output: %s", strings.TrimSpace(string(out)))
|
||||
}
|
||||
|
||||
// readIcebergRows scans a table with PyIceberg through the REST catalog and
|
||||
// returns its "id,label" lines, ordered by id.
|
||||
func readIcebergRows(t *testing.T, env *TestEnvironment, bucketName string, namespace []string, tableName string) string {
|
||||
t.Helper()
|
||||
|
||||
args := []string{
|
||||
"run", "--rm",
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"--entrypoint", "python3",
|
||||
clickhouseWriterImage,
|
||||
"/app/read_rows.py",
|
||||
"--catalog-url", fmt.Sprintf("http://host.docker.internal:%d", env.icebergPort),
|
||||
"--warehouse", "s3://" + bucketName,
|
||||
"--prefix", bucketName,
|
||||
"--s3-endpoint", fmt.Sprintf("http://host.docker.internal:%d", env.s3Port),
|
||||
"--access-key", env.accessKey,
|
||||
"--secret-key", env.secretKey,
|
||||
"--region", "us-west-2",
|
||||
"--table", tableName,
|
||||
}
|
||||
for _, level := range namespace {
|
||||
args = append(args, "--namespace", level)
|
||||
}
|
||||
|
||||
// Keep stdout separate: the caller compares it exactly, and warnings on
|
||||
// stderr from the python stack must not pollute the row data.
|
||||
cmd := exec.Command("docker", args...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("PyIceberg reader failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
return strings.TrimSpace(stdout.String())
|
||||
}
|
||||
|
||||
// doIcebergJSONRequest issues an authenticated JSON request to the Iceberg
|
||||
// REST endpoint and returns the response body. It fails the test unless the
|
||||
// response status matches one of expectedStatuses.
|
||||
func doIcebergJSONRequest(t *testing.T, env *TestEnvironment, token, method, path string, payload any, expectedStatuses ...int) string {
|
||||
t.Helper()
|
||||
|
||||
var body io.Reader
|
||||
if payload != nil {
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal Iceberg request: %v", err)
|
||||
}
|
||||
body = bytes.NewReader(payloadBytes)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d%s", env.bindIP, env.icebergPort, path), body)
|
||||
if err != nil {
|
||||
t.Fatalf("create Iceberg request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Iceberg request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
for _, expectedStatus := range expectedStatuses {
|
||||
if resp.StatusCode == expectedStatus {
|
||||
return string(respBody)
|
||||
}
|
||||
}
|
||||
t.Fatalf("Iceberg request returned unexpected status %d, want %v\nPath: %s\nBody: %s",
|
||||
resp.StatusCode, expectedStatuses, path, respBody)
|
||||
return ""
|
||||
}
|
||||
|
||||
// createTableBucket creates an S3 table bucket using `weed shell`, which
|
||||
// talks to the master over gRPC and bypasses the S3 SigV4 path. The `-master`
|
||||
// flag uses SeaweedFS's canonical `host:port.grpcPort` ServerAddress format
|
||||
// produced by pb.NewServerAddress — the dot separates the HTTP port from the
|
||||
// gRPC port and is required, not a typo.
|
||||
func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Helper()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, env.weedBinary, "shell",
|
||||
fmt.Sprintf("-master=%s:%d.%d", env.bindIP, env.masterPort, env.masterGrpcPort),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("s3tables.bucket -create -name %s -account 000000000000\nexit\n", bucketName))
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create table bucket %s via weed shell: %v\nOutput: %s", bucketName, err, string(output))
|
||||
}
|
||||
t.Logf("Created table bucket: %s", bucketName)
|
||||
}
|
||||
|
||||
// requireClickHouseRuntime skips the test in `-short` mode or when Docker
|
||||
// isn't available, since the test cannot run without the ClickHouse container.
|
||||
func requireClickHouseRuntime(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
if !hasDocker() {
|
||||
t.Skip("Docker not available, skipping ClickHouse integration test")
|
||||
}
|
||||
}
|
||||
|
||||
// hasDocker reports whether `docker version` can run, which we treat as a
|
||||
// sufficient signal that a Docker daemon is reachable from this process.
|
||||
func hasDocker() bool {
|
||||
cmd := exec.Command("docker", "version")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
// randomString returns a lowercase alphanumeric string of the given length.
|
||||
func randomString(length int) string {
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, length)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic("failed to generate random string: " + err.Error())
|
||||
}
|
||||
for i := range b {
|
||||
b[i] = charset[int(b[i])%len(charset)]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read all rows of an Iceberg table via the SeaweedFS REST catalog.
|
||||
|
||||
Used by the ClickHouse integration test to prove that rows written by
|
||||
ClickHouse are readable by another engine: PyIceberg is a strict reader that
|
||||
requires spec-compliant manifests and either parquet field ids or a name
|
||||
mapping. Prints one "id,label" line per row, ordered by id.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from pyiceberg.catalog import load_catalog
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--catalog-url", required=True)
|
||||
p.add_argument("--warehouse", required=True)
|
||||
p.add_argument("--prefix", required=True)
|
||||
p.add_argument("--s3-endpoint", required=True)
|
||||
p.add_argument("--access-key", required=True)
|
||||
p.add_argument("--secret-key", required=True)
|
||||
p.add_argument("--region", default="us-east-1")
|
||||
p.add_argument("--namespace", action="append", required=True)
|
||||
p.add_argument("--table", required=True)
|
||||
args = p.parse_args()
|
||||
|
||||
catalog = load_catalog(
|
||||
"rest",
|
||||
**{
|
||||
"type": "rest",
|
||||
"uri": args.catalog_url,
|
||||
"warehouse": args.warehouse,
|
||||
"prefix": args.prefix,
|
||||
"credential": f"{args.access_key}:{args.secret_key}",
|
||||
"s3.access-key-id": args.access_key,
|
||||
"s3.secret-access-key": args.secret_key,
|
||||
"s3.endpoint": args.s3_endpoint,
|
||||
"s3.region": args.region,
|
||||
"s3.path-style-access": "true",
|
||||
},
|
||||
)
|
||||
|
||||
table = catalog.load_table(tuple(args.namespace) + (args.table,))
|
||||
data = table.scan().to_arrow().to_pydict()
|
||||
rows = sorted(zip(data["id"], data["label"]))
|
||||
for row_id, label in rows:
|
||||
print(f"{row_id},{label}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -600,9 +600,9 @@ func testExpireSnapshots(t *testing.T) {
|
||||
|
||||
handler := icebergHandler.NewHandler(nil)
|
||||
config := icebergHandler.Config{
|
||||
SnapshotRetentionHours: 0, // instant expiry — everything eligible
|
||||
MaxSnapshotsToKeep: 1, // keep only the current snapshot
|
||||
MaxCommitRetries: 3,
|
||||
SnapshotRetentionMs: 0, // instant expiry — everything eligible
|
||||
MaxSnapshotsToKeep: 1, // keep only the current snapshot
|
||||
MaxCommitRetries: 3,
|
||||
}
|
||||
|
||||
result, _, err := handler.ExpireSnapshots(context.Background(), client, bucket, path.Join(ns, tbl), config)
|
||||
@@ -796,7 +796,7 @@ func testCompactDataFiles(t *testing.T) {
|
||||
}
|
||||
|
||||
require.Len(t, addedPaths, 1, "compaction should add exactly one merged parquet file")
|
||||
assert.Contains(t, addedPaths, path.Join("data", compacted.Name))
|
||||
assert.Contains(t, addedPaths, fmt.Sprintf("s3://%s/%s/data/%s", bucket, tablePath, compacted.Name))
|
||||
require.Len(t, deletedPaths, len(files), "compaction should delete every original small input file")
|
||||
for _, file := range files {
|
||||
assert.Contains(t, deletedPaths, path.Join("data", file.name))
|
||||
@@ -932,9 +932,9 @@ func testFullMaintenanceCycle(t *testing.T) {
|
||||
|
||||
// Step 1: Expire snapshots
|
||||
expireConfig := icebergHandler.Config{
|
||||
SnapshotRetentionHours: 0, // instant expiry
|
||||
MaxSnapshotsToKeep: 1,
|
||||
MaxCommitRetries: 3,
|
||||
SnapshotRetentionMs: 0, // instant expiry
|
||||
MaxSnapshotsToKeep: 1,
|
||||
MaxCommitRetries: 3,
|
||||
}
|
||||
result, _, err := handler.ExpireSnapshots(ctx, client, bucket, tablePath, expireConfig)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -685,6 +685,135 @@ func TestTusCreationWithUpload(t *testing.T) {
|
||||
assert.Equal(t, testData, body)
|
||||
}
|
||||
|
||||
// TestTusConcatenation tests the concatenation extension: partial uploads
|
||||
// assembled into a final upload
|
||||
func TestTusConcatenation(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startTestCluster(t, ctx)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
cluster.Stop()
|
||||
os.RemoveAll(cluster.dataDir)
|
||||
}()
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
// The extension is announced
|
||||
optionsReq, err := http.NewRequest(http.MethodOptions, cluster.TusURL()+"/", nil)
|
||||
require.NoError(t, err)
|
||||
optionsReq.Header.Set("Tus-Resumable", TusVersion)
|
||||
optionsResp, err := client.Do(optionsReq)
|
||||
require.NoError(t, err)
|
||||
optionsResp.Body.Close()
|
||||
assert.Contains(t, optionsResp.Header.Get("Tus-Extension"), "concatenation")
|
||||
|
||||
partA := []byte("Hello, ")
|
||||
partB := []byte("concatenated TUS world!")
|
||||
targetPath := "/concat/final.txt"
|
||||
|
||||
createPartial := func(size int) string {
|
||||
req, err := http.NewRequest(http.MethodPost, cluster.TusURL()+targetPath, nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Tus-Resumable", TusVersion)
|
||||
req.Header.Set("Upload-Length", strconv.Itoa(size))
|
||||
req.Header.Set("Upload-Concat", "partial")
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
require.Equal(t, http.StatusCreated, resp.StatusCode)
|
||||
location := resp.Header.Get("Location")
|
||||
require.NotEmpty(t, location)
|
||||
return location
|
||||
}
|
||||
|
||||
patchAll := func(location string, data []byte) {
|
||||
req, err := http.NewRequest(http.MethodPatch, cluster.FullURL(location), bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Tus-Resumable", TusVersion)
|
||||
req.Header.Set("Upload-Offset", "0")
|
||||
req.Header.Set("Content-Type", "application/offset+octet-stream")
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
resp.Body.Close()
|
||||
require.Equal(t, http.StatusNoContent, resp.StatusCode)
|
||||
}
|
||||
|
||||
locationA := createPartial(len(partA))
|
||||
locationB := createPartial(len(partB))
|
||||
concatHeader := "final;" + locationA + " " + locationB
|
||||
|
||||
patchAll(locationA, partA)
|
||||
|
||||
// Concatenation is rejected while a listed partial is unfinished
|
||||
prematureReq, err := http.NewRequest(http.MethodPost, cluster.TusURL()+targetPath, nil)
|
||||
require.NoError(t, err)
|
||||
prematureReq.Header.Set("Tus-Resumable", TusVersion)
|
||||
prematureReq.Header.Set("Upload-Concat", concatHeader)
|
||||
prematureResp, err := client.Do(prematureReq)
|
||||
require.NoError(t, err)
|
||||
prematureResp.Body.Close()
|
||||
require.Equal(t, http.StatusBadRequest, prematureResp.StatusCode)
|
||||
|
||||
patchAll(locationB, partB)
|
||||
|
||||
// A completed partial reports its status and does not land at the target
|
||||
headReq, err := http.NewRequest(http.MethodHead, cluster.FullURL(locationA), nil)
|
||||
require.NoError(t, err)
|
||||
headReq.Header.Set("Tus-Resumable", TusVersion)
|
||||
headResp, err := client.Do(headReq)
|
||||
require.NoError(t, err)
|
||||
headResp.Body.Close()
|
||||
require.Equal(t, http.StatusOK, headResp.StatusCode)
|
||||
assert.Equal(t, "partial", headResp.Header.Get("Upload-Concat"))
|
||||
|
||||
getResp, err := client.Get(cluster.FilerURL() + targetPath)
|
||||
require.NoError(t, err)
|
||||
getResp.Body.Close()
|
||||
require.Equal(t, http.StatusNotFound, getResp.StatusCode,
|
||||
"completed partials should not land at the target path")
|
||||
|
||||
// Concatenate into the final upload
|
||||
finalReq, err := http.NewRequest(http.MethodPost, cluster.TusURL()+targetPath, nil)
|
||||
require.NoError(t, err)
|
||||
finalReq.Header.Set("Tus-Resumable", TusVersion)
|
||||
finalReq.Header.Set("Upload-Concat", concatHeader)
|
||||
finalReq.Header.Set("Upload-Metadata", encodeTusMetadata(map[string]string{
|
||||
"content-type": "text/plain",
|
||||
}))
|
||||
finalResp, err := client.Do(finalReq)
|
||||
require.NoError(t, err)
|
||||
finalResp.Body.Close()
|
||||
require.Equal(t, http.StatusCreated, finalResp.StatusCode)
|
||||
assert.NotEmpty(t, finalResp.Header.Get("Location"))
|
||||
|
||||
// The target file holds both parts in order
|
||||
expected := append(append([]byte{}, partA...), partB...)
|
||||
getResp2, err := client.Get(cluster.FilerURL() + targetPath)
|
||||
require.NoError(t, err)
|
||||
defer getResp2.Body.Close()
|
||||
require.Equal(t, http.StatusOK, getResp2.StatusCode)
|
||||
body, err := io.ReadAll(getResp2.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expected, body, "Concatenated file should hold both parts in order")
|
||||
assert.Contains(t, getResp2.Header.Get("Content-Type"), "text/plain")
|
||||
|
||||
// The consumed partials are gone
|
||||
headReq2, err := http.NewRequest(http.MethodHead, cluster.FullURL(locationA), nil)
|
||||
require.NoError(t, err)
|
||||
headReq2.Header.Set("Tus-Resumable", TusVersion)
|
||||
headResp2, err := client.Do(headReq2)
|
||||
require.NoError(t, err)
|
||||
headResp2.Body.Close()
|
||||
require.Equal(t, http.StatusNotFound, headResp2.StatusCode,
|
||||
"consumed partial should be removed after concatenation")
|
||||
}
|
||||
|
||||
// TestTusResumeAfterInterruption simulates resuming an upload after failure
|
||||
func TestTusResumeAfterInterruption(t *testing.T) {
|
||||
if testing.Short() {
|
||||
|
||||
@@ -315,10 +315,15 @@ func TestVacuumIntegration(t *testing.T) {
|
||||
}
|
||||
commandEnv := shell.NewCommandEnv(options)
|
||||
|
||||
shellCtx, shellCancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
// The session context outlives the vacuum command: a deadline here
|
||||
// closes the master connection mid-command on a slow runner, and the
|
||||
// leaked lock renewal then spins until the test binary's timeout.
|
||||
shellCtx, shellCancel := context.WithCancel(context.Background())
|
||||
defer shellCancel()
|
||||
go commandEnv.MasterClient.KeepConnectedToMaster(shellCtx)
|
||||
commandEnv.MasterClient.WaitUntilConnected(shellCtx)
|
||||
connectCtx, connectCancel := context.WithTimeout(shellCtx, 30*time.Second)
|
||||
commandEnv.MasterClient.WaitUntilConnected(connectCtx)
|
||||
connectCancel()
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Acquire lock (required by shell commands)
|
||||
|
||||
@@ -90,7 +90,7 @@ func TestCopyFileIgnoreNotFoundAndStopOffsetZeroPaths(t *testing.T) {
|
||||
|
||||
missingNoIgnore, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".definitely-missing",
|
||||
Ext: ".missing",
|
||||
CompactionRevision: math.MaxUint32,
|
||||
StopOffset: 1,
|
||||
IgnoreSourceFileNotFound: false,
|
||||
@@ -104,7 +104,7 @@ func TestCopyFileIgnoreNotFoundAndStopOffsetZeroPaths(t *testing.T) {
|
||||
|
||||
missingIgnored, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".definitely-missing",
|
||||
Ext: ".missing",
|
||||
CompactionRevision: math.MaxUint32,
|
||||
StopOffset: 1,
|
||||
IgnoreSourceFileNotFound: true,
|
||||
@@ -119,7 +119,7 @@ func TestCopyFileIgnoreNotFoundAndStopOffsetZeroPaths(t *testing.T) {
|
||||
|
||||
stopZeroStream, err := grpcClient.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".definitely-missing",
|
||||
Ext: ".missing",
|
||||
CompactionRevision: math.MaxUint32,
|
||||
StopOffset: 0,
|
||||
IgnoreSourceFileNotFound: false,
|
||||
|
||||
@@ -352,6 +352,21 @@ func TestConcurrentReaders(t *testing.T) {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
|
||||
// WriteFile's own existence probe ran while the file did not exist, and
|
||||
// WinFsp may serve that answer from its metadata cache for up to the
|
||||
// mount's FileInfoTimeout. Establish visibility once before racing the
|
||||
// readers, so the race exercises concurrent reading rather than the
|
||||
// cache window.
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
break
|
||||
} else if time.Now().After(deadline) {
|
||||
t.Fatalf("file never became visible: %v", err)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 8)
|
||||
for r := 0; r < 8; r++ {
|
||||
|
||||
@@ -44,6 +44,10 @@ type AdminData struct {
|
||||
// Trends holds at-a-glance sparklines built from the admin's own recent
|
||||
// cluster snapshots (no Prometheus required).
|
||||
Trends DashboardTrends `json:"trends"`
|
||||
|
||||
// TierStats breaks volumes and EC shards down by storage tier: local
|
||||
// disk types plus one entry per remote storage holding tiered volumes.
|
||||
TierStats []TierStats `json:"tier_stats"`
|
||||
}
|
||||
|
||||
// Object Store Users management structures
|
||||
@@ -213,6 +217,7 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
|
||||
TotalEcShards: totalEcShards,
|
||||
TotalMountClients: totalMountClients,
|
||||
Trends: s.GetDashboardTrends(),
|
||||
TierStats: topology.TierStats,
|
||||
}
|
||||
|
||||
return adminData, nil
|
||||
|
||||
@@ -2050,7 +2050,7 @@ func (s *AdminServer) getCollectionStats() (map[string]collectionStats, error) {
|
||||
}
|
||||
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
@@ -116,7 +117,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
|
||||
// Get cluster status from master
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
currentMaster := s.masterClient.GetMaster(context.Background())
|
||||
glog.Errorf("Failed to get volume list from master %s: %v", currentMaster, err)
|
||||
@@ -124,6 +125,12 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
}
|
||||
|
||||
if resp.TopologyInfo != nil {
|
||||
// Get volume size limit from response, default to 30GB if not set
|
||||
volumeSizeLimitMb := resp.VolumeSizeLimitMb
|
||||
if volumeSizeLimitMb == 0 {
|
||||
volumeSizeLimitMb = 30000
|
||||
}
|
||||
|
||||
// Process gRPC response
|
||||
for _, dc := range resp.TopologyInfo.DataCenterInfos {
|
||||
dataCenter := DataCenter{
|
||||
@@ -142,6 +149,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
var totalVolumes int64
|
||||
var totalMaxVolumes int64
|
||||
var totalSize int64
|
||||
var remoteSize int64
|
||||
// Prefer the real physical disk capacity the volume server
|
||||
// reports per disk; the slot-based estimate overstates capacity
|
||||
// when maxVolumeCount is configured higher than the disk holds.
|
||||
@@ -153,12 +161,18 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
if diskInfo.DiskTotalBytes > 0 {
|
||||
diskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
} else {
|
||||
diskCapacity += diskInfo.MaxVolumeCount * int64(resp.VolumeSizeLimitMb) * 1024 * 1024
|
||||
diskCapacity += diskInfo.MaxVolumeCount * int64(volumeSizeLimitMb) * 1024 * 1024
|
||||
}
|
||||
|
||||
// Sum up individual volume information
|
||||
// A remote-tiered volume reports its cloud object's
|
||||
// size; keep those bytes out of the local disk usage
|
||||
// that is compared against diskCapacity.
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
totalSize += int64(volInfo.Size)
|
||||
if volInfo.RemoteStorageName != "" {
|
||||
remoteSize += int64(volInfo.Size)
|
||||
} else {
|
||||
totalSize += int64(volInfo.Size)
|
||||
}
|
||||
}
|
||||
|
||||
// ShardSizes is local to this node, so summing
|
||||
@@ -192,12 +206,15 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
DiskUsage: totalSize,
|
||||
DiskCapacity: diskCapacity,
|
||||
LastHeartbeat: time.Now(),
|
||||
RemoteSize: remoteSize,
|
||||
}
|
||||
|
||||
rackObj.Nodes = append(rackObj.Nodes, vs)
|
||||
topology.VolumeServers = append(topology.VolumeServers, vs)
|
||||
topology.TotalVolumes += vs.Volumes
|
||||
topology.TotalSize += totalSize
|
||||
// TotalSize is the logical data size, wherever the
|
||||
// bytes live, so remote-tiered volumes still count.
|
||||
topology.TotalSize += totalSize + remoteSize
|
||||
}
|
||||
|
||||
dataCenter.Racks = append(dataCenter.Racks, rackObj)
|
||||
@@ -210,6 +227,8 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
// nets out tombstones and counts a chunk once no matter how many
|
||||
// volume replicas or EC shard holders report it.
|
||||
topology.TotalChunks = totalCollectionFileCount(resp.TopologyInfo)
|
||||
|
||||
topology.TierStats = CollectTierStats(resp.TopologyInfo, volumeSizeLimitMb)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
@@ -19,7 +20,7 @@ func (s *AdminServer) GetClusterCollections() (*ClusterCollectionsData, error) {
|
||||
|
||||
// Get actual collection information from volume data
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
@@ -44,7 +45,7 @@ func (s *AdminServer) GetClusterEcShards(page int, pageSize int, sortBy string,
|
||||
|
||||
// Get detailed EC shard information via gRPC
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -65,6 +66,7 @@ func (s *AdminServer) GetClusterEcShards(page int, pageSize int, sortBy string,
|
||||
|
||||
// Create individual shard entries for each shard this server has
|
||||
shardBits := ecShardInfo.EcIndexBits
|
||||
shardsInfo := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(ecShardInfo)
|
||||
for shardId := 0; shardId < erasure_coding.MaxShardCount; shardId++ {
|
||||
if (shardBits & (1 << uint(shardId))) != 0 {
|
||||
// Mark this shard as present for this volume
|
||||
@@ -74,7 +76,7 @@ func (s *AdminServer) GetClusterEcShards(page int, pageSize int, sortBy string,
|
||||
VolumeID: volumeId,
|
||||
ShardID: uint32(shardId),
|
||||
Collection: ecShardInfo.Collection,
|
||||
Size: 0, // EC shards don't have individual size in the API response
|
||||
Size: uint64(shardsInfo.Size(erasure_coding.ShardId(shardId))),
|
||||
Server: node.Id,
|
||||
DataCenter: dc.Id,
|
||||
Rack: rack.Id,
|
||||
@@ -261,7 +263,7 @@ func (s *AdminServer) GetClusterEcVolumes(page int, pageSize int, sortBy string,
|
||||
|
||||
// Get detailed EC shard information via gRPC
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -559,7 +561,7 @@ func (s *AdminServer) GetEcVolumeDetails(volumeID uint32, sortBy string, sortOrd
|
||||
|
||||
// Get detailed EC shard information for the specific volume via gRPC
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{VolumeId: volumeID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -571,6 +573,7 @@ func (s *AdminServer) GetEcVolumeDetails(volumeID uint32, sortBy string, sortOrd
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
// Process EC shard information for this specific volume
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
// An older master ignores the filter.
|
||||
if ecShardInfo.Id == volumeID {
|
||||
collection = ecShardInfo.Collection
|
||||
dataCenters[dc.Id] = true
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// TierStats aggregates the volumes and EC shards that live on one storage
|
||||
// tier: a local disk type ("hdd", "ssd", or a custom tag), or the remote
|
||||
// storage a tiered volume was uploaded to. A remote-tiered volume reports
|
||||
// the size of its cloud object, so its bytes belong to the remote tier,
|
||||
// not to the local disk that holds only its index.
|
||||
type TierStats struct {
|
||||
Name string `json:"name"`
|
||||
IsRemote bool `json:"is_remote"`
|
||||
VolumeCount int `json:"volume_count"`
|
||||
EcShardCount int `json:"ec_shard_count"`
|
||||
DataSize int64 `json:"data_size"`
|
||||
DiskUsed int64 `json:"disk_used"`
|
||||
DiskCapacity int64 `json:"disk_capacity"`
|
||||
MaxVolumes int64 `json:"max_volumes"`
|
||||
}
|
||||
|
||||
// UsagePercent is the tier's local disk usage in percent, clamped to
|
||||
// [0, 100]. Remote tiers have no capacity and return 0.
|
||||
func (t TierStats) UsagePercent() int {
|
||||
if t.IsRemote || t.DiskCapacity <= 0 {
|
||||
return 0
|
||||
}
|
||||
percent := int(float64(t.DiskUsed) / float64(t.DiskCapacity) * 100)
|
||||
if percent < 0 {
|
||||
return 0
|
||||
}
|
||||
if percent > 100 {
|
||||
return 100
|
||||
}
|
||||
return percent
|
||||
}
|
||||
|
||||
// tierDiskType maps the empty disk type to its display name.
|
||||
func tierDiskType(diskType string) string {
|
||||
if diskType == "" {
|
||||
return "hdd"
|
||||
}
|
||||
return diskType
|
||||
}
|
||||
|
||||
// CollectTierStats walks the topology and groups capacity and usage by
|
||||
// tier. DiskUsed/DiskCapacity come from the statfs numbers the volume
|
||||
// servers report per disk type; a disk that predates disk_total_bytes
|
||||
// falls back to the slot-based capacity estimate and to the logical
|
||||
// bytes it holds, so mixed-version tiers don't underreport usage.
|
||||
// Remote tiers have no local disk, so only VolumeCount and DataSize are
|
||||
// meaningful there.
|
||||
func CollectTierStats(topo *master_pb.TopologyInfo, volumeSizeLimitMb uint64) []TierStats {
|
||||
if topo == nil {
|
||||
return nil
|
||||
}
|
||||
tiers := make(map[string]*TierStats)
|
||||
tier := func(name string, isRemote bool) *TierStats {
|
||||
key := name
|
||||
if isRemote {
|
||||
key = "remote\x00" + name
|
||||
}
|
||||
t := tiers[key]
|
||||
if t == nil {
|
||||
t = &TierStats{Name: name, IsRemote: isRemote}
|
||||
tiers[key] = t
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
for _, dc := range topo.DataCenterInfos {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for _, node := range rack.DataNodeInfos {
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
local := tier(tierDiskType(diskInfo.Type), false)
|
||||
local.MaxVolumes += diskInfo.MaxVolumeCount
|
||||
hasStatfs := diskInfo.DiskTotalBytes > 0
|
||||
if hasStatfs {
|
||||
local.DiskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
if diskInfo.DiskTotalBytes > diskInfo.DiskFreeBytes {
|
||||
local.DiskUsed += int64(diskInfo.DiskTotalBytes - diskInfo.DiskFreeBytes)
|
||||
}
|
||||
} else {
|
||||
local.DiskCapacity += diskInfo.MaxVolumeCount * int64(volumeSizeLimitMb) * 1024 * 1024
|
||||
}
|
||||
|
||||
var diskLocalBytes int64
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
if volInfo.RemoteStorageName != "" {
|
||||
remote := tier(volInfo.RemoteStorageName, true)
|
||||
remote.VolumeCount++
|
||||
remote.DataSize += int64(volInfo.Size)
|
||||
} else {
|
||||
local.VolumeCount++
|
||||
local.DataSize += int64(volInfo.Size)
|
||||
diskLocalBytes += int64(volInfo.Size)
|
||||
}
|
||||
}
|
||||
|
||||
// ShardSizes is local to this node, so summing across
|
||||
// nodes gives the tier's physical footprint.
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
local.EcShardCount += erasure_coding.GetShardCount(ecShardInfo)
|
||||
ecBytes := erasure_coding.EcShardsTotalSize(ecShardInfo)
|
||||
local.DataSize += ecBytes
|
||||
diskLocalBytes += ecBytes
|
||||
}
|
||||
|
||||
// Without statfs numbers, approximate this disk's
|
||||
// footprint with the logical bytes it holds.
|
||||
if !hasStatfs {
|
||||
local.DiskUsed += diskLocalBytes
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result := make([]TierStats, 0, len(tiers))
|
||||
for _, t := range tiers {
|
||||
result = append(result, *t)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].IsRemote != result[j].IsRemote {
|
||||
return !result[i].IsRemote
|
||||
}
|
||||
return result[i].Name < result[j].Name
|
||||
})
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
func TestCollectTierStats(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{
|
||||
Id: "node1:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {
|
||||
Type: "",
|
||||
MaxVolumeCount: 10,
|
||||
DiskTotalBytes: 1_000_000,
|
||||
DiskFreeBytes: 400_000,
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{
|
||||
{Id: 1, Size: 1000},
|
||||
{Id: 2, Size: 5000, RemoteStorageName: "s3.backup", RemoteStorageKey: "/2.dat"},
|
||||
},
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
|
||||
{Id: 7, EcIndexBits: 0b111, ShardSizes: []int64{10, 20, 30}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: "node2:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"ssd": {
|
||||
Type: "ssd",
|
||||
MaxVolumeCount: 5,
|
||||
// No statfs numbers: capacity falls back to
|
||||
// slots and usage to logical bytes.
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{
|
||||
{Id: 3, Size: 2000, DiskType: "ssd"},
|
||||
{Id: 4, Size: 7000, DiskType: "ssd", RemoteStorageName: "s3.backup", RemoteStorageKey: "/4.dat"},
|
||||
{Id: 5, Size: 100, DiskType: "ssd", RemoteStorageName: "gcs.archive", RemoteStorageKey: "/5.dat"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
// An old server without statfs numbers sharing the
|
||||
// hdd tier with node1: its logical bytes must still
|
||||
// count toward the tier's DiskUsed.
|
||||
Id: "node3:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {
|
||||
Type: "",
|
||||
MaxVolumeCount: 2,
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{
|
||||
{Id: 6, Size: 800},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}
|
||||
|
||||
got := CollectTierStats(topo, 30)
|
||||
|
||||
want := []TierStats{
|
||||
{Name: "hdd", VolumeCount: 2, EcShardCount: 3, DataSize: 1860, DiskUsed: 600_800, DiskCapacity: 1_000_000 + 2*30*1024*1024, MaxVolumes: 12},
|
||||
{Name: "ssd", VolumeCount: 1, DataSize: 2000, DiskUsed: 2000, DiskCapacity: 5 * 30 * 1024 * 1024, MaxVolumes: 5},
|
||||
{Name: "gcs.archive", IsRemote: true, VolumeCount: 1, DataSize: 100},
|
||||
{Name: "s3.backup", IsRemote: true, VolumeCount: 2, DataSize: 12000},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("CollectTierStats mismatch:\n got: %+v\nwant: %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectTierStatsEmpty(t *testing.T) {
|
||||
if got := CollectTierStats(nil, 30); got != nil {
|
||||
t.Errorf("expected nil for nil topology, got %+v", got)
|
||||
}
|
||||
if got := CollectTierStats(&master_pb.TopologyInfo{}, 30); len(got) != 0 {
|
||||
t.Errorf("expected no tiers for empty topology, got %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@ type ClusterTopology struct {
|
||||
TotalChunks int64 `json:"total_chunks"`
|
||||
TotalSize int64 `json:"total_size"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// TierStats breaks volumes and EC shards down by storage tier: local
|
||||
// disk types plus one entry per remote storage holding tiered volumes.
|
||||
TierStats []TierStats `json:"tier_stats"`
|
||||
}
|
||||
|
||||
type MasterNode struct {
|
||||
@@ -52,6 +55,11 @@ type VolumeServer struct {
|
||||
EcVolumes int `json:"ec_volumes"` // Number of EC volumes this server has shards for
|
||||
EcShards int `json:"ec_shards"` // Total number of EC shards on this server
|
||||
EcShardDetails []VolumeServerEcInfo `json:"ec_shard_details"` // Detailed EC shard information
|
||||
|
||||
// RemoteSize is the bytes this server's remote-tiered volumes hold in
|
||||
// cloud storage. Those bytes are excluded from DiskUsage, which only
|
||||
// counts what occupies local disks.
|
||||
RemoteSize int64 `json:"remote_size"`
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) GetDisplayAddress() string {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
@@ -93,7 +94,6 @@ type ExportVolume struct {
|
||||
DiskType string `json:"disk_type"`
|
||||
DiskId uint32 `json:"disk_id"`
|
||||
RemoteStorageName string `json:"remote_storage_name,omitempty"`
|
||||
RemoteStorageKey string `json:"remote_storage_key,omitempty"`
|
||||
}
|
||||
|
||||
type ExportEcShard struct {
|
||||
@@ -122,7 +122,7 @@ func (s *AdminServer) ExportClusterVolumeList(ctx context.Context, collection st
|
||||
}
|
||||
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(ctx, &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(ctx, client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -251,7 +251,6 @@ func buildExportVolume(m *master_pb.VolumeInformationMessage, volumeSizeLimit ui
|
||||
DiskType: m.DiskType,
|
||||
DiskId: m.DiskId,
|
||||
RemoteStorageName: m.RemoteStorageName,
|
||||
RemoteStorageKey: m.RemoteStorageKey,
|
||||
}
|
||||
// Decode replica placement and TTL the way volume.list does.
|
||||
if vi, err := storage.NewVolumeInfo(m); err == nil {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
@@ -32,7 +33,7 @@ func (s *AdminServer) GetClusterVolumes(page int, pageSize int, sortBy string, s
|
||||
|
||||
// Get detailed volume information via gRPC
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -121,7 +122,11 @@ func (s *AdminServer) GetClusterVolumes(page int, pageSize int, sortBy string, s
|
||||
diskTypeMap := make(map[string]bool)
|
||||
collectionMap := make(map[string]bool)
|
||||
versionMap := make(map[string]bool)
|
||||
hasRemoteVolumes := false
|
||||
for _, volume := range volumes {
|
||||
if volume.RemoteStorageName != "" {
|
||||
hasRemoteVolumes = true
|
||||
}
|
||||
if volume.DataCenter != "" {
|
||||
dataCenterMap[volume.DataCenter] = true
|
||||
}
|
||||
@@ -189,7 +194,9 @@ func (s *AdminServer) GetClusterVolumes(page int, pageSize int, sortBy string, s
|
||||
// Determine conditional display flags and extract single values
|
||||
showDataCenterColumn := dataCenterCount > 1
|
||||
showRackColumn := rackCount > 1
|
||||
showDiskTypeColumn := diskTypeCount > 1
|
||||
// Remote-tiered volumes surface in the disk type column, so show it
|
||||
// whenever any volume lives on a remote tier.
|
||||
showDiskTypeColumn := diskTypeCount > 1 || hasRemoteVolumes
|
||||
showCollectionColumn := collectionCount > 1 && collection == "" // Hide column when filtering by collection
|
||||
showVersionColumn := versionCount > 1
|
||||
|
||||
@@ -309,7 +316,7 @@ func (s *AdminServer) sortVolumes(volumes []VolumeWithTopology, sortBy string, s
|
||||
}
|
||||
|
||||
// GetVolumeDetails retrieves detailed information about a specific volume
|
||||
func (s *AdminServer) GetVolumeDetails(volumeID int, server string) (*VolumeDetailsData, error) {
|
||||
func (s *AdminServer) GetVolumeDetails(volumeID uint32, server string) (*VolumeDetailsData, error) {
|
||||
var primaryVolume VolumeWithTopology
|
||||
var replicas []VolumeWithTopology
|
||||
var volumeSizeLimit uint64
|
||||
@@ -317,7 +324,7 @@ func (s *AdminServer) GetVolumeDetails(volumeID int, server string) (*VolumeDeta
|
||||
|
||||
// Find the volume and all its replicas in the cluster
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{VolumeId: volumeID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -328,7 +335,8 @@ func (s *AdminServer) GetVolumeDetails(volumeID int, server string) (*VolumeDeta
|
||||
for _, node := range rack.DataNodeInfos {
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
if int(volInfo.Id) == volumeID {
|
||||
// An older master ignores the filter.
|
||||
if volInfo.Id == volumeID {
|
||||
diskType := volInfo.DiskType
|
||||
if diskType == "" {
|
||||
diskType = "hdd"
|
||||
@@ -418,7 +426,7 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
|
||||
|
||||
// Make only ONE VolumeList call and use it for both topology building AND EC shard processing
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -480,10 +488,17 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
|
||||
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024
|
||||
}
|
||||
|
||||
// Count regular volumes and calculate disk usage
|
||||
// Count regular volumes and calculate disk usage.
|
||||
// A remote-tiered volume reports its cloud object's
|
||||
// size; keep those bytes out of the local disk usage
|
||||
// that is compared against DiskCapacity.
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
vs.Volumes++
|
||||
vs.DiskUsage += int64(volInfo.Size)
|
||||
if volInfo.RemoteStorageName != "" {
|
||||
vs.RemoteSize += int64(volInfo.Size)
|
||||
} else {
|
||||
vs.DiskUsage += int64(volInfo.Size)
|
||||
}
|
||||
}
|
||||
|
||||
// Accumulate EC shard information across all disks for this volume server
|
||||
|
||||
@@ -155,14 +155,14 @@ func (h *ClusterHandlers) ShowVolumeDetails(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
volumeID, err := strconv.Atoi(volumeIDStr)
|
||||
volumeID, err := strconv.ParseUint(volumeIDStr, 10, 32)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid volume ID")
|
||||
return
|
||||
}
|
||||
|
||||
// Get volume details
|
||||
volumeDetails, err := h.adminServer.GetVolumeDetails(volumeID, server)
|
||||
volumeDetails, err := h.adminServer.GetVolumeDetails(uint32(volumeID), server)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get volume details: "+err.Error())
|
||||
return
|
||||
|
||||
@@ -6,6 +6,7 @@ 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/worker/types"
|
||||
)
|
||||
@@ -101,7 +102,8 @@ func (ms *MaintenanceScanner) getVolumeHealthMetrics() ([]*types.VolumeHealthMet
|
||||
glog.V(1).Infof("Collecting volume health metrics from master")
|
||||
err := ms.adminClient.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
|
||||
resp, err := client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
// Streamed, so the master never builds the whole listing to send it.
|
||||
resp, err := pb.CollectVolumeList(context.Background(), client, &master_pb.VolumeListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ const (
|
||||
defaultWaitingBacklogFloor = 8
|
||||
defaultWaitingBacklogMultiplier = 4
|
||||
maxEstimatedRuntimeCap = 8 * time.Hour
|
||||
// How long started jobs may drain past the run window close.
|
||||
scheduledExecutionDrainGrace = 30 * time.Minute
|
||||
)
|
||||
|
||||
type schedulerPolicy struct {
|
||||
@@ -411,15 +413,10 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
if execPolicy.ExecutionTimeout <= 0 {
|
||||
execPolicy.ExecutionTimeout = defaultScheduledExecutionTimeout
|
||||
}
|
||||
if execPolicy.ExecutionTimeout > remaining {
|
||||
execPolicy.ExecutionTimeout = remaining
|
||||
}
|
||||
|
||||
// jobCtx bounds how long this run keeps STARTING jobs; a started job
|
||||
// runs on its own estimated-runtime deadline (see
|
||||
// executeScheduledJobWithExecutor). Jobs still queued when the window
|
||||
// closes are canceled and re-proposed by a later detection, so one large
|
||||
// backlog cannot monopolise the lane for hours.
|
||||
// jobCtx bounds how long this run keeps STARTING jobs; started jobs
|
||||
// drain past the window close (see scheduledAttemptContext), while
|
||||
// still-queued jobs are canceled and re-proposed by a later detection.
|
||||
successCount, errorCount, canceledCount := r.dispatchScheduledProposals(jobCtx, jobType, filtered, clusterContext, execPolicy)
|
||||
|
||||
status := "success"
|
||||
@@ -1201,24 +1198,11 @@ func (r *Plugin) executeScheduledJobWithExecutor(
|
||||
// default execution timeout. This lets handlers like vacuum scale
|
||||
// the timeout based on volume size so large volumes are not killed.
|
||||
timeout := policy.ExecutionTimeout
|
||||
if job.Parameters != nil {
|
||||
if est, ok := job.Parameters["estimated_runtime_seconds"]; ok {
|
||||
if v := est.GetInt64Value(); v > 0 {
|
||||
estimated := time.Duration(v) * time.Second
|
||||
if estimated > maxEstimatedRuntimeCap {
|
||||
estimated = maxEstimatedRuntimeCap
|
||||
}
|
||||
if estimated > timeout {
|
||||
timeout = estimated
|
||||
}
|
||||
}
|
||||
}
|
||||
estimated := scheduledEstimatedRuntime(job.Parameters)
|
||||
if estimated > timeout {
|
||||
timeout = estimated
|
||||
}
|
||||
// The attempt runs against its own deadline, detached from the
|
||||
// dispatch window (ctx): a job started near the end of the window
|
||||
// may run to completion; the window only stops further jobs from
|
||||
// starting.
|
||||
execCtx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
execCtx, cancel := scheduledAttemptContext(ctx, timeout, estimated)
|
||||
_, err := r.executeJobWithExecutor(execCtx, executor, job, clusterContext, int32(attempt))
|
||||
cancel()
|
||||
if err == nil {
|
||||
@@ -1253,6 +1237,43 @@ func (r *Plugin) executeScheduledJobWithExecutor(
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// scheduledEstimatedRuntime returns the job's declared estimated runtime,
|
||||
// capped at maxEstimatedRuntimeCap. The seconds are capped before the
|
||||
// Duration conversion so oversized values cannot overflow.
|
||||
func scheduledEstimatedRuntime(parameters map[string]*plugin_pb.ConfigValue) time.Duration {
|
||||
est, ok := parameters["estimated_runtime_seconds"]
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
v := est.GetInt64Value()
|
||||
if v <= 0 {
|
||||
return 0
|
||||
}
|
||||
if v > int64(maxEstimatedRuntimeCap/time.Second) {
|
||||
v = int64(maxEstimatedRuntimeCap / time.Second)
|
||||
}
|
||||
return time.Duration(v) * time.Second
|
||||
}
|
||||
|
||||
// scheduledAttemptContext bounds one execution attempt: its own timeout,
|
||||
// capped at the window deadline plus scheduledExecutionDrainGrace so a
|
||||
// draining job cannot hold the lane indefinitely, but never below the
|
||||
// job's declared estimated runtime.
|
||||
func scheduledAttemptContext(window context.Context, timeout, estimated time.Duration) (context.Context, context.CancelFunc) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
if window != nil {
|
||||
if windowEnd, ok := window.Deadline(); ok {
|
||||
if drainDeadline := windowEnd.Add(scheduledExecutionDrainGrace); deadline.After(drainDeadline) {
|
||||
if floor := time.Now().Add(estimated); floor.After(drainDeadline) {
|
||||
drainDeadline = floor
|
||||
}
|
||||
deadline = drainDeadline
|
||||
}
|
||||
}
|
||||
}
|
||||
return context.WithDeadline(context.Background(), deadline)
|
||||
}
|
||||
|
||||
func (r *Plugin) shouldSkipDetectionForWaitingJobs(jobType string, policy schedulerPolicy) (bool, int, int) {
|
||||
waitingCount := r.countWaitingTrackedJobs(jobType)
|
||||
threshold := waitingBacklogThreshold(policy)
|
||||
|
||||
@@ -3,11 +3,13 @@ package plugin
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func TestLoadSchedulerPolicyUsesAdminConfig(t *testing.T) {
|
||||
@@ -738,6 +740,144 @@ func TestDispatchScheduledProposalsLocksPerJob(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduledAttemptContextDrainGrace(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
assertDeadline := func(t *testing.T, ctx context.Context, want time.Time) {
|
||||
t.Helper()
|
||||
got, ok := ctx.Deadline()
|
||||
if !ok {
|
||||
t.Fatal("expected attempt context to carry a deadline")
|
||||
}
|
||||
if diff := got.Sub(want); diff < -5*time.Second || diff > 5*time.Second {
|
||||
t.Fatalf("unexpected attempt deadline: got=%v want~%v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
windowEnd := time.Now().Add(time.Minute)
|
||||
window, cancelWindow := context.WithDeadline(context.Background(), windowEnd)
|
||||
defer cancelWindow()
|
||||
|
||||
// Fits inside the window: keeps its own deadline.
|
||||
ctx, cancel := scheduledAttemptContext(window, 30*time.Second, 0)
|
||||
assertDeadline(t, ctx, time.Now().Add(30*time.Second))
|
||||
cancel()
|
||||
|
||||
// Longer: capped at window close plus the grace.
|
||||
ctx, cancel = scheduledAttemptContext(window, 3*time.Hour, 0)
|
||||
assertDeadline(t, ctx, windowEnd.Add(scheduledExecutionDrainGrace))
|
||||
cancel()
|
||||
|
||||
// Estimated runtime: keeps its full deadline.
|
||||
ctx, cancel = scheduledAttemptContext(window, 3*time.Hour, 3*time.Hour)
|
||||
assertDeadline(t, ctx, time.Now().Add(3*time.Hour))
|
||||
cancel()
|
||||
|
||||
// An estimate below the timeout floors the drain cap.
|
||||
ctx, cancel = scheduledAttemptContext(window, 3*time.Hour, 45*time.Minute)
|
||||
assertDeadline(t, ctx, time.Now().Add(45*time.Minute))
|
||||
cancel()
|
||||
|
||||
// No window deadline: the timeout stands alone.
|
||||
ctx, cancel = scheduledAttemptContext(context.Background(), 2*time.Hour, 0)
|
||||
assertDeadline(t, ctx, time.Now().Add(2*time.Hour))
|
||||
cancel()
|
||||
}
|
||||
|
||||
func TestScheduledEstimatedRuntime(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
estimate := func(v int64) map[string]*plugin_pb.ConfigValue {
|
||||
return map[string]*plugin_pb.ConfigValue{
|
||||
"estimated_runtime_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: v}},
|
||||
}
|
||||
}
|
||||
|
||||
if got := scheduledEstimatedRuntime(nil); got != 0 {
|
||||
t.Fatalf("nil parameters: got=%v want=0", got)
|
||||
}
|
||||
if got := scheduledEstimatedRuntime(estimate(-5)); got != 0 {
|
||||
t.Fatalf("negative estimate: got=%v want=0", got)
|
||||
}
|
||||
if got := scheduledEstimatedRuntime(estimate(600)); got != 10*time.Minute {
|
||||
t.Fatalf("normal estimate: got=%v want=10m", got)
|
||||
}
|
||||
// Oversized seconds cap before the Duration conversion can overflow.
|
||||
if got := scheduledEstimatedRuntime(estimate(math.MaxInt64)); got != maxEstimatedRuntimeCap {
|
||||
t.Fatalf("oversized estimate: got=%v want=%v", got, maxEstimatedRuntimeCap)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchScheduledProposalsDrainsStartedJobOnWindowClose(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pluginSvc, err := New(Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
const workerID = "worker-drain"
|
||||
const jobType = "s3_lifecycle" // lifecycle lane: no admin lock needed
|
||||
pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{
|
||||
WorkerId: workerID,
|
||||
Capabilities: []*plugin_pb.JobTypeCapability{
|
||||
{JobType: jobType, CanExecute: true, MaxExecutionConcurrency: 1},
|
||||
},
|
||||
})
|
||||
session := &streamSession{workerID: workerID, outgoing: make(chan *plugin_pb.AdminToWorkerMessage, 8), done: make(chan struct{})}
|
||||
pluginSvc.putSession(session)
|
||||
|
||||
windowCtx, closeWindow := context.WithCancel(context.Background())
|
||||
defer closeWindow()
|
||||
|
||||
policy := schedulerPolicy{
|
||||
ExecutionConcurrency: 1,
|
||||
PerWorkerConcurrency: 1,
|
||||
ExecutionTimeout: time.Hour,
|
||||
ExecutorReserveBackoff: time.Millisecond,
|
||||
}
|
||||
proposals := []*plugin_pb.JobProposal{
|
||||
{ProposalId: "p1", JobType: jobType, DedupeKey: "k1"},
|
||||
{ProposalId: "p2", JobType: jobType, DedupeKey: "k2"},
|
||||
}
|
||||
|
||||
resultCh := make(chan [3]int, 1)
|
||||
go func() {
|
||||
success, errCount, canceled := pluginSvc.dispatchScheduledProposals(
|
||||
windowCtx, jobType, proposals, &plugin_pb.ClusterContext{}, policy)
|
||||
resultCh <- [3]int{success, errCount, canceled}
|
||||
}()
|
||||
|
||||
first := <-session.outgoing
|
||||
execReq := first.GetExecuteJobRequest()
|
||||
if execReq == nil {
|
||||
t.Fatalf("expected execute_job_request, got %+v", first)
|
||||
}
|
||||
|
||||
// Close the window mid-job: the job must drain to completion while the
|
||||
// still-queued second proposal is canceled.
|
||||
closeWindow()
|
||||
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
|
||||
RequestId: first.RequestId,
|
||||
JobId: execReq.Job.JobId,
|
||||
JobType: jobType,
|
||||
Success: true,
|
||||
CompletedAt: timestamppb.Now(),
|
||||
})
|
||||
|
||||
result := <-resultCh
|
||||
if result[0] != 1 || result[1] != 0 || result[2] != 1 {
|
||||
t.Fatalf("unexpected dispatch counts: success=%d errors=%d canceled=%d", result[0], result[1], result[2])
|
||||
}
|
||||
|
||||
select {
|
||||
case unexpected := <-session.outgoing:
|
||||
t.Fatalf("expected no further worker messages (no cancel for the draining job), got %+v", unexpected)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- lane-scoped prune ----------
|
||||
|
||||
func TestPruneSchedulerState_DefaultLaneKeepsForeignLanesAndPrunesOwnStale(t *testing.T) {
|
||||
|
||||
@@ -5,6 +5,15 @@ function basePath(path) {
|
||||
return (window.__BASE_PATH__ || '') + path;
|
||||
}
|
||||
|
||||
// Current-location checks against app paths, ignoring the URL prefix
|
||||
function isCurrentPath(path) {
|
||||
return window.location.pathname === basePath(path);
|
||||
}
|
||||
|
||||
function currentPathStartsWith(path) {
|
||||
return window.location.pathname.startsWith(basePath(path));
|
||||
}
|
||||
|
||||
// Global variables
|
||||
let bucketToDelete = '';
|
||||
|
||||
@@ -16,7 +25,7 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
setupFileManagerEventHandlers();
|
||||
|
||||
// Initialize delete button visibility on file browser page
|
||||
if (window.location.pathname === basePath('/files')) {
|
||||
if (isCurrentPath('/files')) {
|
||||
updateDeleteSelectedButton();
|
||||
}
|
||||
});
|
||||
@@ -71,7 +80,7 @@ function initializeTooltips() {
|
||||
function setupAutoRefresh() {
|
||||
// Refresh dashboard data every 30 seconds
|
||||
setInterval(function () {
|
||||
if (window.location.pathname === basePath('/dashboard')) {
|
||||
if (isCurrentPath('/dashboard')) {
|
||||
htmx.trigger('#dashboard-content', 'refresh');
|
||||
}
|
||||
}, 30000);
|
||||
@@ -88,9 +97,9 @@ function setActiveNavigation() {
|
||||
|
||||
if (href === currentPath) {
|
||||
isActive = true;
|
||||
} else if (currentPath === '/' && href === '/admin') {
|
||||
} else if (isCurrentPath('/') && href === basePath('/admin')) {
|
||||
isActive = true;
|
||||
} else if (currentPath.startsWith('/s3/') && href === '/s3/buckets') {
|
||||
} else if (currentPathStartsWith('/s3/') && href === basePath('/s3/buckets')) {
|
||||
isActive = true;
|
||||
}
|
||||
// Note: Removed the problematic cluster condition that was highlighting all submenu items
|
||||
@@ -105,10 +114,8 @@ function setActiveNavigation() {
|
||||
|
||||
// Set up submenu behavior
|
||||
function setupSubmenuBehavior() {
|
||||
const currentPath = window.location.pathname;
|
||||
|
||||
// If we're on a cluster page, expand the cluster submenu
|
||||
if (currentPath.startsWith('/cluster/')) {
|
||||
if (currentPathStartsWith('/cluster/')) {
|
||||
const clusterSubmenu = document.getElementById('clusterSubmenu');
|
||||
if (clusterSubmenu) {
|
||||
clusterSubmenu.classList.add('show');
|
||||
@@ -123,7 +130,7 @@ function setupSubmenuBehavior() {
|
||||
}
|
||||
|
||||
// If we're on an object store page, expand the object store submenu
|
||||
if (currentPath.startsWith('/object-store/')) {
|
||||
if (currentPathStartsWith('/object-store/')) {
|
||||
const objectStoreSubmenu = document.getElementById('objectStoreSubmenu');
|
||||
if (objectStoreSubmenu) {
|
||||
objectStoreSubmenu.classList.add('show');
|
||||
|
||||
Binary file not shown.
@@ -194,6 +194,87 @@ templ Admin(data dash.AdminData) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Storage Tiers -->
|
||||
if len(data.TierStats) > 0 {
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
<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-layer-group me-2"></i>Storage Tiers
|
||||
</h6>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover" width="100%" cellspacing="0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Tier</th>
|
||||
<th>Volumes</th>
|
||||
<th>EC Shards</th>
|
||||
<th>Data Size</th>
|
||||
<th>Disk Used</th>
|
||||
<th>Capacity</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
for _, tier := range data.TierStats {
|
||||
<tr>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<i class="fas fa-cloud me-1 text-info"></i>{tier.Name}
|
||||
<span class="badge bg-info text-white ms-1">remote</span>
|
||||
} else {
|
||||
<i class="fas fa-hdd me-1 text-muted"></i>{tier.Name}
|
||||
}
|
||||
</td>
|
||||
<td>{fmt.Sprintf("%d", tier.VolumeCount)}</td>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
{fmt.Sprintf("%d", tier.EcShardCount)}
|
||||
}
|
||||
</td>
|
||||
<td>{formatBytes(tier.DataSize)}</td>
|
||||
<td>
|
||||
if tier.IsRemote || tier.DiskUsed == 0 {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
{formatBytes(tier.DiskUsed)}
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
{formatBytes(tier.DiskCapacity)}
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
<div class="progress" style="height: 20px;">
|
||||
<div class="progress-bar" role="progressbar"
|
||||
style={fmt.Sprintf("width: %d%%", tier.UsagePercent())}>
|
||||
{fmt.Sprintf("%d%%", tier.UsagePercent())}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Mount Clients -->
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
@@ -202,7 +283,7 @@ templ Admin(data dash.AdminData) {
|
||||
<h6 class="m-0 font-weight-bold text-primary">
|
||||
<i class="fas fa-plug me-2"></i>Mount Clients
|
||||
</h6>
|
||||
<a id="mountClientsDetailsLink" href="/cluster/mount-clients" class="btn btn-sm btn-outline-primary">
|
||||
<a href={ dash.PUrl(ctx, "/cluster/mount-clients") } class="btn btn-sm btn-outline-primary">
|
||||
View Details <i class="fas fa-arrow-right ms-1"></i>
|
||||
</a>
|
||||
</div>
|
||||
@@ -218,9 +299,6 @@ templ Admin(data dash.AdminData) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function(){var l=document.getElementById('mountClientsDetailsLink'); if(l){l.href=(window.__BASE_PATH__||'')+'/cluster/mount-clients';}})();
|
||||
</script>
|
||||
|
||||
<!-- Master Nodes Status -->
|
||||
<div class="row mb-4">
|
||||
@@ -351,7 +429,7 @@ templ Admin(data dash.AdminData) {
|
||||
<th>Rack</th>
|
||||
<th>Volumes</th>
|
||||
<th>EC Shards</th>
|
||||
<th>Capacity</th>
|
||||
<th>Usage / Capacity</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -384,7 +462,13 @@ templ Admin(data dash.AdminData) {
|
||||
<span class="text-muted">-</span>
|
||||
}
|
||||
</td>
|
||||
<td>{formatBytes(vs.DiskUsage)} / {formatBytes(vs.DiskCapacity)}</td>
|
||||
<td>
|
||||
{formatBytes(vs.DiskUsage)} / {formatBytes(vs.DiskCapacity)}
|
||||
if vs.RemoteSize > 0 {
|
||||
<br/>
|
||||
<small class="text-muted"><i class="fas fa-cloud me-1"></i>{formatBytes(vs.RemoteSize)} remote</small>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
if len(data.VolumeServers) == 0 {
|
||||
|
||||
+589
-369
File diff suppressed because it is too large.
Load diff
@@ -145,7 +145,7 @@ templ ClusterFilers(data dash.ClusterFilersData) {
|
||||
|
||||
function openFilerBrowser(address) {
|
||||
// Open file browser for specific filer
|
||||
window.open('/files?filer=' + encodeURIComponent(address), '_blank');
|
||||
window.open((window.__BASE_PATH__ || '') + '/files?filer=' + encodeURIComponent(address), '_blank');
|
||||
}
|
||||
|
||||
function exportFilers() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1001
|
||||
// templ: version: v0.3.1020
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -147,11 +147,11 @@ func ClusterFilers(data dash.ClusterFilersData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(filer.Address)
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.ResolveAttributeValue(filer.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_filers.templ`, Line: 94, Col: 149}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -183,7 +183,7 @@ func ClusterFilers(data dash.ClusterFilersData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</small></div></div></div><!-- JavaScript for cluster filers functionality --><script>\n\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t// Handle filer action buttons\n\t\tdocument.addEventListener('click', function(e) {\n\t\t\tconst button = e.target.closest('[data-action]');\n\t\t\tif (!button) return;\n\t\t\t\n\t\t\tconst action = button.getAttribute('data-action');\n\t\t\tconst address = button.getAttribute('data-address');\n\t\t\t\n\t\t\tif (!address) return;\n\t\t\t\n\t\t\tswitch(action) {\n\t\t\t\tcase 'open-filer':\n\t\t\t\t\topenFilerBrowser(address);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t});\n\t\n\tfunction openFilerBrowser(address) {\n\t\t// Open file browser for specific filer\n\t\twindow.open('/files?filer=' + encodeURIComponent(address), '_blank');\n\t}\n\t\n\tfunction exportFilers() {\n\t\t// Simple CSV export of filers list\n\t\tconst rows = Array.from(document.querySelectorAll('#filersTable tbody tr')).map(row => {\n\t\t\tconst cells = row.querySelectorAll('td');\n\t\t\tif (cells.length > 1) {\n\t\t\t\treturn {\n\t\t\t\t\taddress: cells[0].textContent.trim(),\n\t\t\t\t\tversion: cells[1].textContent.trim(),\n\t\t\t\t\tdatacenter: cells[2].textContent.trim(),\n\t\t\t\t\track: cells[3].textContent.trim(),\n\t\t\t\t\tcreated: cells[4].textContent.trim()\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn null;\n\t\t}).filter(row => row !== null);\n\t\t\n\t\tconst csvContent = \"data:text/csv;charset=utf-8,\" + \n\t\t\t\"Address,Version,Data Center,Rack,Created At\\n\" +\n\t\t\trows.map(r => '\"' + r.address + '\",\"' + r.version + '\",\"' + r.datacenter + '\",\"' + r.rack + '\",\"' + r.created + '\"').join(\"\\n\");\n\t\t\n\t\tconst encodedUri = encodeURI(csvContent);\n\t\tconst link = document.createElement(\"a\");\n\t\tlink.setAttribute(\"href\", encodedUri);\n\t\tlink.setAttribute(\"download\", \"filers.csv\");\n\t\tdocument.body.appendChild(link);\n\t\tlink.click();\n\t\tdocument.body.removeChild(link);\n\t}\n\t</script>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</small></div></div></div><!-- JavaScript for cluster filers functionality --><script>\n\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t// Handle filer action buttons\n\t\tdocument.addEventListener('click', function(e) {\n\t\t\tconst button = e.target.closest('[data-action]');\n\t\t\tif (!button) return;\n\t\t\t\n\t\t\tconst action = button.getAttribute('data-action');\n\t\t\tconst address = button.getAttribute('data-address');\n\t\t\t\n\t\t\tif (!address) return;\n\t\t\t\n\t\t\tswitch(action) {\n\t\t\t\tcase 'open-filer':\n\t\t\t\t\topenFilerBrowser(address);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t});\n\t\n\tfunction openFilerBrowser(address) {\n\t\t// Open file browser for specific filer\n\t\twindow.open((window.__BASE_PATH__ || '') + '/files?filer=' + encodeURIComponent(address), '_blank');\n\t}\n\t\n\tfunction exportFilers() {\n\t\t// Simple CSV export of filers list\n\t\tconst rows = Array.from(document.querySelectorAll('#filersTable tbody tr')).map(row => {\n\t\t\tconst cells = row.querySelectorAll('td');\n\t\t\tif (cells.length > 1) {\n\t\t\t\treturn {\n\t\t\t\t\taddress: cells[0].textContent.trim(),\n\t\t\t\t\tversion: cells[1].textContent.trim(),\n\t\t\t\t\tdatacenter: cells[2].textContent.trim(),\n\t\t\t\t\track: cells[3].textContent.trim(),\n\t\t\t\t\tcreated: cells[4].textContent.trim()\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn null;\n\t\t}).filter(row => row !== null);\n\t\t\n\t\tconst csvContent = \"data:text/csv;charset=utf-8,\" + \n\t\t\t\"Address,Version,Data Center,Rack,Created At\\n\" +\n\t\t\trows.map(r => '\"' + r.address + '\",\"' + r.version + '\",\"' + r.datacenter + '\",\"' + r.rack + '\",\"' + r.created + '\"').join(\"\\n\");\n\t\t\n\t\tconst encodedUri = encodeURI(csvContent);\n\t\tconst link = document.createElement(\"a\");\n\t\tlink.setAttribute(\"href\", encodedUri);\n\t\tlink.setAttribute(\"download\", \"filers.csv\");\n\t\tdocument.body.appendChild(link);\n\t\tlink.click();\n\t\tdocument.body.removeChild(link);\n\t}\n\t</script>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -164,12 +164,17 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="progress me-2" style="width: 60px; height: 16px;">
|
||||
<div class="progress-bar" role="progressbar"
|
||||
<div class="progress-bar" role="progressbar"
|
||||
style={fmt.Sprintf("width: %d%%", calculatePercent(int(host.DiskUsage), int(host.DiskCapacity)))}>
|
||||
</div>
|
||||
</div>
|
||||
<small>{formatBytes(host.DiskUsage)}</small>
|
||||
</div>
|
||||
if host.RemoteSize > 0 {
|
||||
<div class="mt-1">
|
||||
<small class="text-muted"><i class="fas fa-cloud me-1"></i>{formatBytes(host.RemoteSize)} remote</small>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
if host.PublicURL != "" {
|
||||
@@ -186,6 +191,7 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
data-max-volumes={fmt.Sprintf("%d", host.MaxVolumes)}
|
||||
data-disk-usage={fmt.Sprintf("%d", host.DiskUsage)}
|
||||
data-disk-capacity={fmt.Sprintf("%d", host.DiskCapacity)}
|
||||
data-remote-size={fmt.Sprintf("%d", host.RemoteSize)}
|
||||
data-ec-volumes={fmt.Sprintf("%d", host.EcVolumes)}
|
||||
data-ec-shards={fmt.Sprintf("%d", host.EcShards)}
|
||||
data-last-heartbeat={host.LastHeartbeat.Format("2006-01-02 15:04:05")}>
|
||||
@@ -205,6 +211,7 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
data-max-volumes={fmt.Sprintf("%d", host.MaxVolumes)}
|
||||
data-disk-usage={fmt.Sprintf("%d", host.DiskUsage)}
|
||||
data-disk-capacity={fmt.Sprintf("%d", host.DiskCapacity)}
|
||||
data-remote-size={fmt.Sprintf("%d", host.RemoteSize)}
|
||||
data-ec-volumes={fmt.Sprintf("%d", host.EcVolumes)}
|
||||
data-ec-shards={fmt.Sprintf("%d", host.EcShards)}
|
||||
data-last-heartbeat={host.LastHeartbeat.Format("2006-01-02 15:04:05")}>
|
||||
@@ -260,6 +267,7 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
maxVolumes: parseInt(button.getAttribute('data-max-volumes')),
|
||||
diskUsage: parseInt(button.getAttribute('data-disk-usage')),
|
||||
diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),
|
||||
remoteSize: parseInt(button.getAttribute('data-remote-size')) || 0,
|
||||
ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),
|
||||
ecShards: parseInt(button.getAttribute('data-ec-shards')),
|
||||
lastHeartbeat: button.getAttribute('data-last-heartbeat')
|
||||
@@ -314,6 +322,8 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
'</div>' +
|
||||
'</td></tr>' +
|
||||
'<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +
|
||||
(server.remoteSize > 0 ?
|
||||
'<tr><td><strong>Remote Data:</strong></td><td><i class="fas fa-cloud me-1"></i>' + formatBytes(server.remoteSize) + '</td></tr>' : '') +
|
||||
'</table>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1001
|
||||
// templ: version: v0.3.1020
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumeServers))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 34, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 34, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 56, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 56, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(data.TotalCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 76, Col: 68}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 76, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -95,7 +95,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var5 templ.SafeURL
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", host.PublicURL)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 117, Col: 121}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 117, Col: 121}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -108,7 +108,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 118, Col: 65}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 118, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -126,7 +126,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var7 templ.SafeURL
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", host.Address)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 122, Col: 119}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 122, Col: 119}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -139,7 +139,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 123, Col: 65}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 123, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -157,7 +157,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 129, Col: 99}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 129, Col: 99}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -170,7 +170,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 132, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 132, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -183,7 +183,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(host.Volumes, host.MaxVolumes)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 138, Col: 139}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 138, Col: 139}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -196,7 +196,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 141, Col: 111}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 141, Col: 111}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -209,7 +209,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 145, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 145, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -227,7 +227,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 151, Col: 129}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 151, Col: 129}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -245,7 +245,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d EC volumes", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 156, Col: 127}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 156, Col: 127}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -269,7 +269,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 163, Col: 75}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 163, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -282,7 +282,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(int(host.DiskUsage), int(host.DiskCapacity))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 168, Col: 153}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 168, Col: 153}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -295,368 +295,417 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 171, Col: 83}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 171, Col: 83}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</small></div></td><td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</small></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if host.PublicURL != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
if host.RemoteSize > 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<div class=\"mt-1\"><small class=\"text-muted\"><i class=\"fas fa-cloud me-1\"></i>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(host.ID)
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.RemoteSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 180, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 175, Col: 140}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\" data-address=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, " remote</small></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if host.PublicURL != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 181, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 185, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var20)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "\" data-public-url=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" data-address=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(host.PublicURL)
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 182, Col: 87}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 186, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "\" data-datacenter=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-public-url=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.PublicURL)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 183, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 187, Col: 87}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var22)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" data-rack=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" data-datacenter=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 184, Col: 76}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 188, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" data-rack=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 185, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 189, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" data-max-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" data-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 186, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 190, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var25)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" data-disk-usage=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-max-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskUsage))
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 187, Col: 106}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 191, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" data-disk-capacity=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-disk-usage=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 188, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 192, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-ec-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" data-disk-capacity=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcVolumes))
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 189, Col: 106}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 193, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-ec-shards=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\" data-remote-size=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.RemoteSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 190, Col: 104}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 194, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" data-last-heartbeat=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 191, Col: 125}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 195, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(host.ID)
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 199, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 196, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var31)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\" data-address=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 200, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 197, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" data-public-url=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 201, Col: 85}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 205, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var33)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\" data-datacenter=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "\" data-address=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 202, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 206, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var34)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "\" data-rack=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "\" data-public-url=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 203, Col: 76}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 207, Col: 85}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var35)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "\" data-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" data-datacenter=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 204, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 208, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var36)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "\" data-max-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "\" data-rack=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var37 string
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 205, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 209, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var37)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" data-disk-usage=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "\" data-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskUsage))
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 206, Col: 106}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 210, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var38)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "\" data-disk-capacity=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\" data-max-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 207, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 211, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var39)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "\" data-ec-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "\" data-disk-usage=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var40 string
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcVolumes))
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 208, Col: 106}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 212, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var40)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\" data-ec-shards=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\" data-disk-capacity=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var41 string
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 209, Col: 104}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 213, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var41)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "\" data-last-heartbeat=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\" data-remote-size=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.RemoteSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 210, Col: 125}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 214, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var42)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 215, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var43)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var44 string
|
||||
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 216, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var44)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var45 string
|
||||
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 217, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var45)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "</td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "</td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</tbody></table></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "</tbody></table></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "<div class=\"text-center py-5\"><i class=\"fas fa-server fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volume Servers Found</h5><p class=\"text-muted\">No volume servers are currently available in the cluster.</p></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "<div class=\"text-center py-5\"><i class=\"fas fa-server fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volume Servers Found</h5><p class=\"text-muted\">No volume servers are currently available in the cluster.</p></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "</div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "</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_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
var templ_7745c5c3_Var46 string
|
||||
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 235, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 242, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</small></div></div></div><!-- JavaScript for cluster volume servers functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle volume server action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const serverData = {\n id: button.getAttribute('data-id'),\n address: button.getAttribute('data-address'),\n publicUrl: button.getAttribute('data-public-url'),\n datacenter: button.getAttribute('data-datacenter'),\n rack: button.getAttribute('data-rack'),\n volumes: parseInt(button.getAttribute('data-volumes')),\n maxVolumes: parseInt(button.getAttribute('data-max-volumes')),\n diskUsage: parseInt(button.getAttribute('data-disk-usage')),\n diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),\n ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),\n ecShards: parseInt(button.getAttribute('data-ec-shards')),\n lastHeartbeat: button.getAttribute('data-last-heartbeat')\n };\n showVolumeServerDetails(serverData);\n break;\n }\n });\n });\n \n function showVolumeServerDetails(server) {\n const volumePercent = server.maxVolumes > 0 ? Math.round((server.volumes / server.maxVolumes) * 100) : 0;\n const diskPercent = server.diskCapacity > 0 ? Math.round((server.diskUsage / server.diskCapacity) * 100) : 0;\n \n const modalHtml = '<div class=\"modal fade\" id=\"volumeServerDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-server me-2\"></i>Volume Server Details: ' + server.address + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Server ID:</strong></td><td><code>' + server.id + '</code></td></tr>' +\n '<tr><td><strong>Address:</strong></td><td>' + server.address + '</td></tr>' +\n '<tr><td><strong>Public URL:</strong></td><td>' + server.publicUrl + '</td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.datacenter + '</span></td></tr>' +\n '<tr><td><strong>Rack:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.rack + '</span></td></tr>' +\n '<tr><td><strong>Last Heartbeat:</strong></td><td>' + server.lastHeartbeat + '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Usage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + volumePercent + '%\"></div>' +\n '</div>' +\n '<span>' + server.volumes + '/' + server.maxVolumes + ' (' + volumePercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Disk Usage:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + diskPercent + '%\"></div>' +\n '</div>' +\n '<span>' + formatBytes(server.diskUsage) + '/' + formatBytes(server.diskCapacity) + ' (' + diskPercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +\n '</table>' +\n '</div>' +\n '</div>' +\n \n Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "</small></div></div></div><!-- JavaScript for cluster volume servers functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle volume server action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const serverData = {\n id: button.getAttribute('data-id'),\n address: button.getAttribute('data-address'),\n publicUrl: button.getAttribute('data-public-url'),\n datacenter: button.getAttribute('data-datacenter'),\n rack: button.getAttribute('data-rack'),\n volumes: parseInt(button.getAttribute('data-volumes')),\n maxVolumes: parseInt(button.getAttribute('data-max-volumes')),\n diskUsage: parseInt(button.getAttribute('data-disk-usage')),\n diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),\n remoteSize: parseInt(button.getAttribute('data-remote-size')) || 0,\n ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),\n ecShards: parseInt(button.getAttribute('data-ec-shards')),\n lastHeartbeat: button.getAttribute('data-last-heartbeat')\n };\n showVolumeServerDetails(serverData);\n break;\n }\n });\n });\n \n function showVolumeServerDetails(server) {\n const volumePercent = server.maxVolumes > 0 ? Math.round((server.volumes / server.maxVolumes) * 100) : 0;\n const diskPercent = server.diskCapacity > 0 ? Math.round((server.diskUsage / server.diskCapacity) * 100) : 0;\n \n const modalHtml = '<div class=\"modal fade\" id=\"volumeServerDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-server me-2\"></i>Volume Server Details: ' + server.address + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Server ID:</strong></td><td><code>' + server.id + '</code></td></tr>' +\n '<tr><td><strong>Address:</strong></td><td>' + server.address + '</td></tr>' +\n '<tr><td><strong>Public URL:</strong></td><td>' + server.publicUrl + '</td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.datacenter + '</span></td></tr>' +\n '<tr><td><strong>Rack:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.rack + '</span></td></tr>' +\n '<tr><td><strong>Last Heartbeat:</strong></td><td>' + server.lastHeartbeat + '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Usage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + volumePercent + '%\"></div>' +\n '</div>' +\n '<span>' + server.volumes + '/' + server.maxVolumes + ' (' + volumePercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Disk Usage:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + diskPercent + '%\"></div>' +\n '</div>' +\n '<span>' + formatBytes(server.diskUsage) + '/' + formatBytes(server.diskCapacity) + ' (' + diskPercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +\nLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -400,7 +400,12 @@ templ ClusterVolumes(data dash.ClusterVolumesData) {
|
||||
</td>
|
||||
if data.ShowDiskTypeColumn {
|
||||
<td>
|
||||
<span class="badge bg-primary">{volume.DiskType}</span>
|
||||
<span class="badge bg-primary">{displayDiskType(volume.DiskType)}</span>
|
||||
if volume.RemoteStorageName != "" {
|
||||
<span class="badge bg-info text-white ms-1" title={volume.RemoteStorageKey}>
|
||||
<i class="fas fa-cloud me-1"></i>{volume.RemoteStorageName}
|
||||
</span>
|
||||
}
|
||||
</td>
|
||||
}
|
||||
if data.ShowVersionColumn {
|
||||
@@ -683,14 +688,18 @@ func countUniqueRacks(volumes []dash.VolumeWithTopology) int {
|
||||
return len(rackMap)
|
||||
}
|
||||
|
||||
// displayDiskType maps the empty disk type to its display name.
|
||||
func displayDiskType(diskType string) string {
|
||||
if diskType == "" {
|
||||
return "hdd"
|
||||
}
|
||||
return diskType
|
||||
}
|
||||
|
||||
func countUniqueDiskTypes(volumes []dash.VolumeWithTopology) int {
|
||||
diskTypeMap := make(map[string]bool)
|
||||
for _, volume := range volumes {
|
||||
diskType := volume.DiskType
|
||||
if diskType == "" {
|
||||
diskType = "hdd"
|
||||
}
|
||||
diskTypeMap[diskType] = true
|
||||
diskTypeMap[displayDiskType(volume.DiskType)] = true
|
||||
}
|
||||
return len(diskTypeMap)
|
||||
}
|
||||
|
||||
Loaded 100 of 474 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user