mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da2fd1321e | ||
|
|
4e853efeb9 | ||
|
|
81c90cb446 | ||
|
|
4c2c0ff21c | ||
|
|
1d2d9dfed2 | ||
|
|
c4d743a69f | ||
|
|
fcd28031e7 | ||
|
|
34c7bd03ad | ||
|
|
18f9d9a0b6 | ||
|
|
52e05ccda4 | ||
|
|
514c0c1e99 | ||
|
|
8841eb6c70 | ||
|
|
59cccc788c | ||
|
|
9e7fd2eb90 | ||
|
|
d6a68468ad | ||
|
|
b0e6f7a096 | ||
|
|
de02158212 | ||
|
|
8844d9823f | ||
|
|
3e5aa8c3b3 | ||
|
|
5700aa5e91 | ||
|
|
9281ed8007 | ||
|
|
fd3b437e04 | ||
|
|
689ea6ea3e | ||
|
|
be081b49b7 | ||
|
|
fb3fb9dcb8 | ||
|
|
7a9a9f10af | ||
|
|
ecd778a4a0 | ||
|
|
6a34d82f05 | ||
|
|
b86b2f3cee | ||
|
|
57a122fbcf | ||
|
|
5e01caa522 | ||
|
|
a1b3131bf6 | ||
|
|
aba0cb7b2a | ||
|
|
81e0859c12 | ||
|
|
0d00e92178 | ||
|
|
8541f959a9 | ||
|
|
673d1a02e0 | ||
|
|
6e8a2cdb14 | ||
|
|
cd562b8514 | ||
|
|
617599859b | ||
|
|
ce4c1fe31e | ||
|
|
462e4445e2 | ||
|
|
0d4e11a6e5 | ||
|
|
85f2f9d2d4 | ||
|
|
679835e4fc | ||
|
|
3810fb1123 | ||
|
|
12d0537215 | ||
|
|
b2817e853d | ||
|
|
1e0f571e75 |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
name: Clean up stale SeaweedFS test mounts
|
||||
description: Detach disconnected FUSE test mounts left by earlier jobs on a shared runner.
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Unmount disconnected SeaweedFS test mounts
|
||||
if: runner.os == 'Linux' && runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
env:
|
||||
CLEANUP_SCRIPT: ${{ github.action_path }}/cleanup.py
|
||||
run: python3 "$CLEANUP_SCRIPT"
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Detach disconnected SeaweedFS integration-test mounts without touching live ones."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def test_mounts(mountinfo):
|
||||
"""Read the kernel table directly: traversing a stale mount may block."""
|
||||
roots = {tempfile.gettempdir(), "/tmp", "/var/tmp"}
|
||||
for line in mountinfo.splitlines():
|
||||
fields, filesystem = line.split(" - ", 1)
|
||||
if filesystem.split()[0].split(".")[0] != "fuse":
|
||||
continue
|
||||
fields = fields.split()
|
||||
# mountinfo escapes whitespace and backslashes with octal sequences.
|
||||
target = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields[4])
|
||||
path = Path(target)
|
||||
# Test mounts are a mount* leaf under a seaweedfs_fuse_* scratch dir
|
||||
# (seaweedfs_fuse_test_*/mount, seaweedfs_fuse_failover_*/mount0, ...)
|
||||
# or the posix-compliance workflow's fixed /tmp/seaweedfs/mount.
|
||||
if (not path.name.startswith("mount")
|
||||
or str(path.parent.parent) not in roots
|
||||
or not (path.parent.name.startswith("seaweedfs_fuse")
|
||||
or path.parent.name == "seaweedfs")):
|
||||
continue
|
||||
yield fields[0], target
|
||||
|
||||
|
||||
def mounted(mount_id, target):
|
||||
return (mount_id, target) in test_mounts(Path("/proc/self/mountinfo").read_text())
|
||||
|
||||
|
||||
def cleanup():
|
||||
failed = False
|
||||
for mount_id, target in test_mounts(Path("/proc/self/mountinfo").read_text()):
|
||||
try:
|
||||
# A separate, bounded probe prevents a wedged FUSE daemon from
|
||||
# hanging cleanup. Only ENOTCONN proves the daemon disconnected;
|
||||
# a timeout or another error is not enough to detach a live mount.
|
||||
probe = subprocess.run(
|
||||
[sys.executable, __file__, "--probe", target], timeout=5,
|
||||
capture_output=True, check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
print(f"::warning::FUSE probe timed out; leaving {target} mounted")
|
||||
continue
|
||||
if probe.returncode != errno.ENOTCONN or not mounted(mount_id, target):
|
||||
continue
|
||||
|
||||
print(f"Unmounting disconnected FUSE test mount: {target}", flush=True)
|
||||
# Lazy unmount detaches a dead mount even when an old process still
|
||||
# holds it open. Prefer the unprivileged FUSE helper; sudo is fallback.
|
||||
for command in (
|
||||
["fusermount3", "-uz", "--", target],
|
||||
["fusermount", "-uz", "--", target],
|
||||
["sudo", "-n", "umount", "-l", "--", target],
|
||||
):
|
||||
try:
|
||||
subprocess.run(command, timeout=10, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
print(f"{command[0]}: {error}", file=sys.stderr)
|
||||
if not mounted(mount_id, target):
|
||||
break
|
||||
else:
|
||||
print(f"::error::Could not unmount disconnected FUSE test mount: {target}")
|
||||
failed = True
|
||||
continue
|
||||
# The detached mount's parent still holds the crashed run's data and
|
||||
# logs; test_mounts only yields targets under a SeaweedFS test dir in
|
||||
# a temp root, so the parent is safe to reclaim here.
|
||||
shutil.rmtree(Path(target).parent, ignore_errors=True)
|
||||
return int(failed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--probe":
|
||||
try:
|
||||
os.stat(sys.argv[2])
|
||||
except OSError as error:
|
||||
sys.exit(error.errno)
|
||||
sys.exit(0)
|
||||
sys.exit(cleanup())
|
||||
@@ -0,0 +1,137 @@
|
||||
import errno
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
spec = importlib.util.spec_from_file_location("cleanup", Path(__file__).with_name("cleanup.py"))
|
||||
cleanup = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(cleanup)
|
||||
|
||||
TARGET = "/tmp/seaweedfs_fuse_test_123/mount"
|
||||
MOUNTINFO = f"42 1 0:9 / {TARGET} rw - fuse.seaweedfs seaweedfs rw\n"
|
||||
|
||||
|
||||
class CleanupTests(unittest.TestCase):
|
||||
def run_cleanup(self, results, mounted=True):
|
||||
with patch.object(cleanup.Path, "read_text", return_value=MOUNTINFO), \
|
||||
patch.object(cleanup, "mounted", side_effect=mounted if isinstance(mounted, list) else None,
|
||||
return_value=mounted) as check, \
|
||||
patch.object(cleanup.shutil, "rmtree") as rmtree, \
|
||||
patch.object(cleanup.subprocess, "run", side_effect=results) as run:
|
||||
status = cleanup.cleanup()
|
||||
return status, run, check, rmtree
|
||||
|
||||
def result(self, status):
|
||||
return subprocess.CompletedProcess([], status)
|
||||
|
||||
def test_only_fuse_integration_test_mounts_are_candidates(self):
|
||||
rows = MOUNTINFO
|
||||
rows += MOUNTINFO.replace("fuse.seaweedfs", "ext4")
|
||||
rows += MOUNTINFO.replace(TARGET, "/mnt/production")
|
||||
rows += MOUNTINFO.replace(TARGET, "/tmp/seaweedfs_fuse_test_123/data")
|
||||
rows += MOUNTINFO.replace(TARGET, "/home/user/seaweedfs_fuse_test_123/mount")
|
||||
rows += MOUNTINFO.replace(TARGET, "/tmp/seaweedfs/data")
|
||||
self.assertEqual(list(cleanup.test_mounts(rows)), [("42", TARGET)])
|
||||
|
||||
def test_all_test_mount_layouts_are_candidates(self):
|
||||
targets = (
|
||||
"/tmp/seaweedfs_fuse_test_123/mount",
|
||||
"/tmp/seaweedfs_fuse_failover_456/mount0",
|
||||
"/tmp/seaweedfs_fuse_failover_456/mount1",
|
||||
"/var/tmp/seaweedfs_fuse_p2p_test_789/mount2",
|
||||
"/tmp/seaweedfs/mount",
|
||||
)
|
||||
rows = "".join(
|
||||
MOUNTINFO.replace("42", str(40 + i)).replace(TARGET, target)
|
||||
for i, target in enumerate(targets)
|
||||
)
|
||||
self.assertEqual(
|
||||
list(cleanup.test_mounts(rows)),
|
||||
[(str(40 + i), target) for i, target in enumerate(targets)],
|
||||
)
|
||||
|
||||
def test_mountinfo_paths_are_unescaped_once(self):
|
||||
target = "/tmp/seaweedfs_fuse_test_space and\\slash/mount"
|
||||
encoded = target.replace("\\", r"\134").replace(" ", r"\040")
|
||||
rows = MOUNTINFO.replace(TARGET, encoded)
|
||||
self.assertEqual(list(cleanup.test_mounts(rows)), [("42", target)])
|
||||
|
||||
def test_no_mounts_is_a_noop(self):
|
||||
with patch.object(cleanup.Path, "read_text", return_value=""), \
|
||||
patch.object(cleanup.subprocess, "run") as run:
|
||||
self.assertEqual(cleanup.cleanup(), 0)
|
||||
run.assert_not_called()
|
||||
|
||||
def test_healthy_mount_is_untouched(self):
|
||||
status, run, _, _ = self.run_cleanup([self.result(0)])
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
def test_other_probe_errors_are_untouched(self):
|
||||
for error in (errno.EACCES, errno.ENOENT, errno.EIO):
|
||||
with self.subTest(error=error):
|
||||
status, run, _, _ = self.run_cleanup([self.result(error)])
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
def test_probe_timeout_does_not_detach_a_possibly_live_mount(self):
|
||||
status, run, _, _ = self.run_cleanup([subprocess.TimeoutExpired("probe", 5)])
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
def test_disconnected_mount_is_lazily_unmounted(self):
|
||||
status, run, _, _ = self.run_cleanup([self.result(errno.ENOTCONN), self.result(0)], [True, False])
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(run.call_args_list[1].args[0], ["fusermount3", "-uz", "--", TARGET])
|
||||
self.assertEqual(run.call_args_list[0].kwargs["timeout"], 5)
|
||||
self.assertEqual(run.call_args_list[1].kwargs["timeout"], 10)
|
||||
|
||||
def test_replaced_or_removed_mount_is_untouched(self):
|
||||
status, run, _, _ = self.run_cleanup([self.result(errno.ENOTCONN)], False)
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
def test_mount_identity_is_checked_without_stat(self):
|
||||
with patch.object(cleanup.Path, "read_text", return_value=MOUNTINFO):
|
||||
self.assertTrue(cleanup.mounted("42", TARGET))
|
||||
self.assertFalse(cleanup.mounted("43", TARGET))
|
||||
|
||||
def test_missing_or_timed_out_helper_uses_fallback(self):
|
||||
for error in (FileNotFoundError(), subprocess.TimeoutExpired("fusermount3", 10)):
|
||||
with self.subTest(error=error):
|
||||
status, run, _, _ = self.run_cleanup(
|
||||
[self.result(errno.ENOTCONN), error, self.result(0)], [True, True, False])
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(run.call_args.args[0], ["fusermount", "-uz", "--", TARGET])
|
||||
|
||||
def test_failed_helpers_fall_back_to_sudo(self):
|
||||
status, run, _, _ = self.run_cleanup(
|
||||
[self.result(errno.ENOTCONN), self.result(1), self.result(1), self.result(0)],
|
||||
[True, True, True, False])
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(run.call_args.args[0], ["sudo", "-n", "umount", "-l", "--", TARGET])
|
||||
|
||||
def test_cleanup_fails_when_stale_mount_remains(self):
|
||||
status, run, _, rmtree = self.run_cleanup(
|
||||
[self.result(errno.ENOTCONN), self.result(1), self.result(1), self.result(1)])
|
||||
self.assertEqual(status, 1)
|
||||
self.assertEqual(run.call_count, 4)
|
||||
rmtree.assert_not_called()
|
||||
|
||||
def test_unmounted_test_dir_is_reclaimed(self):
|
||||
status, _, _, rmtree = self.run_cleanup(
|
||||
[self.result(errno.ENOTCONN), self.result(0)], [True, False])
|
||||
self.assertEqual(status, 0)
|
||||
rmtree.assert_called_once_with(Path(TARGET).parent, ignore_errors=True)
|
||||
|
||||
def test_probe_process_reports_errno(self):
|
||||
for target, expected in ((str(Path(__file__)), 0), (str(Path(__file__) / "absent"), errno.ENOTDIR)):
|
||||
with self.subTest(target=target):
|
||||
result = subprocess.run([cleanup.sys.executable, cleanup.__file__, "--probe", target], check=False)
|
||||
self.assertEqual(result.returncode, expected)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -23,8 +23,14 @@ runs:
|
||||
|
||||
bin=$(command -v fusermount3 || true)
|
||||
if [ -z "$bin" ]; then
|
||||
echo "no fusermount3 in PATH" >&2
|
||||
exit 1
|
||||
# Self-hosted runners are not guaranteed to carry fuse3.
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y fuse3
|
||||
bin=$(command -v fusermount3 || true)
|
||||
if [ -z "$bin" ]; then
|
||||
echo "no fusermount3 in PATH after installing fuse3" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if can_mount "$bin"; then
|
||||
ls -l "$bin"
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
name: "actions: unit tests"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- '.github/actions/**'
|
||||
- '.github/workflows/action-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- '.github/actions/**'
|
||||
- '.github/workflows/action-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
cleanup-stale-fuse-mounts:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Run cleanup action unit tests
|
||||
run: python3 .github/actions/cleanup-stale-fuse-mounts/test_cleanup.py
|
||||
@@ -25,6 +25,12 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.39.0
|
||||
|
||||
@@ -170,10 +170,13 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_ref || github.ref }}
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Free Disk Space
|
||||
run: |
|
||||
echo "Available disk space before cleanup:"
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
# Remove pre-installed tools
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
|
||||
# Clean package managers
|
||||
@@ -185,7 +188,7 @@ jobs:
|
||||
[ -d ~/.cache/go-build ] && rm -rf ~/.cache/go-build || true
|
||||
[ -d /go/pkg ] && rm -rf /go/pkg || true
|
||||
echo "Available disk space after cleanup:"
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
|
||||
- name: Configure variant
|
||||
id: config
|
||||
|
||||
@@ -25,7 +25,7 @@ on:
|
||||
rocksdb_version:
|
||||
description: 'RocksDB git tag to use when variant=rocksdb'
|
||||
required: false
|
||||
default: 'v10.10.1'
|
||||
default: 'v11.1.2'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -180,6 +180,10 @@ jobs:
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Download pre-built Rust binaries
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -219,7 +223,7 @@ jobs:
|
||||
sudo docker system prune -af --volumes
|
||||
[ -d ~/.cache/go-build ] && rm -rf ~/.cache/go-build || true
|
||||
[ -d /go/pkg ] && rm -rf /go/pkg || true
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
|
||||
- name: Docker meta
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
@@ -271,8 +275,11 @@ jobs:
|
||||
file: ${{ matrix.dockerfile }}
|
||||
platforms: ${{ matrix.platform }}
|
||||
labels: ${{ steps.docker_meta.outputs.labels }}
|
||||
# Flat single-platform manifest so imagetools create assembles cleanly.
|
||||
provenance: false
|
||||
# mode=max keeps resolvedDependencies complete and records the
|
||||
# builder identity; attestations ride inside each pushed index and
|
||||
# survive the imagetools merge into the multi-arch manifest.
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=gha,scope=${{ matrix.variant }}-${{ matrix.arch }}
|
||||
# max only for rocksdb: its RocksDB compile is sha-independent and worth
|
||||
@@ -282,7 +289,7 @@ jobs:
|
||||
${{ matrix.build_args }}
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
BRANCH=${{ github.sha }}
|
||||
${{ matrix.variant == 'rocksdb' && format('ROCKSDB_VERSION={0}', github.event.inputs.rocksdb_version || 'v10.10.1') || '' }}
|
||||
${{ matrix.variant == 'rocksdb' && format('ROCKSDB_VERSION={0}', github.event.inputs.rocksdb_version || 'v11.1.2') || '' }}
|
||||
|
||||
- name: Export digest
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
@@ -308,6 +315,8 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
packages: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -415,6 +424,45 @@ jobs:
|
||||
${{ env.IMAGE }}@${{ steps.manifest.outputs.digest }}
|
||||
chrislusf/seaweedfs@${{ steps.manifest.outputs.digest }}
|
||||
|
||||
# Attest the merged multi-arch digest itself, so digest-pinning consumers
|
||||
# can verify provenance against the exact index they pull. Both steps
|
||||
# reuse the GHCR login above and push as OCI referrers.
|
||||
- name: Attest build provenance for ${{ matrix.variant }}
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: actions/attest-build-provenance@v4
|
||||
with:
|
||||
subject-name: ${{ env.IMAGE }}
|
||||
subject-digest: ${{ steps.manifest.outputs.digest }}
|
||||
push-to-registry: true
|
||||
|
||||
# SBOMs are generated and attested per platform manifest: an index-wide
|
||||
# scan only describes syft's default platform, while the manifests it
|
||||
# merges differ (some ship the real binary, others placeholders), so the
|
||||
# SBOM has to be bound to the platform digest a consumer actually pulls.
|
||||
- name: Install syft
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: anchore/sbom-action/download-syft@v0
|
||||
|
||||
- name: Attest per-platform SBOMs for ${{ matrix.variant }}
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
working-directory: /tmp/digests
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for f in *; do
|
||||
# Each saved digest is an OCI index (image + attestation manifests);
|
||||
# scan and attest the image manifest a same-platform pull resolves.
|
||||
ref="${{ env.IMAGE }}@sha256:${f}"
|
||||
image=$(crane manifest "$ref" | jq -r '
|
||||
[.manifests[]? | select((.annotations["vnd.docker.reference.type"] // "") != "attestation-manifest"
|
||||
and (.platform.os // "unknown") != "unknown") | .digest][0] // empty')
|
||||
ref="${{ env.IMAGE }}@${image:-sha256:${f}}"
|
||||
syft "registry:${ref}" -o "spdx-json=/tmp/sbom-${f}.spdx.json"
|
||||
cosign attest --yes \
|
||||
--predicate "/tmp/sbom-${f}.spdx.json" \
|
||||
--type spdxjson \
|
||||
"$ref"
|
||||
done
|
||||
|
||||
# Report-only trivy scan: uploads fixable HIGH/CRITICAL findings to GitHub
|
||||
# Security for visibility, but never blocks the release. Releases (including
|
||||
# `latest`) ship regardless — vulnerabilities are tracked, not gated, since
|
||||
@@ -453,7 +501,9 @@ jobs:
|
||||
scanners: vuln
|
||||
vuln-type: os,library
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
# Keep unfixed findings in the report so digest-pinning consumers see
|
||||
# the complete picture, not just what a patch could resolve.
|
||||
ignore-unfixed: false
|
||||
limit-severities-for-sarif: true
|
||||
format: sarif
|
||||
output: trivy-results.sarif
|
||||
|
||||
@@ -4,9 +4,9 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
rocksdb_version:
|
||||
description: 'RocksDB git tag or branch to build (e.g. v10.10.1)'
|
||||
description: 'RocksDB git tag or branch to build (e.g. v11.1.2)'
|
||||
required: true
|
||||
default: 'v10.10.1'
|
||||
default: 'v11.1.2'
|
||||
seaweedfs_ref:
|
||||
description: 'SeaweedFS git tag, branch, or commit to build'
|
||||
required: true
|
||||
|
||||
@@ -42,6 +42,9 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
|
||||
@@ -41,6 +41,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
|
||||
@@ -60,6 +60,7 @@ jobs:
|
||||
# Start SeaweedFS with optimized settings for CI
|
||||
# Include S3 API for s3copier integration tests
|
||||
weed server -dir="$WEED_DATA_DIR" \
|
||||
-ip=127.0.0.1 -ip.bind=127.0.0.1 \
|
||||
-master.raftHashicorp \
|
||||
-master.electionTimeout=1s \
|
||||
-master.volumeSizeLimitMB=100 \
|
||||
|
||||
@@ -41,13 +41,20 @@ jobs:
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
|
||||
- name: Start local Docker registry
|
||||
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
|
||||
run: |
|
||||
if ! docker start registry 2>/dev/null; then
|
||||
docker rm -f registry >/dev/null 2>&1 || true
|
||||
docker run -d --restart=always -p 5000:5000 --name registry registry:2
|
||||
fi
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
driver-opts: network=host
|
||||
|
||||
- name: Set up Docker Compose
|
||||
uses: docker/setup-compose-action@v2
|
||||
|
||||
- name: Build weed race binary
|
||||
run: |
|
||||
cd docker
|
||||
|
||||
@@ -58,6 +58,9 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go ${{ env.GO_VERSION }}
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -393,7 +396,7 @@ jobs:
|
||||
echo "" >> reports/debug/system_info.txt
|
||||
|
||||
echo "Disk Space" >> reports/debug/system_info.txt
|
||||
df -h >> reports/debug/system_info.txt
|
||||
timeout 15 df -h >> reports/debug/system_info.txt || true
|
||||
echo "" >> reports/debug/system_info.txt
|
||||
|
||||
echo "Memory Information" >> reports/debug/system_info.txt
|
||||
|
||||
@@ -32,6 +32,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -51,7 +54,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Filer Group Tests ==="
|
||||
|
||||
# Run tests with automatic server management
|
||||
|
||||
@@ -4,6 +4,7 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/remote_storage/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'test/s3/**'
|
||||
@@ -35,6 +36,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -54,7 +58,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Tests ==="
|
||||
|
||||
# Run tests with automatic server management
|
||||
@@ -201,6 +205,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -220,7 +227,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Tests ==="
|
||||
|
||||
# Run tests with automatic server management
|
||||
@@ -339,6 +346,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -358,7 +368,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Tests ==="
|
||||
make test-with-server
|
||||
|
||||
@@ -398,6 +408,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -417,7 +430,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Tests ==="
|
||||
|
||||
# Run tests with automatic server management
|
||||
|
||||
@@ -91,6 +91,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -111,7 +114,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting S3 IAM Integration Tests (${{ matrix.test-type }}) ==="
|
||||
|
||||
# Set WEED_BINARY to use the installed version
|
||||
|
||||
@@ -37,6 +37,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -57,7 +60,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting S3 Keycloak Integration Tests ==="
|
||||
|
||||
# Set WEED_BINARY to use the installed version
|
||||
|
||||
@@ -89,6 +89,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -108,7 +111,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
|
||||
echo "=== Starting S3 Policy Variables Integration Tests ==="
|
||||
|
||||
@@ -199,6 +202,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -218,7 +224,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
|
||||
echo "=== Starting S3 Policy Enforcement Tests (${{ matrix.test-case }}) ==="
|
||||
|
||||
|
||||
@@ -27,6 +27,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -57,7 +60,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting S3 Spark Integration Tests ==="
|
||||
|
||||
go test -v -timeout 30m . 2>&1 | tee test-output.log || {
|
||||
|
||||
@@ -46,6 +46,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -65,7 +68,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting SSE Tests ==="
|
||||
|
||||
# Run tests with automatic server management
|
||||
|
||||
@@ -30,6 +30,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -53,7 +56,8 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
# A stale FUSE mount can hang or fail df; keep diagnostics best effort.
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting S3 Tables Tests ==="
|
||||
|
||||
# Run S3 Tables integration tests
|
||||
@@ -91,6 +95,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -115,7 +122,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Iceberg Catalog Tests ==="
|
||||
|
||||
# Run Iceberg catalog integration tests using Makefile (handles build)
|
||||
@@ -153,6 +160,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -186,7 +196,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Trino Iceberg Catalog Tests ==="
|
||||
|
||||
# Run Trino + Iceberg catalog integration tests
|
||||
@@ -224,6 +234,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -258,7 +271,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting Dremio Iceberg Catalog Tests ==="
|
||||
|
||||
@@ -298,6 +311,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -332,7 +348,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting Doris Iceberg Catalog Tests ==="
|
||||
|
||||
@@ -382,6 +398,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -418,7 +437,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting ClickHouse Iceberg Catalog Tests ==="
|
||||
|
||||
@@ -470,6 +489,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -507,7 +529,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting OLake Iceberg Catalog Tests ==="
|
||||
|
||||
@@ -570,6 +592,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -602,7 +627,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Polaris Tests ==="
|
||||
|
||||
go test -v -timeout 20m ./test/s3tables/polaris 2>&1 | tee test/s3tables/polaris/test-output.log || {
|
||||
@@ -639,6 +664,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -672,7 +700,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Spark Iceberg Catalog Tests ==="
|
||||
|
||||
# Run Spark + Iceberg catalog integration tests
|
||||
@@ -710,6 +738,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -744,7 +775,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting RisingWave Catalog Tests ==="
|
||||
|
||||
# Run RisingWave catalog integration tests
|
||||
@@ -782,6 +813,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -840,7 +874,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting STS Integration Tests ==="
|
||||
|
||||
# Run STS integration tests
|
||||
@@ -878,6 +912,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -901,7 +938,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting Lakekeeper Integration Tests ==="
|
||||
|
||||
# Run Lakekeeper integration tests
|
||||
@@ -939,6 +976,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -973,7 +1013,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting Unity Catalog Tests ==="
|
||||
|
||||
@@ -1013,6 +1053,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -1046,7 +1089,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting LanceDB Namespace Tests ==="
|
||||
|
||||
@@ -1157,6 +1200,9 @@ jobs:
|
||||
# so do not leave a token in the checkout for it to pick up.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -1191,7 +1237,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting DuckDB Lance Tests ==="
|
||||
|
||||
@@ -1233,6 +1279,9 @@ jobs:
|
||||
# so do not leave a token in the checkout for it to pick up.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -1266,7 +1315,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
docker info
|
||||
echo "=== Starting Spark Lance Namespace Tests ==="
|
||||
|
||||
|
||||
@@ -58,9 +58,9 @@ jobs:
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
python3 -m pip install -r requirements.txt
|
||||
python3 -m pip install tox
|
||||
python3 -m pip install -e .
|
||||
|
||||
- name: Fix S3 tests bucket creation conflicts
|
||||
run: |
|
||||
@@ -411,9 +411,9 @@ jobs:
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
python3 -m pip install -r requirements.txt
|
||||
python3 -m pip install tox
|
||||
python3 -m pip install -e .
|
||||
|
||||
- name: Fix S3 tests bucket creation conflicts
|
||||
run: |
|
||||
@@ -582,9 +582,9 @@ jobs:
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
python3 -m pip install -r requirements.txt
|
||||
python3 -m pip install tox
|
||||
python3 -m pip install -e .
|
||||
|
||||
- name: Run S3 CORS tests
|
||||
timeout-minutes: 10
|
||||
@@ -811,9 +811,9 @@ jobs:
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
python3 -m pip install -r requirements.txt
|
||||
python3 -m pip install tox
|
||||
python3 -m pip install -e .
|
||||
|
||||
- name: Run Ceph S3 tests with SQL store
|
||||
timeout-minutes: 15
|
||||
|
||||
@@ -43,13 +43,20 @@ jobs:
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
|
||||
- name: Start local Docker registry
|
||||
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
|
||||
run: |
|
||||
if ! docker start registry 2>/dev/null; then
|
||||
docker rm -f registry >/dev/null 2>&1 || true
|
||||
docker run -d --restart=always -p 5000:5000 --name registry registry:2
|
||||
fi
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
driver-opts: network=host
|
||||
|
||||
- name: Set up Docker Compose
|
||||
uses: docker/setup-compose-action@v2
|
||||
|
||||
- name: Build weed race binary
|
||||
run: |
|
||||
cd docker
|
||||
|
||||
@@ -31,6 +31,9 @@ jobs:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Clean up stale FUSE mounts
|
||||
uses: ./.github/actions/cleanup-stale-fuse-mounts
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
@@ -50,7 +53,7 @@ jobs:
|
||||
echo "=== System Information ==="
|
||||
uname -a
|
||||
free -h
|
||||
df -h
|
||||
timeout 15 df -h || true
|
||||
echo "=== Starting TUS Tests ==="
|
||||
|
||||
# Run tests with automatic server management
|
||||
|
||||
@@ -144,3 +144,4 @@ weed_bin
|
||||
telemetry/server/telemetry-server
|
||||
.aider*
|
||||
/seaweed-volume/docs
|
||||
__pycache__/
|
||||
@@ -3,7 +3,7 @@ FROM golang:1.26 AS builder
|
||||
RUN apt-get update
|
||||
RUN apt-get install -y build-essential libsnappy-dev zlib1g-dev libbz2-dev libgflags-dev liblz4-dev libzstd-dev
|
||||
|
||||
ARG ROCKSDB_VERSION=v10.10.1
|
||||
ARG ROCKSDB_VERSION=v11.1.2
|
||||
ENV ROCKSDB_VERSION=${ROCKSDB_VERSION}
|
||||
|
||||
# build RocksDB
|
||||
|
||||
@@ -3,7 +3,7 @@ FROM golang:1.26 AS builder
|
||||
RUN apt-get update
|
||||
RUN apt-get install -y build-essential libsnappy-dev zlib1g-dev libbz2-dev libgflags-dev liblz4-dev libzstd-dev
|
||||
|
||||
ARG ROCKSDB_VERSION=v10.10.1
|
||||
ARG ROCKSDB_VERSION=v11.1.2
|
||||
ENV ROCKSDB_VERSION=${ROCKSDB_VERSION}
|
||||
|
||||
# build RocksDB
|
||||
|
||||
@@ -362,7 +362,7 @@ require (
|
||||
github.com/flynn/noise v1.1.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/geoffgarside/ber v1.2.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.3.1 // indirect
|
||||
github.com/go-chi/chi/v5 v5.4.0 // indirect
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.5 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
|
||||
@@ -483,8 +483,8 @@ github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
|
||||
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/chi/v5 v5.4.0 h1:+ufzvFTGKyin26Or5DLrlIDq4ygIDBVcj7oVNeeaYFE=
|
||||
github.com/go-chi/chi/v5 v5.4.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 h1:JnrjqG5iR07/8k7NqrLNilRsl3s1EPRQEGvbPyOce68=
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348/go.mod h1:Czxo/d1g948LtrALAZdL04TL/HnkopquAjxYUuI02bo=
|
||||
github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk=
|
||||
|
||||
+1080
-1094
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
@@ -771,7 +771,8 @@ message FilerConf {
|
||||
string replication = 3;
|
||||
string ttl = 4;
|
||||
string disk_type = 5;
|
||||
bool fsync = 6;
|
||||
// unset inherits from the enclosing path rule, set overrides it
|
||||
optional bool fsync = 6;
|
||||
uint32 volume_growth_count = 7;
|
||||
bool read_only = 8;
|
||||
string data_center = 9;
|
||||
|
||||
@@ -157,6 +157,8 @@ windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
# Paused-time tests drive the write-queue batch window deterministically.
|
||||
tokio = { version = "1", features = ["full", "test-util"] }
|
||||
# Already a transitive dependency of aws-sdk-s3 at a single locked version;
|
||||
# needed directly only for the canned HttpClient in remote_storage::s3 tests.
|
||||
aws-smithy-runtime-api = "1"
|
||||
|
||||
@@ -233,6 +233,25 @@ pub struct Cli {
|
||||
#[arg(long = "volume.allowUntrustedRemoteEndpoints", default_value_t = false)]
|
||||
pub allow_untrusted_remote_endpoints: bool,
|
||||
|
||||
/// Minimum bytes an fsync batch gathers before a drained queue flushes
|
||||
/// without waiting.
|
||||
#[arg(long = "fsyncMinBatchBytes", default_value_t = 1024 * 1024)]
|
||||
pub fsync_min_batch_bytes: u64,
|
||||
|
||||
/// Minimum requests an fsync batch gathers before a drained queue flushes
|
||||
/// without waiting.
|
||||
#[arg(long = "fsyncMinBatchRequests", default_value_t = 128)]
|
||||
pub fsync_min_batch_requests: usize,
|
||||
|
||||
/// How long a below-minimum fsync batch waits for more requests once the
|
||||
/// queue drains; 0 flushes immediately.
|
||||
#[arg(
|
||||
long = "fsyncBatchWait",
|
||||
default_value = "500us",
|
||||
value_parser = parse_go_duration
|
||||
)]
|
||||
pub fsync_batch_wait: std::time::Duration,
|
||||
|
||||
/// A file of command line options, each line in optionName=optionValue format.
|
||||
#[arg(long = "options", default_value = "")]
|
||||
pub options: String,
|
||||
@@ -308,6 +327,14 @@ pub struct VolumeServerConfig {
|
||||
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation
|
||||
/// (allows loopback / link-local / metadata hosts).
|
||||
pub allow_untrusted_remote_endpoints: bool,
|
||||
/// Minimum bytes an fsync batch gathers before a drained queue flushes
|
||||
/// without waiting.
|
||||
pub fsync_min_batch_bytes: u64,
|
||||
/// Minimum requests an fsync batch gathers before a drained queue flushes
|
||||
/// without waiting.
|
||||
pub fsync_min_batch_requests: usize,
|
||||
/// How long a below-minimum fsync batch waits for stragglers.
|
||||
pub fsync_batch_wait: std::time::Duration,
|
||||
}
|
||||
|
||||
pub use crate::storage::needle_map::NeedleMapKind;
|
||||
@@ -938,6 +965,9 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
|
||||
concurrent_download_limit: cli.concurrent_download_limit_mb as i64 * 1024 * 1024,
|
||||
inflight_upload_data_timeout: cli.inflight_upload_data_timeout,
|
||||
inflight_download_data_timeout: cli.inflight_download_data_timeout,
|
||||
fsync_min_batch_bytes: cli.fsync_min_batch_bytes,
|
||||
fsync_min_batch_requests: cli.fsync_min_batch_requests,
|
||||
fsync_batch_wait: cli.fsync_batch_wait,
|
||||
has_slow_read: cli.has_slow_read,
|
||||
read_buffer_size_mb: cli.read_buffer_size_mb,
|
||||
ldb_timeout: cli.ldb_timeout,
|
||||
|
||||
@@ -23,7 +23,7 @@ use seaweed_volume::server::request_id::GrpcRequestIdLayer;
|
||||
use seaweed_volume::server::volume_server::{
|
||||
RuntimeMetricsConfig, VolumeServerState, build_metrics_router,
|
||||
};
|
||||
use seaweed_volume::server::write_queue::WriteQueue;
|
||||
use seaweed_volume::server::write_queue::{self, WriteQueue};
|
||||
use seaweed_volume::storage::store::Store;
|
||||
use seaweed_volume::storage::types::DiskType;
|
||||
|
||||
@@ -436,7 +436,17 @@ async fn run(
|
||||
// The write queue is always on: durable (fsync) uploads go through it so
|
||||
// a batch shares one .dat/.idx sync, the way Go's per-volume async writer
|
||||
// group-commits. Non-fsync writes stay on the synchronous path.
|
||||
let wq = WriteQueue::new(state.clone(), 128);
|
||||
let min_bytes = usize::try_from(config.fsync_min_batch_bytes)
|
||||
.map_err(|_| "fsyncMinBatchBytes exceeds this platform's maximum usize value")?;
|
||||
let wq = WriteQueue::new(
|
||||
state.clone(),
|
||||
128,
|
||||
write_queue::SyncBatchOption {
|
||||
min_bytes,
|
||||
min_requests: config.fsync_min_batch_requests,
|
||||
wait: config.fsync_batch_wait,
|
||||
},
|
||||
);
|
||||
let _ = state.write_queue.set(wq);
|
||||
|
||||
// Set initial metric gauges for concurrent limits and max volumes
|
||||
|
||||
@@ -393,6 +393,9 @@ mod tests {
|
||||
fix_jpg_orientation: false,
|
||||
read_mode: ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
fsync_min_batch_bytes: 1024 * 1024,
|
||||
fsync_min_batch_requests: 128,
|
||||
fsync_batch_wait: std::time::Duration::from_micros(500),
|
||||
cpu_profile: String::new(),
|
||||
mem_profile: String::new(),
|
||||
compaction_byte_per_second: 0,
|
||||
|
||||
@@ -1519,41 +1519,78 @@ fn not_modified_response(
|
||||
etag: &str,
|
||||
last_modified_str: &Option<String>,
|
||||
) -> Option<Response> {
|
||||
// If-Modified-Since first (Go order), then If-None-Match.
|
||||
let not_modified = || {
|
||||
let mut resp = StatusCode::NOT_MODIFIED.into_response();
|
||||
resp.headers_mut()
|
||||
.insert(header::ETAG, etag.parse().unwrap());
|
||||
if let Some(lm) = last_modified_str {
|
||||
resp.headers_mut()
|
||||
.insert(header::LAST_MODIFIED, lm.parse().unwrap());
|
||||
}
|
||||
resp
|
||||
};
|
||||
|
||||
// If-Modified-Since applies only when there is no If-None-Match (RFC 9110 13.2.2).
|
||||
if headers.contains_key(header::IF_NONE_MATCH) {
|
||||
let inm = headers
|
||||
.get_all(header::IF_NONE_MATCH)
|
||||
.iter()
|
||||
.map(|v| v.to_str().unwrap_or(""))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
return etag_list_matches(&inm, etag).then(not_modified);
|
||||
}
|
||||
|
||||
if n.last_modified > 0
|
||||
&& let Some(ims_header) = headers.get(header::IF_MODIFIED_SINCE)
|
||||
&& let Ok(ims_str) = ims_header.to_str()
|
||||
&& let Some(ims_str) = headers
|
||||
.get(header::IF_MODIFIED_SINCE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
{
|
||||
// Parse HTTP date format: "Mon, 02 Jan 2006 15:04:05 GMT"
|
||||
if let Ok(ims_time) =
|
||||
chrono::NaiveDateTime::parse_from_str(ims_str, "%a, %d %b %Y %H:%M:%S GMT")
|
||||
&& (n.last_modified as i64) <= ims_time.and_utc().timestamp()
|
||||
{
|
||||
let mut resp = StatusCode::NOT_MODIFIED.into_response();
|
||||
if let Some(lm) = last_modified_str {
|
||||
resp.headers_mut()
|
||||
.insert(header::LAST_MODIFIED, lm.parse().unwrap());
|
||||
}
|
||||
// Go sets ETag after the 304 paths, so a 304 has no ETag.
|
||||
return Some(resp);
|
||||
return Some(not_modified());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(if_none_match) = headers.get(header::IF_NONE_MATCH)
|
||||
&& let Ok(inm) = if_none_match.to_str()
|
||||
&& inm == etag
|
||||
{
|
||||
let mut resp = StatusCode::NOT_MODIFIED.into_response();
|
||||
if let Some(lm) = last_modified_str {
|
||||
resp.headers_mut()
|
||||
.insert(header::LAST_MODIFIED, lm.parse().unwrap());
|
||||
}
|
||||
// Go sets ETag after the 304 paths, so a 304 has no ETag.
|
||||
return Some(resp);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Weak comparison against "*" or a comma-separated entity-tag list (RFC 9110 13.1.2).
|
||||
fn etag_list_matches(header: &str, etag: &str) -> bool {
|
||||
if header.trim() == "*" {
|
||||
return true;
|
||||
}
|
||||
let etag = etag.trim_matches('"');
|
||||
split_etag_list(header).into_iter().any(|tag| {
|
||||
let tag = tag.trim();
|
||||
let tag = tag.strip_prefix("W/").unwrap_or(tag);
|
||||
// Empty list elements are ignored, so padding like a trailing
|
||||
// comma cannot match an empty opaque tag.
|
||||
!tag.is_empty() && tag.trim_matches('"') == etag
|
||||
})
|
||||
}
|
||||
|
||||
/// Splits an entity-tag list on the commas between tags; a comma inside a
|
||||
/// quoted opaque tag does not split.
|
||||
fn split_etag_list(header: &str) -> Vec<&str> {
|
||||
let mut tags = Vec::new();
|
||||
let (mut start, mut quoted) = (0, false);
|
||||
for (i, b) in header.bytes().enumerate() {
|
||||
match b {
|
||||
b'"' => quoted = !quoted,
|
||||
b',' if !quoted => {
|
||||
tags.push(&header[start..i]);
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
tags.push(&header[start..]);
|
||||
tags
|
||||
}
|
||||
|
||||
/// The 200 reply headers, and the extension, which falls back to the stored name's.
|
||||
fn read_response_headers(
|
||||
n: &Needle,
|
||||
@@ -5644,6 +5681,80 @@ mod tests {
|
||||
delete_handler(State(state.clone()), request).await.status()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_modified_checks_if_none_match_first() {
|
||||
let n = Needle {
|
||||
last_modified: 1700000000,
|
||||
..Needle::default()
|
||||
};
|
||||
let (etag, last_modified_str) = etag_and_last_modified(&n);
|
||||
let bare = n.etag();
|
||||
let before = "Tue, 14 Nov 2023 22:12:20 GMT".to_string();
|
||||
let after = "Tue, 14 Nov 2023 22:14:20 GMT".to_string();
|
||||
|
||||
let cases: Vec<(Vec<(axum::http::HeaderName, String)>, bool)> = vec![
|
||||
(vec![(header::IF_NONE_MATCH, format!("\"{bare}\""))], true),
|
||||
(vec![(header::IF_NONE_MATCH, format!("W/\"{bare}\""))], true),
|
||||
(
|
||||
vec![(header::IF_NONE_MATCH, format!("\"x\", \"{bare}\""))],
|
||||
true,
|
||||
),
|
||||
(vec![(header::IF_NONE_MATCH, "*".into())], true),
|
||||
(vec![(header::IF_NONE_MATCH, "\"x\"".into())], false),
|
||||
(
|
||||
vec![
|
||||
(header::IF_NONE_MATCH, "\"x\"".into()),
|
||||
(header::IF_NONE_MATCH, format!("\"{bare}\"")),
|
||||
],
|
||||
true,
|
||||
),
|
||||
(
|
||||
vec![(header::IF_NONE_MATCH, format!("\"{bare},old\""))],
|
||||
false,
|
||||
),
|
||||
(
|
||||
vec![(header::IF_NONE_MATCH, format!("\"x\",,\"{bare}\""))],
|
||||
true,
|
||||
),
|
||||
(
|
||||
vec![
|
||||
(header::IF_NONE_MATCH, "\"x\"".into()),
|
||||
(header::IF_MODIFIED_SINCE, after.clone()),
|
||||
],
|
||||
false,
|
||||
),
|
||||
(
|
||||
vec![
|
||||
(header::IF_NONE_MATCH, "".into()),
|
||||
(header::IF_MODIFIED_SINCE, after.clone()),
|
||||
],
|
||||
false,
|
||||
),
|
||||
(vec![(header::IF_MODIFIED_SINCE, after)], true),
|
||||
(vec![(header::IF_MODIFIED_SINCE, before)], false),
|
||||
];
|
||||
for (pairs, want) in cases {
|
||||
let mut headers = HeaderMap::new();
|
||||
for (name, value) in &pairs {
|
||||
headers.append(name, value.parse().unwrap());
|
||||
}
|
||||
assert_eq!(
|
||||
not_modified_response(&n, &headers, &etag, &last_modified_str).is_some(),
|
||||
want,
|
||||
"{pairs:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::IF_NONE_MATCH,
|
||||
format!("\"{bare}\"").parse().unwrap(),
|
||||
);
|
||||
let resp = not_modified_response(&n, &headers, &etag, &last_modified_str).unwrap();
|
||||
assert!(resp.headers().contains_key(header::ETAG));
|
||||
assert!(resp.headers().contains_key(header::LAST_MODIFIED));
|
||||
}
|
||||
|
||||
/// A GET whose needle read is parked must not hold the store lock: a
|
||||
/// writer, here a real append to the same volume, must get through.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
@@ -7308,6 +7419,7 @@ mod tests {
|
||||
.set(crate::server::write_queue::WriteQueue::new(
|
||||
state.clone(),
|
||||
128,
|
||||
crate::server::write_queue::SyncBatchOption::default(),
|
||||
))
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
@@ -132,6 +132,9 @@ mod tests {
|
||||
fix_jpg_orientation: false,
|
||||
read_mode: ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
fsync_min_batch_bytes: 1024 * 1024,
|
||||
fsync_min_batch_requests: 128,
|
||||
fsync_batch_wait: std::time::Duration::from_micros(500),
|
||||
cpu_profile: String::new(),
|
||||
mem_profile: String::new(),
|
||||
compaction_byte_per_second: 0,
|
||||
|
||||
@@ -56,6 +56,27 @@ const MAX_CONCURRENT_VOLUME_WRITES: usize = 8;
|
||||
/// retirement is the volume leaving the store.
|
||||
const IDLE_WORKER_POLL: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// Tunes the per-volume durable-write worker. Once the queue drains with the
|
||||
/// batch still below min_bytes and min_requests, the batch stays open up to
|
||||
/// wait for stragglers instead of paying an fsync per request. Mirrors Go's
|
||||
/// storage.SyncBatchOption.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct SyncBatchOption {
|
||||
pub min_bytes: usize,
|
||||
pub min_requests: usize,
|
||||
pub wait: std::time::Duration,
|
||||
}
|
||||
|
||||
impl Default for SyncBatchOption {
|
||||
fn default() -> Self {
|
||||
SyncBatchOption {
|
||||
min_bytes: 1024 * 1024,
|
||||
min_requests: MAX_BATCH_SIZE,
|
||||
wait: std::time::Duration::from_micros(500),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle for submitting write requests to the per-volume workers.
|
||||
#[derive(Clone)]
|
||||
pub struct WriteQueue {
|
||||
@@ -67,23 +88,35 @@ pub struct WriteQueue {
|
||||
/// alone would multiply the old single queue's capacity by volume count.
|
||||
queue_permits: Arc<Semaphore>,
|
||||
workers: Arc<Mutex<HashMap<VolumeId, mpsc::Sender<WriteRequest>>>>,
|
||||
sync_batch: SyncBatchOption,
|
||||
/// Submissions accepted, for tests asserting which writes route here.
|
||||
#[cfg(test)]
|
||||
submits: Arc<std::sync::atomic::AtomicU64>,
|
||||
/// Times a worker armed the straggler window, for tests that must land a
|
||||
/// write inside an already-open batch.
|
||||
#[cfg(test)]
|
||||
windows_armed: Arc<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
impl WriteQueue {
|
||||
/// Create a new write queue. Per-volume workers are spawned lazily on the
|
||||
/// first submission for that volume.
|
||||
pub fn new(state: Arc<VolumeServerState>, capacity: usize) -> Self {
|
||||
pub fn new(
|
||||
state: Arc<VolumeServerState>,
|
||||
capacity: usize,
|
||||
sync_batch: SyncBatchOption,
|
||||
) -> Self {
|
||||
WriteQueue {
|
||||
state,
|
||||
capacity,
|
||||
io_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_VOLUME_WRITES)),
|
||||
queue_permits: Arc::new(Semaphore::new(capacity)),
|
||||
workers: Arc::new(Mutex::new(HashMap::new())),
|
||||
sync_batch,
|
||||
#[cfg(test)]
|
||||
submits: Arc::new(std::sync::atomic::AtomicU64::new(0)),
|
||||
#[cfg(test)]
|
||||
windows_armed: Arc::new(std::sync::atomic::AtomicU64::new(0)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +126,12 @@ impl WriteQueue {
|
||||
self.submits.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// How many batch windows workers have armed so far.
|
||||
#[cfg(test)]
|
||||
fn windows_armed_for_test(&self) -> u64 {
|
||||
self.windows_armed.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Sender for the volume's worker, spawning one on first use.
|
||||
fn worker_for(&self, volume_id: VolumeId) -> mpsc::Sender<WriteRequest> {
|
||||
let mut workers = self.workers.lock().unwrap();
|
||||
@@ -107,6 +146,9 @@ impl WriteQueue {
|
||||
state: self.state.clone(),
|
||||
io_permits: self.io_permits.clone(),
|
||||
workers: self.workers.clone(),
|
||||
sync_batch: self.sync_batch,
|
||||
#[cfg(test)]
|
||||
windows_armed: self.windows_armed.clone(),
|
||||
}
|
||||
.run(),
|
||||
);
|
||||
@@ -191,6 +233,9 @@ struct VolumeWriteWorker {
|
||||
state: Arc<VolumeServerState>,
|
||||
io_permits: Arc<Semaphore>,
|
||||
workers: Arc<Mutex<HashMap<VolumeId, mpsc::Sender<WriteRequest>>>>,
|
||||
sync_batch: SyncBatchOption,
|
||||
#[cfg(test)]
|
||||
windows_armed: Arc<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
impl VolumeWriteWorker {
|
||||
@@ -238,14 +283,40 @@ impl VolumeWriteWorker {
|
||||
let mut batch = Vec::with_capacity(MAX_BATCH_SIZE);
|
||||
let mut batch_bytes: usize = first.needle.data.len();
|
||||
batch.push(first);
|
||||
// Armed once the queue first drains below the minimum batch; holds the
|
||||
// batch open for stragglers so the wait bound is per batch, not per
|
||||
// lull (Go's batchWait).
|
||||
let mut window_deadline = None;
|
||||
while batch.len() < MAX_BATCH_SIZE && batch_bytes < MAX_BATCH_BYTES {
|
||||
match self.rx.try_recv() {
|
||||
Ok(req) => {
|
||||
batch_bytes += req.needle.data.len();
|
||||
batch.push(req);
|
||||
}
|
||||
Err(_) => break,
|
||||
if window_deadline.is_some_and(|d| tokio::time::Instant::now() >= d) {
|
||||
break;
|
||||
}
|
||||
let req = match self.rx.try_recv() {
|
||||
Ok(req) => req,
|
||||
Err(mpsc::error::TryRecvError::Empty) => {
|
||||
let sync = self.sync_batch;
|
||||
if sync.wait.is_zero()
|
||||
|| batch_bytes >= sync.min_bytes
|
||||
|| batch.len() >= sync.min_requests
|
||||
{
|
||||
// a drained queue flushes right away once it holds enough
|
||||
break;
|
||||
}
|
||||
let deadline = *window_deadline.get_or_insert_with(|| {
|
||||
#[cfg(test)]
|
||||
self.windows_armed
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tokio::time::Instant::now() + sync.wait
|
||||
});
|
||||
match tokio::time::timeout_at(deadline, self.rx.recv()).await {
|
||||
Ok(Some(req)) => req,
|
||||
Ok(None) | Err(_) => break,
|
||||
}
|
||||
}
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => break,
|
||||
};
|
||||
batch_bytes += req.needle.data.len();
|
||||
batch.push(req);
|
||||
}
|
||||
debug!("processing write batch of {} requests", batch.len());
|
||||
|
||||
@@ -380,7 +451,7 @@ mod tests {
|
||||
async fn test_write_queue_submit_no_volume() {
|
||||
// Submit a write to a non-existent volume -- should return VolumeError::NotFound.
|
||||
let state = make_test_state();
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE, SyncBatchOption::default());
|
||||
|
||||
let needle = Needle {
|
||||
id: 1.into(),
|
||||
@@ -402,7 +473,7 @@ mod tests {
|
||||
async fn test_write_queue_concurrent_submissions() {
|
||||
// Submit multiple concurrent writes -- all should complete (with errors since no volume).
|
||||
let state = make_test_state();
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE, SyncBatchOption::default());
|
||||
|
||||
let mut handles = Vec::new();
|
||||
for i in 0..10u64 {
|
||||
@@ -430,7 +501,7 @@ mod tests {
|
||||
async fn test_write_queue_batching() {
|
||||
// Verify that many concurrent writes get processed (testing the batching path).
|
||||
let state = make_test_state();
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE, SyncBatchOption::default());
|
||||
|
||||
// Submit MAX_BATCH_SIZE requests concurrently
|
||||
let mut handles = Vec::new();
|
||||
@@ -522,7 +593,7 @@ mod tests {
|
||||
async fn test_write_queue_dropped_sender() {
|
||||
// When the queue is dropped, subsequent submits should fail gracefully.
|
||||
let state = make_test_state();
|
||||
let queue = WriteQueue::new(state, 1);
|
||||
let queue = WriteQueue::new(state, 1, SyncBatchOption::default());
|
||||
|
||||
// Clone then drop the original -- the worker keeps running via its rx handle.
|
||||
let queue2 = queue.clone();
|
||||
@@ -665,7 +736,7 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
|
||||
let queue = WriteQueue::new(state, MAX_BATCH_SIZE, SyncBatchOption::default());
|
||||
|
||||
let in_append = Arc::new(Barrier::new(2));
|
||||
let release = Arc::new(Barrier::new(2));
|
||||
@@ -734,4 +805,85 @@ mod tests {
|
||||
assert!(a1.await.unwrap().is_ok());
|
||||
assert!(a2.await.unwrap().is_ok());
|
||||
}
|
||||
|
||||
/// A durable write below the minimum batch rides out its window so a
|
||||
/// straggler joins the same sync instead of each paying an fsync alone —
|
||||
/// Go's batchWait. Paused time makes the hold observable: a lone write can
|
||||
/// only complete once the runtime auto-advances to the window's deadline.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn test_batch_window_defers_flush_for_stragglers() {
|
||||
use crate::config::MinFreeSpace;
|
||||
use crate::storage::types::{DiskType, NeedleId};
|
||||
use crate::storage::volume::VolumeSpec;
|
||||
use std::time::Duration;
|
||||
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let state = make_test_state();
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let queue = WriteQueue::new(
|
||||
state,
|
||||
MAX_BATCH_SIZE,
|
||||
SyncBatchOption {
|
||||
min_bytes: usize::MAX,
|
||||
min_requests: MAX_BATCH_SIZE,
|
||||
wait: Duration::from_secs(30),
|
||||
},
|
||||
);
|
||||
|
||||
let needle = |id: u64| Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: 0x1111.into(),
|
||||
data: vec![id as u8; 8],
|
||||
data_size: 8,
|
||||
..Needle::default()
|
||||
};
|
||||
|
||||
let start = tokio::time::Instant::now();
|
||||
queue.submit(VolumeId(1), needle(1), true).await.unwrap();
|
||||
assert!(start.elapsed() >= Duration::from_secs(30));
|
||||
|
||||
// Wait for the worker to take the second write and open its batch
|
||||
// window, so the straggler provably lands inside an open batch
|
||||
// instead of arriving during the initial drain.
|
||||
let armed = queue.windows_armed_for_test();
|
||||
let second = tokio::spawn({
|
||||
let queue = queue.clone();
|
||||
async move { queue.submit(VolumeId(1), needle(2), true).await }
|
||||
});
|
||||
for _ in 0..10_000 {
|
||||
if queue.windows_armed_for_test() > armed {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
assert!(queue.windows_armed_for_test() > armed);
|
||||
let third = tokio::spawn({
|
||||
let queue = queue.clone();
|
||||
async move { queue.submit(VolumeId(1), needle(3), true).await }
|
||||
});
|
||||
let (second, third) = tokio::join!(second, third);
|
||||
second.unwrap().unwrap();
|
||||
third.unwrap().unwrap();
|
||||
// One shared window ends both writes ~30s after their batch armed;
|
||||
// back-to-back windows would keep the third out to ~90s.
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed >= Duration::from_secs(60) && elapsed < Duration::from_secs(90));
|
||||
}
|
||||
}
|
||||
@@ -1340,11 +1340,11 @@ async fn non_ascii_fid_and_ttl_are_rejected_not_panicked() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_queue_upload_returns_same_etag_as_direct_write() {
|
||||
use seaweed_volume::server::write_queue::WriteQueue;
|
||||
use seaweed_volume::server::write_queue::{SyncBatchOption, WriteQueue};
|
||||
|
||||
let (direct_state, _direct_tmp) = test_state();
|
||||
let (queued_state, _queued_tmp) = test_state();
|
||||
let wq = WriteQueue::new(queued_state.clone(), 128);
|
||||
let wq = WriteQueue::new(queued_state.clone(), 128, SyncBatchOption::default());
|
||||
let _ = queued_state.write_queue.set(wq);
|
||||
|
||||
let compressible = "seaweedfs ".repeat(200).into_bytes();
|
||||
|
||||
@@ -153,7 +153,7 @@ func (f *FuseTestFramework) Setup(config *TestConfig) error {
|
||||
}
|
||||
|
||||
// Wait for filer to be ready (mini starts all services on filerPort)
|
||||
if err := f.waitForService(f.miniProcess, f.filerAddr, 30*time.Second); err != nil {
|
||||
if err := f.waitForService(f.miniProcess, f.filerAddr, 90*time.Second); err != nil {
|
||||
f.dumpLog("mini")
|
||||
return fmt.Errorf("weed mini not ready: %v", err)
|
||||
}
|
||||
@@ -164,7 +164,7 @@ func (f *FuseTestFramework) Setup(config *TestConfig) error {
|
||||
}
|
||||
|
||||
// Wait for mount to be ready
|
||||
if err := f.waitForMount(30 * time.Second); err != nil {
|
||||
if err := f.waitForMount(90 * time.Second); err != nil {
|
||||
f.dumpLog("mount")
|
||||
return fmt.Errorf("FUSE mount not ready: %v", err)
|
||||
}
|
||||
|
||||
+4
-4
@@ -174,12 +174,12 @@ start-openbao-ci: ## Start OpenBao via Docker for CI
|
||||
ghcr.io/openbao/openbao:latest \
|
||||
bao server -dev -dev-root-token-id=$(OPENBAO_TOKEN) -dev-listen-address=0.0.0.0:8200
|
||||
@echo "Waiting for OpenBao to be ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s $(OPENBAO_ADDR)/v1/sys/health > /dev/null 2>&1; then \
|
||||
echo "$(GREEN)OpenBao is ready$(NC)"; \
|
||||
break; \
|
||||
fi; \
|
||||
if [ $$i -eq 30 ]; then \
|
||||
if [ $$i -eq 90 ]; then \
|
||||
echo "$(RED)Timeout waiting for OpenBao$(NC)"; \
|
||||
docker logs openbao-ci 2>&1 | tail -20; \
|
||||
exit 1; \
|
||||
@@ -213,12 +213,12 @@ start-seaweedfs-ci: check-binary ## Start weed mini with OpenBao KMS config
|
||||
-ip=127.0.0.1 \
|
||||
> /tmp/seaweedfs-kms-mini.log 2>&1 & echo $$! > /tmp/weed-kms-mini.pid
|
||||
@echo "Checking S3 service is ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s http://127.0.0.1:$(S3_PORT) > /dev/null 2>&1; then \
|
||||
echo "$(GREEN)S3 service is ready$(NC)"; \
|
||||
break; \
|
||||
fi; \
|
||||
if [ $$i -eq 30 ]; then \
|
||||
if [ $$i -eq 90 ]; then \
|
||||
echo "$(RED)Timeout waiting for S3 service$(NC)"; \
|
||||
echo "=== Last 50 lines of server log ==="; \
|
||||
tail -50 /tmp/seaweedfs-kms-mini.log 2>/dev/null || echo "No server log found"; \
|
||||
|
||||
@@ -76,12 +76,12 @@ start-seaweedfs: check-binary
|
||||
-ip=127.0.0.1 \
|
||||
> /tmp/seaweedfs-mini.log 2>&1 & echo $$! > /tmp/weed-mini.pid
|
||||
@echo "$(YELLOW)Waiting for S3 service to be ready...$(NC)"
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s -f http://127.0.0.1:$(S3_PORT) > /dev/null 2>&1; then \
|
||||
echo "$(GREEN)S3 service is ready$(NC)"; \
|
||||
break; \
|
||||
fi; \
|
||||
echo "Waiting for S3 service... ($$i/30)"; \
|
||||
echo "Waiting for S3 service... ($$i/90)"; \
|
||||
sleep 1; \
|
||||
done
|
||||
@sleep 2
|
||||
|
||||
@@ -92,7 +92,7 @@ start-server: check-deps
|
||||
echo $$! > weed-server.pid
|
||||
|
||||
@echo "Waiting for S3 server to be ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if echo | nc -z localhost $(S3_PORT); then \
|
||||
echo "S3 server is ready!"; \
|
||||
exit 0; \
|
||||
|
||||
@@ -79,14 +79,14 @@ start-server: check-deps
|
||||
echo $$! > weed-server.pid
|
||||
|
||||
@echo "Waiting for S3 server to be ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if echo | nc -z localhost $(S3_PORT); then \
|
||||
echo "S3 server is ready!"; \
|
||||
exit 0; \
|
||||
fi; \
|
||||
sleep 1; \
|
||||
done; \
|
||||
echo "❌ Server failed to start within 30 seconds"; \
|
||||
echo "❌ Server failed to start within 90 seconds"; \
|
||||
if [ -f weed-server.log ]; then \
|
||||
cat weed-server.log; \
|
||||
fi; \
|
||||
|
||||
@@ -81,7 +81,7 @@ start-services: ## Start SeaweedFS services for testing
|
||||
wait-for-services: ## Wait for all services to be ready
|
||||
@echo "Waiting for services to be ready..."
|
||||
@echo "Checking S3 API server..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s http://localhost:$(S3_PORT) > /dev/null 2>&1; then \
|
||||
echo "OK S3 API server is ready"; \
|
||||
exit 0; \
|
||||
|
||||
@@ -42,6 +42,8 @@ start-server: build-weed
|
||||
@mkdir -p $(SERVER_DIR)
|
||||
@AWS_ACCESS_KEY_ID=$(ACCESS_KEY) AWS_SECRET_ACCESS_KEY=$(SECRET_KEY) $(WEED_BINARY) mini \
|
||||
-dir=$(SERVER_DIR) \
|
||||
-ip=127.0.0.1 \
|
||||
-ip.bind=127.0.0.1 \
|
||||
-s3.port=$(S3_PORT) \
|
||||
-filer.port.grpc=$(FILER_GRPC_PORT) \
|
||||
> weed-test.log 2>&1 & \
|
||||
|
||||
@@ -99,6 +99,27 @@ func shellOn(t *testing.T, masterPort, command string) string {
|
||||
return stripLogs(string(out))
|
||||
}
|
||||
|
||||
// waitForFilerListed polls the master until it lists a filer. A fresh
|
||||
// single-filer mini registers its filer only after an ~10 s empty-membership
|
||||
// confirm, and weed shell finds the filer through that listing, so shell
|
||||
// commands sent before it fail.
|
||||
func waitForFilerListed(t *testing.T, masterPort string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for {
|
||||
cmd := exec.Command(weedBinary, "shell", "-master=localhost:"+masterPort)
|
||||
cmd.Stdin = strings.NewReader("cluster.ps\nexit\n")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err == nil && strings.Contains(string(out), "* filers ") && !strings.Contains(string(out), "* filers 0\n") {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("master on %s lists no filer after 60s: %v\n%s", masterPort, err, out)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func chunkCountOn(t *testing.T, masterPort, path string) string {
|
||||
meta := shellOn(t, masterPort, "fs.meta.cat "+path)
|
||||
idx := strings.LastIndex(meta, "chunks ")
|
||||
@@ -166,6 +187,7 @@ func TestRemoteCacheEvictUnderPressure(t *testing.T) {
|
||||
"-master.volumeSizeLimitMB=32", "-volume.max=2",
|
||||
"-filer.remoteCacheEvictThreshold=0.99")
|
||||
waitForHTTP(t, evictPrimaryS3)
|
||||
waitForFilerListed(t, evictPrimaryMaster)
|
||||
|
||||
remote := createS3Client(evictRemoteS3)
|
||||
_, err := remote.CreateBucket(&s3.CreateBucketInput{Bucket: aws.String(evictBucket)})
|
||||
|
||||
@@ -106,7 +106,7 @@ start-seaweedfs: check-binary
|
||||
> /tmp/seaweedfs-sse-mini.log 2>&1 & echo $$! > /tmp/weed-mini.pid
|
||||
|
||||
@echo "Checking S3 service is ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s http://127.0.0.1:$(S3_PORT) > /dev/null 2>&1; then \
|
||||
echo "✅ S3 service is ready"; \
|
||||
break; \
|
||||
@@ -347,7 +347,7 @@ start-seaweedfs-ci: check-binary
|
||||
> /tmp/seaweedfs-sse-mini.log 2>&1 & echo $$! > /tmp/weed-mini.pid
|
||||
|
||||
@echo "Checking S3 service is ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s http://127.0.0.1:$(S3_PORT) > /dev/null 2>&1; then \
|
||||
echo "✅ S3 service is ready"; \
|
||||
break; \
|
||||
@@ -491,7 +491,7 @@ test-volume-encryption: build-weed
|
||||
-ip=127.0.0.1 \
|
||||
> /tmp/seaweedfs-sse-mini.log 2>&1 & echo $$! > /tmp/weed-mini.pid
|
||||
@echo "Checking S3 service is ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s http://127.0.0.1:$(S3_PORT) > /dev/null 2>&1; then \
|
||||
echo "✅ S3 service is ready"; \
|
||||
break; \
|
||||
|
||||
@@ -94,6 +94,7 @@ start-server: check-deps
|
||||
@echo "🔍 DEBUG: Launching SeaweedFS server in background..."
|
||||
@echo "🔍 DEBUG: Command: $(WEED_BINARY) mini -dir=./test-volume-data -s3.port=$(S3_PORT) -s3.config=../../../docker/compose/s3.json"
|
||||
@$(WEED_BINARY) mini \
|
||||
-ip=127.0.0.1 -ip.bind=127.0.0.1 \
|
||||
-dir=./test-volume-data \
|
||||
-s3.port=$(S3_PORT) \
|
||||
-s3.config=../../../docker/compose/s3.json \
|
||||
@@ -229,13 +230,13 @@ test-with-server: start-server
|
||||
test-versioning-with-configs: check-deps
|
||||
@echo "Testing with different S3 configurations..."
|
||||
@echo "Testing with delete bucket not empty allowed..."
|
||||
@$(WEED_BINARY) mini -s3.port=$(S3_PORT) -s3.allowDeleteBucketNotEmpty=true > weed-test-config1.log 2>&1 & echo $$! > weed-config1.pid
|
||||
@$(WEED_BINARY) mini -ip=127.0.0.1 -ip.bind=127.0.0.1 -s3.port=$(S3_PORT) -s3.allowDeleteBucketNotEmpty=true > weed-test-config1.log 2>&1 & echo $$! > weed-config1.pid
|
||||
@sleep 5
|
||||
@go test -v -timeout=5m -run "TestVersioningBasicWorkflow" . || true
|
||||
@if [ -f weed-config1.pid ]; then kill -TERM $$(cat weed-config1.pid) 2>/dev/null || true; rm -f weed-config1.pid; fi
|
||||
@sleep 2
|
||||
@echo "Testing with delete bucket not empty disabled..."
|
||||
@$(WEED_BINARY) mini -s3.port=$(S3_PORT) -s3.allowDeleteBucketNotEmpty=false > weed-test-config2.log 2>&1 & echo $$! > weed-config2.pid
|
||||
@$(WEED_BINARY) mini -ip=127.0.0.1 -ip.bind=127.0.0.1 -s3.port=$(S3_PORT) -s3.allowDeleteBucketNotEmpty=false > weed-test-config2.log 2>&1 & echo $$! > weed-config2.pid
|
||||
@sleep 5
|
||||
@go test -v -timeout=5m -run "TestVersioningBasicWorkflow" . || true
|
||||
@if [ -f weed-config2.pid ]; then kill -TERM $$(cat weed-config2.pid) 2>/dev/null || true; rm -f weed-config2.pid; fi
|
||||
@@ -279,6 +280,7 @@ debug-server:
|
||||
@$(MAKE) stop-server
|
||||
@mkdir -p ./test-volume-data
|
||||
@$(WEED_BINARY) mini \
|
||||
-ip=127.0.0.1 -ip.bind=127.0.0.1 \
|
||||
-debug \
|
||||
-s3.port=$(S3_PORT) \
|
||||
-s3.allowDeleteBucketNotEmpty=true \
|
||||
@@ -323,6 +325,7 @@ health-check:
|
||||
start-server-simple: check-deps
|
||||
@echo "Starting SeaweedFS server (simple mode)..."
|
||||
@$(WEED_BINARY) mini \
|
||||
-ip=127.0.0.1 -ip.bind=127.0.0.1 \
|
||||
-dir=$(SERVER_DIR) \
|
||||
-s3 \
|
||||
-s3.port=$(S3_PORT) \
|
||||
@@ -331,7 +334,7 @@ start-server-simple: check-deps
|
||||
echo $$! > weed-server.pid
|
||||
|
||||
@echo "Waiting for S3 server to be ready..."
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if echo | nc -z localhost $(S3_PORT); then \
|
||||
echo "S3 server is ready!"; \
|
||||
exit 0; \
|
||||
|
||||
@@ -155,7 +155,7 @@ func startCluster(testDir string) (*testCluster, error) {
|
||||
"-filer.port.grpc=" + strconv.Itoa(filerGrpc),
|
||||
"-s3.port=" + strconv.Itoa(s3Port),
|
||||
"-s3.port.grpc=" + strconv.Itoa(s3Grpc),
|
||||
"-webdav=false", // Disable WebDAV
|
||||
"-webdav=false", // Disable WebDAV
|
||||
"-s3.port.lance=0", // Disable Lance
|
||||
"-s3.port.iceberg=" + strconv.Itoa(icebergPort),
|
||||
"-master.volumeSizeLimitMB=32",
|
||||
|
||||
@@ -115,6 +115,9 @@ SELECT 'duckdb deterministic-location describe ok' AS marker;
|
||||
t.Logf("DuckDB output:\n%s", outputStr)
|
||||
|
||||
if err != nil {
|
||||
if testutil.IsIllegalInstruction(err) {
|
||||
t.Skipf("DuckDB image cannot run on this CPU: %v", err)
|
||||
}
|
||||
// Tolerate environments where the Iceberg extension/version is too
|
||||
// limited to exercise this code path. The intent is to gain
|
||||
// coverage where it's available, not to require it everywhere.
|
||||
|
||||
@@ -351,6 +351,9 @@ SELECT 'DuckDB Iceberg OAuth secret created successfully' as result;
|
||||
t.Logf("DuckDB output:\n%s", outputStr)
|
||||
|
||||
if err != nil {
|
||||
if testutil.IsIllegalInstruction(err) {
|
||||
t.Skipf("DuckDB image cannot run on this CPU: %v", err)
|
||||
}
|
||||
if strings.Contains(outputStr, "iceberg extension is not available") ||
|
||||
strings.Contains(outputStr, "Failed to load") {
|
||||
t.Skip("Skipping: Iceberg extension not available in DuckDB Docker image")
|
||||
@@ -379,6 +382,9 @@ SELECT 'DuckDB Iceberg OAuth secret created successfully' as result;
|
||||
t.Logf("DuckDB fallback output:\n%s", fallbackStr)
|
||||
|
||||
if fallbackErr != nil {
|
||||
if testutil.IsIllegalInstruction(fallbackErr) {
|
||||
t.Skipf("DuckDB image cannot run on this CPU: %v", fallbackErr)
|
||||
}
|
||||
if strings.Contains(fallbackStr, "NotFound_404") && strings.Contains(fallbackStr, "/v1/oauth/tokens") {
|
||||
t.Fatal("OAuth token endpoint returned 404 - the fix is not working")
|
||||
}
|
||||
|
||||
@@ -574,6 +574,9 @@ SELECT 'Iceberg extension loaded successfully' as result;
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Logf("DuckDB output: %s", output)
|
||||
if testutil.IsIllegalInstruction(err) {
|
||||
t.Skipf("DuckDB image cannot run on this CPU: %v", err)
|
||||
}
|
||||
// Check for expected errors in certain CI environments
|
||||
outputStr := string(output)
|
||||
if strings.Contains(outputStr, "iceberg extension is not available") ||
|
||||
|
||||
@@ -218,6 +218,9 @@ SELECT * FROM test_catalog.%s.%s LIMIT 0;
|
||||
}
|
||||
|
||||
if runErr != nil {
|
||||
if testutil.IsIllegalInstruction(runErr) {
|
||||
t.Skipf("DuckDB image cannot run on this CPU: %v", runErr)
|
||||
}
|
||||
if strings.Contains(outStr, "does not exist because schema") &&
|
||||
strings.Contains(outStr, namespace) {
|
||||
t.Fatalf("reproduced issue #9103: DuckDB cannot see namespace %q after ATTACH 's3://%s/'; see output above",
|
||||
|
||||
@@ -2,11 +2,13 @@ package catalog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// TestLanceNamespaceRealClient drives the namespace with the Lance client rather
|
||||
@@ -58,6 +60,9 @@ func TestLanceNamespaceRealClient(t *testing.T) {
|
||||
|
||||
t.Logf("Running Lance client test against %s", namespaceURL)
|
||||
if err := cmd.Run(); err != nil {
|
||||
if testutil.IsIllegalInstruction(err) {
|
||||
t.Skipf("Lance client image cannot run on this CPU: %v", err)
|
||||
}
|
||||
t.Errorf("Lance client test failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -871,6 +871,11 @@ func requireClickHouseRuntime(t *testing.T) {
|
||||
if !hasDocker() {
|
||||
t.Skip("Docker not available, skipping ClickHouse integration test")
|
||||
}
|
||||
// ClickHouse builds for x86-64-v3 (AVX2) since 26.5; on a CPU without it
|
||||
// the binary dies on SIGILL inside the entrypoint before the server can
|
||||
// come up.
|
||||
testutil.RequireImageRunnable(t,
|
||||
"--entrypoint", "clickhouse", clickhouseImage(), "local", "--query", "SELECT 1")
|
||||
}
|
||||
|
||||
// hasDocker reports whether `docker version` can run, which we treat as a
|
||||
|
||||
@@ -272,6 +272,9 @@ func (env *environment) runClient(t *testing.T, bucket string) {
|
||||
out, err := cmd.CombinedOutput()
|
||||
t.Logf("LanceDB client output:\n%s", out)
|
||||
if err != nil {
|
||||
if testutil.IsIllegalInstruction(err) {
|
||||
t.Skipf("LanceDB client image cannot run on this CPU: %v", err)
|
||||
}
|
||||
t.Fatalf("the LanceDB client failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(out), "PASS") {
|
||||
|
||||
@@ -194,6 +194,7 @@ func (env *TestEnvironment) StartRisingWave(t *testing.T) {
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to start RisingWave container: %v\n%s", err, string(output))
|
||||
}
|
||||
env.checkRisingWaveContainer(t)
|
||||
|
||||
// Start a sidecar postgres container for running psql commands
|
||||
sidecarName := "seaweed-risingwave-sidecar-" + randomString(8)
|
||||
@@ -205,6 +206,7 @@ func (env *TestEnvironment) StartRisingWave(t *testing.T) {
|
||||
"sleep", "infinity",
|
||||
)
|
||||
if output, err := sidecarCmd.CombinedOutput(); err != nil {
|
||||
env.checkRisingWaveContainer(t)
|
||||
t.Fatalf("failed to start postgres sidecar: %v\n%s", err, string(output))
|
||||
}
|
||||
|
||||
@@ -220,6 +222,7 @@ func (env *TestEnvironment) waitForRisingWave(timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
env.t.Logf(">>> Waiting for RisingWave to be ready (timeout %v)...\n", timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
env.checkRisingWaveContainer(env.t)
|
||||
if output, err := runPostgresClientSQL(env.postgresSidecar, "SELECT 1;"); err == nil {
|
||||
env.t.Logf(">>> RisingWave is ready.\n")
|
||||
return true
|
||||
@@ -231,6 +234,26 @@ func (env *TestEnvironment) waitForRisingWave(timeout time.Duration) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) checkRisingWaveContainer(t *testing.T) {
|
||||
t.Helper()
|
||||
out, err := exec.Command("docker", "inspect", "--format", "{{.State.Running}} {{.State.ExitCode}} {{.State.OOMKilled}}", env.risingwaveContainer).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("inspect RisingWave container: %v\n%s", err, out)
|
||||
}
|
||||
state := strings.Fields(string(out))
|
||||
if len(state) != 3 {
|
||||
t.Fatalf("unexpected RisingWave container state: %s", out)
|
||||
}
|
||||
if state[0] == "true" {
|
||||
return
|
||||
}
|
||||
if state[1] == "132" && state[2] == "false" {
|
||||
t.Skip("RisingWave image exited with illegal instruction on this CPU")
|
||||
}
|
||||
logs, _ := exec.Command("docker", "logs", env.risingwaveContainer).CombinedOutput()
|
||||
t.Fatalf("RisingWave container exited before it became ready (code %s, OOM killed: %s):\n%s", state[1], state[2], logs)
|
||||
}
|
||||
|
||||
func runPostgresClientSQL(containerName, sql string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -70,6 +70,13 @@ func TestIcebergTableLifecycle(t *testing.T) {
|
||||
|
||||
func testIcebergLifecycleWithDuckDB(t *testing.T) {
|
||||
env := shared
|
||||
|
||||
// The write phase's first act is INSTALLing the iceberg extension, whose
|
||||
// binary can itself target a newer x86-64 baseline than the host CPU has.
|
||||
testutil.RequireImageRunnable(t,
|
||||
"--entrypoint", "duckdb", duckdbImage,
|
||||
"-c", "INSTALL iceberg; LOAD iceberg; SELECT 1;")
|
||||
|
||||
bucket := "lifecycle-duckdb-" + randomSuffix()
|
||||
namespace, table := "sales", "events"
|
||||
env.createTableBucket(t, bucket, "ICEBERG")
|
||||
@@ -109,6 +116,9 @@ func testIcebergLifecycleWithPyIceberg(t *testing.T) {
|
||||
namespace, table := "sales", "events"
|
||||
env.createTableBucket(t, bucket, "ICEBERG")
|
||||
buildClientImage(t, pyicebergImage, "Dockerfile.pyiceberg")
|
||||
testutil.RequireImageRunnable(t,
|
||||
"--entrypoint", "python3", pyicebergImage,
|
||||
"-c", "import pyarrow; from pyiceberg.catalog import load_catalog")
|
||||
|
||||
before := env.pyiceberg(t, "write", bucket, namespace, table)
|
||||
assertSeeded(t, before)
|
||||
|
||||
@@ -35,6 +35,9 @@ func TestLanceTableLifecycle(t *testing.T) {
|
||||
namespace, table := "ml", "events"
|
||||
env.createTableBucket(t, bucket, "LANCE")
|
||||
buildClientImage(t, lanceImage, "Dockerfile.lance")
|
||||
testutil.RequireImageRunnable(t,
|
||||
"--entrypoint", "python3", lanceImage,
|
||||
"-c", "import lance; import lance_namespace; import pyarrow")
|
||||
|
||||
before := env.lance(t, "write", bucket, namespace, table)
|
||||
assertSeeded(t, before)
|
||||
|
||||
@@ -151,7 +151,7 @@ func startCluster(testDir string, extraArgs []string) (*testCluster, error) {
|
||||
"-filer.port.grpc=" + strconv.Itoa(filerGrpc),
|
||||
"-s3.port=" + strconv.Itoa(s3Port),
|
||||
"-s3.port.grpc=" + strconv.Itoa(s3Grpc),
|
||||
"-webdav=false", // Disable WebDAV
|
||||
"-webdav=false", // Disable WebDAV
|
||||
"-s3.port.lance=0", // Disable Lance
|
||||
"-s3.port.iceberg=" + strconv.Itoa(icebergPort),
|
||||
"-admin.ui=false",
|
||||
|
||||
@@ -679,7 +679,7 @@ func startMiniClusterInDir(testDir string, extraArgs []string) (*TestCluster, er
|
||||
"-filer.port.grpc=" + strconv.Itoa(filerGrpcPort),
|
||||
"-s3.port=" + strconv.Itoa(s3Port),
|
||||
"-s3.port.grpc=" + strconv.Itoa(s3GrpcPort),
|
||||
"-webdav=false", // Disable WebDAV
|
||||
"-webdav=false", // Disable WebDAV
|
||||
"-s3.port.lance=0", // Disable Lance
|
||||
"-s3.port.iceberg=" + strconv.Itoa(icebergPort),
|
||||
"-admin.ui=false", // Disable admin UI
|
||||
|
||||
@@ -2,12 +2,15 @@ package testutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -20,6 +23,39 @@ func HasDocker() bool {
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
// RequireImageRunnable runs a throwaway container with the given `docker run`
|
||||
// arguments and skips the test when its process dies on SIGILL. Upstream
|
||||
// images increasingly target x86-64-v3 (AVX2) - ClickHouse since 26.5 - so a
|
||||
// host CPU without those instructions cannot run them at all, and the failure
|
||||
// says nothing about the code under test. Any other outcome, whether a clean
|
||||
// run, an ordinary non-zero exit, or a pull failure, is left for the test
|
||||
// itself to report: the probe can only skip on the one failure the code
|
||||
// cannot cause.
|
||||
func RequireImageRunnable(t *testing.T, args ...string) {
|
||||
t.Helper()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "docker", append([]string{"run", "--rm"}, args...)...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
var exitErr *exec.ExitError
|
||||
// 132 = 128 + SIGILL: docker propagates the container process's death.
|
||||
if errors.As(err, &exitErr) &&
|
||||
(exitErr.ExitCode() == 132 ||
|
||||
strings.Contains(string(out), "Illegal instruction")) {
|
||||
t.Skipf("image cannot execute on this CPU (illegal instruction): docker run %s\n%s",
|
||||
strings.Join(args, " "), out)
|
||||
}
|
||||
}
|
||||
|
||||
func IsIllegalInstruction(err error) bool {
|
||||
var exitErr *exec.ExitError
|
||||
return errors.As(err, &exitErr) && exitErr.ExitCode() == 132
|
||||
}
|
||||
|
||||
func FindBindIP() string {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package testutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsIllegalInstruction(t *testing.T) {
|
||||
if code := os.Getenv("SEAWEEDFS_TEST_EXIT_CODE"); code != "" {
|
||||
status, _ := strconv.Atoi(code)
|
||||
os.Exit(status)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
code string
|
||||
want bool
|
||||
}{
|
||||
{"illegal instruction", "132", true},
|
||||
{"ordinary failure", "1", false},
|
||||
{"out of memory", "137", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestIsIllegalInstruction$")
|
||||
cmd.Env = append(os.Environ(), "SEAWEEDFS_TEST_EXIT_CODE="+tc.code)
|
||||
err := cmd.Run()
|
||||
if got := IsIllegalInstruction(fmt.Errorf("docker run: %w", err)); got != tc.want {
|
||||
t.Fatalf("IsIllegalInstruction(%v) = %v, want %v", err, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if IsIllegalInstruction(nil) || IsIllegalInstruction(errors.New("exit status 132")) {
|
||||
t.Fatal("non-process errors must not be treated as illegal instructions")
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -106,17 +106,17 @@ start-seaweedfs: check-binary
|
||||
|
||||
# Wait for filer to be ready
|
||||
@echo "$(YELLOW)Waiting for filer to be ready...$(NC)"
|
||||
@for i in $$(seq 1 30); do \
|
||||
@for i in $$(seq 1 90); do \
|
||||
if curl -s -f http://127.0.0.1:$(FILER_PORT)/ > /dev/null 2>&1; then \
|
||||
echo "$(GREEN)Filer is ready$(NC)"; \
|
||||
break; \
|
||||
fi; \
|
||||
if [ $$i -eq 30 ]; then \
|
||||
echo "$(RED)Filer failed to start within 30 seconds$(NC)"; \
|
||||
if [ $$i -eq 90 ]; then \
|
||||
echo "$(RED)Filer failed to start within 90 seconds$(NC)"; \
|
||||
$(MAKE) debug-logs; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
echo "Waiting for filer... ($$i/30)"; \
|
||||
echo "Waiting for filer... ($$i/90)"; \
|
||||
sleep 1; \
|
||||
done
|
||||
|
||||
|
||||
@@ -102,6 +102,15 @@ func (cp *ConfigPersistence) ApplyMaintenanceConfigFromToml(v TomlConfig) error
|
||||
ecConf.StrictPlacement = v.GetBool(k)
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.free_slots_deadband"; v.IsSet(k) {
|
||||
ecConf.FreeSlotsDeadband = v.GetInt(k)
|
||||
if ecConf.FreeSlotsDeadband < 0 {
|
||||
ecConf.FreeSlotsDeadband = 0
|
||||
} else if ecConf.FreeSlotsDeadband > 100000 {
|
||||
ecConf.FreeSlotsDeadband = 100000
|
||||
}
|
||||
ecChanged = true
|
||||
}
|
||||
|
||||
if !maintenanceChanged && !vacuumChanged && !balanceChanged && !ecChanged {
|
||||
return nil
|
||||
@@ -223,12 +232,13 @@ var pluginConfigSections = []pluginConfigSection{
|
||||
jobType: "erasure_coding",
|
||||
prefix: "maintenance.erasure_coding",
|
||||
workerKeys: map[string]func(v TomlConfig, key string) *plugin_pb.ConfigValue{
|
||||
"fullness_ratio": doubleValue,
|
||||
"quiet_for_seconds": int64Value,
|
||||
"min_size_mb": int64Value,
|
||||
"preferred_tags": stringListValue,
|
||||
"replica_placement": stringValue,
|
||||
"strict_placement": boolValue,
|
||||
"fullness_ratio": doubleValue,
|
||||
"quiet_for_seconds": int64Value,
|
||||
"min_size_mb": int64Value,
|
||||
"preferred_tags": stringListValue,
|
||||
"replica_placement": stringValue,
|
||||
"strict_placement": boolValue,
|
||||
"free_slots_deadband": int64Value,
|
||||
},
|
||||
// workers read collection_filter from the admin values, not the worker values
|
||||
adminKeys: map[string]func(v TomlConfig, key string) *plugin_pb.ConfigValue{
|
||||
|
||||
+108
-13
@@ -42,6 +42,7 @@ type FilerBackupOptions struct {
|
||||
timeAgo *time.Duration
|
||||
retentionDays *int
|
||||
initialSnapshot *bool
|
||||
concurrency *int
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -65,6 +66,7 @@ func init() {
|
||||
filerBackupOptions.disableErrorRetry = cmdFilerBackup.Flag.Bool("disableErrorRetry", false, "disables errors retry, only logs will print")
|
||||
filerBackupOptions.ignore404Error = cmdFilerBackup.Flag.Bool("ignore404Error", true, "ignore 404 errors from filer")
|
||||
filerBackupOptions.initialSnapshot = cmdFilerBackup.Flag.Bool("initialSnapshot", false, "before subscribing to metadata updates, walk the live filer tree under -filerPath and seed the destination, then subscribe from the walk-start timestamp so concurrent changes are still captured. Runs on every start when -timeAgo is 0 and overwrites the saved checkpoint, so it also re-seeds a reinitialized destination. Remove it once the backup is caught up, otherwise it re-walks the whole tree on each restart.")
|
||||
filerBackupOptions.concurrency = cmdFilerBackup.Flag.Int("concurrency", DefaultConcurrencyLimit, "the maximum number of files that will be backed up concurrently.")
|
||||
}
|
||||
|
||||
var cmdFilerBackup = &Command{
|
||||
@@ -105,10 +107,12 @@ func runFilerBackup(cmd *Command, args []string) bool {
|
||||
|
||||
clientId := util.RandomInt32()
|
||||
var clientEpoch int32
|
||||
var resumeTsNs int64
|
||||
|
||||
for {
|
||||
clientEpoch++
|
||||
err := doFilerBackup(grpcDialOption, &filerBackupOptions, reExcludeFileName, excludeFileNames, excludePathPatterns, clientId, clientEpoch)
|
||||
var err error
|
||||
resumeTsNs, err = doFilerBackup(grpcDialOption, &filerBackupOptions, reExcludeFileName, excludeFileNames, excludePathPatterns, clientId, clientEpoch, resumeTsNs)
|
||||
if err != nil {
|
||||
glog.Errorf("backup from %s: %v", *filerBackupOptions.filer, err)
|
||||
time.Sleep(1747 * time.Millisecond)
|
||||
@@ -120,12 +124,12 @@ const (
|
||||
BackupKeyPrefix = "backup."
|
||||
)
|
||||
|
||||
func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOptions, reExcludeFileName *regexp.Regexp, excludeFileNames []*wildcard.WildcardMatcher, excludePathPatterns []*wildcard.WildcardMatcher, clientId int32, clientEpoch int32) error {
|
||||
func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOptions, reExcludeFileName *regexp.Regexp, excludeFileNames []*wildcard.WildcardMatcher, excludePathPatterns []*wildcard.WildcardMatcher, clientId int32, clientEpoch int32, resumeTsNs int64) (int64, error) {
|
||||
|
||||
// find data sink
|
||||
dataSink := findSink(util.GetViper())
|
||||
if dataSink == nil {
|
||||
return fmt.Errorf("no data sink configured in replication.toml")
|
||||
return 0, fmt.Errorf("no data sink configured in replication.toml")
|
||||
}
|
||||
|
||||
sourceFiler := pb.ServerAddress(*backupOption.filer)
|
||||
@@ -139,14 +143,20 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
startFrom := time.Unix(0, 0)
|
||||
sinkId, legacySinkId := backupCheckpointIds(sourcePath, dataSink)
|
||||
runSnapshot := *backupOption.initialSnapshot && timeAgo == 0
|
||||
if timeAgo == 0 {
|
||||
if resumeTsNs > 0 {
|
||||
// The previous attempt pinned where it stopped — a failed event's
|
||||
// timestamp or the processed watermark — which can sit behind both the
|
||||
// persisted checkpoint and a recomputed -timeAgo window.
|
||||
startFrom = time.Unix(0, resumeTsNs)
|
||||
glog.V(0).Infof("resuming previous attempt at %v", startFrom)
|
||||
} else if timeAgo == 0 {
|
||||
if runSnapshot {
|
||||
// snapshot below sets the start point; no checkpoint read needed
|
||||
glog.V(0).Infof("initialSnapshot requested — walking live tree before subscribing")
|
||||
} else {
|
||||
lastOffsetTsNs, err := getOffsetWithFallback(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("starting from %v (offset read failed: %v)", startFrom, err)
|
||||
return 0, fmt.Errorf("read backup offset: %w", err)
|
||||
} else if lastOffsetTsNs > 0 {
|
||||
startFrom = time.Unix(0, lastOffsetTsNs)
|
||||
glog.V(0).Infof("resuming from %v", startFrom)
|
||||
@@ -166,11 +176,11 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
sourceFiler.ToGrpcAddress(),
|
||||
sourcePath,
|
||||
*backupOption.proxyByFiler); err != nil {
|
||||
return fmt.Errorf("filersource initialization failed: %v", err)
|
||||
return resumeTsNs, fmt.Errorf("filersource initialization failed: %v", err)
|
||||
}
|
||||
|
||||
if err := repl_util.InitializeSSEForReplication(filerSource); err != nil {
|
||||
return fmt.Errorf("SSE initialization failed: %v", err)
|
||||
return resumeTsNs, fmt.Errorf("SSE initialization failed: %v", err)
|
||||
}
|
||||
dataSink.SetSourceFiler(filerSource)
|
||||
|
||||
@@ -181,14 +191,14 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
if runSnapshot {
|
||||
snapshotTsNs, err := runInitialSnapshot(sourceFiler.ToGrpcAddress(), filerSource, sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.ignore404Error)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initial snapshot: %w", err)
|
||||
return 0, fmt.Errorf("initial snapshot: %w", err)
|
||||
}
|
||||
// The walk can take hours on large trees; retry the tiny KV write a
|
||||
// handful of times before giving up so a flaky filer KV doesn't force
|
||||
// the whole walk to repeat on the next retry loop iteration.
|
||||
if err := persistSnapshotOffset(grpcDialOption, sourceFiler, sinkId, snapshotTsNs); err != nil {
|
||||
glog.Errorf("initialSnapshot: FAILED to persist offset %d for sinkId %d after retries: %v — the next retry will redo the full walk", snapshotTsNs, sinkId, err)
|
||||
return fmt.Errorf("persist initial snapshot offset: %w", err)
|
||||
return 0, fmt.Errorf("persist initial snapshot offset: %w", err)
|
||||
}
|
||||
startFrom = time.Unix(0, snapshotTsNs)
|
||||
// walk once per process; retries resume from the persisted checkpoint
|
||||
@@ -218,9 +228,74 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
processEventFn = genProcessFunction(sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.doDeleteFiles, debug)
|
||||
}
|
||||
|
||||
processEventFnWithOffset := pb.AddOffsetFunc(processEventFn, 3*time.Second, func(counter int64, lastTsNs int64) error {
|
||||
glog.V(0).Infof("backup %s progressed to %v %0.2f/sec", sourceFiler, time.Unix(0, lastTsNs), float64(counter)/float64(3))
|
||||
return setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, lastTsNs)
|
||||
if *backupOption.disableErrorRetry {
|
||||
// TrivialOnError semantics: log the failure and advance. Left to the
|
||||
// processor a permanent failure would pin the checkpoint and replay
|
||||
// forever, which is the opposite of what this flag asks for.
|
||||
inner := processEventFn
|
||||
processEventFn = func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if err := inner(resp); err != nil {
|
||||
glog.Errorf("process %v: %v", resp, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Serial event handling caps throughput at one fetch+write at a time, so a
|
||||
// busy source keeps outrunning the backup. The metadata processor fans
|
||||
// events out while serializing same-path and subtree-barrier conflicts,
|
||||
// and the checkpoint only advances on the contiguous processed watermark.
|
||||
concurrency := *backupOption.concurrency
|
||||
if concurrency < 1 || concurrency > 1024 {
|
||||
glog.Warningf("invalid concurrency value %d, using default: %d", concurrency, DefaultConcurrencyLimit)
|
||||
concurrency = DefaultConcurrencyLimit
|
||||
}
|
||||
processor := NewMetadataProcessor(processEventFn, concurrency, startFrom.UnixNano())
|
||||
|
||||
// AddOffsetFunc only checkpoints while events arrive; persist the
|
||||
// completed watermark on a ticker too so work finishing on a quiet
|
||||
// stream does not sit uncheckpointed until the next event.
|
||||
var lastPersistedTsNs atomic.Int64
|
||||
lastPersistedTsNs.Store(-1)
|
||||
stopPersist := make(chan struct{})
|
||||
persistDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(persistDone)
|
||||
ticker := time.NewTicker(3 * time.Second)
|
||||
defer ticker.Stop()
|
||||
persist := func() {
|
||||
if ts := resumeTsNsFor(processor); ts != lastPersistedTsNs.Load() {
|
||||
if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, ts); err == nil {
|
||||
lastPersistedTsNs.Store(ts)
|
||||
} else {
|
||||
glog.Warningf("persist backup offset: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-stopPersist:
|
||||
persist()
|
||||
return
|
||||
case <-ticker.C:
|
||||
persist()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
var lastLogTsNs = time.Now().UnixNano()
|
||||
processEventFnWithOffset := pb.AddOffsetFunc(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
processor.AddSyncJob(resp)
|
||||
return nil
|
||||
}, 3*time.Second, func(counter int64, lastTsNs int64) error {
|
||||
offsetTsNs := processor.processedTsWatermark.Load()
|
||||
if offsetTsNs == 0 {
|
||||
return nil
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
glog.V(0).Infof("backup %s received %0.2f events/sec, processed through %v", sourceFiler, float64(counter)/(float64(now-lastLogTsNs)/1e9), time.Unix(0, offsetTsNs))
|
||||
lastLogTsNs = now
|
||||
return nil
|
||||
})
|
||||
|
||||
if dataSink.IsIncremental() && *filerBackupOptions.retentionDays > 0 {
|
||||
@@ -256,9 +331,29 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
StartTsNs: startFrom.UnixNano(),
|
||||
StopTsNs: 0,
|
||||
EventErrorType: eventErrorType,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
Resubscribe: processor.ResubscribeCh(),
|
||||
}
|
||||
|
||||
return pb.FollowMetadata(sourceFiler, grpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
err := pb.FollowMetadata(sourceFiler, grpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
// Jobs admitted before the stream ended keep running; drain them so the
|
||||
// retry loop's replay cannot race an older write past a newer one.
|
||||
processor.Drain()
|
||||
close(stopPersist)
|
||||
// setOffset has no context, so a stalled checkpoint RPC must not hold the
|
||||
// retry loop: bound the wait and let a late write land in the background.
|
||||
select {
|
||||
case <-persistDone:
|
||||
case <-time.After(30 * time.Second):
|
||||
glog.Warningf("backup %s offset checkpoint did not finish in 30s; reconnecting anyway", sourceFiler)
|
||||
}
|
||||
// Resume the next attempt at the floored watermark — never recompute a
|
||||
// position that skips events. The floor sits one tick below the earliest
|
||||
// failure and stays there even when a redelivery clears the pin, so
|
||||
// events dropped while the processor was stopped still replay.
|
||||
return resumeTsNsFor(processor), err
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -3,11 +3,14 @@ package command
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
@@ -34,14 +37,35 @@ func (s *kvFilerServer) KvPut(_ context.Context, req *filer_pb.KvPutRequest) (*f
|
||||
return &filer_pb.KvPutResponse{}, nil
|
||||
}
|
||||
|
||||
type failingKvFilerServer struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *failingKvFilerServer) KvGet(context.Context, *filer_pb.KvGetRequest) (*filer_pb.KvGetResponse, error) {
|
||||
if s.calls.Add(1) == 1 {
|
||||
return &filer_pb.KvGetResponse{Error: "kv store unavailable"}, nil
|
||||
}
|
||||
return &filer_pb.KvGetResponse{}, nil
|
||||
}
|
||||
|
||||
// a miss reads as ErrNotFound so the retried attempt skips the KEK retry loop
|
||||
func (s *failingKvFilerServer) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func startKvFiler(t *testing.T) (pb.ServerAddress, grpc.DialOption) {
|
||||
return startFiler(t, &kvFilerServer{kv: map[string][]byte{}})
|
||||
}
|
||||
|
||||
func startFiler(t *testing.T, server filer_pb.SeaweedFilerServer) (pb.ServerAddress, grpc.DialOption) {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, &kvFilerServer{kv: map[string][]byte{}})
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, server)
|
||||
go func() { _ = grpcServer.Serve(listener) }()
|
||||
t.Cleanup(func() { grpcServer.Stop() })
|
||||
grpcPort := listener.Addr().(*net.TCPAddr).Port
|
||||
@@ -110,3 +134,38 @@ func TestBackupOffset_DistinctDestinationsDoNotShare(t *testing.T) {
|
||||
t.Fatalf("B reads (%d, %v), want (2000, nil)", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilerBackup_OffsetReadFailureFailsAttempt(t *testing.T) {
|
||||
server := &failingKvFilerServer{}
|
||||
filerAddr, dial := startFiler(t, server)
|
||||
|
||||
config := util.GetViper()
|
||||
config.Set("sink.local.enabled", true)
|
||||
config.Set("sink.local.directory", t.TempDir())
|
||||
t.Cleanup(func() {
|
||||
config.Set("sink.local.enabled", false)
|
||||
config.Set("sink.local.directory", "")
|
||||
})
|
||||
|
||||
options := filerBackupOptions
|
||||
address := string(filerAddr)
|
||||
options.filer = &address
|
||||
|
||||
resumeTsNs, err := doFilerBackup(dial, &options, nil, nil, nil, 1, 1, 0)
|
||||
if err == nil || !strings.Contains(err.Error(), "kv store unavailable") {
|
||||
t.Fatalf("doFilerBackup error = %v, want the offset read failure", err)
|
||||
}
|
||||
if resumeTsNs != 0 {
|
||||
t.Fatalf("resume position = %d, want 0", resumeTsNs)
|
||||
}
|
||||
|
||||
// the next attempt re-reads the checkpoint and gets past it once the KV
|
||||
// recovers, so it must fail later, not on the offset read
|
||||
_, err = doFilerBackup(dial, &options, nil, nil, nil, 1, 2, resumeTsNs)
|
||||
if err == nil || strings.Contains(err.Error(), "kv store unavailable") {
|
||||
t.Fatalf("retried doFilerBackup error = %v, want a later-stage failure", err)
|
||||
}
|
||||
if got := server.calls.Load(); got < 2 {
|
||||
t.Fatalf("checkpoint reads across attempts = %d, want a re-read", got)
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
now := time.Now().UnixNano()
|
||||
glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, time.Unix(0, offsetTsNs), float64(counter)/(float64(now-lastLogTsNs)/1e9))
|
||||
lastLogTsNs = now
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, offsetTsNs)
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, resumeTsNsFor(processor))
|
||||
})
|
||||
|
||||
option.clientEpoch++
|
||||
@@ -65,7 +65,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return processor.processedTsWatermark.Load()
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
Resubscribe: processor.ResubscribeCh(),
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *sour
|
||||
now := time.Now().UnixNano()
|
||||
glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, time.Unix(0, offsetTsNs), float64(counter)/(float64(now-lastLogTsNs)/1e9))
|
||||
lastLogTsNs = now
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, offsetTsNs)
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, resumeTsNsFor(processor))
|
||||
})
|
||||
|
||||
option.clientEpoch++
|
||||
@@ -77,7 +77,7 @@ func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *sour
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return processor.processedTsWatermark.Load()
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
Resubscribe: processor.ResubscribeCh(),
|
||||
}
|
||||
@@ -140,63 +140,24 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
if filer_pb.IsEmpty(resp) {
|
||||
return nil
|
||||
}
|
||||
mustSend := false
|
||||
var renameSrc util.FullPath
|
||||
if message.OldEntry != nil && message.NewEntry != nil {
|
||||
reshaped, inMount := reshapeCrossMountRename(mountedDir, resp)
|
||||
if !inMount {
|
||||
return nil
|
||||
}
|
||||
// a create reshaped from a rename into the mount can carry a
|
||||
// RemoteEntry earned at the old path: it stamps the old key, so
|
||||
// it cannot vouch for this destination
|
||||
mustSend = filer_pb.IsCreate(reshaped)
|
||||
if mustSend {
|
||||
renameSrc = util.NewFullPath(resp.Directory, message.OldEntry.Name)
|
||||
}
|
||||
resp, message = reshaped, reshaped.EventNotification
|
||||
}
|
||||
if filer_pb.IsCreate(resp) {
|
||||
if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
|
||||
return nil
|
||||
}
|
||||
if isSystemPath(message.NewParentPath, message.NewEntry.Name) {
|
||||
glog.V(2).Infof("skipping create of system path: %s/%s", message.NewParentPath, message.NewEntry.Name)
|
||||
return nil
|
||||
}
|
||||
// Propagate delete markers as deletions on the remote.
|
||||
// Delete markers are zero-content version entries, so they
|
||||
// would be filtered out by the HasData check below.
|
||||
if isDeleteMarker(message.NewEntry) {
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(message.NewParentPath, message.NewEntry.Name); ok {
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(newParent, newName), remoteStorageMountLocation)
|
||||
return syncDeleteMarker(client, option, message, dest)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !filer.HasData(message.NewEntry) {
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("create: %+v", resp)
|
||||
if !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping creating: %+v", resp)
|
||||
return nil
|
||||
}
|
||||
// Rewrite internal versioning paths to the original S3 key
|
||||
// to prevent double-versioning when central also has versioning enabled
|
||||
parentPath, entryName := message.NewParentPath, message.NewEntry.Name
|
||||
isRewrittenVersion := false
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(parentPath, entryName); ok {
|
||||
glog.V(0).Infof("rewrite versioned path %s/%s -> %s/%s", parentPath, entryName, newParent, newName)
|
||||
parentPath, entryName = newParent, newName
|
||||
isRewrittenVersion = true
|
||||
}
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(parentPath, entryName), remoteStorageMountLocation)
|
||||
if message.NewEntry.IsDirectory {
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, *option.storageClass))
|
||||
}
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, *option.storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// Skip updateLocalEntry for versioned rewrites: the logical
|
||||
// object (e.g. file.xml) has no filer entry in versioned
|
||||
// buckets, and stamping the internal v_* entry with a
|
||||
// RemoteEntry for the logical key is semantically wrong.
|
||||
// Replay is safe because S3 PutObject is idempotent.
|
||||
if isRewrittenVersion {
|
||||
return nil
|
||||
}
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
return processCreateEvent(option, filerSource, *option.storageClass, client, mountedDir, remoteStorageMountLocation, resp, mustSend, renameSrc)
|
||||
}
|
||||
if filer_pb.IsDelete(resp) {
|
||||
return processDeleteEvent(filerSource, client, mountedDir, remoteStorageMountLocation, resp)
|
||||
@@ -210,6 +171,136 @@ func (option *RemoteSyncOptions) makeEventProcessor(remoteStorage *remote_pb.Rem
|
||||
return eachEntryFunc, nil
|
||||
}
|
||||
|
||||
// reshapeCrossMountRename maps an update event onto the side of it the mount
|
||||
// covers. The subscription delivers a rename when either of its paths lies
|
||||
// under the mounted directory, and only a path under it maps to a remote
|
||||
// key: toRemoteStorageLocation slices the mount prefix off, which panics on
|
||||
// a shorter path and names a key in the wrong tree on a longer one. A rename
|
||||
// into the mount is the creation of the new entry, a rename out of it the
|
||||
// deletion of the old entry's object, unless that entry is remote-only and
|
||||
// the object holds its only copy. An update with both paths inside is
|
||||
// returned as is; one with neither is not the mount's (false).
|
||||
func reshapeCrossMountRename(mountedDir string, resp *filer_pb.SubscribeMetadataResponse) (*filer_pb.SubscribeMetadataResponse, bool) {
|
||||
message := resp.EventNotification
|
||||
oldInMount := isUnderMount(mountedDir, resp.Directory, message.OldEntry.Name)
|
||||
newInMount := isUnderMount(mountedDir, message.NewParentPath, message.NewEntry.Name)
|
||||
switch {
|
||||
case oldInMount && newInMount:
|
||||
return resp, true
|
||||
case newInMount:
|
||||
glog.V(0).Infof("rename into mount %s: %s/%s -> %s/%s, creating", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: message.NewParentPath,
|
||||
EventNotification: &filer_pb.EventNotification{NewEntry: message.NewEntry, NewParentPath: message.NewParentPath, Signatures: message.Signatures},
|
||||
TsNs: resp.TsNs,
|
||||
}, true
|
||||
case oldInMount:
|
||||
if isRemoteOnly(message.OldEntry) {
|
||||
glog.V(0).Infof("rename out of mount %s: %s/%s -> %s/%s, keeping the remote-only object", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return nil, false
|
||||
}
|
||||
glog.V(0).Infof("rename out of mount %s: %s/%s -> %s/%s, deleting", mountedDir, resp.Directory, message.OldEntry.Name, message.NewParentPath, message.NewEntry.Name)
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: resp.Directory,
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: message.OldEntry, Signatures: message.Signatures},
|
||||
TsNs: resp.TsNs,
|
||||
}, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// isUnderMount reports whether dir/name is the mounted directory or lies
|
||||
// below it; a trailing slash on the mount flag does not change the answer.
|
||||
func isUnderMount(mountedDir string, dir string, name string) bool {
|
||||
mount := strings.TrimSuffix(mountedDir, "/")
|
||||
path := string(util.NewFullPath(dir, name))
|
||||
return path == mount || strings.HasPrefix(path, mount+"/")
|
||||
}
|
||||
|
||||
// processCreateEvent uploads a created entry to the remote key its path maps
|
||||
// to. mustSend skips the sync-stamp check: a create reshaped out of a rename
|
||||
// into the mount inherits a RemoteEntry stamped at the old path's key, which
|
||||
// says nothing about whether this destination holds the content. renameSrc is
|
||||
// the path that rename came from, and is empty for a genuine create.
|
||||
func processCreateEvent(
|
||||
filerClient filer_pb.FilerClient,
|
||||
filerSource filer_pb.FilerClient,
|
||||
storageClass string,
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
resp *filer_pb.SubscribeMetadataResponse,
|
||||
mustSend bool,
|
||||
renameSrc util.FullPath,
|
||||
) error {
|
||||
message := resp.EventNotification
|
||||
if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
|
||||
return nil
|
||||
}
|
||||
if isSystemPath(message.NewParentPath, message.NewEntry.Name) {
|
||||
glog.V(2).Infof("skipping create of system path: %s/%s", message.NewParentPath, message.NewEntry.Name)
|
||||
return nil
|
||||
}
|
||||
// Propagate delete markers as deletions on the remote.
|
||||
// Delete markers are zero-content version entries, so they
|
||||
// would be filtered out by the HasData check below.
|
||||
if isDeleteMarker(message.NewEntry) {
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(message.NewParentPath, message.NewEntry.Name); ok {
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(newParent, newName), remoteStorageMountLocation)
|
||||
return syncDeleteMarker(client, filerClient, message, dest)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// A create reshaped from a rename into the mount (mustSend) writes an empty
|
||||
// entry as a zero-byte object; a dropped local copy still skips since the
|
||||
// rename already copied its object to the new key. A stamped entry whose
|
||||
// size diverged since (a truncate) is not a dropped copy and sends its
|
||||
// new content.
|
||||
if !filer.HasData(message.NewEntry) && !(mustSend && !isDroppedLocalCopy(message.NewEntry)) {
|
||||
return nil
|
||||
}
|
||||
glog.V(2).Infof("create: %+v", resp)
|
||||
if !mustSend && !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping creating: %+v", resp)
|
||||
return nil
|
||||
}
|
||||
// Rewrite internal versioning paths to the original S3 key
|
||||
// to prevent double-versioning when central also has versioning enabled
|
||||
parentPath, entryName := message.NewParentPath, message.NewEntry.Name
|
||||
isRewrittenVersion := false
|
||||
if newParent, newName, ok := rewriteVersionedSourcePath(parentPath, entryName); ok {
|
||||
glog.V(0).Infof("rewrite versioned path %s/%s -> %s/%s", parentPath, entryName, newParent, newName)
|
||||
parentPath, entryName = newParent, newName
|
||||
isRewrittenVersion = true
|
||||
}
|
||||
dest := toRemoteStorageLocation(util.FullPath(mountedDir), util.NewFullPath(parentPath, entryName), remoteStorageMountLocation)
|
||||
if message.NewEntry.IsDirectory {
|
||||
glog.V(0).Infof("mkdir %s", remote_storage.FormatLocation(dest))
|
||||
return client.WriteDirectory(dest, remoteWriteEntry(message.NewEntry, storageClass))
|
||||
}
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
if mustSend {
|
||||
return recoverSupersededCreate(filerClient, filerSource, client, mountedDir, remoteStorageMountLocation, message.NewParentPath, message.NewEntry.Name, renameSrc, dest, storageClass)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// Skip updateLocalEntry for versioned rewrites: the logical
|
||||
// object (e.g. file.xml) has no filer entry in versioned
|
||||
// buckets, and stamping the internal v_* entry with a
|
||||
// RemoteEntry for the logical key is semantically wrong.
|
||||
// Replay is safe because S3 PutObject is idempotent.
|
||||
if isRewrittenVersion {
|
||||
return nil
|
||||
}
|
||||
return updateLocalEntry(filerClient, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
|
||||
// processDeleteEvent removes the remote object an entry mapped to. A remote
|
||||
// object that is already absent counts as deleted: the entry was never
|
||||
// uploaded (created and deleted faster than the sync ran, or a replay of an
|
||||
@@ -651,6 +742,176 @@ func uploadCurrentEntry(filerClient filer_pb.FilerClient, filerSource filer_pb.F
|
||||
return updateLocalEntry(filerClient, dir, current, remoteEntry)
|
||||
}
|
||||
|
||||
// recoverSupersededCreate finishes a create reshaped from a rename into the
|
||||
// mount when the filer has moved past the entry the event described. A plain
|
||||
// superseded create skips because the superseding event follows in the log; a
|
||||
// reshaped one has no later event for this destination. remote.uncache accepts
|
||||
// the rename's inherited stamp and drops the chunks, and the update it logs
|
||||
// skips the upload through isDroppedLocalCopy, so the content would exist
|
||||
// nowhere. What the filer holds now decides: local content uploads here only
|
||||
// when the superseding event will not (the stamp-edge case uploadCurrentEntry
|
||||
// covers), and remote-only content copies from the object its stamp
|
||||
// describes, the way completeRemoteOnlyRename finishes a rename.
|
||||
func recoverSupersededCreate(
|
||||
filerClient filer_pb.FilerClient,
|
||||
filerSource filer_pb.FilerClient,
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
dir, name string,
|
||||
renameSrc util.FullPath,
|
||||
dest *remote_pb.RemoteStorageLocation,
|
||||
storageClass string,
|
||||
) error {
|
||||
current, err := currentEntry(filerSource, dir, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current == nil || current.IsDirectory {
|
||||
return nil
|
||||
}
|
||||
if isRemoteOnly(current) {
|
||||
return copyRenameInSource(filerClient, client, mountedDir, remoteStorageMountLocation, dir, current, renameSrc, dest, storageClass)
|
||||
}
|
||||
if shouldSendToRemote(current) {
|
||||
glog.V(0).Infof("leaving %s to the event that superseded the rename", remote_storage.FormatLocation(dest))
|
||||
return nil
|
||||
}
|
||||
glog.V(0).Infof("uploading the current %s in place of the superseded rename", remote_storage.FormatLocation(dest))
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, dir, remoteWriteEntry(current, storageClass), dest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
return updateLocalEntry(filerClient, dir, current, remoteEntry)
|
||||
}
|
||||
|
||||
// copyRenameInSource gives the destination key the content of a remote-only
|
||||
// entry a rename carried into the mount. The object sits at the key the
|
||||
// renamed-from path maps to on its own mount's remote, or where a
|
||||
// pending-rename marker under this mount points. The source object is left
|
||||
// alone: the source side removes it through its own delete event. When the
|
||||
// destination already holds what the stamp describes (an earlier run copied
|
||||
// it), only the stamp is refreshed. With no object on either side the event
|
||||
// fails and holds the offset.
|
||||
func copyRenameInSource(
|
||||
filerClient filer_pb.FilerClient,
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
dir string,
|
||||
current *filer_pb.Entry,
|
||||
renameSrc util.FullPath,
|
||||
dest *remote_pb.RemoteStorageLocation,
|
||||
storageClass string,
|
||||
) error {
|
||||
srcClient, srcLoc, err := renameInSource(filerClient, client, mountedDir, remoteStorageMountLocation, current, renameSrc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing, err := client.StatFile(dest); err == nil {
|
||||
if remote_storage.Describes(current.RemoteEntry, existing) {
|
||||
glog.V(0).Infof("%s already holds the renamed content", remote_storage.FormatLocation(dest))
|
||||
return updateLocalEntry(filerClient, dir, current, existing)
|
||||
}
|
||||
glog.V(0).Infof("%s holds an object the entry does not describe (size %d, want %d); replacing it from %s", remote_storage.FormatLocation(dest), existing.RemoteSize, current.RemoteEntry.RemoteSize, remote_storage.FormatLocation(srcLoc))
|
||||
} else if !errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
|
||||
return err
|
||||
}
|
||||
stat, err := srcClient.StatFile(srcLoc)
|
||||
if errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
|
||||
return fmt.Errorf("%s: content is on neither %s nor %s", util.NewFullPath(dir, current.Name), remote_storage.FormatLocation(srcLoc), remote_storage.FormatLocation(dest))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reader, err := openRemoteObject(srcClient, srcLoc, stat.RemoteSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
glog.V(0).Infof("copy %s -> %s", remote_storage.FormatLocation(srcLoc), remote_storage.FormatLocation(dest))
|
||||
remoteEntry, err := client.WriteFile(dest, remoteWriteEntry(current, storageClass), reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return updateLocalEntry(filerClient, dir, current, remoteEntry)
|
||||
}
|
||||
|
||||
// renameInSource locates the object holding a remote-only rename-in entry's
|
||||
// content and the client that serves it. A pending-rename marker under this
|
||||
// mount names a key on this remote; otherwise the renamed-from path is
|
||||
// resolved through the filer's mount mappings to its own mount's remote
|
||||
// location, served by this client when the source shares this storage.
|
||||
func renameInSource(
|
||||
filerClient filer_pb.FilerClient,
|
||||
client remote_storage.RemoteStorageClient,
|
||||
mountedDir string,
|
||||
remoteStorageMountLocation *remote_pb.RemoteStorageLocation,
|
||||
current *filer_pb.Entry,
|
||||
renameSrc util.FullPath,
|
||||
) (remote_storage.RemoteStorageClient, *remote_pb.RemoteStorageLocation, error) {
|
||||
if src := util.FullPath(current.Extended[filer.ExtRemoteRenameSourceKey]); strings.HasPrefix(string(src), strings.TrimSuffix(mountedDir, "/")+"/") {
|
||||
return client, toRemoteStorageLocation(util.FullPath(mountedDir), src, remoteStorageMountLocation), nil
|
||||
}
|
||||
mappings, err := readMountMappings(filerClient)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
srcMount, srcRemoteLoc, err := filer.FindMountedRemoteMapping(mappings, string(renameSrc))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("rename source %s: %w", renameSrc, err)
|
||||
}
|
||||
srcLoc := filer.MapFullPathToRemoteStorageLocation(util.FullPath(srcMount), srcRemoteLoc, renameSrc)
|
||||
if srcRemoteLoc.Name == remoteStorageMountLocation.Name {
|
||||
return client, srcLoc, nil
|
||||
}
|
||||
conf, err := readRemoteStorageConf(filerClient, srcRemoteLoc.Name)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("rename source %s: %w", renameSrc, err)
|
||||
}
|
||||
srcClient, err := remote_storage.GetRemoteStorage(conf)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("rename source %s: %w", renameSrc, err)
|
||||
}
|
||||
return srcClient, srcLoc, nil
|
||||
}
|
||||
|
||||
// readMountMappings reads the filer's remote mount table, the file
|
||||
// DetectMountInfo reads at startup, through the event's filer client.
|
||||
func readMountMappings(filerClient filer_pb.FilerClient) (mappings *remote_pb.RemoteStorageMapping, err error) {
|
||||
var content []byte
|
||||
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var readErr error
|
||||
content, readErr = filer.ReadInsideFiler(context.Background(), client, filer.DirectoryEtcRemote, filer.REMOTE_STORAGE_MOUNT_FILE)
|
||||
return readErr
|
||||
})
|
||||
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
return filer.UnmarshalRemoteStorageMappings(content)
|
||||
}
|
||||
|
||||
// readRemoteStorageConf reads a remote storage's configuration entry.
|
||||
func readRemoteStorageConf(filerClient filer_pb.FilerClient, storageName string) (*remote_pb.RemoteConf, error) {
|
||||
var content []byte
|
||||
if err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var readErr error
|
||||
content, readErr = filer.ReadInsideFiler(context.Background(), client, filer.DirectoryEtcRemote, storageName+filer.REMOTE_STORAGE_CONF_SUFFIX)
|
||||
return readErr
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conf := &remote_pb.RemoteConf{}
|
||||
if err := proto.Unmarshal(content, conf); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s/%s: %w", filer.DirectoryEtcRemote, storageName+filer.REMOTE_STORAGE_CONF_SUFFIX, err)
|
||||
}
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
// isSuperseded reports whether the filer has moved past the entry an event
|
||||
// described: it is deleted, or it no longer references every chunk the event
|
||||
// named. Those are the chunks the filer deletes when an entry is updated, so
|
||||
|
||||
@@ -413,10 +413,12 @@ func TestIsMetadataOnlyUpdate(t *testing.T) {
|
||||
}
|
||||
|
||||
// stubFilerClient serves one entry; nil means not found. A non-nil err fails
|
||||
// every lookup instead.
|
||||
// every lookup instead. entries, when set, answers lookups by "dir/name"
|
||||
// before entry is consulted.
|
||||
type stubFilerClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
entry *filer_pb.Entry
|
||||
entries map[string]*filer_pb.Entry
|
||||
err error
|
||||
updateErr error
|
||||
lookups int
|
||||
@@ -424,11 +426,14 @@ type stubFilerClient struct {
|
||||
updated *filer_pb.UpdateEntryRequest
|
||||
}
|
||||
|
||||
func (c *stubFilerClient) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest, ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
func (c *stubFilerClient) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest, _ ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
c.lookups++
|
||||
if c.err != nil {
|
||||
return nil, c.err
|
||||
}
|
||||
if c.entries != nil {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: c.entries[req.Directory+"/"+req.Name]}, nil
|
||||
}
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: c.entry}, nil
|
||||
}
|
||||
|
||||
@@ -2017,6 +2022,354 @@ func TestMetadataUpdateKeepsTheStoredStampOnNilResult(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestReshapeCrossMountRename covers an update event with a path outside
|
||||
// the mount. The subscription delivers a rename when either path is under
|
||||
// the mount, and an update of the /etc/remote directory entry itself through
|
||||
// the daemon's /etc/remote prefix; processUpdateEvent then sliced the mount
|
||||
// prefix off both paths, which panics on a path shorter than the mount (seen
|
||||
// on a replay: "slice bounds out of range [20:11]" on the 11-byte
|
||||
// /etc/remote, every restart dying on the same event) and names a key in the
|
||||
// wrong tree on a longer one.
|
||||
func TestReshapeCrossMountRename(t *testing.T) {
|
||||
const mount = "/buckets/mount"
|
||||
chunked := func(name string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, Chunks: []*filer_pb.FileChunk{{FileId: "3,01", Size: 7}}}
|
||||
}
|
||||
event := func(oldDir, oldName, newDir, newName string, oldEntry *filer_pb.Entry) *filer_pb.SubscribeMetadataResponse {
|
||||
if oldEntry == nil {
|
||||
oldEntry = chunked(oldName)
|
||||
}
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: oldDir,
|
||||
TsNs: 42,
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: oldEntry, NewParentPath: newDir, NewEntry: chunked(newName), Signatures: []int32{7}},
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("into the mount from a shorter path is a create of the new entry", func(t *testing.T) {
|
||||
resp := event("/plain", "in.txt", mount+"/lock", "in.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsCreate(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a create", got, inMount)
|
||||
}
|
||||
if got.Directory != mount+"/lock" || got.EventNotification.NewParentPath != mount+"/lock" || got.EventNotification.NewEntry.Name != "in.txt" {
|
||||
t.Errorf("create at %s/%s (dir %s), want %s/in.txt", got.EventNotification.NewParentPath, got.EventNotification.NewEntry.Name, got.Directory, mount+"/lock")
|
||||
}
|
||||
if got.TsNs != 42 || len(got.EventNotification.Signatures) != 1 {
|
||||
t.Errorf("timestamp and signatures must carry over: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("into the mount from a longer path outside it is a create, not a key in the wrong tree", func(t *testing.T) {
|
||||
resp := event("/buckets/other/deeper/tree", "x.txt", mount, "x.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsCreate(got) || got.EventNotification.NewParentPath != mount {
|
||||
t.Fatalf("got %+v inMount=%v, want a create under %s", got, inMount, mount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("out of the mount is a delete of the old entry", func(t *testing.T) {
|
||||
resp := event(mount+"/lock", "out.txt", "/plain", "out.txt", nil)
|
||||
got, inMount := reshapeCrossMountRename(mount, resp)
|
||||
if !inMount || !filer_pb.IsDelete(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a delete", got, inMount)
|
||||
}
|
||||
if got.Directory != mount+"/lock" || got.EventNotification.OldEntry.Name != "out.txt" {
|
||||
t.Errorf("delete of %s/%s, want %s/out.txt", got.Directory, got.EventNotification.OldEntry.Name, mount+"/lock")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("out of the mount keeps the object of a remote-only entry", func(t *testing.T) {
|
||||
remoteOnly := &filer_pb.Entry{Name: "out.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, RemoteEntry: &filer_pb.RemoteEntry{StorageName: "b2", RemoteSize: 7, RemoteMtime: 1786096669}}
|
||||
resp := event(mount+"/lock", "out.txt", "/plain", "out.txt", remoteOnly)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("both paths inside is the update itself", func(t *testing.T) {
|
||||
resp := event(mount+"/a", "x.txt", mount+"/b", "y.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); !inMount || got != resp {
|
||||
t.Fatalf("got %+v inMount=%v, want the same event", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an update of the /etc/remote directory entry itself is not the mount's event", func(t *testing.T) {
|
||||
dirEntry := &filer_pb.Entry{Name: "remote", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/etc",
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: dirEntry, NewParentPath: "/etc", NewEntry: dirEntry},
|
||||
}
|
||||
if got, inMount := reshapeCrossMountRename("/buckets/c4x-storage", resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("neither path inside is not the mount's event", func(t *testing.T) {
|
||||
resp := event("/plain", "x.txt", "/buckets/mounted-not", "x.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount, resp); inMount || got != nil {
|
||||
t.Fatalf("got %+v inMount=%v, want the event dropped", got, inMount)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a trailing slash on the mount flag changes nothing", func(t *testing.T) {
|
||||
resp := event("/plain", "in.txt", mount, "in.txt", nil)
|
||||
if got, inMount := reshapeCrossMountRename(mount+"/", resp); !inMount || !filer_pb.IsCreate(got) {
|
||||
t.Fatalf("got %+v inMount=%v, want a create", got, inMount)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRenameIntoMountUploadsDespiteTheOldStamp covers a file synced at a path
|
||||
// under the mount, renamed out (which deleted its remote object), and renamed
|
||||
// back in: the entry still carries the RemoteEntry the first sync stamped, so
|
||||
// shouldSendToRemote would skip the create the reshape made, leaving the new
|
||||
// key without an object. A reshaped create must send unconditionally.
|
||||
func TestRenameIntoMountUploadsDespiteTheOldStamp(t *testing.T) {
|
||||
const mountedDir = "/buckets/mount"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/"}
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
newEntry := &filer_pb.Entry{
|
||||
Name: "back.txt",
|
||||
Content: []byte("payload"),
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669},
|
||||
RemoteEntry: stamp,
|
||||
}
|
||||
resp, inMount := reshapeCrossMountRename(mountedDir, &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/plain",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "back.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: stamp},
|
||||
NewParentPath: mountedDir + "/lock",
|
||||
NewEntry: newEntry,
|
||||
},
|
||||
})
|
||||
if !inMount || !filer_pb.IsCreate(resp) {
|
||||
t.Fatalf("reshape = %+v inMount=%v, want a create", resp, inMount)
|
||||
}
|
||||
if shouldSendToRemote(resp.EventNotification.NewEntry) {
|
||||
t.Fatal("precondition: the stamp the rename carried should fail shouldSendToRemote")
|
||||
}
|
||||
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: newEntry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp, true, "/plain/back.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantWrite := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/lock/back.txt"}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Fatalf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
|
||||
// a plain create keeps trusting the stamp
|
||||
remote = &recordingRemote{}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp, false, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want the stamped create skipped", remote.writes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenameIntoMountWritesAnEmptyFile: a rename into the mount is reshaped
|
||||
// to a create with mustSend, and an empty entry has no data for the HasData
|
||||
// gate; the new key still takes a zero-byte object. A remote-only entry holds
|
||||
// nothing local to send and is skipped as before.
|
||||
func TestRenameIntoMountWritesAnEmptyFile(t *testing.T) {
|
||||
const mountedDir = "/buckets/mount"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/"}
|
||||
renameIn := func(entry *filer_pb.Entry) *filer_pb.SubscribeMetadataResponse {
|
||||
resp, inMount := reshapeCrossMountRename(mountedDir, &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/plain",
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: entry, NewParentPath: mountedDir + "/lock", NewEntry: entry},
|
||||
})
|
||||
if !inMount || !filer_pb.IsCreate(resp) {
|
||||
t.Fatalf("reshape = %+v inMount=%v, want a create", resp, inMount)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
wantWrite := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/lock/empty.txt"}
|
||||
|
||||
t.Run("an empty entry writes a zero-byte object", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
if filer.HasData(entry) {
|
||||
t.Fatal("precondition: an empty entry carries no data")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true, "/plain/empty.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Errorf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a remote-only entry still skips", func(t *testing.T) {
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 7}, RemoteEntry: stamp}
|
||||
if !isRemoteOnly(entry) {
|
||||
t.Fatal("precondition: the entry should be remote-only")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true, "/plain/empty.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none for a remote-only entry", remote.writes)
|
||||
}
|
||||
})
|
||||
|
||||
// a stamped entry truncated to zero is not remote-only content: its stamp
|
||||
// describes bytes the file no longer holds, so the new key takes a
|
||||
// zero-byte object
|
||||
t.Run("a truncated stamped entry writes a zero-byte object", func(t *testing.T) {
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 7, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: stamp}
|
||||
if !isRemoteOnly(entry) || isDroppedLocalCopy(entry) {
|
||||
t.Fatal("precondition: a truncated stamped entry reports remote-only but is not a dropped copy")
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), true, "/plain/empty.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) {
|
||||
t.Errorf("writes = %+v, want the new key %s written", remote.writes, remote_storage.FormatLocation(wantWrite))
|
||||
}
|
||||
})
|
||||
|
||||
// an ordinary create of an empty entry is unchanged: no object
|
||||
t.Run("a plain empty create still writes nothing", func(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := &stubFilerClient{entry: entry}
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn(entry), false, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want the empty create skipped", remote.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestSupersededRenameInRecoversTheCurrentEntry covers a rename into the
|
||||
// mount whose create event the sync reaches only after remote.uncache dropped
|
||||
// the moved file's chunks: the upload is superseded, and skipping it leaves
|
||||
// the destination object missing once the source side's delete runs.
|
||||
func TestSupersededRenameInRecoversTheCurrentEntry(t *testing.T) {
|
||||
const mountedDir = "/buckets/mount"
|
||||
mountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/mnt"}
|
||||
srcMountLoc := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/plain-remote"}
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "b2", RemoteETag: "abc", RemoteSize: 4, RemoteMtime: 1786096669, LastLocalSyncTsNs: 1786096669*1e9 + 1}
|
||||
// the entry as the rename logged it: local chunks plus the stamp earned
|
||||
// under the source mount
|
||||
eventEntry := &filer_pb.Entry{
|
||||
Name: "a.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 4},
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: "1,01111111", Size: 4}},
|
||||
RemoteEntry: stamp,
|
||||
}
|
||||
// the entry as remote.uncache left it: the chunks are gone and the stamp
|
||||
// still describes the source mount's object
|
||||
uncached := &filer_pb.Entry{
|
||||
Name: "a.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669, FileSize: 4},
|
||||
RemoteEntry: stamp,
|
||||
}
|
||||
mappingContent, err := proto.Marshal(&remote_pb.RemoteStorageMapping{Mappings: map[string]*remote_pb.RemoteStorageLocation{
|
||||
mountedDir: mountLoc,
|
||||
"/plain": srcMountLoc,
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mappingEntry := &filer_pb.Entry{Name: filer.REMOTE_STORAGE_MOUNT_FILE, Content: mappingContent}
|
||||
renameIn := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: mountedDir + "/lock",
|
||||
EventNotification: &filer_pb.EventNotification{NewParentPath: mountedDir + "/lock", NewEntry: eventEntry},
|
||||
}
|
||||
dest := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "bucket", Path: "/mnt/lock/a.txt"}
|
||||
|
||||
newFilerClient := func(entry *filer_pb.Entry) *stubFilerClient {
|
||||
return &stubFilerClient{entries: map[string]*filer_pb.Entry{
|
||||
mountedDir + "/lock/a.txt": proto.Clone(entry).(*filer_pb.Entry),
|
||||
filer.DirectoryEtcRemote + "/" + filer.REMOTE_STORAGE_MOUNT_FILE: mappingEntry,
|
||||
}}
|
||||
}
|
||||
|
||||
t.Run("uncached meanwhile: the source object is copied and the entry stamped", func(t *testing.T) {
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/plain-remote/a.txt": []byte("data")}}
|
||||
filerClient := newFilerClient(uncached)
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn, true, "/plain/a.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], dest) {
|
||||
t.Fatalf("writes = %+v, want the source copied to %s", remote.writes, remote_storage.FormatLocation(dest))
|
||||
}
|
||||
if string(remote.written[0]) != "data" {
|
||||
t.Errorf("written = %q, want the source object's bytes", remote.written[0])
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("updates = %d, want the entry stamped with the copy", filerClient.updates)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the destination already holds it: only a stamp", func(t *testing.T) {
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/mnt/lock/a.txt": []byte("data")}, statETags: map[string]string{"/mnt/lock/a.txt": "abc"}}
|
||||
filerClient := newFilerClient(uncached)
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn, true, "/plain/a.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none once the destination holds the content", remote.writes)
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("updates = %d, want the entry stamped", filerClient.updates)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no object on either side: the event fails", func(t *testing.T) {
|
||||
remote := &recordingRemote{objects: map[string][]byte{}}
|
||||
filerClient := newFilerClient(uncached)
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn, true, "/plain/a.txt"); err == nil {
|
||||
t.Fatal("want the event to fail and hold the offset")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a pending marker under the mount names the source", func(t *testing.T) {
|
||||
marked := proto.Clone(uncached).(*filer_pb.Entry)
|
||||
marked.Extended = map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte(mountedDir + "/lock/old.txt")}
|
||||
remote := &recordingRemote{objects: map[string][]byte{"/mnt/lock/old.txt": []byte("data")}}
|
||||
filerClient := newFilerClient(marked)
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn, true, "/plain/a.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], dest) {
|
||||
t.Fatalf("writes = %+v, want the marked source copied to %s", remote.writes, remote_storage.FormatLocation(dest))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rewritten since: the superseding event uploads", func(t *testing.T) {
|
||||
rewritten := &filer_pb.Entry{
|
||||
Name: "a.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1786096700, FileSize: 4},
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: "2,02222222", Size: 4}},
|
||||
RemoteEntry: stamp,
|
||||
}
|
||||
remote := &recordingRemote{}
|
||||
filerClient := newFilerClient(rewritten)
|
||||
if err := processCreateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, renameIn, true, "/plain/a.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want the rewrite's own event to upload", remote.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestIsSystemPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
dir string
|
||||
@@ -2086,4 +2439,3 @@ func TestRemoteSyncSkipsSystemFolder(t *testing.T) {
|
||||
t.Fatalf("expected 0 remote deletes for system path, got %d deletes", len(remote.deletes))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -222,7 +223,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
if state == nil || state.processor == nil {
|
||||
return
|
||||
}
|
||||
offsetTsNs := state.processor.processedTsWatermark.Load()
|
||||
offsetTsNs := resumeTsNsFor(state.processor)
|
||||
if offsetTsNs == 0 {
|
||||
return
|
||||
}
|
||||
@@ -475,7 +476,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
lastProgressedTsNs = offsetTsNs
|
||||
// collect synchronous offset
|
||||
statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(offsetTsNs))
|
||||
return setOffset(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, offsetTsNs)
|
||||
return setOffset(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor))
|
||||
})
|
||||
|
||||
prefix := sourcePath
|
||||
@@ -495,7 +496,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return processor.processedTsWatermark.Load()
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
Resubscribe: processor.ResubscribeCh(),
|
||||
// While the source has only read activity it emits no metadata events, so
|
||||
@@ -576,16 +577,77 @@ func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddres
|
||||
return lastOffsetTsNs, err
|
||||
}
|
||||
|
||||
func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, offsetTsNs int64) error {
|
||||
return pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// A checkpoint write can outlive its caller's wait and land beside the next
|
||||
// subscription attempt's writes; issued concurrently they may be applied out
|
||||
// of order, moving saved progress backward or forward past events still owed
|
||||
// a replay. Writes to the same persisted key are serialized and each is
|
||||
// ordered by issuance: a write issued before the last one to land is stale
|
||||
// and dropped. Deliberate regressions — resume floors, operator seeds — are
|
||||
// issued after the writes they supersede, so they still apply. State is keyed
|
||||
// by target filer so unrelated streams — or the two directions of a
|
||||
// bidirectional sync — never block or shadow each other.
|
||||
var offsetCheckpointWrites = struct {
|
||||
sync.Mutex
|
||||
byKey map[string]*offsetCheckpoint
|
||||
}{byKey: map[string]*offsetCheckpoint{}}
|
||||
|
||||
syncKey := []byte(signaturePrefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
|
||||
type offsetCheckpoint struct {
|
||||
sync.Mutex
|
||||
lastSeq int64
|
||||
}
|
||||
|
||||
// resumeTsNsFor floors the processed watermark by the earliest failure the
|
||||
// processor saw: a redelivery can clear the pin, but events dropped while it
|
||||
// was stopped only replay if the resume position stays behind it. It also
|
||||
// stays one tick below the newest timestamp seen — a watermark on the
|
||||
// frontier can have finished every job it admitted while more events at the
|
||||
// same timestamp still sit unread in the log, and an exclusive resume there
|
||||
// would skip them.
|
||||
func resumeTsNsFor(p *MetadataProcessor) int64 {
|
||||
ts := p.processedTsWatermark.Load()
|
||||
if newestTsNs := p.NewestSeenTsNs(); newestTsNs > 0 && ts >= newestTsNs {
|
||||
ts = newestTsNs - 1
|
||||
}
|
||||
if failedTsNs := p.EarliestFailedTsNs(); failedTsNs > 0 && failedTsNs-1 < ts {
|
||||
ts = failedTsNs - 1
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
// offsetWriteSeq numbers checkpoint writes in issuance order so a write that
|
||||
// lands late can be told apart from the fresher write it would shadow.
|
||||
var offsetWriteSeq atomic.Int64
|
||||
|
||||
func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, offsetTsNs int64) error {
|
||||
syncKey := []byte(signaturePrefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
|
||||
key := string(filer) + "\x00" + string(syncKey)
|
||||
|
||||
offsetCheckpointWrites.Lock()
|
||||
checkpoint := offsetCheckpointWrites.byKey[key]
|
||||
if checkpoint == nil {
|
||||
checkpoint = &offsetCheckpoint{}
|
||||
offsetCheckpointWrites.byKey[key] = checkpoint
|
||||
}
|
||||
offsetCheckpointWrites.Unlock()
|
||||
|
||||
seq := offsetWriteSeq.Add(1)
|
||||
checkpoint.Lock()
|
||||
defer checkpoint.Unlock()
|
||||
if seq < checkpoint.lastSeq {
|
||||
return nil
|
||||
}
|
||||
checkpoint.lastSeq = seq
|
||||
|
||||
return pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
valueBuf := make([]byte, 8)
|
||||
util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
|
||||
|
||||
resp, err := client.KvPut(context.Background(), &filer_pb.KvPutRequest{
|
||||
// a stalled KvPut must not hold a caller's drain or persistence loop
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
resp, err := client.KvPut(ctx, &filer_pb.KvPutRequest{
|
||||
Key: syncKey,
|
||||
Value: valueBuf,
|
||||
})
|
||||
@@ -600,7 +662,6 @@ func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signature
|
||||
return nil
|
||||
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func genProcessFunction(sourcePath string, targetPath string, excludePaths []string, reExcludeFileName *regexp.Regexp, excludeFileNames []*wildcard.WildcardMatcher, excludePathPatterns []*wildcard.WildcardMatcher, dataSink sink.ReplicationSink, doDeleteFiles bool, debug bool) func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
|
||||
@@ -137,6 +137,19 @@ type MetadataProcessor struct {
|
||||
failedSticky bool
|
||||
oldestFailedTsNs int64
|
||||
|
||||
// earliestFailedTsNs is the smallest timestamp this processor ever failed
|
||||
// on, latched for its lifetime: a redelivery can clear failedTs, but by
|
||||
// then the processor is stopped and has already dropped unrecorded
|
||||
// events — possibly sharing the failure's timestamp — so a resume
|
||||
// position must still sit behind it.
|
||||
earliestFailedTsNs int64
|
||||
|
||||
// newestSeenTsNs is the largest TsNs the stream has offered, job or
|
||||
// marker. A watermark equal to it is not a safe resume point: more
|
||||
// events at the same timestamp can still sit unread in the log, so the
|
||||
// persisted position has to stay one tick below it.
|
||||
newestSeenTsNs int64
|
||||
|
||||
// resubscribeCh closes once a failure has stopped the processor and all
|
||||
// in-flight jobs have drained, asking the metadata follower to drop the
|
||||
// stream so the caller's reconnect replays the pinned events in order —
|
||||
@@ -199,6 +212,21 @@ func (t *MetadataProcessor) OldestFailedTsNs() int64 {
|
||||
return t.oldestFailedTsNs
|
||||
}
|
||||
|
||||
// EarliestFailedTsNs returns the smallest timestamp this processor has ever
|
||||
// failed on, including failures later cleared by a redelivery.
|
||||
func (t *MetadataProcessor) EarliestFailedTsNs() int64 {
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
return t.earliestFailedTsNs
|
||||
}
|
||||
|
||||
// NewestSeenTsNs returns the largest TsNs the stream has offered so far.
|
||||
func (t *MetadataProcessor) NewestSeenTsNs() int64 {
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
return t.newestSeenTsNs
|
||||
}
|
||||
|
||||
// ResubscribeCh closes once a job failure has stopped the processor and its
|
||||
// in-flight jobs have drained, signaling the metadata follower to drop the
|
||||
// stream so a reconnect replays what the watermark still covers.
|
||||
@@ -206,6 +234,18 @@ func (t *MetadataProcessor) ResubscribeCh() <-chan struct{} {
|
||||
return t.resubscribeCh
|
||||
}
|
||||
|
||||
// Drain blocks until every admitted job has finished. Callers whose stream
|
||||
// just ended use it before reconnecting: a replayed event must not race a
|
||||
// still-running job for the same path, or the older write could finish last
|
||||
// and clobber the newer one.
|
||||
func (t *MetadataProcessor) Drain() {
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
for t.activeJobCount > 0 {
|
||||
t.activeJobsCond.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// pathAncestors returns all proper ancestor directories of p.
|
||||
// For "/a/b/c", returns ["/a/b", "/a", "/"].
|
||||
func pathAncestors(p util.FullPath) []util.FullPath {
|
||||
@@ -339,6 +379,9 @@ func (t *MetadataProcessor) AddSyncJob(resp *filer_pb.SubscribeMetadataResponse)
|
||||
// to it so idle stretches still advance the resume point.
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
if resp.TsNs > t.newestSeenTsNs {
|
||||
t.newestSeenTsNs = resp.TsNs
|
||||
}
|
||||
if resp.TsNs > t.filteredTsNs {
|
||||
t.filteredTsNs = resp.TsNs
|
||||
}
|
||||
@@ -354,6 +397,10 @@ func (t *MetadataProcessor) AddSyncJob(resp *filer_pb.SubscribeMetadataResponse)
|
||||
t.activeJobsLock.Lock()
|
||||
defer t.activeJobsLock.Unlock()
|
||||
|
||||
if resp.TsNs > t.newestSeenTsNs {
|
||||
t.newestSeenTsNs = resp.TsNs
|
||||
}
|
||||
|
||||
p, newPath, kind := extractJobInfo(resp)
|
||||
eventKey := failedEventKey{tsNs: resp.TsNs, path: p, newPath: newPath, kind: kind}
|
||||
|
||||
@@ -425,6 +472,9 @@ func (t *MetadataProcessor) AddSyncJob(resp *filer_pb.SubscribeMetadataResponse)
|
||||
// whole mechanism exists to remove.
|
||||
t.stopped = true
|
||||
t.activeJobsCond.Broadcast()
|
||||
if t.earliestFailedTsNs == 0 || resp.TsNs < t.earliestFailedTsNs {
|
||||
t.earliestFailedTsNs = resp.TsNs
|
||||
}
|
||||
if t.failedSticky {
|
||||
if resp.TsNs < t.oldestFailedTsNs {
|
||||
t.oldestFailedTsNs = resp.TsNs
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"container/heap"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -553,6 +554,61 @@ func TestSamePathBarrierSerialization(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestConcurrentJobsUpToLimit proves independent-path jobs run in parallel up
|
||||
// to the concurrency limit: every admitted job is in flight before any
|
||||
// finishes (a serial loop could only have one running), and admissions past
|
||||
// the limit wait for a slot rather than running ahead of it.
|
||||
func TestConcurrentJobsUpToLimit(t *testing.T) {
|
||||
const limit = 3
|
||||
started := make(chan struct{}, limit)
|
||||
release := make(chan struct{})
|
||||
var inFlight, maxInFlight atomic.Int32
|
||||
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
cur := inFlight.Add(1)
|
||||
for {
|
||||
if old := maxInFlight.Load(); cur <= old || maxInFlight.CompareAndSwap(old, cur) {
|
||||
break
|
||||
}
|
||||
}
|
||||
started <- struct{}{}
|
||||
<-release
|
||||
inFlight.Add(-1)
|
||||
return nil
|
||||
}, limit, 0)
|
||||
|
||||
admitDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(admitDone)
|
||||
for i := 0; i < limit+1; i++ {
|
||||
p.AddSyncJob(makeResp("/d", fmt.Sprintf("f%d", i), false, int64(i+1), true))
|
||||
}
|
||||
}()
|
||||
|
||||
for i := 0; i < limit; i++ {
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("only %d of %d jobs entered flight", i, limit)
|
||||
}
|
||||
}
|
||||
// The extra admission must still be blocked on a full pool.
|
||||
select {
|
||||
case <-started:
|
||||
t.Fatal("a job started with no free slot")
|
||||
case <-admitDone:
|
||||
t.Fatal("submission returned past the concurrency limit")
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
|
||||
close(release)
|
||||
<-admitDone
|
||||
p.Drain()
|
||||
if got := maxInFlight.Load(); got != limit {
|
||||
t.Fatalf("peak in-flight = %d, want %d", got, limit)
|
||||
}
|
||||
}
|
||||
|
||||
// benchResult prevents the compiler from optimizing away the conflict check.
|
||||
var benchResult bool
|
||||
|
||||
@@ -1073,3 +1129,107 @@ func TestResubscribeWaitsForSameTsSibling(t *testing.T) {
|
||||
t.Fatal("resubscribe channel never closed after the same-ts jobs drained")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResumeStaysBehindClearedPin verifies the resume floor outlives the
|
||||
// ledger pin: a redelivery can clear failedTs, but events dropped while the
|
||||
// processor was stopped — including ones sharing the failure's timestamp —
|
||||
// still have to replay, so the resume position stays one tick below the
|
||||
// earliest failure.
|
||||
func TestResumeStaysBehindClearedPin(t *testing.T) {
|
||||
fail := true
|
||||
release := make(chan struct{})
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
name := resp.EventNotification.NewEntry.GetName()
|
||||
if name == "slow.txt" {
|
||||
<-release
|
||||
}
|
||||
if name == "bad.txt" && fail {
|
||||
return errors.New("AccessDenied: Access Denied")
|
||||
}
|
||||
return nil
|
||||
}, 10, 0)
|
||||
|
||||
// the slow job holds the drain — and the resubscribe — open so the
|
||||
// redelivery still lands on this processor
|
||||
p.AddSyncJob(makeResp("/dir", "slow.txt", false, 300, true))
|
||||
p.AddSyncJob(makeResp("/dir", "bad.txt", false, 200, true))
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() != 200 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
|
||||
// a same-ts sibling arriving after the stop is dropped
|
||||
p.AddSyncJob(makeResp("/dir", "sib.txt", false, 200, true))
|
||||
p.activeJobsLock.Lock()
|
||||
dropped := p.activeJobTs[200] == 0
|
||||
p.activeJobsLock.Unlock()
|
||||
if !dropped {
|
||||
t.Fatal("sibling admitted after the failure stopped the processor")
|
||||
}
|
||||
|
||||
// the redelivery runs and clears the pin
|
||||
fail = false
|
||||
p.AddSyncJob(makeResp("/dir", "bad.txt", false, 200, true))
|
||||
deadline = time.Now().Add(10 * time.Second)
|
||||
for p.OldestFailedTsNs() != 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if got := p.OldestFailedTsNs(); got != 0 {
|
||||
t.Fatalf("oldest failed = %d after the redelivery, want 0", got)
|
||||
}
|
||||
|
||||
if got := p.EarliestFailedTsNs(); got != 200 {
|
||||
t.Fatalf("earliest failed = %d, want the floor held at 200", got)
|
||||
}
|
||||
if got := resumeTsNsFor(p); got != 199 {
|
||||
t.Fatalf("resume = %d, want 199 so the dropped sibling replays", got)
|
||||
}
|
||||
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p)
|
||||
}
|
||||
|
||||
// TestResumeStaysBelowNewestSeen covers the frontier case: when every admitted
|
||||
// job has finished, the watermark sits on the newest timestamp seen — but the
|
||||
// log can still hold same-timestamp events the stream has not delivered yet.
|
||||
// An exclusive resume there would skip them, so the position stays one tick
|
||||
// below until a newer timestamp proves the block is closed.
|
||||
func TestResumeStaysBelowNewestSeen(t *testing.T) {
|
||||
p := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
return nil
|
||||
}, 10, 0)
|
||||
|
||||
// the event at 100 finishes before a same-timestamp sibling could even be
|
||||
// read; the watermark reaches the frontier but cannot persist there
|
||||
p.AddSyncJob(makeResp("/dir", "a.txt", false, 100, true))
|
||||
waitForJobsToDrain(t, p)
|
||||
if got := resumeTsNsFor(p); got != 99 {
|
||||
t.Fatalf("resume = %d at the frontier, want 99 so an unread same-ts event replays", got)
|
||||
}
|
||||
|
||||
// once a newer timestamp is seen the 100-block is closed: a slow job at
|
||||
// 200 in flight pins nothing below it, so 100 is now a safe position
|
||||
release := make(chan struct{})
|
||||
p2 := NewMetadataProcessor(func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if resp.TsNs == 200 {
|
||||
<-release
|
||||
}
|
||||
return nil
|
||||
}, 10, 0)
|
||||
p2.AddSyncJob(makeResp("/dir", "c.txt", false, 100, true))
|
||||
p2.AddSyncJob(makeResp("/dir", "b.txt", false, 200, true))
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for p2.processedTsWatermark.Load() != 100 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if got := resumeTsNsFor(p2); got != 100 {
|
||||
t.Fatalf("resume = %d below the frontier, want 100", got)
|
||||
}
|
||||
|
||||
// finishing the 200 job lands the watermark back on the frontier
|
||||
close(release)
|
||||
waitForJobsToDrain(t, p2)
|
||||
if got := resumeTsNsFor(p2); got != 199 {
|
||||
t.Fatalf("resume = %d at the frontier, want 199", got)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package command
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// The offset key is a persistence contract: a changed form orphans saved
|
||||
// checkpoints, so the historical forms must survive verbatim and the
|
||||
@@ -74,3 +78,50 @@ func TestSyncOffset_HistoricalFallbackThenIndependence(t *testing.T) {
|
||||
t.Fatalf("B read = (%d, %v), want (111, nil)", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncOffset_StaleWriteDropped: a checkpoint write issued before a write
|
||||
// that already landed under the same key is stale and must not apply, while
|
||||
// a deliberately regressed value issued later — a resume floor or an
|
||||
// operator seed — still does.
|
||||
func TestSyncOffset_StaleWriteDropped(t *testing.T) {
|
||||
filerAddr, dial := startKvFiler(t)
|
||||
prefix := getSignaturePrefixByPath("/data", "/backup-stale")
|
||||
sourceSig := int32(77)
|
||||
|
||||
if err := setOffset(dial, filerAddr, prefix, sourceSig, 300); err != nil {
|
||||
t.Fatalf("seed offset: %v", err)
|
||||
}
|
||||
|
||||
// Pin the checkpoint past the next write's issuance seq, simulating a
|
||||
// write that was issued before a newer one already landed.
|
||||
syncKey := []byte(prefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(prefix):len(prefix)+4], uint32(sourceSig))
|
||||
mapKey := string(filerAddr) + "\x00" + string(syncKey)
|
||||
offsetCheckpointWrites.Lock()
|
||||
checkpoint := offsetCheckpointWrites.byKey[mapKey]
|
||||
offsetCheckpointWrites.Unlock()
|
||||
if checkpoint == nil {
|
||||
t.Fatal("no checkpoint state for the seeded key")
|
||||
}
|
||||
checkpoint.Lock()
|
||||
checkpoint.lastSeq = offsetWriteSeq.Load() + 1000
|
||||
checkpoint.Unlock()
|
||||
|
||||
if err := setOffset(dial, filerAddr, prefix, sourceSig, 100); err != nil {
|
||||
t.Fatalf("stale write: %v", err)
|
||||
}
|
||||
if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 300 {
|
||||
t.Fatalf("after stale write = (%d, %v), want (300, nil)", got, err)
|
||||
}
|
||||
|
||||
// a later-issued regression is deliberate and must apply
|
||||
checkpoint.Lock()
|
||||
checkpoint.lastSeq = 0
|
||||
checkpoint.Unlock()
|
||||
if err := setOffset(dial, filerAddr, prefix, sourceSig, 199); err != nil {
|
||||
t.Fatalf("floored write: %v", err)
|
||||
}
|
||||
if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 199 {
|
||||
t.Fatalf("after floored write = (%d, %v), want (199, nil)", got, err)
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,6 @@ type MasterOptions struct {
|
||||
fileSizeLimitMB *int
|
||||
volumePreallocate *bool
|
||||
maxParallelVacuumPerServer *int
|
||||
maxWritableVolumes *int
|
||||
vacuumIntervalSeconds *int
|
||||
vacuumDeleteEmptyAfterSeconds *int
|
||||
// pulseSeconds *int
|
||||
@@ -95,8 +94,7 @@ func init() {
|
||||
m.volumeSizeLimitMB = cmdMaster.Flag.Uint("volumeSizeLimitMB", util.DefaultVolumeSizeLimitMB, "Master stops directing writes to oversized volumes.")
|
||||
m.fileSizeLimitMB = cmdMaster.Flag.Int("fileSizeLimitMB", 256, "limit the file size accepted by /submit, should match the volume servers' -fileSizeLimitMB (-volume.fileSizeLimitMB under weed server or weed mini, which set this for you)")
|
||||
m.volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
m.maxParallelVacuumPerServer = cmdMaster.Flag.Int("maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel per volume server")
|
||||
m.maxWritableVolumes = cmdMaster.Flag.Int("maxWritableVolumes", 0, "maximum writable volumes in a volume layout (collection + replica placement + ttl + disk type) assignments are spread over, fullest picked first; 0 means no limit")
|
||||
m.maxParallelVacuumPerServer = cmdMaster.Flag.Int("maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel per volume server; 0 for no limit (deprecated, use master.vacuum.max_parallel_per_server in master.toml)")
|
||||
m.vacuumIntervalSeconds = cmdMaster.Flag.Int("vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
m.vacuumDeleteEmptyAfterSeconds = cmdMaster.Flag.Int("vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
// m.pulseSeconds = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
|
||||
@@ -479,7 +477,6 @@ func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOp
|
||||
FileSizeLimitMB: *m.fileSizeLimitMB,
|
||||
VolumePreallocate: *m.volumePreallocate,
|
||||
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
|
||||
MaxWritableVolumes: *m.maxWritableVolumes,
|
||||
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
|
||||
VacuumDeleteEmptyAfterSeconds: *m.vacuumDeleteEmptyAfterSeconds,
|
||||
// PulseSeconds: *m.pulseSeconds,
|
||||
@@ -491,5 +488,6 @@ func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOp
|
||||
MetricsIntervalSec: *m.metricsIntervalSec,
|
||||
TelemetryUrl: *m.telemetryUrl,
|
||||
TelemetryEnabled: *m.telemetryEnabled,
|
||||
SingleMaster: isSingleMasterMode(*m.peers),
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ func init() {
|
||||
mf.metricsIntervalSec = aws.Int(0)
|
||||
mf.raftResumeState = aws.Bool(false)
|
||||
mf.maxParallelVacuumPerServer = aws.Int(1)
|
||||
mf.maxWritableVolumes = aws.Int(0)
|
||||
mf.vacuumIntervalSeconds = aws.Int(840)
|
||||
mf.vacuumDeleteEmptyAfterSeconds = aws.Int(0)
|
||||
mf.telemetryUrl = aws.String("https://telemetry.seaweedfs.com/api/collect")
|
||||
|
||||
@@ -445,8 +445,7 @@ func initMiniMasterFlags() {
|
||||
miniMasterOptions.peers = cmdMini.Flag.String("master.peers", "", "all master nodes in comma separated ip:masterPort list (default: none for single master)")
|
||||
miniMasterOptions.volumeSizeLimitMB = cmdMini.Flag.Uint("master.volumeSizeLimitMB", defaultMiniVolumeSizeMB, "Master stops directing writes to oversized volumes (default: 128MB for mini)")
|
||||
miniMasterOptions.volumePreallocate = cmdMini.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
miniMasterOptions.maxParallelVacuumPerServer = cmdMini.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
|
||||
miniMasterOptions.maxWritableVolumes = cmdMini.Flag.Int("master.maxWritableVolumes", 0, "maximum writable volumes in a volume layout (collection + replica placement + ttl + disk type) assignments are spread over, fullest picked first; 0 means no limit")
|
||||
miniMasterOptions.maxParallelVacuumPerServer = cmdMini.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server; 0 for no limit (deprecated, use master.vacuum.max_parallel_per_server in master.toml)")
|
||||
miniMasterOptions.vacuumIntervalSeconds = cmdMini.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
miniMasterOptions.vacuumDeleteEmptyAfterSeconds = cmdMini.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
miniMasterOptions.defaultReplication = cmdMini.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
|
||||
@@ -517,6 +516,9 @@ func initMiniVolumeFlags() {
|
||||
miniOptions.v.hasSlowRead = cmdMini.Flag.Bool("volume.hasSlowRead", true, "if true, prevents slow reads from blocking other requests")
|
||||
miniOptions.v.readBufferSizeMB = cmdMini.Flag.Int("volume.readBufferSizeMB", 4, "read buffer size in MB")
|
||||
miniOptions.v.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("volume.allowUntrustedRemoteEndpoints", false, "if true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints.")
|
||||
miniOptions.v.fsyncMinBatchBytes = cmdMini.Flag.Int64("volume.fsyncMinBatchBytes", 1*1024*1024, "minimum bytes an fsync batch gathers before a drained queue flushes without waiting")
|
||||
miniOptions.v.fsyncMinBatchRequests = cmdMini.Flag.Int("volume.fsyncMinBatchRequests", 128, "minimum requests an fsync batch gathers before a drained queue flushes without waiting")
|
||||
miniOptions.v.fsyncBatchWait = cmdMini.Flag.Duration("volume.fsyncBatchWait", 500*time.Microsecond, "how long a below-minimum fsync batch waits for more requests once the queue drains; 0 flushes immediately")
|
||||
miniOptions.v.preStopSeconds = cmdMini.Flag.Int("volume.preStopSeconds", 1, "number of seconds between stop send heartbeats and stop volume server (default: 1 for mini)")
|
||||
miniOptions.v.setDiskIOProbeDefaults()
|
||||
}
|
||||
|
||||
@@ -66,6 +66,9 @@
|
||||
# replica_placement = ""
|
||||
# fail planning when the placement constraints cannot be met instead of relaxing them
|
||||
# strict_placement = false
|
||||
# volume-slot deadband for shard placement: nodes whose free volume slots differ by at
|
||||
# most this much tie and fewer live shards wins; applied times data shards (0 = strict)
|
||||
# free_slots_deadband = 0
|
||||
# max retry attempts for a failed erasure coding job
|
||||
# retry_limit = 1
|
||||
# seconds to wait between retry attempts
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
# /etc/seaweedfs/master.toml
|
||||
# this file is read by master
|
||||
|
||||
[master]
|
||||
# cap on writable volumes per volume layout (collection + replica placement +
|
||||
# ttl + disk type) that write assignments spread over; fullest picked first.
|
||||
# 0 = no limit
|
||||
max_writable_volumes_per_layout = 0
|
||||
|
||||
|
||||
[master.maintenance]
|
||||
# periodically run these scripts are the same as running them from 'weed shell'
|
||||
# Scripts are skipped while an admin server is connected.
|
||||
@@ -11,6 +18,15 @@ scripts = """{{DEFAULT_MAINTENANCE_SCRIPTS}}"""
|
||||
sleep_minutes = 17 # sleep minutes between each script execution
|
||||
|
||||
|
||||
# vacuum reclaims deleted space by compacting volumes
|
||||
[master.vacuum]
|
||||
# concurrent volume compactions per volume server; overrides the deprecated
|
||||
# -maxParallelVacuumPerServer flag (default 1) when set; 0 = no limit
|
||||
# max_parallel_per_server = 1
|
||||
# concurrent volume copies compacting within one rack; 0 = no limit
|
||||
max_parallel_per_rack = 0
|
||||
|
||||
|
||||
[master.sequencer]
|
||||
type = "raft" # Choose [raft|snowflake] type for storing the file id sequence
|
||||
# when sequencer.type = snowflake, the snowflake id must be different from other masters
|
||||
|
||||
@@ -81,3 +81,16 @@ workers = 5 # optional: concurrent worker
|
||||
buffer_size = 10000 # optional: event buffer size (default: 10000, range: 100-1000000)
|
||||
# event_types = ["create", "update", "delete", "rename"] # optional: filter by event types (default: all)
|
||||
# path_prefixes = ["/important", "/data"] # optional: filter by path prefixes (default: all)
|
||||
#
|
||||
# Additional endpoints can be declared as named subsections, each with its own
|
||||
# endpoint, filters, retry and worker settings, e.g.:
|
||||
# [notification.webhook.file_ingress]
|
||||
# enabled = true
|
||||
# endpoint = "https://ingress.example.com/hook"
|
||||
# event_types = ["create"]
|
||||
# path_prefixes = ["/buckets/uploads/data"]
|
||||
#
|
||||
# [notification.webhook.metadata_extractor]
|
||||
# enabled = true
|
||||
# endpoint = "https://metadata.example.com/hook"
|
||||
# path_prefixes = ["/buckets/repository"]
|
||||
@@ -97,8 +97,7 @@ func init() {
|
||||
masterOptions.peers = cmdServer.Flag.String("master.peers", "", "all master nodes in comma separated ip:masterPort list")
|
||||
masterOptions.volumeSizeLimitMB = cmdServer.Flag.Uint("master.volumeSizeLimitMB", util.DefaultVolumeSizeLimitMB, "Master stops directing writes to oversized volumes.")
|
||||
masterOptions.volumePreallocate = cmdServer.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
masterOptions.maxParallelVacuumPerServer = cmdServer.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
|
||||
masterOptions.maxWritableVolumes = cmdServer.Flag.Int("master.maxWritableVolumes", 0, "maximum writable volumes in a volume layout (collection + replica placement + ttl + disk type) assignments are spread over, fullest picked first; 0 means no limit")
|
||||
masterOptions.maxParallelVacuumPerServer = cmdServer.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server; 0 for no limit (deprecated, use master.vacuum.max_parallel_per_server in master.toml)")
|
||||
masterOptions.vacuumIntervalSeconds = cmdServer.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
masterOptions.vacuumDeleteEmptyAfterSeconds = cmdServer.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
masterOptions.defaultReplication = cmdServer.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
|
||||
@@ -165,6 +164,9 @@ func init() {
|
||||
serverOptions.v.hasSlowRead = cmdServer.Flag.Bool("volume.hasSlowRead", true, "<experimental> if true, this prevents slow reads from blocking other requests, but large file read P99 latency will increase.")
|
||||
serverOptions.v.readBufferSizeMB = cmdServer.Flag.Int("volume.readBufferSizeMB", 4, "<experimental> larger values can optimize query performance but will increase some memory usage,Use with hasSlowRead normally")
|
||||
serverOptions.v.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("volume.allowUntrustedRemoteEndpoints", false, "if true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints.")
|
||||
serverOptions.v.fsyncMinBatchBytes = cmdServer.Flag.Int64("volume.fsyncMinBatchBytes", 1*1024*1024, "minimum bytes an fsync batch gathers before a drained queue flushes without waiting")
|
||||
serverOptions.v.fsyncMinBatchRequests = cmdServer.Flag.Int("volume.fsyncMinBatchRequests", 128, "minimum requests an fsync batch gathers before a drained queue flushes without waiting")
|
||||
serverOptions.v.fsyncBatchWait = cmdServer.Flag.Duration("volume.fsyncBatchWait", 500*time.Microsecond, "how long a below-minimum fsync batch waits for more requests once the queue drains; 0 flushes immediately")
|
||||
serverOptions.v.setDiskIOProbeDefaults()
|
||||
|
||||
s3Options.port = cmdServer.Flag.Int("s3.port", 8333, "s3 server http listen port")
|
||||
|
||||
@@ -76,6 +76,9 @@ type VolumeServerOptions struct {
|
||||
readBufferSizeMB *int
|
||||
ldbTimeout *int64
|
||||
allowUntrustedRemoteEndpoints *bool
|
||||
fsyncMinBatchBytes *int64
|
||||
fsyncMinBatchRequests *int
|
||||
fsyncBatchWait *time.Duration
|
||||
debug *bool
|
||||
debugPort *int
|
||||
diskIOProbe *bool
|
||||
@@ -147,6 +150,22 @@ func (v *VolumeServerOptions) setDiskIOProbeDefaults() {
|
||||
}
|
||||
}
|
||||
|
||||
// syncBatchOption resolves the fsync batch window, defaulting each field so
|
||||
// commands or embedders that leave the option pointers unset still start.
|
||||
func (v *VolumeServerOptions) syncBatchOption() storage.SyncBatchOption {
|
||||
option := storage.DefaultSyncBatchOption
|
||||
if v.fsyncMinBatchBytes != nil {
|
||||
option.MinBytes = *v.fsyncMinBatchBytes
|
||||
}
|
||||
if v.fsyncMinBatchRequests != nil {
|
||||
option.MinRequests = *v.fsyncMinBatchRequests
|
||||
}
|
||||
if v.fsyncBatchWait != nil {
|
||||
option.Wait = *v.fsyncBatchWait
|
||||
}
|
||||
return option
|
||||
}
|
||||
|
||||
func (v *VolumeServerOptions) applyDiskIOProbeConfig() {
|
||||
v.setDiskIOProbeDefaults()
|
||||
|
||||
@@ -230,6 +249,9 @@ func init() {
|
||||
v.hasSlowRead = cmdVolume.Flag.Bool("hasSlowRead", true, "<experimental> if true, this prevents slow reads from blocking other requests, but large file read P99 latency will increase.")
|
||||
v.readBufferSizeMB = cmdVolume.Flag.Int("readBufferSizeMB", 4, "<experimental> larger values can optimize query performance but will increase some memory usage,Use with hasSlowRead normally.")
|
||||
v.allowUntrustedRemoteEndpoints = cmdVolume.Flag.Bool("volume.allowUntrustedRemoteEndpoints", false, "if true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints.")
|
||||
v.fsyncMinBatchBytes = cmdVolume.Flag.Int64("fsyncMinBatchBytes", 1*1024*1024, "minimum bytes an fsync batch gathers before a drained queue flushes without waiting")
|
||||
v.fsyncMinBatchRequests = cmdVolume.Flag.Int("fsyncMinBatchRequests", 128, "minimum requests an fsync batch gathers before a drained queue flushes without waiting")
|
||||
v.fsyncBatchWait = cmdVolume.Flag.Duration("fsyncBatchWait", 500*time.Microsecond, "how long a below-minimum fsync batch waits for more requests once the queue drains; 0 flushes immediately")
|
||||
v.debug = cmdVolume.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
|
||||
v.debugPort = cmdVolume.Flag.Int("debug.port", 6060, "http port for debugging")
|
||||
v.setDiskIOProbeDefaults()
|
||||
@@ -460,6 +482,7 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
*v.ldbTimeout,
|
||||
*v.allowUntrustedRemoteEndpoints,
|
||||
diskProbeConfig,
|
||||
v.syncBatchOption(),
|
||||
)
|
||||
// starting grpc server
|
||||
grpcS := v.startGrpcService(volumeServer)
|
||||
|
||||
+1
-1
@@ -434,7 +434,7 @@ func SyncWrite(ctx context.Context) bool {
|
||||
// syncWriteContext flags ctx when the storage rule on p asks for fsync, so the
|
||||
// store write is held to the same durability as the data path.
|
||||
func (f *Filer) syncWriteContext(ctx context.Context, p util.FullPath) context.Context {
|
||||
if f.FilerConf != nil && f.FilerConf.MatchStorageRule(string(p)).Fsync {
|
||||
if f.FilerConf != nil && f.FilerConf.MatchStorageRule(string(p)).GetFsync() {
|
||||
return WithSyncWrite(ctx)
|
||||
}
|
||||
return ctx
|
||||
|
||||
+21
-12
@@ -33,10 +33,11 @@ const (
|
||||
)
|
||||
|
||||
// FilerConfVersion is stamped into every configuration this build writes.
|
||||
// Version 0 predates worm presence: it was written with EmitUnpopulated, so every
|
||||
// rule carries an explicit "worm": false that meant nothing. Reading one back as an
|
||||
// override would silently lift worm off nested paths, so it is dropped to unset.
|
||||
const FilerConfVersion = 1
|
||||
// Version 0 predates worm presence and version 1 predates fsync presence: both
|
||||
// were written with EmitUnpopulated, so every rule carries an explicit false
|
||||
// that meant nothing. Reading one back as an override would silently lift the
|
||||
// setting off nested paths, so a false from an older version is dropped to unset.
|
||||
const FilerConfVersion = 2
|
||||
|
||||
type FilerConf struct {
|
||||
rules ptrie.Trie[*filer_pb.FilerConf_PathConf]
|
||||
@@ -126,9 +127,12 @@ func (fc *FilerConf) LoadFromBytes(data []byte) (err error) {
|
||||
|
||||
func (fc *FilerConf) doLoadConf(conf *filer_pb.FilerConf) (err error) {
|
||||
for _, location := range conf.Locations {
|
||||
if conf.Version < FilerConfVersion && location.Worm != nil && !*location.Worm {
|
||||
if conf.Version < 1 && location.Worm != nil && !*location.Worm {
|
||||
location.Worm = nil
|
||||
}
|
||||
if conf.Version < 2 && location.Fsync != nil && !*location.Fsync {
|
||||
location.Fsync = nil
|
||||
}
|
||||
err = fc.SetLocationConf(location)
|
||||
if err != nil {
|
||||
// this is not recoverable
|
||||
@@ -227,7 +231,10 @@ func ClonePathConf(src *filer_pb.FilerConf_PathConf) *filer_pb.FilerConf_PathCon
|
||||
if src == nil {
|
||||
return &filer_pb.FilerConf_PathConf{}
|
||||
}
|
||||
var worm *bool
|
||||
var fsync, worm *bool
|
||||
if src.Fsync != nil {
|
||||
fsync = proto.Bool(*src.Fsync)
|
||||
}
|
||||
if src.Worm != nil {
|
||||
worm = proto.Bool(*src.Worm)
|
||||
}
|
||||
@@ -237,7 +244,7 @@ func ClonePathConf(src *filer_pb.FilerConf_PathConf) *filer_pb.FilerConf_PathCon
|
||||
Replication: src.Replication,
|
||||
Ttl: src.Ttl,
|
||||
DiskType: src.DiskType,
|
||||
Fsync: src.Fsync,
|
||||
Fsync: fsync,
|
||||
VolumeGrowthCount: src.VolumeGrowthCount,
|
||||
ReadOnly: src.ReadOnly,
|
||||
MaxFileNameLength: src.MaxFileNameLength,
|
||||
@@ -484,7 +491,7 @@ func ClearBucketLifecycleDayTTLs(ctx context.Context, client filer_pb.SeaweedFil
|
||||
// flag, a placement pin - is an operator's, and deleting the whole rule to
|
||||
// retire its TTL would take their configuration with it.
|
||||
func isLifecycleOwnedPathConf(c *filer_pb.FilerConf_PathConf) bool {
|
||||
return c.GetDiskType() == "" && !c.GetFsync() && !c.GetReadOnly() &&
|
||||
return c.GetDiskType() == "" && c.Fsync == nil && !c.GetReadOnly() &&
|
||||
c.GetDataCenter() == "" && c.GetRack() == "" && c.GetDataNode() == "" &&
|
||||
c.GetMaxFileNameLength() == 0 && !c.GetDisableChunkDeletion() &&
|
||||
c.Worm == nil && c.GetWormGracePeriodSeconds() == 0 && c.GetWormRetentionTimeSeconds() == 0
|
||||
@@ -507,7 +514,12 @@ func mergePathConf(a, b *filer_pb.FilerConf_PathConf) {
|
||||
a.Replication = util.Nvl(b.Replication, a.Replication)
|
||||
a.Ttl = util.Nvl(b.Ttl, a.Ttl)
|
||||
a.DiskType = util.Nvl(b.DiskType, a.DiskType)
|
||||
a.Fsync = b.Fsync || a.Fsync
|
||||
// fsync and worm merge on presence, so a nested rule can turn them off.
|
||||
// readOnly and disableChunkDeletion stay OR'ed on purpose: a nested rule
|
||||
// must not be able to lift a lock the bucket set.
|
||||
if b.Fsync != nil {
|
||||
a.Fsync = proto.Bool(*b.Fsync)
|
||||
}
|
||||
if b.VolumeGrowthCount > 0 {
|
||||
a.VolumeGrowthCount = b.VolumeGrowthCount
|
||||
}
|
||||
@@ -519,9 +531,6 @@ func mergePathConf(a, b *filer_pb.FilerConf_PathConf) {
|
||||
a.Rack = util.Nvl(b.Rack, a.Rack)
|
||||
a.DataNode = util.Nvl(b.DataNode, a.DataNode)
|
||||
a.DisableChunkDeletion = b.DisableChunkDeletion || a.DisableChunkDeletion
|
||||
// worm merges on presence, so a nested rule can turn it off. readOnly, fsync and
|
||||
// disableChunkDeletion stay OR'ed on purpose: a nested rule must not be able to
|
||||
// lift a lock the bucket set.
|
||||
if b.Worm != nil {
|
||||
// copy the value: a is often a scratch conf while b is a live trie entry
|
||||
a.Worm = proto.Bool(*b.Worm)
|
||||
|
||||
@@ -102,6 +102,54 @@ func TestWormLegacyFalseIsNotAnOverride(t *testing.T) {
|
||||
assert.False(t, fc.MatchStorageRule("/buckets/b/sub/x").GetWorm())
|
||||
}
|
||||
|
||||
func TestFsyncInheritance(t *testing.T) {
|
||||
fc := NewFilerConf()
|
||||
fc.doLoadConf(&filer_pb.FilerConf{
|
||||
Version: FilerConfVersion,
|
||||
Locations: []*filer_pb.FilerConf_PathConf{
|
||||
{LocationPrefix: "/buckets/b/", Fsync: proto.Bool(true), Ttl: "7d"},
|
||||
{LocationPrefix: "/buckets/b/quiet/", Collection: "quiet"},
|
||||
{LocationPrefix: "/buckets/b/scratch/", Fsync: proto.Bool(false)},
|
||||
{LocationPrefix: "/buckets/b/scratch/keep/", Fsync: proto.Bool(true)},
|
||||
},
|
||||
})
|
||||
|
||||
// a rule that says nothing about fsync keeps inheriting it, along with the ttl
|
||||
rule := fc.MatchStorageRule("/buckets/b/quiet/x")
|
||||
assert.True(t, rule.GetFsync())
|
||||
assert.Equal(t, "7d", rule.Ttl)
|
||||
|
||||
// an explicit false turns it off, and a deeper rule turns it back on
|
||||
assert.False(t, fc.MatchStorageRule("/buckets/b/scratch/x").GetFsync())
|
||||
assert.True(t, fc.MatchStorageRule("/buckets/b/scratch/keep/x").GetFsync())
|
||||
|
||||
// paths with no rule at all are unaffected
|
||||
assert.False(t, fc.MatchStorageRule("/buckets/other/x").GetFsync())
|
||||
}
|
||||
|
||||
// TestFsyncLegacyFalseIsNotAnOverride pins that the explicit "fsync": false
|
||||
// every pre-version-2 configuration carries does not read as a per-path
|
||||
// opt-out.
|
||||
func TestFsyncLegacyFalseIsNotAnOverride(t *testing.T) {
|
||||
const conf = `{
|
||||
"locations": [
|
||||
{"locationPrefix": "/buckets/b/", "fsync": true},
|
||||
{"locationPrefix": "/buckets/b/sub/", "collection": "sub", "fsync": false}
|
||||
]
|
||||
}`
|
||||
|
||||
for _, version := range []string{"", `"version": 0,`, `"version": 1,`} {
|
||||
fc := NewFilerConf()
|
||||
assert.NoError(t, fc.LoadFromBytes([]byte(`{`+version+conf[1:])))
|
||||
assert.True(t, fc.MatchStorageRule("/buckets/b/sub/x").GetFsync(), version)
|
||||
}
|
||||
|
||||
// the same file at the current version means what it says
|
||||
fc := NewFilerConf()
|
||||
assert.NoError(t, fc.LoadFromBytes([]byte(`{"version": 2,`+conf[1:])))
|
||||
assert.False(t, fc.MatchStorageRule("/buckets/b/sub/x").GetFsync())
|
||||
}
|
||||
|
||||
// TestWormSurvivesRoundTrip guards the write side: an explicit false has to be
|
||||
// stamped along with a version that says to honor it.
|
||||
func TestWormSurvivesRoundTrip(t *testing.T) {
|
||||
@@ -119,6 +167,23 @@ func TestWormSurvivesRoundTrip(t *testing.T) {
|
||||
assert.True(t, reloaded.MatchStorageRule("/buckets/b/other/x").GetWorm())
|
||||
}
|
||||
|
||||
// TestFsyncSurvivesRoundTrip guards the write side: an explicit false has to be
|
||||
// stamped along with a version that says to honor it.
|
||||
func TestFsyncSurvivesRoundTrip(t *testing.T) {
|
||||
fc := NewFilerConf()
|
||||
fc.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/b/", Fsync: proto.Bool(true)})
|
||||
fc.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/b/sub/", Fsync: proto.Bool(false)})
|
||||
fc.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/b/other/", Ttl: "7d"})
|
||||
|
||||
var buf bytes.Buffer
|
||||
assert.NoError(t, fc.ToText(&buf))
|
||||
|
||||
reloaded := NewFilerConf()
|
||||
assert.NoError(t, reloaded.LoadFromBytes(buf.Bytes()))
|
||||
assert.False(t, reloaded.MatchStorageRule("/buckets/b/sub/x").GetFsync())
|
||||
assert.True(t, reloaded.MatchStorageRule("/buckets/b/other/x").GetFsync())
|
||||
}
|
||||
|
||||
// TestClonePathConf verifies that ClonePathConf copies all exported fields.
|
||||
// Uses reflection to automatically detect new fields added to the protobuf,
|
||||
// ensuring the test fails if ClonePathConf is not updated for new fields.
|
||||
@@ -130,7 +195,7 @@ func TestClonePathConf(t *testing.T) {
|
||||
Replication: "001",
|
||||
Ttl: "7d",
|
||||
DiskType: "ssd",
|
||||
Fsync: true,
|
||||
Fsync: proto.Bool(true),
|
||||
VolumeGrowthCount: 5,
|
||||
ReadOnly: true,
|
||||
MaxFileNameLength: 255,
|
||||
@@ -189,9 +254,11 @@ func TestClonePathConf(t *testing.T) {
|
||||
// Verify mutation of clone doesn't affect source
|
||||
clone.Collection = "modified"
|
||||
clone.ReadOnly = false
|
||||
*clone.Fsync = false
|
||||
*clone.Worm = false
|
||||
assert.Equal(t, "test_collection", src.Collection, "Modifying clone should not affect source Collection")
|
||||
assert.Equal(t, true, src.ReadOnly, "Modifying clone should not affect source ReadOnly")
|
||||
assert.Equal(t, true, src.GetFsync(), "Modifying clone should not affect source Fsync")
|
||||
assert.Equal(t, true, src.GetWorm(), "Modifying clone should not affect source Worm")
|
||||
}
|
||||
|
||||
|
||||
@@ -788,7 +788,22 @@ func (f *Filer) applyTraversedEntry(ctx context.Context, entry *Entry, peerTsNs
|
||||
return fmt.Errorf("check local state for %s: %w", entry.FullPath, err)
|
||||
}
|
||||
if localTsNs >= peerTsNs {
|
||||
return nil
|
||||
if localTsNs != 0 {
|
||||
return nil
|
||||
}
|
||||
// Zero timestamps carry no order: keep the path only when an entry
|
||||
// exists locally — a missing one takes the peer's copy, or an
|
||||
// epoch-dated entry from a peer reporting no commit time is dropped.
|
||||
if f.Store == nil {
|
||||
return nil
|
||||
}
|
||||
local, findErr := f.Store.FindEntry(ctx, entry.FullPath)
|
||||
if findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("check local state for %s: %w", entry.FullPath, findErr)
|
||||
}
|
||||
if local != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if insertErr := f.Store.InsertEntry(ctx, entry); insertErr != nil {
|
||||
// Entry already exists (root dir, or partial previous bootstrap);
|
||||
|
||||
@@ -575,6 +575,43 @@ func TestBootstrapUpdatesExistingByCommitTime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A missing local entry has no commit time to order against: the peer copy
|
||||
// must apply even when both sides are timestamp-less — an epoch-dated entry
|
||||
// from a peer that predates EntryTsNs is still bootstrapped, while an
|
||||
// existing zero-mtime local entry keeps its place.
|
||||
func TestBootstrapCopiesMissingEntryWithoutCommitTime(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
missing := util.NewFullPath("/dir", "missing")
|
||||
existing := util.NewFullPath("/dir", "existing")
|
||||
|
||||
store.entries[string(existing)] = &Entry{
|
||||
FullPath: existing,
|
||||
Attr: Attr{Mtime: time.Unix(0, 0)},
|
||||
Content: []byte("zero-mtime local entry"),
|
||||
}
|
||||
for _, path := range []util.FullPath{missing, existing} {
|
||||
entry := &Entry{
|
||||
FullPath: path,
|
||||
Attr: Attr{Mtime: time.Unix(0, 0)},
|
||||
Content: []byte("epoch-dated peer entry"),
|
||||
}
|
||||
if err := f.applyTraversedEntry(context.Background(), entry, 0); err != nil {
|
||||
t.Fatalf("applyTraversedEntry %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
got, err := store.FindEntry(context.Background(), missing)
|
||||
if err != nil {
|
||||
t.Fatalf("missing local entry must take the peer copy: %v", err)
|
||||
}
|
||||
if string(got.Content) != "epoch-dated peer entry" {
|
||||
t.Fatalf("content = %q, want peer entry applied", got.Content)
|
||||
}
|
||||
if got, _ := store.FindEntry(context.Background(), existing); string(got.Content) != "zero-mtime local entry" {
|
||||
t.Fatalf("content = %q, existing local entry must be kept", got.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// A delete whose commit record failed to persist still blocks a stale
|
||||
// replayed create: the pending record stands in until the retry lands it.
|
||||
func TestPendingDeleteRecordBlocksStaleReplay(t *testing.T) {
|
||||
|
||||
@@ -415,11 +415,7 @@ func doNewChunkStreamReader(ctx context.Context, lookupFileIdFn wdclient.LookupF
|
||||
|
||||
func NewChunkStreamReaderFromFiler(ctx context.Context, masterClient *wdclient.MasterClient, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
|
||||
|
||||
lookupFileIdFn := func(ctx context.Context, fileId string) (targetUrl []string, err error) {
|
||||
return masterClient.LookupFileId(ctx, fileId)
|
||||
}
|
||||
|
||||
return doNewChunkStreamReader(ctx, lookupFileIdFn, chunks)
|
||||
return doNewChunkStreamReader(ctx, masterClient.GetLookupFileIdFunction(), chunks)
|
||||
}
|
||||
|
||||
// NewChunkStreamReaderFromLookup creates a ChunkStreamReader from a lookup function.
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"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/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
)
|
||||
|
||||
// lookupOnlyMaster announces no volumes on KeepConnected, so the client's
|
||||
// cache stays empty, but answers LookupVolume with the one volume server.
|
||||
type lookupOnlyMaster struct {
|
||||
master_pb.UnimplementedSeaweedServer
|
||||
volumeUrl string
|
||||
}
|
||||
|
||||
func (m *lookupOnlyMaster) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {
|
||||
if _, err := stream.Recv(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.Send(&master_pb.KeepConnectedResponse{}); err != nil {
|
||||
return err
|
||||
}
|
||||
<-stream.Context().Done()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *lookupOnlyMaster) LookupVolume(ctx context.Context, req *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
|
||||
resp := &master_pb.LookupVolumeResponse{}
|
||||
for _, id := range req.VolumeOrFileIds {
|
||||
resp.VolumeIdLocations = append(resp.VolumeIdLocations, &master_pb.LookupVolumeResponse_VolumeIdLocation{
|
||||
VolumeOrFileId: id,
|
||||
Locations: []*master_pb.Location{{Url: m.volumeUrl, PublicUrl: m.volumeUrl}},
|
||||
})
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// A filer's cached volume map can lose a volume that still exists: a failed
|
||||
// read invalidates every cached location of it, and the master only announces
|
||||
// changes. Readers built from the filer's MasterClient must then ask the master
|
||||
// instead of failing until the process restarts.
|
||||
func TestChunkStreamReaderFromFilerAsksMasterOnCacheMiss(t *testing.T) {
|
||||
content := []byte("metadata log chunk")
|
||||
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(content)
|
||||
}))
|
||||
t.Cleanup(volume.Close)
|
||||
|
||||
master := &lookupOnlyMaster{volumeUrl: strings.TrimPrefix(volume.URL, "http://")}
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
grpcServer := grpc.NewServer()
|
||||
master_pb.RegisterSeaweedServer(grpcServer, master)
|
||||
go func() { _ = grpcServer.Serve(lis) }()
|
||||
t.Cleanup(grpcServer.Stop)
|
||||
_, port, err := net.SplitHostPort(lis.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split listener address: %v", err)
|
||||
}
|
||||
|
||||
mc := wdclient.NewMasterClient(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
"", cluster.FilerType, pb.ServerAddress("localhost:0"), "", "",
|
||||
*pb.NewServiceDiscoveryFromMap(map[string]pb.ServerAddress{"m": pb.ServerAddress(fmt.Sprintf("127.0.0.1:0.%s", port))}),
|
||||
)
|
||||
connecting, stopConnecting := context.WithCancel(context.Background())
|
||||
t.Cleanup(stopConnecting)
|
||||
go mc.KeepConnectedToMaster(connecting)
|
||||
waiting, cancelWaiting := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancelWaiting()
|
||||
mc.WaitUntilConnected(waiting)
|
||||
if waiting.Err() != nil {
|
||||
t.Fatal("the master client never connected to the fake master")
|
||||
}
|
||||
|
||||
chunks := []*filer_pb.FileChunk{{FileId: "1,0123456789", Offset: 0, Size: uint64(len(content))}}
|
||||
got, err := io.ReadAll(NewChunkStreamReaderFromFiler(context.Background(), mc, chunks))
|
||||
if err != nil {
|
||||
t.Fatalf("read with volume 1 missing from the cache: %v", err)
|
||||
}
|
||||
if string(got) != string(content) {
|
||||
t.Fatalf("read %q, want %q", got, content)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
|
||||
)
|
||||
|
||||
const (
|
||||
// clockSkewTolerance matches the typical JWT library clock skew allowance (RFC 7519)
|
||||
clockSkewTolerance = 5 * time.Minute
|
||||
// defaultJTICacheSize is the default maximum number of JTI entries to cache
|
||||
defaultJTICacheSize = 10000
|
||||
// defaultCleanupInterval is how often to scan for expired JTI entries
|
||||
defaultCleanupInterval = 5 * time.Minute
|
||||
// eagerCleanupMinInterval rate limits opportunistic sweeps near capacity
|
||||
eagerCleanupMinInterval = 5 * time.Second
|
||||
// tokenFingerprintPrefix marks replay-cache keys derived from the token's
|
||||
// own fingerprint, used when the token carries no usable jti claim
|
||||
tokenFingerprintPrefix = "fp:"
|
||||
)
|
||||
|
||||
// jtiEntry represents a cached JTI with metadata
|
||||
type jtiEntry struct {
|
||||
subject string
|
||||
expiresAt time.Time
|
||||
// uncounted marks an entry merged in past the capacity bound: it keeps
|
||||
// rejecting replays but does not charge the count, so merged excess can
|
||||
// neither reject new exchanges nor be double-counted when swept.
|
||||
uncounted bool
|
||||
}
|
||||
|
||||
// jtiReplayCache wraps the consumed-token store that backs JTI replay
|
||||
// protection. Each consumed token identifier is held until the token's exp
|
||||
// plus clock skew, and a second presentation of the same identifier is
|
||||
// rejected with ErrProviderTokenReplayed.
|
||||
//
|
||||
// The cache is bounded by maxSize and uses automatic TTL-based expiration:
|
||||
// a background worker sweeps expired entries, an eager sweep runs when the
|
||||
// cache nears capacity, and the consume path reclaims expired slots before
|
||||
// rejecting a fresh token for capacity.
|
||||
//
|
||||
// Thread Safety:
|
||||
// All methods are safe for concurrent use. The consume path uses atomic
|
||||
// LoadOrStore to prevent TOCTOU races.
|
||||
type jtiReplayCache struct {
|
||||
name string // owning provider name, for log messages
|
||||
|
||||
enabled atomic.Bool
|
||||
maxSize atomic.Int64
|
||||
lastSweep atomic.Int64 // unix nano of the last sweep; rate limits eager cleanups
|
||||
|
||||
// storeMu guards the store/count pair: replay-state handoffs (adoptFrom,
|
||||
// mergeFrom) repoint them under the write lock while the consume path
|
||||
// holds a read lock, so a consume can never land in a store the handoff
|
||||
// already drained and abandoned.
|
||||
// It is always acquired before sweepMu, never while holding it.
|
||||
storeMu sync.RWMutex
|
||||
store *sync.Map // map[string]*jtiEntry - atomic storage for consumed token keys
|
||||
count *atomic.Int64 // entries in store; shared with the store
|
||||
|
||||
// mu guards the lifecycle of the cleanup worker: cleanupCancel and
|
||||
// cleanupDone. The worker itself only touches store/count, so holding
|
||||
// mu while waiting for it is safe.
|
||||
mu sync.Mutex
|
||||
cleanupCancel context.CancelFunc
|
||||
cleanupDone chan struct{} // Closed when cleanup goroutine exits
|
||||
|
||||
// sweepMu serializes cache sweeps so at most one scan runs at a time.
|
||||
sweepMu sync.Mutex
|
||||
}
|
||||
|
||||
func newJTIReplayCache(name string) *jtiReplayCache {
|
||||
return &jtiReplayCache{
|
||||
name: name,
|
||||
store: &sync.Map{},
|
||||
count: &atomic.Int64{},
|
||||
}
|
||||
}
|
||||
|
||||
// configure applies the replay-protection settings: a previous worker is
|
||||
// always stopped, whether the new configuration enables protection or
|
||||
// disables it. The consumed-token store survives re-configuration: resetting
|
||||
// it would let already-seen tokens be replayed against the refreshed provider.
|
||||
func (c *jtiReplayCache) configure(enabled bool, maxSize int64) {
|
||||
c.mu.Lock()
|
||||
c.stopWorkerLocked()
|
||||
if enabled {
|
||||
if maxSize <= 0 {
|
||||
maxSize = defaultJTICacheSize
|
||||
}
|
||||
// the bound must land before the flag: a consume that sees enabled
|
||||
// with a zero bound would reject the first token it registers
|
||||
c.maxSize.Store(maxSize)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
c.cleanupCancel = cancel
|
||||
c.cleanupDone = done
|
||||
c.enabled.Store(true)
|
||||
c.mu.Unlock()
|
||||
|
||||
go c.cleanupLoop(ctx, done, defaultCleanupInterval)
|
||||
glog.V(2).Infof("OIDC provider %q: JTI replay protection enabled (max size: %d)", c.name, maxSize)
|
||||
} else {
|
||||
c.enabled.Store(false)
|
||||
c.mu.Unlock()
|
||||
glog.Warningf("OIDC provider %q: JTI replay protection is DISABLED", c.name)
|
||||
}
|
||||
}
|
||||
|
||||
// stopWorkerLocked cancels the current cleanup goroutine and waits briefly
|
||||
// for it to exit. Caller must hold mu.
|
||||
func (c *jtiReplayCache) stopWorkerLocked() {
|
||||
if c.cleanupCancel == nil {
|
||||
return
|
||||
}
|
||||
c.cleanupCancel()
|
||||
select {
|
||||
case <-c.cleanupDone:
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine exited", c.name)
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("OIDC provider %q: Timeout waiting for JTI cleanup goroutine", c.name)
|
||||
}
|
||||
c.cleanupCancel = nil
|
||||
c.cleanupDone = nil
|
||||
}
|
||||
|
||||
// consume marks a token as used and rejects a second presentation of it.
|
||||
// jti is the token's jti claim (may be empty); tokenExpiresAt is its exp.
|
||||
// A no-op while protection is disabled.
|
||||
func (c *jtiReplayCache) consume(token, jti, subject string, tokenExpiresAt time.Time) error {
|
||||
if !c.enabled.Load() {
|
||||
return nil
|
||||
}
|
||||
|
||||
key := jti
|
||||
if key == "" {
|
||||
// Providers that issue no jti cannot be tracked by claim, so the
|
||||
// signed input keys the entry: a repeated presentation of the same
|
||||
// claims is a replay even when the signature bytes differ (e.g.
|
||||
// ECDSA s/N-s malleability).
|
||||
signingInput := token
|
||||
if i := strings.LastIndexByte(token, '.'); i > 0 {
|
||||
signingInput = token[:i]
|
||||
}
|
||||
sum := sha256.Sum256([]byte(signingInput))
|
||||
key = tokenFingerprintPrefix + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
if tokenExpiresAt.IsZero() {
|
||||
// a cache slot is freed only by expiry, so a token without exp
|
||||
// would hold it forever and eventually exhaust the bound
|
||||
return fmt.Errorf("%w: missing exp claim", providers.ErrProviderMissingClaims)
|
||||
}
|
||||
expiresAt := tokenExpiresAt.Add(clockSkewTolerance)
|
||||
if !time.Now().Before(expiresAt) {
|
||||
return fmt.Errorf("%w: token expired", providers.ErrProviderTokenExpired)
|
||||
}
|
||||
|
||||
entry := &jtiEntry{
|
||||
subject: subject,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
|
||||
// The read lock pins the store/count pair for the whole test-and-set
|
||||
// so a replay-state handoff cannot repoint them mid-check and strand
|
||||
// this consume in an abandoned store.
|
||||
c.storeMu.RLock()
|
||||
store, count := c.store, c.count
|
||||
|
||||
// Atomic test-and-set detects replays before any capacity work runs,
|
||||
// so a replayed token cannot trigger cleanup scans.
|
||||
if _, loaded := store.LoadOrStore(key, entry); loaded {
|
||||
c.storeMu.RUnlock()
|
||||
glog.Warningf("OIDC provider %q: Token replay detected (jti: %s)",
|
||||
c.name, jtiLogKey(key))
|
||||
return fmt.Errorf("%w: jti %s has already been used",
|
||||
providers.ErrProviderTokenReplayed, jtiLogKey(key))
|
||||
}
|
||||
|
||||
// The count is incremented as part of the insert, so concurrent
|
||||
// validations cannot all slip under the limit: whoever pushes the
|
||||
// count over evicts their own entry and is rejected.
|
||||
newCount := count.Add(1)
|
||||
maxSize := c.maxSize.Load()
|
||||
if newCount > maxSize {
|
||||
// Over the bound: expired entries may still occupy slots, so
|
||||
// reclaim them with a synchronized sweep before rejecting.
|
||||
c.sweepStore(store, count)
|
||||
if count.Load() > maxSize {
|
||||
if _, loaded := store.LoadAndDelete(key); loaded {
|
||||
count.Add(-1)
|
||||
}
|
||||
c.storeMu.RUnlock()
|
||||
glog.Errorf("OIDC provider %q: JTI cache FULL (%d entries) - rejecting token. "+
|
||||
"This may indicate a DoS attack or insufficient cache size. Consider increasing JTICacheMaxSize.",
|
||||
c.name, maxSize)
|
||||
return fmt.Errorf("JTI cache capacity exceeded")
|
||||
}
|
||||
} else if newCount >= maxSize*9/10 {
|
||||
glog.Warningf("OIDC provider %q: JTI cache at %d%% capacity (%d/%d), triggering eager cleanup",
|
||||
c.name, (newCount*100)/maxSize, newCount, maxSize)
|
||||
go c.performEagerCleanup()
|
||||
}
|
||||
c.storeMu.RUnlock()
|
||||
|
||||
glog.V(4).Infof("OIDC provider %q: Registered JTI %s (expires at %v, cache size: %d)",
|
||||
c.name, jtiLogKey(key), expiresAt, newCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
// evictExpired removes entries whose expiry has passed and returns how
|
||||
// many it deleted. Caller must hold sweepMu.
|
||||
func (c *jtiReplayCache) evictExpired(now time.Time, store *sync.Map, count *atomic.Int64) int {
|
||||
removed := 0
|
||||
store.Range(func(key, value interface{}) bool {
|
||||
expiresAt := value.(*jtiEntry).expiresAt
|
||||
if !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
// LoadAndDelete reports whether this call actually removed the
|
||||
// entry, so concurrent deletes cannot decrement the count twice.
|
||||
if v, loaded := store.LoadAndDelete(key); loaded {
|
||||
if !v.(*jtiEntry).uncounted {
|
||||
count.Add(-1)
|
||||
}
|
||||
removed++
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return removed
|
||||
}
|
||||
|
||||
// state returns the cache's current store/count pair.
|
||||
func (c *jtiReplayCache) state() (*sync.Map, *atomic.Int64) {
|
||||
c.storeMu.RLock()
|
||||
defer c.storeMu.RUnlock()
|
||||
return c.store, c.count
|
||||
}
|
||||
|
||||
// sweepStore runs one serialized expiry scan over the given store. It only
|
||||
// takes sweepMu, so callers already holding storeMu may use it.
|
||||
func (c *jtiReplayCache) sweepStore(store *sync.Map, count *atomic.Int64) {
|
||||
c.sweepMu.Lock()
|
||||
defer c.sweepMu.Unlock()
|
||||
c.lastSweep.Store(time.Now().UnixNano())
|
||||
if removed := c.evictExpired(time.Now(), store, count); removed > 0 {
|
||||
glog.V(4).Infof("OIDC provider %q: Cleaned up %d expired JTI entries (remaining: %d)",
|
||||
c.name, removed, count.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// sweepExpired runs a scan that is guaranteed to complete before the
|
||||
// caller proceeds; the periodic worker uses it so the scan always covers
|
||||
// the store currently in effect, not one captured earlier.
|
||||
func (c *jtiReplayCache) sweepExpired() {
|
||||
store, count := c.state()
|
||||
c.sweepStore(store, count)
|
||||
}
|
||||
|
||||
// performEagerCleanup performs an opportunistic cleanup of expired JTI
|
||||
// entries when the cache approaches capacity. At most one sweep runs at a
|
||||
// time and no more often than eagerCleanupMinInterval, so a burst of
|
||||
// requests near the limit cannot each turn into a full-cache scan.
|
||||
func (c *jtiReplayCache) performEagerCleanup() {
|
||||
if !c.enabled.Load() {
|
||||
return
|
||||
}
|
||||
if time.Since(time.Unix(0, c.lastSweep.Load())) < eagerCleanupMinInterval {
|
||||
return
|
||||
}
|
||||
store, count := c.state()
|
||||
if !c.sweepMu.TryLock() {
|
||||
return
|
||||
}
|
||||
defer c.sweepMu.Unlock()
|
||||
c.lastSweep.Store(time.Now().UnixNano())
|
||||
|
||||
beforeCount := count.Load()
|
||||
if removed := c.evictExpired(time.Now(), store, count); removed > 0 {
|
||||
glog.Infof("OIDC provider %q: Eager cleanup removed %d expired JTI entries (%d -> %d)",
|
||||
c.name, removed, beforeCount, count.Load())
|
||||
} else {
|
||||
glog.Warningf("OIDC provider %q: Eager cleanup found no expired entries to remove. "+
|
||||
"Cache may be filled with valid long-lived tokens. Consider increasing JTICacheMaxSize.",
|
||||
c.name)
|
||||
}
|
||||
}
|
||||
|
||||
// cleanupLoop periodically removes expired JTI entries from the cache.
|
||||
// This prevents memory growth by removing JTIs after their tokens have
|
||||
// expired. Runs until ctx is cancelled; done is closed on exit.
|
||||
func (c *jtiReplayCache) cleanupLoop(ctx context.Context, done chan struct{}, interval time.Duration) {
|
||||
defer close(done)
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine started (interval: %v)", c.name, interval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine stopping", c.name)
|
||||
return
|
||||
case <-ticker.C:
|
||||
c.sweepExpired()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stop gracefully stops the cleanup worker.
|
||||
// Should be called when the provider is being shut down to prevent goroutine
|
||||
// leaks.
|
||||
func (c *jtiReplayCache) stop(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
cancel, done := c.cleanupCancel, c.cleanupDone
|
||||
c.mu.Unlock()
|
||||
|
||||
if cancel == nil {
|
||||
return nil
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
glog.V(2).Infof("OIDC provider %q: Cleanup goroutine shutdown complete", c.name)
|
||||
case <-ctx.Done():
|
||||
glog.Warningf("OIDC provider %q: Shutdown timeout waiting for cleanup goroutine: %v", c.name, ctx.Err())
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
if c.cleanupDone == done {
|
||||
c.cleanupCancel = nil
|
||||
c.cleanupDone = nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// adoptFrom takes over the consumed-token store of another cache, so tokens
|
||||
// it already saw stay rejected across the rebuild. The caller must shut down
|
||||
// the replaced provider; only one cleanup worker may sweep the shared store
|
||||
// at a time. Call before the new provider serves validators; sweepMu
|
||||
// excludes its own cleanup worker during the swap.
|
||||
func (c *jtiReplayCache) adoptFrom(old *jtiReplayCache) {
|
||||
if old == nil || old == c {
|
||||
return
|
||||
}
|
||||
c.storeMu.Lock()
|
||||
c.sweepMu.Lock()
|
||||
c.store, c.count = old.store, old.count
|
||||
c.sweepMu.Unlock()
|
||||
c.storeMu.Unlock()
|
||||
}
|
||||
|
||||
// mergeFrom hands this cache's store to another cache and then folds the
|
||||
// other's consumed-token entries in, so rejections the other recorded keep
|
||||
// holding when its records move to a shared provider. Repointing first means
|
||||
// tokens the other still consumes — in-flight exchanges or ones routed to it
|
||||
// before the provider map updates — land in the shared store instead of a
|
||||
// store this merge already drained. Unlike adoptFrom it swaps nothing of its
|
||||
// own, so it is safe on a cache that is already serving validators.
|
||||
func (c *jtiReplayCache) mergeFrom(other *jtiReplayCache) {
|
||||
if other == nil || other == c {
|
||||
return
|
||||
}
|
||||
c.storeMu.RLock()
|
||||
defer c.storeMu.RUnlock()
|
||||
store, count := c.store, c.count
|
||||
|
||||
other.storeMu.Lock()
|
||||
oldStore := other.store
|
||||
if oldStore == store {
|
||||
other.storeMu.Unlock()
|
||||
return
|
||||
}
|
||||
other.store, other.count = store, count
|
||||
other.storeMu.Unlock()
|
||||
|
||||
c.sweepMu.Lock()
|
||||
defer c.sweepMu.Unlock()
|
||||
now := time.Now()
|
||||
oldStore.Range(func(key, value interface{}) bool {
|
||||
entry := value.(*jtiEntry)
|
||||
if expiresAt := entry.expiresAt; !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
return true
|
||||
}
|
||||
// A consumed token is never dropped to fit the bound: merged entries
|
||||
// stay but do not charge the count, so a store filled past the bound
|
||||
// by the merge cannot reject new exchanges while it drains by expiry.
|
||||
store.LoadOrStore(key, &jtiEntry{subject: entry.subject, expiresAt: entry.expiresAt, uncounted: true})
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// jtiLogKey redacts a token identifier for logs and error strings: a stable
|
||||
// fingerprint that still lets operators correlate repeated presentations.
|
||||
func jtiLogKey(jti string) string {
|
||||
sum := sha256.Sum256([]byte(jti))
|
||||
return hex.EncodeToString(sum[:8])
|
||||
}
|
||||
+30
-335
@@ -6,7 +6,6 @@ import (
|
||||
"crypto/elliptic"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
@@ -20,7 +19,6 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -29,30 +27,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
)
|
||||
|
||||
const (
|
||||
// clockSkewTolerance matches the typical JWT library clock skew allowance (RFC 7519)
|
||||
clockSkewTolerance = 5 * time.Minute
|
||||
// defaultJTICacheSize is the default maximum number of JTI entries to cache
|
||||
defaultJTICacheSize = 10000
|
||||
// defaultCleanupInterval is how often to scan for expired JTI entries
|
||||
defaultCleanupInterval = 5 * time.Minute
|
||||
// eagerCleanupMinInterval rate limits opportunistic sweeps near capacity
|
||||
eagerCleanupMinInterval = 5 * time.Second
|
||||
// tokenFingerprintPrefix marks replay-cache keys derived from the token's
|
||||
// own fingerprint, used when the token carries no usable jti claim
|
||||
tokenFingerprintPrefix = "fp:"
|
||||
)
|
||||
|
||||
// jtiEntry represents a cached JTI with metadata
|
||||
type jtiEntry struct {
|
||||
subject string
|
||||
expiresAt time.Time
|
||||
// uncounted marks an entry merged in past the capacity bound: it keeps
|
||||
// rejecting replays but does not charge jtiCount, so merged excess can
|
||||
// neither reject new exchanges nor be double-counted when swept.
|
||||
uncounted bool
|
||||
}
|
||||
|
||||
// OIDCProvider implements OpenID Connect authentication with JTI replay protection.
|
||||
//
|
||||
// Replay Protection:
|
||||
@@ -84,31 +58,24 @@ type OIDCProvider struct {
|
||||
resolvedJWKSUri string
|
||||
discoveryFailed bool
|
||||
|
||||
// JTI replay protection fields. jtiStore and jtiCount are allocated once
|
||||
// in NewOIDCProvider and survive re-initialization, so a config refresh
|
||||
// cannot reopen already-consumed tokens for replay.
|
||||
jtiEnabled atomic.Bool
|
||||
jtiStore *sync.Map // map[string]*jtiEntry - atomic storage for consumed token keys
|
||||
jtiCount *atomic.Int64 // entries in jtiStore; shared with the store
|
||||
jtiMaxSize atomic.Int64
|
||||
jtiLastSweep atomic.Int64 // unix nano of the last sweep; rate limits eager cleanups
|
||||
// jti wraps the consumed-token cache behind the replay protection. It is
|
||||
// allocated by NewOIDCProvider or lazily by replayCache, and survives
|
||||
// re-initialization, so a config refresh cannot reopen already-consumed
|
||||
// tokens for replay. jtiOnce makes a zero-value OIDCProvider safe.
|
||||
jti *jtiReplayCache
|
||||
jtiOnce sync.Once
|
||||
}
|
||||
|
||||
// jtiStoreMu guards the jtiStore/jtiCount pair: replay-state handoffs
|
||||
// (AdoptReplayStateFrom, MergeReplayStateFrom) repoint them under the
|
||||
// write lock while the consume path holds a read lock, so a consume can
|
||||
// never land in a store the handoff already drained and abandoned.
|
||||
// It is always acquired before jtiSweepMu, never while holding it.
|
||||
jtiStoreMu sync.RWMutex
|
||||
|
||||
// jtiMu guards the lifecycle of the cleanup worker: jtiCleanupCancel and
|
||||
// jtiCleanupDone. The worker itself only touches jtiStore/jtiCount, so
|
||||
// holding jtiMu while waiting for it is safe.
|
||||
jtiMu sync.Mutex
|
||||
jtiCleanupCancel context.CancelFunc
|
||||
jtiCleanupDone chan struct{} // Closed when cleanup goroutine exits
|
||||
|
||||
// jtiSweepMu serializes cache sweeps so at most one scan runs at a time.
|
||||
jtiSweepMu sync.Mutex
|
||||
// replayCache returns the consumed-token cache, allocating it for providers
|
||||
// built without NewOIDCProvider so the delegated operations never panic on a
|
||||
// nil cache.
|
||||
func (p *OIDCProvider) replayCache() *jtiReplayCache {
|
||||
p.jtiOnce.Do(func() {
|
||||
if p.jti == nil {
|
||||
p.jti = newJTIReplayCache(p.name)
|
||||
}
|
||||
})
|
||||
return p.jti
|
||||
}
|
||||
|
||||
// OIDCConfig holds OIDC provider configuration
|
||||
@@ -391,8 +358,7 @@ func NewOIDCProvider(name string) *OIDCProvider {
|
||||
return &OIDCProvider{
|
||||
name: name,
|
||||
httpClient: &http.Client{Timeout: 30 * time.Second, CheckRedirect: refuseDowngradeRedirect},
|
||||
jtiStore: &sync.Map{},
|
||||
jtiCount: &atomic.Int64{},
|
||||
jti: newJTIReplayCache(name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,53 +478,12 @@ func (p *OIDCProvider) Initialize(config interface{}) error {
|
||||
if oidcConfig.JTIReplayProtectionEnabled != nil {
|
||||
jtiEnabled = *oidcConfig.JTIReplayProtectionEnabled
|
||||
}
|
||||
|
||||
p.jtiMu.Lock()
|
||||
p.stopJTICleanupWorkerLocked()
|
||||
if jtiEnabled {
|
||||
maxSize := int64(oidcConfig.JTICacheMaxSize)
|
||||
if maxSize <= 0 {
|
||||
maxSize = defaultJTICacheSize
|
||||
}
|
||||
// the bound must land before the flag: a consume that sees enabled
|
||||
// with a zero bound would reject the first token it registers
|
||||
p.jtiMaxSize.Store(maxSize)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
p.jtiCleanupCancel = cancel
|
||||
p.jtiCleanupDone = done
|
||||
p.jtiEnabled.Store(true)
|
||||
p.jtiMu.Unlock()
|
||||
|
||||
go p.cleanupExpiredJTIs(ctx, done, defaultCleanupInterval)
|
||||
glog.V(2).Infof("OIDC provider %q: JTI replay protection enabled (max size: %d)", p.name, maxSize)
|
||||
} else {
|
||||
p.jtiEnabled.Store(false)
|
||||
p.jtiMu.Unlock()
|
||||
glog.Warningf("OIDC provider %q: JTI replay protection is DISABLED", p.name)
|
||||
}
|
||||
p.replayCache().configure(jtiEnabled, int64(oidcConfig.JTICacheMaxSize))
|
||||
|
||||
// For testing, we'll skip the actual OIDC client initialization
|
||||
return nil
|
||||
}
|
||||
|
||||
// stopJTICleanupWorkerLocked cancels the current cleanup goroutine and waits
|
||||
// briefly for it to exit. Caller must hold jtiMu.
|
||||
func (p *OIDCProvider) stopJTICleanupWorkerLocked() {
|
||||
if p.jtiCleanupCancel == nil {
|
||||
return
|
||||
}
|
||||
p.jtiCleanupCancel()
|
||||
select {
|
||||
case <-p.jtiCleanupDone:
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine exited", p.name)
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("OIDC provider %q: Timeout waiting for JTI cleanup goroutine", p.name)
|
||||
}
|
||||
p.jtiCleanupCancel = nil
|
||||
p.jtiCleanupDone = nil
|
||||
}
|
||||
|
||||
// validateConfig validates the OIDC configuration
|
||||
func (p *OIDCProvider) validateConfig(config *OIDCConfig) error {
|
||||
if config.Issuer == "" {
|
||||
@@ -935,85 +860,14 @@ func (p *OIDCProvider) validateToken(ctx context.Context, token string, singleUs
|
||||
tokenClaims.Claims[key] = value
|
||||
}
|
||||
|
||||
// Extract and validate JTI claim for replay protection. The check runs
|
||||
// only for single-use callers: a bearer token is meant to be presented on
|
||||
// every request, so validating it must not consume it.
|
||||
if singleUse && p.jtiEnabled.Load() {
|
||||
// Consume the token for replay protection. The check runs only for
|
||||
// single-use callers: a bearer token is meant to be presented on every
|
||||
// request, so validating it must not consume it.
|
||||
if singleUse {
|
||||
jti, _ := claims["jti"].(string)
|
||||
key := jti
|
||||
if key == "" {
|
||||
// Providers that issue no jti cannot be tracked by claim, so the
|
||||
// signed input keys the entry: a repeated presentation of the same
|
||||
// claims is a replay even when the signature bytes differ (e.g.
|
||||
// ECDSA s/N-s malleability).
|
||||
signingInput := token
|
||||
if i := strings.LastIndexByte(token, '.'); i > 0 {
|
||||
signingInput = token[:i]
|
||||
}
|
||||
sum := sha256.Sum256([]byte(signingInput))
|
||||
key = tokenFingerprintPrefix + hex.EncodeToString(sum[:])
|
||||
if err := p.replayCache().consume(token, jti, subject, tokenClaims.ExpiresAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
expiresAt := tokenClaims.ExpiresAt
|
||||
if expiresAt.IsZero() {
|
||||
// a cache slot is freed only by expiry, so a token without exp
|
||||
// would hold it forever and eventually exhaust the bound
|
||||
return nil, fmt.Errorf("%w: missing exp claim", providers.ErrProviderMissingClaims)
|
||||
}
|
||||
expiresAt = expiresAt.Add(clockSkewTolerance)
|
||||
if !time.Now().Before(expiresAt) {
|
||||
return nil, fmt.Errorf("%w: token expired", providers.ErrProviderTokenExpired)
|
||||
}
|
||||
|
||||
entry := &jtiEntry{
|
||||
subject: subject,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
|
||||
// The read lock pins the store/count pair for the whole test-and-set
|
||||
// so a replay-state handoff cannot repoint them mid-check and strand
|
||||
// this consume in an abandoned store.
|
||||
p.jtiStoreMu.RLock()
|
||||
store, count := p.jtiStore, p.jtiCount
|
||||
|
||||
// Atomic test-and-set detects replays before any capacity work runs,
|
||||
// so a replayed token cannot trigger cleanup scans.
|
||||
if _, loaded := store.LoadOrStore(key, entry); loaded {
|
||||
p.jtiStoreMu.RUnlock()
|
||||
glog.Warningf("OIDC provider %q: Token replay detected (jti: %s)",
|
||||
p.name, jtiLogKey(key))
|
||||
return nil, fmt.Errorf("%w: jti %s has already been used",
|
||||
providers.ErrProviderTokenReplayed, jtiLogKey(key))
|
||||
}
|
||||
|
||||
// The count is incremented as part of the insert, so concurrent
|
||||
// validations cannot all slip under the limit: whoever pushes the
|
||||
// count over evicts their own entry and is rejected.
|
||||
newCount := count.Add(1)
|
||||
maxSize := p.jtiMaxSize.Load()
|
||||
if newCount > maxSize {
|
||||
// Over the bound: expired entries may still occupy slots, so
|
||||
// reclaim them with a synchronized sweep before rejecting.
|
||||
p.sweepJTIStore(store, count)
|
||||
if count.Load() > maxSize {
|
||||
if _, loaded := store.LoadAndDelete(key); loaded {
|
||||
count.Add(-1)
|
||||
}
|
||||
p.jtiStoreMu.RUnlock()
|
||||
glog.Errorf("OIDC provider %q: JTI cache FULL (%d entries) - rejecting token. "+
|
||||
"This may indicate a DoS attack or insufficient cache size. Consider increasing JTICacheMaxSize.",
|
||||
p.name, maxSize)
|
||||
return nil, fmt.Errorf("JTI cache capacity exceeded")
|
||||
}
|
||||
} else if newCount >= maxSize*9/10 {
|
||||
glog.Warningf("OIDC provider %q: JTI cache at %d%% capacity (%d/%d), triggering eager cleanup",
|
||||
p.name, (newCount*100)/maxSize, newCount, maxSize)
|
||||
go p.performEagerCleanup()
|
||||
}
|
||||
p.jtiStoreMu.RUnlock()
|
||||
|
||||
glog.V(4).Infof("OIDC provider %q: Registered JTI %s (expires at %v, cache size: %d)",
|
||||
p.name, jtiLogKey(key), expiresAt, newCount)
|
||||
}
|
||||
|
||||
return tokenClaims, nil
|
||||
@@ -1445,148 +1299,22 @@ func (p *OIDCProvider) mapUserInfoToIdentity(userInfo map[string]interface{}) *p
|
||||
return identity
|
||||
}
|
||||
|
||||
// evictExpiredJTIs removes entries whose expiry has passed and returns how
|
||||
// many it deleted. Caller must hold jtiSweepMu.
|
||||
func (p *OIDCProvider) evictExpiredJTIs(now time.Time, store *sync.Map, count *atomic.Int64) int {
|
||||
removed := 0
|
||||
store.Range(func(key, value interface{}) bool {
|
||||
expiresAt := value.(*jtiEntry).expiresAt
|
||||
if !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
// LoadAndDelete reports whether this call actually removed the
|
||||
// entry, so concurrent deletes cannot decrement the count twice.
|
||||
if v, loaded := store.LoadAndDelete(key); loaded {
|
||||
if !v.(*jtiEntry).uncounted {
|
||||
count.Add(-1)
|
||||
}
|
||||
removed++
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return removed
|
||||
}
|
||||
|
||||
// replayState returns the provider's current store/count pair.
|
||||
func (p *OIDCProvider) replayState() (*sync.Map, *atomic.Int64) {
|
||||
p.jtiStoreMu.RLock()
|
||||
defer p.jtiStoreMu.RUnlock()
|
||||
return p.jtiStore, p.jtiCount
|
||||
}
|
||||
|
||||
// sweepJTIStore runs one serialized expiry scan over the given store. It only
|
||||
// takes jtiSweepMu, so callers already holding jtiStoreMu may use it.
|
||||
func (p *OIDCProvider) sweepJTIStore(store *sync.Map, count *atomic.Int64) {
|
||||
p.jtiSweepMu.Lock()
|
||||
defer p.jtiSweepMu.Unlock()
|
||||
p.jtiLastSweep.Store(time.Now().UnixNano())
|
||||
if removed := p.evictExpiredJTIs(time.Now(), store, count); removed > 0 {
|
||||
glog.V(4).Infof("OIDC provider %q: Cleaned up %d expired JTI entries (remaining: %d)",
|
||||
p.name, removed, count.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// sweepExpiredJTIs runs a scan that is guaranteed to complete before the
|
||||
// caller proceeds; the capacity-rejection path uses it so a fresh token is
|
||||
// not refused while expired entries still hold slots.
|
||||
func (p *OIDCProvider) sweepExpiredJTIs() {
|
||||
store, count := p.replayState()
|
||||
p.sweepJTIStore(store, count)
|
||||
}
|
||||
|
||||
// performEagerCleanup performs an opportunistic cleanup of expired JTI
|
||||
// entries when the cache approaches capacity. At most one sweep runs at a
|
||||
// time and no more often than eagerCleanupMinInterval, so a burst of
|
||||
// requests near the limit cannot each turn into a full-cache scan.
|
||||
func (p *OIDCProvider) performEagerCleanup() {
|
||||
if !p.jtiEnabled.Load() {
|
||||
return
|
||||
}
|
||||
if time.Since(time.Unix(0, p.jtiLastSweep.Load())) < eagerCleanupMinInterval {
|
||||
return
|
||||
}
|
||||
store, count := p.replayState()
|
||||
if !p.jtiSweepMu.TryLock() {
|
||||
return
|
||||
}
|
||||
defer p.jtiSweepMu.Unlock()
|
||||
p.jtiLastSweep.Store(time.Now().UnixNano())
|
||||
|
||||
beforeCount := count.Load()
|
||||
if removed := p.evictExpiredJTIs(time.Now(), store, count); removed > 0 {
|
||||
glog.Infof("OIDC provider %q: Eager cleanup removed %d expired JTI entries (%d -> %d)",
|
||||
p.name, removed, beforeCount, count.Load())
|
||||
} else {
|
||||
glog.Warningf("OIDC provider %q: Eager cleanup found no expired entries to remove. "+
|
||||
"Cache may be filled with valid long-lived tokens. Consider increasing JTICacheMaxSize.",
|
||||
p.name)
|
||||
}
|
||||
}
|
||||
|
||||
// cleanupExpiredJTIs periodically removes expired JTI entries from the cache.
|
||||
// This prevents memory growth by removing JTIs after their tokens have expired.
|
||||
// Runs in a background goroutine until ctx is cancelled; done is closed on exit.
|
||||
func (p *OIDCProvider) cleanupExpiredJTIs(ctx context.Context, done chan struct{}, interval time.Duration) {
|
||||
defer close(done)
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine started (interval: %v)", p.name, interval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine stopping", p.name)
|
||||
return
|
||||
case <-ticker.C:
|
||||
p.sweepExpiredJTIs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown gracefully stops the JTI cleanup goroutine.
|
||||
// Should be called when the provider is being shut down to prevent goroutine leaks.
|
||||
func (p *OIDCProvider) Shutdown(ctx context.Context) error {
|
||||
p.jtiMu.Lock()
|
||||
cancel, done := p.jtiCleanupCancel, p.jtiCleanupDone
|
||||
p.jtiMu.Unlock()
|
||||
|
||||
if cancel == nil {
|
||||
return nil
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
glog.V(2).Infof("OIDC provider %q: Cleanup goroutine shutdown complete", p.name)
|
||||
case <-ctx.Done():
|
||||
glog.Warningf("OIDC provider %q: Shutdown timeout waiting for cleanup goroutine: %v", p.name, ctx.Err())
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
p.jtiMu.Lock()
|
||||
if p.jtiCleanupDone == done {
|
||||
p.jtiCleanupCancel = nil
|
||||
p.jtiCleanupDone = nil
|
||||
}
|
||||
p.jtiMu.Unlock()
|
||||
return nil
|
||||
return p.replayCache().stop(ctx)
|
||||
}
|
||||
|
||||
// AdoptReplayStateFrom takes over the consumed-token store of the provider it
|
||||
// replaces, so tokens it already saw stay rejected across the rebuild. The
|
||||
// caller must shut down the replaced provider; only one cleanup worker may
|
||||
// sweep the shared store at a time. Call before the new provider serves
|
||||
// validators; jtiSweepMu excludes its own cleanup worker during the swap.
|
||||
// validators.
|
||||
func (p *OIDCProvider) AdoptReplayStateFrom(old *OIDCProvider) {
|
||||
if old == nil || old == p {
|
||||
if old == nil || old == p || old.jti == nil {
|
||||
return
|
||||
}
|
||||
p.jtiStoreMu.Lock()
|
||||
p.jtiSweepMu.Lock()
|
||||
p.jtiStore, p.jtiCount = old.jtiStore, old.jtiCount
|
||||
p.jtiSweepMu.Unlock()
|
||||
p.jtiStoreMu.Unlock()
|
||||
p.replayCache().adoptFrom(old.jti)
|
||||
}
|
||||
|
||||
// MergeReplayStateFrom hands this provider's store to another provider and
|
||||
@@ -1601,38 +1329,5 @@ func (p *OIDCProvider) MergeReplayStateFrom(other *OIDCProvider) {
|
||||
if other == nil || other == p {
|
||||
return
|
||||
}
|
||||
p.jtiStoreMu.RLock()
|
||||
defer p.jtiStoreMu.RUnlock()
|
||||
store, count := p.jtiStore, p.jtiCount
|
||||
|
||||
other.jtiStoreMu.Lock()
|
||||
oldStore := other.jtiStore
|
||||
if oldStore == store {
|
||||
other.jtiStoreMu.Unlock()
|
||||
return
|
||||
}
|
||||
other.jtiStore, other.jtiCount = store, count
|
||||
other.jtiStoreMu.Unlock()
|
||||
|
||||
p.jtiSweepMu.Lock()
|
||||
defer p.jtiSweepMu.Unlock()
|
||||
now := time.Now()
|
||||
oldStore.Range(func(key, value interface{}) bool {
|
||||
entry := value.(*jtiEntry)
|
||||
if expiresAt := entry.expiresAt; !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
return true
|
||||
}
|
||||
// A consumed token is never dropped to fit the bound: merged entries
|
||||
// stay but do not charge the count, so a store filled past the bound
|
||||
// by the merge cannot reject new exchanges while it drains by expiry.
|
||||
store.LoadOrStore(key, &jtiEntry{subject: entry.subject, expiresAt: entry.expiresAt, uncounted: true})
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// jtiLogKey redacts a token identifier for logs and error strings: a stable
|
||||
// fingerprint that still lets operators correlate repeated presentations.
|
||||
func jtiLogKey(jti string) string {
|
||||
sum := sha256.Sum256([]byte(jti))
|
||||
return hex.EncodeToString(sum[:8])
|
||||
p.replayCache().mergeFrom(other.replayCache())
|
||||
}
|
||||
@@ -1067,10 +1067,10 @@ func TestOIDCProviderJTICleanup(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check cache size is 1
|
||||
assert.Equal(t, int64(1), provider.jtiCount.Load())
|
||||
assert.Equal(t, int64(1), provider.jti.count.Load())
|
||||
|
||||
// Verify entry exists and check its expiration includes clock skew
|
||||
val, ok := provider.jtiStore.Load("cleanup-test-jti")
|
||||
val, ok := provider.jti.store.Load("cleanup-test-jti")
|
||||
require.True(t, ok, "JTI entry should exist")
|
||||
entry := val.(*jtiEntry)
|
||||
|
||||
@@ -1088,21 +1088,21 @@ func TestOIDCProviderJTICleanup(t *testing.T) {
|
||||
// both the entry and the count must actually be cleared
|
||||
cleanupCtx, cleanupCancel := context.WithCancel(context.Background())
|
||||
cleanupDone := make(chan struct{})
|
||||
go provider.cleanupExpiredJTIs(cleanupCtx, cleanupDone, 20*time.Millisecond)
|
||||
go provider.jti.cleanupLoop(cleanupCtx, cleanupDone, 20*time.Millisecond)
|
||||
defer func() {
|
||||
cleanupCancel()
|
||||
<-cleanupDone
|
||||
}()
|
||||
|
||||
provider.jtiStore.Store("expired-cleanup-jti", &jtiEntry{
|
||||
provider.jti.store.Store("expired-cleanup-jti", &jtiEntry{
|
||||
subject: "expired-user",
|
||||
expiresAt: time.Now().Add(-time.Minute),
|
||||
})
|
||||
provider.jtiCount.Add(1)
|
||||
provider.jti.count.Add(1)
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
_, stillThere := provider.jtiStore.Load("expired-cleanup-jti")
|
||||
return !stillThere && provider.jtiCount.Load() == 1 // only the valid entry remains
|
||||
_, stillThere := provider.jti.store.Load("expired-cleanup-jti")
|
||||
return !stillThere && provider.jti.count.Load() == 1 // only the valid entry remains
|
||||
}, 2*time.Second, 10*time.Millisecond, "periodic cleanup should evict the expired entry")
|
||||
}
|
||||
|
||||
@@ -1124,7 +1124,7 @@ func TestOIDCProviderReinitialization(t *testing.T) {
|
||||
|
||||
// First initialization
|
||||
require.NoError(t, provider.Initialize(config))
|
||||
require.NotNil(t, provider.jtiCleanupCancel, "First cleanup cancel should be set")
|
||||
require.NotNil(t, provider.jti.cleanupCancel, "First cleanup cancel should be set")
|
||||
|
||||
// Create and validate a token to ensure JTI protection is working
|
||||
token1 := createTestJWT(t, privateKey, jwt.MapClaims{
|
||||
@@ -1140,7 +1140,7 @@ func TestOIDCProviderReinitialization(t *testing.T) {
|
||||
|
||||
// Second initialization should not cause errors
|
||||
require.NoError(t, provider.Initialize(config))
|
||||
require.NotNil(t, provider.jtiCleanupCancel, "Second cleanup cancel should be set")
|
||||
require.NotNil(t, provider.jti.cleanupCancel, "Second cleanup cancel should be set")
|
||||
|
||||
// The JTI cache survives re-initialization, so the consumed token is
|
||||
// still detected as a replay rather than being usable again
|
||||
@@ -1150,7 +1150,7 @@ func TestOIDCProviderReinitialization(t *testing.T) {
|
||||
|
||||
// Third initialization to ensure it works multiple times
|
||||
require.NoError(t, provider.Initialize(config))
|
||||
require.NotNil(t, provider.jtiCleanupCancel, "Third cleanup cancel should be set")
|
||||
require.NotNil(t, provider.jti.cleanupCancel, "Third cleanup cancel should be set")
|
||||
|
||||
// Verify JTI replay protection still works after re-initialization
|
||||
token2 := createTestJWT(t, privateKey, jwt.MapClaims{
|
||||
@@ -1201,16 +1201,16 @@ func TestOIDCProviderJTIEagerCleanup(t *testing.T) {
|
||||
subject: fmt.Sprintf("expired-user-%d", i),
|
||||
expiresAt: time.Now().Add(-time.Hour), // Already expired
|
||||
}
|
||||
provider.jtiStore.Store(jti, entry)
|
||||
provider.jtiCount.Add(1)
|
||||
provider.jti.store.Store(jti, entry)
|
||||
provider.jti.count.Add(1)
|
||||
}
|
||||
|
||||
assert.Equal(t, int64(5), provider.jtiCount.Load(), "Should have 5 expired entries")
|
||||
assert.Equal(t, int64(5), provider.jti.count.Load(), "Should have 5 expired entries")
|
||||
|
||||
// Perform eager cleanup - should remove all expired entries
|
||||
provider.performEagerCleanup()
|
||||
provider.jti.performEagerCleanup()
|
||||
|
||||
assert.Equal(t, int64(0), provider.jtiCount.Load(),
|
||||
assert.Equal(t, int64(0), provider.jti.count.Load(),
|
||||
"All expired entries should be removed by eager cleanup")
|
||||
|
||||
// Now test that adding valid tokens works after cleanup
|
||||
@@ -1228,7 +1228,7 @@ func TestOIDCProviderJTIEagerCleanup(t *testing.T) {
|
||||
}
|
||||
|
||||
// Should have 9 valid entries now (90% of capacity, triggers eager cleanup warning)
|
||||
assert.Equal(t, int64(9), provider.jtiCount.Load(), "Should have 9 valid entries")
|
||||
assert.Equal(t, int64(9), provider.jti.count.Load(), "Should have 9 valid entries")
|
||||
|
||||
// 10th token should succeed (at capacity but not over)
|
||||
token10 := createTestJWT(t, privateKey, jwt.MapClaims{
|
||||
@@ -1282,11 +1282,11 @@ func TestOIDCProviderConcurrentCleanupNoNegativeCount(t *testing.T) {
|
||||
subject: fmt.Sprintf("user-%d", i),
|
||||
expiresAt: time.Now().Add(-time.Hour), // Already expired
|
||||
}
|
||||
provider.jtiStore.Store(jti, entry)
|
||||
provider.jtiCount.Add(1)
|
||||
provider.jti.store.Store(jti, entry)
|
||||
provider.jti.count.Add(1)
|
||||
}
|
||||
|
||||
initialCount := provider.jtiCount.Load()
|
||||
initialCount := provider.jti.count.Load()
|
||||
assert.Equal(t, int64(50), initialCount, "Should have 50 expired entries")
|
||||
|
||||
// Run multiple concurrent cleanups
|
||||
@@ -1297,14 +1297,14 @@ func TestOIDCProviderConcurrentCleanupNoNegativeCount(t *testing.T) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
provider.performEagerCleanup()
|
||||
provider.jti.performEagerCleanup()
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Counter should be 0 (all entries removed), never negative
|
||||
finalCount := provider.jtiCount.Load()
|
||||
finalCount := provider.jti.count.Load()
|
||||
assert.Equal(t, int64(0), finalCount,
|
||||
"Counter should be 0 after concurrent cleanups, got %d", finalCount)
|
||||
assert.GreaterOrEqual(t, finalCount, int64(0),
|
||||
@@ -1312,7 +1312,7 @@ func TestOIDCProviderConcurrentCleanupNoNegativeCount(t *testing.T) {
|
||||
|
||||
// Verify store is actually empty
|
||||
storeCount := 0
|
||||
provider.jtiStore.Range(func(key, value interface{}) bool {
|
||||
provider.jti.store.Range(func(key, value interface{}) bool {
|
||||
storeCount++
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -22,9 +22,8 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
brokerHealthCheckTimeout = 5 * time.Second
|
||||
brokerHealthCheckAttempts = 3
|
||||
brokerHealthCheckBackoff = 250 * time.Millisecond
|
||||
brokerHealthCheckTimeout = 5 * time.Second
|
||||
brokerHealthCheckBackoff = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
// NewBrokerClientWithFilerAccessor creates a client with a shared filer accessor
|
||||
@@ -102,14 +101,17 @@ func (bc *BrokerClient) Close() error {
|
||||
return bc.conn.Close()
|
||||
}
|
||||
|
||||
// HealthCheck verifies the broker connection is working
|
||||
// HealthCheck verifies the broker connection is working. A freshly announced
|
||||
// broker may still be acquiring its balancer lock, so keep retrying for the
|
||||
// same window cluster discovery waits out.
|
||||
func (bc *BrokerClient) HealthCheck() error {
|
||||
if bc.client == nil {
|
||||
return fmt.Errorf("broker client not connected")
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(clusterNodeDiscoveryTimeout)
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= brokerHealthCheckAttempts; attempt++ {
|
||||
for attempt := 1; ; attempt++ {
|
||||
ctx, cancel := context.WithTimeout(bc.ctx, brokerHealthCheckTimeout)
|
||||
_, err := bc.client.FindBrokerLeader(ctx, &mq_pb.FindBrokerLeaderRequest{})
|
||||
cancel()
|
||||
@@ -117,17 +119,18 @@ func (bc *BrokerClient) HealthCheck() error {
|
||||
return nil
|
||||
}
|
||||
lastErr = err
|
||||
if attempt == brokerHealthCheckAttempts {
|
||||
if !time.Now().Before(deadline) {
|
||||
break
|
||||
}
|
||||
backoff := min(time.Duration(attempt)*brokerHealthCheckBackoff, time.Second)
|
||||
select {
|
||||
case <-bc.ctx.Done():
|
||||
return bc.ctx.Err()
|
||||
case <-time.After(time.Duration(attempt) * brokerHealthCheckBackoff):
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("broker health check failed after %d attempts: %v", brokerHealthCheckAttempts, lastErr)
|
||||
return fmt.Errorf("broker health check failed after %v: %v", clusterNodeDiscoveryTimeout, lastErr)
|
||||
}
|
||||
|
||||
// GetPartitionRangeInfo gets comprehensive range information from SeaweedMQ broker's native range manager
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
)
|
||||
|
||||
type stubMessagingClient struct {
|
||||
mq_pb.SeaweedMessagingClient
|
||||
calls int
|
||||
failFor int
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *stubMessagingClient) FindBrokerLeader(ctx context.Context, in *mq_pb.FindBrokerLeaderRequest, opts ...grpc.CallOption) (*mq_pb.FindBrokerLeaderResponse, error) {
|
||||
s.calls++
|
||||
if s.calls <= s.failFor {
|
||||
return nil, s.err
|
||||
}
|
||||
return &mq_pb.FindBrokerLeaderResponse{}, nil
|
||||
}
|
||||
|
||||
func TestHealthCheckRetriesPastTransientBrokerErrors(t *testing.T) {
|
||||
stub := &stubMessagingClient{failFor: 2, err: errors.New("lock broker_balancer not found")}
|
||||
bc := &BrokerClient{ctx: context.Background(), client: stub}
|
||||
if err := bc.HealthCheck(); err != nil || stub.calls != 3 {
|
||||
t.Fatalf("err %v after %d calls, want success on the 3rd", err, stub.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealthCheckGivesUpAtDeadline(t *testing.T) {
|
||||
defer func(orig time.Duration) { clusterNodeDiscoveryTimeout = orig }(clusterNodeDiscoveryTimeout)
|
||||
clusterNodeDiscoveryTimeout = 300 * time.Millisecond
|
||||
|
||||
stub := &stubMessagingClient{failFor: 1 << 30, err: errors.New("lock broker_balancer not found")}
|
||||
bc := &BrokerClient{ctx: context.Background(), client: stub}
|
||||
if err := bc.HealthCheck(); err == nil || stub.calls < 2 {
|
||||
t.Fatalf("err %v after %d calls, want repeated retries then an error", err, stub.calls)
|
||||
}
|
||||
}
|
||||
@@ -52,21 +52,23 @@ func NewSeaweedMQBrokerHandler(masters string, filerGroup string, clientHost str
|
||||
time.Sleep(2 * time.Second)
|
||||
glog.V(1).Infof("Initial connection delay completed")
|
||||
|
||||
// Discover brokers from masters using master client
|
||||
// Discover brokers and filers from masters using master client. A fresh
|
||||
// node registers only after its announce delay (a filer also waits out its
|
||||
// empty-membership confirm window), so an empty list right after startup
|
||||
// is normal: wait rather than fail fast.
|
||||
glog.V(1).Infof("About to call discoverBrokersWithMasterClient...")
|
||||
brokerAddresses, err := discoverBrokersWithMasterClient(ctx, masterClient, filerGroup)
|
||||
brokerAddresses, err := waitForClusterNodes(ctx, "brokers", clusterNodeDiscoveryTimeout, func() ([]string, error) {
|
||||
return discoverBrokersWithMasterClient(ctx, masterClient, filerGroup)
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("Broker discovery failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to discover brokers: %v", err)
|
||||
}
|
||||
glog.V(1).Infof("Broker discovery returned: %v", brokerAddresses)
|
||||
|
||||
if len(brokerAddresses) == 0 {
|
||||
return nil, fmt.Errorf("no brokers discovered from masters")
|
||||
}
|
||||
|
||||
// Discover filers from masters using master client
|
||||
filerAddresses, err := discoverFilersWithMasterClient(ctx, masterClient, filerGroup)
|
||||
filerAddresses, err := waitForClusterNodes(ctx, "filers", clusterNodeDiscoveryTimeout, func() ([]pb.ServerAddress, error) {
|
||||
return discoverFilersWithMasterClient(ctx, masterClient, filerGroup)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to discover filers: %v", err)
|
||||
}
|
||||
@@ -143,7 +145,31 @@ func discoverBrokersWithMasterClient(ctx context.Context, masterClient *wdclient
|
||||
return brokers, err
|
||||
}
|
||||
|
||||
// discoverFilersWithMasterClient queries masters for available filers using reusable master client
|
||||
// clusterNodeDiscoveryTimeout bounds how long the gateway waits for the
|
||||
// masters to list a node; well above a fresh node's announce delay.
|
||||
var clusterNodeDiscoveryTimeout = 60 * time.Second
|
||||
|
||||
// waitForClusterNodes calls discover until it returns at least one node, an
|
||||
// error, or timeout passes, retrying once a second while the list is empty.
|
||||
func waitForClusterNodes[T any](ctx context.Context, nodeType string, timeout time.Duration, discover func() ([]T, error)) ([]T, error) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
nodes, err := discover()
|
||||
if err != nil || len(nodes) > 0 {
|
||||
return nodes, err
|
||||
}
|
||||
if !time.Now().Before(deadline) {
|
||||
return nil, fmt.Errorf("no %s registered with the masters after %v", nodeType, timeout)
|
||||
}
|
||||
glog.V(1).Infof("no %s registered with the masters yet; retrying", nodeType)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func discoverFilersWithMasterClient(ctx context.Context, masterClient *wdclient.MasterClient, filerGroup string) ([]pb.ServerAddress, error) {
|
||||
var filers []pb.ServerAddress
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
// A fresh filer is listed by the masters only after its announce delay, so an
|
||||
// empty list must be waited out, not handed to the filer client accessor
|
||||
// (which panics on it).
|
||||
func TestWaitForFilersWaitsOutEmptyListing(t *testing.T) {
|
||||
calls := 0
|
||||
filers, err := waitForClusterNodes(context.Background(), "filers", 10*time.Second, func() ([]pb.ServerAddress, error) {
|
||||
calls++
|
||||
if calls < 3 {
|
||||
return nil, nil
|
||||
}
|
||||
return []pb.ServerAddress{"filer:8888"}, nil
|
||||
})
|
||||
if err != nil || len(filers) != 1 || calls != 3 {
|
||||
t.Fatalf("filers %v err %v after %d calls, want 1 filer after 3", filers, err, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFilersGivesUpWithAnError(t *testing.T) {
|
||||
filers, err := waitForClusterNodes(context.Background(), "filers", 1500*time.Millisecond, func() ([]pb.ServerAddress, error) { return nil, nil })
|
||||
if err == nil || len(filers) != 0 {
|
||||
t.Fatalf("still empty: filers %v err %v, want an error", filers, err)
|
||||
}
|
||||
boom := errors.New("master down")
|
||||
if _, err := waitForClusterNodes(context.Background(), "filers", time.Minute, func() ([]pb.ServerAddress, error) { return nil, boom }); !errors.Is(err, boom) {
|
||||
t.Fatalf("discovery error: got %v, want it returned at once", err)
|
||||
}
|
||||
}
|
||||
@@ -26,10 +26,10 @@ func LoadConfiguration(config *util.ViperProxy, prefix string) {
|
||||
return
|
||||
}
|
||||
|
||||
validateOneEnabledQueue(config)
|
||||
validateOneEnabledQueue(config, prefix)
|
||||
|
||||
for _, queue := range MessageQueues {
|
||||
if config.GetBool(prefix + queue.GetName() + ".enabled") {
|
||||
if queueEnabled(config, prefix, queue) {
|
||||
if err := queue.Initialize(config, prefix+queue.GetName()+"."); err != nil {
|
||||
glog.Fatalf("Failed to initialize notification for %s: %+v",
|
||||
queue.GetName(), err)
|
||||
@@ -42,10 +42,26 @@ func LoadConfiguration(config *util.ViperProxy, prefix string) {
|
||||
|
||||
}
|
||||
|
||||
func validateOneEnabledQueue(config *util.ViperProxy) {
|
||||
// queueEnabled reports whether a queue is switched on — by the flat
|
||||
// "<prefix><name>.enabled" flag or, for queues accepting named sub-instances
|
||||
// ([notification.<queue>.<target>]), by any enabled subconfig.
|
||||
func queueEnabled(config util.Configuration, prefix string, queue MessageQueue) bool {
|
||||
key := prefix + queue.GetName() + "."
|
||||
if config.GetBool(key + "enabled") {
|
||||
return true
|
||||
}
|
||||
if q, ok := queue.(interface {
|
||||
HasEnabledSubconfig(util.Configuration, string) bool
|
||||
}); ok {
|
||||
return q.HasEnabledSubconfig(config, key)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func validateOneEnabledQueue(config *util.ViperProxy, prefix string) {
|
||||
enabledQueue := ""
|
||||
for _, queue := range MessageQueues {
|
||||
if config.GetBool(queue.GetName() + ".enabled") {
|
||||
if queueEnabled(config, prefix, queue) {
|
||||
if enabledQueue == "" {
|
||||
enabledQueue = queue.GetName()
|
||||
} else {
|
||||
|
||||
@@ -3,7 +3,6 @@ package webhook
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/notification"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -30,12 +29,6 @@ func (e eventType) valid() bool {
|
||||
return notification.ValidEventType(string(e))
|
||||
}
|
||||
|
||||
var (
|
||||
pubSubHandlerNameTemplate = func(n int) string {
|
||||
return "webhook_handler_" + strconv.Itoa(n)
|
||||
}
|
||||
)
|
||||
|
||||
type client interface {
|
||||
sendMessage(message *webhookMessage) error
|
||||
}
|
||||
|
||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user