Compare commits

..
Author SHA1 Message Date
Chris Lu 1d5236af36 filer: exempt multipart upload staging from the entry lock check
createMultipartUpload stamps the object's requested retention and legal
hold on .uploads/<uploadId> so the completed object inherits them, but
the directory is bookkeeping, not a locked object. The new delete-time
check refused to remove it anyway: routedMultipartFinalize failed at the
upload-dir mutation, the just-committed version's own retention then
refused the rollback, and the orphaned locked version made every
subsequent bucket nuke answer BucketNotEmpty -- the cascading object_lock
setup errors in the Ceph suite. The gateway's bucket-lock scan already
skips .uploads for the same reason; the filer now mirrors it by exempting
anything at or under a bucket's first .uploads segment, which also covers
abort, s3.clean.uploads, and stale-part cleanup.
2026-10-23 22:19:16 -07:00
user.email 75967b355c filer: run the lock pre-pass for ancestors of the buckets dir
A recursive delete rooted at the buckets dir (or an ancestor of it when
nested) reaches each bucket only mid-walk, where an unmarked bucket on a
drop-capable store loses its children to an unchecked
DeleteFolderChildren. mayDescendantsHoldLocks now also answers true when
the subtree contains the buckets dir rather than sitting inside it, so
the pre-pass walks those buckets before the first drop can run.
2026-10-23 18:56:57 -07:00
chrislusf de470c66fb filer: run the lock pre-pass only where the subtree can hold locks
The recursive pre-pass listed the whole subtree on every directory
delete, doubling metadata reads for trees that cannot carry S3
retention or legal hold. The gateway only sets those attributes under
a lock-enabled bucket, so scope the second scan to that case plus the
store-level bucket drop that never lists its children. Entries the
walk does list are still refused on sight, wherever they sit; a
planted attribute outside the object-lock model now fails the delete
at its page instead of before the first side effect.
2026-10-23 18:48:26 -07:00
user.email 4f90865348 filer server: forward authorization metadata to the write owner
A routed ObjectTransaction/CreateEntry/UpdateEntry reached the owner
without the caller's authorization metadata, so the owner's admin-peer
check refused an authorized governance bypass and the delete stayed
locked. forwardToWriteOwner now hands each send a context carrying the
incoming authorization header.
2026-10-23 18:24:56 -07:00
user.email 15ac3500a3 filer: check descendants before an unlisted bucket drop
A non-recursive delete of an unmarked bucket on a drop-capable store
swept children nothing had listed, swallowing entries under legal hold
or retention. Walk the subtree for locks before the store drop, the
same check the recursive preflight already runs.
2026-10-23 18:24:56 -07:00
user.email 876e98ff15 filer: retract delete tombstones when a recursive delete aborts
A child error that propagates out of doBatchDeleteFolderMetaAndData left
the remote-deletion tombstones noted for the aborted subtree and this
directory behind, hiding still-existing remote children until the
tombstone expired. Drop both on the way out, like the preflight and
list-error paths already do.
2026-10-23 18:19:10 -07:00
user.emailandDevin 77cc6f3cbc filer server: read the guard key through a nil-safe accessor
FilerServers built without NewFilerServer leave filerGuard unset; a
bypass request there panicked on SigningKey instead of being refused.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 18:10:00 -07:00
user.email 9009825fcc s3api: keep the lock error chain through version-delete failures
Wrapping the filer's refusal with %v stripped its identity, so a lock
refusal raced past the gateway check surfaced as InternalError instead of
AccessDenied.
2026-10-23 18:06:17 -07:00
user.email d1dc0889f3 filer server: honor bypass_governance_retention only for admin peers
The flag was trusted blindly, so any gRPC client could delete
governance-retained entries a normal delete refuses. It now requires an
authenticated admin peer -- an mTLS client, a Bearer token signed with
jwt.filer_signing.key, or a local caller when no key is configured, the
same gate the IAM gRPC service uses. The S3 gateway attaches the admin
Bearer token when it forwards an authorized bypass.
2026-10-23 18:06:17 -07:00
user.email f4f3fa35f6 filer: check the whole subtree for locks before a recursive delete
A lock refusal used to surface only when the delete walk reached the
page holding the locked entry, so earlier descendants -- and any tombstones
noted for them -- were already gone. Walk the subtree for active locks
first and refuse before the delete emits a single side effect; this also
covers the drop-whole-bucket path, whose DeleteFolderChildren never lists
the children it removes, so an unmarked bucket no longer swallows entries
under retention or legal hold. A lock refusal is not a recursive error:
ignoreRecursiveError no longer waives ErrEntryLocked at any depth.
2026-10-23 18:06:17 -07:00
user.emailandDevin 1aa88de0ac filer server: report lock refusals as ENTRY_LOCKED on transactions
applyObjectMutation's refusal surfaced only inside the prefixed
resp.Error text, so a routed specific-version delete mapped a lock
refusal (e.g. legal hold stored in a letter case the WriteCondition
equality check misses but the mutation check catches) to InternalError
instead of AccessDenied. routedDeleteSpecificVersion and
routedDeleteNullVersion now map the structured code to AccessDenied;
the null version's fallback still covers anything else.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 18:03:50 -07:00
user.emailandDevin bdda9d8879 filer_pb: add ENTRY_LOCKED to FilerError
A mutation-level object-lock refusal on the transaction path needs a
classification the "mutation N:" error prefix does not strip, unlike the
leading wire marker remote clients read on plain delete failures.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 18:03:50 -07:00
user.emailandDevin 5fb41d946e filer: keep locked entries visible past their TTL
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 17:56:54 -07:00
user.emailandDevin 57ae6ffce0 filer: cover object-lock delete enforcement
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 17:54:16 -07:00
user.emailandDevin 4dd9cc289d s3api: assert governance bypass on authorized deletes, map filer lock refusals
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 17:49:21 -07:00
user.emailandDevin 6d733cb863 filer server: forward bypass_governance_retention into the delete context
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 17:49:21 -07:00
user.emailandDevin bb06389a8c filer: refuse deletes of entries under active object lock
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 17:47:57 -07:00
user.emailandDevin c701d57535 filer_pb: add bypass_governance_retention to delete mutations
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-23 17:47:04 -07:00
240 changed files with 3839 additions and 11185 deletions

No files matched your search

@@ -1,11 +0,0 @@
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"
@@ -1,89 +0,0 @@
#!/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())
@@ -1,137 +0,0 @@
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,14 +23,8 @@ runs:
bin=$(command -v fusermount3 || true)
if [ -z "$bin" ]; then
# 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
echo "no fusermount3 in PATH" >&2
exit 1
fi
if can_mount "$bin"; then
ls -l "$bin"
-30
View File
@@ -1,30 +0,0 @@
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
-6
View File
@@ -25,12 +25,6 @@ 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
+2 -5
View File
@@ -170,13 +170,10 @@ 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:"
timeout 15 df -h || true
df -h
# Remove pre-installed tools
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
# Clean package managers
@@ -188,7 +185,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:"
timeout 15 df -h || true
df -h
- name: Configure variant
id: config
@@ -25,7 +25,7 @@ on:
rocksdb_version:
description: 'RocksDB git tag to use when variant=rocksdb'
required: false
default: 'v11.1.2'
default: 'v10.10.1'
permissions:
contents: read
@@ -180,10 +180,6 @@ 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
@@ -223,7 +219,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
timeout 15 df -h || true
df -h
- name: Docker meta
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
@@ -275,11 +271,8 @@ jobs:
file: ${{ matrix.dockerfile }}
platforms: ${{ matrix.platform }}
labels: ${{ steps.docker_meta.outputs.labels }}
# 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
# Flat single-platform manifest so imagetools create assembles cleanly.
provenance: false
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
@@ -289,7 +282,7 @@ jobs:
${{ matrix.build_args }}
BUILDKIT_INLINE_CACHE=1
BRANCH=${{ github.sha }}
${{ matrix.variant == 'rocksdb' && format('ROCKSDB_VERSION={0}', github.event.inputs.rocksdb_version || 'v11.1.2') || '' }}
${{ matrix.variant == 'rocksdb' && format('ROCKSDB_VERSION={0}', github.event.inputs.rocksdb_version || 'v10.10.1') || '' }}
- name: Export digest
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
@@ -315,8 +308,6 @@ jobs:
permissions:
contents: read
id-token: write
attestations: write
packages: write
strategy:
fail-fast: false
matrix:
@@ -424,45 +415,6 @@ 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
@@ -501,9 +453,7 @@ jobs:
scanners: vuln
vuln-type: os,library
severity: HIGH,CRITICAL
# Keep unfixed findings in the report so digest-pinning consumers see
# the complete picture, not just what a patch could resolve.
ignore-unfixed: false
ignore-unfixed: true
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. v11.1.2)'
description: 'RocksDB git tag or branch to build (e.g. v10.10.1)'
required: true
default: 'v11.1.2'
default: 'v10.10.1'
seaweedfs_ref:
description: 'SeaweedFS git tag, branch, or commit to build'
required: true
-3
View File
@@ -42,9 +42,6 @@ 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,9 +41,6 @@ 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,7 +60,6 @@ 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 \
+1 -8
View File
@@ -41,20 +41,13 @@ jobs:
cache: ${{ runner.environment == 'github-hosted' }}
- name: Start local Docker registry
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
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
- 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
+1 -4
View File
@@ -58,9 +58,6 @@ 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:
@@ -396,7 +393,7 @@ jobs:
echo "" >> reports/debug/system_info.txt
echo "Disk Space" >> reports/debug/system_info.txt
timeout 15 df -h >> reports/debug/system_info.txt || true
df -h >> reports/debug/system_info.txt
echo "" >> reports/debug/system_info.txt
echo "Memory Information" >> reports/debug/system_info.txt
+1 -4
View File
@@ -32,9 +32,6 @@ 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 +51,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Filer Group Tests ==="
# Run tests with automatic server management
+4 -17
View File
@@ -4,7 +4,6 @@ on:
pull_request:
paths:
- 'weed/s3api/**'
- 'weed/remote_storage/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/**'
@@ -36,9 +35,6 @@ 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:
@@ -58,7 +54,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Tests ==="
# Run tests with automatic server management
@@ -205,9 +201,6 @@ 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:
@@ -227,7 +220,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Tests ==="
# Run tests with automatic server management
@@ -346,9 +339,6 @@ 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:
@@ -368,7 +358,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Tests ==="
make test-with-server
@@ -408,9 +398,6 @@ 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:
@@ -430,7 +417,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Tests ==="
# Run tests with automatic server management
+1 -4
View File
@@ -91,9 +91,6 @@ 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:
@@ -114,7 +111,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting S3 IAM Integration Tests (${{ matrix.test-type }}) ==="
# Set WEED_BINARY to use the installed version
+1 -4
View File
@@ -37,9 +37,6 @@ 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,7 +57,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting S3 Keycloak Integration Tests ==="
# Set WEED_BINARY to use the installed version
+2 -8
View File
@@ -89,9 +89,6 @@ 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 +108,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting S3 Policy Variables Integration Tests ==="
@@ -202,9 +199,6 @@ 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:
@@ -224,7 +218,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting S3 Policy Enforcement Tests (${{ matrix.test-case }}) ==="
+1 -4
View File
@@ -27,9 +27,6 @@ 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,7 +57,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting S3 Spark Integration Tests ==="
go test -v -timeout 30m . 2>&1 | tee test-output.log || {
+1 -4
View File
@@ -46,9 +46,6 @@ 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:
@@ -68,7 +65,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting SSE Tests ==="
# Run tests with automatic server management
+16 -65
View File
@@ -30,9 +30,6 @@ 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:
@@ -56,8 +53,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
# A stale FUSE mount can hang or fail df; keep diagnostics best effort.
timeout 15 df -h || true
df -h
echo "=== Starting S3 Tables Tests ==="
# Run S3 Tables integration tests
@@ -95,9 +91,6 @@ 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:
@@ -122,7 +115,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Iceberg Catalog Tests ==="
# Run Iceberg catalog integration tests using Makefile (handles build)
@@ -160,9 +153,6 @@ 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:
@@ -196,7 +186,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Trino Iceberg Catalog Tests ==="
# Run Trino + Iceberg catalog integration tests
@@ -234,9 +224,6 @@ 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:
@@ -271,7 +258,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting Dremio Iceberg Catalog Tests ==="
@@ -311,9 +298,6 @@ 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:
@@ -348,7 +332,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting Doris Iceberg Catalog Tests ==="
@@ -398,9 +382,6 @@ 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:
@@ -437,7 +418,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting ClickHouse Iceberg Catalog Tests ==="
@@ -489,9 +470,6 @@ 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:
@@ -529,7 +507,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting OLake Iceberg Catalog Tests ==="
@@ -592,9 +570,6 @@ 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:
@@ -627,7 +602,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Polaris Tests ==="
go test -v -timeout 20m ./test/s3tables/polaris 2>&1 | tee test/s3tables/polaris/test-output.log || {
@@ -664,9 +639,6 @@ 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:
@@ -700,7 +672,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Spark Iceberg Catalog Tests ==="
# Run Spark + Iceberg catalog integration tests
@@ -738,9 +710,6 @@ 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:
@@ -775,7 +744,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting RisingWave Catalog Tests ==="
# Run RisingWave catalog integration tests
@@ -813,9 +782,6 @@ 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:
@@ -874,7 +840,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting STS Integration Tests ==="
# Run STS integration tests
@@ -912,9 +878,6 @@ 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:
@@ -938,7 +901,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting Lakekeeper Integration Tests ==="
# Run Lakekeeper integration tests
@@ -976,9 +939,6 @@ 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:
@@ -1013,7 +973,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting Unity Catalog Tests ==="
@@ -1053,9 +1013,6 @@ 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:
@@ -1089,7 +1046,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting LanceDB Namespace Tests ==="
@@ -1200,9 +1157,6 @@ 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:
@@ -1237,7 +1191,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting DuckDB Lance Tests ==="
@@ -1279,9 +1233,6 @@ 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:
@@ -1315,7 +1266,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
docker info
echo "=== Starting Spark Lance Namespace Tests ==="
+12 -12
View File
@@ -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
python3 -m pip install -r requirements.txt
python3 -m pip install tox
python3 -m pip install -e .
pip install -r requirements.txt
pip install tox
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
python3 -m pip install -r requirements.txt
python3 -m pip install tox
python3 -m pip install -e .
pip install -r requirements.txt
pip install tox
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
python3 -m pip install -r requirements.txt
python3 -m pip install tox
python3 -m pip install -e .
pip install -r requirements.txt
pip install tox
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
python3 -m pip install -r requirements.txt
python3 -m pip install tox
python3 -m pip install -e .
pip install -r requirements.txt
pip install tox
pip install -e .
- name: Run Ceph S3 tests with SQL store
timeout-minutes: 15
+1 -8
View File
@@ -43,20 +43,13 @@ jobs:
cache: ${{ runner.environment == 'github-hosted' }}
- name: Start local Docker registry
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
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
- 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
+1 -4
View File
@@ -31,9 +31,6 @@ 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 +50,7 @@ jobs:
echo "=== System Information ==="
uname -a
free -h
timeout 15 df -h || true
df -h
echo "=== Starting TUS Tests ==="
# Run tests with automatic server management
-1
View File
@@ -144,4 +144,3 @@ weed_bin
telemetry/server/telemetry-server
.aider*
/seaweed-volume/docs
__pycache__/
+1 -1
View File
@@ -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=v11.1.2
ARG ROCKSDB_VERSION=v10.10.1
ENV ROCKSDB_VERSION=${ROCKSDB_VERSION}
# build RocksDB
+1 -1
View File
@@ -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=v11.1.2
ARG ROCKSDB_VERSION=v10.10.1
ENV ROCKSDB_VERSION=${ROCKSDB_VERSION}
# build RocksDB
+1 -1
View File
@@ -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.4.0 // indirect
github.com/go-chi/chi/v5 v5.3.1 // 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
+2 -2
View File
@@ -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.4.0 h1:+ufzvFTGKyin26Or5DLrlIDq4ygIDBVcj7oVNeeaYFE=
github.com/go-chi/chi/v5 v5.4.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
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-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=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.50"
appVersion: "4.49"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.50.0
version: 4.49.0
@@ -170,6 +170,9 @@ spec:
{{- if .Values.filer.metricsIp }}
-metricsIp={{ .Values.filer.metricsIp }} \
{{- end }}
{{- if .Values.filer.redirectOnRead }}
-redirectOnRead \
{{- end }}
{{- if .Values.filer.disableHttp }}
-disableHttp \
{{- end }}
+3
View File
@@ -740,6 +740,9 @@ 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
+1094 -1034
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 55 KiB

+1 -2
View File
@@ -771,8 +771,7 @@ message FilerConf {
string replication = 3;
string ttl = 4;
string disk_type = 5;
// unset inherits from the enclosing path rule, set overrides it
optional bool fsync = 6;
bool fsync = 6;
uint32 volume_growth_count = 7;
bool read_only = 8;
string data_center = 9;
-2
View File
@@ -157,8 +157,6 @@ 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"
-30
View File
@@ -233,25 +233,6 @@ 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,
@@ -327,14 +308,6 @@ 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;
@@ -965,9 +938,6 @@ 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,
+2 -12
View File
@@ -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::{self, WriteQueue};
use seaweed_volume::server::write_queue::WriteQueue;
use seaweed_volume::storage::store::Store;
use seaweed_volume::storage::types::DiskType;
@@ -436,17 +436,7 @@ 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 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 wq = WriteQueue::new(state.clone(), 128);
let _ = state.write_queue.set(wq);
// Set initial metric gauges for concurrent limits and max volumes
-3
View File
@@ -393,9 +393,6 @@ 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,
+63 -187
View File
@@ -1519,78 +1519,41 @@ fn not_modified_response(
etag: &str,
last_modified_str: &Option<String>,
) -> Option<Response> {
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-Modified-Since first (Go order), then If-None-Match.
if n.last_modified > 0
&& let Some(ims_str) = headers
.get(header::IF_MODIFIED_SINCE)
.and_then(|v| v.to_str().ok())
&& let Some(ims_header) = headers.get(header::IF_MODIFIED_SINCE)
&& let Ok(ims_str) = ims_header.to_str()
{
// 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()
{
return Some(not_modified());
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);
}
}
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,
@@ -3039,62 +3002,50 @@ pub async fn post_handler(
let needle_etag = n.etag();
let needle_has_name = n.has_name();
// 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;
// Replicate to remote volume servers if this volume has replicas.
// Matches Go's GetWritableRemoteReplications: skip if copy_count == 1.
// No leader-known gate: when the lookup cannot run, the write must fail
// 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
// 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
.map_err(|e| format!("replication task failed: {}", e))
.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),
);
.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),
);
}
}
}
let resp = match write_result {
@@ -5693,80 +5644,6 @@ 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)]
@@ -7431,7 +7308,6 @@ mod tests {
.set(crate::server::write_queue::WriteQueue::new(
state.clone(),
128,
crate::server::write_queue::SyncBatchOption::default(),
))
.is_ok()
);
-3
View File
@@ -132,9 +132,6 @@ 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,
+12 -164
View File
@@ -56,27 +56,6 @@ 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 {
@@ -88,35 +67,23 @@ 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,
sync_batch: SyncBatchOption,
) -> Self {
pub fn new(state: Arc<VolumeServerState>, capacity: usize) -> 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)),
}
}
@@ -126,12 +93,6 @@ 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();
@@ -146,9 +107,6 @@ 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(),
);
@@ -233,9 +191,6 @@ 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 {
@@ -283,40 +238,14 @@ 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 {
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,
}
match self.rx.try_recv() {
Ok(req) => {
batch_bytes += req.needle.data.len();
batch.push(req);
}
Err(mpsc::error::TryRecvError::Disconnected) => break,
};
batch_bytes += req.needle.data.len();
batch.push(req);
Err(_) => break,
}
}
debug!("processing write batch of {} requests", batch.len());
@@ -451,7 +380,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, SyncBatchOption::default());
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
let needle = Needle {
id: 1.into(),
@@ -473,7 +402,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, SyncBatchOption::default());
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
let mut handles = Vec::new();
for i in 0..10u64 {
@@ -501,7 +430,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, SyncBatchOption::default());
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
// Submit MAX_BATCH_SIZE requests concurrently
let mut handles = Vec::new();
@@ -593,7 +522,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, SyncBatchOption::default());
let queue = WriteQueue::new(state, 1);
// Clone then drop the original -- the worker keeps running via its rx handle.
let queue2 = queue.clone();
@@ -736,7 +665,7 @@ mod tests {
.unwrap();
}
}
let queue = WriteQueue::new(state, MAX_BATCH_SIZE, SyncBatchOption::default());
let queue = WriteQueue::new(state, MAX_BATCH_SIZE);
let in_append = Arc::new(Barrier::new(2));
let release = Arc::new(Barrier::new(2));
@@ -805,85 +734,4 @@ 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));
}
}
+2 -2
View File
@@ -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::{SyncBatchOption, WriteQueue};
use seaweed_volume::server::write_queue::WriteQueue;
let (direct_state, _direct_tmp) = test_state();
let (queued_state, _queued_tmp) = test_state();
let wq = WriteQueue::new(queued_state.clone(), 128, SyncBatchOption::default());
let wq = WriteQueue::new(queued_state.clone(), 128);
let _ = queued_state.write_queue.set(wq);
let compressible = "seaweedfs ".repeat(200).into_bytes();
+2 -2
View File
@@ -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, 90*time.Second); err != nil {
if err := f.waitForService(f.miniProcess, f.filerAddr, 30*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(90 * time.Second); err != nil {
if err := f.waitForMount(30 * time.Second); err != nil {
f.dumpLog("mount")
return fmt.Errorf("FUSE mount not ready: %v", err)
}
+4 -4
View File
@@ -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 90); do \
@for i in $$(seq 1 30); 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 90 ]; then \
if [ $$i -eq 30 ]; 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 90); do \
@for i in $$(seq 1 30); 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 90 ]; then \
if [ $$i -eq 30 ]; 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"; \
+2 -2
View File
@@ -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 90); do \
@for i in $$(seq 1 30); 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/90)"; \
echo "Waiting for S3 service... ($$i/30)"; \
sleep 1; \
done
@sleep 2
+1 -1
View File
@@ -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 90); do \
@for i in $$(seq 1 30); do \
if echo | nc -z localhost $(S3_PORT); then \
echo "S3 server is ready!"; \
exit 0; \
+2 -2
View File
@@ -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 90); do \
@for i in $$(seq 1 30); 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 90 seconds"; \
echo "❌ Server failed to start within 30 seconds"; \
if [ -f weed-server.log ]; then \
cat weed-server.log; \
fi; \
+1 -1
View File
@@ -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 90); do \
@for i in $$(seq 1 30); do \
if curl -s http://localhost:$(S3_PORT) > /dev/null 2>&1; then \
echo "OK S3 API server is ready"; \
exit 0; \
-2
View File
@@ -42,8 +42,6 @@ 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,27 +99,6 @@ 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 ")
@@ -187,7 +166,6 @@ 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)})
+3 -3
View File
@@ -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 90); do \
@for i in $$(seq 1 30); 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 90); do \
@for i in $$(seq 1 30); 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 90); do \
@for i in $$(seq 1 30); do \
if curl -s http://127.0.0.1:$(S3_PORT) > /dev/null 2>&1; then \
echo "✅ S3 service is ready"; \
break; \
+3 -6
View File
@@ -94,7 +94,6 @@ 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 \
@@ -230,13 +229,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 -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
@$(WEED_BINARY) mini -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 -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
@$(WEED_BINARY) mini -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
@@ -280,7 +279,6 @@ 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 \
@@ -325,7 +323,6 @@ 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) \
@@ -334,7 +331,7 @@ start-server-simple: check-deps
echo $$! > weed-server.pid
@echo "Waiting for S3 server to be ready..."
@for i in $$(seq 1 90); do \
@for i in $$(seq 1 30); 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,9 +115,6 @@ 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,9 +351,6 @@ 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")
@@ -382,9 +379,6 @@ 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,9 +574,6 @@ 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") ||
-3
View File
@@ -218,9 +218,6 @@ 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",
+1 -6
View File
@@ -2,13 +2,11 @@ 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
@@ -60,9 +58,6 @@ 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,11 +871,6 @@ 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,9 +272,6 @@ 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,7 +194,6 @@ 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)
@@ -206,7 +205,6 @@ 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))
}
@@ -222,7 +220,6 @@ 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
@@ -234,26 +231,6 @@ 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,7 +466,6 @@ 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),
@@ -485,7 +484,7 @@ func waitForTrino(t *testing.T, containerName string, timeout time.Duration) {
deadline := time.Now().Add(timeout)
var lastOutput []byte
containerDead := false
retryCount := 0
for time.Now().Before(deadline) {
// Try system catalog query as a readiness check
cmd := exec.Command("docker", "exec", containerName,
@@ -496,51 +495,26 @@ func waitForTrino(t *testing.T, containerName string, timeout time.Duration) {
return
} else {
lastOutput = output
if trinoContainerExited(output) {
containerDead = true
outputStr := string(output)
if strings.Contains(outputStr, "No such container") ||
strings.Contains(outputStr, "is not running") {
break
}
retryCount++
}
time.Sleep(1 * time.Second)
}
// If we can't connect to system catalog, try to at least connect to Trino server
if output, err := exec.Command("docker", "exec", containerName, "trino", "--version").CombinedOutput(); err == nil {
cmd := exec.Command("docker", "exec", containerName, "trino", "--version")
if err := cmd.Run(); 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)
}
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()
t.Fatalf("Timed out waiting for Trino to be ready\nLast output:\n%s", string(lastOutput))
}
func runTrinoSQL(t *testing.T, containerName, sql string) string {
@@ -70,13 +70,6 @@ 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")
@@ -116,9 +109,6 @@ 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,9 +35,6 @@ 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
-36
View File
@@ -2,15 +2,12 @@ package testutil
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
@@ -23,39 +20,6 @@ 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 {
-39
View File
@@ -1,39 +0,0 @@
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
View File
@@ -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 90); do \
@for i in $$(seq 1 30); 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 90 ]; then \
echo "$(RED)Filer failed to start within 90 seconds$(NC)"; \
if [ $$i -eq 30 ]; then \
echo "$(RED)Filer failed to start within 30 seconds$(NC)"; \
$(MAKE) debug-logs; \
exit 1; \
fi; \
echo "Waiting for filer... ($$i/90)"; \
echo "Waiting for filer... ($$i/30)"; \
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.StatusOK {
t.Fatalf("mismatched If-None-Match overrides If-Modified-Since: expected 200, got %d", precedenceResp.StatusCode)
if precedenceResp.StatusCode != http.StatusNotModified {
t.Fatalf("conditional precedence expected 304, got %d", precedenceResp.StatusCode)
}
if string(precedenceBody) != string(payload) {
t.Fatalf("mismatched If-None-Match body mismatch: got %q want %q", string(precedenceBody), string(payload))
if len(precedenceBody) != 0 {
t.Fatalf("conditional precedence expected empty body, got %d bytes", len(precedenceBody))
}
invalidIMSReq := mustNewRequest(t, http.MethodGet, clusterHarness.VolumeAdminURL()+"/"+fid)
+6 -16
View File
@@ -102,15 +102,6 @@ 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
@@ -232,13 +223,12 @@ 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,
"free_slots_deadband": int64Value,
"fullness_ratio": doubleValue,
"quiet_for_seconds": int64Value,
"min_size_mb": int64Value,
"preferred_tags": stringListValue,
"replica_placement": stringValue,
"strict_placement": boolValue,
},
// workers read collection_filter from the admin values, not the worker values
adminKeys: map[string]func(v TomlConfig, key string) *plugin_pb.ConfigValue{
+13 -108
View File
@@ -42,7 +42,6 @@ type FilerBackupOptions struct {
timeAgo *time.Duration
retentionDays *int
initialSnapshot *bool
concurrency *int
}
var (
@@ -66,7 +65,6 @@ 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{
@@ -107,12 +105,10 @@ func runFilerBackup(cmd *Command, args []string) bool {
clientId := util.RandomInt32()
var clientEpoch int32
var resumeTsNs int64
for {
clientEpoch++
var err error
resumeTsNs, err = doFilerBackup(grpcDialOption, &filerBackupOptions, reExcludeFileName, excludeFileNames, excludePathPatterns, clientId, clientEpoch, resumeTsNs)
err := doFilerBackup(grpcDialOption, &filerBackupOptions, reExcludeFileName, excludeFileNames, excludePathPatterns, clientId, clientEpoch)
if err != nil {
glog.Errorf("backup from %s: %v", *filerBackupOptions.filer, err)
time.Sleep(1747 * time.Millisecond)
@@ -124,12 +120,12 @@ const (
BackupKeyPrefix = "backup."
)
func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOptions, reExcludeFileName *regexp.Regexp, excludeFileNames []*wildcard.WildcardMatcher, excludePathPatterns []*wildcard.WildcardMatcher, clientId int32, clientEpoch int32, resumeTsNs int64) (int64, error) {
func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOptions, reExcludeFileName *regexp.Regexp, excludeFileNames []*wildcard.WildcardMatcher, excludePathPatterns []*wildcard.WildcardMatcher, clientId int32, clientEpoch int32) error {
// find data sink
dataSink := findSink(util.GetViper())
if dataSink == nil {
return 0, fmt.Errorf("no data sink configured in replication.toml")
return fmt.Errorf("no data sink configured in replication.toml")
}
sourceFiler := pb.ServerAddress(*backupOption.filer)
@@ -143,20 +139,14 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
startFrom := time.Unix(0, 0)
sinkId, legacySinkId := backupCheckpointIds(sourcePath, dataSink)
runSnapshot := *backupOption.initialSnapshot && 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 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 {
return 0, fmt.Errorf("read backup offset: %w", err)
glog.V(0).Infof("starting from %v (offset read failed: %v)", startFrom, err)
} else if lastOffsetTsNs > 0 {
startFrom = time.Unix(0, lastOffsetTsNs)
glog.V(0).Infof("resuming from %v", startFrom)
@@ -176,11 +166,11 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
sourceFiler.ToGrpcAddress(),
sourcePath,
*backupOption.proxyByFiler); err != nil {
return resumeTsNs, fmt.Errorf("filersource initialization failed: %v", err)
return fmt.Errorf("filersource initialization failed: %v", err)
}
if err := repl_util.InitializeSSEForReplication(filerSource); err != nil {
return resumeTsNs, fmt.Errorf("SSE initialization failed: %v", err)
return fmt.Errorf("SSE initialization failed: %v", err)
}
dataSink.SetSourceFiler(filerSource)
@@ -191,14 +181,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 0, fmt.Errorf("initial snapshot: %w", err)
return 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 0, fmt.Errorf("persist initial snapshot offset: %w", err)
return fmt.Errorf("persist initial snapshot offset: %w", err)
}
startFrom = time.Unix(0, snapshotTsNs)
// walk once per process; retries resume from the persisted checkpoint
@@ -228,74 +218,9 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
processEventFn = genProcessFunction(sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.doDeleteFiles, debug)
}
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
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 dataSink.IsIncremental() && *filerBackupOptions.retentionDays > 0 {
@@ -331,29 +256,9 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
StartTsNs: startFrom.UnixNano(),
StopTsNs: 0,
EventErrorType: eventErrorType,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
},
Resubscribe: processor.ResubscribeCh(),
}
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
return pb.FollowMetadata(sourceFiler, grpcDialOption, metadataFollowOption, processEventFnWithOffset)
}
+1 -60
View File
@@ -3,14 +3,11 @@ 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"
)
@@ -37,35 +34,14 @@ 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, server)
filer_pb.RegisterSeaweedFilerServer(grpcServer, &kvFilerServer{kv: map[string][]byte{}})
go func() { _ = grpcServer.Serve(listener) }()
t.Cleanup(func() { grpcServer.Stop() })
grpcPort := listener.Addr().(*net.TCPAddr).Port
@@ -134,38 +110,3 @@ 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)
}
}
+2 -2
View File
@@ -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, resumeTsNsFor(processor))
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, offsetTsNs)
})
option.clientEpoch++
@@ -65,7 +65,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
StopTsNs: 0,
EventErrorType: pb.RetryForeverOnError,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
return processor.processedTsWatermark.Load()
},
Resubscribe: processor.ResubscribeCh(),
}
+56 -317
View File
@@ -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, resumeTsNsFor(processor))
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, offsetTsNs)
})
option.clientEpoch++
@@ -77,7 +77,7 @@ func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *sour
StopTsNs: 0,
EventErrorType: pb.RetryForeverOnError,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
return processor.processedTsWatermark.Load()
},
Resubscribe: processor.ResubscribeCh(),
}
@@ -140,24 +140,63 @@ 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 {
if filer_pb.IsCreate(resp) {
if isMultipartUploadFile(message.NewParentPath, message.NewEntry.Name) {
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)
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
}
resp, message = reshaped, reshaped.EventNotification
}
if filer_pb.IsCreate(resp) {
return processCreateEvent(option, filerSource, *option.storageClass, client, mountedDir, remoteStorageMountLocation, resp, mustSend, renameSrc)
// 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)
}
if filer_pb.IsDelete(resp) {
return processDeleteEvent(filerSource, client, mountedDir, remoteStorageMountLocation, resp)
@@ -171,136 +210,6 @@ 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
@@ -742,176 +651,6 @@ 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
+3 -355
View File
@@ -413,12 +413,10 @@ func TestIsMetadataOnlyUpdate(t *testing.T) {
}
// stubFilerClient serves one entry; nil means not found. A non-nil err fails
// every lookup instead. entries, when set, answers lookups by "dir/name"
// before entry is consulted.
// every lookup instead.
type stubFilerClient struct {
filer_pb.SeaweedFilerClient
entry *filer_pb.Entry
entries map[string]*filer_pb.Entry
err error
updateErr error
lookups int
@@ -426,14 +424,11 @@ type stubFilerClient struct {
updated *filer_pb.UpdateEntryRequest
}
func (c *stubFilerClient) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest, _ ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
func (c *stubFilerClient) LookupDirectoryEntry(context.Context, *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
}
@@ -2022,354 +2017,6 @@ 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
@@ -2439,3 +2086,4 @@ func TestRemoteSyncSkipsSystemFolder(t *testing.T) {
t.Fatalf("expected 0 remote deletes for system path, got %d deletes", len(remote.deletes))
}
}
+8 -69
View File
@@ -7,7 +7,6 @@ import (
"os"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
@@ -223,7 +222,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
if state == nil || state.processor == nil {
return
}
offsetTsNs := resumeTsNsFor(state.processor)
offsetTsNs := state.processor.processedTsWatermark.Load()
if offsetTsNs == 0 {
return
}
@@ -476,7 +475,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, resumeTsNsFor(processor))
return setOffset(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, offsetTsNs)
})
prefix := sourcePath
@@ -496,7 +495,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
StopTsNs: 0,
EventErrorType: pb.RetryForeverOnError,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
return processor.processedTsWatermark.Load()
},
Resubscribe: processor.ResubscribeCh(),
// While the source has only read activity it emits no metadata events, so
@@ -577,77 +576,16 @@ func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddres
return lastOffsetTsNs, err
}
// 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{}}
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 {
syncKey := []byte(signaturePrefix + "____")
util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
valueBuf := make([]byte, 8)
util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
// 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{
resp, err := client.KvPut(context.Background(), &filer_pb.KvPutRequest{
Key: syncKey,
Value: valueBuf,
})
@@ -662,6 +600,7 @@ 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 {
-50
View File
@@ -137,19 +137,6 @@ 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 —
@@ -212,21 +199,6 @@ 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.
@@ -234,18 +206,6 @@ 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 {
@@ -379,9 +339,6 @@ 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
}
@@ -397,10 +354,6 @@ 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}
@@ -472,9 +425,6 @@ 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
-160
View File
@@ -4,7 +4,6 @@ import (
"container/heap"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
@@ -554,61 +553,6 @@ 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
@@ -1129,107 +1073,3 @@ 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 -52
View File
@@ -1,10 +1,6 @@
package command
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/util"
)
import "testing"
// The offset key is a persistence contract: a changed form orphans saved
// checkpoints, so the historical forms must survive verbatim and the
@@ -78,50 +74,3 @@ 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)
}
}
+4 -2
View File
@@ -57,6 +57,7 @@ type MasterOptions struct {
fileSizeLimitMB *int
volumePreallocate *bool
maxParallelVacuumPerServer *int
maxWritableVolumes *int
vacuumIntervalSeconds *int
vacuumDeleteEmptyAfterSeconds *int
// pulseSeconds *int
@@ -94,7 +95,8 @@ 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; 0 for no limit (deprecated, use master.vacuum.max_parallel_per_server in master.toml)")
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.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")
@@ -477,6 +479,7 @@ 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,
@@ -488,6 +491,5 @@ func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOp
MetricsIntervalSec: *m.metricsIntervalSec,
TelemetryUrl: *m.telemetryUrl,
TelemetryEnabled: *m.telemetryEnabled,
SingleMaster: isSingleMasterMode(*m.peers),
}
}
+1
View File
@@ -47,6 +47,7 @@ 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")
+2 -4
View File
@@ -445,7 +445,8 @@ 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; 0 for no limit (deprecated, use master.vacuum.max_parallel_per_server in master.toml)")
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.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.")
@@ -516,9 +517,6 @@ 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()
}
-3
View File
@@ -66,9 +66,6 @@
# 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
-16
View File
@@ -4,13 +4,6 @@
# /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.
@@ -18,15 +11,6 @@ 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
-13
View File
@@ -81,16 +81,3 @@ 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"]
+2 -4
View File
@@ -97,7 +97,8 @@ 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; 0 for no limit (deprecated, use master.vacuum.max_parallel_per_server in master.toml)")
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.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.")
@@ -164,9 +165,6 @@ 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")
-23
View File
@@ -76,9 +76,6 @@ type VolumeServerOptions struct {
readBufferSizeMB *int
ldbTimeout *int64
allowUntrustedRemoteEndpoints *bool
fsyncMinBatchBytes *int64
fsyncMinBatchRequests *int
fsyncBatchWait *time.Duration
debug *bool
debugPort *int
diskIOProbe *bool
@@ -150,22 +147,6 @@ 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()
@@ -249,9 +230,6 @@ 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()
@@ -482,7 +460,6 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
*v.ldbTimeout,
*v.allowUntrustedRemoteEndpoints,
diskProbeConfig,
v.syncBatchOption(),
)
// starting grpc server
grpcS := v.startGrpcService(volumeServer)
+1 -1
View File
@@ -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 > prefix {
if startFileName != "" {
lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
}
+6 -4
View File
@@ -434,7 +434,7 @@ func SyncWrite(ctx context.Context) bool {
// syncWriteContext flags ctx when the storage rule on p asks for fsync, so the
// store write is held to the same durability as the data path.
func (f *Filer) syncWriteContext(ctx context.Context, p util.FullPath) context.Context {
if f.FilerConf != nil && f.FilerConf.MatchStorageRule(string(p)).GetFsync() {
if f.FilerConf != nil && f.FilerConf.MatchStorageRule(string(p)).Fsync {
return WithSyncWrite(ctx)
}
return ctx
@@ -772,8 +772,10 @@ 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.
if entry != nil && entry.TtlSec > 0 && !entry.IsDirectory() {
// 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()) {
if entry.IsExpireS3Enabled() {
if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() {
if delErr := f.doDeleteEntryMetaAndData(ctx, entry, true, false, nil); delErr != nil {
@@ -812,7 +814,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() {
if entry.TtlSec > 0 && !entry.IsDirectory() && !entryLockedForDelete(entry, false, time.Now()) {
if entry.IsExpireS3Enabled() {
if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() {
// Collect for deletion after iteration completes to avoid DB deadlock
+12 -21
View File
@@ -33,11 +33,10 @@ const (
)
// FilerConfVersion is stamped into every configuration this build writes.
// 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
// 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
type FilerConf struct {
rules ptrie.Trie[*filer_pb.FilerConf_PathConf]
@@ -127,12 +126,9 @@ 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 < 1 && location.Worm != nil && !*location.Worm {
if conf.Version < FilerConfVersion && 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
@@ -231,10 +227,7 @@ func ClonePathConf(src *filer_pb.FilerConf_PathConf) *filer_pb.FilerConf_PathCon
if src == nil {
return &filer_pb.FilerConf_PathConf{}
}
var fsync, worm *bool
if src.Fsync != nil {
fsync = proto.Bool(*src.Fsync)
}
var worm *bool
if src.Worm != nil {
worm = proto.Bool(*src.Worm)
}
@@ -244,7 +237,7 @@ func ClonePathConf(src *filer_pb.FilerConf_PathConf) *filer_pb.FilerConf_PathCon
Replication: src.Replication,
Ttl: src.Ttl,
DiskType: src.DiskType,
Fsync: fsync,
Fsync: src.Fsync,
VolumeGrowthCount: src.VolumeGrowthCount,
ReadOnly: src.ReadOnly,
MaxFileNameLength: src.MaxFileNameLength,
@@ -491,7 +484,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.Fsync == nil && !c.GetReadOnly() &&
return c.GetDiskType() == "" && !c.GetFsync() && !c.GetReadOnly() &&
c.GetDataCenter() == "" && c.GetRack() == "" && c.GetDataNode() == "" &&
c.GetMaxFileNameLength() == 0 && !c.GetDisableChunkDeletion() &&
c.Worm == nil && c.GetWormGracePeriodSeconds() == 0 && c.GetWormRetentionTimeSeconds() == 0
@@ -514,12 +507,7 @@ 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)
// 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)
}
a.Fsync = b.Fsync || a.Fsync
if b.VolumeGrowthCount > 0 {
a.VolumeGrowthCount = b.VolumeGrowthCount
}
@@ -531,6 +519,9 @@ 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)
+1 -68
View File
@@ -102,54 +102,6 @@ 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) {
@@ -167,23 +119,6 @@ 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.
@@ -195,7 +130,7 @@ func TestClonePathConf(t *testing.T) {
Replication: "001",
Ttl: "7d",
DiskType: "ssd",
Fsync: proto.Bool(true),
Fsync: true,
VolumeGrowthCount: 5,
ReadOnly: true,
MaxFileNameLength: 255,
@@ -254,11 +189,9 @@ 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")
}
+224 -5
View File
@@ -5,18 +5,21 @@ 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
@@ -25,6 +28,11 @@ 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.
@@ -32,6 +40,9 @@ 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)
}
@@ -45,6 +56,14 @@ 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
@@ -80,6 +99,147 @@ 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
@@ -131,6 +291,15 @@ 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)
}
@@ -143,6 +312,16 @@ 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:
@@ -154,7 +333,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) {
if errors.Is(err, ErrNonEmptyFolder) || errors.Is(err, ErrEntryLocked) {
return err
}
return fmt.Errorf("delete directory %s: %v", p, err)
@@ -164,6 +343,9 @@ 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)
}
@@ -208,7 +390,9 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
var chunksToDelete []*filer_pb.FileChunk
lastFileName := ""
includeLastFile := false
listedChildren := !isDeletingBucket || !f.Store.CanDropWholeBucket()
// 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)
if listedChildren {
for {
entries, _, err := f.ListDirectoryEntries(ctx, entry.FullPath, lastFileName, includeLastFile, PaginationSize, "", "", "")
@@ -225,10 +409,26 @@ 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) {
f.noteRemoteDeletion(sub.FullPath, sub.IsDirectory(), time.Now().UnixNano())
subTombstoneTs = time.Now().UnixNano()
f.noteRemoteDeletion(sub.FullPath, sub.IsDirectory(), subTombstoneTs)
}
if sub.IsDirectory() {
subIsDeletingBucket := f.IsBucket(sub)
@@ -242,7 +442,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
}
}
}
if err != nil && !ignoreRecursiveError {
if err != nil && (!ignoreRecursiveError || errors.Is(err, ErrEntryLocked)) {
break
}
f.NotifyUpdateEvent(ctx, deleteEventEntry(ctx, sub), nil, shouldDeleteChunks, isFromOtherCluster, nil)
@@ -258,7 +458,12 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
}
}
}
if err != nil && !ignoreRecursiveError {
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)
return err
}
}
@@ -274,6 +479,14 @@ 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)
}
@@ -289,6 +502,12 @@ 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
+329
View File
@@ -5,10 +5,12 @@ 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"
)
@@ -117,3 +119,330 @@ 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)))
}
+36 -29
View File
@@ -400,39 +400,46 @@ func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath u
return actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, eachEntryFunc)
}
// lastFileName must stay at the last name delivered to eachEntryFunc; the
// raw scan cursor runs ahead over non-matching names and cannot be returned.
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
}
count := int64(0)
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
}
scanInclusive = false
if len(page) == 0 {
return
}
for _, entry := range page {
if !strings.HasPrefix(entry.Name(), prefix) {
continue
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
}
}
count++
res, resErr := eachEntryFunc(entry)
if resErr != nil {
err = fmt.Errorf("failed to process eachEntryFunc for entry %q: %w", entry.Name(), resErr)
}
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 {
return
}
lastFileName = entry.Name()
if !res || count >= limit {
return
}
}
if scanName >= prefix && !strings.HasPrefix(scanName, prefix) {
return
} else {
break
}
}
return
-38
View File
@@ -205,41 +205,3 @@ 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)
}
+2 -6
View File
@@ -156,11 +156,7 @@ 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))
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))
scan, err := hrpc.NewScanRange(ctx, store.table, expectedPrefix, nil, hrpc.Families(family))
if err != nil {
return lastFileName, err
}
@@ -192,7 +188,7 @@ func (store *HbaseStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPa
value := cell.Value
if fileName < startFileName || (fileName == startFileName && !includeStartFile) {
if fileName == startFileName && !includeStartFile {
continue
}
+1 -1
View File
@@ -221,7 +221,7 @@ func (store *LevelDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dir
directoryPrefix := genDirectoryKeyPrefix(dirPath, prefix)
lastFileStart := directoryPrefix
if startFileName > prefix {
if startFileName != "" {
lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
}
-25
View File
@@ -110,28 +110,3 @@ func BenchmarkInsertEntry(b *testing.B) {
store.InsertEntry(ctx, entry)
}
}
func TestListDirectoryPrefixedEntries_StartBelowPrefix(t *testing.T) {
store := &LevelDBStore{}
store.initialize(t.TempDir())
defer store.Shutdown()
ctx := context.Background()
for _, name := range []string{"item-a", "item-a.versions", "item-b.versions"} {
if err := store.InsertEntry(ctx, &filer.Entry{FullPath: util.FullPath("/d/" + name)}); err != nil {
t.Fatalf("insert %s: %v", name, err)
}
}
var names []string
_, err := store.ListDirectoryPrefixedEntries(ctx, util.FullPath("/d"), "item", true, 100, "item-b", func(entry *filer.Entry) (bool, error) {
names = append(names, entry.Name())
return true, nil
})
if err != nil {
t.Fatalf("list: %v", err)
}
if len(names) != 1 || names[0] != "item-b.versions" {
t.Fatalf("want [item-b.versions], got %v", names)
}
}
Loaded 100 of 240 files, more files were not shown because too many files have changed in this diff. Show more