mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
76
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b3bd81eae | ||
|
|
ec8f979350 | ||
|
|
1a0485a43d | ||
|
|
8c1a0a0cc2 | ||
|
|
0c32eab48e | ||
|
|
85470416cb | ||
|
|
e442eda88e | ||
|
|
216c1032e6 | ||
|
|
03f773f087 | ||
|
|
a32d021f6f | ||
|
|
c871f3f6e6 | ||
|
|
36e6a2c5e1 | ||
|
|
f9dac64374 | ||
|
|
7b43dec665 | ||
|
|
efe80b1938 | ||
|
|
95d8a709e8 | ||
|
|
e432b75822 | ||
|
|
93aba4412e | ||
|
|
71cf9d4f21 | ||
|
|
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 | ||
|
|
347d02cf9e | ||
|
|
8311221fb4 | ||
|
|
d6b4290527 | ||
|
|
ff4b43e0f1 | ||
|
|
44235b5def | ||
|
|
8de67b6c38 | ||
|
|
eeeda21a67 | ||
|
|
c551bea9ce | ||
|
|
ff5433e63b | ||
|
|
30981f4665 |
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=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.49"
|
||||
appVersion: "4.50"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.49.0
|
||||
version: 4.50.0
|
||||
@@ -170,9 +170,6 @@ spec:
|
||||
{{- if .Values.filer.metricsIp }}
|
||||
-metricsIp={{ .Values.filer.metricsIp }} \
|
||||
{{- end }}
|
||||
{{- if .Values.filer.redirectOnRead }}
|
||||
-redirectOnRead \
|
||||
{{- end }}
|
||||
{{- if .Values.filer.disableHttp }}
|
||||
-disableHttp \
|
||||
{{- end }}
|
||||
|
||||
@@ -740,9 +740,6 @@ filer:
|
||||
# encrypt data on volume servers
|
||||
encryptVolumeData: false
|
||||
|
||||
# Whether proxy or redirect to volume server during file GET request
|
||||
redirectOnRead: false
|
||||
|
||||
# Limit sub dir listing size (default 100000)
|
||||
dirListLimit: 100000
|
||||
|
||||
|
||||
+1034
-1094
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 53 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;
|
||||
@@ -783,6 +784,7 @@ message FilerConf {
|
||||
optional bool worm = 14;
|
||||
uint64 worm_grace_period_seconds = 15;
|
||||
uint64 worm_retention_time_seconds = 16;
|
||||
bool inode_index = 17;
|
||||
}
|
||||
repeated PathConf locations = 2;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -3002,50 +3039,62 @@ pub async fn post_handler(
|
||||
let needle_etag = n.etag();
|
||||
let needle_has_name = n.has_name();
|
||||
|
||||
let write_result = write_upload_needle(&state, vid, n, fsync).await;
|
||||
|
||||
// Replicate to remote volume servers if this volume has replicas.
|
||||
// Matches Go's GetWritableRemoteReplications: skip if copy_count == 1.
|
||||
let needs_replication = !is_replicate && {
|
||||
let store = state.store.read().unwrap();
|
||||
store
|
||||
.find_volume(vid)
|
||||
.is_some_and(|(_, v)| v.super_block().replica_placement.get_copy_count() > 1)
|
||||
};
|
||||
|
||||
// The fan-out runs concurrently with the local needle write, like Go's
|
||||
// ReplicatedWrite: it reads the already-buffered request body, so the two
|
||||
// sides share no mutable state. The ack still waits for both.
|
||||
let replication = if needs_replication {
|
||||
let state_clone = state.clone();
|
||||
let path_clone = path.clone();
|
||||
let query_clone = query.clone();
|
||||
let headers_clone = headers.clone();
|
||||
let body_clone = body.clone();
|
||||
Some(tokio::spawn(async move {
|
||||
do_replicated_request(
|
||||
&state_clone,
|
||||
vid.0,
|
||||
Method::POST,
|
||||
&path_clone,
|
||||
&query_clone,
|
||||
&headers_clone,
|
||||
Some(body_clone),
|
||||
)
|
||||
.await
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let write_result = write_upload_needle(&state, vid, n, fsync).await;
|
||||
|
||||
// No leader-known gate: when the lookup cannot run, the write must fail
|
||||
// rather than be acknowledged on fewer copies than required.
|
||||
if !is_replicate && write_result.is_ok() {
|
||||
let needs_replication = {
|
||||
let store = state.store.read().unwrap();
|
||||
store
|
||||
.find_volume(vid)
|
||||
.is_some_and(|(_, v)| v.super_block().replica_placement.get_copy_count() > 1)
|
||||
};
|
||||
if needs_replication {
|
||||
let state_clone = state.clone();
|
||||
let path_clone = path.clone();
|
||||
let query_clone = query.clone();
|
||||
let headers_clone = headers.clone();
|
||||
let body_clone = body.clone();
|
||||
let replication = tokio::spawn(async move {
|
||||
do_replicated_request(
|
||||
&state_clone,
|
||||
vid.0,
|
||||
Method::POST,
|
||||
&path_clone,
|
||||
&query_clone,
|
||||
&headers_clone,
|
||||
Some(body_clone),
|
||||
)
|
||||
.await
|
||||
});
|
||||
let replication_result = replication
|
||||
.await
|
||||
// rather than be acknowledged on fewer copies than required. The local
|
||||
// write result takes precedence, matching Go's error ordering.
|
||||
let replication_result = match replication {
|
||||
Some(task) => Some(
|
||||
task.await
|
||||
.map_err(|e| format!("replication task failed: {}", e))
|
||||
.flatten();
|
||||
if let Err(e) = replication_result {
|
||||
tracing::error!("replicated write failed: {}", e);
|
||||
return json_error_with_query(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("replication failed: {}", e),
|
||||
Some(&query),
|
||||
);
|
||||
}
|
||||
}
|
||||
.flatten(),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
if write_result.is_ok()
|
||||
&& let Some(Err(e)) = replication_result
|
||||
{
|
||||
tracing::error!("replicated write failed: {}", e);
|
||||
return json_error_with_query(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("replication failed: {}", e),
|
||||
Some(&query),
|
||||
);
|
||||
}
|
||||
|
||||
let resp = match write_result {
|
||||
@@ -5644,6 +5693,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 +7431,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()
|
||||
|
||||
@@ -466,6 +466,7 @@ func (env *TestEnvironment) startTrinoContainer(t *testing.T, configDir string)
|
||||
|
||||
cmd := exec.Command("docker", "run", "-d",
|
||||
"--name", containerName,
|
||||
"--memory", "4g",
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-v", fmt.Sprintf("%s:/etc/trino/catalog", configDir),
|
||||
"-v", fmt.Sprintf("%s:/test", env.dataDir),
|
||||
@@ -484,7 +485,7 @@ func waitForTrino(t *testing.T, containerName string, timeout time.Duration) {
|
||||
|
||||
deadline := time.Now().Add(timeout)
|
||||
var lastOutput []byte
|
||||
retryCount := 0
|
||||
containerDead := false
|
||||
for time.Now().Before(deadline) {
|
||||
// Try system catalog query as a readiness check
|
||||
cmd := exec.Command("docker", "exec", containerName,
|
||||
@@ -495,26 +496,51 @@ func waitForTrino(t *testing.T, containerName string, timeout time.Duration) {
|
||||
return
|
||||
} else {
|
||||
lastOutput = output
|
||||
outputStr := string(output)
|
||||
if strings.Contains(outputStr, "No such container") ||
|
||||
strings.Contains(outputStr, "is not running") {
|
||||
if trinoContainerExited(output) {
|
||||
containerDead = true
|
||||
break
|
||||
}
|
||||
retryCount++
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
|
||||
// If we can't connect to system catalog, try to at least connect to Trino server
|
||||
cmd := exec.Command("docker", "exec", containerName, "trino", "--version")
|
||||
if err := cmd.Run(); err == nil {
|
||||
if output, err := exec.Command("docker", "exec", containerName, "trino", "--version").CombinedOutput(); err == nil {
|
||||
// Trino process is running, even if catalog isn't ready yet
|
||||
// Give it a bit more time
|
||||
time.Sleep(5 * time.Second)
|
||||
return
|
||||
} else {
|
||||
lastOutput = output
|
||||
containerDead = containerDead || trinoContainerExited(output)
|
||||
}
|
||||
|
||||
t.Fatalf("Timed out waiting for Trino to be ready\nLast output:\n%s", string(lastOutput))
|
||||
if containerDead {
|
||||
t.Fatalf("Trino container %s exited before becoming ready\nLast output:\n%s\n%s", containerName, string(lastOutput), trinoContainerDiagnostics(containerName))
|
||||
}
|
||||
t.Fatalf("Timed out waiting for Trino to be ready\nLast output:\n%s\n%s", string(lastOutput), trinoContainerDiagnostics(containerName))
|
||||
}
|
||||
|
||||
func trinoContainerExited(output []byte) bool {
|
||||
s := string(output)
|
||||
return strings.Contains(s, "No such container") || strings.Contains(s, "is not running")
|
||||
}
|
||||
|
||||
func trinoContainerDiagnostics(containerName string) string {
|
||||
var b strings.Builder
|
||||
if out, err := exec.Command("docker", "inspect", "-f",
|
||||
"status={{.State.Status}} exitCode={{.State.ExitCode}} oomKilled={{.State.OOMKilled}} error={{.State.Error}}",
|
||||
containerName).CombinedOutput(); err == nil {
|
||||
fmt.Fprintf(&b, "docker inspect: %s\n", strings.TrimSpace(string(out)))
|
||||
} else {
|
||||
fmt.Fprintf(&b, "docker inspect failed: %v (%s)\n", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
if out, err := exec.Command("docker", "logs", "--tail", "80", containerName).CombinedOutput(); err == nil {
|
||||
fmt.Fprintf(&b, "docker logs:\n%s", string(out))
|
||||
} else {
|
||||
fmt.Fprintf(&b, "docker logs failed: %v (%s)", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func runTrinoSQL(t *testing.T, containerName, sql string) string {
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -170,11 +170,11 @@ func TestConditionalHeaderPrecedenceAndInvalidIfModifiedSince(t *testing.T) {
|
||||
precedenceReq.Header.Set("If-None-Match", "\"definitely-different-etag\"")
|
||||
precedenceResp := framework.DoRequest(t, client, precedenceReq)
|
||||
precedenceBody := framework.ReadAllAndClose(t, precedenceResp)
|
||||
if precedenceResp.StatusCode != http.StatusNotModified {
|
||||
t.Fatalf("conditional precedence expected 304, got %d", precedenceResp.StatusCode)
|
||||
if precedenceResp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("mismatched If-None-Match overrides If-Modified-Since: expected 200, got %d", precedenceResp.StatusCode)
|
||||
}
|
||||
if len(precedenceBody) != 0 {
|
||||
t.Fatalf("conditional precedence expected empty body, got %d bytes", len(precedenceBody))
|
||||
if string(precedenceBody) != string(payload) {
|
||||
t.Fatalf("mismatched If-None-Match body mismatch: got %q want %q", string(precedenceBody), string(payload))
|
||||
}
|
||||
|
||||
invalidIMSReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -181,7 +181,7 @@ func (store *EtcdStore) DeleteFolderChildren(ctx context.Context, fullpath weed_
|
||||
func (store *EtcdStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
|
||||
directoryPrefix := genDirectoryKeyPrefix(dirPath, prefix)
|
||||
lastFileStart := directoryPrefix
|
||||
if startFileName != "" {
|
||||
if startFileName > prefix {
|
||||
lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
|
||||
}
|
||||
|
||||
|
||||
+8
-7
@@ -364,7 +364,10 @@ func (f *Filer) ListExistingPeerUpdates(ctx context.Context) (existingNodes []*m
|
||||
}
|
||||
|
||||
func (f *Filer) SetStore(store FilerStore) (isFresh bool) {
|
||||
f.Store = NewFilerStoreWrapper(store)
|
||||
fsw := NewFilerStoreWrapper(store)
|
||||
// f.FilerConf is swapped on filer.conf reloads, so resolve it per call.
|
||||
fsw.filerConfFn = func() *FilerConf { return f.FilerConf }
|
||||
f.Store = fsw
|
||||
|
||||
isFresh = f.setOrLoadFilerStoreSignature(store)
|
||||
|
||||
@@ -434,7 +437,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
|
||||
@@ -772,10 +775,8 @@ func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, e
|
||||
}
|
||||
entry, err = f.Store.FindEntry(ctx, p)
|
||||
// A directory is deleted here one row at a time, which would strand whatever is
|
||||
// under it, so a TTL an older build left on one is not acted on. Retention
|
||||
// outranks expiry the same way it outranks lifecycle rules on S3: a locked
|
||||
// entry stays visible rather than being evicted on read.
|
||||
if entry != nil && entry.TtlSec > 0 && !entry.IsDirectory() && !entryLockedForDelete(entry, false, time.Now()) {
|
||||
// under it, so a TTL an older build left on one is not acted on.
|
||||
if entry != nil && entry.TtlSec > 0 && !entry.IsDirectory() {
|
||||
if entry.IsExpireS3Enabled() {
|
||||
if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() {
|
||||
if delErr := f.doDeleteEntryMetaAndData(ctx, entry, true, false, nil); delErr != nil {
|
||||
@@ -814,7 +815,7 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
|
||||
glog.V(1).InfofCtx(ctx, "listing %q canceled: %v", p, ctx.Err())
|
||||
return false, fmt.Errorf("context canceled: %w", ctx.Err())
|
||||
default:
|
||||
if entry.TtlSec > 0 && !entry.IsDirectory() && !entryLockedForDelete(entry, false, time.Now()) {
|
||||
if entry.TtlSec > 0 && !entry.IsDirectory() {
|
||||
if entry.IsExpireS3Enabled() {
|
||||
if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() {
|
||||
// Collect for deletion after iteration completes to avoid DB deadlock
|
||||
|
||||
+64
-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,
|
||||
@@ -248,9 +255,51 @@ func ClonePathConf(src *filer_pb.FilerConf_PathConf) *filer_pb.FilerConf_PathCon
|
||||
Worm: worm,
|
||||
WormGracePeriodSeconds: src.WormGracePeriodSeconds,
|
||||
WormRetentionTimeSeconds: src.WormRetentionTimeSeconds,
|
||||
InodeIndex: src.InodeIndex,
|
||||
}
|
||||
}
|
||||
|
||||
// MatchInodeIndexRule reports whether an inode_index rule covers path. Unlike
|
||||
// MatchStorageRule it requires the rule's location to end at a path boundary,
|
||||
// so a rule on /exports does not index /exports2 or /exports_old.
|
||||
func (fc *FilerConf) MatchInodeIndexRule(path string) bool {
|
||||
active := false
|
||||
fc.rules.MatchPrefix([]byte(path), func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
|
||||
if !value.InodeIndex {
|
||||
return true
|
||||
}
|
||||
rulePath := strings.TrimSuffix(string(key), "/")
|
||||
if path == rulePath || strings.HasPrefix(path, rulePath+"/") {
|
||||
active = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return active
|
||||
}
|
||||
|
||||
// InodeIndexActiveUnder reports whether entries inside dirPath may carry inode
|
||||
// index rows: either dirPath itself is covered by an inode_index rule, or such
|
||||
// a rule applies to a subtree inside dirPath.
|
||||
func (fc *FilerConf) InodeIndexActiveUnder(dirPath string) bool {
|
||||
if fc.MatchInodeIndexRule(dirPath) {
|
||||
return true
|
||||
}
|
||||
prefix := dirPath
|
||||
if !strings.HasSuffix(prefix, "/") {
|
||||
prefix += "/"
|
||||
}
|
||||
active := false
|
||||
fc.rules.Walk(func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
|
||||
if value.InodeIndex && (string(key) == dirPath || strings.HasPrefix(string(key), prefix)) {
|
||||
active = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return active
|
||||
}
|
||||
|
||||
// ApplyBucketQuotaReadOnly sets read-only when usedSize exceeds quota and clears it
|
||||
// once back under, reporting whether the flag changed. A non-positive quota is left
|
||||
// untouched so a manually locked bucket is never reopened.
|
||||
@@ -484,7 +533,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 +556,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,13 +573,11 @@ 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)
|
||||
}
|
||||
a.InodeIndex = b.InodeIndex || a.InodeIndex
|
||||
if b.WormRetentionTimeSeconds > 0 {
|
||||
a.WormRetentionTimeSeconds = b.WormRetentionTimeSeconds
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -141,6 +206,7 @@ func TestClonePathConf(t *testing.T) {
|
||||
Worm: proto.Bool(true),
|
||||
WormGracePeriodSeconds: 3600,
|
||||
WormRetentionTimeSeconds: 86400,
|
||||
InodeIndex: true,
|
||||
}
|
||||
|
||||
clone := ClonePathConf(src)
|
||||
@@ -189,9 +255,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")
|
||||
}
|
||||
|
||||
|
||||
@@ -5,21 +5,18 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const (
|
||||
MsgFailDelNonEmptyFolder = "fail to delete non-empty folder"
|
||||
MsgFailDelLockedEntry = "fail to delete locked entry"
|
||||
)
|
||||
|
||||
// ErrNonEmptyFolder is a non-recursive delete refused because the folder still
|
||||
@@ -28,11 +25,6 @@ const (
|
||||
// chose, cannot forge one.
|
||||
var ErrNonEmptyFolder = errors.New(MsgFailDelNonEmptyFolder)
|
||||
|
||||
// ErrEntryLocked is a delete refused because the entry carries an active legal
|
||||
// hold or an unexpired retention. It follows ErrNonEmptyFolder's leading-marker
|
||||
// rule for the same reason.
|
||||
var ErrEntryLocked = errors.New(MsgFailDelLockedEntry)
|
||||
|
||||
// DeleteEntryError turns the text of DeleteEntryResponse.Error back into an
|
||||
// error carrying the condition the filer reported. Call it on the response
|
||||
// field, before formatting a path around it.
|
||||
@@ -40,9 +32,6 @@ func DeleteEntryError(msg string) error {
|
||||
if strings.HasPrefix(msg, MsgFailDelNonEmptyFolder) {
|
||||
return &deleteEntryError{msg: msg, cause: ErrNonEmptyFolder}
|
||||
}
|
||||
if strings.HasPrefix(msg, MsgFailDelLockedEntry) {
|
||||
return &deleteEntryError{msg: msg, cause: ErrEntryLocked}
|
||||
}
|
||||
return errors.New(msg)
|
||||
}
|
||||
|
||||
@@ -56,14 +45,6 @@ func IsNonEmptyFolderError(err error) bool {
|
||||
return errors.Is(err, ErrNonEmptyFolder) || strings.HasPrefix(err.Error(), MsgFailDelNonEmptyFolder)
|
||||
}
|
||||
|
||||
// IsEntryLockedError is the ErrEntryLocked counterpart of IsNonEmptyFolderError.
|
||||
func IsEntryLockedError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
return errors.Is(err, ErrEntryLocked) || strings.HasPrefix(err.Error(), MsgFailDelLockedEntry)
|
||||
}
|
||||
|
||||
type deleteEntryError struct {
|
||||
msg string
|
||||
cause error
|
||||
@@ -99,147 +80,6 @@ func keepsRemoteObject(ctx context.Context) bool {
|
||||
return ctx.Value(keepRemoteObjectKey{}) != nil
|
||||
}
|
||||
|
||||
type bypassGovernanceRetentionKey struct{}
|
||||
|
||||
// WithBypassGovernanceRetention records that the caller is authorized to drop
|
||||
// governance-mode retention on this delete -- the S3 gateway sets it after
|
||||
// s3:BypassGovernanceRetention. Legal hold and compliance retention refuse
|
||||
// the delete regardless.
|
||||
func WithBypassGovernanceRetention(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, bypassGovernanceRetentionKey{}, true)
|
||||
}
|
||||
|
||||
// BypassesGovernanceRetention reports whether ctx carries the governance-bypass
|
||||
// assertion WithBypassGovernanceRetention plants.
|
||||
func BypassesGovernanceRetention(ctx context.Context) bool {
|
||||
return ctx.Value(bypassGovernanceRetentionKey{}) != nil
|
||||
}
|
||||
|
||||
// entryLockedForDelete mirrors the S3 gateway's EntryHasActiveLock on the
|
||||
// entry's extended attributes, except a governance bypass skips only
|
||||
// governance-mode retention. An unparseable retention date fails closed.
|
||||
func entryLockedForDelete(entry *Entry, bypassGovernance bool, now time.Time) bool {
|
||||
ext := entry.Extended
|
||||
if ext == nil {
|
||||
return false
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(string(ext[s3_constants.ExtLegalHoldKey])), s3_constants.LegalHoldOn) {
|
||||
return true
|
||||
}
|
||||
mode := strings.ToUpper(strings.TrimSpace(string(ext[s3_constants.ExtObjectLockModeKey])))
|
||||
if mode != s3_constants.RetentionModeCompliance && mode != s3_constants.RetentionModeGovernance {
|
||||
return false
|
||||
}
|
||||
if bypassGovernance && mode == s3_constants.RetentionModeGovernance {
|
||||
return false
|
||||
}
|
||||
dateBytes, found := ext[s3_constants.ExtRetentionUntilDateKey]
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
timestamp, err := strconv.ParseInt(strings.TrimSpace(string(dateBytes)), 10, 64)
|
||||
if err != nil {
|
||||
glog.Warningf("unparseable retention date %q on %s, treating as locked: %v", dateBytes, entry.FullPath, err)
|
||||
return true
|
||||
}
|
||||
return time.Unix(timestamp, 0).After(now)
|
||||
}
|
||||
|
||||
func (f *Filer) entryDeleteLockError(ctx context.Context, entry *Entry) error {
|
||||
if f.multipartStagingPath(entry.FullPath) {
|
||||
return nil
|
||||
}
|
||||
if entryLockedForDelete(entry, BypassesGovernanceRetention(ctx), time.Now()) {
|
||||
return fmt.Errorf("%w: %s", ErrEntryLocked, entry.FullPath)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// multipartStagingPath reports whether p is a bucket's .uploads dir or inside
|
||||
// it. createMultipartUpload stamps the object's requested retention and legal
|
||||
// hold on the upload directory so the completed object inherits them, but the
|
||||
// staging area is bookkeeping, not a locked object: finalize, abort, and
|
||||
// s3.clean.uploads all have to be able to remove it, and the gateway's
|
||||
// bucket-lock scan skips it for the same reason.
|
||||
func (f *Filer) multipartStagingPath(p util.FullPath) bool {
|
||||
rel := strings.TrimPrefix(string(p), f.DirBucketsPath+"/")
|
||||
if rel == string(p) {
|
||||
return false
|
||||
}
|
||||
_, rest, found := strings.Cut(rel, "/")
|
||||
return found && (rest == s3_constants.MultipartUploadsFolder || strings.HasPrefix(rest, s3_constants.MultipartUploadsFolder+"/"))
|
||||
}
|
||||
|
||||
// lockedDescendantError walks the subtree once, refusing the delete on the
|
||||
// first entry under an active legal hold or retention. It runs before the
|
||||
// recursive delete emits any side effect, so a refusal cannot arrive after
|
||||
// earlier descendants -- or the ancestor's remote tombstone -- are already
|
||||
// gone, and it covers the store-drop path whose DeleteFolderChildren never
|
||||
// lists the children it removes. The per-page check in the delete walk still
|
||||
// catches a lock planted between this pass and the delete.
|
||||
func (f *Filer) lockedDescendantError(ctx context.Context, entry *Entry) error {
|
||||
lastFileName := ""
|
||||
includeLastFile := false
|
||||
for {
|
||||
entries, _, err := f.ListDirectoryEntries(ctx, entry.FullPath, lastFileName, includeLastFile, PaginationSize, "", "", "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("list folder %s: %v", entry.FullPath, err)
|
||||
}
|
||||
for _, sub := range entries {
|
||||
lastFileName = sub.Name()
|
||||
if lockErr := f.entryDeleteLockError(ctx, sub); lockErr != nil {
|
||||
return lockErr
|
||||
}
|
||||
if sub.IsDirectory() {
|
||||
if lockErr := f.lockedDescendantError(ctx, sub); lockErr != nil {
|
||||
return lockErr
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(entries) < PaginationSize {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// objectLockEnabledOnEntry mirrors the S3 gateway's IsObjectLockEnabled.
|
||||
func objectLockEnabledOnEntry(entry *Entry) bool {
|
||||
enabled, found := entry.Extended[s3_constants.ExtObjectLockEnabledKey]
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
v := string(enabled)
|
||||
return v == s3_constants.ObjectLockEnabled || v == "true"
|
||||
}
|
||||
|
||||
// mayDescendantsHoldLocks reports whether the subtree under p can hold an
|
||||
// entry under retention or legal hold. The S3 gateway refuses to set either
|
||||
// outside a lock-enabled bucket, so a tree elsewhere can only carry planted
|
||||
// attributes, which the walk still refuses on sight. The pre-pass that makes
|
||||
// refusal atomic is worth its second scan only when locks genuinely apply.
|
||||
func (f *Filer) mayDescendantsHoldLocks(ctx context.Context, p util.FullPath, entry *Entry) bool {
|
||||
if objectLockEnabledOnEntry(entry) {
|
||||
return true
|
||||
}
|
||||
rel := strings.TrimPrefix(string(p), f.DirBucketsPath+"/")
|
||||
if rel == string(p) {
|
||||
// The subtree can also hold locks by containing the buckets dir
|
||||
// itself: deleting it or an ancestor drops each bucket's children
|
||||
// unseen mid-walk.
|
||||
dir := strings.TrimSuffix(string(p), "/")
|
||||
return dir == f.DirBucketsPath || strings.HasPrefix(f.DirBucketsPath, dir+"/")
|
||||
}
|
||||
bucket, _, _ := strings.Cut(rel, "/")
|
||||
if bucket == "" {
|
||||
return false
|
||||
}
|
||||
bucketEntry, err := f.FindEntry(ctx, util.FullPath(f.DirBucketsPath+"/"+bucket))
|
||||
if err != nil {
|
||||
return !errors.Is(err, filer_pb.ErrNotFound)
|
||||
}
|
||||
return bucketEntry != nil && objectLockEnabledOnEntry(bucketEntry)
|
||||
}
|
||||
|
||||
// emptyFolderDeleteContext makes deleting a folder that is empty in the filer
|
||||
// metadata-only when it is under a remote mount. A mount is populated lazily,
|
||||
// so the folder can still hold remote objects never read, and removing its
|
||||
@@ -291,15 +131,6 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
if ifNotModifiedAfter > 0 && entry.Attr.Mtime.Unix() > ifNotModifiedAfter {
|
||||
return nil
|
||||
}
|
||||
// A cluster replaying a delete the origin already authorized must not
|
||||
// second-guess it: the entry's lock state here may legitimately still be
|
||||
// in force (e.g. an expired-elsewhere retention, or a governance bypass
|
||||
// the peer observed before shipping the event).
|
||||
if !isFromOtherCluster {
|
||||
if lockErr := f.entryDeleteLockError(ctx, entry); lockErr != nil {
|
||||
return lockErr
|
||||
}
|
||||
}
|
||||
if !isRecursive && entry.IsDirectory() {
|
||||
ctx = f.emptyFolderDeleteContext(ctx, p)
|
||||
}
|
||||
@@ -312,16 +143,6 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
// per entry rather than dropped wholesale with it.
|
||||
dropsCollection := isDeleteCollection && collectionName != ""
|
||||
if entry.IsDirectory() {
|
||||
// The pre-pass is mandatory when the delete ends in a store-level
|
||||
// drop that never lists the children it removes; when they are walked
|
||||
// anyway, the per-page check already refuses a lock on sight, so the
|
||||
// second scan only buys atomicity where locks genuinely apply.
|
||||
childrenDroppedUnseen := isDeleteCollection && (dropsCollection || !shouldDeleteChunks) && f.Store.CanDropWholeBucket() && !objectLockEnabledOnEntry(entry)
|
||||
if isRecursive && !isFromOtherCluster && (childrenDroppedUnseen || f.mayDescendantsHoldLocks(ctx, p, entry)) {
|
||||
if lockErr := f.lockedDescendantError(ctx, entry); lockErr != nil {
|
||||
return lockErr
|
||||
}
|
||||
}
|
||||
// delete the folder children, not including the folder itself
|
||||
err = f.doBatchDeleteFolderMetaAndData(ctx, entry, isRecursive, ignoreRecursiveError, shouldDeleteChunks && !dropsCollection, isDeleteCollection && (dropsCollection || !shouldDeleteChunks), isFromOtherCluster, signatures, func(hardLinkIds []HardLinkId) error {
|
||||
// A case not handled:
|
||||
@@ -333,7 +154,7 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(2).InfofCtx(ctx, "delete directory %s: %v", p, err)
|
||||
if errors.Is(err, ErrNonEmptyFolder) || errors.Is(err, ErrEntryLocked) {
|
||||
if errors.Is(err, ErrNonEmptyFolder) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("delete directory %s: %v", p, err)
|
||||
@@ -343,9 +164,6 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
|
||||
// delete the file or folder
|
||||
err = f.doDeleteEntryMetaAndData(ctx, entry, shouldDeleteChunks, isFromOtherCluster, signatures)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrEntryLocked) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("delete file %s: %v", p, err)
|
||||
}
|
||||
|
||||
@@ -390,9 +208,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
var chunksToDelete []*filer_pb.FileChunk
|
||||
lastFileName := ""
|
||||
includeLastFile := false
|
||||
// A lock-enabled bucket must be walked even when the store could drop it
|
||||
// whole: entries under active retention or legal hold refuse the delete.
|
||||
listedChildren := !isDeletingBucket || !f.Store.CanDropWholeBucket() || objectLockEnabledOnEntry(entry)
|
||||
listedChildren := !isDeletingBucket || !f.Store.CanDropWholeBucket()
|
||||
if listedChildren {
|
||||
for {
|
||||
entries, _, err := f.ListDirectoryEntries(ctx, entry.FullPath, lastFileName, includeLastFile, PaginationSize, "", "", "")
|
||||
@@ -409,26 +225,10 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
return fmt.Errorf("%w: %s", ErrNonEmptyFolder, entry.FullPath)
|
||||
}
|
||||
|
||||
// Refuse before any side effect of this page (events, remote
|
||||
// deletes, the folder-children sweep): a locked entry anywhere in
|
||||
// it fails the whole delete rather than slipping through the
|
||||
// store-level drop the walk ends in. Refusal is not a recursive
|
||||
// error -- ignoreRecursiveError must not waive a lock.
|
||||
if isRecursive && !isFromOtherCluster {
|
||||
for _, sub := range entries {
|
||||
if lockErr := f.entryDeleteLockError(ctx, sub); lockErr != nil {
|
||||
f.unnoteRemoteDeletion(entry.FullPath, dirTombstoneTs)
|
||||
return lockErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, sub := range entries {
|
||||
lastFileName = sub.Name()
|
||||
var subTombstoneTs int64
|
||||
if !keepsRemoteObject(ctx) {
|
||||
subTombstoneTs = time.Now().UnixNano()
|
||||
f.noteRemoteDeletion(sub.FullPath, sub.IsDirectory(), subTombstoneTs)
|
||||
f.noteRemoteDeletion(sub.FullPath, sub.IsDirectory(), time.Now().UnixNano())
|
||||
}
|
||||
if sub.IsDirectory() {
|
||||
subIsDeletingBucket := f.IsBucket(sub)
|
||||
@@ -442,7 +242,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil && (!ignoreRecursiveError || errors.Is(err, ErrEntryLocked)) {
|
||||
if err != nil && !ignoreRecursiveError {
|
||||
break
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, deleteEventEntry(ctx, sub), nil, shouldDeleteChunks, isFromOtherCluster, nil)
|
||||
@@ -458,12 +258,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil && (!ignoreRecursiveError || errors.Is(err, ErrEntryLocked)) {
|
||||
// the delete is abandoned: the tombstones noted for this
|
||||
// subtree and this level would hide children that still
|
||||
// exist
|
||||
f.unnoteRemoteDeletion(sub.FullPath, subTombstoneTs)
|
||||
f.unnoteRemoteDeletion(entry.FullPath, dirTombstoneTs)
|
||||
if err != nil && !ignoreRecursiveError {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -479,14 +274,6 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
// a non-recursive delete already proved the folder empty above, so sweeping the
|
||||
// children now can only remove entries that raced in after that listing
|
||||
if isRecursive || !listedChildren {
|
||||
if !listedChildren && !isRecursive && !isFromOtherCluster {
|
||||
// A bucket dropped whole sweeps children nothing has listed; a
|
||||
// recursive caller already walked them in the preflight, but a
|
||||
// non-recursive one has not.
|
||||
if lockErr := f.lockedDescendantError(ctx, entry); lockErr != nil {
|
||||
return lockErr
|
||||
}
|
||||
}
|
||||
if storeDeletionErr := f.Store.DeleteFolderChildren(ctx, entry.FullPath); storeDeletionErr != nil {
|
||||
return fmt.Errorf("filer store delete: %w", storeDeletionErr)
|
||||
}
|
||||
@@ -502,12 +289,6 @@ func (f *Filer) doDeleteEntryMetaAndData(ctx context.Context, entry *Entry, shou
|
||||
|
||||
glog.V(3).InfofCtx(ctx, "deleting entry %v, delete chunks: %v", entry.FullPath, shouldDeleteChunks)
|
||||
|
||||
if !isFromOtherCluster {
|
||||
if lockErr := f.entryDeleteLockError(ctx, entry); lockErr != nil {
|
||||
return lockErr
|
||||
}
|
||||
}
|
||||
|
||||
if !isFromOtherCluster && !keepsRemoteObject(ctx) {
|
||||
if _, remoteDeletionErr := f.maybeDeleteFromRemote(ctx, entry); remoteDeletionErr != nil {
|
||||
return remoteDeletionErr
|
||||
|
||||
@@ -5,12 +5,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -119,330 +117,3 @@ func TestDeleteFolderKeepsSharedHardLinkChunks(t *testing.T) {
|
||||
require.NoError(t, err, "surviving link must keep the inode record")
|
||||
require.Equal(t, 0, f.pendingDeletionCount())
|
||||
}
|
||||
|
||||
func retentionEntry(mode string, until time.Time) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
s3_constants.ExtObjectLockModeKey: []byte(mode),
|
||||
s3_constants.ExtRetentionUntilDateKey: []byte(strconv.FormatInt(until.Unix(), 10)),
|
||||
}
|
||||
}
|
||||
|
||||
func TestEntryLockedForDelete(t *testing.T) {
|
||||
now := time.Now()
|
||||
future := now.Add(time.Hour)
|
||||
past := now.Add(-time.Hour)
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
ext map[string][]byte
|
||||
bypass bool
|
||||
locked bool
|
||||
}{
|
||||
{"no attributes", nil, false, false},
|
||||
{"legal hold on", map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("ON")}, false, true},
|
||||
{"legal hold bypass still locks", map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("on")}, true, true},
|
||||
{"legal hold off", map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("OFF")}, false, false},
|
||||
{"compliance active", retentionEntry(s3_constants.RetentionModeCompliance, future), false, true},
|
||||
{"compliance bypass still locks", retentionEntry(s3_constants.RetentionModeCompliance, future), true, true},
|
||||
{"compliance expired", retentionEntry(s3_constants.RetentionModeCompliance, past), false, false},
|
||||
{"governance active", retentionEntry(s3_constants.RetentionModeGovernance, future), false, true},
|
||||
{"governance bypass", retentionEntry(s3_constants.RetentionModeGovernance, future), true, false},
|
||||
{"governance expired", retentionEntry(s3_constants.RetentionModeGovernance, past), false, false},
|
||||
{"mode without date", map[string][]byte{s3_constants.ExtObjectLockModeKey: []byte(s3_constants.RetentionModeCompliance)}, false, false},
|
||||
{"unparseable date fails closed", map[string][]byte{
|
||||
s3_constants.ExtObjectLockModeKey: []byte(s3_constants.RetentionModeCompliance),
|
||||
s3_constants.ExtRetentionUntilDateKey: []byte("not-a-time"),
|
||||
}, false, true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
entry := &Entry{FullPath: "/buckets/b/o", Attr: Attr{Mode: 0644}, Extended: tt.ext}
|
||||
require.Equal(t, tt.locked, entryLockedForDelete(entry, tt.bypass, now))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The same leading-marker contract as ErrNonEmptyFolder keeps the wire text
|
||||
// classifiable and unforgeable.
|
||||
func TestEntryLockedClassification(t *testing.T) {
|
||||
err := fmt.Errorf("%w: %s", ErrEntryLocked, "/buckets/b/locked.bin")
|
||||
if !IsEntryLockedError(err) {
|
||||
t.Errorf("expected the sentinel to be recognized: %v", err)
|
||||
}
|
||||
if !errors.Is(DeleteEntryError(err.Error()), ErrEntryLocked) {
|
||||
t.Errorf("expected the wire text to classify: %v", err)
|
||||
}
|
||||
spoofed := "delete file /buckets/b/" + MsgFailDelLockedEntry + ": filer store delete: disk full"
|
||||
if errors.Is(DeleteEntryError(spoofed), ErrEntryLocked) {
|
||||
t.Errorf("expected no forgery from the entry name: %v", spoofed)
|
||||
}
|
||||
if IsEntryLockedError(errors.New(spoofed)) {
|
||||
t.Errorf("expected no forgery from the entry name: %v", spoofed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteEntryRefusesLockedObject(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
ctx := context.Background()
|
||||
|
||||
locked := &Entry{
|
||||
FullPath: "/buckets/b/locked.bin",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: retentionEntry(s3_constants.RetentionModeCompliance, time.Now().Add(time.Hour)),
|
||||
}
|
||||
require.NoError(t, f.CreateEntry(ctx, locked, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, locked.FullPath, false, false, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
require.True(t, IsEntryLockedError(err))
|
||||
require.True(t, IsEntryLockedError(DeleteEntryError(err.Error())))
|
||||
require.NotNil(t, store.getEntry("/buckets/b/locked.bin"), "locked entry must survive the refused delete")
|
||||
}
|
||||
|
||||
// A recursive delete fails at the locked descendant without removing anything.
|
||||
func TestDeleteEntryRecursiveRefusesLockedDescendant(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/d", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/d/free.txt", Attr: Attr{Mode: 0644}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{
|
||||
FullPath: "/d/locked.txt",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("ON")},
|
||||
}, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, "/d", true, true, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
require.NotNil(t, store.getEntry("/d"), "the folder itself must survive")
|
||||
require.NotNil(t, store.getEntry("/d/free.txt"), "unlocked siblings must survive a refused delete")
|
||||
require.NotNil(t, store.getEntry("/d/locked.txt"))
|
||||
}
|
||||
|
||||
// A lock refusal surfaces from any depth and cannot be waived by
|
||||
// ignoreRecursiveError: nothing in the subtree may be removed.
|
||||
func TestDeleteEntryRecursiveRefusesLockedGrandchild(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/d", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/d/early.txt", Attr: Attr{Mode: 0644}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/d/sub", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{
|
||||
FullPath: "/d/sub/locked.txt",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: retentionEntry(s3_constants.RetentionModeCompliance, time.Now().Add(time.Hour)),
|
||||
}, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, "/d", true, true, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
for _, p := range []string{"/d", "/d/early.txt", "/d/sub", "/d/sub/locked.txt"} {
|
||||
require.NotNil(t, store.getEntry(p), "%s must survive a refused recursive delete", p)
|
||||
}
|
||||
}
|
||||
|
||||
// Governance bypass is the only waiver the delete honors.
|
||||
func TestDeleteEntryGovernanceBypass(t *testing.T) {
|
||||
future := time.Now().Add(time.Hour)
|
||||
|
||||
t.Run("governance locked deletes with bypass", func(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
entry := &Entry{FullPath: "/o", Attr: Attr{Mode: 0644}, Extended: retentionEntry(s3_constants.RetentionModeGovernance, future)}
|
||||
require.NoError(t, f.CreateEntry(context.Background(), entry, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.DeleteEntryMetaAndData(WithBypassGovernanceRetention(context.Background()), entry.FullPath, false, false, true, false, nil, 0))
|
||||
require.Nil(t, store.getEntry("/o"))
|
||||
})
|
||||
|
||||
t.Run("compliance still refuses with bypass", func(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
entry := &Entry{FullPath: "/o", Attr: Attr{Mode: 0644}, Extended: retentionEntry(s3_constants.RetentionModeCompliance, future)}
|
||||
require.NoError(t, f.CreateEntry(context.Background(), entry, nil, false, false, nil, true, 255))
|
||||
require.ErrorIs(t, f.DeleteEntryMetaAndData(WithBypassGovernanceRetention(context.Background()), entry.FullPath, false, false, true, false, nil, 0), ErrEntryLocked)
|
||||
require.NotNil(t, store.getEntry("/o"))
|
||||
})
|
||||
}
|
||||
|
||||
// A delete replayed from a peer cluster applies as sent: the origin already
|
||||
// enforced retention before shipping the event.
|
||||
func TestDeleteEntryClusterReplaySkipsLockCheck(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
ctx := context.Background()
|
||||
|
||||
entry := &Entry{
|
||||
FullPath: "/locked",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("ON")},
|
||||
}
|
||||
require.NoError(t, f.CreateEntry(ctx, entry, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.DeleteEntryMetaAndData(ctx, entry.FullPath, false, false, true, true, nil, 0))
|
||||
require.Nil(t, store.getEntry("/locked"))
|
||||
}
|
||||
|
||||
type bucketDropStore struct {
|
||||
*stubFilerStore
|
||||
}
|
||||
|
||||
func (s *bucketDropStore) OnBucketCreation(string) {}
|
||||
func (s *bucketDropStore) OnBucketDeletion(string) {}
|
||||
func (s *bucketDropStore) CanDropWholeBucket() bool { return true }
|
||||
|
||||
// A lock-enabled bucket is walked rather than dropped whole, so its locked
|
||||
// objects still refuse the delete on a store that could drop it blindly.
|
||||
func TestDeleteBucketOnDropCapableStoreRefusesLockedObject(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
f.DirBucketsPath = "/buckets"
|
||||
f.Store = NewFilerStoreWrapper(&bucketDropStore{store})
|
||||
ctx := context.Background()
|
||||
|
||||
bucket := &Entry{
|
||||
FullPath: "/buckets/b",
|
||||
Attr: Attr{Mode: os.ModeDir | 0755},
|
||||
Extended: map[string][]byte{s3_constants.ExtObjectLockEnabledKey: []byte(s3_constants.ObjectLockEnabled)},
|
||||
}
|
||||
require.NoError(t, f.CreateEntry(ctx, bucket, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{
|
||||
FullPath: "/buckets/b/locked.bin",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: retentionEntry(s3_constants.RetentionModeCompliance, time.Now().Add(time.Hour)),
|
||||
}, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, "/buckets/b", true, false, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
require.NotNil(t, store.getEntry("/buckets/b/locked.bin"), "a drop-whole-bucket store must not swallow the locked object")
|
||||
}
|
||||
|
||||
// A bucket without the lock-enabled attribute can still carry entries under
|
||||
// retention, so the drop-whole-bucket path must not skip the lock walk.
|
||||
func TestDeleteUnmarkedBucketOnDropCapableStoreRefusesLockedObject(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
f.DirBucketsPath = "/buckets"
|
||||
f.Store = NewFilerStoreWrapper(&bucketDropStore{store})
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/buckets/b", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{
|
||||
FullPath: "/buckets/b/held.bin",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("ON")},
|
||||
}, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, "/buckets/b", true, true, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
require.NotNil(t, store.getEntry("/buckets/b/held.bin"), "an unmarked bucket drop must not swallow the locked object")
|
||||
}
|
||||
|
||||
// A non-recursive delete of an unmarked bucket never lists the children the
|
||||
// store drops, so the sweep itself must check them for locks first.
|
||||
func TestDeleteUnmarkedBucketNonRecursiveRefusesLockedObject(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
f.DirBucketsPath = "/buckets"
|
||||
f.Store = NewFilerStoreWrapper(&bucketDropStore{store})
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/buckets/b", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{
|
||||
FullPath: "/buckets/b/held.bin",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("ON")},
|
||||
}, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, "/buckets/b", false, true, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
require.NotNil(t, store.getEntry("/buckets/b/held.bin"), "a non-recursive unmarked bucket drop must not swallow the locked object")
|
||||
}
|
||||
|
||||
// A recursive delete rooted at the buckets dir reaches each bucket only
|
||||
// mid-walk, so the pre-pass has to know the subtree holds buckets whose
|
||||
// children the store would drop unseen.
|
||||
func TestDeleteBucketsRootRecursiveRefusesLockedObject(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
f.DirBucketsPath = "/buckets"
|
||||
f.Store = NewFilerStoreWrapper(&bucketDropStore{store})
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/buckets", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{FullPath: "/buckets/b", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.CreateEntry(ctx, &Entry{
|
||||
FullPath: "/buckets/b/held.bin",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("ON")},
|
||||
}, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, "/buckets", true, true, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
require.NotNil(t, store.getEntry("/buckets/b/held.bin"), "an unseen bucket drop must not swallow the locked object")
|
||||
}
|
||||
|
||||
// An expired retention no longer locks: the delete proceeds normally.
|
||||
func TestDeleteEntryAllowsExpiredRetention(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
ctx := context.Background()
|
||||
|
||||
entry := &Entry{
|
||||
FullPath: "/old",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: retentionEntry(s3_constants.RetentionModeCompliance, time.Now().Add(-time.Hour)),
|
||||
}
|
||||
require.NoError(t, f.CreateEntry(ctx, entry, nil, false, false, nil, true, 255))
|
||||
require.NoError(t, f.DeleteEntryMetaAndData(ctx, entry.FullPath, false, false, true, false, nil, 0))
|
||||
require.Nil(t, store.getEntry("/old"))
|
||||
}
|
||||
|
||||
// Retention and legal hold stamped on a multipart upload directory are
|
||||
// bookkeeping for the finished object, not a lock on the staging entry:
|
||||
// finalize, abort, and s3.clean.uploads all remove it. The gateway's
|
||||
// bucket-lock scan skips .uploads for the same reason.
|
||||
func TestDeleteEntryAllowsLockedMultipartStaging(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
f.DirBucketsPath = "/buckets"
|
||||
ctx := context.Background()
|
||||
future := time.Now().Add(time.Hour)
|
||||
|
||||
upload := &Entry{
|
||||
FullPath: "/buckets/b/.uploads/upload-id",
|
||||
Attr: Attr{Mode: os.ModeDir | 0755},
|
||||
Extended: retentionEntry(s3_constants.RetentionModeCompliance, future),
|
||||
}
|
||||
require.NoError(t, f.CreateEntry(ctx, upload, nil, false, false, nil, true, 255))
|
||||
part := &Entry{
|
||||
FullPath: "/buckets/b/.uploads/upload-id/0001_part",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte("ON")},
|
||||
}
|
||||
require.NoError(t, f.CreateEntry(ctx, part, nil, false, false, nil, true, 255))
|
||||
|
||||
require.NoError(t, f.DeleteEntryMetaAndData(ctx, upload.FullPath, true, false, true, false, nil, 0))
|
||||
require.Nil(t, store.getEntry(string(upload.FullPath)))
|
||||
require.Nil(t, store.getEntry(string(part.FullPath)))
|
||||
}
|
||||
|
||||
// The .uploads carve-out stops at the bucket's first path segment: an object
|
||||
// key that nests the name deeper still holds real lock attributes.
|
||||
func TestDeleteEntryRefusesLockedObjectUnderNestedUploadsName(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
f.DirBucketsPath = "/buckets"
|
||||
ctx := context.Background()
|
||||
|
||||
entry := &Entry{
|
||||
FullPath: "/buckets/b/dir/.uploads/x",
|
||||
Attr: Attr{Mode: 0644},
|
||||
Extended: retentionEntry(s3_constants.RetentionModeCompliance, time.Now().Add(time.Hour)),
|
||||
}
|
||||
require.NoError(t, f.CreateEntry(ctx, entry, nil, false, false, nil, true, 255))
|
||||
|
||||
err := f.DeleteEntryMetaAndData(ctx, entry.FullPath, false, false, true, false, nil, 0)
|
||||
require.ErrorIs(t, err, ErrEntryLocked)
|
||||
require.NotNil(t, store.getEntry(string(entry.FullPath)))
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const inodeIndexKeyPrefix = "filer.inode.path."
|
||||
const InodeIndexInitialGeneration uint64 = 1
|
||||
|
||||
// inodeRowLocks serializes the read-modify-write of one inode's index row so
|
||||
// concurrent writers (hard links share an inode) cannot overwrite each other.
|
||||
var inodeRowLocks [256]sync.Mutex
|
||||
|
||||
func inodeRowLock(inode uint64) *sync.Mutex {
|
||||
return &inodeRowLocks[inode%uint64(len(inodeRowLocks))]
|
||||
}
|
||||
|
||||
type inodeIndexEntry struct {
|
||||
path util.FullPath
|
||||
inode uint64
|
||||
}
|
||||
|
||||
// InodeIndexRecord is the inode→path reverse-lookup row consumed by the NFS
|
||||
// gateway to resolve filehandles. Rows are maintained only for paths covered
|
||||
// by an inode_index rule in filer.conf (see shell nfs.enable); everywhere else
|
||||
// the filer writes nothing.
|
||||
type InodeIndexRecord struct {
|
||||
Generation uint64 `json:"generation,omitempty"`
|
||||
Paths []string `json:"paths,omitempty"`
|
||||
}
|
||||
|
||||
func InodeIndexKey(inode uint64) []byte {
|
||||
key := make([]byte, len(inodeIndexKeyPrefix)+8)
|
||||
copy(key, inodeIndexKeyPrefix)
|
||||
binary.BigEndian.PutUint64(key[len(inodeIndexKeyPrefix):], inode)
|
||||
return key
|
||||
}
|
||||
|
||||
func DecodeInodeIndexRecord(value []byte) (*InodeIndexRecord, error) {
|
||||
if len(value) == 0 {
|
||||
return &InodeIndexRecord{}, nil
|
||||
}
|
||||
|
||||
// The first foundation slice stored the current path as raw bytes. Keep that
|
||||
// format readable so existing records are transparently upgraded on write.
|
||||
if value[0] != '{' {
|
||||
record := &InodeIndexRecord{Generation: InodeIndexInitialGeneration}
|
||||
record.AddPath(util.FullPath(value))
|
||||
return record, nil
|
||||
}
|
||||
|
||||
record := &InodeIndexRecord{}
|
||||
if err := json.Unmarshal(value, record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
record.normalize()
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (record *InodeIndexRecord) Encode() ([]byte, error) {
|
||||
record.normalize()
|
||||
return json.Marshal(record)
|
||||
}
|
||||
|
||||
func (record *InodeIndexRecord) normalize() {
|
||||
if len(record.Paths) == 0 {
|
||||
return
|
||||
}
|
||||
if record.Generation == 0 {
|
||||
record.Generation = InodeIndexInitialGeneration
|
||||
}
|
||||
|
||||
sanitized := make([]string, 0, len(record.Paths))
|
||||
for _, path := range record.Paths {
|
||||
if path == "" {
|
||||
continue
|
||||
}
|
||||
sanitized = append(sanitized, path)
|
||||
}
|
||||
if len(sanitized) == 0 {
|
||||
record.Paths = nil
|
||||
return
|
||||
}
|
||||
|
||||
sort.Strings(sanitized)
|
||||
deduped := sanitized[:1]
|
||||
for _, path := range sanitized[1:] {
|
||||
if path == deduped[len(deduped)-1] {
|
||||
continue
|
||||
}
|
||||
deduped = append(deduped, path)
|
||||
}
|
||||
record.Paths = deduped
|
||||
}
|
||||
|
||||
func (record *InodeIndexRecord) AddPath(path util.FullPath) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
record.normalize()
|
||||
target := string(path)
|
||||
index := sort.SearchStrings(record.Paths, target)
|
||||
if index < len(record.Paths) && record.Paths[index] == target {
|
||||
return false
|
||||
}
|
||||
record.Paths = append(record.Paths, "")
|
||||
copy(record.Paths[index+1:], record.Paths[index:])
|
||||
record.Paths[index] = target
|
||||
return true
|
||||
}
|
||||
|
||||
func (record *InodeIndexRecord) RemovePath(path util.FullPath) bool {
|
||||
if len(record.Paths) == 0 || path == "" {
|
||||
return false
|
||||
}
|
||||
record.normalize()
|
||||
target := string(path)
|
||||
index := sort.SearchStrings(record.Paths, target)
|
||||
if index >= len(record.Paths) || record.Paths[index] != target {
|
||||
return false
|
||||
}
|
||||
record.Paths = append(record.Paths[:index], record.Paths[index+1:]...)
|
||||
if len(record.Paths) == 0 {
|
||||
record.Paths = nil
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (record *InodeIndexRecord) CanonicalPath() util.FullPath {
|
||||
record.normalize()
|
||||
if len(record.Paths) == 0 {
|
||||
return ""
|
||||
}
|
||||
return util.FullPath(record.Paths[0])
|
||||
}
|
||||
|
||||
func (record *InodeIndexRecord) FullPaths() []util.FullPath {
|
||||
record.normalize()
|
||||
if len(record.Paths) == 0 {
|
||||
return nil
|
||||
}
|
||||
paths := make([]util.FullPath, 0, len(record.Paths))
|
||||
for _, path := range record.Paths {
|
||||
paths = append(paths, util.FullPath(path))
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// inodeIndexInScope reports whether the entry at path gets an inode index row.
|
||||
// The index is opt-in per filer.conf inode_index location rules; with no
|
||||
// matching rule (the default) nothing is ever written.
|
||||
func (fsw *FilerStoreWrapper) inodeIndexInScope(path util.FullPath) bool {
|
||||
if fsw.filerConfFn == nil {
|
||||
return false
|
||||
}
|
||||
fc := fsw.filerConfFn()
|
||||
if fc == nil {
|
||||
return false
|
||||
}
|
||||
return fc.MatchInodeIndexRule(string(path))
|
||||
}
|
||||
|
||||
// inodeIndexUnder reports whether any entry inside dirPath may carry an inode
|
||||
// index row, so DeleteFolderChildren can skip the housekeeping walk entirely
|
||||
// when the subtree does not intersect any inode_index rule.
|
||||
func (fsw *FilerStoreWrapper) inodeIndexUnder(dirPath util.FullPath) bool {
|
||||
if fsw.filerConfFn == nil {
|
||||
return false
|
||||
}
|
||||
fc := fsw.filerConfFn()
|
||||
if fc == nil {
|
||||
return false
|
||||
}
|
||||
return fc.InodeIndexActiveUnder(string(dirPath))
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) lookupInodeIndex(ctx context.Context, inode uint64) (*InodeIndexRecord, error) {
|
||||
if inode == 0 {
|
||||
return nil, ErrKvNotFound
|
||||
}
|
||||
|
||||
value, err := fsw.KvGet(ctx, InodeIndexKey(inode))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return DecodeInodeIndexRecord(value)
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) storeInodeIndex(ctx context.Context, path util.FullPath, inode uint64) error {
|
||||
if inode == 0 || path == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
lock := inodeRowLock(inode)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
record, err := fsw.lookupInodeIndex(ctx, inode)
|
||||
if err != nil {
|
||||
if err != ErrKvNotFound {
|
||||
return err
|
||||
}
|
||||
record = &InodeIndexRecord{Generation: InodeIndexInitialGeneration}
|
||||
}
|
||||
if !record.AddPath(path) {
|
||||
return nil
|
||||
}
|
||||
|
||||
value, err := record.Encode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fsw.KvPut(ctx, InodeIndexKey(inode), value)
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) lookupInodePath(ctx context.Context, inode uint64) (util.FullPath, error) {
|
||||
record, err := fsw.lookupInodeIndex(ctx, inode)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
path := record.CanonicalPath()
|
||||
if path == "" {
|
||||
return "", ErrKvNotFound
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) lookupInodePaths(ctx context.Context, inode uint64) ([]util.FullPath, error) {
|
||||
record, err := fsw.lookupInodeIndex(ctx, inode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
paths := record.FullPaths()
|
||||
if len(paths) == 0 {
|
||||
return nil, ErrKvNotFound
|
||||
}
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) removePathFromInodeIndex(ctx context.Context, path util.FullPath, inode uint64) error {
|
||||
if inode == 0 || path == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
lock := inodeRowLock(inode)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
record, err := fsw.lookupInodeIndex(ctx, inode)
|
||||
if err != nil {
|
||||
if err == ErrKvNotFound {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !record.RemovePath(path) {
|
||||
return nil
|
||||
}
|
||||
if len(record.Paths) == 0 {
|
||||
return fsw.KvDelete(ctx, InodeIndexKey(inode))
|
||||
}
|
||||
|
||||
value, err := record.Encode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fsw.KvPut(ctx, InodeIndexKey(inode), value)
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) collectInodeIndexEntries(ctx context.Context, dirPath util.FullPath) ([]inodeIndexEntry, error) {
|
||||
if !fsw.inodeIndexUnder(dirPath) {
|
||||
return nil, nil
|
||||
}
|
||||
// Honor caller cancellation during the walk: a DeleteFolderChildren on a
|
||||
// pathological directory could otherwise loop indefinitely gathering
|
||||
// entries even after the client has given up, turning into a DoS vector.
|
||||
// If the walk is aborted, the caller treats the index cleanup as
|
||||
// best-effort and drops the partial result.
|
||||
var collected []inodeIndexEntry
|
||||
if err := fsw.collectInodeIndexEntriesRecursive(ctx, dirPath, &collected); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collected, nil
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) collectInodeIndexEntriesRecursive(ctx context.Context, dirPath util.FullPath, collected *[]inodeIndexEntry) error {
|
||||
actualStore := fsw.getActualStore(dirPath + "/")
|
||||
|
||||
lastFileName := ""
|
||||
includeStartFile := false
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
page := make([]*Entry, 0, PaginationSize)
|
||||
nextLastFileName, err := actualStore.ListDirectoryEntries(ctx, dirPath, lastFileName, includeStartFile, PaginationSize, func(entry *Entry) (bool, error) {
|
||||
page = append(page, entry)
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, entry := range page {
|
||||
if entry.Attr.Inode != 0 {
|
||||
*collected = append(*collected, inodeIndexEntry{path: entry.FullPath, inode: entry.Attr.Inode})
|
||||
}
|
||||
if entry.IsDirectory() {
|
||||
if err := fsw.collectInodeIndexEntriesRecursive(ctx, entry.FullPath, collected); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(page) < PaginationSize {
|
||||
return nil
|
||||
}
|
||||
lastFileName = nextLastFileName
|
||||
includeStartFile = false
|
||||
}
|
||||
}
|
||||
|
||||
// recordInodeIndexWrite updates the inode→path secondary index after the
|
||||
// primary store mutation has already succeeded. The index is best-effort: a
|
||||
// failure here must not surface as an operation error, because the caller
|
||||
// would then observe a failed create/update even though the entry was
|
||||
// persisted, and a retry cannot heal the index (DeleteEntry exits early once
|
||||
// the entry is gone). We log and let later writes rebuild the record.
|
||||
func (fsw *FilerStoreWrapper) recordInodeIndexWrite(ctx context.Context, op string, path util.FullPath, inode uint64) {
|
||||
if inode == 0 || path == "" || !fsw.inodeIndexInScope(path) {
|
||||
return
|
||||
}
|
||||
if err := fsw.storeInodeIndex(ctx, path, inode); err != nil {
|
||||
glog.WarningfCtx(ctx, "%s: update inode index for %s (inode %d): %v", op, path, inode, err)
|
||||
}
|
||||
}
|
||||
|
||||
// recordInodeIndexRemoval mirrors recordInodeIndexWrite for removals.
|
||||
func (fsw *FilerStoreWrapper) recordInodeIndexRemoval(ctx context.Context, op string, path util.FullPath, inode uint64) {
|
||||
if inode == 0 || path == "" || !fsw.inodeIndexInScope(path) {
|
||||
return
|
||||
}
|
||||
if err := fsw.removePathFromInodeIndex(ctx, path, inode); err != nil {
|
||||
glog.WarningfCtx(ctx, "%s: clear inode index for %s (inode %d): %v", op, path, inode, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func inodeIndexConf(prefixes ...string) *FilerConf {
|
||||
fc := NewFilerConf()
|
||||
for _, prefix := range prefixes {
|
||||
_ = fc.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: prefix, InodeIndex: true})
|
||||
}
|
||||
return fc
|
||||
}
|
||||
|
||||
func newInodeIndexWrapper(prefixes ...string) (*FilerStoreWrapper, *stubFilerStore) {
|
||||
store := newStubFilerStore()
|
||||
wrapper := NewFilerStoreWrapper(store)
|
||||
fc := inodeIndexConf(prefixes...)
|
||||
wrapper.filerConfFn = func() *FilerConf { return fc }
|
||||
return wrapper, store
|
||||
}
|
||||
|
||||
func countInodeIndexRows(store *stubFilerStore) int {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
count := 0
|
||||
for key := range store.kv {
|
||||
if strings.HasPrefix(key, inodeIndexKeyPrefix) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func TestFilerStoreWrapperMaintainsInodeIndexLifecycle(t *testing.T) {
|
||||
wrapper, _ := newInodeIndexWrapper("/")
|
||||
ctx := context.Background()
|
||||
|
||||
created := &Entry{
|
||||
FullPath: util.FullPath("/docs/report.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: 42,
|
||||
},
|
||||
}
|
||||
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, created))
|
||||
path, err := wrapper.lookupInodePath(ctx, created.Attr.Inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, created.FullPath, path)
|
||||
paths, err := wrapper.lookupInodePaths(ctx, created.Attr.Inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []util.FullPath{created.FullPath}, paths)
|
||||
record, err := wrapper.lookupInodeIndex(ctx, created.Attr.Inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, InodeIndexInitialGeneration, record.Generation)
|
||||
|
||||
updated := &Entry{
|
||||
FullPath: util.FullPath("/docs/report.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o600,
|
||||
Inode: 42,
|
||||
},
|
||||
}
|
||||
require.NoError(t, wrapper.UpdateEntry(ctx, updated))
|
||||
path, err = wrapper.lookupInodePath(ctx, updated.Attr.Inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, updated.FullPath, path)
|
||||
|
||||
require.NoError(t, wrapper.DeleteEntry(ctx, created.FullPath))
|
||||
_, err = wrapper.lookupInodePath(ctx, created.Attr.Inode)
|
||||
require.ErrorIs(t, err, ErrKvNotFound)
|
||||
}
|
||||
|
||||
func TestFilerStoreWrapperMaintainsMultiplePathsPerInode(t *testing.T) {
|
||||
wrapper, _ := newInodeIndexWrapper("/")
|
||||
ctx := context.Background()
|
||||
inode := uint64(88)
|
||||
hardLinkId := NewHardLinkId()
|
||||
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/links/b.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: inode,
|
||||
},
|
||||
HardLinkId: hardLinkId,
|
||||
HardLinkCounter: 2,
|
||||
}))
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/links/a.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: inode,
|
||||
},
|
||||
HardLinkId: hardLinkId,
|
||||
HardLinkCounter: 2,
|
||||
}))
|
||||
|
||||
paths, err := wrapper.lookupInodePaths(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []util.FullPath{"/links/a.txt", "/links/b.txt"}, paths)
|
||||
record, err := wrapper.lookupInodeIndex(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, InodeIndexInitialGeneration, record.Generation)
|
||||
|
||||
path, err := wrapper.lookupInodePath(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, util.FullPath("/links/a.txt"), path)
|
||||
|
||||
require.NoError(t, wrapper.DeleteEntry(ctx, util.FullPath("/links/a.txt")))
|
||||
|
||||
paths, err = wrapper.lookupInodePaths(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []util.FullPath{"/links/b.txt"}, paths)
|
||||
|
||||
path, err = wrapper.lookupInodePath(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, util.FullPath("/links/b.txt"), path)
|
||||
}
|
||||
|
||||
func TestFilerStoreWrapperUpgradesLegacySinglePathInodeIndexRecords(t *testing.T) {
|
||||
wrapper := NewFilerStoreWrapper(newStubFilerStore())
|
||||
ctx := context.Background()
|
||||
inode := uint64(91)
|
||||
|
||||
require.NoError(t, wrapper.KvPut(ctx, InodeIndexKey(inode), []byte("/legacy/path.txt")))
|
||||
|
||||
path, err := wrapper.lookupInodePath(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, util.FullPath("/legacy/path.txt"), path)
|
||||
|
||||
paths, err := wrapper.lookupInodePaths(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []util.FullPath{"/legacy/path.txt"}, paths)
|
||||
|
||||
require.NoError(t, wrapper.storeInodeIndex(ctx, util.FullPath("/legacy/second.txt"), inode))
|
||||
|
||||
paths, err = wrapper.lookupInodePaths(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []util.FullPath{"/legacy/path.txt", "/legacy/second.txt"}, paths)
|
||||
|
||||
value, err := wrapper.KvGet(ctx, InodeIndexKey(inode))
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{"generation":1,"paths":["/legacy/path.txt","/legacy/second.txt"]}`, string(value))
|
||||
}
|
||||
|
||||
func TestFilerStoreWrapperKeepsInodeIndexWhenDeleteArrivesAfterRenameInsert(t *testing.T) {
|
||||
wrapper, _ := newInodeIndexWrapper("/")
|
||||
ctx := context.Background()
|
||||
inode := uint64(77)
|
||||
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/old/name.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: inode,
|
||||
},
|
||||
}))
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/new/name.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: inode,
|
||||
},
|
||||
}))
|
||||
require.NoError(t, wrapper.DeleteEntry(ctx, util.FullPath("/old/name.txt")))
|
||||
|
||||
path, err := wrapper.lookupInodePath(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, util.FullPath("/new/name.txt"), path)
|
||||
|
||||
paths, err := wrapper.lookupInodePaths(ctx, inode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []util.FullPath{"/new/name.txt"}, paths)
|
||||
}
|
||||
|
||||
func TestInodeIndexDisabledWritesNothing(t *testing.T) {
|
||||
// No filer.conf wired at all, and a conf with no inode_index rules: both
|
||||
// must leave the KV store free of index rows.
|
||||
t.Run("no conf", func(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
runInodeIndexDisabledScenario(t, NewFilerStoreWrapper(store), store)
|
||||
})
|
||||
t.Run("conf without rules", func(t *testing.T) {
|
||||
wrapper, store := newInodeIndexWrapper()
|
||||
runInodeIndexDisabledScenario(t, wrapper, store)
|
||||
})
|
||||
}
|
||||
|
||||
func runInodeIndexDisabledScenario(t *testing.T, wrapper *FilerStoreWrapper, store *stubFilerStore) {
|
||||
ctx := context.Background()
|
||||
entry := &Entry{
|
||||
FullPath: util.FullPath("/docs/report.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: 42,
|
||||
},
|
||||
}
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, entry))
|
||||
require.NoError(t, wrapper.UpdateEntry(ctx, entry))
|
||||
assert.Zero(t, countInodeIndexRows(store))
|
||||
require.NoError(t, wrapper.DeleteEntry(ctx, entry.FullPath))
|
||||
assert.Zero(t, countInodeIndexRows(store))
|
||||
}
|
||||
|
||||
func TestInodeIndexScopedToConfiguredPrefixes(t *testing.T) {
|
||||
wrapper, store := newInodeIndexWrapper("/exports")
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/exports/docs/in.txt"),
|
||||
Attr: Attr{Mode: 0o644, Inode: 1001},
|
||||
}))
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/other/out.txt"),
|
||||
Attr: Attr{Mode: 0o644, Inode: 1002},
|
||||
}))
|
||||
|
||||
assert.Equal(t, 1, countInodeIndexRows(store))
|
||||
path, err := wrapper.lookupInodePath(ctx, 1001)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, util.FullPath("/exports/docs/in.txt"), path)
|
||||
_, err = wrapper.lookupInodePath(ctx, 1002)
|
||||
require.ErrorIs(t, err, ErrKvNotFound)
|
||||
|
||||
require.NoError(t, wrapper.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/exports/docs"),
|
||||
Attr: Attr{Mode: os.ModeDir | 0o755, Inode: 1000},
|
||||
}))
|
||||
require.NoError(t, wrapper.DeleteFolderChildren(ctx, util.FullPath("/exports")))
|
||||
_, err = wrapper.lookupInodePath(ctx, 1001)
|
||||
require.ErrorIs(t, err, ErrKvNotFound)
|
||||
}
|
||||
|
||||
func TestRecursiveDeleteRemovesDescendantInodeIndexes(t *testing.T) {
|
||||
f, _ := newTestFilerWithStubStore()
|
||||
fc := inodeIndexConf("/tree")
|
||||
f.Store.(*FilerStoreWrapper).filerConfFn = func() *FilerConf { return fc }
|
||||
ctx := context.Background()
|
||||
|
||||
entries := []*Entry{
|
||||
{
|
||||
FullPath: util.FullPath("/tree"),
|
||||
Attr: Attr{
|
||||
Mode: os.ModeDir | 0o755,
|
||||
Inode: 100,
|
||||
},
|
||||
},
|
||||
{
|
||||
FullPath: util.FullPath("/tree/file.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: 101,
|
||||
},
|
||||
},
|
||||
{
|
||||
FullPath: util.FullPath("/tree/subdir"),
|
||||
Attr: Attr{
|
||||
Mode: os.ModeDir | 0o755,
|
||||
Inode: 102,
|
||||
},
|
||||
},
|
||||
{
|
||||
FullPath: util.FullPath("/tree/subdir/nested.txt"),
|
||||
Attr: Attr{
|
||||
Mode: 0o644,
|
||||
Inode: 103,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
require.NoError(t, f.Store.InsertEntry(ctx, entry))
|
||||
}
|
||||
|
||||
require.NoError(t, f.DeleteEntryMetaAndData(ctx, util.FullPath("/tree"), true, false, false, false, nil, 0))
|
||||
|
||||
for _, inode := range []uint64{100, 101, 102, 103} {
|
||||
_, err := f.Store.(*FilerStoreWrapper).lookupInodePath(ctx, inode)
|
||||
require.ErrorIs(t, err, ErrKvNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInodeIndexActiveUnder(t *testing.T) {
|
||||
fc := inodeIndexConf("/exports")
|
||||
assert.True(t, fc.InodeIndexActiveUnder("/"))
|
||||
assert.True(t, fc.InodeIndexActiveUnder("/exports"))
|
||||
assert.True(t, fc.InodeIndexActiveUnder("/exports/sub"))
|
||||
assert.False(t, fc.InodeIndexActiveUnder("/other"))
|
||||
assert.False(t, fc.InodeIndexActiveUnder("/exp"))
|
||||
assert.False(t, fc.InodeIndexActiveUnder("/export"))
|
||||
|
||||
assert.False(t, NewFilerConf().InodeIndexActiveUnder("/"))
|
||||
}
|
||||
|
||||
func TestMatchInodeIndexRule(t *testing.T) {
|
||||
fc := inodeIndexConf("/exports")
|
||||
assert.True(t, fc.MatchInodeIndexRule("/exports"))
|
||||
assert.True(t, fc.MatchInodeIndexRule("/exports/sub/file"))
|
||||
assert.False(t, fc.MatchInodeIndexRule("/exports2"))
|
||||
assert.False(t, fc.MatchInodeIndexRule("/exports_old/x"))
|
||||
assert.False(t, fc.MatchInodeIndexRule("/exp"))
|
||||
assert.False(t, fc.MatchInodeIndexRule("/other"))
|
||||
|
||||
assert.True(t, inodeIndexConf("/").MatchInodeIndexRule("/anything"))
|
||||
assert.False(t, NewFilerConf().MatchInodeIndexRule("/exports"))
|
||||
}
|
||||
@@ -39,7 +39,8 @@ type FilerStoreWrapper struct {
|
||||
defaultStore FilerStore
|
||||
pathToStore ptrie.Trie[string]
|
||||
storeIdToStore map[string]FilerStore
|
||||
hasPathSpecificStore bool // fast check to skip MatchPrefix when no path-specific stores
|
||||
hasPathSpecificStore bool // fast check to skip MatchPrefix when no path-specific stores
|
||||
filerConfFn func() *FilerConf // set by Filer.SetStore; nil disables the inode index
|
||||
}
|
||||
|
||||
func NewFilerStoreWrapper(store FilerStore) *FilerStoreWrapper {
|
||||
@@ -154,7 +155,11 @@ func (fsw *FilerStoreWrapper) InsertEntry(ctx context.Context, entry *Entry) err
|
||||
return err
|
||||
}
|
||||
|
||||
return actualStore.InsertEntry(ctx, entry)
|
||||
if err := actualStore.InsertEntry(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
fsw.recordInodeIndexWrite(ctx, "InsertEntry", entry.FullPath, entry.Attr.Inode)
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertEntryKnownAbsent skips the pre-insert FindEntry path when the caller has
|
||||
@@ -183,7 +188,11 @@ func (fsw *FilerStoreWrapper) InsertEntryKnownAbsent(ctx context.Context, entry
|
||||
}
|
||||
}
|
||||
|
||||
return actualStore.InsertEntry(ctx, entry)
|
||||
if err := actualStore.InsertEntry(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
fsw.recordInodeIndexWrite(ctx, "InsertEntryKnownAbsent", entry.FullPath, entry.Attr.Inode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) UpdateEntry(ctx context.Context, entry *Entry) error {
|
||||
@@ -211,7 +220,11 @@ func (fsw *FilerStoreWrapper) UpdateEntry(ctx context.Context, entry *Entry) err
|
||||
return err
|
||||
}
|
||||
|
||||
return actualStore.UpdateEntry(ctx, entry)
|
||||
if err := actualStore.UpdateEntry(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
fsw.recordInodeIndexWrite(ctx, "UpdateEntry", entry.FullPath, entry.Attr.Inode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeEntryMimeForStore(entry *Entry) {
|
||||
@@ -263,6 +276,8 @@ func (fsw *FilerStoreWrapper) DeleteEntry(ctx context.Context, fp util.FullPath)
|
||||
if findErr == filer_pb.ErrNotFound || existingEntry == nil {
|
||||
return nil
|
||||
}
|
||||
inode := existingEntry.Attr.Inode
|
||||
fullPath := existingEntry.FullPath
|
||||
if len(existingEntry.HardLinkId) != 0 {
|
||||
// remove hard link
|
||||
op := ctx.Value("OP")
|
||||
@@ -277,7 +292,11 @@ func (fsw *FilerStoreWrapper) DeleteEntry(ctx context.Context, fp util.FullPath)
|
||||
}
|
||||
}
|
||||
|
||||
return actualStore.DeleteEntry(ctx, fp)
|
||||
if err := actualStore.DeleteEntry(ctx, fp); err != nil {
|
||||
return err
|
||||
}
|
||||
fsw.recordInodeIndexRemoval(ctx, "DeleteEntry", fullPath, inode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) DeleteOneEntry(ctx context.Context, existingEntry *Entry) (err error) {
|
||||
@@ -285,6 +304,8 @@ func (fsw *FilerStoreWrapper) DeleteOneEntry(ctx context.Context, existingEntry
|
||||
return err
|
||||
}
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
fullPath := existingEntry.FullPath
|
||||
inode := existingEntry.Attr.Inode
|
||||
actualStore := fsw.getActualStore(existingEntry.FullPath)
|
||||
stats.FilerStoreCounter.WithLabelValues(actualStore.GetName(), "delete").Inc()
|
||||
start := time.Now()
|
||||
@@ -307,7 +328,11 @@ func (fsw *FilerStoreWrapper) DeleteOneEntry(ctx context.Context, existingEntry
|
||||
}
|
||||
}
|
||||
|
||||
return actualStore.DeleteEntry(ctx, existingEntry.FullPath)
|
||||
if err := actualStore.DeleteEntry(ctx, existingEntry.FullPath); err != nil {
|
||||
return err
|
||||
}
|
||||
fsw.recordInodeIndexRemoval(ctx, "DeleteOneEntry", fullPath, inode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) DeleteFolderChildren(ctx context.Context, fp util.FullPath) (err error) {
|
||||
@@ -322,7 +347,20 @@ func (fsw *FilerStoreWrapper) DeleteFolderChildren(ctx context.Context, fp util.
|
||||
stats.FilerStoreHistogram.WithLabelValues(actualStore.GetName(), "deleteFolderChildren").Observe(time.Since(start).Seconds())
|
||||
}()
|
||||
|
||||
return actualStore.DeleteFolderChildren(ctx, fp)
|
||||
collected, collectErr := fsw.collectInodeIndexEntries(ctx, fp)
|
||||
if collectErr != nil {
|
||||
// Index collection is best-effort: a failure here only prevents inode
|
||||
// index housekeeping, not the directory removal itself.
|
||||
glog.WarningfCtx(ctx, "collectInodeIndexEntries %s: %v; deleting folder children without index cleanup", fp, collectErr)
|
||||
collected = nil
|
||||
}
|
||||
if err := actualStore.DeleteFolderChildren(ctx, fp); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range collected {
|
||||
fsw.recordInodeIndexRemoval(ctx, "DeleteFolderChildren", entry.path, entry.inode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (string, error) {
|
||||
@@ -400,46 +438,39 @@ func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath u
|
||||
return actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, eachEntryFunc)
|
||||
}
|
||||
|
||||
var notPrefixed []*Entry
|
||||
lastFileName, err = actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, func(entry *Entry) (bool, error) {
|
||||
notPrefixed = append(notPrefixed, entry)
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// lastFileName must stay at the last name delivered to eachEntryFunc; the
|
||||
// raw scan cursor runs ahead over non-matching names and cannot be returned.
|
||||
count := int64(0)
|
||||
for count < limit && len(notPrefixed) > 0 {
|
||||
for _, entry := range notPrefixed {
|
||||
if strings.HasPrefix(entry.Name(), prefix) {
|
||||
count++
|
||||
res, resErr := eachEntryFunc(entry)
|
||||
|
||||
if resErr != nil {
|
||||
err = fmt.Errorf("failed to process eachEntryFunc for entry %q: %w", entry.Name(), resErr)
|
||||
return
|
||||
}
|
||||
|
||||
if !res {
|
||||
return
|
||||
}
|
||||
if count >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
scanName, scanInclusive := startFileName, includeStartFile
|
||||
for count < limit {
|
||||
var page []*Entry
|
||||
if scanName, err = actualStore.ListDirectoryEntries(ctx, dirPath, scanName, scanInclusive, limit, func(entry *Entry) (bool, error) {
|
||||
page = append(page, entry)
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
if count < limit && lastFileName < prefix {
|
||||
notPrefixed = notPrefixed[:0]
|
||||
lastFileName, err = actualStore.ListDirectoryEntries(ctx, dirPath, lastFileName, false, limit, func(entry *Entry) (bool, error) {
|
||||
notPrefixed = append(notPrefixed, entry)
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
scanInclusive = false
|
||||
if len(page) == 0 {
|
||||
return
|
||||
}
|
||||
for _, entry := range page {
|
||||
if !strings.HasPrefix(entry.Name(), prefix) {
|
||||
continue
|
||||
}
|
||||
count++
|
||||
res, resErr := eachEntryFunc(entry)
|
||||
if resErr != nil {
|
||||
err = fmt.Errorf("failed to process eachEntryFunc for entry %q: %w", entry.Name(), resErr)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
break
|
||||
lastFileName = entry.Name()
|
||||
if !res || count >= limit {
|
||||
return
|
||||
}
|
||||
}
|
||||
if scanName >= prefix && !strings.HasPrefix(scanName, prefix) {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
|
||||
@@ -205,3 +205,41 @@ func TestFilerStoreWrapperRollbackSucceedsWithCancelledContext(t *testing.T) {
|
||||
assert.NoError(t, wrapper.RollbackTransaction(cancelledCtx()))
|
||||
assert.NoError(t, wrapper.RollbackTransaction(expiredCtx()))
|
||||
}
|
||||
|
||||
type noPrefixListStore struct {
|
||||
*stubFilerStore
|
||||
}
|
||||
|
||||
func (s *noPrefixListStore) ListDirectoryPrefixedEntries(context.Context, util.FullPath, string, bool, int64, string, ListEachEntryFunc) (string, error) {
|
||||
return "", ErrUnsupportedListDirectoryPrefixed
|
||||
}
|
||||
|
||||
// The wrapper fallback must return the last delivered name as the cursor, not
|
||||
// the end of the raw page, and must keep paging while prefix matches can still
|
||||
// follow the raw cursor.
|
||||
func TestPrefixFilterEntriesCursorStaysAtLastDelivered(t *testing.T) {
|
||||
store := &noPrefixListStore{newStubFilerStore()}
|
||||
wrapper := NewFilerStoreWrapper(store)
|
||||
ctx := context.Background()
|
||||
for _, name := range []string{"a", "b1", "b2", "b3", "b4"} {
|
||||
require.NoError(t, store.InsertEntry(ctx, &Entry{FullPath: util.FullPath("/d/" + name)}))
|
||||
}
|
||||
|
||||
var delivered []string
|
||||
lastFileName, err := wrapper.ListDirectoryPrefixedEntries(ctx, util.FullPath("/d"), "", false, 2, "b", func(entry *Entry) (bool, error) {
|
||||
delivered = append(delivered, entry.Name())
|
||||
return true, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"b1", "b2"}, delivered)
|
||||
assert.Equal(t, "b2", lastFileName)
|
||||
|
||||
delivered = delivered[:0]
|
||||
lastFileName, err = wrapper.ListDirectoryPrefixedEntries(ctx, util.FullPath("/d"), lastFileName, false, 10, "b", func(entry *Entry) (bool, error) {
|
||||
delivered = append(delivered, entry.Name())
|
||||
return true, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"b3", "b4"}, delivered)
|
||||
assert.Equal(t, "b4", lastFileName)
|
||||
}
|
||||
@@ -156,7 +156,11 @@ func (store *HbaseStore) ListDirectoryEntries(ctx context.Context, dirPath util.
|
||||
func (store *HbaseStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
|
||||
family := map[string][]string{store.cfMetaDir: {COLUMN_NAME}}
|
||||
expectedPrefix := []byte(dirPath.Child(prefix))
|
||||
scan, err := hrpc.NewScanRange(ctx, store.table, expectedPrefix, nil, hrpc.Families(family))
|
||||
scanStart := expectedPrefix
|
||||
if resumeKey := []byte(dirPath.Child(startFileName)); bytes.Compare(resumeKey, scanStart) > 0 {
|
||||
scanStart = resumeKey
|
||||
}
|
||||
scan, err := hrpc.NewScanRange(ctx, store.table, scanStart, nil, hrpc.Families(family))
|
||||
if err != nil {
|
||||
return lastFileName, err
|
||||
}
|
||||
@@ -188,7 +192,7 @@ func (store *HbaseStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPa
|
||||
|
||||
value := cell.Value
|
||||
|
||||
if fileName == startFileName && !includeStartFile {
|
||||
if fileName < startFileName || (fileName == startFileName && !includeStartFile) {
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user