Compare commits

..
Author SHA1 Message Date
d9eaf85cd7 perf(lance): skip unused _versions lookups (#13371)
* lance: skip unused _versions lookups

Read _versions/ only for include_declared=false, check_declared
or a new-name register: listings now do one lookup per table
instead of two (about 45% faster at 100-500 tables).
A failed _versions lookup no longer hides a table that never needed it.

Adds visibility regression tests, lookup-count tests and a benchmark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance: read the deregistered marker through datasetState

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance: trim the dataset-state comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 23:44:47 -08:00
a4269d6b51 mount: export and import the in-memory state of a mount for a handover (#13370)
* pb: add mount_handover.proto, the state a mount hands to its successor

Messages for the in-memory state a new `weed mount` process needs to take
over a live FUSE connection. The stream is a small header followed by
length-delimited HandoverFrame messages, one record per frame, so a table of
millions of inodes is neither encoded nor decoded as a whole. Protobuf keeps
the state readable across builds: fields are only added, and a reader ignores
fields and frame bodies it does not know, so a newer build imports what an
older one exported. File entries reuse filer_pb.Entry.

Generated with protoc 33.4 and protoc-gen-go 1.36.6, as mount.pb.go is.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: export and import the in-memory state of a mount for a handover

ExportHandoverState / ImportHandoverState carry what a new weed mount process
needs to serve the kernel's existing node and handle ids: the inode table
(paths, hard-link names, lookup counts, which inodes are directories), open
file handles under their fh ids with entry, base entry, entry version and the
flags that change later operations, directory handles with the window of
entries the kernel is inside, held POSIX/flock locks and the routed (-dlm)
session id with its mirror, the mount signature, the sticky per-inode write
errors, atime/dir-mtime overlays, removed-directory entries, the -nfsExport
records, and the metadata subscription position. Nothing is carried that
cannot be: the export is refused, naming every cause, for dirty pages,
uploads or deferred flushes, an unpublished create, a handle busy under its
lock, a blocked lock waiter (never answered with EINTR, which the kernel
turns into a restart only for a caller with a signal pending), a background
create, or a filer token. The handle of an unlinked file crosses dirty, as its
entry exists only there.

Encoding: protobuf (weed/pb/mount_handover.proto), one length-delimited frame
per record behind a header with a format version, ending in a frame with the
CRC-32. Frames stream, so a million-inode table is neither encoded nor decoded
as a whole, and the importer builds the final maps directly. Import verifies
the checksum before it changes anything, refuses another mount root, cache
mode or a WFS that already holds state, and makes no filer call: a manifest
chunk is resolved lazily on the first read, as after a failed resolution. A
caller's *bufio.Reader is used as it is and left right behind the state, so
more can follow on the same connection.

Every structure documents next to its type what crosses, what is rebuilt and
what must be empty; a test fails when a field is added without a place in it.

Three hooks in existing code, none of which changes behaviour:

- MetaCache.SubscribedTsNs is the log position of the last subscribed event
  handled, applied or skipped as the mount's own. The subscription's start is
  its first position, so a mount that hands over before its first event still
  passes one on. WFS.handoverMetaTsNs, which only an import sets, is where
  StartBackgroundTasks starts the subscription instead of at the start time.
- WFS.asyncCreates and WFS.routedLockWaiters count the writeback Mknod create
  goroutines and the SETLKW calls polling a routed lock. Neither has a handle
  or a table entry to inspect, and a handover must not drop either.

No caller yet: the handover itself follows.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: flush everything a handover would refuse to carry

FlushForHandover flushes every open handle that has dirty pages, dirty
metadata (this publishes deferred creates, whose only copy is a placeholder in
the meta cache that does not cross) or a deferred close flush, through doFlush
as fsync does, and waits for the closed files draining in the background and
the creates still being sent, all bounded by a context. No new flush logic.
It is safe while requests are served, like an fsync of every open file from
another thread, which keeps the bulk of the uploads out of the pause.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: measure the handover of a million-inode table

Skipped with -short. Logs encode and decode time and bytes for 1M inodes:
1.3 s to export, 1.6 s to import and 39 MB on a 2-vCPU VM.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: hand over a file whose first open was closed

Each open of a file has its own fh id over one shared handle. The handle's
own id is that of the first open, and stays so when that open is closed: it
keys the handle's lock. The import required it to be among the live opens,
so a file opened twice and then closed through its first descriptor was
exported, and refused by the successor before anything was installed.

The import now only requires the handle ids to be distinct, as the lock
table does. Tested for both close orders.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: export the subscription position only with its events applied

The metadata subscription moves its position on as soon as an event is in
the meta cache. What the event does to the inode table and to the open
handles, a rename by another mount or a newer entry, is queued for the
invalidation worker and happens later. An export in between carried the
position of the event without its change, and the successor, resuming
behind the event, never applied it: an open file kept its old entry and a
renamed inode its old path.

The export now refuses while the subscription runs, since it would keep
feeding the worker, and waits for the worker to be through what it holds
before it takes the handle locks, which the worker needs. The wait is
bounded at 5 s and ends in a refusal: the worker can sit in a kernel
notification that needs a request served, which nobody does while the FUSE
server is stopped.

Hooks: WFS.metaFollowers counts the subscription goroutines, and
MetaCache.WaitForEntryInvalidationsWithin is the bounded drain.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: an imported subscription position survives another handover

The import kept the position for StartBackgroundTasks only, and the export
reads the meta cache's, which stayed zero until the subscription started. A
mount that handed over again before that passed on no position, and its
successor would have followed from its own start time, missing the events
in between. The import now also records the position in the meta cache.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: refuse a handover between different lock modes

The advisory locks an application holds are either in the mount's own
table or, with -dlm and no writeback cache, on the filer, and each mode
only asks its own place. The import installed whatever it was given: a
successor started with -dlm kept the predecessor's local locks in a table
it no longer consults, so a second lock on the same range was granted; one
started without it kept routed locks whose leases nothing renews.

The mode now crosses in the identity (Identity.routed_locks) and the import
refuses another one before it changes anything, as for the cache mode.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: read a handle's dirty state under its lock in the handover flush

FlushForHandover runs once while requests are served, and looked for the
handles to flush by reading their dirty flags and page state under the
handle map's lock only. Writes, truncates and flushes change those under
the handle's flush lock, so the read raced with them.

Each handle is now examined under its own flush lock, in the worker that
flushes it, with the map's lock held only to list the handles: a handle's
lock is never taken under the map's. A handle closed since it was listed
is left to its release or to the background drain. asyncFlushPending is
still read under the map's lock, as RELEASE reads it.

The new test runs the flush next to writers and to opens and closes; with
the handle lock taken out again the race detector reports the read.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: hand over the nfs export records not yet written to the filer

With -nfsExport one background writer keeps the filer's record of every
open file. The export listed the inodes that have a path or an open count
and marked those still queued for the writer. Two kinds of pending work
were missing:

- a record to remove. When the removal timer of a closed file fires, the
  inode has no path and no open left, only its place in the writer's
  queue, so it was not listed and the registration stayed on the filer;
- a write the writer had taken from its queue: in flight, or failed and
  waiting a second for its retry. It is lost with the process, and the
  record crossed as clean.

The writer now counts what it has taken and not finished
(exportedHandles.unwritten), and the export lists queued and unfinished
inodes too and marks both dirty. Writes in flight are not waited for: the
successor writes the record again under the same owner, with the same
result.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: keep followMetadataUpdates' doc comment on its function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: hand over the owner of the nfs export registrations

The owner is a hash of the hostname and mount directory, so a successor in
a replaced pod has another one: the records it rewrites or removes would sit
next to the exporter's instead of replacing them. The importer takes the
exporter's owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: bound the wait for the held nfs record write in the handover test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: stop the nfs export writer once a handover export starts

The successor registers under the exporter's owner, so a record write of
the exporter landing after one of the successor's took the record back,
and a removal timer firing in the exporter dropped the successor's entry.
The export now stops the writer before it captures the records: a write
not yet at its put drops it and stays dirty, a put already sent is waited
for (the export refuses if it does not return in time), and the writer
starts again when the export fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: let the drain test's events through only once the export waits

TestHandoverExportWaitsForEventsToReachTheState released the held
invalidations 100 ms after it started the export goroutine. A goroutine
that started later found the events applied already, and the test passed
without testing the wait.

The export now calls a test hook, handoverEventSettleStarted, when it
starts that wait, with the subscription's position already taken. The
test lets the events through only after the hook, and after checking that
the export did not finish while they were held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: wait for the exporter's removal timer instead of a fixed sleep

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: confirm the stopped writer took the removal's wake in the handover test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: whitebear009 <whitebear009@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 23:43:41 -08:00
8760e2778b worker: dir_usage takes off what a TTL expires (#13369)
* worker: dir_usage takes off what a TTL expires

A plain TTL removes an expired row without an event, so a record kept
counting it until its bucket was seeded again. An entry's attributes say
when listings start leaving it out (Entry.ExpiresAt, which listingExpired
now uses), so a record keeps what each directory has still to expire,
grouped by the step it expires in, and each run takes off what came off
by its position. A step is an hour, or for a TTL of 200 hours or more the
largest power of two hours up to 1% of it, so a record stays bounded.

An event counts an entry only if the record has not taken it off yet, so
an S3 expiry, which logs a delete, comes off once. Record version 2 seeds
the records made before again.

Part of #13257.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* dir_usage: decide a seeded directory's share after what expired

The seed took off what had expired by its position only after the final
share check, so a directory the walk kept could be dropped against a
total that still counted those entries. Take them off first, and hand
what a dropped directory has still to expire to the directory above.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* dir_usage: drop a seeded directory below its share with dropTracked

A directory below its share has none above its share below it, so
dropping it with what is below, its entries staying counted above, is
what untrack did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 23:40:58 -08:00
Chris LuandClaude Opus 5.5 f796077361 s3: keep a shared STS signing key on the filer when no IAM config is given (#13368)
* s3: keep a shared STS signing key on the filer when no IAM config is given

Without an IAM config file, jwt.filer_signing.key, or an SSE-S3 KEK, the
IAM loader had no STS signing key and STS stayed off. The KEK used to be
created automatically, which made STS work out of the box; it no longer is.

In that zero-config case, read the key from /etc/iam/sts_signing_key on the
filer, creating it once with an exclusive create, so every gateway sharing
the filer signs and validates session tokens with the same key across
restarts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: wait for the winning gateway's STS key after a refused create

With per-filer stores the exclusive create is decided by the write owner,
so the key another gateway created may reach this filer a little after the
create is refused. Keep reading until it shows up instead of leaving STS
off on the losing gateway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: refuse the filer STS key while an SSE-S3 key goes unloaded

A gateway whose SSE-S3 setup failed (a KEK it cannot unwrap, or a
configured key that was rejected) has no master key, so it fell through
to the STS key kept on the filer while the other gateways signed with
the KEK. Leave STS off on such a gateway instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 23:37:07 -08:00
55 changed files with 6693 additions and 1793 deletions

No files matched your search

-41
View File
@@ -1,41 +0,0 @@
# Block CI in the shared repository
The block module stays in `seaweed-block/` with its own `go.mod` and unchanged module path. Root `block-*.yml` workflows run shell commands there; action inputs name the subdirectory explicitly. The imported subtree is unchanged: every port file lives under root `.github/`. Existing module scripts and data remain base-owned inputs; only the Git adapters and unit-group coordinator live in root `.github/block/scripts/`. The existing nested workflows are inert because GitHub only discovers root workflows.
PR and master-push workflows select `seaweed-block/**` and their root block workflow files. All jobs default to `ubuntu-latest`. Set the repository variable `BLOCK_RUNNER_LABEL` only after the corresponding dedicated runner label is registered and available; same-repository/trusted events then use that label. Fork PRs always use GitHub-hosted runners. GitHub Actions cannot fall back after requesting an unavailable label, so an unset variable is the explicit safe default. Unset it again if the registered pool is withdrawn. Runner discovery would require runner-management API access that the read-only workflow token does not have; no new credential is requested.
The unit check keeps `go test (linux)` and `process-level tests (real binaries)` under workflow `Block Test`. Module-relative diff/blob adapters preserve the block model map and allow list. Root block workflow/Docker recipe changes still pass the block trace/public-text checks; unrelated host code is excluded. No imported module paths or product formats change.
## Read-only merge checks
From a trusted current master checkout, run inside the module:
```sh
python3 ../.github/block/scripts/safe-merge-check.py 123
```
It requires an open, ready, mergeable PR, the latest successful `Block Test` run at its exact head against current master, both successful named jobs, and the base-owned spec-trace/public-text checks. It rechecks head/base after inspection. It never merges or comments. The manager performs the authorized squash merge with `--match-head-commit`.
For a batch, preserve its builder's exact order in a local manifest:
```json
{"base":"BASE_SHA","batch_pr":123,"head":"BATCH_SHA","prs":[{"number":121,"head":"HEAD_121","evidence":"evidence/121.txt"},{"number":122,"head":"HEAD_122","evidence":"evidence/122.txt"}]}
```
```sh
python3 ../.github/block/scripts/safe-merge-check.py --batch batch.json
# After the authorized ordered squash merges, compare master with the printed tested tree:
python3 ../.github/block/scripts/safe-merge-check.py --verify-tree TESTED_TREE_SHA
```
The manifest and acceptance files are operator inputs from the batch builder, never files supplied by a PR. Batch readiness refuses a moved master/head, changed order or missing evidence and runs each member's base-owned local checks. Building/pushing a batch and merging remain manager operations.
## Releases
Only `seaweed-block/vX.Y.Z[-pre]` tags publish. Image tags omit the namespace and retain the existing block/CSI image names. Only block stable tags decide whether `alpha` advances. Root-context Docker recipes preserve Git revision metadata while building the nested module and retain the lab-binary refusal.
The Linux amd64 tarball contains `blockmaster`, `blockvolume` and `sw-block` copied from the exact published image digest, with `SHA256SUMS`. The GitHub release uses the namespaced tag and does not replace the shared repository's latest release. Release notes must already exist in the module. No tag, image or release is created by preparation or local tests.
## Move-window checks
This revision targets the v1.1.0 import branch. Do not edit files under `seaweed-block/` here; development stays in its source repository until the v1.1.1 history update. The root unit-group helpers project the qualified #1001 source; refresh root CI adapters against the corresponding source when that later import arrives. Run the normal Test workflow, base-owned checks and a controlled nonproduction release rehearsal before enabling real publication. Validate organization runner registration, Docker, GHCR package access, and existing repository rulesets/check names. Existing host workflows are unchanged; their broad Go filters may also select a block-only PR. The first import needs its own reviewed bootstrap evidence: a pre-import master has no block scripts, so neither the new pull_request_target gates nor the base-owned local checker can qualify that initial import from an absent base module. Once the import/port is on the trusted base, subsequent block PRs use these checks.
-130
View File
@@ -1,130 +0,0 @@
"""Local-only checks for the nested-module CI port; no Go suites or publishing."""
from pathlib import Path
import copy
import importlib.util
import os
import subprocess
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
class PortTests(unittest.TestCase):
def test_root_workflows_use_module_run_and_action_paths(self):
for name in ("test", "spec-trace", "post-merge-review", "known-bugs"):
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
self.assertIn("working-directory: seaweed-block", text)
self.assertIn("vars.BLOCK_RUNNER_LABEL", text)
self.assertIn("|| 'ubuntu-latest'", text)
if "go-version-file:" in text: self.assertIn("go-version-file: seaweed-block/go.mod", text)
if name != "known-bugs":
self.assertIn('"seaweed-block/**"', text)
self.assertIn('".github/workflows/block-*.yml"', text)
test = (ROOT / ".github/workflows/block-test.yml").read_text()
self.assertIn("- master", test)
self.assertIn("git diff --relative --name-only HEAD^1 HEAD -- .", test)
self.assertIn("go test (linux)", test)
self.assertIn("process-level tests (real binaries)", test)
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
self.assertIn("working-directory: ${{ github.workspace }}", post)
def test_release_tag_namespace_and_artifact_identity(self):
text = (ROOT / ".github/workflows/block-release.yml").read_text()
self.assertIn('"seaweed-block/v*"', text)
self.assertNotIn('tags:\n - "v*"', text)
self.assertIn("git tag -l 'seaweed-block/v*'", text)
self.assertIn('docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"', text)
self.assertIn('gh release create "$GITHUB_REF_NAME"', text)
self.assertIn('--latest=false', text)
self.assertIn('vars.BLOCK_RUNNER_LABEL', text)
self.assertIn("|| 'ubuntu-latest'", text)
self.assertIn('github.event.pull_request.head.repo.full_name == github.repository', text)
self.assertIn('sw-block-${version}-linux-amd64.tar.gz', text)
self.assertNotIn("go build", text)
for name in ("sw-block", "blockcsi"):
recipe = (ROOT / (".github/dockerfiles/block-" + name + ".Dockerfile")).read_text()
self.assertIn("WORKDIR /src/seaweed-block", recipe)
self.assertIn("COPY . /src", recipe)
self.assertGreater(recipe.index("RUN bash scripts/refuse-lab-binary.sh"), recipe.rindex("go build"))
def test_nested_git_paths_and_blobs_stay_module_relative(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); module = root / "seaweed-block"; module.mkdir()
def git(*args):
return subprocess.check_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master")
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
git("config", "commit.gpgsign", "false")
(module / "core").mkdir(); (module / "docs").mkdir()
code = module / "core/a.go"; code.write_text("package a\nconst N=1\n")
(root / "host.go").write_text("package host\n")
git("add", "."); git("commit", "-m", "base")
base = git("rev-parse", "HEAD").decode().strip()
(module / "docs/a.md").write_text("documentation\n")
git("add", "."); git("commit", "-m", "docs")
docs = git("rev-parse", "HEAD").decode().strip()
def run(name, *args):
return subprocess.check_output(["bash", str(HERE / name), *args], cwd=module, timeout=20)
self.assertEqual(run("docs-only-scope.sh", base, docs), b"docs_only 1\n")
code.write_text("package a\nconst N=2\n")
(root / "host.go").write_text("package host\nconst Changed=true\n")
git("add", "."); git("commit", "-m", "code")
head = git("rev-parse", "HEAD").decode().strip()
self.assertEqual(run("post-merge-review-changed.sh", docs, head), b"M\0core/a.go\0")
self.assertTrue(run("chunkstore-scope.sh", docs, head).startswith(b"skip 1"))
blobs = root / "blobs"
run("changed-go-blobs.sh", docs, head, str(blobs))
self.assertEqual((blobs / "old/core/a.go").read_text(), "package a\nconst N=1\n")
self.assertEqual((blobs / "new/core/a.go").read_text(), "package a\nconst N=2\n")
self.assertFalse((blobs / "new/host.go").exists())
control = root / ".github/workflows/block-test.yml"
control.parent.mkdir(parents=True)
control.write_text("name: Block Test\n")
git("add", ".github"); git("commit", "-m", "CI control")
control_head = git("rev-parse", "HEAD").decode().strip()
self.assertIn(b".github/workflows/block-test.yml\0", run("post-merge-review-changed.sh", docs, control_head))
self.assertTrue(run("docs-only-scope.sh", base, control_head).startswith(b"run "))
checker = root / ".github/block/scripts/public-text-check.sh"
checker.parent.mkdir(parents=True)
checker.write_text("pattern='disk" + "station'\n")
git("add", ".github"); git("commit", "-m", "checker pattern")
pattern_head = git("rev-parse", "HEAD").decode().strip()
title, body = root / "title.txt", root / "body.txt"
title.write_text("CI scope"); body.write_text("Checker patterns")
self.assertEqual(run("public-text-check.sh", control_head, pattern_head, str(title), str(body)), b"public-text: clean\n")
def test_safe_merge_refuses_wrong_head_base_and_incomplete_jobs(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
run = {"name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
check.validate(pr, run, jobs, "base")
for key, value in (("head_sha", "other"), ("conclusion", "cancelled"), ("name", "Other Test")):
wrong = copy.deepcopy(run); wrong[key] = value
with self.assertRaises(ValueError): check.validate(pr, wrong, jobs, "base")
with self.assertRaises(ValueError): check.validate(pr, run, jobs, "moved")
with self.assertRaises(ValueError): check.validate(pr, run, jobs[:1], "base")
failed = copy.deepcopy(jobs); failed[0]["conclusion"] = "failure"
with self.assertRaises(ValueError): check.validate(pr, run, failed, "base")
def test_batch_preserves_pinned_base_heads_order_and_evidence(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
with tempfile.TemporaryDirectory() as tmp:
evidence = Path(tmp) / "acceptance"; evidence.write_text("review accepted")
prs = [{"number": n, "state": "open", "draft": False, "base": {"ref": "master"}, "head": {"sha": str(n)}} for n in (1, 2)]
manifest = {"base": "base", "head": "batch", "prs": [{"number": p["number"], "head": p["head"]["sha"], "evidence": str(evidence)} for p in prs]}
check.validate_batch(manifest, prs, "base")
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "moved")
with self.assertRaises(ValueError): check.validate_batch(manifest, list(reversed(prs)), "base")
wrong = copy.deepcopy(prs); wrong[0]["head"]["sha"] = "new"
with self.assertRaises(ValueError): check.validate_batch(manifest, wrong, "base")
evidence.write_text("")
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base")
if __name__ == "__main__": unittest.main()
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env bash
# Writes the old and new blob of each changed non-test Go file between two
# commits under <out>/old/<path> and <out>/new/<path>, for the spec trace's
# kind DOCS (objects only; nothing from the PR is built or run).
#
# usage: changed-go-blobs.sh <merge-base> <head> <out>
#
# The paths come from the PR's tree objects, which git does not check when it
# prints a diff. A path that is absolute or has an empty, '.' or '..'
# component would write outside <out>, so it is refused before anything is
# written (exit 1).
set -euo pipefail
mb=$1 head=$2 out=$3
prefix=$(git rev-parse --show-prefix)
mkdir -p "$out"
git diff --relative --name-only --no-renames -z "$mb" "$head" -- "*.go" ":(exclude)*_test.go" >"$out/.paths"
while IFS= read -r -d "" p; do
case "/$p/" in
*//* | */./* | */../*)
printf 'changed-go-blobs: refusing path %q\n' "$p" >&2
exit 1
;;
esac
done <"$out/.paths"
while IFS= read -r -d "" p; do
mkdir -p "$out/old/$(dirname "$p")" "$out/new/$(dirname "$p")"
git show "$mb:$prefix$p" >"$out/old/$p" 2>/dev/null || rm -f "$out/old/$p"
git show "$head:$prefix$p" >"$out/new/$p" 2>/dev/null || rm -f "$out/new/$p"
done <"$out/.paths"
rm -f "$out/.paths"
-13
View File
@@ -1,13 +0,0 @@
#!/usr/bin/env bash
# Run only from a trusted base checkout; HEAD code is inspected as Git objects.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
base=${1:?BASE}; head=${2:?HEAD}; body=${3:?BODY}; title=${4:?TITLE}
[ "$(git rev-parse HEAD)" = "$(git rev-parse "$base")" ] || { echo "refusing: checkout is not the trusted base" >&2; exit 2; }
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mb=$(git merge-base "$base" "$head")
bash "$here/post-merge-review-changed.sh" "$mb" "$head" >"$work/changed.bin"
bash "$here/changed-go-blobs.sh" "$mb" "$head" "$work/blobs"
bash .github/scripts/spec-trace-check.sh "$body" "$work/blobs" .github/model-code-trace.tsv <"$work/changed.bin"
bash "$here/public-text-check.sh" "$mb" "$head" "$title" "$body"
-33
View File
@@ -1,33 +0,0 @@
#!/usr/bin/env bash
# chunkstore-scope.sh BASE HEAD: decides whether a pull request runs the
# real-filer integration tests. It prints one line:
# "run N FIRST" at least one of the N changed files is under
# core/frontend/chunkstore/, core/storage/ or
# core/frontend/durable/ (FIRST is one)
# "skip N" none of the N changed files is
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
# and the caller then runs the tests: an error never selects skip.
#
# The NUL-delimited list is written to a file first and read to its end, so
# no pipe can stop early and leave a writer's error looking like an answer.
set -euo pipefail
[ "$#" -eq 2 ] || { echo "usage: chunkstore-scope.sh BASE HEAD" >&2; exit 2; }
list=$(mktemp)
trap 'rm -f "$list"' EXIT
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
echo "chunkstore-scope: git diff $1 $2 failed" >&2
exit 2
fi
n=0
hit=""
while IFS= read -r -d '' f; do
n=$((n + 1))
case $f in
core/frontend/chunkstore/* | core/storage/* | core/frontend/durable/*) [ -n "$hit" ] || hit=$f ;;
esac
done <"$list"
if [ -n "$hit" ]; then
echo "run $n $hit"
else
echo "skip $n"
fi
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/env bash
# docs-only-scope.sh BASE HEAD: classifies the files changed between BASE and
# HEAD for the process-level suite. It prints one line:
# "docs_only N" every one of the N changed files is under docs/
# "run N [FIRST-OTHER]" no file changed, or at least one is elsewhere
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
# and the caller then runs the tests: an error never selects docs_only.
#
# The NUL-delimited list is written to a file first and read to its end, so
# no pipe can stop early and leave a writer's error looking like an answer.
set -euo pipefail
[ "$#" -eq 2 ] || { echo "usage: docs-only-scope.sh BASE HEAD" >&2; exit 2; }
list=$(mktemp)
trap 'rm -f "$list"' EXIT
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
echo "docs-only-scope: git diff $1 $2 failed" >&2
exit 2
fi
if [ -n "$(git rev-parse --show-prefix)" ]; then
git -C "$(git rev-parse --show-toplevel)" diff --name-only --no-renames -z "$1" "$2" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' >>"$list"
fi
n=0
other=""
while IFS= read -r -d '' f; do
n=$((n + 1))
case $f in
docs/*) ;;
*) [ -n "$other" ] || other=$f ;;
esac
done <"$list"
if [ "$n" -gt 0 ] && [ -z "$other" ]; then
echo "docs_only $n"
else
echo "run $n${other:+ $other}"
fi
-121
View File
@@ -1,121 +0,0 @@
"""Check that every code and test anchor of the invariants ledger exists at a git ref.
usage: python -I ledger_check.py <repo-dir> <git-ref> [<ledger path in repo>]
A ledger row is a table line whose first cell holds `INV-...`. In its cells, a
backticked token that ends in .go is a FILE; a backticked identifier (or
Type.Method) is a SYMBOL of the nearest file named before it in the same cell,
or, in the test cell, of any file named in that cell. A file must exist at the
ref; a symbol must occur in its file as a whole word (for a test: `func Name(`).
A symbol with no file in its cell is looked up in the whole tree. A file may
be a glob (`volume_lock*.go`). A lower-case token with an underscore (a build
tag, a JSON key, a reason string) is not a Go symbol and is not checked.
Prints one line per missing anchor and a summary. It reads; it changes nothing.
Exit: 0 when every anchor exists; 1 when one is missing; 2 when git fails or no
row or anchor was found (an error is never read as a pass).
"""
import re
import subprocess
import sys
def git(repo, *args):
"""git's output. A git failure ends the check with exit 2: an error must
never read as "no anchors". `git grep` finding nothing (exit 1) is not one."""
r = subprocess.run(["git", "-C", repo] + list(args), capture_output=True, text=True,
encoding="utf-8", errors="replace")
if r.returncode != 0 and not (args and args[0] == "grep" and r.returncode == 1):
print("ledger_check: git %s failed (exit %d): %s" % (" ".join(args[:2]), r.returncode, r.stderr.strip()[:300]),
file=sys.stderr)
sys.exit(2)
return r.stdout
def main():
repo, ref = sys.argv[1], sys.argv[2]
ledger = sys.argv[3] if len(sys.argv) > 3 else "docs/design/invariants.md"
text = git(repo, "show", "%s:%s" % (ref, ledger))
prefix = sys.argv[4] if len(sys.argv) > 4 else ""
files = set(git(repo, "ls-tree", "-r", "--name-only", ref, "--", prefix or ".").split("\n"))
cache = {}
def body(path):
if path not in cache:
cache[path] = git(repo, "show", "%s:%s" % (ref, path))
return cache[path]
def resolve(tok):
"""A file token may be a full path or a bare file name."""
if tok in files:
return [tok]
if "*" in tok:
rx = re.compile("^(.*/)?" + "[^/]*".join(re.escape(x) for x in tok.split("*")) + "$")
return [f for f in files if rx.match(f)]
if "/" not in tok:
return [f for f in files if f.endswith("/" + tok)]
# a path with a directory matches whole path components only
return [f for f in files if f.endswith("/" + tok)]
ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?(\(\))?$")
go_all = None
rows = missing = anchors = 0
for n, line in enumerate(text.split("\n"), 1):
if not line.startswith("|"):
continue
cells = [c.strip() for c in line.strip().strip("|").split("|")]
m = re.match(r"`(INV-[A-Z0-9-]+)`", cells[0]) if cells else None
if not m or len(cells) < 6:
continue
rows += 1
inv, status = m.group(1), cells[-1]
if "ARCHIVED" in status:
continue
for ci, kind in ((3, "code"), (4, "test")):
toks = re.findall(r"`([^`]+)`", cells[ci])
cell_files = []
for t in toks:
if t.endswith(".go"):
cell_files.append(t)
cur = None
for t in toks:
if t.endswith(".go"):
cur = t
anchors += 1
if not resolve(t):
missing += 1
print("%s (line %d, %s, %s): file %s does not exist" % (inv, n, kind, status, t))
continue
if not ident.match(t):
continue
sym = t.rstrip("()").split(".")[-1]
if sym in ("nil", "true", "false") or sym.isupper() or len(sym) < 3:
continue
if "_" in sym and sym == sym.lower():
# a build tag, a JSON key or a reason string: not a Go symbol
continue
scope = [cur] if (cur and kind == "code") else cell_files
paths = [p for f in scope for p in resolve(f)]
anchors += 1
if kind == "test" and sym.startswith(("Test", "Fuzz", "Benchmark")):
pat = re.compile(r"func %s\(" % re.escape(sym))
else:
pat = re.compile(r"\b%s\b" % re.escape(sym))
if paths:
ok = any(pat.search(body(p)) for p in paths)
else:
if go_all is None:
go_all = git(repo, "grep", "-h", "-E", r"^(func|type|var|const|\s+[A-Za-z_]+\s)", ref, "--", prefix + "*.go")
ok = bool(pat.search(go_all))
if not ok:
missing += 1
where = ", ".join(scope) if scope else "the tree"
print("%s (line %d, %s, %s): %s not found in %s" % (inv, n, kind, status, t, where))
print("%d rows, %d anchors, %d missing at %s" % (rows, anchors, missing, ref))
if rows == 0 or anchors == 0:
print("ledger_check: no ledger rows or anchors found: refusing to pass", file=sys.stderr)
sys.exit(2)
sys.exit(1 if missing else 0)
if __name__ == "__main__":
main()
@@ -1,14 +0,0 @@
#!/usr/bin/env bash
# Usage: post-merge-review-changed.sh BASE HEAD
#
# Writes what a PR changes (BASE...HEAD) as NUL-separated STATUS, PATH pairs,
# unquoted, so any byte in a name reaches the check as itself. --no-renames
# reports a move as a delete of the old name and an add of the new one.
set -euo pipefail
base=${1:?usage: post-merge-review-changed.sh BASE HEAD}
head=${2:?usage: post-merge-review-changed.sh BASE HEAD}
git diff --relative -z --name-status --no-renames "$base...$head" -- .
if [ -n "$(git rev-parse --show-prefix)" ]; then
git -C "$(git rev-parse --show-toplevel)" diff -z --name-status --no-renames "$base...$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**'
fi
@@ -1,54 +0,0 @@
#!/usr/bin/env bash
# Refuses internal names in what a pull request makes public: the lines it
# adds, its commit messages, its title and its description. This repository is
# public; internal seat names and internal file-share paths do not belong in it.
#
# Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE
# Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage.
#
# The patterns live only here and in this check's own test; both files are
# excluded from the scan of added lines.
set -euo pipefail
[ "$#" -eq 4 ] || { echo "usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE" >&2; exit 2; }
mb=$1; head=$2; title=$3; body=$4
for f in "$title" "$body"; do
[ -f "$f" ] && [ -r "$f" ] || { echo "public-text: cannot read $f" >&2; exit 2; }
done
git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify "$head^{commit}" >/dev/null ||
{ echo "public-text: unknown commit $mb or $head" >&2; exit 2; }
# match: a grep error fails the check instead of reading as "no hit".
match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; }
pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation'
out=$(mktemp); trap 'rm -f "$out"' EXIT
report() { # report WHERE < matching lines
local where=$1 line
while IFS= read -r line; do
printf 'public-text: %s: %s
' "$where" "${line:0:160}" >>"$out"
done
}
# Added lines of the diff, with file and line number.
{
git diff --relative --no-color --no-renames -U0 "$mb" "$head" -- . \
':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh'
if [ -n "$(git rev-parse --show-prefix)" ]; then
git -C "$(git rev-parse --show-toplevel)" diff --no-color --no-renames -U0 "$mb" "$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' ':(exclude).github/block/scripts/public-text-check.sh'
fi
} |
awk '
/^diff --git / { hdr = 1; next }
hdr && /^\+\+\+ / { f = substr($0, 7); next }
/^@@ / { hdr = 0; split($3, a, ","); n = substr(a[1], 2) + 0; next }
!hdr && /^\+/ { print f ":" n ": " substr($0, 2); n++ }
' | match | report "added line"
# Commit messages (subjects and bodies) of the pull request.
git log --format='%h %s%n%b' "$mb..$head" | match | report "commit message"
match "$title" | report "title"
match "$body" | report "description"
hits=$(wc -l <"$out" | tr -d ' ')
if [ "$hits" -gt 0 ]; then
cat "$out"
echo "public-text: $hits hit(s). Say what the code or test does instead of who asked for it; keep internal paths out." >&2
exit 1
fi
echo "public-text: clean"
@@ -1,144 +0,0 @@
"""Run fake recorders through the real group executor, without product tests."""
from pathlib import Path
import json
import os
import subprocess
import time
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
import importlib.util
import signal
SCRIPT = Path(__file__).with_name("run-unit-groups.py")
FAKE = r'''import json, os, sys, time
from pathlib import Path
out = Path(sys.argv[1]); group = out.parent.name
root = Path(os.environ["FIXTURE_ROOT"])
(root / (group + ".started")).write_text("started")
deadline = time.monotonic() + 5
while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()):
if time.monotonic() >= deadline: sys.exit(17)
time.sleep(.01)
flags = sys.argv[2:]
assert "-p=" + ("4" if group == "g3" else "1") in flags
assert "-short" in flags and "-count=1" in flags and "20m" in flags
if sys.platform == "linux":
wal = Path(os.environ["TMPDIR"]) / "v1.bin"
with wal.open("w") as descriptor:
assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found"
else:
assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory"
out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n")
out.with_suffix(".stderr").write_text("fixture stderr")
(root / (group + ".finished")).write_text("finished")
sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0)
'''
class GroupRunnerTests(unittest.TestCase):
def run_groups(self, fail="", empty=False, alias=False):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n")
fake = root / "fake.py"; fake.write_text(FAKE)
env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail)
scratch = root / "tmp"
if alias:
scratch.mkdir()
link = root / "runner-temp"
link.symlink_to(scratch, target_is_directory=True)
scratch = link
result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20)
self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr)
expected = ["g3"] if empty else ["g1", "g2", "g3"]
for group in expected:
self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr)
self.assertTrue((root / "evidence" / group / "go-test.stderr").exists())
self.assertTrue((root / "tmp" / group).is_dir())
events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()]
self.assertCountEqual([e["Package"] for e in events], expected)
statuses = json.loads((root / "evidence" / "unit-groups.json").read_text())
self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0)
@unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control")
def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True)
def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups()
def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2")
def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True)
def test_cancel_escalates_even_after_group_leader_exits(self):
spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT)
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
leader = Mock(pid=12345)
leader.wait.return_value = 0
with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]):
module.terminate([leader])
self.assertIn(unittest.mock.call(12345, signal.SIGTERM), killpg.call_args_list)
self.assertIn(unittest.mock.call(12345, 9), killpg.call_args_list)
leader.wait.assert_called()
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
def test_cancel_kills_resistant_child_after_recorder_exits(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "")
child = root / "child.py"
child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n")
fake = root / "recorder.py"
fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n")
marker = root / "child"
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
pid = None
try:
deadline = time.monotonic() + 5
while not marker.exists():
if time.monotonic() >= deadline: self.fail("resistant child did not start")
time.sleep(.01)
pid = int(marker.read_text())
runner.terminate()
self.assertEqual(runner.wait(timeout=12), 130)
deadline = time.monotonic() + 2
while True:
stat = Path(f"/proc/{pid}/stat")
if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break
if time.monotonic() >= deadline: self.fail("resistant child survived cancellation")
time.sleep(.01)
finally:
if pid is not None:
try: os.kill(pid, signal.SIGKILL)
except ProcessLookupError: pass
if runner.poll() is None: runner.kill()
runner.communicate(timeout=5)
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
def test_cancel_joins_every_started_group(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("example/" + group + "\n")
fake = root / "held.py"
fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n")
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 5
markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")]
while not all(p.exists() for p in markers):
if time.monotonic() >= deadline: self.fail("groups did not start")
time.sleep(.01)
children = [int(p.read_text()) for p in markers]
runner.terminate()
self.assertEqual(runner.wait(timeout=10), 130)
for child in children:
with self.assertRaises(ProcessLookupError): os.kill(child, 0)
finally:
if runner.poll() is None: runner.terminate()
runner.communicate(timeout=10)
if __name__ == "__main__": unittest.main()
-123
View File
@@ -1,123 +0,0 @@
"""Run the three default unit groups concurrently on the current runner.
Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...]
The recorder accepts OUTPUT followed by go-test flags and packages. Each group
owns its logs/events; they are combined only after all group processes exit.
"""
from contextlib import ExitStack
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
def stop(_signum, _frame):
raise KeyboardInterrupt
def terminate(processes):
for process in processes:
try:
if os.name == "posix": os.killpg(process.pid, signal.SIGTERM)
elif process.poll() is None: process.terminate()
except ProcessLookupError:
pass
if os.name == "posix":
# The leader may exit on TERM while its descendants remain in the group.
# Bound the grace period by group lifetime, never by leader lifetime.
deadline = time.monotonic() + 5
remaining = list(processes)
while remaining and time.monotonic() < deadline:
alive = []
for process in remaining:
process.poll() # Reap an exited leader without forgetting its PGID.
try:
os.killpg(process.pid, 0)
alive.append(process)
except ProcessLookupError:
pass
remaining = alive
if remaining: time.sleep(.05)
for process in remaining:
try: os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError: pass
for process in processes:
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
def run(plan, evidence, temp, recorder):
groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")}
evidence.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
processes, results, times = {}, {}, {}
with ExitStack() as files:
try:
for group, packages in groups.items():
results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0}
if not packages:
print(f"{group}: no packages selected by scope", flush=True)
continue
out = evidence / group; out.mkdir(parents=True, exist_ok=True)
scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True)
# /proc/self/fd exposes resolved paths; preserve fixture identity even
# when the runner temp directory is a symlink to its data disk.
scratch = scratch.resolve(strict=True)
log = files.enter_context((out / "console.log").open("w", encoding="utf-8"))
command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages]
times[group] = time.monotonic()
processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix")
print(f"{group}: started {len(packages)} packages", flush=True)
remaining = set(processes)
while remaining:
for group in tuple(remaining):
status = processes[group].poll()
if status is not None:
results[group]["status"] = status
results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3)
remaining.remove(group)
if remaining: time.sleep(.05)
except BaseException:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
terminate(processes.values())
raise
for group in processes:
print(f"--- {group} ---", flush=True)
print((evidence / group / "console.log").read_text(errors="replace"), flush=True)
summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results}
try:
(evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
with (evidence / "go-test.json").open("ab") as combined:
for group in processes:
events = evidence / group / "go-test.json"
if events.exists(): combined.write(events.read_bytes())
except OSError as error:
print(f"test evidence unavailable: {error}", file=sys.stderr)
print(json.dumps(summary), flush=True)
return int(any(r["status"] != 0 for r in results.values()))
def main(argv):
if len(argv) < 5:
print(__doc__.strip(), file=sys.stderr)
return 2
signal.signal(signal.SIGTERM, stop)
try:
return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:])
except KeyboardInterrupt:
return 130
except (OSError, ValueError) as error:
print(f"unit groups: {error}", file=sys.stderr)
return 2
if __name__ == "__main__": sys.exit(main(sys.argv))
-105
View File
@@ -1,105 +0,0 @@
"""Read-only block merge readiness check. Run from a trusted master checkout.
Usage (inside seaweed-block/): python3 ../.github/block/scripts/safe-merge-check.py PR
Never merges, posts comments, changes account config or pushes refs.
"""
import json
import subprocess
import sys
import tempfile
from pathlib import Path
REPO = "seaweedfs/seaweedfs"
JOBS = {"go test (linux)", "process-level tests (real binaries)"}
def validate(pr, run, jobs, current):
if pr["state"] != "open" or pr["draft"] or pr["mergeable"] is not True:
raise ValueError("PR must be open, ready and mergeable")
if pr["base"]["ref"] != "master": raise ValueError("expected master base")
if run["name"] != "Block Test" or run["head_sha"] != pr["head"]["sha"]:
raise ValueError("wrong workflow or head")
if run["status"] != "completed" or run["conclusion"] != "success":
raise ValueError("Block Test is not successful")
bases = [p["base"]["sha"] for p in run["pull_requests"] if p["number"] == pr["number"]]
if bases != [current]: raise ValueError("tested base is not current master")
required = [j for j in jobs if j["name"] in JOBS]
if len(required) != 2 or {j["name"] for j in required} != JOBS or any(j["conclusion"] != "success" for j in required):
raise ValueError("both block test jobs must succeed")
def api(path):
return json.loads(subprocess.check_output(["gh", "api", "repos/" + REPO + "/" + path]))
def successful_run(pr, current):
runs = api("actions/runs?head_sha=" + pr["head"]["sha"] + "&event=pull_request&per_page=100")["workflow_runs"]
runs = [r for r in runs if r["name"] == "Block Test"]
if not runs: raise ValueError("no Block Test run")
run = max(runs, key=lambda r: (r["created_at"], r["id"]))
pages = json.loads(subprocess.check_output(["gh", "api", "--paginate", "--slurp", "repos/" + REPO + "/actions/runs/" + str(run["id"]) + "/jobs?per_page=100"]))
validate(pr, run, [j for page in pages for j in page["jobs"]], current)
return run
def local_checks(pr, current):
if subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() != current:
raise ValueError("run from trusted current master checkout")
with tempfile.TemporaryDirectory() as tmp:
body, title = Path(tmp) / "body", Path(tmp) / "title"
body.write_text(pr["body"] or "", encoding="utf-8")
title.write_text(pr["title"], encoding="utf-8")
subprocess.run(["git", "-c", "fetch.fsckObjects=true", "fetch", "--no-tags", "origin", "+refs/pull/" + str(pr["number"]) + "/head:refs/remotes/block-review/head"], check=True)
actual = subprocess.check_output(["git", "rev-parse", "refs/remotes/block-review/head"], text=True).strip()
if actual != pr["head"]["sha"]: raise ValueError("PR head moved; recheck")
subprocess.run(["bash", str(Path(__file__).resolve().with_name("check-pr-base.sh")), current, actual, str(body), str(title)], check=True)
def validate_batch(manifest, prs, current):
if manifest["base"] != current: raise ValueError("master moved since batch creation")
if not manifest["head"] or len(manifest["prs"]) < 2: raise ValueError("expected pinned batch and at least two PRs")
numbers = [p["number"] for p in manifest["prs"]]
if len(set(numbers)) != len(numbers) or numbers != [p["number"] for p in prs]:
raise ValueError("batch PR order differs or repeats")
for saved, pr in zip(manifest["prs"], prs):
if pr["state"] != "open" or pr["draft"] or pr["base"]["ref"] != "master" or pr["head"]["sha"] != saved["head"]:
raise ValueError("batch member is not ready or its head changed")
if not Path(saved["evidence"]).is_file() or not Path(saved["evidence"]).read_text().strip():
raise ValueError("batch member has no acceptance evidence")
def main(args):
current = api("git/ref/heads/master")["object"]["sha"]
if len(args) == 2 and args[0] == "--verify-tree":
tree = api("git/commits/" + current)["tree"]["sha"]
if tree != args[1]: raise ValueError("master tree differs from the tested batch")
print(json.dumps({"tree_matches": True, "master": current, "tree": tree}))
return
if len(args) == 2 and args[0] == "--batch":
manifest = json.loads(Path(args[1]).read_text())
prs = [api("pulls/" + str(p["number"])) for p in manifest["prs"]]
validate_batch(manifest, prs, current)
batch = api("pulls/" + str(manifest["batch_pr"]))
if batch["head"]["sha"] != manifest["head"]: raise ValueError("batch head changed")
run = successful_run(batch, current)
for pr in prs: local_checks(pr, current)
if api("git/ref/heads/master")["object"]["sha"] != current: raise ValueError("master moved; recheck")
for pr in prs + [batch]:
if api("pulls/" + str(pr["number"]))["head"]["sha"] != pr["head"]["sha"]: raise ValueError("head moved; recheck")
print(json.dumps({"ready": True, "base": current, "head": manifest["head"], "run": run["id"], "tree": api("git/commits/" + manifest["head"])["tree"]["sha"], "order": [p["number"] for p in prs]}))
return
if len(args) != 1 or not args[0].isdecimal(): raise ValueError("expected PR, --batch MANIFEST or --verify-tree TREE")
pr = api("pulls/" + args[0])
run = successful_run(pr, current)
local_checks(pr, current)
if api("git/ref/heads/master")["object"]["sha"] != current or api("pulls/" + args[0])["head"]["sha"] != pr["head"]["sha"]:
raise ValueError("base or head moved; recheck")
print(json.dumps({"ready": True, "head": pr["head"]["sha"], "base": current, "run": run["id"], "merge_mode": "squash"}))
if __name__ == "__main__":
try:
main(sys.argv[1:])
except (IndexError, KeyError, ValueError, OSError, subprocess.SubprocessError) as error:
print("REFUSED: " + str(error), file=sys.stderr)
sys.exit(1)
@@ -1,52 +0,0 @@
"""Exact coverage before scope selection; old heavy-package rules afterward."""
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location("planner", Path(__file__).with_name("unit-test-shards.py"))
planner = importlib.util.module_from_spec(spec)
spec.loader.exec_module(planner)
MODULE = "example.invalid/product"
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
class UnitShardTests(unittest.TestCase):
def setUp(self):
self.packages = [MODULE + "/" + p for p in (*HEAVY, "cmd/sw-block", "core/frontend/chunkstore", "internal/newpackage", "core/storage/child")]
self.groups = planner.partition(MODULE, self.packages)
def test_exact_cover_and_stable_order(self):
flat = [p for group in self.groups.values() for p in group]
self.assertCountEqual(flat, self.packages)
self.assertEqual(len(flat), len(set(flat)))
self.assertEqual(self.groups, planner.partition(MODULE, list(reversed(self.packages))))
self.assertEqual(self.groups["g1"], [MODULE + "/core/storage"])
self.assertEqual(self.groups["g2"], [MODULE + "/" + p for p in HEAVY[1:]])
self.assertIn(MODULE + "/internal/newpackage", self.groups["g3"])
self.assertIn(MODULE + "/core/storage/child", self.groups["g3"])
def test_existing_heavy_scope_on_main_train_and_prs(self):
all_changed = [p + "/changed.go" for p in HEAVY]
for event, ref in (("push", ""), ("pull_request", "train/next")):
selected = planner.select(MODULE, self.groups, event, ref, all_changed)
self.assertEqual(selected["g1"], [])
self.assertEqual(selected["g2"], [])
self.assertEqual(selected["g3"], self.groups["g3"])
self.assertEqual(planner.select(MODULE, self.groups, "pull_request", "fix/x", all_changed), self.groups)
for path in HEAVY:
selected = planner.select(MODULE, self.groups, "pull_request", "fix/x", [path + "/x.go"])
heavy = selected["g1"] + selected["g2"]
self.assertEqual(heavy, [MODULE + "/" + path])
nested = planner.select(MODULE, self.groups, "pull_request", "fix/x", ["core/storage/child/x.go", "core/storage/"])
self.assertEqual(nested["g1"], [])
self.assertEqual(nested["g2"], [])
self.assertEqual(nested["g3"], self.groups["g3"])
def test_invalid_inventory_is_refused(self):
for packages in ([], self.packages + [self.packages[0]], self.packages[1:], self.packages + ["other/pkg"]):
with self.subTest(packages=packages), self.assertRaises(ValueError):
planner.partition(MODULE, packages)
if __name__ == "__main__":
unittest.main()
-55
View File
@@ -1,55 +0,0 @@
"""Plan the default unit groups from the full go-list inventory.
Usage: go list ./... | python3 unit-test-shards.py MODULE OUT_DIR EVENT HEAD_REF CHANGED_FILE
The complete partition covers every package exactly once. Existing scope rules
then select heavy packages only on ordinary PRs that touch their direct files.
"""
from pathlib import Path
import sys
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
def partition(module, packages):
if not module or any(c.isspace() for c in module):
raise ValueError("expected one module path")
if not packages or len(packages) != len(set(packages)):
raise ValueError("empty package list or duplicate package")
if any(p != module and not p.startswith(module + "/") for p in packages):
raise ValueError("package outside the selected module")
heavy = [module + "/" + p for p in HEAVY]
if not set(heavy) <= set(packages):
raise ValueError("required heavy packages missing from go list")
return {"g1": heavy[:1], "g2": heavy[1:], "g3": sorted(set(packages) - set(heavy))}
def select(module, groups, event, head_ref, changed):
selected = set()
if event != "push" and not head_ref.startswith("train/"):
for p in HEAVY:
if any(f.startswith(p + "/") and f[len(p) + 1:] and "/" not in f[len(p) + 1:] for f in changed):
selected.add(module + "/" + p)
return {name: [p for p in packages if name == "g3" or p in selected]
for name, packages in groups.items()}
def main(argv):
if len(argv) != 6:
print(__doc__.strip(), file=sys.stderr)
return 2
try:
groups = partition(argv[1], sys.stdin.read().split())
groups = select(argv[1], groups, argv[3], argv[4], Path(argv[5]).read_text().splitlines())
out = Path(argv[2])
out.mkdir(parents=True, exist_ok=True)
for name, packages in groups.items():
(out / (name + ".txt")).write_text("".join(p + "\n" for p in packages), encoding="utf-8")
print(f"{name}: {len(packages)} packages")
except (OSError, ValueError) as error:
print(f"unit-test-shards: {error}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -1,27 +0,0 @@
FROM golang:1.25-bookworm AS build
WORKDIR /src/seaweed-block
COPY seaweed-block/go.mod seaweed-block/go.sum ./
RUN go mod download
COPY . /src
RUN CGO_ENABLED=0 go build -o /out/blockcsi ./cmd/blockcsi
# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the
# runtime stage, so neither a build nor a push of this image can complete.
RUN bash scripts/refuse-lab-binary.sh /out/blockcsi
FROM debian:bookworm-slim
RUN apt-get update && \
apt-get install -y --no-install-recommends \
e2fsprogs \
kmod \
multipath-tools \
nvme-cli \
open-iscsi \
sg3-utils \
util-linux && \
rm -rf /var/lib/apt/lists/*
COPY --from=build /out/blockcsi /usr/local/bin/blockcsi
ENTRYPOINT ["/usr/local/bin/blockcsi"]
@@ -1,24 +0,0 @@
FROM golang:1.25-bookworm AS build
WORKDIR /src/seaweed-block
COPY seaweed-block/go.mod seaweed-block/go.sum ./
RUN go mod download
COPY . /src
RUN CGO_ENABLED=0 go build -o /out/blockmaster ./cmd/blockmaster && \
CGO_ENABLED=0 go build -o /out/blockvolume ./cmd/blockvolume && \
CGO_ENABLED=0 go build -o /out/sw-block ./cmd/sw-block
# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the
# runtime stage, so neither a build nor a push of this image can complete.
RUN bash scripts/refuse-lab-binary.sh /out/blockmaster /out/blockvolume /out/sw-block
FROM debian:bookworm-slim
RUN apt-get update && \
apt-get install -y --no-install-recommends kmod && \
rm -rf /var/lib/apt/lists/*
COPY --from=build /out/blockmaster /usr/local/bin/blockmaster
COPY --from=build /out/blockvolume /usr/local/bin/blockvolume
COPY --from=build /out/sw-block /usr/local/bin/sw-block
USER 65532:65532
-70
View File
@@ -1,70 +0,0 @@
name: Block known bugs
# Nightly: every open-issue reproduction that is skipped by default (t.Skip unless
# SEAWEED_KNOWN_BUGS=1) runs and is EXPECTED TO FAIL. If one passes, its bug is
# fixed but its skip is still in place: this job fails and names it, so the skip
# is removed in the fix PR (or right after). A fix PR removes the test's line here
# together with its skip.
on:
schedule:
- cron: "17 6 * * *"
workflow_dispatch:
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
jobs:
known-bugs:
name: known-bug reproductions still fail
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
timeout-minutes: 15
env:
CGO_ENABLED: "0"
SEAWEED_KNOWN_BUGS: "1"
steps:
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false
- name: Runner disk is NVMe
# A self-hosted runner whose work, temp or Go cache directory sits on a
# SATA system disk times the process-level tests out under disk load;
# this names the runner and stops the job before it starts.
if: runner.environment == 'self-hosted'
run: |
bash .github/scripts/require-nvme-test.sh
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: seaweed-block/go.mod
cache: false
- name: Each reproduction still fails
run: |
set -u
ok=1
while read -r issue pkg test; do
[ -n "$issue" ] || continue
if go test -count=1 -run "^${test}\$" "$pkg" > "out-${test}.txt" 2>&1; then
echo "::error::${test} (${pkg}) now PASSES: ${issue} looks fixed, remove its skip"
ok=0
elif grep -q "^--- FAIL: ${test} " "out-${test}.txt"; then
echo "${test} (${issue}) still fails, as expected"
else
echo "::error::${test} (${pkg}) did not run or failed to build:"; tail -20 "out-${test}.txt"
ok=0
fi
done <<'LIST'
#186 ./cmd/blockmaster/ TestChartOptInLoopbackFlagIsAcceptedByBlockmaster
#187 ./cmd/blockmaster/ TestChartDefaultAuthorityStateSurvivesPodReplacement
#188 ./core/ops/ TestDeleteSafety_UntimedCleanupCannotProveFreshness
#189 ./core/storage/ TestMultiBlockRecordsRequireDistinctOnDiskImplVersion
LIST
[ "$ok" = 1 ]
@@ -1,66 +0,0 @@
name: Block post-merge-review paths
# A PR labelled "post-merge-review" may merge before its full review only if
# every changed file is allowed by .github/post-merge-review-allow.txt.
# This check fails such a PR otherwise; without the label it passes.
#
# pull_request_target: the workflow, the allow list and the script all come
# from the base branch, so a PR cannot change its own check. The PR's code is
# never checked out or run: only its commit is fetched, for the file list.
on:
pull_request_target:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
# edited: a retarget changes the base, and with it the diff.
types: [opened, synchronize, reopened, labeled, unlabeled, edited]
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
concurrency:
group: block-post-merge-review-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
paths:
name: post-merge-review paths
# GitHub-hosted: on the self-hosted runners this job ended in 'Set up
# job' with no log on every runner (2026-11-29), while spec trace, on the
# same runners, passes. Unlabelled PRs only echo here, so the hosted
# queue costs little; the merge gate does not wait for it unless the PR
# is labelled.
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
timeout-minutes: 5
steps:
- name: Not labelled
if: ${{ !contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
working-directory: ${{ github.workspace }}
run: echo "no post-merge-review label; nothing to check"
- name: Checkout base
if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
ref: ${{ github.event.pull_request.base.sha }}
fetch-depth: 0
persist-credentials: false
- name: Check changed paths
if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
env:
BASE: ${{ github.event.pull_request.base.sha }}
HEAD: ${{ github.event.pull_request.head.sha }}
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
bash .github/scripts/post-merge-review-check-test.sh
git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head"
bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt <changed.bin
-118
View File
@@ -1,118 +0,0 @@
name: Publish block release
on:
workflow_dispatch:
push:
tags:
- "seaweed-block/v*"
permissions:
contents: write
packages: write
env:
REGISTRY: ghcr.io
BLOCK_IMAGE: ghcr.io/seaweedfs/seaweed-block
CSI_IMAGE: ghcr.io/seaweedfs/seaweed-block-csi
jobs:
publish:
# Publish only from a version tag; a manual run from a branch must not move :alpha.
if: startsWith(github.ref, 'refs/tags/seaweed-block/v')
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # the tag list decides whether :alpha moves
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Compute image tags
id: tags
shell: bash
run: |
set -euo pipefail
# vX.Y.Z-pre (a release candidate) publishes only its own version tag. A stable vX.Y.Z also
# publishes sha-*, and moves :alpha only when it is the highest stable version tag, so a later
# patch on an older line never moves :alpha back.
short_sha="${GITHUB_SHA::12}"
version="${GITHUB_REF_NAME#seaweed-block/}"
if [[ ! "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then
echo "refusing to publish: tag ${version} is not vX.Y.Z or vX.Y.Z-pre" >&2
exit 1
fi
stable=false
move_alpha=false
if [[ "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
stable=true
highest="$(git tag -l 'seaweed-block/v*' | sed 's|^seaweed-block/||' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)"
if [[ "${version}" == "${highest}" ]]; then
move_alpha=true
fi
fi
{
echo "block_tags<<EOF"
echo "${BLOCK_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${BLOCK_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${BLOCK_IMAGE}:alpha"; fi
echo "EOF"
echo "csi_tags<<EOF"
echo "${CSI_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${CSI_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${CSI_IMAGE}:alpha"; fi
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Build and push block image
id: block
uses: docker/build-push-action@v6
with:
context: .
file: .github/dockerfiles/block-sw-block.Dockerfile
platforms: linux/amd64
push: true
tags: ${{ steps.tags.outputs.block_tags }}
- name: Build and push CSI image
uses: docker/build-push-action@v6
with:
context: .
file: .github/dockerfiles/block-blockcsi.Dockerfile
platforms: linux/amd64
push: true
tags: ${{ steps.tags.outputs.csi_tags }}
- name: Publish matching binary tarball
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BLOCK_DIGEST: ${{ steps.block.outputs.digest }}
shell: bash
run: |
set -euo pipefail
version="${GITHUB_REF_NAME#seaweed-block/}"
notes="seaweed-block/docs/releases/${version%%-*}.md"
test -s "$notes"
out="$RUNNER_TEMP/block-release"
mkdir -p "$out/bin"
docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"
container=$(docker create "${BLOCK_IMAGE}@${BLOCK_DIGEST}")
trap 'docker rm "$container" >/dev/null' EXIT
for binary in blockmaster blockvolume sw-block; do
docker cp "$container:/usr/local/bin/$binary" "$out/bin/$binary"
done
bash seaweed-block/scripts/refuse-lab-binary.sh "$out/bin/"*
asset="sw-block-${version}-linux-amd64.tar.gz"
tar -C "$out/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
args=(--repo "$GITHUB_REPOSITORY" --verify-tag --latest=false --title "Seaweed Block $version" --notes-file "$notes")
if [[ "$version" == *-* ]]; then args+=(--prerelease); fi
gh release create "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" "${args[@]}"
-93
View File
@@ -1,93 +0,0 @@
name: Block spec trace
# Every PR description carries the spec trace (see the PR template); this
# check fails a PR whose description does not.
#
# pull_request_target: the workflow and the script come from the base branch,
# so a PR cannot change its own check. The PR's code is never checked out or
# run: only its commit is fetched, for the file list. The description is read
# from the event through an environment variable, never interpolated.
on:
pull_request_target:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
# edited: the check reads the description and the base.
types: [opened, synchronize, reopened, edited]
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
concurrency:
group: block-spec-trace-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
trace:
name: spec trace
# The base-owned check defaults to a disposable hosted runner. Only a
# same-repository PR may opt into the registered BLOCK_RUNNER_LABEL.
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
timeout-minutes: 5
steps:
- name: Checkout base
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
# github.sha is the tip of the base branch when the event fires; the
# PR's base.sha can predate this workflow's own scripts.
ref: ${{ github.sha }}
fetch-depth: 0
persist-credentials: false
# spec-trace-check.sh builds the trusted sametokens.go; a self-hosted
# runner has no Go on its PATH unless the job sets it up.
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: seaweed-block/go.mod
cache: false
- name: Check spec trace
env:
BASE: ${{ github.event.pull_request.base.sha }}
HEAD: ${{ github.event.pull_request.head.sha }}
PR: ${{ github.event.pull_request.number }}
BODY: ${{ github.event.pull_request.body }}
TITLE: ${{ github.event.pull_request.title }}
run: |
set -euo pipefail
bash .github/scripts/spec-trace-check-test.sh
python3 -B .github/scripts/model-trace-check-test.py
bash .github/scripts/changed-go-blobs-test.sh
# fsckObjects: a PR's objects are checked as they arrive, so a tree
# with a '..' or '.git' entry is refused here.
git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head"
printf '%s' "$BODY" >body.txt
bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
# Old and new blobs of each changed non-test Go file, for kind DOCS
# (objects only; a path that would leave blobs/ is refused).
mb=$(git merge-base "$BASE" "$HEAD")
bash ../.github/block/scripts/changed-go-blobs.sh "$mb" "$HEAD" blobs
# Mapping and validator come from the trusted base checkout above.
bash .github/scripts/spec-trace-check.sh body.txt blobs .github/model-code-trace.tsv <changed.bin
# Internal names stay out of this public repository: added lines,
# commit messages, title and description (no PR code is run).
bash .github/scripts/public-text-check-test.sh
printf '%s' "$TITLE" >title.txt
bash ../.github/block/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt
- name: Invariants ledger anchors (report only)
# Every code and test anchor of docs/design/invariants.md must exist at
# the PR's commit (git objects only; nothing from the PR is run). It
# reports and does not fail the check while the known imprecise
# anchors are being corrected; then this step becomes gating.
continue-on-error: true
env:
HEAD: ${{ github.event.pull_request.head.sha }}
run: python3 -I ../.github/block/scripts/ledger_check.py "$GITHUB_WORKSPACE" "$HEAD" seaweed-block/docs/design/invariants.md seaweed-block/ || true
-365
View File
@@ -1,365 +0,0 @@
name: Block Test
on:
pull_request:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
# ready_for_review: a Draft runs no Go suite (below); marking it ready starts one.
types: [opened, synchronize, reopened, ready_for_review]
push:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
branches:
- master
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
# One run per PR (or per branch for pushes). A new push to a PR cancels the
# superseded run; runs on main are never cancelled so every merge gets a result.
concurrency:
group: block-test-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
test:
# One job, two suites, one runner selection. 'unit' is the Go suite below;
# 'process' runs the process-level tests: real blockmaster, blockvolume and
# sw-block against a pinned SeaweedFS release. Those tests are named in
# .github/process-level-tests.txt, and every one must PASS, so a test that
# skips, fails, never starts or is cut off by the timeout fails the suite.
# Tests that need root or systemd are not in the list (see its header).
strategy:
fail-fast: false
matrix:
suite: [unit, process]
name: ${{ matrix.suite == 'unit' && 'go test (linux)' || 'process-level tests (real binaries)' }}
# The suite writes heavily to the runner disk (real files, fsync), so a
# Draft PR skips it; its author tests locally until the PR is ready.
if: github.event_name == 'push' || !github.event.pull_request.draft
# Hosted by default until this repository has a registered block pool.
# Set BLOCK_RUNNER_LABEL only for an available dedicated label. Forks
# always stay on disposable GitHub-hosted runners.
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
# process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence).
timeout-minutes: ${{ matrix.suite == 'unit' && 60 || 90 }}
env:
# Pure-Go build: no package in the default build needs cgo, and the
# hosted runner should not depend on a C toolchain being present.
CGO_ENABLED: "0"
steps:
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false
# Two commits: the PR merge commit and its base parent, so the test
# step can see which packages the PR touches.
fetch-depth: 2
- name: Nested module CI contracts
run: python3 -I ../.github/block/scripts/block-ci-port-test.py
- name: Runner disk is NVMe
# A self-hosted runner whose work, temp or Go cache directory sits on a
# SATA system disk times the process-level tests out under disk load;
# this names the runner and stops the job before it starts.
if: runner.environment == 'self-hosted'
run: |
bash .github/scripts/require-nvme-test.sh
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
- name: Start whole-job load evidence
# Begins after checkout, before toolchain setup/build/tests. No host
# installation or privileged reads. A job-sized lifetime also bounds
# the sampler if cancellation prevents the stop step.
continue-on-error: true
env:
CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }}
run: |
echo "CI_EVIDENCE_DIR=$CI_EVIDENCE_DIR" >>"$GITHUB_ENV"
mkdir -p "$CI_EVIDENCE_DIR"
: >"$CI_EVIDENCE_DIR/go-test.json"
python3 -I .github/scripts/ci-load.py start "$CI_EVIDENCE_DIR/load.tsv" --duration ${{ matrix.suite == 'unit' && 2400 || 5400 }}
- name: Self-test evidence capture
run: |
python3 -B .github/scripts/ci-load-test.py
bash .github/scripts/record-go-test-test.sh
- name: Docs-only pull request
id: scope
if: matrix.suite == 'process' && github.event_name == 'pull_request'
# A pull request that changes only files under docs/ runs no product
# code the process-level tests could exercise, so they are skipped and
# the job still reports success. HEAD is the merge commit, HEAD^1 its
# base parent (fetch-depth 2 above). Pushes to main always run them, and
# so does any error of the check (../.github/block/scripts/docs-only-scope.sh).
run: |
set -euo pipefail
bash .github/scripts/docs-only-scope-test.sh
if out=$(bash ../.github/block/scripts/docs-only-scope.sh HEAD^1 HEAD); then
case $out in
"docs_only "*)
echo "skipped: docs only (${out#docs_only } files under docs/); the process-level tests run on the merge to main"
echo "docs_only=1" >>"$GITHUB_OUTPUT" ;;
*) echo "process-level tests run: $out" ;;
esac
else
echo "process-level tests run: the docs-only check failed"
fi
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: seaweed-block/go.mod
# The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk;
# uploading them as an Actions cache (~4 GB) in the post step
# outlasted the job timeout after every test had passed. Only the
# GitHub-hosted (fork PR) runner uses the Actions cache.
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: seaweed-block/go.sum
- name: Go version
if: matrix.suite == 'unit'
run: go version
- name: Build
if: matrix.suite == 'unit'
run: go build ./...
- name: Vet
if: matrix.suite == 'unit'
run: go vet ./...
- name: Lab build tags stay out of images and releases
if: matrix.suite == 'unit'
# swblock_lab_bigvol lifts the 1 TiB create cap and the local
# headroom refusal for scale rehearsals only; swblock_v11_format turns
# on the draft v1.1 store format. The default test run pins the
# release cap (TestReleaseBuildKeepsTheCreateCap) and the release
# format. This step checks the tags' allowlist and that every image
# Dockerfile refuses a lab binary (scripts/refuse-lab-binary.sh) after
# its build, with controls, then tests each tag alone and both.
run: |
set -euo pipefail
bash .github/scripts/lab-tag-check.sh .
bash .github/scripts/lab-tag-check-test.sh
for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do
go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'Lab|Headroom|Revision|LegacyBound' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/
done
- name: Test default configuration
if: matrix.suite == 'unit'
# Preserve the existing scope: main/train omit the four heavy packages;
# ordinary PRs add each only when its direct package files are touched.
# Three subprocesses share this ONE runner: storage, durable plus touched
# master/authority, and the remaining selected packages at -p=4.
env:
EVENT: ${{ github.event_name }}
HEAD_REF: ${{ github.head_ref }}
run: |
set -euo pipefail
python3 -I ../.github/block/scripts/unit-test-shards-test.py
python3 -I ../.github/block/scripts/run-unit-groups-test.py
plan="$RUNNER_TEMP/unit-groups"
mkdir -p "$plan"
go list ./... >"$plan/all.txt"
mod=$(go list -m)
# Main pushes need no changed-path list; a shallow initial push may
# have no parent. Ordinary PRs use the merge commit's base parent.
: >"$plan/changed.txt"
if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then
git diff --relative --name-only HEAD^1 HEAD -- . >"$plan/changed.txt"
fi
python3 -I ../.github/block/scripts/unit-test-shards.py "$mod" "$plan" "$EVENT" "$HEAD_REF" "$plan/changed.txt" <"$plan/all.txt"
python3 -I ../.github/block/scripts/run-unit-groups.py "$plan" "$CI_EVIDENCE_DIR" "$RUNNER_TEMP/unit-group-tmp" \
bash .github/scripts/record-go-test.sh
- name: Format v3 tagged tests
if: matrix.suite == 'unit'
# The swblock_format_v3_test tests of the four packages that carry them.
# Five durable tests are skipped by name: each installs a BASE on a chunk
# store, which no production path does (its invariant row is DORMANT);
# they are rewritten at the start of the next release, then this skip
# goes.
run: |
set -euo pipefail
skip='^(TestDurableProviderV3_AttachesCompletedChunkBASE|TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD|TestDurableProviderV3_DefersBASERetirementUntilLocalPresence|TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE|TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE)$'
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -count=1 -timeout 20m -tags swblock_format_v3_test -skip "$skip" \
./core/frontend/durable/ ./core/recovery/ ./core/replication/ ./core/transport/
- name: Self-test of the required-tests gate
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# The gate must fail on a skip, a failure, a test that never ran, one
# cut off mid-run, and one that reports PASS and then exits nonzero or
# hangs; this proves it before it judges the real run.
run: |
python3 -I .github/scripts/required-tests-check-test.py
bash .github/scripts/chunkstore-scope-test.sh
bash .github/scripts/run-named-tests-test.sh
python3 -I .github/scripts/shard-named-tests-test.py
- name: Pinned SeaweedFS
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# The release archive is checked against its sha256 before every use,
# also when taken from the runner's cache; a mismatch fails the step.
# Nothing else is fetched.
env:
WEED_VERSION: "4.53"
WEED_SHA256: d1a7dec9f48d8b33895a0ea8951971defc2dc5312906dcc76fa5a5f74a6ee90d
run: |
set -euo pipefail
cache="${RUNNER_TOOL_CACHE:-$RUNNER_TEMP}/seaweedfs-weed/$WEED_VERSION"
tgz="$cache/linux_amd64.tar.gz"
mkdir -p "$cache"
if ! echo "$WEED_SHA256 $tgz" | sha256sum -c --status - 2>/dev/null; then
part="$tgz.$$.part"
curl -fsSL --retry 3 -o "$part" "https://github.com/seaweedfs/seaweedfs/releases/download/$WEED_VERSION/linux_amd64.tar.gz"
echo "$WEED_SHA256 $part" | sha256sum -c - || { rm -f "$part"; exit 1; }
mv -f "$part" "$tgz"
fi
bin="$RUNNER_TEMP/weed-$WEED_VERSION"
mkdir -p "$bin"
tar -xzf "$tgz" -C "$bin" weed
echo "CHUNKSTORE_WEED=$bin/weed" >>"$GITHUB_ENV"
- name: Real-filer integration tests
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# The chunkstore_integration tests run against the pinned weed above
# (master, volume and filer as real processes): the conditional HEAD
# writes, cut uploads and object deletes of the chunk store, and the
# layout sync crash cases of the durable provider. They fail, never
# skip, without the binary. Pushes to main and train PRs always run
# them; another PR runs them when it touches core/frontend/chunkstore/,
# core/storage/ or core/frontend/durable/.
env:
EVENT: ${{ github.event_name }}
HEAD_REF: ${{ github.head_ref }}
# ../.github/block/scripts/chunkstore-scope.sh decides; an error of that check
# runs the tests. Each filtered run must PASS at least one test, so a
# filter that matches nothing fails instead of passing empty.
run: |
set -euo pipefail
if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then
if out=$(bash ../.github/block/scripts/chunkstore-scope.sh HEAD^1 HEAD); then
case $out in
"skip "*) echo "skipped: the PR touches neither core/frontend/chunkstore/ nor core/storage/ ($out)"; exit 0 ;;
*) echo "real-filer integration tests run: $out" ;;
esac
else
echo "real-filer integration tests run: the scope check failed"
fi
fi
for spec in "./core/frontend/chunkstore/ ^TestIntegration" "./core/frontend/durable/ ^TestQD1LayoutSync"; do
pkg=${spec%% *}; filter=${spec#* }
log="$RUNNER_TEMP/integration-$(basename "$pkg").log"
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -v -timeout 20m -tags chunkstore_integration -run "$filter" "$pkg" 2>&1 | tee "$log"
grep -q '^--- PASS: ' "$log" || { echo "no test of $pkg matched $filter"; exit 1; }
done
- name: Build the binaries and the test binary once
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
run: |
set -euo pipefail
bins="$RUNNER_TEMP/swblock-bins"
mkdir -p "$bins"
for b in blockmaster blockvolume sw-block; do go build -o "$bins/$b" "./cmd/$b"; done
go test -c -tags 'subprocess chunkstore_integration' -o "$bins/blockvolume.test" ./cmd/blockvolume
go test -c -o "$bins/blockcsi.test" ./cmd/blockcsi
# The known-zero acceptance's first-start crash step holds a test-only
# blockvolume (build tag kzhold, never released) at a chosen point.
go build -tags kzhold -o "$RUNNER_TEMP/blockvolume-kzhold" ./cmd/blockvolume
echo "SWBLOCK_TEST_BINS=$bins" >>"$GITHUB_ENV"
echo "KZ_HOLD_BIN=$RUNNER_TEMP/blockvolume-kzhold" >>"$GITHUB_ENV"
- name: Run the named process-level tests
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# Each named test in its own process of the one test binary, in
# sequence, so a panic or a hang in one cannot hide the others; each
# is bounded (TEST_TIMEOUT, then killed) and its exit status is kept:
# the gate needs a PASS event AND exit 0 for every named test. The known-zero acceptance
# runs its small shape (1 GiB, user-space client, no device); the
# 1 TiB run is lab only.
env:
KZ_RUN: "1"
KZ_SIZE: 1G
F1_RUN: "1"
TEST_TIMEOUT: 15m
# A failed test copies each daemon's whole log here (keepFullLog);
# the step below keeps them as the run's artifact.
SWBLOCK_TEST_LOG_DIR: ${{ env.CI_EVIDENCE_DIR }}/daemon-logs
run: |
set -euo pipefail
# SHARDS parallel shards, balanced by their last measured times
# (.github/process-level-seconds.txt). Each shard is its own sequence
# of test processes with its own slice of the test port ranges
# (SWBLOCK_TEST_PORT_SHARD) and its own TMPDIR; the gate judges every
# named test from all the shards together.
names=.github/process-level-tests.txt
# The manifest tags CSI entries; every other name uses blockvolume.test.
# The final checker still requires the complete, unsplit manifest.
awk '!/# package=blockcsi/' "$names" > "$RUNNER_TEMP/blockvolume-names.txt"
awk '/# package=blockcsi/ {sub(/#.*/, ""); if ($0 ~ /[^[:space:]]/) print}' "$names" > "$RUNNER_TEMP/blockcsi-names.txt"
test -s "$RUNNER_TEMP/blockcsi-names.txt"
shards=4
python3 -I .github/scripts/shard-named-tests.py "$RUNNER_TEMP/blockvolume-names.txt" .github/process-level-seconds.txt "$shards" "$RUNNER_TEMP/shard"
pids=()
for k in $(seq 1 "$shards"); do
mkdir -p "$RUNNER_TEMP/tmp-$k"
SWBLOCK_TEST_PORT_SHARD=$k SWBLOCK_TEST_PORT_SHARDS=$shards TMPDIR="$RUNNER_TEMP/tmp-$k" \
bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockvolume.test" "$RUNNER_TEMP/shard/$k.txt" \
"$RUNNER_TEMP/process-level-$k.json" "$RUNNER_TEMP/process-level-$k.status" "$TEST_TIMEOUT" cmd/blockvolume \
>"$RUNNER_TEMP/process-level-$k.log" 2>&1 &
pids+=($!)
done
for p in "${pids[@]}"; do wait "$p" || true; done
for k in $(seq 1 "$shards"); do sed "s/^/[shard $k] /" "$RUNNER_TEMP/process-level-$k.log"; done
# CSI uses the same per-case isolation, timeout and verdict as the shards.
TEST_PKG=github.com/seaweedfs/seaweed-block/cmd/blockcsi \
bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockcsi.test" "$RUNNER_TEMP/blockcsi-names.txt" \
"$RUNNER_TEMP/process-level-csi.json" "$RUNNER_TEMP/process-level-csi.status" "$TEST_TIMEOUT" cmd/blockcsi \
>"$RUNNER_TEMP/process-level-csi.log" 2>&1 || true
cat "$RUNNER_TEMP/process-level-csi.log"
cat "$RUNNER_TEMP"/process-level-*.status >"$RUNNER_TEMP/process-level.status"
python3 -I .github/scripts/required-tests-check.py --status "$RUNNER_TEMP/process-level.status" \
"$names" "$RUNNER_TEMP"/process-level-*.json
- name: Stop load evidence and collect raw process events
if: always()
continue-on-error: true
env:
SUITE: ${{ matrix.suite }}
run: |
if [ -z "${CI_EVIDENCE_DIR:-}" ]; then exit 0; fi
python3 -I .github/scripts/ci-load.py stop "$CI_EVIDENCE_DIR/load.tsv" || true
if [ "$SUITE" = process ]; then
mkdir -p "$CI_EVIDENCE_DIR/shards"
shopt -s nullglob
for file in "$RUNNER_TEMP"/process-level-*.json "$RUNNER_TEMP"/process-level-*.log "$RUNNER_TEMP"/process-level*.status; do
cp "$file" "$CI_EVIDENCE_DIR/shards/"
done
for file in "$CI_EVIDENCE_DIR"/shards/*.json; do cat "$file" >>"$CI_EVIDENCE_DIR/go-test.json"; done
fi
- name: Keep failed-job tests, load, daemon logs and shard results
# Both suites retain timed events and whole-job load. Process evidence
# also retains the original shard receipts and full daemon logs.
if: failure()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ env.CI_EVIDENCE_DIR }}
retention-days: 14
if-no-files-found: warn
+60 -1
View File
@@ -10,6 +10,7 @@ import (
"fmt"
"math"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -23,7 +24,8 @@ const (
Dir = filer.DirectoryEtcSeaweedFS + "/dir_usage"
// Version is the version of the record format and of the rules that
// pick the directories; a record of another version is made again.
Version = 1
// Version 2 takes off what a TTL expires.
Version = 2
// MinSharePercent is the share of its bucket's bytes a directory holds
// at least to get a record of its own. Directories at one depth do not
// overlap, so a bucket has at most 100/MinSharePercent records per level.
@@ -71,6 +73,59 @@ func (u Usage) IsZero() bool {
return u == Usage{}
}
// Value is what an entry adds to the directories above it, and when a record
// takes that off for its TTL.
type Value struct {
Usage
// Expires is when a record takes the entry off, in unix seconds, 0 if
// never: see Expires.
Expires int64
}
// EntryValue is what entry adds to the directories above it, and until when.
func EntryValue(entry *filer_pb.Entry) Value {
return Value{Usage: EntryUsage(entry), Expires: Expires(entry)}
}
// Expires is when a record takes entry off, in unix seconds: the end of the
// step in which listings start leaving it out, or 0 if they never do. The
// plain TTL removes the row without an event, so a record takes off by the
// step what expired in it, and counts an expired entry for at most a step.
func Expires(entry *filer_pb.Entry) int64 {
ttlSec := int64(entry.GetAttributes().GetTtlSec())
if entry == nil || entry.IsDirectory || ttlSec <= 0 {
return 0
}
expiresAt, ok := filer.FromPbEntry("/", entry).ExpiresAt()
if !ok {
return 0
}
step := expiryStep(ttlSec)
if t := expiresAt.Unix(); t > 0 {
return (t + step - 1) / step * step
}
// expired long ago
return step
}
// expiryStep is an hour, or for a TTL of 200 hours or more the largest power
// of two hours up to 1% of it: a record counts an expired entry for at most
// an hour or 1% of its TTL, and fewer than 200 steps fit in any TTL, so a
// directory has about that many pending for each TTL in it at most.
func expiryStep(ttlSec int64) int64 {
step := int64(time.Hour / time.Second)
for step*2 <= ttlSec/100 {
step *= 2
}
return step
}
// TakenOff reports whether a record at tsNs has taken off what comes off at
// expires.
func TakenOff(expires, tsNs int64) bool {
return expires != 0 && expires <= tsNs/int64(time.Second)
}
// Record is what the job keeps of one bucket, or of one directory directly
// under / outside the buckets folder.
type Record struct {
@@ -83,6 +138,10 @@ type Record struct {
// Dirs are the totals of Root, at "", and of each directory below it
// with a record of its own, by its path relative to Root.
Dirs map[string]Usage `json:"dirs"`
// Expiring is what Dirs count that a TTL takes out later, by when it
// comes off (unix seconds, see Expires) and then by the directory in Dirs
// nearest above it. What comes off by TsNs is taken off.
Expiring map[int64]map[string]Usage `json:"expiring,omitempty"`
}
// Relative is path relative to root, "" for root itself.
+58
View File
@@ -1,8 +1,11 @@
package dirusage
import (
"math"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -36,3 +39,58 @@ func TestRootsOfAPath(t *testing.T) {
t.Errorf("what holds the buckets folder counts")
}
}
func TestExpiresByTheStepOfItsTTL(t *testing.T) {
expiresAt := time.Date(2026, 12, 4, 10, 20, 0, 0, time.UTC)
file := func(ttl time.Duration) *filer_pb.Entry {
return &filer_pb.Entry{Name: "f", Attributes: &filer_pb.FuseAttributes{
FileSize: 1,
Crtime: expiresAt.Add(-ttl).Unix(),
TtlSec: int32(ttl / time.Second),
}}
}
for _, c := range []struct{ ttl, step time.Duration }{
{30 * time.Minute, time.Hour},
{7 * 24 * time.Hour, time.Hour},
{200 * time.Hour, 2 * time.Hour},
{30 * 24 * time.Hour, 4 * time.Hour},
{365 * 24 * time.Hour, 64 * time.Hour},
} {
step := int64(c.step / time.Second)
want := (expiresAt.Unix() + step - 1) / step * step
if got := Expires(file(c.ttl)); got != want {
t.Errorf("TTL %v: comes off at %d, want %d, the end of its %v step", c.ttl, got, want, c.step)
}
}
if got := Expires(&filer_pb.Entry{Name: "f", Attributes: &filer_pb.FuseAttributes{TtlSec: 60}}); got != 3600 {
t.Errorf("an entry that expired long ago comes off at %d", got)
}
for _, entry := range []*filer_pb.Entry{nil, {Name: "f", Attributes: &filer_pb.FuseAttributes{FileSize: 1}},
{Name: "d", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{TtlSec: 60}}} {
if got := Expires(entry); got != 0 {
t.Errorf("%v comes off at %d", entry, got)
}
}
}
func TestExpiryStepsAreFewAndShort(t *testing.T) {
hour := int64(time.Hour / time.Second)
for ttl := int64(1); ttl <= math.MaxInt32; ttl = ttl*9/8 + 1 {
step := expiryStep(ttl)
if step%hour != 0 || step/hour&(step/hour-1) != 0 {
t.Fatalf("TTL %ds: step %ds is not a power of two hours", ttl, step)
}
if step > max(hour, ttl/100) {
t.Errorf("TTL %ds: step %ds counts an expired entry for longer than an hour or 1%% of it", ttl, step)
}
if ttl/step >= 200 {
t.Errorf("TTL %ds: %d steps of %ds", ttl, ttl/step, step)
}
}
if !TakenOff(10, 10*int64(time.Second)) || TakenOff(10, 10*int64(time.Second)-1) || TakenOff(0, math.MaxInt64) {
t.Errorf("TakenOff")
}
if TakenOff(math.MaxInt64/2, math.MaxInt64) {
t.Errorf("a step beyond the last position is taken off")
}
}
+16
View File
@@ -229,6 +229,22 @@ func (entry *Entry) IsS3Versioning() (exist bool) {
return exist
}
// ExpiresAt is when listings start leaving entry out; ok is false for an
// entry they never leave out: a directory, one with no TTL, and a version of
// a versioned S3 object.
func (entry *Entry) ExpiresAt() (expiresAt time.Time, ok bool) {
if entry.TtlSec <= 0 || entry.IsDirectory() {
return time.Time{}, false
}
if entry.IsExpireS3Enabled() {
if entry.IsS3Versioning() {
return time.Time{}, false
}
return entry.GetS3ExpireTime(), true
}
return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second), true
}
func (entry *Entry) GetS3ExpireTime() (expireTime time.Time) {
if entry.Mtime.IsZero() {
expireTime = entry.Crtime
+2 -7
View File
@@ -1256,13 +1256,8 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
// listingExpired reports whether a listing leaves the entry out and deletes it.
func listingExpired(entry *Entry) bool {
if entry.TtlSec <= 0 || entry.IsDirectory() {
return false
}
if entry.IsExpireS3Enabled() {
return entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning()
}
return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now())
expiresAt, ok := entry.ExpiresAt()
return ok && expiresAt.Before(time.Now())
}
// DeleteEmptyParentDirectories recursively checks and deletes parent directories if they become empty.
+13
View File
@@ -155,6 +155,19 @@ func (f *Filer) Put(path util.FullPath, size uint64, chunks int) {
f.putEntry(parentOf(path), entry)
}
// PutTTL writes a file of size at path, created at crtime with a plain TTL.
func (f *Filer) PutTTL(path util.FullPath, size uint64, crtime time.Time, ttl time.Duration) {
f.mu.Lock()
defer f.mu.Unlock()
entry := &filer_pb.Entry{Name: path.Name(), Attributes: &filer_pb.FuseAttributes{
FileSize: size,
Crtime: crtime.Unix(),
Mtime: crtime.Unix(),
TtlSec: int32(ttl / time.Second),
}}
f.putEntry(parentOf(path), entry)
}
// Mkdir creates a directory at path, and the missing ones above it.
func (f *Filer) Mkdir(path util.FullPath) {
f.mu.Lock()
+143
View File
@@ -0,0 +1,143 @@
package mount
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// FlushForHandover publishes everything a handover would otherwise refuse to
// carry: every open handle with dirty pages, dirty metadata (a deferred create
// is published here: its only copy in the meta cache is a placeholder that
// does not cross) or a deferred close flush is flushed the way fsync flushes
// it, and the closed files still draining in the background and the creates
// still being sent are waited for. It adds no flush logic: each handle goes
// through doFlush with allowAsync false. ctx bounds the wait; on expiry the
// work already started carries on in the background, nothing is lost, and the
// error says so.
//
// It is safe while requests are served, like an fsync of every open file from
// another thread: run it once then, so the bulk of the uploads is not part of
// the pause, and again after the FUSE server stopped reading requests, for
// what became dirty in between. ExportHandoverState still refuses whatever is
// left (a failed flush leaves its handle dirty, and a file closed during the
// first run may still drain in the background).
func (wfs *WFS) FlushForHandover(ctx context.Context) error {
done := make(chan error, 1)
go func() { done <- wfs.flushForHandover(ctx) }()
select {
case err := <-done:
return err
case <-ctx.Done():
return fmt.Errorf("flush before handover: %w", ctx.Err())
}
}
func (wfs *WFS) flushForHandover(ctx context.Context) error {
// Closed files draining in the background first: their handle is still in
// the map, and a new flush of it would race the drain.
wfs.pendingAsyncFlushMu.Lock()
drains := make([]chan struct{}, 0, len(wfs.pendingAsyncFlush))
for _, done := range wfs.pendingAsyncFlush {
drains = append(drains, done)
}
wfs.pendingAsyncFlushMu.Unlock()
for _, done := range drains {
select {
case <-done:
case <-ctx.Done():
return ctx.Err()
}
}
// Requests are still served during the first run, so each handle's state
// is read under the lock its writers hold. The map's lock is only held to
// list the handles: a handle's flush lock is never taken under it.
type openHandle struct {
fh *FileHandle
// deferred is asyncFlushPending, read under the map's lock as RELEASE
// reads it. A close sets it with no lock, so a flag missed here waits
// for the run after the FUSE server stopped; the export refuses the
// handle until then.
deferred bool
}
wfs.fhMap.RLock()
handles := make([]openHandle, 0, len(wfs.fhMap.inode2fh))
for _, fh := range wfs.fhMap.inode2fh {
handles = append(handles, openHandle{fh, fh.asyncFlushPending})
}
wfs.fhMap.RUnlock()
var (
mu sync.Mutex
errs []error
wg sync.WaitGroup
)
concurrency := wfs.option.ConcurrentWriters
if concurrency <= 0 {
concurrency = 16
}
sem := make(chan struct{}, concurrency)
for _, h := range handles {
if ctx.Err() != nil {
break
}
wg.Add(1)
sem <- struct{}{}
go func(h openHandle) {
defer wg.Done()
defer func() { <-sem }()
if !h.deferred && !wfs.hasUnflushedState(h.fh) {
return
}
// Closed since it was listed: its release, or the background
// drain waited for above on the next run, deals with it.
if !wfs.fhMap.isOpen(h.fh) {
return
}
if status := wfs.doFlush(context.Background(), h.fh, unknownCallerId, unknownCallerId, false, metadataFlushTimeout); !status.Ok() {
mu.Lock()
errs = append(errs, fmt.Errorf("flush %s: status %v", h.fh.FullPath(), status))
mu.Unlock()
}
}(h)
}
wg.Wait()
if err := ctx.Err(); err != nil {
return err
}
// Creates sent in the background have no handle to wait on.
for wfs.asyncCreates.Load() > 0 {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(10 * time.Millisecond):
}
}
if len(errs) > 0 {
glog.Warningf("flush before handover: %d handles failed to flush", len(errs))
}
return errors.Join(errs...)
}
// hasUnflushedState reports whether fh has anything a flush would publish. It
// waits for the handle's flush lock: writes, truncates and flushes change this
// state under it.
func (wfs *WFS) hasUnflushedState(fh *FileHandle) bool {
lock := wfs.fhLockTable.AcquireLock("FlushForHandover", fh.fh, util.SharedLock)
defer wfs.fhLockTable.ReleaseLock(fh.fh, lock)
return fh.dirtyMetadata || fh.dirtyContent || fh.dirtyPages.HasPendingUploads()
}
// isOpen reports whether fh is still the handle of its inode with an open left.
func (i *FileHandleToInode) isOpen(fh *FileHandle) bool {
i.RLock()
defer i.RUnlock()
return i.inode2fh[fh.inode] == fh && fh.counter > 0
}
+146
View File
@@ -0,0 +1,146 @@
//go:build !windows
package mount
import (
"bytes"
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// A deferred create is published by the flush helper, after which the export
// goes through and carries a clean handle with a base.
func TestFlushForHandoverPublishesDeferredCreate(t *testing.T) {
wfs := newHandoverWFS(t)
wfs.option.WritebackCache = false // a plain mount: the flush is synchronous
startFakeFiler(t, wfs, &fakeFilerServer{})
fh, _ := openUnpublishedCreate(t, wfs, util.FullPath("/dir/file"), nil)
if err := wfs.ExportHandoverState(&bytes.Buffer{}); err == nil {
t.Fatalf("export before the flush: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := wfs.FlushForHandover(ctx); err != nil {
t.Fatalf("flush: %v", err)
}
if fh.dirtyMetadata || fh.baseEntry.Load() == nil || fh.dirtyPages.HasPendingUploads() {
t.Fatalf("handle still dirty: metadata %v, base %v", fh.dirtyMetadata, fh.baseEntry.Load())
}
data := exportToBytes(t, wfs)
dst := newHandoverWFS(t)
dst.option.WritebackCache = false
if err := dst.ImportHandoverState(bytes.NewReader(data)); err != nil {
t.Fatalf("import: %v", err)
}
got := dst.fhMap.inode2fh[fh.inode]
if got == nil || got.dirtyMetadata || got.baseEntry.Load() == nil {
t.Fatalf("restored handle: %+v", got)
}
}
func TestFlushForHandoverWaitsForBackgroundWork(t *testing.T) {
wfs := newHandoverWFS(t)
drain := make(chan struct{})
wfs.pendingAsyncFlush[7] = drain
wfs.asyncCreates.Add(1)
go func() {
time.Sleep(50 * time.Millisecond)
close(drain)
time.Sleep(50 * time.Millisecond)
wfs.asyncCreates.Add(-1)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
start := time.Now()
if err := wfs.FlushForHandover(ctx); err != nil {
t.Fatalf("flush: %v", err)
}
if time.Since(start) < 90*time.Millisecond {
t.Fatalf("returned after %v, before the background work finished", time.Since(start))
}
}
func TestFlushForHandoverHonoursDeadline(t *testing.T) {
wfs := newHandoverWFS(t)
wfs.pendingAsyncFlush[7] = make(chan struct{}) // never finishes
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
if err := wfs.FlushForHandover(ctx); err == nil {
t.Fatal("expected the deadline to end the wait")
}
}
// The first run happens while requests are served: writes and flushes change
// a handle's dirty state under its flush lock, and opens and closes change the
// handle map, while the flush looks for what to publish. Meant for -race.
func TestFlushForHandoverAlongsideWritesAndCloses(t *testing.T) {
wfs := newHandoverWFS(t)
plain := func(name string) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{FileMode: 0o644}}
}
now := time.Now().Unix()
var written []*FileHandle
for i := 0; i < 8; i++ {
path := util.FullPath(fmt.Sprintf("/w%d", i))
inode := wfs.inodeToPath.Lookup(path, now, false, false, 0, true)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, plain(path.Name()), 1, 1, false)
fh.RememberPath(path)
written = append(written, fh)
}
churned := wfs.inodeToPath.Lookup("/churn", now, false, false, 0, true)
stop := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
go func() { // a write, and the flush that publishes it, on every handle
defer wg.Done()
for {
for _, fh := range written {
lock := wfs.fhLockTable.AcquireLock("write", fh.fh, util.ExclusiveLock)
fh.dirtyMetadata, fh.dirtyContent = true, true
fh.dirtyMetadata, fh.dirtyContent = false, false
wfs.fhLockTable.ReleaseLock(fh.fh, lock)
}
select {
case <-stop:
return
default:
}
}
}()
go func() { // another file opened and closed over and over
defer wg.Done()
for {
_, id, _, _ := wfs.fhMap.AcquireFileHandle(wfs, churned, plain("churn"), 1, 1, false)
wfs.ReleaseHandle(id)
select {
case <-stop:
return
default:
}
}
}()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
for i := 0; i < 300; i++ {
if err := wfs.FlushForHandover(ctx); err != nil {
t.Fatalf("flush %d: %v", i, err)
}
}
close(stop)
wg.Wait()
for _, fh := range written {
if fh.counter != 1 || fh.dirtyMetadata {
t.Fatalf("%s: counter %d, dirty %v", fh.FullPath(), fh.counter, fh.dirtyMetadata)
}
}
}
+363
View File
@@ -0,0 +1,363 @@
package mount
import (
"fmt"
"slices"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// How a FileHandle crosses a handover. Every field is one of: crosses
// (exported, restored as is), rebuilt (derived again on import), or empty
// (must hold nothing at export; the export is refused otherwise, and the
// importer starts it empty). TestHandoverClassifiesEveryHandleField fails when
// a field is added without a line here.
//
// fh, fhs, counter crosses: fhs are the ids the kernel holds, one per open, and counter
// their number. fh is the id of the first open and keys the handle's
// lock for as long as the handle lives, also once that open is closed.
// inode crosses.
// entry crosses (filer_pb.Entry); the chunk group over it is rebuilt without
// any RPC, a manifest chunk is resolved lazily (chunkViewStale).
// baseEntry crosses: the filer state last acknowledged, merges judge events by it.
// entryVersionTsNs/Signature crosses: events at or below it must not roll the entry back.
// savedDir, savedName crosses: the path of a handle whose inode was forgotten.
// isDeleted, deleteEpoch, cross: they change what a later flush, rename or unlink does.
// isRenamed, nameTaken,
// linkRefresh
// contentType crosses: the mime the next flush stamps.
// sinceBase crosses its scalars (truncatedTo, rewrote) when it still marks the
// current base; empty of failed-flush folds and sent chunks.
// dirtyMetadata, dirtyContent, pendingAppend, pendingAppendOffset
// cross, but only an unlinked file's handle may carry them set: its
// flushes are skipped, so it stays dirty for good and its entry, with
// the chunk list its uploads built, exists only in the handle.
// dirtyPages empty: unflushed data cannot be carried; a new page writer is built.
// asyncFlushPending/Uid/Gid empty: a deferred close flush has to finish first.
// dlmLock empty: a lease held by a live renewal goroutine of this process.
// entryChunkGroup, chunkViewStale, reader
// rebuilt: read state.
// writebackContentError rebuilt: bound to the per-inode flag in wfs.writebackContentErrors,
// which crosses on its own (set flags only).
// wfs, entryLock, remoteInstallMu, pageWrites, mirrorFile
// rebuilt: process-local; pageWrites only compares against itself.
// handoverBlocker returns why fh cannot cross, or "". The caller holds fh's
// lock.
func (fh *FileHandle) handoverBlocker() string {
name := fh.FullPath()
switch {
case fh.counter <= 0 || fh.asyncFlushPending:
return fmt.Sprintf("%s: close flush still deferred", name)
case fh.dlmLock != nil:
return fmt.Sprintf("%s: holds a distributed lock", name)
case fh.dirtyPages.HasPendingUploads():
return fmt.Sprintf("%s: dirty pages or uploads in flight", name)
case fh.isDeleted:
// Never published again; its dirty flags cross as they are.
case fh.unpublishedCreate():
return fmt.Sprintf("%s: unpublished create", name)
case fh.dirtyMetadata || fh.dirtyContent || fh.pendingAppend:
return fmt.Sprintf("%s: unflushed changes", name)
}
if m := fh.sinceBase.Load(); m != nil && m.base == fh.baseEntry.Load() {
if len(m.folds) > 0 || m.sent.size() > 0 {
return fmt.Sprintf("%s: a failed flush left state over its base", name)
}
}
return ""
}
func (s *sentChunks) size() int {
if s == nil {
return 0
}
s.Lock()
defer s.Unlock()
return len(s.ids)
}
// lockHandlesForHandover takes every open handle's flush lock without waiting
// and checks each can cross. A lock that is held means an operation on the
// handle is in flight (a delete, a rename, a flush, a write). The locks stay
// held until release, so the handles cannot change while they are exported.
func (wfs *WFS) lockHandlesForHandover() (handles []*FileHandle, release func(), blockers handoverBlockers) {
wfs.fhMap.RLock()
handles = make([]*FileHandle, 0, len(wfs.fhMap.inode2fh))
for _, fh := range wfs.fhMap.inode2fh {
handles = append(handles, fh)
}
openIds := 0
for _, fh := range handles {
openIds += len(fh.fhs)
for id := range fh.fhs {
if wfs.fhMap.fh2inode[id] != fh.inode {
blockers.add("file handle %d of inode %d is not registered", id, fh.inode)
}
}
}
if openIds != len(wfs.fhMap.fh2inode) {
blockers.add("%d registered file handle ids, %d open", len(wfs.fhMap.fh2inode), openIds)
}
wfs.fhMap.RUnlock()
slices.SortFunc(handles, func(a, b *FileHandle) int { return compareU64(uint64(a.fh), uint64(b.fh)) })
type held struct {
fh FileHandleId
lock *util.ActiveLock
}
var locks []held
release = func() {
for _, h := range locks {
wfs.fhLockTable.ReleaseLock(h.fh, h.lock)
}
}
for _, fh := range handles {
lock, ok := wfs.fhLockTable.TryAcquireLock("handover", fh.fh, util.ExclusiveLock)
if !ok {
blockers.add("%s: busy, an operation on it is in flight", fh.FullPath())
continue
}
locks = append(locks, held{fh.fh, lock})
if why := fh.handoverBlocker(); why != "" {
blockers.add("%s", why)
}
}
return handles, release, blockers
}
func compareU64(a, b uint64) int {
switch {
case a < b:
return -1
case a > b:
return 1
}
return 0
}
func (wfs *WFS) exportFileHandles(e *handoverEncoder, handles []*FileHandle) error {
for _, fh := range handles {
rec := &hpb.FileHandle{
Fh: uint64(fh.fh),
Inode: fh.inode,
Counter: fh.counter,
VersionTsNs: fh.entryVersionTsNs.Load(),
VersionSignature: fh.entryVersionSignature.Load(),
SavedDir: fh.savedDir,
SavedName: fh.savedName,
IsDeleted: fh.isDeleted,
DeleteEpoch: fh.deleteEpoch,
IsRenamed: fh.isRenamed,
NameTaken: fh.nameTaken,
LinkRefresh: fh.linkRefresh,
ContentType: fh.contentType,
DirtyMetadata: fh.dirtyMetadata,
DirtyContent: fh.dirtyContent,
PendingAppend: fh.pendingAppend,
PendingAppendOffset: fh.pendingAppendOffset,
}
for id, appendMode := range fh.fhs {
rec.Opens = append(rec.Opens, &hpb.OpenFh{Fh: uint64(id), Append: appendMode})
}
slices.SortFunc(rec.Opens, func(a, b *hpb.OpenFh) int { return compareU64(a.Fh, b.Fh) })
fh.entry.RLock()
if fh.entry.Entry != nil {
// The frame is marshalled below, still under the lock.
rec.Entry = fh.entry.Entry
}
base := fh.baseEntry.Load()
rec.Base = base
if m := fh.sinceBase.Load(); m != nil && m.base == base {
rec.Mark = &hpb.BaseMark{TruncatedTo: m.truncatedTo, Rewrote: m.rewrote}
}
err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_FileHandle{FileHandle: rec}})
fh.entry.RUnlock()
if err != nil {
return fmt.Errorf("export file handle %d (%s): %w", fh.fh, fh.FullPath(), err)
}
}
return nil
}
// captureDirHandles copies the directory handles, with the window of entries
// each holds: the kernel's next READDIR continues inside it, and a handle
// rebuilt empty would list again from the start and skip by position (the
// fallback for a handle the process has never seen, not a faithful resume).
// lastListedName is how far the store listing reached, ahead of what the
// kernel has consumed, so it only makes sense together with the entries.
func (wfs *WFS) captureDirHandles() (records []*hpb.DirHandle, blockers handoverBlockers) {
wfs.dhMap.Lock()
defer wfs.dhMap.Unlock()
for id, dh := range wfs.dhMap.dir2inode {
if !dh.TryLock() {
blockers.add("directory handle %d: a read is in flight", id)
continue
}
rec := &hpb.DirHandle{
Fh: uint64(id),
EntryStreamOffset: dh.entryStreamOffset,
IsFinished: dh.isFinished,
LastListedName: dh.lastListedName,
SnapshotTsNs: dh.snapshotTsNs,
}
for _, entry := range dh.entryStream {
dir, _ := entry.FullPath.DirAndName()
rec.Entries = append(rec.Entries, &hpb.StreamEntry{Dir: dir, Entry: entry.ToProtoEntry()})
}
dh.Unlock()
records = append(records, rec)
}
return records, blockers
}
func restoreDirHandles(records []*hpb.DirHandle) map[DirectoryHandleId]*DirectoryHandle {
handles := make(map[DirectoryHandleId]*DirectoryHandle, len(records))
for _, rec := range records {
dh := &DirectoryHandle{
isFinished: rec.IsFinished,
entryStreamOffset: rec.EntryStreamOffset,
lastListedName: rec.LastListedName,
snapshotTsNs: rec.SnapshotTsNs,
}
for _, se := range rec.Entries {
dh.entryStream = append(dh.entryStream, filer.FromPbEntry(se.Dir, se.Entry))
}
handles[DirectoryHandleId(rec.Fh)] = dh
}
return handles
}
// exportContentErrors lists the inodes whose writeback refusal flag is set: it
// outlives the handle, until the kernel forgets the inode.
func (wfs *WFS) exportContentErrors() []*hpb.ContentError {
var records []*hpb.ContentError
wfs.writebackContentErrors.Range(func(key, value any) bool {
if value.(*atomic.Bool).Load() {
records = append(records, &hpb.ContentError{Inode: key.(uint64)})
}
return true
})
return records
}
// checkHandoverHandles refuses records that would leave the handle maps
// inconsistent, before any state is replaced.
func checkHandoverHandles(imp *handoverImport) error {
byInode := make(map[uint64]bool, len(imp.fileHandles))
lockKeys := make(map[uint64]bool, len(imp.fileHandles))
ids := make(map[uint64]bool)
for _, rec := range imp.fileHandles {
if byInode[rec.Inode] {
return fmt.Errorf("two file handles for inode %d", rec.Inode)
}
byInode[rec.Inode] = true
// The handle's own id need not be among its opens: it is the first
// open's, which may have been closed while later ones stay.
if lockKeys[rec.Fh] {
return fmt.Errorf("two file handles with the id %d", rec.Fh)
}
lockKeys[rec.Fh] = true
if len(rec.Opens) == 0 || int64(len(rec.Opens)) != rec.Counter {
return fmt.Errorf("file handle %d of inode %d: %d opens, counter %d", rec.Fh, rec.Inode, len(rec.Opens), rec.Counter)
}
for _, o := range rec.Opens {
if ids[o.Fh] {
return fmt.Errorf("file handle id %d appears twice", o.Fh)
}
ids[o.Fh] = true
}
}
return nil
}
func (wfs *WFS) importContentErrors(records []*hpb.ContentError) {
if !wfs.option.WritebackCache {
return
}
for _, rec := range records {
state, _ := wfs.writebackContentErrors.LoadOrStore(rec.Inode, new(atomic.Bool))
state.(*atomic.Bool).Store(true)
}
}
// installFileHandles builds the handles of the records and enters them in the
// maps. Their entries are bound to the inode table, which must be installed.
func (wfs *WFS) installFileHandles(records []*hpb.FileHandle) {
restored := make([]*FileHandle, 0, len(records))
for _, rec := range records {
restored = append(restored, wfs.restoreFileHandle(rec))
}
wfs.fhMap.Lock()
defer wfs.fhMap.Unlock()
for _, fh := range restored {
wfs.fhMap.inode2fh[fh.inode] = fh
for id := range fh.fhs {
wfs.fhMap.fh2inode[id] = fh.inode
}
}
}
// restoreFileHandle builds the handle a record describes, as AcquireFileHandle
// built it at open. It is not yet in the maps, and makes no RPC.
func (wfs *WFS) restoreFileHandle(rec *hpb.FileHandle) *FileHandle {
fh := newFileHandle(wfs, FileHandleId(rec.Fh), rec.Inode, nil)
fh.counter = rec.Counter
fh.fhs = make(map[FileHandleId]bool, len(rec.Opens))
for _, o := range rec.Opens {
fh.fhs[FileHandleId(o.Fh)] = o.Append
}
fh.savedDir, fh.savedName = rec.SavedDir, rec.SavedName
fh.isDeleted, fh.deleteEpoch = rec.IsDeleted, rec.DeleteEpoch
fh.isRenamed, fh.nameTaken = rec.IsRenamed, rec.NameTaken
fh.linkRefresh = rec.LinkRefresh
fh.contentType = rec.ContentType
fh.dirtyMetadata, fh.dirtyContent = rec.DirtyMetadata, rec.DirtyContent
fh.pendingAppend, fh.pendingAppendOffset = rec.PendingAppend, rec.PendingAppendOffset
fh.entryVersionTsNs.Store(rec.VersionTsNs)
fh.entryVersionSignature.Store(rec.VersionSignature)
if wfs.option.WritebackCache {
wfs.inodeToPath.RLock()
state, found := wfs.writebackContentErrors.Load(rec.Inode)
if !found {
state, _ = wfs.writebackContentErrors.LoadOrStore(rec.Inode, new(atomic.Bool))
}
wfs.inodeToPath.RUnlock()
fh.writebackContentError = state.(*atomic.Bool)
}
if rec.Base != nil {
fh.baseEntry.Store(rec.Base)
}
if rec.Mark != nil {
fh.sinceBase.Store(&baseMark{base: rec.Base, truncatedTo: rec.Mark.TruncatedTo, rewrote: rec.Mark.Rewrote})
}
if rec.Entry != nil {
if rec.Entry.Attributes == nil {
rec.Entry.Attributes = &filer_pb.FuseAttributes{}
}
fh.restoreEntry(rec.Entry)
}
return fh
}
// restoreEntry installs an entry and the read view over it without a remote
// call. A manifest chunk is resolved from a volume server, so a handle that
// has one starts with the view of its plain chunks and marked stale: its first
// read or lseek resolves the rest (refreshChunkView), as after a failed
// resolution.
func (fh *FileHandle) restoreEntry(entry *filer_pb.Entry) {
fh.wfs.readAuth.Track(fh.FullPath(), entry.Chunks)
plain := make([]*filer_pb.FileChunk, 0, len(entry.Chunks))
for _, c := range entry.Chunks {
if !c.IsChunkManifest {
plain = append(plain, c)
}
}
fh.entryChunkGroup, _ = filer.NewChunkGroup(fh.wfs.LookupFn(), fh.wfs.chunkCache, plain, fh.wfs.option.ConcurrentReaders, fh.wfs.CacheInvalidator(), fh.wfs.manifestCache, fh.wfs.readerCacheBudget)
fh.chunkViewStale.Store(len(plain) != len(entry.Chunks))
fh.entry.SetEntry(entry)
}
+178
View File
@@ -0,0 +1,178 @@
package mount
import (
"errors"
"fmt"
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// What of InodeToPath crosses a handover, field by field:
//
// inode2path (path, extraPaths, nlookup) crosses: the kernel holds these ids and counts.
// path2inode rebuilt from the paths of inode2path; the few
// names it maps differently (a name kept for an inode
// that no longer lists it, or the reverse) cross as
// name fixups, normally none.
// dirStates (which inodes are directories) crosses as a flag, with subdirCount, the in-memory
// link count that readdir has not recomputed yet.
// dirStates.isChildrenCached, readDirDirect, cachedExpiresTime, lastAccess, lastRefresh,
// lastRebuildAttempt, lastSectionAttempts dropped: the meta cache starts empty, so every
// listing reloads from the filer.
// dirPaths rebuilt from dirStates and the primary path.
// wasCachedDirs, wasCachedOrder, wasCachedGen dropped: a hint for rebuilding dropped listings.
// forgotten, forgottenInodes cross when the importer retains them (-nfsExport):
// a handle the NFS server holds resolves through them.
// nextInodeId unused: inodes are derived from the path hash and
// probed for collisions against inode2path.
// cacheMetaTtlSec configuration of the new process.
func (i *InodeToPath) exportHandover(e *handoverEncoder) error {
i.RLock()
defer i.RUnlock()
var fixups []*hpb.NameFixup
agreeing := 0
for inode, ie := range i.inode2path {
rec := &hpb.Inode{Inode: inode, Nlookup: ie.nlookup, Path: string(ie.path)}
if ie.extraPaths != nil {
rec.Extra = make([]string, len(*ie.extraPaths))
for n, p := range *ie.extraPaths {
rec.Extra[n] = string(p)
}
}
if d, isDir := i.dirStates[inode]; isDir {
rec.IsDir, rec.Subdirs = true, d.subdirCount
}
for _, p := range ie.appendPaths(nil) {
if mapped, found := i.path2inode[p]; found && mapped == inode {
agreeing++
} else {
fixups = append(fixups, &hpb.NameFixup{Path: string(p), Inode: mapped})
}
}
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_Inode{Inode: rec}}); err != nil {
return err
}
}
if agreeing != len(i.path2inode) {
for p, inode := range i.path2inode {
if !i.listsPath(inode, p) {
fixups = append(fixups, &hpb.NameFixup{Path: string(p), Inode: inode})
}
}
}
for _, f := range fixups {
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_NameFixup{NameFixup: f}}); err != nil {
return err
}
}
if i.forgotten == nil {
return nil
}
// Oldest first, so the importer's LRU ends in the same order.
for _, inode := range i.forgotten.Keys() {
path, _ := i.forgotten.Peek(inode)
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_Forgotten{Forgotten: &hpb.Forgotten{Inode: inode, Path: string(path)}}}); err != nil {
return err
}
}
return nil
}
// listsPath reports whether the inode's entry lists path. Requires the lock.
func (i *InodeToPath) listsPath(inode uint64, path util.FullPath) bool {
ie := i.inode2path[inode]
if ie == nil {
return false
}
for _, p := range ie.appendPaths(nil) {
if p == path {
return true
}
}
return false
}
// handoverInodeTable is an inode table being decoded, in the final shapes of
// the maps it will become.
type handoverInodeTable struct {
inode2path map[uint64]*InodeEntry
path2inode map[util.FullPath]uint64
dirStates map[uint64]*dirState
dirPaths map[util.FullPath]*dirState
fixups []*hpb.NameFixup
forgotten []*hpb.Forgotten
}
func newHandoverInodeTable() *handoverInodeTable {
return &handoverInodeTable{
inode2path: make(map[uint64]*InodeEntry),
path2inode: make(map[util.FullPath]uint64),
dirStates: make(map[uint64]*dirState),
dirPaths: make(map[util.FullPath]*dirState),
}
}
func (t *handoverInodeTable) addInode(rec *hpb.Inode) error {
if _, dup := t.inode2path[rec.Inode]; dup {
return fmt.Errorf("inode %d appears twice", rec.Inode)
}
ie := &InodeEntry{path: util.FullPath(rec.Path), nlookup: rec.Nlookup}
if len(rec.Extra) > 0 {
extra := make([]util.FullPath, len(rec.Extra))
for n, p := range rec.Extra {
extra[n] = util.FullPath(p)
}
ie.extraPaths = &extra
}
t.inode2path[rec.Inode] = ie
for _, p := range ie.appendPaths(nil) {
t.path2inode[p] = rec.Inode
}
if rec.IsDir {
d := &dirState{path: ie.path, subdirCount: rec.Subdirs}
t.dirStates[rec.Inode] = d
if ie.path != "" {
t.dirPaths[ie.path] = d
}
}
return nil
}
// check refuses a table the kernel could not be served from.
func (t *handoverInodeTable) check() error {
if t.inode2path[1] == nil {
return errors.New("handover state has no root inode")
}
return nil
}
// installHandover replaces the tables of a fresh InodeToPath with the decoded
// ones. The caller has checked the table holds nothing but its root.
func (i *InodeToPath) installHandover(t *handoverInodeTable) {
for _, f := range t.fixups {
if f.Inode == 0 {
delete(t.path2inode, util.FullPath(f.Path))
} else {
t.path2inode[util.FullPath(f.Path)] = f.Inode
}
}
i.Lock()
defer i.Unlock()
i.inode2path = t.inode2path
i.path2inode = t.path2inode
i.dirStates = t.dirStates
i.dirPaths = t.dirPaths
i.wasCachedDirs = make(map[util.FullPath]uint64)
i.wasCachedOrder = nil
if i.forgotten == nil {
return
}
for _, f := range t.forgotten {
path := util.FullPath(f.Path)
i.forgotten.Add(f.Inode, path)
i.forgottenInodes[path] = f.Inode
}
}
+64
View File
@@ -0,0 +1,64 @@
//go:build !windows
package mount
import (
"bytes"
"fmt"
"runtime"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// Measures the export and import of a table of a million inodes (a thousand
// directories of a thousand files, a few with hard links) and checks the
// result. The numbers go to the test log.
func TestHandoverLargeInodeTable(t *testing.T) {
if testing.Short() {
t.Skip("large table")
}
const dirs, perDir = 1000, 1000
src := newHandoverWFS(t)
now := time.Now().Unix()
start := time.Now()
var last uint64
for d := 0; d < dirs; d++ {
dir := util.FullPath(fmt.Sprintf("/d%04d", d))
src.inodeToPath.Lookup(dir, now, true, false, 0, true)
for f := 0; f < perDir; f++ {
path := dir.Child(fmt.Sprintf("file-%06d.dat", f))
last = src.inodeToPath.Lookup(path, now, false, false, 0, true)
if f%250 == 0 { // a hard link
src.inodeToPath.Lookup(dir.Child(fmt.Sprintf("link-%06d", f)), now, false, true, last, true)
}
}
}
t.Logf("built %d inodes in %v", len(src.inodeToPath.inode2path), time.Since(start).Round(time.Millisecond))
var buf bytes.Buffer
start = time.Now()
if err := src.ExportHandoverState(&buf); err != nil {
t.Fatalf("export: %v", err)
}
encode := time.Since(start)
size := buf.Len()
var before, after runtime.MemStats
dst := newHandoverWFS(t)
runtime.GC()
runtime.ReadMemStats(&before)
start = time.Now()
if err := dst.ImportHandoverState(&buf); err != nil {
t.Fatalf("import: %v", err)
}
decode := time.Since(start)
runtime.ReadMemStats(&after)
n := len(src.inodeToPath.inode2path)
t.Logf("%d inodes: export %v (%.0f ns/inode), %d bytes (%.1f bytes/inode), import %v (%.0f ns/inode), import allocated %d MiB in total",
n, encode.Round(time.Millisecond), float64(encode.Nanoseconds())/float64(n), size, float64(size)/float64(n),
decode.Round(time.Millisecond), float64(decode.Nanoseconds())/float64(n), (after.TotalAlloc-before.TotalAlloc)>>20)
requireSameInodeTables(t, src.inodeToPath, dst.inodeToPath)
}
+138
View File
@@ -0,0 +1,138 @@
package mount
import (
"slices"
"github.com/seaweedfs/seaweedfs/weed/filer/posixlock"
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
)
// How the lock state crosses a handover:
//
// PosixLockTable.inodes[].locks crosses: the held byte-range and flock locks.
// PosixLockTable.inodes[].waiters empty: a blocked SETLKW is a request in flight. It is never
// answered with EINTR: the kernel turns that into a restart
// (ERESTARTSYS) only when the caller has a signal pending, and
// otherwise the application can see errno 512. Export refuses
// while one is blocked; the caller resumes serving and retries.
// inodeLocks.wakeRefs, dead empty/rebuilt: a woken waiter still retrying is a waiter.
// WFS.routedLockWaiters empty: the same for SETLKW polling a routed (-dlm) lock.
// WFS.fhLocks crosses: the owners per open fh, which RELEASE drains (the
// kernel sends no cleanup for OFD locks).
// WFS.posixSid crosses (identity): routed locks live on the filer under this
// session id with a 15 s lease renewed every 5 s; the importer
// takes the id, so the filer sees one continuous session. The
// keepalive loop only starts in StartBackgroundTasks, after the
// import, and reads the id at each tick.
// WFS.posixOwn crosses: the mirror of routed locks the keepalive re-asserts.
// WFS.posixHint crosses: which owners FLUSH must release.
// WFS.posixLostKeys dropped: only de-duplicates a warning.
//
// Whether locks are routed (crossMountLocks: -dlm without writeback cache)
// crosses in the identity, and the importer refuses another mode: it would look
// for the held locks in the place the exporter did not put them.
// captureLocalLocks copies the held locks of the local table, and reports the
// waiters that would be dropped.
func (wfs *WFS) captureLocalLocks() (sets []*hpb.LockSet, blockers handoverBlockers) {
plt := wfs.posixLocks
plt.mu.Lock()
defer plt.mu.Unlock()
for inode, il := range plt.inodes {
il.mu.Lock()
if il.dead {
il.mu.Unlock()
continue
}
if len(il.waiters) > 0 || il.wakeRefs > 0 {
blockers.add("inode %d: %d lock waiters still blocked", inode, len(il.waiters)+il.wakeRefs)
}
if len(il.locks) > 0 {
set := &hpb.LockSet{Inode: inode}
for _, l := range il.locks {
set.Locks = append(set.Locks, &hpb.Lock{Start: l.Start, End: l.End, Typ: l.Typ, Owner: l.Owner, Pid: l.Pid, IsFlock: l.IsFlock})
}
sets = append(sets, set)
}
il.mu.Unlock()
}
return sets, blockers
}
func (wfs *WFS) exportLocks(e *handoverEncoder, local []*hpb.LockSet) error {
for _, set := range local {
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_LockSet{LockSet: set}}); err != nil {
return err
}
}
var owners []*hpb.LockOwners
wfs.fhLocks.mu.Lock()
for fh, set := range wfs.fhLocks.m {
owners = append(owners, &hpb.LockOwners{Key: fh, Owners: sortedKeys(set)})
}
wfs.fhLocks.mu.Unlock()
for _, o := range owners {
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_FhLockOwners{FhLockOwners: o}}); err != nil {
return err
}
}
var hints []*hpb.LockOwners
wfs.posixHint.mu.Lock()
for inode, set := range wfs.posixHint.m {
hints = append(hints, &hpb.LockOwners{Key: inode, Owners: sortedKeys(set)})
}
wfs.posixHint.mu.Unlock()
for _, o := range hints {
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_LockHint{LockHint: o}}); err != nil {
return err
}
}
for key, ranges := range wfs.posixOwn.Snapshot() {
rec := &hpb.RoutedKey{Key: key}
for _, r := range ranges {
rec.Ranges = append(rec.Ranges, &hpb.RoutedRange{Start: r.Start, End: r.End, Type: r.Type, Sid: r.Sid, Owner: r.Owner, Pid: r.Pid, IsFlock: r.IsFlock, Principal: r.Principal})
}
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_RoutedKey{RoutedKey: rec}}); err != nil {
return err
}
}
return nil
}
func sortedKeys(set map[uint64]struct{}) []uint64 {
keys := make([]uint64, 0, len(set))
for k := range set {
keys = append(keys, k)
}
slices.Sort(keys)
return keys
}
func (wfs *WFS) importLocks(imp *handoverImport) {
plt := wfs.posixLocks
plt.mu.Lock()
for _, set := range imp.localLocks {
il := &inodeLocks{locks: make([]lockRange, len(set.Locks))}
for n, l := range set.Locks {
il.locks[n] = lockRange{Start: l.Start, End: l.End, Typ: l.Typ, Owner: l.Owner, Pid: l.Pid, IsFlock: l.IsFlock}
}
plt.inodes[set.Inode] = il
}
plt.mu.Unlock()
for _, rec := range imp.fhLocks {
for _, owner := range rec.Owners {
wfs.fhLocks.add(rec.Key, owner)
}
}
for _, rec := range imp.lockHints {
for _, owner := range rec.Owners {
wfs.posixHint.add(rec.Key, owner)
}
}
for _, rec := range imp.routed {
for _, r := range rec.Ranges {
wfs.posixOwn.Track(rec.Key, posixlock.Range{Start: r.Start, End: r.End, Type: r.Type, Sid: r.Sid, Owner: r.Owner, Pid: r.Pid, IsFlock: r.IsFlock, Principal: r.Principal})
}
}
}
+177
View File
@@ -0,0 +1,177 @@
package mount
import (
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// What else the mount keeps in memory that is keyed by a kernel-visible id,
// and how it crosses:
//
// atimeMap, dirMtimeMap cross (bounded, 8192 each): overlays on the attributes the
// kernel sees; dropped, times would step back to the filer's.
// removedDirs crosses: the only copy of a removed directory's entry, which
// serves fstat on a descriptor still open until the final forget.
// writebackContentErrors crosses, set flags only (writeback mode): the sticky refusal of
// an inode, until its forget; see handoverContentErrors.
// exportedHandles crosses its in-memory half (path, open count, pending removal,
// unwritten record, owner) with -nfsExport; the records themselves
// are on the filer already. Unwritten covers what the writer has
// queued and what it has taken but not finished, a removal too,
// which has neither path nor open count left.
// openMtimeCache dropped: only decides FOPEN_KEEP_CACHE, the next open refills it.
// refreshingDirs dropped: background directory refreshes, redone on demand.
// pendingAsyncFlush, asyncFlushWg, asyncCreates
// empty: export refuses while any is pending.
// hardLinkLockTable, fhLockTable, metadataPublicationLocks
// empty: locks of operations in flight, which the drain finished.
// readAuth, chunkProofs not carried: export refuses with a filer token configured.
// meta cache, chunk cache not carried: rebuilt (caches are a separate step).
// metadata subscription its position crosses (Identity.meta_resume_ts_ns).
func (wfs *WFS) exportOverlays(e *handoverEncoder) error {
var frames []*hpb.HandoverFrame
wfs.atimeMu.Lock()
for inode, t := range wfs.atimeMap {
frames = append(frames, &hpb.HandoverFrame{Body: &hpb.HandoverFrame_Atime{Atime: &hpb.InodeTime{Inode: inode, UnixNanos: t.UnixNano()}}})
}
wfs.atimeMu.Unlock()
wfs.dirMtimeMu.Lock()
for inode, t := range wfs.dirMtimeMap {
frames = append(frames, &hpb.HandoverFrame{Body: &hpb.HandoverFrame_DirMtime{DirMtime: &hpb.InodeTime{Inode: inode, UnixNanos: t.UnixNano()}}})
}
wfs.dirMtimeMu.Unlock()
wfs.removedDirMu.Lock()
for inode, entry := range wfs.removedDirs {
frames = append(frames, &hpb.HandoverFrame{Body: &hpb.HandoverFrame_RemovedDir{RemovedDir: &hpb.RemovedDir{Inode: inode, Entry: proto.Clone(entry).(*filer_pb.Entry)}}})
}
wfs.removedDirMu.Unlock()
for _, rec := range wfs.exportContentErrors() {
frames = append(frames, &hpb.HandoverFrame{Body: &hpb.HandoverFrame_ContentError{ContentError: rec}})
}
for _, rec := range wfs.exportedHandles.capture() {
frames = append(frames, &hpb.HandoverFrame{Body: &hpb.HandoverFrame_NfsRecord{NfsRecord: rec}})
}
for _, f := range frames {
if err := e.write(f); err != nil {
return err
}
}
return nil
}
func (wfs *WFS) importOverlays(imp *handoverImport) {
wfs.atimeMu.Lock()
for _, r := range imp.atimes {
wfs.atimeMap[r.Inode] = time.Unix(0, r.UnixNanos)
}
wfs.atimeMu.Unlock()
wfs.dirMtimeMu.Lock()
for _, r := range imp.dirMtimes {
wfs.dirMtimeMap[r.Inode] = time.Unix(0, r.UnixNanos)
}
wfs.dirMtimeMu.Unlock()
if len(imp.removedDirs) > 0 {
wfs.removedDirMu.Lock()
if wfs.removedDirs == nil {
wfs.removedDirs = make(map[uint64]*filer_pb.Entry, len(imp.removedDirs))
}
for _, r := range imp.removedDirs {
wfs.removedDirs[r.Inode] = r.Entry
}
wfs.removedDirMu.Unlock()
}
wfs.exportedHandles.restore(imp.identity.NfsOwner, imp.nfs)
}
// capture lists the in-memory records of the nfs export registrations. A nil
// receiver (nfs export off) has none.
//
// A record is dirty when the filer does not hold its latest state for sure:
// the writer has it queued, has its write in flight, or waits to retry one that
// failed. The export stopped the writer first (handOver), so the successor,
// which registers under the same owner, writes these and no write of this
// process lands after its own. An inode whose removal timer has fired is only
// in the writer's hands, with no path and no open left, and its record says
// just that: dirty, and no path.
func (h *exportedHandles) capture() []*hpb.NfsRecord {
if h == nil {
return nil
}
h.mu.Lock()
defer h.mu.Unlock()
inodes := make(map[uint64]struct{}, len(h.paths)+len(h.opens)+len(h.dirty)+len(h.unwritten))
for inode := range h.paths {
inodes[inode] = struct{}{}
}
for inode := range h.opens {
inodes[inode] = struct{}{}
}
for inode := range h.dirty {
inodes[inode] = struct{}{}
}
for inode := range h.unwritten {
inodes[inode] = struct{}{}
}
records := make([]*hpb.NfsRecord, 0, len(inodes))
for inode := range inodes {
_, pendingRemoval := h.removals[inode]
_, queued := h.dirty[inode]
records = append(records, &hpb.NfsRecord{
Inode: inode,
Path: string(h.paths[inode]),
Opens: int64(h.opens[inode]),
PendingRemoval: pendingRemoval,
Dirty: queued || h.unwritten[inode] > 0,
})
}
return records
}
// restore installs records captured by another process. A record whose file
// was closed starts its removal timer again; one whose write had not reached
// the filer is written by the background loop, as it would have been: with no
// path, that write removes this mount's registration. The owner is the
// exporter's: a successor in a new pod has another hostname, and would
// otherwise neither replace nor remove the registrations already on the filer.
func (h *exportedHandles) restore(owner uint32, records []*hpb.NfsRecord) {
if h == nil {
return
}
h.mu.Lock()
defer h.mu.Unlock()
if owner != 0 {
h.owner = owner
}
for _, r := range records {
inode := r.Inode
if r.Path != "" {
h.paths[inode] = util.FullPath(r.Path)
}
if r.Opens > 0 {
h.opens[inode] = int(r.Opens)
}
if r.Dirty {
h.markDirty(inode)
}
if r.PendingRemoval && r.Opens <= 0 {
var t *time.Timer
t = time.AfterFunc(h.delay, func() {
h.mu.Lock()
defer h.mu.Unlock()
if h.removals[inode] != t {
return
}
delete(h.removals, inode)
delete(h.paths, inode)
h.markDirty(inode)
})
h.removals[inode] = t
}
}
}
+466
View File
@@ -0,0 +1,466 @@
package mount
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"hash"
"hash/crc32"
"io"
"strings"
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/glog"
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
)
// Handover state: what a new `weed mount` process needs, beyond the FUSE
// connection itself, to answer the requests the kernel still holds ids for.
// The kernel keeps referring to node ids (inodes, with lookup counts) and to
// file and directory handle ids that this process handed out; the successor
// must resolve exactly the same ids.
//
// Stream layout (schema in weed/pb/mount_handover.proto):
//
// magic (8 bytes) | format version (uint32, big endian) |
// frames: uvarint length, then a HandoverFrame message, one record each |
// a last frame, End, carrying the CRC-32 (IEEE) of everything before it.
//
// Protobuf, framed per record, so the inode table (millions of records) is
// encoded one record at a time and decoded straight into the table's final
// maps: neither side holds the encoding or a second copy of the table. It also
// keeps the state readable across builds, which a handover between two
// releases needs, as the newer importer reads what the older exporter wrote:
// fields are only added, and unknown fields and frame bodies are ignored.
// Entries are filer_pb.Entry. The format version changes only for a change an
// old reader could not survive; an importer refuses a version it does not
// know, and its caller keeps the old process serving.
//
// Import decodes everything into private structures and verifies the checksum
// before it touches the WFS, so a truncated or corrupt stream changes nothing.
//
// The state carries chunk cipher keys (they are part of file entries): send it
// over a private channel such as a unix socket, never to disk.
//
// Filer tokens (-filer.tokenFile): the read tokens and chunk assignment proofs
// (readAuth, chunkProofs) are not carried, so a mount with a token source
// refuses to export instead.
const (
handoverMagic = "SWMNTHO\x00"
handoverFormatVersion = uint32(1)
// handoverMaxFrame bounds one record; a file entry with a huge chunk list
// is the largest.
handoverMaxFrame = 1 << 30
)
// handoverBlockers collects the reasons an export is refused, so the caller
// sees all of them at once rather than one per attempt.
type handoverBlockers []string
func (b *handoverBlockers) add(format string, args ...any) {
*b = append(*b, fmt.Sprintf(format, args...))
}
func (b handoverBlockers) err() error {
if len(b) == 0 {
return nil
}
const shown = 8
list := b
more := ""
if len(list) > shown {
more = fmt.Sprintf(" (and %d more)", len(list)-shown)
list = list[:shown]
}
return fmt.Errorf("mount state cannot be handed over: %s%s", strings.Join(list, "; "), more)
}
type handoverEncoder struct {
w io.Writer
crc hash.Hash32
frames uint64
buf []byte
}
func (e *handoverEncoder) write(frame *hpb.HandoverFrame) error {
var err error
e.buf, err = proto.MarshalOptions{}.MarshalAppend(e.buf[:0], frame)
if err != nil {
return err
}
var prefix [binary.MaxVarintLen64]byte
n := binary.PutUvarint(prefix[:], uint64(len(e.buf)))
e.crc.Write(prefix[:n])
e.crc.Write(e.buf)
e.frames++
if _, err := e.w.Write(prefix[:n]); err != nil {
return err
}
_, err = e.w.Write(e.buf)
return err
}
// ExportHandoverState writes the state a successor process needs to serve the
// kernel's existing node and handle ids. The caller must have stopped reading
// FUSE requests and drained those in flight (go-fuse Server.Stop), must have
// ended the metadata subscription (stopMetadataFollow), and should have run
// FlushForHandover; nothing here talks to the filer.
//
// It refuses, naming every cause, when something cannot be carried safely: a
// file handle with dirty pages, uploads in flight or a deferred close flush; a
// handle busy under its lock (a delete, rename or flush still running); an
// unpublished create (it exists only as a placeholder in the meta cache, which
// does not cross); a lock waiter still blocked, in the local table or polling
// a routed lock (it is never answered with EINTR, which the kernel turns into
// a restart only for a caller with a signal pending); a background create or
// close flush; a metadata subscription still running, or events of it that
// did not reach the open files in time; an nfs export record still being
// written; a filer token. The caller then resumes serving. The inode table is
// read under its lock while it is encoded, so w must not block for long.
func (wfs *WFS) ExportHandoverState(w io.Writer) (err error) {
var blockers handoverBlockers
if wfs.option.FilerTokenSource != nil || wfs.chunkProofs != nil {
blockers.add("a filer token is configured: read tokens and chunk proofs do not cross")
}
// Before the handle locks: the invalidation worker takes them.
metaResumeTsNs, eventBlockers := wfs.settleMetadataEvents()
blockers = append(blockers, eventBlockers...)
handles, release, handleBlockers := wfs.lockHandlesForHandover()
defer release()
blockers = append(blockers, handleBlockers...)
locks, lockBlockers := wfs.captureLocalLocks()
blockers = append(blockers, lockBlockers...)
if n := wfs.routedLockWaiters.Load(); n > 0 {
blockers.add("%d routed lock requests still waiting", n)
}
dirHandles, dirBlockers := wfs.captureDirHandles()
blockers = append(blockers, dirBlockers...)
wfs.pendingAsyncFlushMu.Lock()
pending := len(wfs.pendingAsyncFlush)
wfs.pendingAsyncFlushMu.Unlock()
if pending > 0 {
blockers.add("%d closed files still flush in the background", pending)
}
if n := wfs.asyncCreates.Load(); n > 0 {
blockers.add("%d file creates are still being sent to the filer", n)
}
if err := wfs.exportedHandles.handOver(handoverEventSettleWait); err != nil {
blockers.add("%v", err)
}
defer func() {
if err != nil {
wfs.exportedHandles.resume()
}
}()
if err := blockers.err(); err != nil {
return err
}
bw := bufio.NewWriterSize(w, 1<<16)
if _, err := bw.WriteString(handoverMagic); err != nil {
return err
}
if err := binary.Write(bw, binary.BigEndian, handoverFormatVersion); err != nil {
return err
}
crc := crc32.NewIEEE()
e := &handoverEncoder{w: bw, crc: crc}
identity := &hpb.Identity{
MountRoot: wfs.option.FilerMountRootPath,
Writeback: wfs.option.WritebackCache,
NfsExport: wfs.exportedHandles != nil,
Signature: wfs.signature,
PosixSid: wfs.posixSid,
MetaResumeTsNs: metaResumeTsNs,
RoutedLocks: wfs.crossMountLocks(),
}
if wfs.exportedHandles != nil {
identity.NfsOwner = wfs.exportedHandles.owner
}
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_Identity{Identity: identity}}); err != nil {
return err
}
if err := wfs.inodeToPath.exportHandover(e); err != nil {
return err
}
if err := wfs.exportFileHandles(e, handles); err != nil {
return err
}
for _, dh := range dirHandles {
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_DirHandle{DirHandle: dh}}); err != nil {
return err
}
}
if err := wfs.exportLocks(e, locks); err != nil {
return err
}
if err := wfs.exportOverlays(e); err != nil {
return err
}
end := &hpb.End{Crc32: crc.Sum32(), Frames: e.frames}
// The end frame is outside its own checksum.
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_End{End: end}}); err != nil {
return err
}
return bw.Flush()
}
// handoverEventSettleWait bounds how long an export waits for the metadata
// events already received to reach the open files. A variable for tests.
var handoverEventSettleWait = 5 * time.Second
// handoverEventSettleStarted is called when an export starts that wait, with
// the subscription's position already taken. A hook for tests.
var handoverEventSettleStarted = func() {}
// settleMetadataEvents returns the log position the successor resumes the
// metadata subscription from, once every event up to it has had its effect on
// the state exported next. The subscription moves its position on as soon as an
// event is in the meta cache, while what the event does to the inode table and
// to the open handles (a rename by another mount, a newer entry) is queued for
// the invalidation worker. An export between the two would carry the position
// without the change, and the successor, resuming behind the event, would
// never apply it. So the subscription has to be over, or it would keep feeding
// the worker, and the worker has to be through what it holds. The wait is
// bounded: the worker may sit in a kernel notification that needs a request
// served, which no one does while the FUSE server is stopped.
func (wfs *WFS) settleMetadataEvents() (resumeTsNs int64, blockers handoverBlockers) {
if wfs.metaCache == nil {
return 0, nil
}
if wfs.metaFollowers.Load() > 0 {
blockers.add("the metadata subscription is still running")
return 0, blockers
}
resumeTsNs = wfs.metaCache.SubscribedTsNs()
handoverEventSettleStarted()
if !wfs.metaCache.WaitForEntryInvalidationsWithin(handoverEventSettleWait) {
blockers.add("metadata events are still being applied to the open files")
}
return resumeTsNs, blockers
}
// handoverImport is a decoded stream, held apart from the WFS until it has
// been verified in full.
type handoverImport struct {
identity *hpb.Identity
inodes *handoverInodeTable
fileHandles []*hpb.FileHandle
dirHandles []*hpb.DirHandle
localLocks []*hpb.LockSet
fhLocks []*hpb.LockOwners
lockHints []*hpb.LockOwners
routed []*hpb.RoutedKey
nfs []*hpb.NfsRecord
atimes []*hpb.InodeTime
dirMtimes []*hpb.InodeTime
removedDirs []*hpb.RemovedDir
contentErrs []*hpb.ContentError
}
// ImportHandoverState installs the state ExportHandoverState wrote into a WFS
// that has just been constructed: before StartBackgroundTasks, before any
// request is served, with nothing opened or looked up. It makes no filer call.
// A stream that is truncated, corrupt, of an unknown version or meant for
// another mount root, cache mode or lock mode (-dlm) is refused before anything
// is changed, and so is a WFS that already holds state. Afterwards
// NewServerFromDev can serve the connection: the kernel's ids resolve as they
// did in the old process, file handles read, write, flush and release like
// live ones and refresh their entries lazily, directory listings in progress
// continue where the kernel is, and the metadata subscription resumes from the
// exported position instead of the start time.
//
// The stream is read through a buffer, which may take more from r than the
// state. A caller with more to read after it, such as the rest of a handover
// conversation on the same socket, passes its own *bufio.Reader: that one is
// used as it is, and is left right behind the End frame.
func (wfs *WFS) ImportHandoverState(r io.Reader) error {
br, ok := r.(*bufio.Reader)
if !ok {
br = bufio.NewReaderSize(r, 1<<16)
}
magic := make([]byte, len(handoverMagic))
if _, err := io.ReadFull(br, magic); err != nil {
return fmt.Errorf("read handover state header: %w", unexpectedEOF(err))
}
if string(magic) != handoverMagic {
return errors.New("handover state: bad magic")
}
var version uint32
if err := binary.Read(br, binary.BigEndian, &version); err != nil {
return fmt.Errorf("read handover state version: %w", unexpectedEOF(err))
}
if version != handoverFormatVersion {
return fmt.Errorf("handover state: format version %d, this build reads %d", version, handoverFormatVersion)
}
crc := crc32.NewIEEE()
imp := &handoverImport{}
var buf []byte
var frames uint64
for {
length, err := binary.ReadUvarint(br)
if err != nil {
return fmt.Errorf("handover state: read frame length: %w", unexpectedEOF(err))
}
if length > handoverMaxFrame {
return fmt.Errorf("handover state: frame of %d bytes", length)
}
if uint64(cap(buf)) < length {
buf = make([]byte, length)
}
buf = buf[:length]
if _, err := io.ReadFull(br, buf); err != nil {
return fmt.Errorf("handover state: read frame: %w", unexpectedEOF(err))
}
frame := &hpb.HandoverFrame{}
if err := proto.Unmarshal(buf, frame); err != nil {
return fmt.Errorf("handover state: decode frame: %w", err)
}
if end := frame.GetEnd(); end != nil {
if end.Crc32 != crc.Sum32() || end.Frames != frames {
return fmt.Errorf("handover state: checksum or frame count mismatch (stream %08x/%d, computed %08x/%d)", end.Crc32, end.Frames, crc.Sum32(), frames)
}
break
}
var prefix [binary.MaxVarintLen64]byte
crc.Write(prefix[:binary.PutUvarint(prefix[:], length)])
crc.Write(buf)
frames++
if err := imp.add(frame); err != nil {
return fmt.Errorf("handover state: %w", err)
}
}
if imp.identity == nil || imp.inodes == nil {
return errors.New("handover state: identity or inode table missing")
}
return wfs.installHandover(imp)
}
func unexpectedEOF(err error) error {
if errors.Is(err, io.EOF) {
return io.ErrUnexpectedEOF
}
return err
}
// add files one decoded frame. A body this build does not know is skipped.
func (imp *handoverImport) add(frame *hpb.HandoverFrame) error {
switch body := frame.Body.(type) {
case *hpb.HandoverFrame_Identity:
imp.identity = body.Identity
case *hpb.HandoverFrame_Inode:
return imp.table().addInode(body.Inode)
case *hpb.HandoverFrame_NameFixup:
imp.table().fixups = append(imp.table().fixups, body.NameFixup)
case *hpb.HandoverFrame_Forgotten:
imp.table().forgotten = append(imp.table().forgotten, body.Forgotten)
case *hpb.HandoverFrame_FileHandle:
imp.fileHandles = append(imp.fileHandles, body.FileHandle)
case *hpb.HandoverFrame_DirHandle:
imp.dirHandles = append(imp.dirHandles, body.DirHandle)
case *hpb.HandoverFrame_LockSet:
imp.localLocks = append(imp.localLocks, body.LockSet)
case *hpb.HandoverFrame_FhLockOwners:
imp.fhLocks = append(imp.fhLocks, body.FhLockOwners)
case *hpb.HandoverFrame_LockHint:
imp.lockHints = append(imp.lockHints, body.LockHint)
case *hpb.HandoverFrame_RoutedKey:
imp.routed = append(imp.routed, body.RoutedKey)
case *hpb.HandoverFrame_NfsRecord:
imp.nfs = append(imp.nfs, body.NfsRecord)
case *hpb.HandoverFrame_Atime:
imp.atimes = append(imp.atimes, body.Atime)
case *hpb.HandoverFrame_DirMtime:
imp.dirMtimes = append(imp.dirMtimes, body.DirMtime)
case *hpb.HandoverFrame_RemovedDir:
imp.removedDirs = append(imp.removedDirs, body.RemovedDir)
case *hpb.HandoverFrame_ContentError:
imp.contentErrs = append(imp.contentErrs, body.ContentError)
}
return nil
}
func (imp *handoverImport) table() *handoverInodeTable {
if imp.inodes == nil {
imp.inodes = newHandoverInodeTable()
}
return imp.inodes
}
// installHandover puts a verified import into the WFS. Everything that can
// fail on the data is checked before the first map is replaced.
func (wfs *WFS) installHandover(imp *handoverImport) error {
if imp.identity.MountRoot != wfs.option.FilerMountRootPath {
return fmt.Errorf("handover state is for mount root %q, this mount serves %q", imp.identity.MountRoot, wfs.option.FilerMountRootPath)
}
if imp.identity.Writeback != wfs.option.WritebackCache {
return fmt.Errorf("handover state was exported with writebackCache=%v, this mount runs with %v", imp.identity.Writeback, wfs.option.WritebackCache)
}
// The held locks are either in the mount's table or on the filer, and each
// mode only asks its own place: with another mode here, a lock an
// application holds would no longer exclude anyone, and one held on the
// filer would lose the keepalive that renews its lease.
if imp.identity.RoutedLocks != wfs.crossMountLocks() {
return fmt.Errorf("handover state was exported with distributed locks (-dlm) in effect=%v, this mount runs with %v", imp.identity.RoutedLocks, wfs.crossMountLocks())
}
if err := wfs.requireFreshForHandover(); err != nil {
return err
}
if err := imp.inodes.check(); err != nil {
return err
}
if err := checkHandoverHandles(imp); err != nil {
return err
}
dirHandles := restoreDirHandles(imp.dirHandles)
if imp.identity.NfsExport && wfs.exportedHandles == nil && len(imp.nfs) > 0 {
glog.Warningf("handover: dropping %d nfs export records, this mount does not register them", len(imp.nfs))
}
wfs.signature = imp.identity.Signature
wfs.posixSid = imp.identity.PosixSid
wfs.handoverMetaTsNs = imp.identity.MetaResumeTsNs
if wfs.metaCache != nil {
// Also what this process exports, should it hand over before its own
// subscription started.
wfs.metaCache.NoteSubscribedTsNs(wfs.handoverMetaTsNs)
}
wfs.inodeToPath.installHandover(imp.inodes)
wfs.importContentErrors(imp.contentErrs)
wfs.installFileHandles(imp.fileHandles)
wfs.dhMap.Lock()
for id, dh := range dirHandles {
wfs.dhMap.dir2inode[id] = dh
}
wfs.dhMap.Unlock()
wfs.importLocks(imp)
wfs.importOverlays(imp)
return nil
}
// requireFreshForHandover refuses a WFS that already serves or holds state:
// the import replaces the tables, so it would silently drop what they hold.
func (wfs *WFS) requireFreshForHandover() error {
wfs.inodeToPath.RLock()
inodes := len(wfs.inodeToPath.inode2path)
wfs.inodeToPath.RUnlock()
wfs.fhMap.RLock()
handles := len(wfs.fhMap.inode2fh) + len(wfs.fhMap.fh2inode)
wfs.fhMap.RUnlock()
wfs.dhMap.Lock()
dirHandles := len(wfs.dhMap.dir2inode)
wfs.dhMap.Unlock()
wfs.posixLocks.mu.Lock()
locks := len(wfs.posixLocks.inodes)
wfs.posixLocks.mu.Unlock()
if inodes > 1 || handles > 0 || dirHandles > 0 || locks > 0 {
return fmt.Errorf("handover state can only be imported into a fresh mount (inodes %d, file handles %d, directory handles %d, lock tables %d)", inodes, handles, dirHandles, locks)
}
return nil
}
File diff suppressed because it is too large. Load diff
+40
View File
@@ -44,6 +44,7 @@ type MetaCache struct {
isCachedFn func(fullpath util.FullPath) bool
invalidateFunc func(EntryInvalidation)
onDirectoryUpdate func(dir util.FullPath)
subscribedTsNs atomic.Int64 // log position of the last subscribed event handled; see SubscribedTsNs
pinnedChildFn func(*filer.Entry) bool // a child a rebuild must not drop (local-only, not yet on the filer); nil disables
dropListingFn func(dir util.FullPath) // drops a directory's cached listing; see dropListingsOf. nil disables
visitGroup singleflight.Group // deduplicates concurrent EnsureVisited calls for the same path
@@ -1345,6 +1346,26 @@ func (mc *MetaCache) WaitForEntryInvalidations() {
mc.invalidateWorker.Drain()
}
// WaitForEntryInvalidationsWithin is WaitForEntryInvalidations with a bound:
// it reports whether every invalidation enqueued before the call was
// processed in time. One can wait long, for a handle lock or for the kernel to
// take a notification.
func (mc *MetaCache) WaitForEntryInvalidationsWithin(timeout time.Duration) bool {
done := make(chan struct{})
go func() {
mc.invalidateWorker.Drain()
close(done)
}()
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-done:
return true
case <-timer.C:
return false
}
}
func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *filer_pb.SubscribeMetadataResponse, options MetadataResponseApplyOptions, allowUncachedInsert bool) (metadataResponseSideEffects, error) {
message := resp.GetEventNotification()
if message == nil {
@@ -1792,3 +1813,22 @@ func collectEntryInvalidations(resp *filer_pb.SubscribeMetadataResponse) []Entry
return invalidations
}
// SubscribedTsNs is the log position of the last event the metadata
// subscription handled, applied or skipped as the mount's own. A successor
// process resumes the subscription from it. 0 before the first event. The
// event is in the cache by then, but its entry invalidations may still be
// queued: see WaitForEntryInvalidationsWithin.
func (mc *MetaCache) SubscribedTsNs() int64 {
return mc.subscribedTsNs.Load()
}
// NoteSubscribedTsNs records the log position of a handled subscribed event.
func (mc *MetaCache) NoteSubscribedTsNs(tsNs int64) {
for {
current := mc.subscribedTsNs.Load()
if tsNs <= current || mc.subscribedTsNs.CompareAndSwap(current, tsNs) {
return
}
}
}
@@ -117,11 +117,16 @@ func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32
for _, sig := range resp.EventNotification.Signatures {
if sig == selfSignature {
glog.V(4).Infof("skip self-originated event %s", resp.Directory)
mc.NoteSubscribedTsNs(resp.TsNs)
return nil
}
}
}
return applySubscribedEvent(mc, resp)
if err := applySubscribedEvent(mc, resp); err != nil {
return err
}
mc.NoteSubscribedTsNs(resp.TsNs)
return nil
}
prefix := dir
+28 -3
View File
@@ -202,7 +202,14 @@ type WFS struct {
posixHint *posixLockHint // local fcntl-lock hint for routed mode
posixOwn *posixlock.Manager // mirror of locks this mount holds, re-asserted via keepalive
posixLostKeys sync.Map // keys whose lock loss was already reported, see notePosixLockLoss
fhLocks fhLockOwners // non-flock lock owners per open fh, drained at release
// routedLockWaiters counts SetLkw calls polling the filer for a routed lock.
routedLockWaiters atomic.Int64
// asyncCreates counts file creates being sent to the filer in the background.
asyncCreates atomic.Int64
// handoverMetaTsNs, set by ImportHandoverState, is the log position the
// metadata subscription resumes from instead of the start time.
handoverMetaTsNs int64
fhLocks fhLockOwners // non-flock lock owners per open fh, drained at release
peerRegistrar *PeerRegistrar
peerDirectory *PeerDirectory
peerGrpcServer *PeerGrpcServer
@@ -245,6 +252,9 @@ type WFS struct {
metaFollowMu sync.Mutex
metaFollowCancel context.CancelFunc
metaFollowWg sync.WaitGroup
// metaFollowers counts the subscription goroutines metaFollowWg tracks,
// for a caller that must not wait: a handover exports only at zero.
metaFollowers atomic.Int32
// entryChanged is notified of every applied metadata event, for a front
// end that has to push invalidations to its own client.
@@ -556,8 +566,7 @@ func (wfs *WFS) StartBackgroundTasks() error {
return err
}
startTime := time.Now()
wfs.followMetadataUpdates(startTime, follower)
wfs.followMetadataUpdates(wfs.metadataFollowStart(), follower)
go wfs.loopCheckQuota()
go wfs.loopFlushDirtyMetadata()
go wfs.loopEvictIdleDirCache()
@@ -569,6 +578,20 @@ func (wfs *WFS) StartBackgroundTasks() error {
return nil
}
// metadataFollowStart is where the metadata subscription starts: now, or the
// position a predecessor process handed over. It is also recorded as the
// subscription's position, so a mount that hands over before its first event
// passes on where it started rather than nothing: its successor would
// otherwise start at its own start time and miss the events in between.
func (wfs *WFS) metadataFollowStart() time.Time {
startTime := time.Now()
if wfs.handoverMetaTsNs > 0 {
startTime = time.Unix(0, wfs.handoverMetaTsNs)
}
wfs.metaCache.NoteSubscribedTsNs(startTime.UnixNano())
return startTime
}
// followMetadataUpdates starts the subscription that keeps the meta cache
// current, tracked so unmount can end it. See stopMetadataFollow.
func (wfs *WFS) followMetadataUpdates(startTime time.Time, follower *meta_cache.MetadataFollower) {
@@ -580,10 +603,12 @@ func (wfs *WFS) followMetadataUpdates(startTime time.Time, follower *meta_cache.
wfs.metaFollowMu.Lock()
wfs.metaFollowCancel = cancel
wfs.metaFollowWg.Add(1)
wfs.metaFollowers.Add(1)
wfs.metaFollowMu.Unlock()
go func() {
defer wfs.metaFollowWg.Done()
defer wfs.metaFollowers.Add(-1)
meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, wfs.subscriptionCredentials(), func(lastTsNs int64, err error) {
glog.Warningf("meta events follow retry from %v: %v", time.Unix(0, lastTsNs), err)
// A subscription gap may have dropped events.
+2
View File
@@ -611,7 +611,9 @@ func (wfs *WFS) asyncCreateEntry(dirFullPath util.FullPath, entry *filer_pb.Entr
requestEntry := proto.Clone(entry).(*filer_pb.Entry)
dir := string(dirFullPath)
entryPath := dirFullPath.Child(entry.Name)
wfs.asyncCreates.Add(1)
go func() {
defer wfs.asyncCreates.Add(-1)
wfs.mapPbIdFromLocalToFiler(requestEntry)
request := &filer_pb.CreateEntryRequest{
Directory: dir,
+89 -1
View File
@@ -58,8 +58,21 @@ type exportedHandles struct {
// currentPath, when set, gives the inode's path as the mount knows it now,
// which a rename moves before it updates the open handles.
currentPath func(inode uint64) util.FullPath
// unwritten counts, per inode, the writes the writer took from dirty and
// has not finished: in flight, or failed and waiting for the retry. A
// handover carries these as dirty, since they are lost with the process.
unwritten map[uint64]int
// handedOver stops the writer once an export is under way: the successor
// owns the same registrations, and a write of this process landing after
// one of its own would take the record back.
handedOver bool
// putting is closed when the put the writer has sent returns; nil when it
// has none.
putting chan struct{}
}
var errHandedOver = errors.New("handed over")
func newExportedHandles(owner uint32, put func(key, value []byte) error, get func(ctx context.Context, key []byte) ([]byte, error), lock func(inode uint64) (unlock func(), err error)) *exportedHandles {
h := &exportedHandles{
owner: owner,
@@ -73,6 +86,7 @@ func newExportedHandles(owner uint32, put func(key, value []byte) error, get fun
get: get,
lock: lock,
}
h.unwritten = make(map[uint64]int)
go h.loop()
return h
}
@@ -89,6 +103,10 @@ func (h *exportedHandles) loop() {
for range h.wake {
for {
h.mu.Lock()
if h.handedOver {
h.mu.Unlock()
break
}
var inode uint64
found := false
for inode = range h.dirty {
@@ -100,22 +118,42 @@ func (h *exportedHandles) loop() {
break
}
delete(h.dirty, inode)
h.unwritten[inode]++
path := h.paths[inode]
h.mu.Unlock()
if err := h.write(inode, path); err != nil {
if err := h.write(inode, path); errors.Is(err, errHandedOver) {
h.mu.Lock()
h.written(inode)
h.markDirty(inode)
h.mu.Unlock()
continue
} else if err != nil {
glog.Warningf("record nfs export handle %d %q: %v", inode, path, err)
time.AfterFunc(exportedHandleRetryDelay, func() {
h.mu.Lock()
defer h.mu.Unlock()
h.written(inode)
if h.paths[inode] == path {
h.markDirty(inode)
}
})
continue
}
h.mu.Lock()
h.written(inode)
h.mu.Unlock()
}
}
}
// written ends one count of unwritten: the write is done, or the wait for its
// retry is over. The caller holds mu.
func (h *exportedHandles) written(inode uint64) {
if h.unwritten[inode]--; h.unwritten[inode] <= 0 {
delete(h.unwritten, inode)
}
}
// write replaces this mount's registration of the inode with path, or drops
// it when path is empty, keeping those of other mounts. The filer KV has no
// compare-and-swap, so mounts take turns on a record through the lock manager
@@ -149,9 +187,59 @@ func (h *exportedHandles) write(inode uint64, path util.FullPath) error {
kept = kept[len(kept)-maxExportedHandleRegistrations:]
}
}
h.mu.Lock()
if h.handedOver {
h.mu.Unlock()
return errHandedOver
}
putting := make(chan struct{})
h.putting = putting
h.mu.Unlock()
defer func() {
h.mu.Lock()
h.putting = nil
h.mu.Unlock()
close(putting)
}()
return h.put(key, formatExportedHandle(kept))
}
// handOver stops the writer for an export, and waits up to wait for a put it
// has already sent: no write of this process may land after the successor's.
// A write not yet at its put drops it and stays dirty.
func (h *exportedHandles) handOver(wait time.Duration) error {
if h == nil {
return nil
}
h.mu.Lock()
h.handedOver = true
putting := h.putting
h.mu.Unlock()
if putting == nil {
return nil
}
select {
case <-putting:
return nil
case <-time.After(wait):
return errors.New("an nfs export record is still being written to the filer")
}
}
// resume restarts the writer after an export that did not go through.
func (h *exportedHandles) resume() {
if h == nil {
return
}
h.mu.Lock()
defer h.mu.Unlock()
h.handedOver = false
select {
case h.wake <- struct{}{}:
default:
}
}
type exportedHandleRegistration struct {
owner uint32
path util.FullPath
+2
View File
@@ -224,6 +224,8 @@ func (wfs *WFS) routedSetLkw(cancel <-chan struct{}, in *fuse.LkIn) fuse.Status
}
ctx, done := posixLockContext(cancel)
defer done()
wfs.routedLockWaiters.Add(1)
defer wfs.routedLockWaiters.Add(-1)
status := posixPollAcquire(cancel, func() (bool, error) {
resp, err := wfs.callPosixLock(ctx, key, filer_pb.PosixLockOp_TRY_LOCK, lk)
if err != nil {
+2
View File
@@ -9,6 +9,8 @@ gen:
protoc remote.proto --go_out=./remote_pb --go-grpc_out=./remote_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc iam.proto --go_out=./iam_pb --go-grpc_out=./iam_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc mount.proto --go_out=./mount_pb --go-grpc_out=./mount_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
mkdir -p ./mount_handover_pb
protoc mount_handover.proto --go_out=./mount_handover_pb --go_opt=paths=source_relative
mkdir -p ./mount_peer_pb
protoc mount_peer.proto --go_out=./mount_peer_pb --go-grpc_out=./mount_peer_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc s3.proto --go_out=./s3_pb --go-grpc_out=./s3_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
+188
View File
@@ -0,0 +1,188 @@
syntax = "proto3";
package mount_handover_pb;
import "filer.proto";
option go_package = "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb";
option java_package = "seaweedfs.client";
option java_outer_classname = "MountHandoverProto";
// The in-memory state a new `weed mount` process needs to take over a live
// FUSE connection from the old one (see weed/mount/handover_state.go).
//
// The stream is a small raw header (magic, format version) followed by
// length-delimited HandoverFrame messages, one record each, so a table of
// millions of inodes is neither encoded nor decoded as a whole. The last frame
// is End, carrying the CRC-32 of all frames before it. Fields are only ever
// added; a reader ignores fields and frame bodies it does not know, so a newer
// build imports what an older one exported.
message HandoverFrame {
oneof body {
Identity identity = 1;
Inode inode = 2;
NameFixup name_fixup = 3;
Forgotten forgotten = 4;
FileHandle file_handle = 5;
DirHandle dir_handle = 6;
LockSet lock_set = 7;
LockOwners fh_lock_owners = 8;
LockOwners lock_hint = 9;
RoutedKey routed_key = 10;
NfsRecord nfs_record = 11;
InodeTime atime = 12;
InodeTime dir_mtime = 13;
RemovedDir removed_dir = 14;
ContentError content_error = 15;
End end = 100;
}
}
message Identity {
string mount_root = 1;
bool writeback = 2;
bool nfs_export = 3;
// the id this mount stamps on its filer mutations
int32 signature = 4;
// the session id of its routed (-dlm) locks
uint64 posix_sid = 5;
// ts_ns of the last metadata event processed; the subscription resumes there
int64 meta_resume_ts_ns = 6;
// advisory locks are held on the filer (-dlm without writeback cache), not in
// the mount's own table; a successor must keep them where they are
bool routed_locks = 7;
// the owner its nfs export registrations are stored under (-nfsExport)
uint32 nfs_owner = 8;
}
message Inode {
uint64 inode = 1;
uint64 nlookup = 2;
string path = 3; // empty: the last name was removed, the kernel still holds the inode
repeated string extra = 4; // other names of a hard link
bool is_dir = 5;
int32 subdirs = 6;
}
message NameFixup {
string path = 1;
uint64 inode = 2; // 0: the name maps to no inode
}
message Forgotten {
uint64 inode = 1;
string path = 2;
}
message OpenFh {
uint64 fh = 1;
bool append = 2;
}
message BaseMark {
int64 truncated_to = 1;
bool rewrote = 2;
}
message FileHandle {
uint64 fh = 1;
uint64 inode = 2;
int64 counter = 3;
repeated OpenFh opens = 4;
filer_pb.Entry entry = 5;
filer_pb.Entry base = 6;
int64 version_ts_ns = 7;
int32 version_signature = 8;
string saved_dir = 9;
string saved_name = 10;
bool is_deleted = 11;
uint64 delete_epoch = 12;
bool is_renamed = 13;
bool name_taken = 14;
bytes link_refresh = 15;
string content_type = 16;
BaseMark mark = 17;
// only an unlinked file's handle can still be dirty at export
bool dirty_metadata = 18;
bool dirty_content = 19;
bool pending_append = 20;
uint64 pending_append_offset = 21;
}
message StreamEntry {
string dir = 1;
filer_pb.Entry entry = 2;
}
message DirHandle {
uint64 fh = 1;
uint64 entry_stream_offset = 2;
bool is_finished = 3;
string last_listed_name = 4;
int64 snapshot_ts_ns = 5;
repeated StreamEntry entries = 6;
}
message Lock {
uint64 start = 1;
uint64 end = 2;
uint32 typ = 3;
uint64 owner = 4;
uint32 pid = 5;
bool is_flock = 6;
}
message LockSet {
uint64 inode = 1;
repeated Lock locks = 2;
}
// owners per open fh (fh_lock_owners) or per inode (lock_hint)
message LockOwners {
uint64 key = 1;
repeated uint64 owners = 2;
}
message RoutedRange {
uint64 start = 1;
uint64 end = 2;
uint32 type = 3;
uint64 sid = 4;
uint64 owner = 5;
uint32 pid = 6;
bool is_flock = 7;
string principal = 8;
}
message RoutedKey {
string key = 1;
repeated RoutedRange ranges = 2;
}
message NfsRecord {
uint64 inode = 1;
string path = 2;
int64 opens = 3;
bool pending_removal = 4;
bool dirty = 5;
}
message InodeTime {
uint64 inode = 1;
int64 unix_nanos = 2;
}
message RemovedDir {
uint64 inode = 1;
filer_pb.Entry entry = 2;
}
message ContentError {
uint64 inode = 1;
}
message End {
uint32 crc32 = 1; // IEEE, over every frame before this one
uint64 frames = 2;
}
File diff suppressed because it is too large. Load diff
+294
View File
@@ -0,0 +1,294 @@
package lance
import (
"errors"
"net/http"
"net/http/httptest"
"slices"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
// These tests pin what the catalog reports about a Lance table from the
// marker files beside its dataset: .lance-deregistered hides it, and
// _versions/ is what separates a table holding data from one only declared.
// addVersions gives the dataset in dir a version manifest, which is what a
// Lance client writing data leaves behind.
func addVersions(h *testHarness, dir string) {
h.filer.Put(dir, versionsDir, nil)
h.filer.PutFile(dir+"/"+versionsDir, "1.manifest", time.Now())
}
// seedTableStates declares, in namespace bucket$ns, one table in each state a
// listing has to tell apart, and returns the identifiers of the two that are
// registered.
func seedTableStates(t *testing.T, h *testHarness, bucket, ns string) (declaredOnly, withData string) {
t.Helper()
prefix := bucket + "$" + ns + "$"
h.mustDo(t, http.MethodPost, "/v1/namespace/"+bucket+"$"+ns+"/create", `{}`, http.StatusOK)
declareLanceTable(t, h, prefix+"declared_only")
addVersions(h, declareLanceTable(t, h, prefix+"with_data"))
addVersions(h, declareLanceTable(t, h, prefix+"deregistered_with_data"))
h.mustDo(t, http.MethodPost, "/v1/table/"+prefix+"deregistered_with_data/deregister", `{}`, http.StatusOK)
declareLanceTable(t, h, prefix+"deregistered_empty")
h.mustDo(t, http.MethodPost, "/v1/table/"+prefix+"deregistered_empty/deregister", `{}`, http.StatusOK)
return prefix + "declared_only", prefix + "with_data"
}
func listedTables(t *testing.T, h *testHarness, target string) []string {
t.Helper()
listed := decode[ListTablesResponse](t, h.mustDo(t, http.MethodGet, target, "", http.StatusOK))
tables := slices.Clone(listed.Tables)
slices.Sort(tables)
return tables
}
func TestListTablesVisibility(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
declaredOnly, withData := seedTableStates(t, h, "analytics", "sales")
// an undeclared bucket holds both formats; only the Lance table is listed
h.createBucket(t, "mixed", "")
h.mustDo(t, http.MethodPost, "/v1/namespace/mixed$sales/create", `{}`, http.StatusOK)
addVersions(h, declareLanceTable(t, h, "mixed$sales$vectors"))
var created s3tables.CreateTableResponse
if err := h.admin.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), s3tables.NewManagerClient(h.filer.Client), "CreateTable",
&s3tables.CreateTableRequest{
TableBucketARN: h.bucketARN(t, "mixed"),
Namespace: []string{"sales"},
Name: "ledger",
Format: s3tables.FormatIceberg,
MetadataLocation: "s3://mixed/sales/ledger/metadata/v1.metadata.json",
}, &created, ""); err != nil {
t.Fatalf("create iceberg table: %v", err)
}
for _, tc := range []struct {
query string
analytics []string
}{
{query: "", analytics: []string{declaredOnly, withData}},
{query: "?include_declared=true", analytics: []string{declaredOnly, withData}},
{query: "?include_declared=false", analytics: []string{withData}},
} {
if got := listedTables(t, h, "/v1/namespace/analytics$sales/table/list"+tc.query); !slices.Equal(got, tc.analytics) {
t.Errorf("ListTables%s = %v, want %v", tc.query, got, tc.analytics)
}
if got, want := listedTables(t, h, "/v1/namespace/mixed$sales/table/list"+tc.query), []string{"mixed$sales$vectors"}; !slices.Equal(got, want) {
t.Errorf("ListTables%s in a mixed bucket = %v, want %v", tc.query, got, want)
}
}
}
// ListAllTables lists declared-only tables too, and does not read
// include_declared at all.
func TestListAllTablesVisibility(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.createBucket(t, "metrics", s3tables.FormatLance)
a1, a2 := seedTableStates(t, h, "analytics", "sales")
m1, m2 := seedTableStates(t, h, "metrics", "ops")
want := []string{a1, a2, m1, m2}
slices.Sort(want)
for _, query := range []string{"", "?include_declared=false"} {
if got := listedTables(t, h, "/v1/table"+query); !slices.Equal(got, want) {
t.Errorf("ListAllTables%s = %v, want %v", query, got, want)
}
}
}
func TestListTablesDelimiterAndPaging(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
declaredOnly, withData := seedTableStates(t, h, "analytics", "sales")
dotted := listedTables(t, h, "/v1/namespace/analytics.sales/table/list?delimiter=.")
if want := []string{"analytics.sales.declared_only", "analytics.sales.with_data"}; !slices.Equal(dotted, want) {
t.Errorf("ListTables with delimiter . = %v, want %v", dotted, want)
}
// One table a page: the token walks every catalog record, the deregistered
// ones answer as empty pages, and nothing is listed twice.
var all []string
token := ""
for page := 0; ; page++ {
if page > 10 {
t.Fatalf("paging did not end; listed so far %v", all)
}
target := "/v1/namespace/analytics$sales/table/list?limit=1"
if token != "" {
target += "&page_token=" + token
}
listed := decode[ListTablesResponse](t, h.mustDo(t, http.MethodGet, target, "", http.StatusOK))
if len(listed.Tables) > 1 {
t.Fatalf("page %d holds %v, more than limit=1", page, listed.Tables)
}
all = append(all, listed.Tables...)
if listed.PageToken == "" {
break
}
token = listed.PageToken
}
slices.Sort(all)
if want := []string{declaredOnly, withData}; !slices.Equal(all, want) {
t.Errorf("tables across pages = %v, want %v", all, want)
}
}
func TestDescribeTableCheckDeclared(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
declaredOnly, withData := seedTableStates(t, h, "analytics", "sales")
describe := func(id, query, body string) DescribeTableResponse {
t.Helper()
return decode[DescribeTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/describe"+query, body, http.StatusOK))
}
for _, id := range []string{declaredOnly, withData} {
for _, req := range []struct{ query, body string }{
{"", `{}`},
{"?check_declared=false", `{}`},
{"", `{"check_declared":false}`},
} {
if got := describe(id, req.query, req.body).IsOnlyDeclared; got != nil {
t.Errorf("describe %s%s %s: is_only_declared = %v, want it absent", id, req.query, req.body, *got)
}
}
}
for _, req := range []struct{ query, body string }{
{"?check_declared=true", `{}`},
{"", `{"check_declared":true}`},
} {
for id, want := range map[string]bool{declaredOnly: true, withData: false} {
got := describe(id, req.query, req.body).IsOnlyDeclared
if got == nil || *got != want {
t.Errorf("describe %s%s %s: is_only_declared = %v, want %v", id, req.query, req.body, got, want)
}
}
recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$deregistered_with_data/describe"+req.query, req.body, http.StatusNotFound)
if code := decode[errorResponse](t, recorder).Code; code != codeTableNotFound {
t.Errorf("describe of a deregistered table%s %s: code %d, want %d", req.query, req.body, code, codeTableNotFound)
}
}
}
// A deregistered table is absent to every operation until it is registered
// again, and registering it again is not a conflict.
func TestDeregisteredTableIsAbsent(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
declaredOnly, withData := seedTableStates(t, h, "analytics", "sales")
gone := "analytics$sales$deregistered_with_data"
internal := func(id string) error {
t.Helper()
parts, err := parseIdentifier(id, defaultDelimiter)
if err != nil {
t.Fatalf("parse %s: %v", id, err)
}
_, _, err = h.server.DescribeTableInternal(httptest.NewRequest(http.MethodPost, "/", nil), parts)
return err
}
for _, id := range []string{declaredOnly, withData} {
h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/exists", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/describe", `{}`, http.StatusOK)
if err := internal(id); err != nil {
t.Errorf("DescribeTableInternal(%s) = %v, want the table", id, err)
}
}
location := `{"location":"s3://analytics/sales/with_data"}`
h.mustDo(t, http.MethodPost, "/v1/table/"+withData+"/register", location, http.StatusConflict)
h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/exists", `{}`, http.StatusNotFound)
h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/describe", `{}`, http.StatusNotFound)
var tablesErr *s3tables.S3TablesError
if err := internal(gone); !errors.As(err, &tablesErr) || tablesErr.Type != s3tables.ErrCodeNoSuchTable {
t.Errorf("DescribeTableInternal of a deregistered table = %v, want %s", err, s3tables.ErrCodeNoSuchTable)
}
h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/register",
`{"location":"s3://analytics/sales/deregistered_with_data"}`, http.StatusOK)
if h.filer.Get("/buckets/analytics/sales/deregistered_with_data", deregisteredMarker) != nil {
t.Errorf("register left %s behind", deregisteredMarker)
}
h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/exists", `{}`, http.StatusOK)
if got := listedTables(t, h, "/v1/namespace/analytics$sales/table/list"); !slices.Contains(got, gone) {
t.Errorf("re-registered table missing from the listing %v", got)
}
}
// The markers are read where the catalog record says the dataset is: its
// recorded location, or the name path when it records none.
func TestListingReadsMarkersAtTheRecordedLocation(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
client := s3tables.NewManagerClient(h.filer.Client)
create := func(name, location string) {
t.Helper()
var resp s3tables.CreateTableResponse
if err := h.admin.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), client, "CreateTable", &s3tables.CreateTableRequest{
TableBucketARN: h.bucketARN(t, "analytics"),
Namespace: []string{"sales"},
Name: name,
Format: s3tables.FormatLance,
MetadataLocation: location,
}, &resp, ""); err != nil {
t.Fatalf("create %s: %v", name, err)
}
}
create("unplaced", "")
create("alias", "s3://analytics/sales/store")
var summaries s3tables.ListTablesResponse
if err := h.admin.Execute(t.Context(), client, "ListTables", &s3tables.ListTablesRequest{
TableBucketARN: h.bucketARN(t, "analytics"), Namespace: []string{"sales"},
}, &summaries, ""); err != nil {
t.Fatalf("list tables: %v", err)
}
for _, summary := range summaries.Tables {
if summary.Name == "unplaced" && summary.MetadataLocation != "" {
t.Fatalf("unplaced records location %q; the fallback case needs none", summary.MetadataLocation)
}
}
list := func(query string) []string {
t.Helper()
return listedTables(t, h, "/v1/namespace/analytics$sales/table/list"+query)
}
both := []string{"analytics$sales$alias", "analytics$sales$unplaced"}
if got := list(""); !slices.Equal(got, both) {
t.Fatalf("listing = %v, want %v", got, both)
}
// data at the name path does not count for a table recorded elsewhere
addVersions(h, "/buckets/analytics/sales/alias")
if got := list("?include_declared=false"); len(got) != 0 {
t.Errorf("include_declared=false with data only at the name paths = %v, want none", got)
}
addVersions(h, "/buckets/analytics/sales/store")
addVersions(h, "/buckets/analytics/sales/unplaced")
if got := list("?include_declared=false"); !slices.Equal(got, both) {
t.Errorf("include_declared=false with data at the recorded locations = %v, want %v", got, both)
}
// a marker at the name path does not hide a table recorded elsewhere
h.filer.PutFile("/buckets/analytics/sales/alias", deregisteredMarker, time.Now())
if got := list(""); !slices.Equal(got, both) {
t.Errorf("listing with a marker only at alias's name path = %v, want %v", got, both)
}
h.filer.PutFile("/buckets/analytics/sales/store", deregisteredMarker, time.Now())
h.filer.PutFile("/buckets/analytics/sales/unplaced", deregisteredMarker, time.Now())
if got := list(""); len(got) != 0 {
t.Errorf("listing with markers at the recorded locations = %v, want none", got)
}
}
+8 -7
View File
@@ -87,7 +87,7 @@ func (s *Server) lanceTableIDs(r *http.Request, bucket string, summaries []s3tab
if location == "" {
location = tableLocation(bucket, summary.Namespace, summary.Name)
}
deregistered, hasData, err := s.datasetState(r, location)
deregistered, hasData, err := s.datasetState(r, location, !includeDeclared)
if err != nil {
glog.V(2).Infof("lance: cannot read dataset state for %s: %v", location, err)
continue
@@ -213,7 +213,7 @@ func (s *Server) describeTable(r *http.Request, parts []string, internal bool) (
return "", nil, err
}
location := table.location
deregistered, _, err := s.datasetState(r, location)
deregistered, _, err := s.datasetState(r, location, false)
if err != nil {
return "", nil, err
}
@@ -262,7 +262,8 @@ func (s *Server) handleDescribeTable(w http.ResponseWriter, r *http.Request) {
}
location := table.location
deregistered, hasData, err := s.datasetState(r, location)
checkDeclared := wants(r, "check_declared", req.CheckDeclared)
deregistered, hasData, err := s.datasetState(r, location, checkDeclared)
if err != nil {
writeError(w, r, http.StatusInternalServerError, codeInternal, err.Error())
return
@@ -289,7 +290,7 @@ func (s *Server) handleDescribeTable(w http.ResponseWriter, r *http.Request) {
if wants(r, "with_table_uri", req.WithTableURI) {
resp.TableURI = location
}
if wants(r, "check_declared", req.CheckDeclared) {
if checkDeclared {
onlyDeclared := !hasData
resp.IsOnlyDeclared = &onlyDeclared
}
@@ -332,7 +333,7 @@ func (s *Server) handleTableExists(w http.ResponseWriter, r *http.Request) {
writeStorageError(w, r, err)
return
}
deregistered, _, err := s.datasetState(r, table.location)
deregistered, _, err := s.datasetState(r, table.location, false)
if err != nil {
writeError(w, r, http.StatusInternalServerError, codeInternal, err.Error())
return
@@ -391,7 +392,7 @@ func (s *Server) handleRegisterTable(w http.ResponseWriter, r *http.Request) {
case err == nil:
// A deregistered table is absent as far as the spec is concerned, so
// registering over it is a re-registration rather than a conflict.
deregistered, _, stateErr := s.datasetState(r, existing.location)
deregistered, _, stateErr := s.datasetState(r, existing.location, false)
if stateErr != nil {
writeError(w, r, http.StatusInternalServerError, codeInternal, stateErr.Error())
return
@@ -451,7 +452,7 @@ func (s *Server) handleRegisterTable(w http.ResponseWriter, r *http.Request) {
}
// CreateTable also answers for a table the caller cannot read, so
// bringing that one back still needs UpdateTable.
deregistered, _, stateErr := s.datasetState(r, location)
deregistered, _, stateErr := s.datasetState(r, location, false)
if stateErr != nil {
glog.V(1).Infof("lance: could not check %s for %s: %v", deregisteredMarker, location, stateErr)
}
@@ -0,0 +1,150 @@
package lance
import (
"fmt"
"net/http"
"net/http/httptest"
"path"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
)
// These benchmarks measure the listings against the in-memory filer, whose
// lookups cost no network round trip. The rtt cases add a fixed delay to every
// filer lookup to stand in for one; they model a filer on another host, not
// any measured deployment. lookups/op and versions/op are exact counts and do
// not depend on the machine.
// simulatedFilerRTT is the delay the rtt cases add to each filer lookup.
const simulatedFilerRTT = 200 * time.Microsecond
type benchHarness struct {
router *mux.Router
filer *s3tablestest.MemFiler
lookups atomic.Int64
versions atomic.Int64
delay atomic.Int64 // nanoseconds added to each lookup
}
// newBenchHarness seeds tablesPerBucket Lance tables in namespace ns of each
// named bucket, each holding data (a _versions/ manifest), so every listing,
// include_declared=false included, lists them all.
func newBenchHarness(b *testing.B, buckets []string, tablesPerBucket int) *benchHarness {
b.Helper()
filer := s3tablestest.Start(b)
server := NewServer(s3tables.NewManagerClient(filer.Client), openAuthenticator{})
server.SetS3Endpoint("http://127.0.0.1:8333")
server.SetS3Region(s3tables.DefaultRegion)
router := mux.NewRouter().SkipClean(true)
server.RegisterRoutes(router)
h := &benchHarness{router: router, filer: filer}
admin := s3tables.NewManager()
admin.SetTrusted(true)
for _, bucket := range buckets {
var resp s3tables.CreateTableBucketResponse
if err := admin.Execute(b.Context(), s3tables.NewManagerClient(filer.Client), "CreateTableBucket",
&s3tables.CreateTableBucketRequest{Name: bucket, Format: s3tables.FormatLance}, &resp, ""); err != nil {
b.Fatalf("create table bucket %s: %v", bucket, err)
}
h.mustDo(b, http.MethodPost, "/v1/namespace/"+bucket+"$ns/create", `{}`)
for i := range tablesPerBucket {
name := fmt.Sprintf("t%04d", i)
h.mustDo(b, http.MethodPost, "/v1/table/"+bucket+"$ns$"+name+"/declare", `{}`)
dir := "/buckets/" + bucket + "/ns/" + name
if filer.Get(path.Dir(dir), name) == nil {
filer.Put(path.Dir(dir), name, nil)
}
filer.Put(dir, versionsDir, nil)
filer.PutFile(dir+"/"+versionsDir, "1.manifest", time.Now())
}
}
filer.OnLookup = func(dir, name string) {
h.lookups.Add(1)
if name == versionsDir {
h.versions.Add(1)
}
if d := time.Duration(h.delay.Load()); d > 0 {
// spin: time.Sleep overshoots a delay this short several times over
for start := time.Now(); time.Since(start) < d; {
}
}
}
return h
}
func (h *benchHarness) mustDo(b *testing.B, method, target, body string) *httptest.ResponseRecorder {
b.Helper()
recorder := httptest.NewRecorder()
h.router.ServeHTTP(recorder, httptest.NewRequest(method, target, strings.NewReader(body)))
if recorder.Code != http.StatusOK {
b.Fatalf("%s %s = %d (%s)", method, target, recorder.Code, recorder.Body.String())
}
return recorder
}
// run times GET target and reports the filer lookups each request made.
func (h *benchHarness) run(b *testing.B, target string, wantTables int, rtt time.Duration) {
b.Helper()
// one request outside the timer, to check the listing is the one meant
if got := strings.Count(h.mustDo(b, http.MethodGet, target, "").Body.String(), "$ns$t"); got != wantTables {
b.Fatalf("GET %s listed %d tables, want %d", target, got, wantTables)
}
h.delay.Store(int64(rtt))
defer h.delay.Store(0)
h.lookups.Store(0)
h.versions.Store(0)
ops := 0
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
h.mustDo(b, http.MethodGet, target, "")
ops++
}
b.StopTimer()
b.ReportMetric(float64(h.lookups.Load())/float64(ops), "lookups/op")
b.ReportMetric(float64(h.versions.Load())/float64(ops), "versions/op")
}
func BenchmarkLanceListTables(b *testing.B) {
for _, tables := range []int{10, 100, 500} {
h := newBenchHarness(b, []string{"analytics"}, tables)
for _, rtt := range []time.Duration{0, simulatedFilerRTT} {
if rtt > 0 && tables > 100 {
continue // 500 tables at 200µs a lookup is too slow to repeat usefully
}
for _, query := range []string{"", "?include_declared=false"} {
label := "default"
if query != "" {
label = "include_declared=false"
}
b.Run(fmt.Sprintf("tables=%d/rtt=%s/%s", tables, rtt, label), func(b *testing.B) {
h.run(b, "/v1/namespace/analytics$ns/table/list"+query, tables, rtt)
})
}
}
}
}
func BenchmarkLanceListAllTables(b *testing.B) {
buckets := []string{"analytics", "metrics"}
for _, perBucket := range []int{5, 50, 250} {
h := newBenchHarness(b, buckets, perBucket)
total := perBucket * len(buckets)
for _, rtt := range []time.Duration{0, simulatedFilerRTT} {
if rtt > 0 && total > 100 {
continue
}
b.Run(fmt.Sprintf("tables=%d/rtt=%s", total, rtt), func(b *testing.B) {
h.run(b, "/v1/table", total, rtt)
})
}
}
}
+211
View File
@@ -0,0 +1,211 @@
package lance
import (
"net/http"
"net/http/httptest"
"path"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
// lookupCounter counts, by entry name, the lookups the filer answers. The
// filer runs them on its own goroutines, hence the lock.
type lookupCounter struct {
mu sync.Mutex
counts map[string]int
}
func countLookups(h *testHarness) *lookupCounter {
c := &lookupCounter{counts: map[string]int{}}
h.filer.OnLookup = func(dir, name string) {
c.mu.Lock()
c.counts[name]++
c.mu.Unlock()
}
return c
}
func (c *lookupCounter) reset() {
c.mu.Lock()
c.counts = map[string]int{}
c.mu.Unlock()
}
func (c *lookupCounter) get(name string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.counts[name]
}
// declareLanceTable declares a table and returns the filer directory of its
// dataset, creating that directory if the declare did not.
func declareLanceTable(t *testing.T, h *testHarness, id string) string {
t.Helper()
declared := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/declare", `{}`, http.StatusOK))
dir := "/buckets/" + strings.TrimPrefix(declared.Location, "s3://")
if h.filer.Get(path.Dir(dir), path.Base(dir)) == nil {
h.filer.Put(path.Dir(dir), path.Base(dir), nil)
}
return dir
}
// A listing needs a table's _versions/ only to drop declared-only tables,
// which ListTables does for include_declared=false and nothing else does.
// Probing it for every Lance table regardless doubles the filer lookups of
// the default listing and of ListAllTables (N tables, 2N lookups) for an
// answer that is thrown away. A deregistered table is dropped on its marker
// alone, so its _versions/ is never needed either.
func TestListingProbesVersionsOnlyWhenNeeded(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.createBucket(t, "metrics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/namespace/metrics$ops/create", `{}`, http.StatusOK)
declareLanceTable(t, h, "analytics$sales$declared")
withData := declareLanceTable(t, h, "analytics$sales$withdata")
h.filer.Put(withData, versionsDir, nil)
h.filer.PutFile(withData+"/"+versionsDir, "1.manifest", time.Now())
gone := declareLanceTable(t, h, "analytics$sales$gone")
h.filer.Put(gone, versionsDir, nil)
h.filer.PutFile(gone+"/"+versionsDir, "1.manifest", time.Now())
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/deregister", `{}`, http.StatusOK)
declareLanceTable(t, h, "metrics$ops$latency")
lookups := countLookups(h)
cases := []struct {
name string
target string
wantTables []string
wantMarker int // .lance-deregistered: one per Lance table listed from
wantVersions int // _versions: only where its answer decides the listing
}{
{
name: "ListTables default",
target: "/v1/namespace/analytics$sales/table/list",
wantTables: []string{"analytics$sales$declared", "analytics$sales$withdata"},
wantMarker: 3,
wantVersions: 0,
},
{
name: "ListTables include_declared=true",
target: "/v1/namespace/analytics$sales/table/list?include_declared=true",
wantTables: []string{"analytics$sales$declared", "analytics$sales$withdata"},
wantMarker: 3,
wantVersions: 0,
},
{
name: "ListTables include_declared=false",
target: "/v1/namespace/analytics$sales/table/list?include_declared=false",
wantTables: []string{"analytics$sales$withdata"},
wantMarker: 3,
// declared and withdata; gone is dropped on its marker
wantVersions: 2,
},
{
name: "ListAllTables",
target: "/v1/table",
wantTables: []string{"analytics$sales$declared", "analytics$sales$withdata", "metrics$ops$latency"},
wantMarker: 4,
wantVersions: 0,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
lookups.reset()
listed := decode[ListTablesResponse](t, h.mustDo(t, http.MethodGet, tc.target, "", http.StatusOK))
got := slices.Clone(listed.Tables)
slices.Sort(got)
if !slices.Equal(got, tc.wantTables) {
t.Errorf("tables = %v, want %v", got, tc.wantTables)
}
if n := lookups.get(deregisteredMarker); n != tc.wantMarker {
t.Errorf("%s lookups = %d, want %d", deregisteredMarker, n, tc.wantMarker)
}
if n := lookups.get(versionsDir); n != tc.wantVersions {
t.Errorf("%s lookups = %d, want %d: the listing probed data it does not use", versionsDir, n, tc.wantVersions)
}
})
}
}
// Describe, exists and register read a table's _versions/ only where the
// answer is used: describe with check_declared, and the register of a new
// name, which needs a dataset at the location. Everything else decides on the
// .lance-deregistered marker alone.
func TestHandlersProbeVersionsOnlyWhenNeeded(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
declareLanceTable(t, h, "analytics$sales$declared")
addVersions(h, declareLanceTable(t, h, "analytics$sales$withdata"))
addVersions(h, declareLanceTable(t, h, "analytics$sales$gone"))
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/deregister", `{}`, http.StatusOK)
h.filer.Put("/buckets/analytics/sales", "imported", nil)
addVersions(h, "/buckets/analytics/sales/imported")
internal := func(id string) {
t.Helper()
parts, err := parseIdentifier(id, defaultDelimiter)
if err != nil {
t.Fatalf("parse %s: %v", id, err)
}
if _, _, err := h.server.DescribeTableInternal(httptest.NewRequest(http.MethodPost, "/", nil), parts); err != nil {
t.Fatalf("DescribeTableInternal(%s): %v", id, err)
}
}
lookups := countLookups(h)
// in order: re-registering gone and registering imported change the state
cases := []struct {
name string
do func()
wantMarker int
wantVersions int
}{
{"describe", func() {
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$declared/describe", `{}`, http.StatusOK)
}, 1, 0},
{"describe check_declared", func() {
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$withdata/describe?check_declared=true", `{}`, http.StatusOK)
}, 1, 1},
{"describe check_declared deregistered", func() {
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/describe?check_declared=true", `{}`, http.StatusNotFound)
}, 1, 0},
{"DescribeTableInternal", func() { internal("analytics$sales$withdata") }, 1, 0},
{"exists", func() {
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$withdata/exists", `{}`, http.StatusOK)
}, 1, 0},
{"register existing name", func() {
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$withdata/register",
`{"location":"s3://analytics/sales/withdata"}`, http.StatusConflict)
}, 1, 0},
{"register deregistered name", func() {
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/register",
`{"location":"s3://analytics/sales/gone"}`, http.StatusOK)
}, 1, 0},
{"register new name", func() {
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$imported/register",
`{"location":"s3://analytics/sales/imported"}`, http.StatusOK)
}, 1, 1},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
lookups.reset()
tc.do()
if n := lookups.get(deregisteredMarker); n != tc.wantMarker {
t.Errorf("%s lookups = %d, want %d", deregisteredMarker, n, tc.wantMarker)
}
if n := lookups.get(versionsDir); n != tc.wantVersions {
t.Errorf("%s lookups = %d, want %d: the handler probed data it does not use", versionsDir, n, tc.wantVersions)
}
})
}
}
+6 -5
View File
@@ -84,15 +84,16 @@ func (s *Server) removeMarker(r *http.Request, location, name string) error {
// datasetState reports the two things the spec asks about a table's storage:
// whether it has been deregistered, and whether it holds data yet. A dataset
// holds data once it has a version manifest, which is how a directory catalog
// decides the same question.
func (s *Server) datasetState(r *http.Request, location string) (deregistered, hasData bool, err error) {
// decides the same question. _versions/ is read only when checkData is set
// and the table is not deregistered; otherwise hasData is false.
func (s *Server) datasetState(r *http.Request, location string, checkData bool) (deregistered, hasData bool, err error) {
dir := datasetDir(location)
if dir == "" {
return false, false, nil
}
if deregistered, err = s.entryExists(r, dir, deregisteredMarker); err != nil {
return false, false, err
if deregistered, err = s.entryExists(r, dir, deregisteredMarker); err != nil || deregistered || !checkData {
return deregistered, false, err
}
hasData, err = s.entryExists(r, dir, versionsDir)
return deregistered, hasData, err
return false, hasData, err
}
+9 -1
View File
@@ -1520,8 +1520,16 @@ func loadIAMManagerFromConfig(configPath string, filerAddressProvider func() str
if kek := GetSSES3KeyManager().GetMasterKey(); len(kek) > 0 {
iamConfig.STS.SigningKey = kek
glog.V(1).Infof("Using SSE-S3 Master Key (KEK) for STS service")
} else if persistByDefault {
// 3. Zero-config: a key shared through the filer
key, err := loadOrCreateSTSSigningKey(filerAddressProvider())
if err != nil {
return nil, fmt.Errorf("no signing key found for STS service and none could be kept on the filer at %s/%s: %w", stsSigningKeyDir, stsSigningKeyName, err)
}
iamConfig.STS.SigningKey = key
glog.V(0).Infof("Using the STS signing key stored on the filer at %s/%s", stsSigningKeyDir, stsSigningKeyName)
} else {
// 3. Fail if no signing key is available
// 4. Fail if no signing key is available
// This ensures consistency across multiple S3 servers and secure operation
return nil, fmt.Errorf("no signing key found for STS service; please provide 'signingKey' in IAM config, configure 'jwt.filer_signing.key' in security.toml, or ensure SSE-S3 is initialized")
}
+98
View File
@@ -0,0 +1,98 @@
package s3api
import (
"context"
"crypto/rand"
"errors"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
)
const (
stsSigningKeyDir = "/etc/iam"
stsSigningKeyName = "sts_signing_key"
stsSigningKeySize = 32
)
var stsSigningKeyRetryInterval = time.Second
// loadOrCreateSTSSigningKey returns the STS signing key kept on the filer,
// creating it on first use, so every gateway sharing the filer signs and
// validates session tokens with the same key. It refuses when an SSE-S3 key
// is configured or kept on the filer, since gateways that load it sign with it.
func loadOrCreateSTSSigningKey(filerAddress string) (key []byte, err error) {
v := util.GetViper()
if v.GetString(sseS3KEKConfigKey) != "" || v.GetString(sseS3KeyConfigKey) != "" {
return nil, fmt.Errorf("the SSE-S3 key set by %s or %s was not loaded", sseS3KEKConfigKey, sseS3KeyConfigKey)
}
grpcDialOption := security.LoadClientTLS(v, "grpc.client")
err = pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, kekErr := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: SSES3KEKDirectory, Name: SSES3KEKFileName})
if kekErr == nil {
return fmt.Errorf("the SSE-S3 KEK at %s exists on the filer but was not loaded", defaultKEKPath)
}
if !errors.Is(kekErr, filer_pb.ErrNotFound) {
return kekErr
}
stored, readErr := filer.ReadInsideFiler(ctx, client, stsSigningKeyDir, stsSigningKeyName)
if readErr == nil && len(stored) > 0 {
key = stored
return nil
}
if readErr != nil && !errors.Is(readErr, filer_pb.ErrNotFound) {
return readErr
}
fresh := make([]byte, stsSigningKeySize)
if _, randErr := rand.Read(fresh); randErr != nil {
return randErr
}
now := time.Now().Unix()
createErr := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
Directory: stsSigningKeyDir,
OExcl: true,
Entry: &filer_pb.Entry{
Name: stsSigningKeyName,
Attributes: &filer_pb.FuseAttributes{
Mtime: now,
Crtime: now,
FileMode: uint32(0600),
FileSize: stsSigningKeySize,
},
Content: fresh,
},
})
if createErr == nil {
key = fresh
return nil
}
if !errors.Is(createErr, filer_pb.ErrEntryAlreadyExists) {
return createErr
}
// Another gateway created it first; with per-filer stores it can
// reach this filer a little after the create was refused.
for {
stored, readErr = filer.ReadInsideFiler(ctx, client, stsSigningKeyDir, stsSigningKeyName)
if readErr == nil && len(stored) > 0 {
key = stored
return nil
}
if readErr != nil && !errors.Is(readErr, filer_pb.ErrNotFound) {
return readErr
}
select {
case <-ctx.Done():
return createErr
case <-time.After(stsSigningKeyRetryInterval):
}
}
})
return key, err
}
+168
View File
@@ -0,0 +1,168 @@
package s3api
import (
"bytes"
"context"
"net"
"strconv"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type stsKeyTestFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
mu sync.Mutex
entries map[string]*filer_pb.Entry
// createdBehind is stored by the first CreateEntry before it answers
// "already exists", as if another gateway had won the create.
createdBehind []byte
// hiddenLookups is how many lookups after a refused create still miss,
// as if the winner's key had not yet reached this filer.
hiddenLookups int
refused bool
creates int
}
func (f *stsKeyTestFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
entry, ok := f.entries[req.Directory+"/"+req.Name]
if f.refused && f.hiddenLookups > 0 {
f.hiddenLookups--
ok = false
}
if !ok {
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
}
return &filer_pb.LookupDirectoryEntryResponse{Entry: entry}, nil
}
func (f *stsKeyTestFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.creates++
path := req.Directory + "/" + req.Entry.Name
if f.createdBehind != nil {
f.entries[path] = &filer_pb.Entry{Name: req.Entry.Name, Content: f.createdBehind}
f.createdBehind = nil
}
if _, exists := f.entries[path]; exists && req.OExcl {
f.refused = true
return &filer_pb.CreateEntryResponse{Error: "entry already exists", ErrorCode: filer_pb.FilerError_ENTRY_ALREADY_EXISTS}, nil
}
f.entries[path] = req.Entry
return &filer_pb.CreateEntryResponse{}, nil
}
func (f *stsKeyTestFiler) stored() []byte {
f.mu.Lock()
defer f.mu.Unlock()
if entry, ok := f.entries[stsSigningKeyDir+"/"+stsSigningKeyName]; ok {
return entry.Content
}
return nil
}
func startSTSKeyTestFiler(t *testing.T, f *stsKeyTestFiler) string {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
server := pb.NewGrpcServer()
filer_pb.RegisterSeaweedFilerServer(server, f)
go func() { _ = server.Serve(lis) }()
t.Cleanup(server.Stop)
host, port, err := net.SplitHostPort(lis.Addr().String())
require.NoError(t, err)
grpcPort, err := strconv.Atoi(port)
require.NoError(t, err)
return string(pb.NewServerAddress(host, 1, grpcPort))
}
func TestLoadOrCreateSTSSigningKey(t *testing.T) {
f := &stsKeyTestFiler{entries: map[string]*filer_pb.Entry{}}
address := startSTSKeyTestFiler(t, f)
first, err := loadOrCreateSTSSigningKey(address)
require.NoError(t, err)
assert.Len(t, first, stsSigningKeySize)
assert.Equal(t, first, f.stored())
second, err := loadOrCreateSTSSigningKey(address)
require.NoError(t, err)
assert.Equal(t, first, second)
assert.Equal(t, 1, f.creates)
}
func TestLoadOrCreateSTSSigningKeyLosesCreateRace(t *testing.T) {
winner := bytes.Repeat([]byte{7}, stsSigningKeySize)
f := &stsKeyTestFiler{entries: map[string]*filer_pb.Entry{}, createdBehind: winner}
address := startSTSKeyTestFiler(t, f)
key, err := loadOrCreateSTSSigningKey(address)
require.NoError(t, err)
assert.Equal(t, winner, key)
assert.Equal(t, winner, f.stored())
}
func TestLoadOrCreateSTSSigningKeyWaitsForWinnersKey(t *testing.T) {
saved := stsSigningKeyRetryInterval
stsSigningKeyRetryInterval = time.Millisecond
t.Cleanup(func() { stsSigningKeyRetryInterval = saved })
winner := bytes.Repeat([]byte{9}, stsSigningKeySize)
f := &stsKeyTestFiler{entries: map[string]*filer_pb.Entry{}, createdBehind: winner, hiddenLookups: 3}
address := startSTSKeyTestFiler(t, f)
key, err := loadOrCreateSTSSigningKey(address)
require.NoError(t, err)
assert.Equal(t, winner, key)
assert.Equal(t, 0, f.hiddenLookups)
}
func TestLoadOrCreateSTSSigningKeyRefusesUnloadedKEK(t *testing.T) {
f := &stsKeyTestFiler{entries: map[string]*filer_pb.Entry{
defaultKEKPath: {Name: SSES3KEKFileName, Content: []byte("wrapped")},
}}
address := startSTSKeyTestFiler(t, f)
_, err := loadOrCreateSTSSigningKey(address)
require.Error(t, err)
assert.Nil(t, f.stored())
assert.Equal(t, 0, f.creates)
}
func TestLoadOrCreateSTSSigningKeyRefusesConfiguredSSEKey(t *testing.T) {
t.Setenv("WEED_S3_SSE_KEY", "unloaded")
f := &stsKeyTestFiler{entries: map[string]*filer_pb.Entry{}}
address := startSTSKeyTestFiler(t, f)
_, err := loadOrCreateSTSSigningKey(address)
require.Error(t, err)
assert.Nil(t, f.stored())
assert.Equal(t, 0, f.creates)
}
func TestLoadIAMManagerFromConfig_NoFileKeepsSigningKeyOnFiler(t *testing.T) {
if len(GetSSES3KeyManager().GetMasterKey()) > 0 {
t.Skip("an SSE-S3 master key takes precedence")
}
f := &stsKeyTestFiler{entries: map[string]*filer_pb.Entry{}}
address := startSTSKeyTestFiler(t, f)
manager, err := loadIAMManagerFromConfig("", func() string { return address }, func() string { return "" })
require.NoError(t, err)
require.NotNil(t, manager.GetSTSService())
assert.Len(t, f.stored(), stsSigningKeySize)
_, err = loadIAMManagerFromConfig("", func() string { return address }, func() string { return "" })
require.NoError(t, err)
assert.Equal(t, 1, f.creates)
}
+217 -46
View File
@@ -103,9 +103,14 @@ func run(ctx context.Context, client filer_pb.FilerClient, now time.Time, stats
}
stats.removed++
}
for root, record := range t.records {
if takeOffExpired(record, untilNs) {
t.changed[root] = true
}
}
for root := range t.changed {
record := t.records[root]
record.TsNs = untilNs
record.TsNs = max(record.TsNs, untilNs)
if err := store.Save(ctx, record); err != nil {
return err
}
@@ -247,6 +252,8 @@ func (t *tracker) recordOf(path util.FullPath, tsNs int64) (*dirusage.Record, st
// side applies what an event did at path: from and to are the entry before
// and after, nil where there was none. moved is set when from went elsewhere.
// An entry the record has taken off for its TTL is no longer counted, so an
// event about it changes nothing again.
func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry, moved bool) {
if t.roots.IsRoot(path) {
t.rootChanged(path, tsNs, to)
@@ -256,8 +263,19 @@ func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry,
if record == nil {
return
}
delta := dirusage.EntryUsage(to)
delta.Sub(dirusage.EntryUsage(from))
var delta dirusage.Usage
if from != nil {
if value := dirusage.EntryValue(from); counted(value, record.TsNs) {
delta.Sub(value.Usage)
expireAt(record, rel, value, -1)
}
}
if to != nil {
if value := dirusage.EntryValue(to); counted(value, record.TsNs) {
delta.Add(value.Usage)
expireAt(record, rel, value, 1)
}
}
addUp(record, rel, delta)
if from != nil && from.IsDirectory && (to == nil || !to.IsDirectory) {
dropTracked(record, joinRelative(rel, path.Name()), rel, moved && to == nil)
@@ -265,6 +283,72 @@ func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry,
t.changed[util.FullPath(record.Root)] = true
}
// counted reports whether a record at tsNs counts an entry with value.
func counted(value dirusage.Value, tsNs int64) bool {
return !dirusage.TakenOff(value.Expires, tsNs)
}
// expireAt adds (sign 1) or withdraws (sign -1) an entry in the directory
// at rel to what comes off when it expires, under the directory with a
// record nearest above it.
func expireAt(record *dirusage.Record, rel string, value dirusage.Value, sign int) {
if value.Expires == 0 {
return
}
if record.Expiring == nil {
record.Expiring = make(map[int64]map[string]dirusage.Usage)
}
totals := record.Expiring[value.Expires]
if totals == nil {
totals = make(map[string]dirusage.Usage)
record.Expiring[value.Expires] = totals
}
at := nearestTracked(record, rel)
usage := totals[at]
if sign > 0 {
usage.Add(value.Usage)
} else {
usage.Sub(value.Usage)
}
if usage.IsZero() {
delete(totals, at)
} else {
totals[at] = usage
}
if len(totals) == 0 {
delete(record.Expiring, value.Expires)
}
}
// takeOffExpired takes off what expired by tsNs and reports whether
// anything did.
func takeOffExpired(record *dirusage.Record, tsNs int64) bool {
took := false
for expires, totals := range record.Expiring {
if !dirusage.TakenOff(expires, tsNs) {
continue
}
for at, usage := range totals {
var expired dirusage.Usage
expired.Sub(usage)
addUp(record, at, expired)
}
delete(record.Expiring, expires)
took = true
}
return took
}
// nearestTracked is rel, or the directory with a record nearest above it.
func nearestTracked(record *dirusage.Record, rel string) string {
for {
if _, tracked := record.Dirs[rel]; tracked || rel == "" {
return rel
}
rel = parentRelative(rel)
}
}
// trackedBelow are the directories at or below path with a record, relative
// to path.
func (t *tracker) trackedBelow(path util.FullPath, tsNs int64) []string {
@@ -338,7 +422,9 @@ func addUp(record *dirusage.Record, rel string, delta dirusage.Usage) {
// dropTracked drops the record of a removed directory and of what was below
// it. A directory deleted with totals left had entries that went without
// events, as when a store drops a whole bucket: the rest comes off the
// directories above it. A moved directory's entries each log their own move.
// directories above it, and so does what was still to expire there. A moved
// directory's entries each log their own move, and what they had still to
// expire waits for that under the directory above.
func dropTracked(record *dirusage.Record, rel, parentRel string, moved bool) {
usage, tracked := record.Dirs[rel]
if !tracked {
@@ -349,10 +435,27 @@ func dropTracked(record *dirusage.Record, rel, parentRel string, moved bool) {
rest.Sub(usage)
addUp(record, parentRel, rest)
}
delete(record.Dirs, rel)
for below := range record.Dirs {
if strings.HasPrefix(below, rel+"/") {
delete(record.Dirs, below)
below := func(at string) bool { return at == rel || strings.HasPrefix(at, rel+"/") }
for at := range record.Dirs {
if below(at) {
delete(record.Dirs, at)
}
}
above := nearestTracked(record, parentRel)
for expires, totals := range record.Expiring {
for at, usage := range totals {
if !below(at) {
continue
}
delete(totals, at)
if moved {
waiting := totals[above]
waiting.Add(usage)
totals[above] = waiting
}
}
if len(totals) == 0 {
delete(record.Expiring, expires)
}
}
}
@@ -385,22 +488,48 @@ func depthOf(rel string) int {
// seeding adds up a walk of the buckets folder or of / into the totals of
// the roots in it: of each directory being walked, kept once it is done while
// it holds its share of what the walk counted of its root so far. A directory
// holding its share of the whole root holds it of any part.
// holding its share of the whole root holds it of any part, unless entries
// went or expired since it was done.
type seeding struct {
roots dirusage.Roots
totals map[util.FullPath]map[string]*dirusage.Usage // by root, then by path relative to it
roots dirusage.Roots
dirs map[util.FullPath]map[string]*seedDir // by root, then by path relative to it
}
// seedDir is what a walk keeps of a directory: its totals, and what of them
// a TTL takes out, by when, for the entries it is the nearest kept directory
// above.
type seedDir struct {
usage dirusage.Usage
expiring map[int64]dirusage.Usage
}
func (d *seedDir) expire(expires int64, usage dirusage.Usage, sign int) {
if d.expiring == nil {
d.expiring = make(map[int64]dirusage.Usage)
}
total := d.expiring[expires]
if sign > 0 {
total.Add(usage)
} else {
total.Sub(usage)
}
if total.IsZero() {
delete(d.expiring, expires)
} else {
d.expiring[expires] = total
}
}
// seedRoots walks container, the buckets folder or /, into the roots in it
// that toSeed holds, and returns their records.
func seedRoots(ctx context.Context, client filer_pb.FilerClient, roots dirusage.Roots, container util.FullPath, toSeed map[util.FullPath]bool) (map[util.FullPath]*dirusage.Record, error) {
s := &seeding{roots: roots, totals: make(map[util.FullPath]map[string]*dirusage.Usage)}
seed := &treewalk.Seed[dirusage.Usage]{
s := &seeding{roots: roots, dirs: make(map[util.FullPath]map[string]*seedDir)}
seed := &treewalk.Seed[dirusage.Value]{
Client: client,
ClientName: clientName,
Concurrency: seedConcurrency,
PageSize: seedPageSize,
Value: dirusage.EntryUsage,
Value: dirusage.EntryValue,
Change: s.change,
Started: s.started,
Done: s.done,
@@ -424,81 +553,123 @@ func seedRoots(ctx context.Context, client filer_pb.FilerClient, roots dirusage.
return s.records(atNs), nil
}
// of is the totals of the root dir is in, and dir relative to it; nil for
// the container.
func (s *seeding) of(dir util.FullPath) (root util.FullPath, totals map[string]*dirusage.Usage, rel string) {
// of is the directories kept of the root dir is in, and dir relative to it;
// nil for the container.
func (s *seeding) of(dir util.FullPath) (root util.FullPath, dirs map[string]*seedDir, rel string) {
root, ok := s.roots.RootOf(dir)
if !ok {
return "", nil, ""
}
return root, s.totals[root], dirusage.Relative(root, dir)
return root, s.dirs[root], dirusage.Relative(root, dir)
}
func (s *seeding) started(dir util.FullPath, depth int) {
root, totals, rel := s.of(dir)
root, dirs, rel := s.of(dir)
switch {
case root == "":
case rel == "":
s.totals[root] = map[string]*dirusage.Usage{"": {}}
case totals != nil && depthOf(rel) <= dirusage.MaxDepth:
totals[rel] = &dirusage.Usage{}
s.dirs[root] = map[string]*seedDir{"": {}}
case dirs != nil && depthOf(rel) <= dirusage.MaxDepth:
dirs[rel] = &seedDir{}
}
}
// change adds what changed in dir to each directory being walked or kept
// above it. An entry of the container is a root: one that goes away during
// the walk gets no record, since a store that drops a whole bucket logs no
// event for what was in it; the next run seeds it if it comes back.
func (s *seeding) change(dir util.FullPath, name string, from, to *dirusage.Usage) {
// above it, and what of it expires to the nearest. An entry of the container
// is a root: one that goes away during the walk gets no record, since a
// store that drops a whole bucket logs no event for what was in it; the next
// run seeds it if it comes back.
func (s *seeding) change(dir util.FullPath, name string, from, to *dirusage.Value) {
if path := dir.Child(name); s.roots.IsRoot(path) {
if to == nil {
delete(s.totals, path)
delete(s.dirs, path)
}
return
}
_, totals, rel := s.of(dir)
if totals == nil {
_, dirs, rel := s.of(dir)
if dirs == nil {
return
}
var delta dirusage.Usage
if to != nil {
delta.Add(*to)
delta.Add(to.Usage)
}
if from != nil {
delta.Sub(*from)
delta.Sub(from.Usage)
}
var nearest *seedDir
for {
if usage := totals[rel]; usage != nil {
usage.Add(delta)
if d := dirs[rel]; d != nil {
d.usage.Add(delta)
if nearest == nil {
nearest = d
}
}
if rel == "" {
return
break
}
rel = parentRelative(rel)
}
if from != nil && from.Expires != 0 {
nearest.expire(from.Expires, from.Usage, -1)
}
if to != nil && to.Expires != 0 {
nearest.expire(to.Expires, to.Usage, 1)
}
}
// done drops a directory below its share, and hands what of it expires to
// the nearest directory kept above.
func (s *seeding) done(dir util.FullPath, depth int) {
_, totals, rel := s.of(dir)
if totals == nil || rel == "" {
_, dirs, rel := s.of(dir)
if dirs == nil || rel == "" {
return
}
if usage := totals[rel]; usage != nil && !holdsShare(*usage, *totals[""]) {
delete(totals, rel)
d := dirs[rel]
if d == nil || holdsShare(d.usage, dirs[""].usage) {
return
}
delete(dirs, rel)
for above := parentRelative(rel); ; above = parentRelative(above) {
if kept := dirs[above]; kept != nil {
for expires, usage := range d.expiring {
kept.expire(expires, usage, 1)
}
return
}
}
}
// records are the totals of each root at atNs. What expired by then comes off
// first, so a directory the walk kept keeps its record if it holds its share
// of its root at atNs.
func (s *seeding) records(atNs int64) map[util.FullPath]*dirusage.Record {
records := make(map[util.FullPath]*dirusage.Record, len(s.totals))
for root, totals := range s.totals {
rootUsage := *totals[""]
dirs := map[string]dirusage.Usage{"": rootUsage}
for rel, usage := range totals {
if rel != "" && holdsShare(*usage, rootUsage) {
dirs[rel] = *usage
records := make(map[util.FullPath]*dirusage.Record, len(s.dirs))
for root, dirs := range s.dirs {
record := &dirusage.Record{
Version: dirusage.Version,
Root: string(root),
TsNs: atNs,
SeededNs: atNs,
Dirs: make(map[string]dirusage.Usage, len(dirs)),
}
for rel, d := range dirs {
record.Dirs[rel] = d.usage
}
for rel, d := range dirs {
for expires, usage := range d.expiring {
expireAt(record, rel, dirusage.Value{Usage: usage, Expires: expires}, 1)
}
}
records[root] = &dirusage.Record{Version: dirusage.Version, Root: string(root), TsNs: atNs, SeededNs: atNs, Dirs: dirs}
takeOffExpired(record, atNs)
rootUsage := record.Dirs[""]
for rel, usage := range record.Dirs {
if rel != "" && !holdsShare(usage, rootUsage) {
// its entries stay counted above, and none below holds its share
dropTracked(record, rel, parentRelative(rel), true)
}
}
records[root] = record
}
return records
}
+119 -8
View File
@@ -39,13 +39,16 @@ func addLogStart(f *treewalktest.Filer, start time.Time) {
}
// totals adds up tree below root by directory, relative to root, leaving out
// what the counts leave out.
func totals(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath) map[string]dirusage.Usage {
// what the counts leave out and what a record at atNs took off for a TTL.
func totals(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath, atNs int64) map[string]dirusage.Usage {
sums := map[string]dirusage.Usage{"": {}}
for path, entry := range tree {
if !path.IsUnder(root) {
continue
}
if dirusage.TakenOff(dirusage.Expires(entry), atNs) {
continue
}
dir, _ := path.DirAndName()
if dirusage.Skipped(util.FullPath(dir)) {
continue
@@ -72,7 +75,7 @@ func totals(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath) map[stri
// directory up to MaxDepth below it holding its share, and nothing else.
func expectSeeded(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry) {
t.Helper()
sums := totals(tree, util.FullPath(record.Root))
sums := totals(tree, util.FullPath(record.Root), record.TsNs)
want := map[string]dirusage.Usage{}
for rel, usage := range sums {
if rel == "" || depthOf(rel) <= dirusage.MaxDepth && holdsShare(usage, sums[""]) {
@@ -82,10 +85,10 @@ func expectSeeded(t *testing.T, record *dirusage.Record, tree map[util.FullPath]
expectDirs(t, record, want)
}
// expectTracked checks each total a record keeps against the tree.
func expectTracked(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry) {
// expectTracked checks each total a record keeps against the tree at atNs.
func expectTracked(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry, atNs int64) {
t.Helper()
sums := totals(tree, util.FullPath(record.Root))
sums := totals(tree, util.FullPath(record.Root), atNs)
for rel, usage := range record.Dirs {
if want, found := sums[rel]; !found || usage != want {
t.Errorf("%s %q: %+v, the tree has %+v", record.Root, rel, usage, want)
@@ -125,7 +128,8 @@ func runAt(t *testing.T, client filer_pb.FilerClient, now time.Time) *runStats {
func expectCurrent(t *testing.T, f *treewalktest.Filer, records map[util.FullPath]*dirusage.Record, cursor int64) {
t.Helper()
for _, record := range records {
expectTracked(t, record, f.At(max(record.TsNs, cursor)))
at := max(record.TsNs, cursor)
expectTracked(t, record, f.At(at), at)
}
}
@@ -254,7 +258,7 @@ func TestRunSeedsWhileTheTreeChanges(t *testing.T) {
}
records, _ := loadRecords(t, client)
for _, record := range records {
expectTracked(t, record, f.At(record.TsNs))
expectTracked(t, record, f.At(record.TsNs), record.TsNs)
}
// and the next run picks up from there
@@ -378,3 +382,110 @@ func TestRunSavesTheOtherSeededRecordsWhenOneSaveFails(t *testing.T) {
}
expectCurrent(t, f, records, cursor)
}
func TestRunTakesOffWhatATTLExpires(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
now := time.Now()
f.Put("/buckets/b1/a/keep", 1000, 1)
f.PutTTL("/buckets/b1/a/soon", 500, now, 30*time.Minute)
f.PutTTL("/buckets/b1/b/later", 300, now, 240*time.Hour)
// below 1%: what expires there comes off b1 itself
f.PutTTL("/buckets/b1/c/tiny", 5, now, 30*time.Minute)
runOnce(t, client)
records, _ := loadRecords(t, client)
b1 := records["/buckets/b1"]
if b1 == nil || b1.Dirs[""].Bytes != 1805 || len(b1.Expiring) != 2 {
t.Fatalf("seeded b1: %+v", b1)
}
if _, kept := b1.Dirs["c"]; kept {
t.Fatalf("b1 keeps c, below its share")
}
expectSeeded(t, b1, f.At(b1.TsNs))
// three hours on, on the filer's clock
f.Skew = 3 * time.Hour
if stats := runOnce(t, client); stats.written != 1 {
t.Errorf("wrote %d records, want b1", stats.written)
}
records, cursor := loadRecords(t, client)
b1 = records["/buckets/b1"]
if b1.Dirs[""].Bytes != 1300 || b1.Dirs["a"].Bytes != 1000 || len(b1.Expiring) != 1 {
t.Errorf("b1 after the first TTL: %+v, expiring %+v", b1.Dirs, b1.Expiring)
}
expectCurrent(t, f, records, cursor)
}
func TestSeedingSharesAreThoseAfterWhatExpired(t *testing.T) {
start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC)
s := &seeding{roots: dirusage.NewRoots("/buckets"), dirs: make(map[util.FullPath]map[string]*seedDir)}
add := func(dir util.FullPath, entry *filer_pb.Entry) {
value := dirusage.EntryValue(entry)
s.change(dir, entry.Name, nil, &value)
}
s.started("/buckets/b", 0)
add("/buckets/b", testDir("keep"))
add("/buckets/b", testDir("tmp"))
// keep is walked first and holds all the walk counted then; what tmp
// holds expires before the walk ends
s.started("/buckets/b/keep", 1)
add("/buckets/b/keep", testFile("k", 5))
s.done("/buckets/b/keep", 1)
s.started("/buckets/b/tmp", 1)
add("/buckets/b/tmp", testTTLFile("t", 1000, start.Add(30*time.Minute)))
s.done("/buckets/b/tmp", 1)
s.done("/buckets/b", 0)
record := s.records(hourAfter(start.Add(30*time.Minute)) * int64(time.Second))["/buckets/b"]
expectDirs(t, record, map[string]dirusage.Usage{
"": {Bytes: 5, Chunks: 1, Files: 1, Dirs: 2},
"keep": {Bytes: 5, Chunks: 1, Files: 1},
})
if len(record.Expiring) != 0 {
t.Errorf("still waiting: %+v", record.Expiring)
}
// a directory dropped for its share hands what it has still to expire
// to the directory above
s = &seeding{roots: dirusage.NewRoots("/buckets"), dirs: make(map[util.FullPath]map[string]*seedDir)}
s.started("/buckets/b", 0)
add("/buckets/b", testDir("big"))
add("/buckets/b", testDir("small"))
s.started("/buckets/b/small", 1)
add("/buckets/b/small", testTTLFile("s", 5, start.Add(5*time.Hour)))
s.done("/buckets/b/small", 1)
s.started("/buckets/b/big", 1)
add("/buckets/b/big", testFile("g", 1000))
s.done("/buckets/b/big", 1)
s.done("/buckets/b", 0)
record = s.records(start.UnixNano())["/buckets/b"]
expectDirs(t, record, map[string]dirusage.Usage{
"": {Bytes: 1005, Chunks: 2, Files: 2, Dirs: 2},
"big": {Bytes: 1000, Chunks: 1, Files: 1},
})
if got := record.Expiring[hourAfter(start.Add(5*time.Hour))]; len(got) != 1 || got[""] != (dirusage.Usage{Bytes: 5, Chunks: 1, Files: 1}) {
t.Errorf("waiting to expire: %+v", record.Expiring)
}
}
func TestRunSeedsAgainARecordOfAnotherVersion(t *testing.T) {
shortLogMargin(t)
f, client := newTestFiler(t, time.Hour)
buildBuckets(f)
runOnce(t, client)
store := &dirusage.Store{Client: client, Signature: 1, Roots: dirusage.Roots{Buckets: "/buckets"}}
old, err := store.Load(context.Background(), "/buckets/b2")
if err != nil || old == nil {
t.Fatalf("load b2: %v, %v", old, err)
}
old.Version = 1
if err := store.Save(context.Background(), old); err != nil {
t.Fatal(err)
}
if stats := runOnce(t, client); stats.seeded != 1 {
t.Errorf("seeded %d roots, want b2 again", stats.seeded)
}
records, _ := loadRecords(t, client)
if b2 := records["/buckets/b2"]; b2 == nil || b2.Version != dirusage.Version {
t.Errorf("b2 record %+v", b2)
}
}
+146
View File
@@ -2,9 +2,11 @@ package dir_usage
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer/dirusage"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -189,3 +191,147 @@ func TestHoldsShare(t *testing.T) {
t.Errorf("a non-empty directory of a tiny bucket holds its share; an empty one never does")
}
}
// testTTLFile is a file of size that a plain TTL takes out at expiresAt.
func testTTLFile(name string, size uint64, expiresAt time.Time) *filer_pb.Entry {
entry := testFile(name, size)
entry.Attributes.Crtime = expiresAt.Add(-time.Hour).Unix()
entry.Attributes.TtlSec = int32(time.Hour / time.Second)
return entry
}
func hourAfter(t time.Time) int64 {
return (t.Unix() + 3599) / 3600 * 3600
}
func TestTrackerTakesOffWhatATTLExpiresAtTheEndOfItsStep(t *testing.T) {
start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC)
expires := start.Add(90 * time.Minute)
record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{"": {}, "a": {}})
tr := newTestTracker(record)
applyAll(t, tr,
testEvent(start.UnixNano()+1, "/buckets/b/a/deep", nil, testTTLFile("f", 10, expires), ""),
testEvent(start.UnixNano()+2, "/buckets/b/a", nil, testFile("g", 5), ""),
)
expectDirs(t, record, map[string]dirusage.Usage{
"": {Bytes: 15, Chunks: 2, Files: 2},
"a": {Bytes: 15, Chunks: 2, Files: 2},
})
end := hourAfter(expires)
if got := record.Expiring[end]["a"]; got != (dirusage.Usage{Bytes: 10, Chunks: 1, Files: 1}) {
t.Errorf("waiting to expire at %d under a: %+v, all %+v", end, got, record.Expiring)
}
if takeOffExpired(record, end*int64(time.Second)-1) {
t.Errorf("took off before the end of its step")
}
if !takeOffExpired(record, end*int64(time.Second)) {
t.Errorf("took nothing off at the end of its step")
}
expectDirs(t, record, map[string]dirusage.Usage{
"": {Bytes: 5, Chunks: 1, Files: 1},
"a": {Bytes: 5, Chunks: 1, Files: 1},
})
if len(record.Expiring) != 0 {
t.Errorf("still waiting: %+v", record.Expiring)
}
}
func TestTrackerWithdrawsAnEntryGoneBeforeItExpires(t *testing.T) {
start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC)
file := testTTLFile("f", 10, start.Add(time.Hour))
longer := testTTLFile("f", 30, start.Add(5*time.Hour))
record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{"": {}})
tr := newTestTracker(record)
applyAll(t, tr,
testEvent(start.UnixNano()+1, "/buckets/b", nil, file, ""),
// written again with a later expiry, then deleted
testEvent(start.UnixNano()+2, "/buckets/b", file, longer, ""),
testEvent(start.UnixNano()+3, "/buckets/b", longer, nil, ""),
)
expectDirs(t, record, map[string]dirusage.Usage{"": {}})
if len(record.Expiring) != 0 {
t.Errorf("still waiting: %+v", record.Expiring)
}
}
func TestTrackerTakesOffAnExpiredEntryOnce(t *testing.T) {
// the step f expired in ended before the record's position, so f was
// taken off then
start := time.Date(2026, 12, 4, 6, 0, 0, 0, time.UTC)
expired := testTTLFile("f", 10, start.Add(-2*time.Hour))
record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{"": {Bytes: 1, Files: 1, Chunks: 1}})
tr := newTestTracker(record)
applyAll(t, tr,
// an S3 delete or a listing removes the expired entry, with an event
testEvent(start.UnixNano()+1, "/buckets/b", expired, nil, ""),
// a write whose TTL had passed before it lands never shows
testEvent(start.UnixNano()+2, "/buckets/b", nil, testTTLFile("g", 7, start.Add(-time.Hour)), ""),
)
expectDirs(t, record, map[string]dirusage.Usage{"": {Bytes: 1, Files: 1, Chunks: 1}})
}
func TestTrackerExpiresS3ObjectsUnlessVersioned(t *testing.T) {
start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC)
s3Object := func(name string, versioned bool) *filer_pb.Entry {
entry := testFile(name, 10)
entry.Attributes.Mtime = start.Unix()
entry.Attributes.TtlSec = int32(time.Hour / time.Second)
entry.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
if versioned {
entry.Extended[s3_constants.ExtVersionIdKey] = []byte("v1")
}
return entry
}
if got, want := dirusage.Expires(s3Object("o", false)), hourAfter(start.Add(time.Hour)); got != want {
t.Errorf("S3 object comes off at %d, want %d", got, want)
}
if got := dirusage.Expires(s3Object("v", true)); got != 0 {
t.Errorf("a version of a versioned object comes off at %d", got)
}
if got := dirusage.Expires(testDir("d")); got != 0 {
t.Errorf("a directory comes off at %d", got)
}
}
func TestTrackerMovesWhatExpiresWithAMovedDirectory(t *testing.T) {
start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC)
file := testTTLFile("f", 10, start.Add(time.Hour))
hour := hourAfter(start.Add(time.Hour))
record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{
"": {Bytes: 10, Files: 1, Chunks: 1, Dirs: 1},
"x": {Bytes: 10, Files: 1, Chunks: 1},
})
record.Expiring = map[int64]map[string]dirusage.Usage{hour: {"x": {Bytes: 10, Files: 1, Chunks: 1}}}
tr := newTestTracker(record)
applyAll(t, tr,
testEvent(start.UnixNano()+1, "/buckets/b", testDir("x"), testDir("y"), ""),
testEvent(start.UnixNano()+2, "/buckets/b/x", file, file, "/buckets/b/y"),
)
expectDirs(t, record, map[string]dirusage.Usage{
"": {Bytes: 10, Files: 1, Chunks: 1, Dirs: 1},
"y": {Bytes: 10, Files: 1, Chunks: 1},
})
if got := record.Expiring[hour]; len(got) != 1 || got["y"] != (dirusage.Usage{Bytes: 10, Files: 1, Chunks: 1}) {
t.Errorf("waiting to expire: %+v", record.Expiring)
}
}
func TestTrackerDropsWhatExpiresUnderADeletedDirectory(t *testing.T) {
start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC)
hour := hourAfter(start.Add(time.Hour))
record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{
"": {Bytes: 15, Files: 2, Chunks: 2, Dirs: 1},
"x": {Bytes: 10, Files: 1, Chunks: 1},
})
record.Expiring = map[int64]map[string]dirusage.Usage{hour: {
"x": {Bytes: 10, Files: 1, Chunks: 1},
"": {Bytes: 5, Files: 1, Chunks: 1},
}}
tr := newTestTracker(record)
// deleted with nothing logged for what was in it
applyAll(t, tr, testEvent(start.UnixNano()+1, "/buckets/b", testDir("x"), nil, ""))
expectDirs(t, record, map[string]dirusage.Usage{"": {Bytes: 5, Files: 1, Chunks: 1}})
if got := record.Expiring[hour]; len(got) != 1 || got[""] != (dirusage.Usage{Bytes: 5, Files: 1, Chunks: 1}) {
t.Errorf("waiting to expire: %+v", record.Expiring)
}
}