mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6317e3beb | ||
|
|
3404bf5e00 | ||
|
|
e58a806489 | ||
|
|
62bd08e0c0 |
No files matched your search
@@ -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, unit-group coordinator and relative documentation link check 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 of the test, spec-trace and known-bugs jobs then use that label. The post-merge-review paths check and the release always run hosted. 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.
|
||||
@@ -1,408 +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 shutil
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[2]
|
||||
|
||||
|
||||
class PortTests(unittest.TestCase):
|
||||
def test_relative_documentation_links_are_checked(self):
|
||||
text = (ROOT / ".github/workflows/block-test.yml").read_text()
|
||||
marker = " - name: Relative documentation links\n"
|
||||
self.assertEqual(text.count(marker), 1)
|
||||
step = text.split(marker, 1)[1].split("\n - name:", 1)[0]
|
||||
self.assertIn("if: matrix.suite == 'unit'", step)
|
||||
self.assertIn("python3 -B ../.github/block/scripts/doc-links-check-test.py", step)
|
||||
self.assertIn("python3 -I ../.github/block/scripts/doc-links-check.py .", step)
|
||||
self.assertNotIn("continue-on-error", step)
|
||||
self.assertNotIn("|| true", step)
|
||||
|
||||
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)
|
||||
if name == "post-merge-review":
|
||||
self.assertIn("runs-on: ubuntu-latest", text)
|
||||
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
|
||||
else:
|
||||
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 --no-renames HEAD^1 HEAD -- .", test)
|
||||
self.assertIn("go test (linux)", test)
|
||||
self.assertIn("process-level tests (real binaries)", test)
|
||||
scope = test.split(" - name: Docs-only pull request\n", 1)[1].split("\n", 2)[1]
|
||||
self.assertEqual(scope.strip(), "if: matrix.suite == 'process' && github.event_name == 'pull_request'")
|
||||
self.assertEqual(test.count("if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'"), 5)
|
||||
self.assertNotRegex(test, r"if: matrix\.suite == 'process'\s*\n")
|
||||
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
|
||||
self.assertIn("working-directory: ${{ github.workspace }}", post)
|
||||
|
||||
def test_labelled_post_merge_review_refuses_host_files(self):
|
||||
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
|
||||
step = post.split(" - name: Check changed paths\n", 1)[1].split(" run: |\n", 1)[1].split("\n\n - name:", 1)[0]
|
||||
script = "\n".join(line[10:] for line in step.splitlines())
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); module = root / "seaweed-block"
|
||||
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")
|
||||
for name in ("post-merge-review-check.sh", "post-merge-review-allow.txt"):
|
||||
source = ROOT / "seaweed-block/.github" / ("scripts/" + name if name.endswith(".sh") else name)
|
||||
target = module / ".github" / ("scripts/" + name if name.endswith(".sh") else name)
|
||||
target.parent.mkdir(parents=True, exist_ok=True); target.write_bytes(source.read_bytes())
|
||||
(module / ".github/scripts/post-merge-review-check-test.sh").write_text("exit 0\n")
|
||||
(root / ".github/block/scripts").mkdir(parents=True)
|
||||
(root / ".github/block/scripts/post-merge-review-changed.sh").write_bytes((HERE / "post-merge-review-changed.sh").read_bytes())
|
||||
git("add", "."); git("commit", "-m", "base"); git("remote", "add", "origin", str(root))
|
||||
base = git("rev-parse", "HEAD").decode().strip()
|
||||
def check(*paths):
|
||||
git("reset", "-q", "--hard", base)
|
||||
for path in paths: (root / path).parent.mkdir(parents=True, exist_ok=True); (root / path).write_text("changed\n")
|
||||
git("add", "--", *paths); git("commit", "-m", "change")
|
||||
git("update-ref", "refs/pull/1/head", "HEAD")
|
||||
env = dict(os.environ, BASE=base, HEAD=git("rev-parse", "HEAD").decode().strip(), PR="1")
|
||||
return subprocess.run(["bash", "-eo", "pipefail", "-c", script], cwd=module, env=env, capture_output=True, timeout=30)
|
||||
self.assertEqual(check("seaweed-block/docs/a.md").returncode, 0)
|
||||
for host in ("weed/example_test.go", "README.md", "docs/a.md"):
|
||||
out = check("seaweed-block/docs/a.md", host)
|
||||
self.assertEqual(out.returncode, 1, out)
|
||||
self.assertEqual([l for l in out.stdout.splitlines() if l.startswith(b"DENY")], [b"DENY host " + host.encode() + b" (outside seaweed-block)"])
|
||||
|
||||
def test_known_bugs_use_the_module_verdict_helper(self):
|
||||
text = (ROOT / ".github/workflows/block-known-bugs.yml").read_text()
|
||||
self.assertIn("bash .github/scripts/known-bugs-test.sh", text)
|
||||
self.assertIn("bash .github/scripts/known-bugs.sh <<'LIST'", text)
|
||||
rows = text.split("<<'LIST'\n", 1)[1].split("\n LIST", 1)[0].split("\n")
|
||||
self.assertTrue(rows)
|
||||
for row in rows:
|
||||
issue, pkg, test = row.split()
|
||||
sources = (ROOT / "seaweed-block" / pkg).glob("*_test.go")
|
||||
self.assertTrue(any("func " + test + "(" in s.read_text() for s in sources), row)
|
||||
|
||||
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('gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber', text)
|
||||
publish = 'gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false'
|
||||
self.assertLess(text.index("--clobber"), text.index(publish))
|
||||
self.assertIn("runs-on: ubuntu-latest", text)
|
||||
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
|
||||
self.assertIn('sw-block-${version}-linux-amd64.tar.gz', text)
|
||||
self.assertNotIn("go build", text)
|
||||
self.assertLess(text.index("refusing to publish: release notes"), text.index("docker/build-push-action"))
|
||||
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"))
|
||||
built = re.findall(r"go build -o (\S+)", recipe)
|
||||
refused = re.search(r"^RUN bash scripts/refuse-lab-binary\.sh (.+)$", recipe, re.M).group(1).split()
|
||||
self.assertTrue(built)
|
||||
self.assertEqual(sorted(built), sorted(refused))
|
||||
|
||||
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"))
|
||||
for durable in ("core/frontend/chunkstore/c.go", "core/storage/s.go", "core/frontend/durable/d.go"):
|
||||
(module / durable).parent.mkdir(parents=True, exist_ok=True); (module / durable).write_text("package x\n")
|
||||
git("add", "."); git("commit", "-m", "durable")
|
||||
self.assertEqual(run("chunkstore-scope.sh", head, "HEAD"), b"run 1 " + durable.encode() + b"\n")
|
||||
git("reset", "-q", "--hard", head)
|
||||
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")
|
||||
from_root = subprocess.check_output(["bash", str(HERE / "public-text-check.sh"), control_head, pattern_head, str(title), str(body)], cwd=root, timeout=20)
|
||||
self.assertEqual(from_root, b"public-text: clean\n")
|
||||
artifact_path = "docs/spec/" + "recorded-example.txt"
|
||||
artifact = module / artifact_path
|
||||
artifact.parent.mkdir(parents=True); artifact.write_text("")
|
||||
git("add", "."); git("commit", "-m", "artifact")
|
||||
artifact_head = git("rev-parse", "HEAD").decode().strip()
|
||||
command = ["bash", str(HERE / "public-text-check.sh"), pattern_head, artifact_head, str(title), str(body)]
|
||||
for cwd in (root, module):
|
||||
leak = subprocess.run(command, cwd=cwd, capture_output=True, timeout=20)
|
||||
self.assertEqual(leak.returncode, 1, (cwd, leak.stdout, leak.stderr))
|
||||
self.assertIn(b"artifact path: " + artifact_path.encode(), leak.stdout)
|
||||
git("rm", str(artifact.relative_to(root))); git("commit", "-m", "remove artifact")
|
||||
deleted = git("rev-parse", "HEAD").decode().strip()
|
||||
removal = ["bash", str(HERE / "public-text-check.sh"), artifact_head, deleted, str(title), str(body)]
|
||||
for cwd in (root, module):
|
||||
result = subprocess.run(removal, cwd=cwd, capture_output=True, timeout=20)
|
||||
self.assertEqual((result.returncode, result.stdout), (0, b"public-text: clean\n"), result.stderr)
|
||||
fakebin = root / "fakebin"; fakebin.mkdir()
|
||||
fakegit = fakebin / "git"
|
||||
fakegit.write_text("#!/bin/sh\nfor arg; do\n if [ \"$arg\" = --diff-filter=ACMT ]; then\n printf 'docs/spec/partial.txt\\0'\n exit 23\n fi\ndone\nexec \"$PUBLIC_TEXT_REAL_GIT\" \"$@\"\n")
|
||||
fakegit.chmod(0o755)
|
||||
env = dict(os.environ, PUBLIC_TEXT_REAL_GIT=shutil.which("git"), PATH=str(fakebin) + os.pathsep + os.environ["PATH"])
|
||||
for cwd in (root, module):
|
||||
result = subprocess.run(removal, cwd=cwd, env=env, capture_output=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 2, (cwd, result.stdout, result.stderr))
|
||||
self.assertIn(b"cannot enumerate artifact paths", result.stderr)
|
||||
self.assertNotIn(b"public-text: clean", result.stdout)
|
||||
|
||||
def test_public_text_adapter_passes_the_module_self_test(self):
|
||||
module = ROOT / "seaweed-block/.github/scripts"
|
||||
pattern = lambda path: [l for l in path.read_text().splitlines() if l.startswith("pat=")]
|
||||
self.assertEqual(pattern(HERE / "public-text-check.sh"), pattern(module / "public-text-check.sh"))
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for source in (module / "public-text-check-test.sh", HERE / "public-text-check.sh"):
|
||||
(Path(tmp) / source.name).write_bytes(source.read_bytes())
|
||||
subprocess.run(["bash", str(Path(tmp) / "public-text-check-test.sh")], check=True, capture_output=True, timeout=60)
|
||||
|
||||
|
||||
def test_root_block_ci_files_pass_the_public_text_scan(self):
|
||||
pat = next(l for l in (HERE / "public-text-check.sh").read_text().splitlines() if l.startswith("pat='"))[5:-1]
|
||||
files = [p for p in (ROOT / ".github/block").rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name != "public-text-check.sh"]
|
||||
files += sorted((ROOT / ".github/workflows").glob("block-*.yml")) + sorted((ROOT / ".github/dockerfiles").glob("block-*.Dockerfile"))
|
||||
hits = subprocess.run(["grep", "-E", "-i", "-n", "-H", "--", pat, *map(str, files)], capture_output=True, timeout=20)
|
||||
self.assertEqual(hits.returncode, 1, hits.stdout.decode() + hits.stderr.decode())
|
||||
|
||||
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 = {"path": ".github/workflows/block-test.yml", "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_same_named_workflow_cannot_satisfy_the_gate(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 = {"id": 1, "created_at": "1", "path": ".github/workflows/block-test.yml", "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]
|
||||
duplicate = dict(run, id=2, created_at="2", path=".github/workflows/pretend.yml")
|
||||
with self.assertRaises(ValueError): check.validate(pr, duplicate, jobs, "base")
|
||||
missing = dict(run); del missing["path"]
|
||||
with self.assertRaises(ValueError): check.validate(pr, missing, jobs, "base")
|
||||
import json
|
||||
with patch.object(check, "api", return_value={"workflow_runs": [run, duplicate]}), patch.object(check.subprocess, "check_output", return_value=json.dumps([{"jobs": jobs}]).encode()):
|
||||
self.assertEqual(check.successful_run(pr, "base")["id"], 1)
|
||||
with patch.object(check, "api", return_value={"workflow_runs": [duplicate]}):
|
||||
with self.assertRaises(ValueError): check.successful_run(pr, "base")
|
||||
|
||||
def test_control_path_changes_need_independent_workflow_review(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)
|
||||
real_output = subprocess.check_output
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
def git(*args): return real_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")
|
||||
(root / "code.go").write_text("package example")
|
||||
git("add", "."); git("commit", "-m", "base")
|
||||
base = git("rev-parse", "HEAD").decode().strip()
|
||||
for name in (".github/workflows/pretend.yml", ".github/block/scripts/check.py", ".github/dockerfiles/block-image.Dockerfile", "seaweed-block/.github/scripts/record-go-test.sh"):
|
||||
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text("control")
|
||||
git("add", "."); git("commit", "-m", "control")
|
||||
added = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.check_control_paths(base, added)
|
||||
git("rm", name); git("commit", "-m", "remove")
|
||||
removed = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.check_control_paths(added, removed)
|
||||
(root / "code.go").write_text("package example\nconst N=2")
|
||||
git("add", "."); git("commit", "-m", "code")
|
||||
head = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
check.check_control_paths(base, head)
|
||||
git("checkout", "-q", "-b", "master-later", base)
|
||||
(root / ".github/workflows").mkdir(parents=True, exist_ok=True)
|
||||
(root / ".github/workflows/block-test.yml").write_text("master control")
|
||||
git("add", "."); git("commit", "-m", "master control")
|
||||
master = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
check.check_control_paths(master, head)
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.check_control_paths(head, master)
|
||||
with patch.object(check, "check_control_paths", side_effect=ValueError("workflow_review_required")), patch.object(check.subprocess, "check_output", side_effect=["base", "head"]), patch.object(check.subprocess, "run") as run:
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.local_checks({"number": 1, "body": "body", "title": "title", "head": {"sha": "head"}}, "base")
|
||||
self.assertEqual(run.call_count, 1) # fetch only; no checker certification
|
||||
|
||||
def test_control_path_diff_refuses_multiple_merge_bases(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)
|
||||
real_output = subprocess.check_output
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
def git(*args): return real_output(["git", *args], cwd=root, timeout=15).decode().strip()
|
||||
git("init", "-b", "master")
|
||||
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
|
||||
git("config", "commit.gpgsign", "false")
|
||||
git("commit", "--allow-empty", "-m", "base"); base = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "-b", "left")
|
||||
(root / "left.txt").write_text("left")
|
||||
git("add", "."); git("commit", "-m", "left"); left = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "-b", "right", base)
|
||||
(root / "right.txt").write_text("right")
|
||||
git("add", "."); git("commit", "-m", "right"); right = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "left"); git("merge", "--no-ff", right, "-m", "left merge")
|
||||
left_merge = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "right"); git("merge", "--no-ff", left, "-m", "right merge")
|
||||
right_merge = git("rev-parse", "HEAD")
|
||||
self.assertEqual(set(git("merge-base", "--all", left_merge, right_merge).splitlines()), {left, right})
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
with self.assertRaisesRegex(ValueError, "ambiguous_merge_base"):
|
||||
check.check_control_paths(left_merge, right_merge)
|
||||
check.check_control_paths(left, left_merge)
|
||||
|
||||
def test_fork_runner_guard_is_required_not_only_the_fallback(self):
|
||||
expected = "${{ (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' }}"
|
||||
for name in ("test", "spec-trace", "known-bugs"):
|
||||
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip().startswith("runs-on:")]
|
||||
self.assertEqual(lines, ["runs-on: " + expected])
|
||||
|
||||
def test_rerun_during_local_checks_cannot_report_ready(self):
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
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)
|
||||
def pr(number):
|
||||
return {"number": number, "state": "open", "draft": False, "mergeable": True,
|
||||
"base": {"ref": "master"}, "head": {"sha": str(number)}}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
evidence = Path(tmp) / "acceptance"; evidence.write_text("accepted")
|
||||
members = [pr(1), pr(2)]
|
||||
manifest = {"base": "base", "head": "3", "batch_pr": 3,
|
||||
"prs": [{"number": n, "head": str(n), "evidence": str(evidence)} for n in (1, 2)]}
|
||||
path = Path(tmp) / "batch.json"; path.write_text(json.dumps(manifest))
|
||||
for batch in (False, True):
|
||||
for outcome in ("in_progress", "failed_run", "failed_job", "new_run", "success"):
|
||||
with self.subTest(batch=batch, outcome=outcome):
|
||||
changed = False
|
||||
observations = []
|
||||
number = 3 if batch else 1
|
||||
def api(endpoint):
|
||||
if endpoint == "git/ref/heads/master": return {"object": {"sha": "base"}}
|
||||
if endpoint.startswith("pulls/"): return pr(int(endpoint.split("/")[-1]))
|
||||
if endpoint == "git/commits/3": return {"tree": {"sha": "tree"}}
|
||||
observations.append(("run", changed))
|
||||
run = {"id": 10, "run_attempt": 2 if changed else 1, "created_at": "1",
|
||||
"path": check.WORKFLOW_PATH, "name": "Block Test", "head_sha": str(number),
|
||||
"status": "completed", "conclusion": "success",
|
||||
"pull_requests": [{"number": number, "base": {"sha": "base"}}]}
|
||||
if changed and outcome in ("in_progress", "new_run"):
|
||||
run.update(status="in_progress", conclusion=None)
|
||||
if outcome == "new_run": run.update(id=11, created_at="2")
|
||||
if changed and outcome == "failed_run": run["conclusion"] = "failure"
|
||||
return {"workflow_runs": [run]}
|
||||
def jobs(*args, **kwargs):
|
||||
observations.append(("jobs", changed))
|
||||
result = [{"name": name, "conclusion": "success"} for name in check.JOBS]
|
||||
if changed and outcome == "failed_job": result[0]["conclusion"] = "failure"
|
||||
return json.dumps([{"jobs": result}]).encode()
|
||||
def local(*args):
|
||||
nonlocal changed
|
||||
changed = True
|
||||
output = io.StringIO()
|
||||
with patch.object(check, "api", side_effect=api), patch.object(check.subprocess, "check_output", side_effect=jobs), patch.object(check, "fetch_review_head"), patch.object(check, "local_checks", side_effect=local), contextlib.redirect_stdout(output):
|
||||
if outcome == "success":
|
||||
check.main(["--batch", str(path)] if batch else ["1"])
|
||||
else:
|
||||
with self.assertRaises(ValueError):
|
||||
check.main(["--batch", str(path)] if batch else ["1"])
|
||||
if outcome == "success":
|
||||
self.assertTrue(json.loads(output.getvalue())["ready"])
|
||||
else:
|
||||
self.assertNotIn('"ready": true', output.getvalue())
|
||||
self.assertIn(("run", True), observations)
|
||||
self.assertIn(("jobs", True), observations)
|
||||
|
||||
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")
|
||||
batch_manifest = dict(manifest, batch_pr=3)
|
||||
manifest_path = Path(tmp) / "batch.json"
|
||||
import json
|
||||
manifest_path.write_text(json.dumps(batch_manifest))
|
||||
replies = {"git/ref/heads/master": {"object": {"sha": "base"}}, "pulls/1": prs[0], "pulls/2": prs[1], "pulls/3": {"number": 3, "head": {"sha": "batch"}}}
|
||||
with patch.object(check, "api", side_effect=lambda path: replies[path]), patch.object(check, "fetch_review_head", side_effect=ValueError("workflow_review_required")) as fetch, patch.object(check, "successful_run") as run:
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.main(["--batch", str(manifest_path)])
|
||||
fetch.assert_called_once_with(replies["pulls/3"], "base")
|
||||
run.assert_not_called()
|
||||
evidence.write_text("")
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base")
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -1,142 +0,0 @@
|
||||
"""Relative Markdown links must resolve; code, anchors and URLs are not paths."""
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location("links", Path(__file__).with_name("doc-links-check.py"))
|
||||
links = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(links)
|
||||
|
||||
|
||||
class DocLinksTests(unittest.TestCase):
|
||||
def check(self, files):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
for name, text in files.items():
|
||||
path = Path(root, name)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
return [(source, target) for source, _, target in links.broken_links(root)]
|
||||
|
||||
def test_existing_targets_pass(self):
|
||||
broken = self.check({
|
||||
"README.md": "[guide](docs/guide.md#start)  [dir](docs/) [ref][r]\n\n[r]: <docs/a b.md>\n",
|
||||
"docs/guide.md": "[up](../README.md) [root](/docs/d.svg) [esc](a%20b.md)\n",
|
||||
"docs/d.svg": "",
|
||||
"docs/a b.md": "",
|
||||
})
|
||||
self.assertEqual(broken, [])
|
||||
|
||||
def test_missing_targets_fail(self):
|
||||
broken = self.check({
|
||||
"README.md": "[gone](docs/gone.md) [nested [x]](docs/x.md#a)\n\n[r]: missing.md\n",
|
||||
"docs/guide.md": "[up](../nope.md)\n",
|
||||
})
|
||||
self.assertCountEqual(broken, [
|
||||
("README.md", "docs/gone.md"),
|
||||
("README.md", "docs/x.md#a"),
|
||||
("README.md", "missing.md"),
|
||||
("docs/guide.md", "../nope.md"),
|
||||
])
|
||||
|
||||
def test_urls_anchors_and_code_are_not_checked(self):
|
||||
broken = self.check({
|
||||
"README.md": "\n".join([
|
||||
"[web](https://example.invalid/x) [mail](mailto:a@example.invalid) [top](#top) [proto](//host/x)",
|
||||
"`[code](gone.md)` and ``[code](gone.md)``",
|
||||
"```",
|
||||
"[fenced](gone.md)",
|
||||
"```",
|
||||
"~~~md",
|
||||
"[tilde](gone.md)",
|
||||
"~~~",
|
||||
]) + "\n",
|
||||
})
|
||||
self.assertEqual(broken, [])
|
||||
|
||||
def test_wrapped_labels_parentheses_and_long_fences(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
Path(root, "guide(v2).md").write_text("")
|
||||
Path(root, "README.md").write_text("\n".join([
|
||||
"[guide](guide(v2).md) [old](guide(v1).md)",
|
||||
"",
|
||||
"see the [wrapped",
|
||||
"label](wrapped.md) here",
|
||||
"",
|
||||
"`[wrapped",
|
||||
"code](gone.md)` then [after](after.md)",
|
||||
"````md",
|
||||
"```",
|
||||
"[example](missing.md)",
|
||||
"```",
|
||||
"````",
|
||||
]) + "\n")
|
||||
broken = [(line, target) for _, line, target in links.broken_links(root)]
|
||||
self.assertEqual(broken, [(1, "guide(v1).md"), (3, "wrapped.md"), (7, "after.md")])
|
||||
|
||||
def test_code_spans_require_complete_equal_delimiter_runs(self):
|
||||
cases = [
|
||||
("`unmatched\n[real](real.md) ``", [(2, "real.md")]),
|
||||
("``unmatched\n[real](real.md) `", [(2, "real.md")]),
|
||||
("``unmatched\n[real](real.md) ```", [(2, "real.md")]),
|
||||
("`[wrapped\ncode](hidden.md)`\n[after](after.md)", [(3, "after.md")]),
|
||||
("``[wrapped `\ncode](hidden.md)``\n[after](after.md)", [(3, "after.md")]),
|
||||
]
|
||||
for text, expected in cases:
|
||||
with self.subTest(text=text), tempfile.TemporaryDirectory() as root:
|
||||
Path(root, "README.md").write_text(text + "\n", encoding="utf-8")
|
||||
broken = [(line, target) for _, line, target in links.broken_links(root)]
|
||||
self.assertEqual(broken, expected)
|
||||
|
||||
def test_escaped_backticks_do_not_hide_links(self):
|
||||
cases = [
|
||||
("\\`\n[real](real.md)\n\\`", [(2, "real.md")]),
|
||||
("\\\\`[code](hidden.md)`\n[after](after.md)", [(2, "after.md")]),
|
||||
("`[code](hidden.md)\\`\n[after](after.md)", [(2, "after.md")]),
|
||||
]
|
||||
for text, expected in cases:
|
||||
with self.subTest(text=text):
|
||||
self.assertEqual(list(links.link_targets(text)), expected)
|
||||
|
||||
def test_masked_code_preserves_reference_line_context(self):
|
||||
text = "Use `code\nmore`[r]: gone.md\n\n[r]: real.md\n"
|
||||
self.assertEqual(list(links.link_targets(text)), [(4, "real.md")])
|
||||
|
||||
def test_code_masking_contract(self):
|
||||
cases = [
|
||||
("unequal runs", "`unmatched\n[real](real.md) ``", [], [(2, "real.md")]),
|
||||
("escaped delimiters", "\\`\n[real](real.md)\n\\`", [], [(2, "real.md")]),
|
||||
("reference context", "Use `code\nmore`[r]: gone.md\n\n[r]: real.md", [], [(4, "real.md")]),
|
||||
("wrapped span", "`[code\nhere](hidden.md)`\n[after](after.md)", [], [(3, "after.md")]),
|
||||
("hidden-space invalid target", "[example](`foo bar`)", [], []),
|
||||
("hidden-space invalid reference", "[r]: `a b`", [], []),
|
||||
("existing literal target", "[example](`foo.md`)", ["`foo.md`"], []),
|
||||
("missing literal target", "[example](`foo.md`)", [], [(1, "`foo.md`")]),
|
||||
]
|
||||
for name, text, existing, expected in cases:
|
||||
with self.subTest(name=name), tempfile.TemporaryDirectory() as root:
|
||||
Path(root, "README.md").write_text(text + "\n", encoding="utf-8")
|
||||
for target in existing:
|
||||
Path(root, target).touch()
|
||||
broken = [(line, target) for _, line, target in links.broken_links(root)]
|
||||
self.assertEqual(broken, expected)
|
||||
masked = links.mask_code_spans(text)
|
||||
self.assertEqual(len(masked), len(text))
|
||||
self.assertEqual([i for i, c in enumerate(masked) if c == "\n"],
|
||||
[i for i, c in enumerate(text) if c == "\n"])
|
||||
|
||||
def test_main_exit_status(self):
|
||||
out = io.StringIO()
|
||||
with tempfile.TemporaryDirectory() as root, contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
|
||||
Path(root, "README.md").write_text("[gone](gone.md)\n")
|
||||
self.assertEqual(links.main(["doc-links-check.py", root]), 1)
|
||||
Path(root, "gone.md").write_text("")
|
||||
self.assertEqual(links.main(["doc-links-check.py", root]), 0)
|
||||
self.assertEqual(links.main(["doc-links-check.py"]), 2)
|
||||
self.assertIn("README.md:1: broken relative link gone.md", out.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,128 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail when a Markdown file links to a relative path that does not exist.
|
||||
|
||||
Usage: doc-links-check.py <root>
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
SKIP_DIRS = {".git", "node_modules", "vendor"}
|
||||
FENCE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$")
|
||||
BACKTICKS = re.compile(r"`+")
|
||||
INLINE_DESTINATION = r"<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+"
|
||||
REFERENCE_DESTINATION = r"<[^>]*>|\S+"
|
||||
INLINE_LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\[\]]*\])*\]\(\s*(" + INLINE_DESTINATION + r")")
|
||||
REFERENCE = re.compile(r"^[ \t]{0,3}\[[^\]]+\]:\s*(" + REFERENCE_DESTINATION + r")", re.M)
|
||||
SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
|
||||
|
||||
|
||||
def mask_code_spans(text):
|
||||
runs = list(BACKTICKS.finditer(text))
|
||||
masked = list(text)
|
||||
i = 0
|
||||
while i < len(runs):
|
||||
opening = runs[i]
|
||||
start = opening.start()
|
||||
# Only prose escapes delimiters; backslashes inside code are literal.
|
||||
preceding = start
|
||||
while preceding > 0 and text[preceding - 1] == "\\":
|
||||
preceding -= 1
|
||||
if (start - preceding) % 2:
|
||||
start += 1
|
||||
width = opening.end() - start
|
||||
if not width:
|
||||
i += 1
|
||||
continue
|
||||
closing = next((j for j in range(i + 1, len(runs))
|
||||
if len(runs[j].group()) == width), None)
|
||||
if closing is None:
|
||||
i += 1
|
||||
continue
|
||||
# Keep columns and non-whitespace line context as well as line numbers.
|
||||
for pos in range(start, runs[closing].end()):
|
||||
if text[pos] != "\n":
|
||||
masked[pos] = "\0"
|
||||
i = closing + 1
|
||||
return "".join(masked)
|
||||
|
||||
|
||||
def paragraph_targets(first, lines):
|
||||
# A link label may wrap, so links are matched per paragraph.
|
||||
original = "\n".join(lines)
|
||||
text = mask_code_spans(original)
|
||||
# Masked bytes are context only, never a synthetic filesystem destination.
|
||||
found = []
|
||||
for regex, syntax in ((INLINE_LINK, INLINE_DESTINATION), (REFERENCE, REFERENCE_DESTINATION)):
|
||||
for match in regex.finditer(text):
|
||||
target = original[match.start(1):match.end(1)]
|
||||
if re.fullmatch(syntax, target):
|
||||
found.append((match.start(), target))
|
||||
for pos, target in sorted(found):
|
||||
yield first + text.count("\n", 0, pos), target
|
||||
|
||||
|
||||
def link_targets(text):
|
||||
fence, block, first = None, [], 1
|
||||
for lineno, line in enumerate(text.splitlines() + [""], 1):
|
||||
m = FENCE.match(line)
|
||||
if fence is not None:
|
||||
# Only a fence of the same character, at least as long, closes it.
|
||||
if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not m.group(2).strip():
|
||||
fence = None
|
||||
continue
|
||||
if m or not line.strip():
|
||||
yield from paragraph_targets(first, block)
|
||||
block = []
|
||||
if m:
|
||||
fence = m.group(1)
|
||||
continue
|
||||
if not block:
|
||||
first = lineno
|
||||
block.append(line)
|
||||
|
||||
|
||||
def local_path(target):
|
||||
if target.startswith("<") and target.endswith(">"):
|
||||
target = target[1:-1]
|
||||
if not target or target.startswith(("#", "//")) or SCHEME.match(target):
|
||||
return None
|
||||
path = urllib.parse.unquote(target.split("#", 1)[0].split("?", 1)[0])
|
||||
return path or None
|
||||
|
||||
|
||||
def broken_links(root):
|
||||
root = os.path.abspath(root)
|
||||
for dirpath, dirnames, filenames in os.walk(root):
|
||||
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
|
||||
for name in sorted(filenames):
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
source = os.path.join(dirpath, name)
|
||||
with open(source, encoding="utf-8", errors="replace") as f:
|
||||
text = f.read()
|
||||
for lineno, target in link_targets(text):
|
||||
path = local_path(target)
|
||||
if path is None:
|
||||
continue
|
||||
if path.startswith("/"):
|
||||
resolved = os.path.join(root, path.lstrip("/"))
|
||||
else:
|
||||
resolved = os.path.join(dirpath, path)
|
||||
if not os.path.exists(resolved):
|
||||
yield os.path.relpath(source, root), lineno, target
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
broken = list(broken_links(argv[1]))
|
||||
for source, lineno, target in broken:
|
||||
print(f"{source}:{lineno}: broken relative link {target}")
|
||||
return 1 if broken else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -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
|
||||
@@ -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,70 +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 names, machine paths and raw run artifacts 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|/home/[^/[:space:]]+/|(^|[^[:alnum:]_])pid[[:space:]]*[:=][[:space:]]*[0-9]+|[0-9]+[[:space:]]+cores[[:space:]]+with[[:space:]]+[0-9]+([.][0-9]+)?[[:space:]]*(KB|MB|GB|KiB|MiB|GiB)?[[:space:]]+heap|docs/spec/([^/[:space:]]+/)*recorded-[^/[:space:]]+'
|
||||
out=$(mktemp); paths=; trap 'rm -f "$out" "$paths"' EXIT
|
||||
paths=$(mktemp)
|
||||
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
|
||||
}
|
||||
# Raw run artifacts are not public specs, even with scrubbed contents.
|
||||
# Allow deletions so existing artifacts can be removed.
|
||||
repo_root=$(git rev-parse --show-toplevel)
|
||||
if ! (cd "$repo_root" && git diff --name-only -z --no-relative --no-renames --diff-filter=ACMT "$mb" "$head" -- docs/spec/ seaweed-block/docs/spec/) >"$paths"; then
|
||||
echo 'public-text: cannot enumerate artifact paths' >&2
|
||||
exit 2
|
||||
fi
|
||||
while IFS= read -r -d '' path; do
|
||||
# Match the module's paths the same way from either entry point.
|
||||
path=${path#seaweed-block/}
|
||||
if [[ $path =~ ^docs/spec/(.*/)?recorded-[^/]+(/|$) ]]; then
|
||||
printf '%s\n' "$path" | report "artifact path"
|
||||
fi
|
||||
done <"$paths"
|
||||
# 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' \
|
||||
':(exclude,top).github/block/scripts/public-text-check.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,145 +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)
|
||||
group = 12345
|
||||
leader = Mock(pid=group)
|
||||
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(group, signal.SIGTERM), killpg.call_args_list)
|
||||
self.assertIn(unittest.mock.call(group, 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()
|
||||
@@ -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))
|
||||
@@ -1,106 +0,0 @@
|
||||
"""Exercise the actual pre-checkout and always-run cleanup workflow bodies."""
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
WORKFLOWS = sorted((ROOT / ".github/workflows").glob("block-*.yml"))
|
||||
|
||||
|
||||
def step(text, name):
|
||||
marker = " - name: " + name + "\n"
|
||||
if text.count(marker) != 1:
|
||||
raise AssertionError("missing or duplicate " + name)
|
||||
return text.split(marker, 1)[1].split("\n - name:", 1)[0]
|
||||
|
||||
|
||||
def code(block):
|
||||
return textwrap.dedent(block.split(" run: |\n", 1)[1]).split("\n", 1)[1].rsplit("\nPY", 1)[0]
|
||||
|
||||
|
||||
def execute(source, workspace, temp, free=None):
|
||||
output = io.StringIO()
|
||||
with patch.dict(os.environ, {"GITHUB_WORKSPACE": str(workspace), "RUNNER_TEMP": str(temp)}), contextlib.redirect_stdout(output):
|
||||
with contextlib.ExitStack() as stack:
|
||||
if free is not None:
|
||||
stack.enter_context(patch("shutil.disk_usage", return_value=shutil._ntuple_diskusage(100_000_000_000, 0, free)))
|
||||
try:
|
||||
exec(compile(source, "<workflow>", "exec"), {})
|
||||
except SystemExit as err:
|
||||
return err.code, output.getvalue()
|
||||
return 0, output.getvalue()
|
||||
|
||||
|
||||
class RunnerWorkspaceTests(unittest.TestCase):
|
||||
def test_every_job_checks_before_checkout_and_cleans_last_even_on_failure(self):
|
||||
for path in WORKFLOWS:
|
||||
text = path.read_text()
|
||||
before = step(text, "Runner free space")
|
||||
after = step(text, "Clean job workspace")
|
||||
self.assertLess(text.index("- name: Runner free space"), text.index("- name: Checkout"), path.name)
|
||||
self.assertIn("if: always() && runner.environment == 'self-hosted'", after)
|
||||
self.assertNotIn("continue-on-error", after)
|
||||
self.assertNotIn("- name:", text.split("- name: Clean job workspace", 1)[1])
|
||||
self.assertIn("working-directory: ${{ runner.temp }}", before)
|
||||
self.assertIn("working-directory: ${{ runner.temp }}", after)
|
||||
self.assertIn("python3 -I -", before)
|
||||
self.assertIn("python3 -I -", after)
|
||||
|
||||
def test_low_space_refuses_and_boundary_admits(self):
|
||||
for path in WORKFLOWS:
|
||||
source = code(step(path.read_text(), "Runner free space"))
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
rc, out = execute(source, root, root, 9_999_999_999)
|
||||
self.assertEqual(rc, 75)
|
||||
self.assertIn("runner_disk_low", out)
|
||||
self.assertIn("required_bytes=10000000000", out)
|
||||
self.assertEqual(execute(source, root, root, 10_000_000_000)[0], 0)
|
||||
with patch("shutil.disk_usage", side_effect=[shutil._ntuple_diskusage(100, 0, 10_000_000_000), shutil._ntuple_diskusage(100, 0, 1)]):
|
||||
rc, out = execute(source, root / "work", root / "temp")
|
||||
self.assertEqual(rc, 75)
|
||||
self.assertIn("runner_disk_low", out)
|
||||
with patch("shutil.disk_usage", side_effect=OSError("probe failed")):
|
||||
rc, out = execute(source, root, root)
|
||||
self.assertEqual(rc, 75)
|
||||
self.assertIn("runner_disk_check_failed", out)
|
||||
|
||||
def test_cleanup_removes_hidden_and_build_files_but_not_symlink_targets(self):
|
||||
for path in WORKFLOWS:
|
||||
source = code(step(path.read_text(), "Clean job workspace"))
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp); work = root / "repo/repo"; work.mkdir(parents=True)
|
||||
(work / ".git").mkdir(); (work / ".git/config").write_text("config")
|
||||
(work / "binary").write_bytes(b"build")
|
||||
outside = root / "outside"; outside.mkdir(); (outside / "keep").write_text("keep")
|
||||
(work / "link").symlink_to(outside, target_is_directory=True)
|
||||
rc, out = execute(source, work, root)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual(list(work.iterdir()), [])
|
||||
self.assertTrue((outside / "keep").is_file())
|
||||
self.assertEqual(execute(source, root, root)[0], 1)
|
||||
self.assertEqual(execute(source, Path(root.anchor), root)[0], 1)
|
||||
alias = root / "alias"; alias.symlink_to(work, target_is_directory=True)
|
||||
self.assertEqual(execute(source, alias, root)[0], 1)
|
||||
|
||||
def test_cleanup_refuses_symlinked_ancestors_and_preserves_external_sentinel(self):
|
||||
for path in WORKFLOWS:
|
||||
with self.subTest(workflow=path.name), tempfile.TemporaryDirectory() as temp:
|
||||
base = Path(temp)
|
||||
external = base / "external/repo/repo"; external.mkdir(parents=True)
|
||||
sentinel = external / "keep"; sentinel.write_text("outside checkout")
|
||||
alias = base / "alias"; alias.symlink_to(base / "external", target_is_directory=True)
|
||||
source = code(step(path.read_text(), "Clean job workspace"))
|
||||
rc, out = execute(source, alias / "repo/repo", base)
|
||||
self.assertTrue(sentinel.is_file(), "cleanup followed a workspace ancestor outside the checkout")
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("runner_workspace_cleanup_refused", out)
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -1,132 +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"
|
||||
WORKFLOW_PATH = ".github/workflows/block-test.yml"
|
||||
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.get("path") != WORKFLOW_PATH or 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.get("path") == WORKFLOW_PATH and 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 check_control_paths(base, head):
|
||||
# Inspect both sides of renames and fail on enumeration errors. These PRs
|
||||
# need independent workflow review; their own Actions results cannot waive it.
|
||||
# Diff from the merge base: master's later control changes are not the PR's,
|
||||
# and the tested merge commit already ran them.
|
||||
bases = subprocess.check_output(["git", "merge-base", "--all", base, head]).decode("ascii").splitlines()
|
||||
if len(bases) != 1:
|
||||
raise ValueError("ambiguous_merge_base: expected exactly one merge base")
|
||||
paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", bases[0], head]).split(b"\0")
|
||||
controls = [p.decode("utf-8", errors="replace") for p in paths if p.startswith((b".github/workflows/", b".github/block/", b".github/dockerfiles/block-", b"seaweed-block/.github/"))]
|
||||
if controls:
|
||||
raise ValueError("workflow_review_required: CI controls changed: " + ", ".join(controls))
|
||||
|
||||
|
||||
def fetch_review_head(pr, current):
|
||||
if subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() != current:
|
||||
raise ValueError("run from trusted current master checkout")
|
||||
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")
|
||||
check_control_paths(current, actual)
|
||||
return actual
|
||||
|
||||
|
||||
def local_checks(pr, current):
|
||||
actual = fetch_review_head(pr, current)
|
||||
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(["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")
|
||||
fetch_review_head(batch, current)
|
||||
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")
|
||||
tree = api("git/commits/" + manifest["head"])["tree"]["sha"]
|
||||
# A rerun can invalidate the earlier success while local checks execute.
|
||||
run = successful_run(batch, current)
|
||||
print(json.dumps({"ready": True, "base": current, "head": manifest["head"], "run": run["id"], "tree": tree, "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")
|
||||
# Refresh the latest run and both jobs after every potentially slow check.
|
||||
run = successful_run(pr, current)
|
||||
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()
|
||||
@@ -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
|
||||
@@ -1,127 +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: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- 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: Known-bug verdict controls
|
||||
run: bash .github/scripts/known-bugs-test.sh
|
||||
|
||||
- name: Each reproduction still fails
|
||||
run: |
|
||||
bash .github/scripts/known-bugs.sh <<'LIST'
|
||||
#186 ./cmd/blockmaster/ TestChartOptInLoopbackFlagIsAcceptedByBlockmaster
|
||||
LIST
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,146 +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: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- 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
|
||||
# The allow list speaks for the module only: any host file keeps the full review.
|
||||
git -C .. diff -z --name-only --no-renames "$BASE...$HEAD" -- . ':(exclude)seaweed-block/' \
|
||||
':(exclude).github/workflows/block-*.yml' ':(exclude).github/dockerfiles/block-*.Dockerfile' ':(exclude).github/block/**' >host.bin
|
||||
host=0
|
||||
while IFS= read -r -d '' path; do
|
||||
printf 'DENY host %q (outside seaweed-block)\n' "$path"
|
||||
host=1
|
||||
done <host.bin
|
||||
bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt <changed.bin
|
||||
exit "$host"
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,201 +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: ubuntu-latest
|
||||
steps:
|
||||
- name: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- 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
|
||||
notes="seaweed-block/docs/releases/${version%%-*}.md"
|
||||
if [[ ! -s "${notes}" ]]; then
|
||||
echo "refusing to publish: release notes ${notes} are missing or empty" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "notes=${notes}" >> "$GITHUB_OUTPUT"
|
||||
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 }}
|
||||
NOTES: ${{ steps.tags.outputs.notes }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#seaweed-block/}"
|
||||
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)
|
||||
prerelease=false
|
||||
if [[ "$version" == *-* ]]; then prerelease=true; fi
|
||||
# A rerun replaces the assets, then publishes a draft an interrupted run left.
|
||||
if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber
|
||||
gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --verify-tag --latest=false \
|
||||
--prerelease="$prerelease" --title "Seaweed Block $version" --notes-file "$NOTES"
|
||||
fi
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,164 +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: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- 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
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,445 +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 commit for pushes). A new push to a PR cancels the
|
||||
# superseded run; a queued master run would be replaced by a newer one in a
|
||||
# shared group, so each merge gets its own group and its own result.
|
||||
concurrency:
|
||||
group: block-test-${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
|
||||
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: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- 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
|
||||
python3 -B ../.github/block/scripts/runner-workspace-test.py
|
||||
|
||||
- name: Relative documentation links
|
||||
if: matrix.suite == 'unit'
|
||||
run: |
|
||||
python3 -B ../.github/block/scripts/doc-links-check-test.py
|
||||
python3 -I ../.github/block/scripts/doc-links-check.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 --no-renames 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
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -9,7 +9,6 @@ on:
|
||||
- 'weed/storage/volume_vacuum*.go'
|
||||
- 'weed/storage/volume_loading.go'
|
||||
- 'weed/storage/disk_location.go'
|
||||
- 'weed/server/filer_grpc_server_rename.go'
|
||||
- 'test/winfsp/**'
|
||||
- '.github/workflows/mount-windows.yml'
|
||||
# No base branch filter: this is the only thing that runs the Windows mount,
|
||||
@@ -21,7 +20,6 @@ on:
|
||||
- 'weed/storage/volume_vacuum*.go'
|
||||
- 'weed/storage/volume_loading.go'
|
||||
- 'weed/storage/disk_location.go'
|
||||
- 'weed/server/filer_grpc_server_rename.go'
|
||||
- 'test/winfsp/**'
|
||||
- '.github/workflows/mount-windows.yml'
|
||||
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
name: "release: bump version and cut the release"
|
||||
|
||||
# One entry point for a SeaweedFS release:
|
||||
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, point the
|
||||
# chart's cosi.image at the newest COSI driver release, commit to master
|
||||
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, commit to master
|
||||
# 2. push the <appVersion> tag, which fans out to the workflows that trigger on
|
||||
# `push: tags` (binaries_release*, container_release_unified, helm_manual_release)
|
||||
# 3. create the GitHub release, with GitHub's generated notes
|
||||
# 4. dispatch "Prepare release" in seaweedfs-csi-driver, seaweedfs-operator and
|
||||
# seaweedfs-cosi-driver, which pick up the new master through `go get`, and
|
||||
# wait for all three. The COSI driver image cut here reaches the chart at
|
||||
# the next release, through step 1.
|
||||
# 4. dispatch "Prepare release" in seaweedfs-csi-driver and seaweedfs-operator,
|
||||
# which pick up the new master through `go get -u`, and wait for both
|
||||
#
|
||||
# Events raised by the default GITHUB_TOKEN do not start other workflows, and it
|
||||
# cannot reach the other repositories at all. Add a repo secret RELEASE_PAT
|
||||
# with `contents: write` here and `actions: write` on the csi-driver, operator
|
||||
# and cosi-driver repos. Without it the tag is still pushed, but nothing
|
||||
# downstream of it runs.
|
||||
# cannot reach the other two repositories at all. Add a repo secret RELEASE_PAT
|
||||
# with `contents: write` here and `actions: write` on the csi-driver and operator
|
||||
# repos. Without it the tag is still pushed, but nothing downstream of it runs.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -32,7 +28,7 @@ on:
|
||||
type: string
|
||||
required: false
|
||||
downstream:
|
||||
description: "Also release the CSI driver, the operator and the COSI driver"
|
||||
description: "Also release the CSI driver and the operator"
|
||||
type: boolean
|
||||
default: true
|
||||
dry_run:
|
||||
@@ -138,43 +134,6 @@ jobs:
|
||||
sed -i -E "s/^version:.*/version: ${CHART_VERSION}/" "$CHART"
|
||||
cat "$CHART"
|
||||
|
||||
- name: Point the chart at the newest COSI driver release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REPO: seaweedfs/seaweedfs-cosi-driver
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VALUES=k8s/charts/seaweedfs/values.yaml
|
||||
IMAGE="ghcr.io/${REPO}"
|
||||
CUR=$(grep -oP "^ image: \"${IMAGE}:\K[^\"]+" "$VALUES" || true)
|
||||
if [ -z "$CUR" ]; then
|
||||
echo "::warning::no ${IMAGE} image line in ${VALUES}; cosi.image is left alone"
|
||||
exit 0
|
||||
fi
|
||||
# Not worth failing a release over: keep the current image instead.
|
||||
if ! NEW=$(timeout 60 gh release view -R "$REPO" --json tagName --jq .tagName); then
|
||||
echo "::warning::could not read the latest ${REPO} release; cosi.image stays ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$NEW" = "$CUR" ]; then
|
||||
echo "cosi.image is already ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$(printf '%s\n%s\n' "${CUR#v}" "${NEW#v}" | sort -V | tail -n1)" != "${NEW#v}" ]; then
|
||||
echo "::warning::the latest ${REPO} release ${NEW} is older than ${CUR}; cosi.image stays ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
# A release without its image would break every chart install with cosi.enabled.
|
||||
TOKEN=$(curl -sf --connect-timeout 10 --max-time 30 "https://ghcr.io/token?scope=repository:${REPO}:pull" | jq -r .token || true)
|
||||
if ! curl -sfI -o /dev/null --connect-timeout 10 --max-time 30 -H "Authorization: Bearer ${TOKEN}" \
|
||||
-H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \
|
||||
"https://ghcr.io/v2/${REPO}/manifests/${NEW}"; then
|
||||
echo "::warning::${IMAGE}:${NEW} is not pullable; cosi.image stays ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
sed -i -E "s|^( image: \"${IMAGE}:)[^\"]+\"|\1${NEW}\"|" "$VALUES"
|
||||
grep -n "^ image: \"${IMAGE}:" "$VALUES"
|
||||
|
||||
- name: Commit, and push the tag
|
||||
id: tag
|
||||
env:
|
||||
@@ -197,7 +156,7 @@ jobs:
|
||||
if git diff --quiet; then
|
||||
echo "::warning::Version files are already at ${TAG}; tagging the current HEAD."
|
||||
else
|
||||
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml k8s/charts/seaweedfs/values.yaml
|
||||
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml
|
||||
git commit -m "${TAG}"
|
||||
git push
|
||||
fi
|
||||
@@ -228,20 +187,14 @@ jobs:
|
||||
include:
|
||||
- repo: seaweedfs/seaweedfs-csi-driver
|
||||
workflow: prepare_release.yaml
|
||||
ref: master
|
||||
- repo: seaweedfs/seaweedfs-operator
|
||||
workflow: prepare_release.yml
|
||||
ref: master
|
||||
- repo: seaweedfs/seaweedfs-cosi-driver
|
||||
workflow: prepare_release.yaml
|
||||
ref: main
|
||||
steps:
|
||||
- name: Release ${{ matrix.repo }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.RELEASE_PAT }}
|
||||
REPO: ${{ matrix.repo }}
|
||||
WORKFLOW: ${{ matrix.workflow }}
|
||||
REF: ${{ matrix.ref }}
|
||||
SHA: ${{ needs.release.outputs.sha }}
|
||||
MODULE: github.com/seaweedfs/seaweedfs
|
||||
run: |
|
||||
@@ -251,7 +204,7 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The dispatched workflow pins seaweedfs with `go get ...@latest`, so
|
||||
# The dispatched workflow pins seaweedfs with `go get -u ...@latest`, so
|
||||
# wait until the proxy serves the release commit as the tip. Asking for
|
||||
# the commit by name is what makes the proxy fetch it. The proxy can
|
||||
# take longer than five minutes to refresh @latest after a new tag.
|
||||
@@ -278,7 +231,7 @@ jobs:
|
||||
BEFORE=$(released)
|
||||
# A minute early, so runner clock skew cannot hide the run.
|
||||
DISPATCHED_AT=$(date -u -d '1 minute ago' '+%Y-%m-%dT%H:%M:%SZ')
|
||||
gh workflow run -R "$REPO" "$WORKFLOW" --ref "$REF" -f bump=patch -f update_seaweedfs=true
|
||||
gh workflow run -R "$REPO" "$WORKFLOW" --ref master -f bump=patch -f update_seaweedfs=true
|
||||
|
||||
RUN_ID=""
|
||||
for _ in $(seq 12); do
|
||||
|
||||
@@ -722,53 +722,6 @@ The chart does not enable `runAsNonRoot` by default because its default `hostPat
|
||||
|
||||
Security contexts configured for a component also apply to the chart-managed helper containers for that component. User-provided init containers and sidecars must define their own container security context and writable mounts.
|
||||
|
||||
### Run as a non-root user with PVC storage
|
||||
|
||||
The standard SeaweedFS image creates a `seaweed` user and group with UID/GID `1000`. Configure the pod security context so kubelet gives that user access to the mounted volumes. kubelet applies `fsGroup` to claims and `emptyDir`, but not to `hostPath`, which the master, volume and filer data and logs use by default, so move those off `hostPath` as well:
|
||||
|
||||
```yaml
|
||||
master:
|
||||
data:
|
||||
type: "persistentVolumeClaim"
|
||||
size: "1Gi"
|
||||
logs:
|
||||
type: "emptyDir"
|
||||
podSecurityContext:
|
||||
enabled: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
runAsNonRoot: true
|
||||
fsGroup: 1000
|
||||
|
||||
volume:
|
||||
dataDirs:
|
||||
- name: data1
|
||||
type: "persistentVolumeClaim"
|
||||
size: "100Gi"
|
||||
maxVolumes: 0
|
||||
podSecurityContext:
|
||||
enabled: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
runAsNonRoot: true
|
||||
fsGroup: 1000
|
||||
|
||||
filer:
|
||||
data:
|
||||
type: "persistentVolumeClaim"
|
||||
size: "25Gi"
|
||||
logs:
|
||||
type: "emptyDir"
|
||||
podSecurityContext:
|
||||
enabled: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
runAsNonRoot: true
|
||||
fsGroup: 1000
|
||||
```
|
||||
|
||||
Apply the same `podSecurityContext` to every other enabled workload, such as `s3`, `admin`, `worker`, or `sftp`, and set `s3.logs` and `sftp.logs` to `emptyDir`; for an all-in-one deployment, use the `allInOne` values key. If you use a custom image with a different UID/GID, replace `1000` with the values for that image. Storage classes that do not support `fsGroup` may need permissions adjusted on the storage backend. A release that already runs on `hostPath` cannot switch its claims in place; see [Master data](#master-data-hostpath-vs-a-claim).
|
||||
|
||||
## OpenShift Support
|
||||
|
||||
SeaweedFS can be deployed on OpenShift or any cluster enforcing the Kubernetes "restricted" Pod Security Standard. By default, OpenShift blocks containers that run as root or use `hostPath` volumes.
|
||||
|
||||
+5
-17
@@ -1,6 +1,4 @@
|
||||
# Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
|
||||
# FormatGate.Finalize: BeginFormatFinalize checks and sets its memory-only intent atomically under Publisher mu + leaseMu; the durable raise holds neither lock.
|
||||
# FormatGate.Grant: grants/regrants and deadline-extending renewals require GrantReport (a current process report) during intent and at level 1.
|
||||
cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall
|
||||
cmd/sw-block/chunk.go CutTime.Poll
|
||||
cmd/sw-block/cut_progress_poll.go CutTime.CliGiveUp
|
||||
@@ -13,18 +11,14 @@ cmd/sw-block/volume_backup.go RestoreCommand.Abort
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.Run
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.Start
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.CrashRestart
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen
|
||||
cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
|
||||
cmd/sw-block/volume_verbs.go CutTime.Poll
|
||||
cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
|
||||
core/authority/authority.go DeleteRetire.RetireLine
|
||||
core/authority/authority.go FormatGate.Finalize
|
||||
core/authority/authority.go FormatGate.Place
|
||||
core/authority/authority_store_file.go DeleteRetire.RetireLine
|
||||
core/authority/format_finalize.go FormatGate.Finalize
|
||||
core/authority/format_finalize.go FormatGate.Grant
|
||||
core/authority/authority.go DeleteRetire.Retire
|
||||
core/authority/authority_store_file.go DeleteRetire.Retire
|
||||
core/authority/workspace.go HolderInterface.ForcedMove
|
||||
core/authority/workspace.go HolderInterface.PlannedMove
|
||||
core/authority/workspace.go MoveAdmission.Ack
|
||||
@@ -40,12 +34,9 @@ core/authority/workspace.go StopAndRestart.LeaseEnds
|
||||
core/authority/workspace.go StopAndRestart.ReadForced
|
||||
core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
|
||||
core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
|
||||
core/authority/workspace_lease_v100.go FormatGate.Finalize
|
||||
core/authority/workspace_lease_view.go FormatGate.Grant
|
||||
core/authority/workspace_lease_view.go FormatGate.Renew
|
||||
core/authority/workspace_lease_view.go HolderInterface.Grant
|
||||
core/authority/workspace_lease_view.go HolderInterface.Regrant
|
||||
core/authority/workspace_retirement.go DeleteRetire.RetireLine
|
||||
core/authority/workspace_retirement.go DeleteRetire.Retire
|
||||
core/engine/apply.go ReplicationPeer.Reconcile
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Request
|
||||
@@ -196,7 +187,6 @@ core/frontend/durable/provider_layout.go EngineAdapter.SettleDown
|
||||
core/frontend/durable/provider_layout.go StopAndRestart.SettleDown
|
||||
core/frontend/durable/provider_preempt.go CutTime.Preempt
|
||||
core/frontend/durable/provider_preempt.go CutTime.Settle
|
||||
core/frontend/durable/provider_seal_replay.go PlainSealReplay.Reply
|
||||
core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite
|
||||
core/frontend/durable/storage_adapter.go HolderInterface.Write
|
||||
core/frontend/durable/storage_adapter.go WALHold.Resubmit
|
||||
@@ -216,11 +206,9 @@ core/host/master/product_loop.go FencingRound.Decide
|
||||
core/host/master/product_loop.go Promotion.Decide
|
||||
core/host/master/services.go FormatGate.Report
|
||||
core/host/master/spec_retirement.go DeleteRetire.ReadOK
|
||||
core/host/master/store_attestation.go FormatGate.Finalize
|
||||
core/host/master/store_attestation.go ReplicationPeer.Attest
|
||||
core/host/master/workspace_binding.go FormatGate.Place
|
||||
core/host/master/workspace_binding.go FormatGate.Grant
|
||||
core/host/master/workspace_binding.go MoveAdmission.Ack
|
||||
core/host/master/workspace_service.go FormatGate.Grant
|
||||
core/host/master/workspace_service.go FormatGate.Place
|
||||
core/host/master/workspace_service.go FormatGate.Renew
|
||||
core/host/master/workspace_service.go MoveAdmission.ReadForMove
|
||||
|
||||
|
@@ -1,91 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
// Re-importing the same declarative spec must preserve the durable records,
|
||||
// including the registration observation time. This checks replacement, not
|
||||
// just equal JSON: an identical rewrite still pays the durability barriers.
|
||||
func TestUnchangedSpecRestartKeepsAll999ImportRecords(t *testing.T) {
|
||||
const count = 999
|
||||
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
|
||||
open := func() *master.Host {
|
||||
t.Helper()
|
||||
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
closeHost := func(h *master.Host) {
|
||||
t.Helper()
|
||||
h.Start()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := h.Close(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
nodes := make([]lifecycle.NodeRegistration, count)
|
||||
intents := make([]lifecycle.PlacementIntent, count)
|
||||
for i := range nodes {
|
||||
id := fmt.Sprintf("n%04d", i)
|
||||
nodes[i] = lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"}
|
||||
intents[i] = lifecycle.PlacementIntent{VolumeID: fmt.Sprintf("v%04d", i), DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: id, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}
|
||||
}
|
||||
importSpec := func(h *master.Host) {
|
||||
t.Helper()
|
||||
if err := importLifecycleNodeInventory(h, nodes); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := importLifecyclePlacementIntents(h, intents); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h := open()
|
||||
importSpec(h)
|
||||
closeHost(h)
|
||||
before := make(map[string]os.FileInfo, 2*count)
|
||||
for _, kind := range []string{"nodes", "placements"} {
|
||||
entries, err := os.ReadDir(filepath.Join(lifecycleDir, kind))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != count {
|
||||
t.Fatalf("%s records=%d, want %d", kind, len(entries), count)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
path := filepath.Join(lifecycleDir, kind, entry.Name())
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before[path] = info
|
||||
}
|
||||
}
|
||||
h = open()
|
||||
importSpec(h)
|
||||
closeHost(h)
|
||||
rewritten := map[string]int{}
|
||||
for path, info := range before {
|
||||
after, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !os.SameFile(info, after) || !info.ModTime().Equal(after.ModTime()) {
|
||||
rewritten[filepath.Base(filepath.Dir(path))]++
|
||||
}
|
||||
}
|
||||
if rewritten["nodes"] != 0 || rewritten["placements"] != 0 {
|
||||
t.Fatalf("unchanged restart replaced records: nodes=%d placements=%d; want zero", rewritten["nodes"], rewritten["placements"])
|
||||
}
|
||||
}
|
||||
@@ -274,7 +274,6 @@ func run(f flags) int {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster: dynamic lifecycle topology enabled by cluster-spec node inventory; assignments will be derived from verified placement intents")
|
||||
}
|
||||
cfg := master.Config{
|
||||
FailStopLifecycleWrites: true,
|
||||
EphemeralLauncherState: (f.launcherManifestDir != "" || f.launcherKubernetesApply) && f.launcherStateHostPath == "",
|
||||
AuthorityStoreDir: f.authorityStore,
|
||||
LifecycleStoreDir: f.lifecycleStore,
|
||||
@@ -340,9 +339,6 @@ func run(f flags) int {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster:", err)
|
||||
return 1
|
||||
}
|
||||
if st := h.Lifecycle(); st != nil {
|
||||
fmt.Fprintf(os.Stderr, "blockmaster: lifecycle import durability: nodes %s; placements %s\n", st.Nodes.ImportDurabilityMode(), st.Placements.ImportDurabilityMode())
|
||||
}
|
||||
// Every promotion decides on the probe round's answers: each candidate
|
||||
// answers a fresh round over its authenticated node stream.
|
||||
h.SetPromotionEvidenceProvider(h.NewRoundPromotionEvidenceProvider(f.launcherReplicationAck, nil))
|
||||
@@ -482,8 +478,10 @@ func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistra
|
||||
if stores == nil {
|
||||
return fmt.Errorf("lifecycle node import requires --lifecycle-store")
|
||||
}
|
||||
if err := stores.Nodes.ImportNodes(nodes); err != nil {
|
||||
return fmt.Errorf("import lifecycle nodes: %w", err)
|
||||
for _, node := range nodes {
|
||||
if _, err := stores.Nodes.RegisterNode(node); err != nil {
|
||||
return fmt.Errorf("register lifecycle node %s: %w", node.ServerID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -512,7 +510,6 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
|
||||
if stores == nil {
|
||||
return fmt.Errorf("lifecycle placement import requires --lifecycle-store")
|
||||
}
|
||||
plans := make([]lifecycle.PlacementPlan, 0, len(intents))
|
||||
for _, intent := range intents {
|
||||
if stores.Deletions.Reserved(intent.VolumeID) {
|
||||
continue // never placed again (see importLifecycleVolumes)
|
||||
@@ -531,10 +528,9 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
|
||||
Source: slot.Source,
|
||||
})
|
||||
}
|
||||
plans = append(plans, plan)
|
||||
}
|
||||
if err := stores.Placements.ImportPlans(plans); err != nil {
|
||||
return fmt.Errorf("import lifecycle placement seeds: %w", err)
|
||||
if _, err := stores.Placements.ApplyPlan(plan); err != nil {
|
||||
return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// only a host that holds no volume: a retired id is then unregistered, so a
|
||||
// holder RPC under it is refused (refuseWorkspaceHolderHost) and the checks
|
||||
// only get stricter. This guard fails when any other non-test caller of
|
||||
// RegisterNode, ImportNodes or RemoveNode appears anywhere.
|
||||
// RegisterNode or RemoveNode appears anywhere.
|
||||
func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
@@ -56,7 +56,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "ImportNodes" || sel.Sel.Name == "RemoveNode") {
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "RemoveNode") {
|
||||
sites = append(sites, filepath.ToSlash(rel)+":"+fn.Name.Name+"."+sel.Sel.Name)
|
||||
}
|
||||
return true
|
||||
@@ -68,7 +68,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sort.Strings(sites)
|
||||
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.ImportNodes", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
|
||||
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
|
||||
if strings.Join(sites, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want)
|
||||
}
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
func TestMasterImportPersistenceFailureExitsAndRecovers(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
nodeDir := filepath.Join(root, "lifecycle", "nodes")
|
||||
store, err := lifecycle.OpenNodeInventoryStore(nodeDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := lifecycle.NodeRegistration{ServerID: "kept", Addr: "127.0.0.1:19001"}
|
||||
old, err = store.RegisterNode(old)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A real rename failure, even as root; the preceding committed record
|
||||
// stays untouched. Directories are not parsed as JSON records on reload.
|
||||
block := filepath.Join(nodeDir, "new.json")
|
||||
if err := os.Mkdir(block, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec := filepath.Join(root, "spec.yaml")
|
||||
if err := os.WriteFile(spec, []byte("nodes:\n - server_id: new\n addr: 127.0.0.1:19002\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := []string{"--listen", "127.0.0.1:0", "--authority-store", filepath.Join(root, "authority"), "--lifecycle-store", filepath.Join(root, "lifecycle"), "--cluster-spec", spec}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep))
|
||||
out, runErr := cmd.CombinedOutput()
|
||||
var exit *exec.ExitError
|
||||
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != 1 {
|
||||
t.Fatalf("master did not fail-stop with exit1: %v context=%v\n%s", runErr, ctx.Err(), out)
|
||||
}
|
||||
text := string(out)
|
||||
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
|
||||
t.Fatalf("missing single persistence ERROR: %s", text)
|
||||
}
|
||||
oldRaw, err := json.Marshal(old)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMasterImportPersistenceRecoveryChild$", "-test.timeout=8s")
|
||||
recovery.Env = append(os.Environ(), "MASTER_RECOVERY_ROOT="+root, "MASTER_RECOVERY_OLD="+string(oldRaw))
|
||||
if out, err := recovery.CombinedOutput(); err != nil {
|
||||
t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMasterImportPersistenceRecoveryChild(t *testing.T) {
|
||||
root := os.Getenv("MASTER_RECOVERY_ROOT")
|
||||
if root == "" {
|
||||
t.Skip("bounded recovery subprocess")
|
||||
}
|
||||
nodeDir := filepath.Join(root, "lifecycle", "nodes")
|
||||
var old lifecycle.NodeRegistration
|
||||
if err := json.Unmarshal([]byte(os.Getenv("MASTER_RECOVERY_OLD")), &old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A new master must load the complete committed record, not a speculative
|
||||
// new registration or partial JSON from the failed write.
|
||||
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
t.Cleanup(func() {
|
||||
closeCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer stop()
|
||||
if err := h.Close(closeCtx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if got, ok := h.Lifecycle().Nodes.GetNodeSnapshot("kept"); !ok || got.ServerID != old.ServerID || got.Addr != old.Addr || !got.SeenAt.Equal(old.SeenAt) {
|
||||
t.Fatalf("committed record lost on restart: %+v %v", got, ok)
|
||||
}
|
||||
if _, ok := h.Lifecycle().Nodes.GetNodeSnapshot("new"); ok {
|
||||
t.Fatal("failed record appeared on restart")
|
||||
}
|
||||
entries, err := os.ReadDir(nodeDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {
|
||||
raw, err := os.ReadFile(filepath.Join(nodeDir, entry.Name()))
|
||||
if err != nil || !json.Valid(raw) {
|
||||
t.Fatalf("partial record %s: %v", entry.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// A master restart must not replace live holders while rebuilding its
|
||||
// heartbeat view. Registration time is deliberately older than the window;
|
||||
// only the new process's received heartbeats make its node evidence fresh.
|
||||
func TestMasterImportRestartKeepsLiveHoldersAcrossFreshnessWindow(t *testing.T) {
|
||||
const window = 6 * time.Second
|
||||
env := startHandoffEnvVolumes(t, 1, []string{"v2"}, "--freshness-window", window.String(), "--lifecycle-product-loop-interval", "100ms")
|
||||
env.volExtra = append(env.volExtra, "--heartbeat-interval", "250ms")
|
||||
for id, volume := range map[string]string{"s1": "v1", "n-v2": "v2"} {
|
||||
host := env.hosts[id]
|
||||
host.volume, host.replica = volume, "r1"
|
||||
env.hosts[id] = host
|
||||
}
|
||||
first, second := f1Up(t, env, "s1"), f1Up(t, env, "n-v2")
|
||||
epochs := map[string]uint64{}
|
||||
for volume, holder := range map[string]*daemon{"v1": first, "v2": second} {
|
||||
epoch, err := adoptedEpochOf(volume, holder.line("blockvolume: volume "+volume+" adopted as PRIMARY at r1@"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
epochs[volume] = epoch
|
||||
}
|
||||
// Both durable registrations now age beyond freshness while holders keep
|
||||
// reporting; a restart must not renew these durable observation times.
|
||||
time.Sleep(window + 100*time.Millisecond)
|
||||
env.masterProcess.term(t, 10*time.Second)
|
||||
started := time.Now()
|
||||
env.masterProcess = env.h.start(t, "blockmaster-import-restarted", env.h.master, env.masterArgs...)
|
||||
conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
client := control.NewClusterEvidenceServiceClient(conn)
|
||||
fresh := map[string]bool{}
|
||||
verified := map[string]bool{}
|
||||
observed := map[string]bool{}
|
||||
samples := 0
|
||||
for time.Since(started) < window {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
status, err := client.GetClusterStatus(ctx, &control.GetClusterStatusRequest{})
|
||||
cancel()
|
||||
if err == nil {
|
||||
samples++
|
||||
for _, node := range status.Nodes {
|
||||
if at := node.GetLastHeartbeatAt(); at != nil && at.AsTime().After(started) {
|
||||
fresh[node.GetNodeName()] = true
|
||||
}
|
||||
}
|
||||
for _, volume := range status.Volumes {
|
||||
if epoch, ok := epochs[volume.VolumeId]; ok && volume.Epoch != 0 {
|
||||
observed[volume.VolumeId] = true
|
||||
if volume.Epoch != epoch {
|
||||
t.Fatalf("%s changed epoch after restart: %d -> %d", volume.VolumeId, epoch, volume.Epoch)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, event := range status.Events {
|
||||
if event.EventType == "placement_verified" {
|
||||
verified[event.VolumeId] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"primary lost:", "decision=replace("} {
|
||||
if env.masterProcess.has(bad) {
|
||||
t.Fatalf("live-holder restart made a loss/replacement decision: %s", bad)
|
||||
}
|
||||
}
|
||||
for id, d := range map[string]*daemon{"s1": first, "n-v2": second} {
|
||||
select {
|
||||
case <-d.done:
|
||||
t.Fatalf("live holder %s exited during master restart: %v", id, d.err)
|
||||
default:
|
||||
}
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if samples == 0 {
|
||||
t.Fatal("no successful status sample in the freshness window")
|
||||
}
|
||||
for _, id := range []string{"s1", "n-v2"} {
|
||||
if !fresh[id] {
|
||||
t.Fatalf("live node %s never became fresh after restart", id)
|
||||
}
|
||||
}
|
||||
for id := range epochs {
|
||||
if !observed[id] {
|
||||
t.Fatalf("volume %s never showed its authoritative epoch again", id)
|
||||
}
|
||||
if !verified[id] {
|
||||
t.Fatalf("placement %s did not verify again within one window", id)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{"s1", "n-v2"} {
|
||||
block := pattern("restart-live-io!")
|
||||
env.writeBlock(t, id, 0, block)
|
||||
}
|
||||
t.Logf("master restart: %d status samples, both nodes fresh, both placements verified, no loss/replacement or holder exit within %s", samples, window)
|
||||
}
|
||||
@@ -36,9 +36,8 @@ var restoreCreateRPC = func(ctx context.Context, master string, req *control.Cre
|
||||
}
|
||||
|
||||
// bCatalog dials the filer and opens the volume catalog; a command that
|
||||
// writes first passes the single-filer start check, then runs the chunk
|
||||
// condition probe; each runs within timeout. It returns exit -1 on success,
|
||||
// else the exit code after reporting.
|
||||
// writes first passes the single-filer start check. It returns exit -1 on
|
||||
// success, else the exit code after reporting.
|
||||
func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.BCatalog, func() error, int) {
|
||||
if filer == "" {
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false)
|
||||
@@ -68,11 +67,6 @@ func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdo
|
||||
if err != nil {
|
||||
return fail(err.Error())
|
||||
}
|
||||
if writes {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
cat.ProbeChunkGuard(ctx)
|
||||
cancel()
|
||||
}
|
||||
return cat, closeFn, -1
|
||||
}
|
||||
|
||||
@@ -360,9 +354,7 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int {
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
var ref chunkstore.VolumeRef
|
||||
return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
u, err := cat.Usage(ctx, ref)
|
||||
u.MetadataGuard = ""
|
||||
return u, err
|
||||
return cat.Usage(ctx, ref)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ func TestOpsChunk_CatalogCommands(t *testing.T) {
|
||||
if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 || !strings.Contains(out, tgt.Dir()) {
|
||||
t.Fatalf("restore: %d %q %q", code, out, errs)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) || strings.Contains(out, "metadata_guard") {
|
||||
if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) {
|
||||
t.Fatalf("target usage: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" {
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// A command that changes chunk metadata runs the chunk condition probe on
|
||||
// the catalog it opens, so its adoptions and marks send the filer's chunk
|
||||
// condition as blockvolume's do; a read-only command writes nothing.
|
||||
func TestOpsChunkWritingCatalogRunsTheChunkConditionProbe(t *testing.T) {
|
||||
mem := newMemChunkStore()
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
|
||||
for _, tc := range []struct {
|
||||
writes bool
|
||||
guard string
|
||||
}{{true, chunkstore.MetadataGuardChunks}, {false, chunkstore.MetadataGuardReread}} {
|
||||
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", tc.writes, time.Minute, io.Discard, io.Discard)
|
||||
if exit >= 0 {
|
||||
t.Fatalf("writes=%v: catalog open exited %d", tc.writes, exit)
|
||||
}
|
||||
_ = closeFn()
|
||||
if got := cat.MetadataGuard(); got != tc.guard {
|
||||
t.Fatalf("writes=%v: metadata guard %q, want %q", tc.writes, got, tc.guard)
|
||||
}
|
||||
left, err := mem.ListEntries(context.Background(), "/blocks", "", "", 100)
|
||||
if err != nil || len(left) != 0 {
|
||||
t.Fatalf("writes=%v: %d entries left under the catalog base (%v)", tc.writes, len(left), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stalledProbeFiler stalls the probe's disposable HEAD create until its
|
||||
// context ends.
|
||||
type stalledProbeFiler struct{ *memChunkStore }
|
||||
|
||||
func (f stalledProbeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
|
||||
if inStartupProbe(dir, e.GetName()) {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
return f.memChunkStore.CreateEntry(ctx, dir, e, oExcl)
|
||||
}
|
||||
|
||||
// The probe runs within the command's --timeout: after a passing census, a
|
||||
// probe stalled on its filer ends at the timeout, leaves the guard off and
|
||||
// refuses nothing.
|
||||
func TestOpsChunkWritingCatalogProbeIsBoundedByTheTimeout(t *testing.T) {
|
||||
mem := newMemChunkStore()
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
return stalledProbeFiler{mem}, func() error { return nil }, nil
|
||||
}
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
|
||||
start := time.Now()
|
||||
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", true, 200*time.Millisecond, io.Discard, io.Discard)
|
||||
if exit >= 0 {
|
||||
t.Fatalf("a stalled probe refused the command: exit %d", exit)
|
||||
}
|
||||
_ = closeFn()
|
||||
if took := time.Since(start); took > 5*time.Second {
|
||||
t.Fatalf("a stalled probe held the command %v past its 200ms --timeout", took)
|
||||
}
|
||||
if got := cat.MetadataGuard(); got != chunkstore.MetadataGuardReread {
|
||||
t.Fatalf("metadata guard %q after a stalled probe, want %q", got, chunkstore.MetadataGuardReread)
|
||||
}
|
||||
}
|
||||
|
||||
// betweenLookupAndUpdate runs before, once it is set, ahead of the next
|
||||
// update: what other writers do while a stale one is between its lookup and
|
||||
// its update.
|
||||
type betweenLookupAndUpdate struct {
|
||||
*memChunkStore
|
||||
before func()
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) runBefore() {
|
||||
if b := f.before; b != nil {
|
||||
f.before = nil
|
||||
b()
|
||||
}
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
f.runBefore()
|
||||
return f.memChunkStore.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
|
||||
f.runBefore()
|
||||
return f.memChunkStore.UpdateEntryIfChunks(ctx, dir, e, expected, fids)
|
||||
}
|
||||
|
||||
// A writing command's adoption that paused between its lookup and its update
|
||||
// does not land on an object a cleaner deleted and another executor created
|
||||
// again in between, through the store of the catalog bCatalog opens. An
|
||||
// unchanged object is still adopted; a catalog that ran no probe lets the
|
||||
// stale write through.
|
||||
func TestOpsChunkStaleCLIAdoptionDoesNotOverwriteARecreatedObject(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
writes, recreate bool
|
||||
}{
|
||||
{"probed catalog, recreated object", true, true},
|
||||
{"probed catalog, unchanged object", true, false},
|
||||
{"catalog without the probe, recreated object", false, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := newMemChunkStore()
|
||||
hooked := &betweenLookupAndUpdate{memChunkStore: mem}
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return hooked, func() error { return nil }, nil }
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
|
||||
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", tc.writes, time.Minute, io.Discard, io.Discard)
|
||||
if exit >= 0 {
|
||||
t.Fatalf("catalog open exited %d", exit)
|
||||
}
|
||||
defer closeFn()
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: "v", ID: id}
|
||||
stale, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
others, err := chunkstore.NewLayoutStore(mem, mem, path.Join("/blocks", ref.Dir()), id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := bytes.Repeat([]byte{0x5a}, 4096)
|
||||
rel := layout.NameChunk(1, data).Path()
|
||||
obj := path.Join("/blocks", ref.Dir(), rel)
|
||||
fid := func() string {
|
||||
e, err := mem.LookupEntry(ctx, path.Dir(obj), path.Base(obj))
|
||||
if err != nil || len(e.Chunks) != 1 {
|
||||
t.Fatalf("lookup %s: %+v %v", rel, e, err)
|
||||
}
|
||||
return e.Chunks[0].FileId
|
||||
}
|
||||
if err := others.Create(ctx, rel, data, "producer-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := fid()
|
||||
meta, found, err := others.Stat(ctx, rel)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("stat: %v %v", found, err)
|
||||
}
|
||||
second := first
|
||||
if tc.recreate {
|
||||
hooked.before = func() {
|
||||
if err := others.Mark(ctx, rel, meta, "clean-1"); err != nil {
|
||||
t.Errorf("mark: %v", err)
|
||||
}
|
||||
if err := others.DeleteMarked(ctx, rel, "clean-1"); err != nil {
|
||||
t.Errorf("delete: %v", err)
|
||||
}
|
||||
if err := others.Create(ctx, rel, data, "producer-1"); err != nil {
|
||||
t.Errorf("re-create: %v", err)
|
||||
}
|
||||
second = fid()
|
||||
}
|
||||
}
|
||||
err = stale.Reuse(ctx, rel, meta, "writer-1")
|
||||
if tc.recreate && second == first {
|
||||
t.Fatalf("fixture: the object was not re-created with a new chunk (%s)", first)
|
||||
}
|
||||
switch {
|
||||
case tc.writes && tc.recreate:
|
||||
if !errors.Is(err, layout.ErrPrecondition) {
|
||||
t.Fatalf("the stale CLI adoption over a re-created object answered %v, want ErrPrecondition", err)
|
||||
}
|
||||
if got := fid(); got != second {
|
||||
t.Fatalf("the stale CLI adoption wrote chunk %s over the re-created object's %s", got, second)
|
||||
}
|
||||
case tc.recreate:
|
||||
if err != nil || fid() != first {
|
||||
t.Fatalf("control: without the probe the stale adoption should land (err %v, chunk %s, first %s)", err, fid(), first)
|
||||
}
|
||||
default:
|
||||
if err != nil {
|
||||
t.Fatalf("adoption of an unchanged object: %v", err)
|
||||
}
|
||||
if m, _, err := others.Stat(ctx, rel); err != nil || m.Session != "writer-1" {
|
||||
t.Fatalf("after adoption: %+v %v", m, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// inStartupProbe reports whether dir/name lies in a catalog probe's
|
||||
// disposable directory: a fake that stalls object deletes lets the probe's
|
||||
// own cleanup through, as a real filer deletes its inline HEAD at once.
|
||||
func inStartupProbe(dir, name string) bool {
|
||||
return strings.Contains(path.Join(dir, name), "/.startup-head-probe-")
|
||||
}
|
||||
@@ -100,9 +100,6 @@ type waitingDeleteFiler struct {
|
||||
}
|
||||
|
||||
func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if inStartupProbe(dir, name) {
|
||||
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
f.calls++
|
||||
if f.calls == 1 {
|
||||
timer := time.NewTimer(f.bound / 2)
|
||||
@@ -169,9 +166,6 @@ func TestVolumeDeleteRefreshesAnExpiredSweepAndWaitsFromLastRemoval(t *testing.T
|
||||
type blockedDeleteFiler struct{ *memChunkStore }
|
||||
|
||||
func (f *blockedDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if inStartupProbe(dir, name) {
|
||||
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
@@ -6,9 +6,6 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -21,26 +18,14 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// The real master issues the move and reports the current holder. Only the unit and holder
|
||||
// process are fixtures: enabling the unit renews the real assigned epoch;
|
||||
// the holder's stop ACK goes through the real detached-HEAD check.
|
||||
func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
|
||||
if os.Getenv("VOLUME_START_MASTER_CHILD") != t.Name() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1")
|
||||
cmd.Env = append(os.Environ(), "VOLUME_START_MASTER_CHILD="+t.Name())
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("bounded master stop/restart/start child: %v\n%s", err, out)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, tc := range []struct{ loseAnswer, restartMaster bool }{{false, false}, {true, false}, {false, true}, {true, true}} {
|
||||
loseAnswer := tc.loseAnswer
|
||||
t.Run(fmt.Sprintf("lost-answer-%v/master-restart-%v", loseAnswer, tc.restartMaster), func(t *testing.T) {
|
||||
for _, loseAnswer := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("lost-answer-%v", loseAnswer), func(t *testing.T) {
|
||||
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
@@ -57,7 +42,6 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
|
||||
}
|
||||
defer conn.Close()
|
||||
rpc := control.NewWorkspaceServiceClient(conn)
|
||||
observations := control.NewObservationServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
h := newFakeHost(t)
|
||||
@@ -82,12 +66,6 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
|
||||
exited79 := false
|
||||
env.Systemctl = func(ctx context.Context, args ...string) (string, error) {
|
||||
if args[0] == "enable" {
|
||||
// A real newly enabled holder reports before it can receive its
|
||||
// first serving deadline; a move record alone grants no I/O.
|
||||
if _, err := observations.ReportHeartbeat(ctx, &control.HeartbeatReport{ReadsLevel: 1, ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
|
||||
Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}}); err != nil {
|
||||
return "report", err
|
||||
}
|
||||
ws, err := rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-f"})
|
||||
if err != nil {
|
||||
return "query", err
|
||||
@@ -131,22 +109,6 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) {
|
||||
if code, out, errs := runStop(env, stopOpts{Volume: "vol-f", NoCut: true, Timeout: time.Second}); code != 0 {
|
||||
t.Fatalf("stop=%d %s %s", code, out, errs)
|
||||
}
|
||||
if tc.restartMaster {
|
||||
// Keep the configured endpoint while losing all memory-only reports.
|
||||
cfg.Listen = mh.Addr()
|
||||
stop()
|
||||
_ = conn.Close()
|
||||
restarted, restartStop := startDeleteMaster(t, cfg)
|
||||
defer restartStop()
|
||||
restartedConn, err := grpc.NewClient(restarted.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer restartedConn.Close()
|
||||
rpc = control.NewWorkspaceServiceClient(restartedConn)
|
||||
observations = control.NewObservationServiceClient(restartedConn)
|
||||
recorder.WorkspaceServiceClient = rpc
|
||||
}
|
||||
code, out, errs := runStart(env, v, startOpts{Wait: time.Second})
|
||||
if loseAnswer {
|
||||
if code != wsExitUnknown || h.called("enable") != 1 {
|
||||
|
||||
@@ -189,9 +189,7 @@ type Publisher struct {
|
||||
// 0 keeps v1.0's master semantics (a current lease horizon, version-1
|
||||
// records), 1 is v1.1's. Written under mu and leaseMu, read under
|
||||
// either.
|
||||
formatLevel uint32
|
||||
formatFinalizing bool // guarded by mu and leaseMu; no store I/O while setting it
|
||||
requireFormatReadProofs bool // configured by the master before serving
|
||||
formatLevel uint32
|
||||
// Level 0's horizon extender (workspace_lease_v100.go).
|
||||
leaseClosing bool // guarded by mu and leaseMu
|
||||
extWG sync.WaitGroup // admitted extenders
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FormatReadProof is an in-memory report captured before entering grant locks.
|
||||
// Revision changes whenever a reporting process or its read level changes.
|
||||
// Reading it under the grant locks is atomic and never waits on another lock.
|
||||
type FormatReadProof struct {
|
||||
Server, Process, Replica string
|
||||
Epoch uint64
|
||||
Reads uint32
|
||||
Reported bool
|
||||
Revision *atomic.Uint64
|
||||
Version uint64
|
||||
}
|
||||
|
||||
func (r FormatReadProof) current(replica string, epoch uint64, incarnation string) bool {
|
||||
return r.Reported && r.Reads >= 1 && r.Replica == replica && r.Epoch == epoch &&
|
||||
r.Revision != nil && r.Revision.Load() == r.Version &&
|
||||
(incarnation == "" || r.Process == incarnation)
|
||||
}
|
||||
|
||||
// FormatServingBlocker names a possibly-serving process without a proven report.
|
||||
type FormatServingBlocker struct{ Volume, Server, Detail string }
|
||||
|
||||
// RequireFormatReadProofs enables the master's report gate before serving.
|
||||
func (p *Publisher) RequireFormatReadProofs() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
p.requireFormatReadProofs = true
|
||||
}
|
||||
|
||||
// BeginFormatFinalize atomically checks possible live leases and closes the
|
||||
// level-0 grant path. No I/O or caller callback runs under these locks.
|
||||
// The caller serializes placement/owner changes with this memory step, then
|
||||
// admits new work at the target level while the durable write runs.
|
||||
func (p *Publisher) BeginFormatFinalize(proofs map[string]FormatReadProof, otherGuardsPassed bool) []FormatServingBlocker {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
now := p.workspaceNow()
|
||||
var blocked []FormatServingBlocker
|
||||
for volume, lv := range p.leaseViews {
|
||||
if !lv.d.bound || !lv.d.leasePresent || (lv.d.revoking && lv.d.ackRecorded) {
|
||||
continue
|
||||
}
|
||||
skew := time.Duration(lv.d.maxSkewNS)
|
||||
until := lv.deadline.Add(skew)
|
||||
if p.formatLevel == 0 {
|
||||
if horizon := time.Unix(0, lv.d.horizon).Add(skew); horizon.After(until) {
|
||||
until = horizon
|
||||
}
|
||||
}
|
||||
if !lv.d.uncertain && !now.Before(until) {
|
||||
continue
|
||||
}
|
||||
proof := proofs[volume]
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
if ok && (lv.d.issuedHost == "" || proof.Server == lv.d.issuedHost) && proof.current(lv.d.replica, lv.d.epoch, line.info.Incarnation) {
|
||||
continue
|
||||
}
|
||||
server := proof.Server
|
||||
if lv.d.issuedHost != "" {
|
||||
server = lv.d.issuedHost
|
||||
}
|
||||
if server == "" {
|
||||
server = "unknown"
|
||||
}
|
||||
detail := fmt.Sprintf("volume %s: serving process has not reported reading level 1", volume)
|
||||
if proof.Process != "" {
|
||||
detail += fmt.Sprintf(" (process %s reads level %d)", proof.Process, proof.Reads)
|
||||
}
|
||||
blocked = append(blocked, FormatServingBlocker{volume, server, detail})
|
||||
}
|
||||
sort.Slice(blocked, func(i, j int) bool {
|
||||
if blocked[i].Server == blocked[j].Server {
|
||||
return blocked[i].Volume < blocked[j].Volume
|
||||
}
|
||||
return blocked[i].Server < blocked[j].Server
|
||||
})
|
||||
if len(blocked) == 0 && otherGuardsPassed {
|
||||
p.formatFinalizing = true
|
||||
p.requireFormatReadProofs = true
|
||||
}
|
||||
return blocked
|
||||
}
|
||||
|
||||
// CancelFormatFinalize reopens the level-0 grant path after a failed durable raise.
|
||||
func (p *Publisher) CancelFormatFinalize() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
p.formatFinalizing = false
|
||||
}
|
||||
|
||||
// Caller holds mu or leaseMu; proof validation reads atomics only.
|
||||
func (p *Publisher) formatReadProofError(proof FormatReadProof, replica string, epoch uint64, incarnation string) error {
|
||||
if !p.requireFormatReadProofs || (p.formatLevel == 0 && !p.formatFinalizing) {
|
||||
return nil
|
||||
}
|
||||
if !proof.current(replica, epoch, incarnation) {
|
||||
return fmt.Errorf("workspace lease: node %q's process must report reading format level 1 before a grant or lease extension (binary_too_old or no current report)", proof.Server)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Both the abrupt exit and recovery lifetime are bounded by the parent.
|
||||
func TestFormatFinalizeIntentDoesNotSurviveProcessExit(t *testing.T) {
|
||||
if phase := os.Getenv("FORMAT_INTENT_CRASH_PHASE"); phase != "" {
|
||||
disk, err := NewFileAuthorityStore(os.Getenv("FORMAT_INTENT_CRASH_STORE"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = disk.Close() })
|
||||
clock := newTestClock()
|
||||
p := level0Publisher(t, disk, 30*time.Second, clock)
|
||||
if phase == "crash" {
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
clock.at(120)
|
||||
if blocked := p.BeginFormatFinalize(nil, true); len(blocked) != 0 || !p.formatFinalizing || p.FormatLevel() != 0 {
|
||||
t.Fatalf("before durable raise: intent=%v level=%d blockers=%v", p.formatFinalizing, p.FormatLevel(), blocked)
|
||||
}
|
||||
os.Exit(23) // no Close, no Cancel, no durable raise
|
||||
}
|
||||
p.RequireFormatReadProofs()
|
||||
if p.FormatLevel() != 0 || p.formatFinalizing {
|
||||
t.Fatalf("restart retained intent or raised level: intent=%v level=%d", p.formatFinalizing, p.FormatLevel())
|
||||
}
|
||||
clock.at(360)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatalf("restart changed the level-0 regrant path: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
dir := t.TempDir()
|
||||
for _, phase := range []string{"crash", "recover"} {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1")
|
||||
cmd.Env = append(os.Environ(), "FORMAT_INTENT_CRASH_PHASE="+phase, "FORMAT_INTENT_CRASH_STORE="+dir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
cancel()
|
||||
if phase == "crash" {
|
||||
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 23 {
|
||||
t.Fatalf("intent child did not reach its own crash boundary: %v\n%s", err, out)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("bounded recovery: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatFinalizeFailedCheckLeavesLevelZeroGrantsOpen(t *testing.T) {
|
||||
for _, otherGuardsPassed := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(otherGuardsPassed), func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
clock := newTestClock()
|
||||
p := level0Publisher(t, disk, 30*time.Second, clock)
|
||||
p.RequireFormatReadProofs()
|
||||
if otherGuardsPassed {
|
||||
bindAndGrant(t, p, "v", "r") // serving-report check fails
|
||||
}
|
||||
blocked := p.BeginFormatFinalize(nil, otherGuardsPassed)
|
||||
if otherGuardsPassed && len(blocked) == 0 {
|
||||
t.Fatal("unreported serving holder was not refused")
|
||||
}
|
||||
if p.formatFinalizing || p.FormatLevel() != 0 {
|
||||
t.Fatal("failed check left an admission intent or raised the level")
|
||||
}
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "fresh", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatalf("failed finalize changed level-0 publication: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatFinalizeIntentRequiresRegrantReport(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
clock := newTestClock()
|
||||
p := level0Publisher(t, disk, 30*time.Second, clock)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
p.RequireFormatReadProofs()
|
||||
clock.at(120) // both the deadline and level-0 persisted horizon have ended
|
||||
if blocked := p.BeginFormatFinalize(nil, true); len(blocked) != 0 {
|
||||
t.Fatalf("ended lease blocks finalize: %v", blocked)
|
||||
}
|
||||
// The durable envelope has not yet been written: the actual level stays 0.
|
||||
if got := p.FormatLevel(); got != 0 {
|
||||
t.Fatalf("intent prematurely raised level=%d", got)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "must report") {
|
||||
t.Fatalf("regrant without report during durable raise: %v", err)
|
||||
}
|
||||
revision := &atomic.Uint64{}
|
||||
proof := FormatReadProof{Server: "node", Replica: "r", Epoch: 1, Reported: true, Reads: 1, Revision: revision}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
|
||||
t.Fatalf("capable regrant during intent: %v", err)
|
||||
}
|
||||
clock.at(240)
|
||||
revision.Add(1) // report changed after a proof was captured, before re-grant
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err == nil {
|
||||
t.Fatal("stale process proof revived a lease")
|
||||
}
|
||||
proof.Version = revision.Load()
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
|
||||
t.Fatalf("fresh proof did not retry: %v", err)
|
||||
}
|
||||
p.CancelFormatFinalize()
|
||||
if p.formatFinalizing {
|
||||
t.Fatal("failed raise kept the intent")
|
||||
}
|
||||
// Clearing a failed raise restores the level-0 path (no report required).
|
||||
clock.at(360)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatalf("level-0 retry after failed finalize: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases(t *testing.T) {
|
||||
for _, state := range []string{"live", "released", "ended", "unserved"} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
clock := newTestClock()
|
||||
disk, _ := newTempStore(t)
|
||||
p := level0Publisher(t, disk, 30*time.Second, clock)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
switch state {
|
||||
case "released":
|
||||
ctx := context.Background()
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Gen: 7, Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "ended":
|
||||
clock.at(120)
|
||||
case "unserved":
|
||||
// An authority line alone is not a grant: reconstruct its no-lease view.
|
||||
p.mu.Lock()
|
||||
p.workspace["v"] = &WorkspaceState{}
|
||||
p.refreshLeaseViewLocked("v")
|
||||
p.mu.Unlock()
|
||||
}
|
||||
blocked := p.BeginFormatFinalize(nil, true)
|
||||
if (len(blocked) > 0) != (state == "live") {
|
||||
t.Fatalf("%s: blockers=%v", state, blocked)
|
||||
}
|
||||
if state == "live" && (blocked[0].Volume != "v" || !strings.Contains(blocked[0].Detail, "serving")) {
|
||||
t.Fatalf("unnamed live holder: %v", blocked)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatFinalizeLiveRenewalChecksCurrentProcess(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
p := level0Publisher(t, disk, 30*time.Second, newTestClock())
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Incarnation: "capable", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
revision := &atomic.Uint64{}
|
||||
proof := FormatReadProof{Server: "node", Process: "capable", Replica: "r", Epoch: 1, Reported: true, Reads: 1, Revision: revision}
|
||||
if blocked := p.BeginFormatFinalize(map[string]FormatReadProof{"v": proof}, true); len(blocked) != 0 {
|
||||
t.Fatal(blocked)
|
||||
}
|
||||
for _, phase := range []string{"intent", "complete"} {
|
||||
if phase == "complete" {
|
||||
p.FinalizeFormatLevel()
|
||||
}
|
||||
for _, invalid := range []string{"missing", "old", "replacement", "stale"} {
|
||||
bad := proof
|
||||
switch invalid {
|
||||
case "missing":
|
||||
bad.Reported = false
|
||||
case "old":
|
||||
bad.Reads = 0
|
||||
case "replacement":
|
||||
bad.Process = "replacement"
|
||||
case "stale":
|
||||
bad.Version++
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, bad); err == nil {
|
||||
t.Fatalf("%s: %s report renewed a live lease", phase, invalid)
|
||||
}
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
|
||||
t.Fatalf("%s: current capable process could not renew: %v", phase, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatFinalizeDeadlineProofSurvivesIntentCompletion(t *testing.T) {
|
||||
for _, path := range []string{"first", "live", "regrant"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
clock := newTestClock()
|
||||
p := level0Publisher(t, disk, 30*time.Second, clock)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if path != "first" {
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if path == "regrant" {
|
||||
clock.at(120)
|
||||
}
|
||||
revision := &atomic.Uint64{}
|
||||
proof := FormatReadProof{Server: "node", Replica: "r", Epoch: 1, Reported: true, Reads: 1, Revision: revision}
|
||||
if blocked := p.BeginFormatFinalize(map[string]FormatReadProof{"v": proof}, true); len(blocked) != 0 {
|
||||
t.Fatal(blocked)
|
||||
}
|
||||
p.testBeforeGrantLock = func(site string) {
|
||||
if site == "renewal" {
|
||||
revision.Add(1) // captured before the process report changed
|
||||
p.FinalizeFormatLevel()
|
||||
}
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err == nil {
|
||||
t.Fatal("stale proof crossed intent completion into a serving deadline")
|
||||
}
|
||||
p.testBeforeGrantLock = nil
|
||||
proof.Version = revision.Load()
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil {
|
||||
t.Fatalf("current capable proof did not retry after completion: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -106,35 +106,6 @@ func TestObservationHostRebuildsAtAnExpiryWithNoHeartbeat(t *testing.T) {
|
||||
waitFor("the expiry's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 0 && b.BuiltAt.Equal(clk.Now()) })
|
||||
}
|
||||
|
||||
// A clock swapped while the host runs is the one its next build uses; under
|
||||
// -race the swap does not race the host reading the clock for its deadline.
|
||||
func TestObservationHostClockSwappedWhileRunning(t *testing.T) {
|
||||
start := time.Now()
|
||||
host := NewObservationHost(ObservationHostConfig{
|
||||
Freshness: FreshnessConfig{FreshnessWindow: time.Hour},
|
||||
Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}},
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
host.Start(ctx)
|
||||
defer host.Stop()
|
||||
_ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1")))
|
||||
time.Sleep(50 * time.Millisecond) // the host is waiting on s1's expiry
|
||||
|
||||
clk := newFakeClock(start.Add(2 * time.Hour))
|
||||
host.SetNowForTest(clk.Now)
|
||||
host.Wake()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if b, have := host.LastBuild(); have && len(b.Snapshot.Servers) == 0 && b.BuiltAt.Equal(clk.Now()) {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
b, _ := host.LastBuild()
|
||||
t.Fatalf("s1 not expired on the swapped clock: last build at %v with %d servers", b.BuiltAt, len(b.Snapshot.Servers))
|
||||
}
|
||||
|
||||
// normalizedBuild is a build with its stamps cleared: when it was built, the
|
||||
// store revision, and the timestamps the evidence carries.
|
||||
func normalizedBuild(b BuildResult) BuildResult {
|
||||
|
||||
@@ -258,7 +258,7 @@ func (h *ObservationHost) run(ctx context.Context) {
|
||||
var deadlineC <-chan time.Time
|
||||
var timer *time.Timer
|
||||
if at := h.store.NextDeadline(); !at.IsZero() {
|
||||
d := at.Sub(h.store.clock())
|
||||
d := at.Sub(h.store.now())
|
||||
if d < 10*time.Millisecond {
|
||||
d = 10 * time.Millisecond
|
||||
}
|
||||
|
||||
@@ -285,14 +285,6 @@ func (s *ObservationStore) SetNowForTest(now func() time.Time) {
|
||||
s.now = now
|
||||
}
|
||||
|
||||
// clock reads the time from the clock source SetNowForTest may swap.
|
||||
func (s *ObservationStore) clock() time.Time {
|
||||
s.mu.Lock()
|
||||
now := s.now
|
||||
s.mu.Unlock()
|
||||
return now()
|
||||
}
|
||||
|
||||
// NewObservationStore constructs a store with the given freshness
|
||||
// configuration. `now` is injected for deterministic testing; pass
|
||||
// time.Now in production.
|
||||
|
||||
@@ -58,7 +58,6 @@ func (p *Publisher) FinalizeFormatLevel() {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
p.formatLevel = 1
|
||||
p.formatFinalizing = false
|
||||
}
|
||||
|
||||
// envelopeVersionLocked is the record envelope version the level writes:
|
||||
|
||||
@@ -18,7 +18,6 @@ var ErrWorkspaceRevoked = errors.New("workspace lease: revocation ACK is recorde
|
||||
type leaseDerived struct {
|
||||
bound bool // an authority line exists for the volume
|
||||
replica string
|
||||
incarnation string // current line's process identity; renewal reads only leaseMu
|
||||
epoch uint64
|
||||
ownerFromMove bool
|
||||
issuedHost string // NewHost of the issued move that minted the line; "" if none
|
||||
@@ -49,7 +48,6 @@ func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived {
|
||||
d := leaseDerived{uncertain: p.workspaceUncertain[volume], storeless: p.store == nil, maxSkewNS: int64(p.workspaceSkew(nil))}
|
||||
if _, line, ok := p.workspaceLineLocked(volume); ok {
|
||||
d.bound, d.replica, d.epoch = true, line.info.ReplicaID, line.info.Epoch
|
||||
d.incarnation = line.info.Incarnation
|
||||
d.issuedHost, d.ownerFromMove = line.info.ServerID, line.info.OwnerFromMove
|
||||
}
|
||||
if s := p.workspace[volume]; s != nil {
|
||||
@@ -243,14 +241,10 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
|
||||
// holder only once its restart floor (deadline restart + TTL, set at load)
|
||||
// plus the skew bound has passed, so no durable horizon is needed. A first grant and an
|
||||
// expired re-grant after the shared move barrier write synchronously.
|
||||
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64, proofs ...FormatReadProof) (WorkspaceLease, error) {
|
||||
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
var proof FormatReadProof
|
||||
if len(proofs) > 0 {
|
||||
proof = proofs[0]
|
||||
}
|
||||
p.beforeWorkspaceGrantLock("renewal")
|
||||
p.leaseMu.Lock()
|
||||
now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it
|
||||
@@ -274,7 +268,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
}
|
||||
if !lv.d.leasePresent {
|
||||
unlock() // never re-enter p.mu while holding the leaf
|
||||
return p.firstWorkspaceGrant(ctx, volume, holder, epoch, proof)
|
||||
return p.firstWorkspaceGrant(ctx, volume, holder, epoch)
|
||||
}
|
||||
if lv.d.revoking { // tell the host to drain; never extend
|
||||
l := lv.d.lease
|
||||
@@ -284,7 +278,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
}
|
||||
if !now.Before(lv.deadline) || (p.formatLevel == 0 && now.UnixNano() >= lv.d.horizon) {
|
||||
unlock()
|
||||
return p.regrantWorkspaceLease(ctx, volume, holder, epoch, proof)
|
||||
return p.regrantWorkspaceLease(ctx, volume, holder, epoch)
|
||||
}
|
||||
// Where the synchronous write used to refuse (persistWorkspaceLocked):
|
||||
// a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001).
|
||||
@@ -292,13 +286,6 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
// A live deadline does not prove that the caller is the capable process
|
||||
// checked by finalize: a replacement may already have reported level 0.
|
||||
// Validate its current report under this leaf lock, without I/O or mu.
|
||||
if err := p.formatReadProofError(proof, holder, epoch, lv.d.incarnation); err != nil {
|
||||
unlock()
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
if p.formatLevel == 0 {
|
||||
return p.renewV100Locked(volume, holder, epoch, lv, now) // releases leaseMu
|
||||
}
|
||||
@@ -327,7 +314,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
// its holder's lease. A host whose first renewal fails does not fence: it has
|
||||
// no deadline yet and retries. The record's ExpiresAtNS is now+1.5*TTL, the
|
||||
// form v1.0.x reads; this process's deadline is now+TTL.
|
||||
func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64, proof FormatReadProof) (WorkspaceLease, error) {
|
||||
func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
p.beforeWorkspaceGrantLock("first grant")
|
||||
p.mu.Lock()
|
||||
if p.deleteReserved[volume] {
|
||||
@@ -339,10 +326,6 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
|
||||
}
|
||||
if err := p.formatReadProofError(proof, holder, epoch, line.info.Incarnation); err != nil {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
s := cloneWorkspace(p.workspace[volume])
|
||||
if s == nil {
|
||||
s = &WorkspaceState{}
|
||||
@@ -373,7 +356,7 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri
|
||||
// INV-WS-LEASE-REGRANT-001: serialize an expired re-grant with move issue,
|
||||
// reusing the forced-move barrier so the old process's validity is past.
|
||||
// The live renewal path releases leaseMu before entering this writer.
|
||||
func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64, proof FormatReadProof) (WorkspaceLease, error) {
|
||||
func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
p.beforeWorkspaceGrantLock("regrant")
|
||||
// INV-WS-RENEW-NONBLOCKING-001: a held writer refuses this attempt;
|
||||
// a returning process can retry after that writer has settled.
|
||||
@@ -393,9 +376,6 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st
|
||||
s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch {
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
|
||||
}
|
||||
if err := p.formatReadProofError(proof, holder, epoch, line.info.Incarnation); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
if s.Lease.Revoking || s.Ack != nil || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) {
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: revocation or move pending")
|
||||
}
|
||||
|
||||
@@ -31,9 +31,6 @@ type BCatalog struct {
|
||||
base string
|
||||
cleanMu sync.Mutex
|
||||
cursors map[VolumeRef]*cleanCursor
|
||||
// chunkGuard: the startup probe saw the filer refuse a mismatched
|
||||
// IF_CHUNKS_EQUAL update; every store it opens sends the condition.
|
||||
chunkGuard bool
|
||||
}
|
||||
|
||||
// NewBCatalog returns the catalog of the volumes under base.
|
||||
@@ -52,29 +49,9 @@ func (c *BCatalog) Store(v VolumeRef) (*LayoutStore, error) {
|
||||
}
|
||||
counts, _ := c.headWrites.LoadOrStore(v.Dir(), s.headWrites)
|
||||
s.headWrites = counts.(*headWriteCounters)
|
||||
s.chunkGuard = c.chunkGuard
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Metadata change protections, as /status and the startup log name them.
|
||||
const (
|
||||
MetadataGuardChunks = "filer_chunk_condition" // the probe saw IF_CHUNKS_EQUAL enforced; the page re-read stays as well
|
||||
// MetadataGuardReread: enforcement was not established. The filer
|
||||
// applied the probe, or did not answer it definitely, or this client
|
||||
// cannot send the condition; it says nothing about what the filer
|
||||
// supports. The re-read is the only check.
|
||||
MetadataGuardReread = "page_reread_only"
|
||||
)
|
||||
|
||||
// MetadataGuard names the protection this catalog's metadata changes run
|
||||
// under, decided once by the startup probe.
|
||||
func (c *BCatalog) MetadataGuard() string {
|
||||
if c.chunkGuard {
|
||||
return MetadataGuardChunks
|
||||
}
|
||||
return MetadataGuardReread
|
||||
}
|
||||
|
||||
func (c *BCatalog) open(v VolumeRef) (*LayoutStore, *layout.Reader, error) {
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
@@ -366,12 +343,6 @@ type Usage struct {
|
||||
Dependents int `json:"dependents"`
|
||||
OwnChunks int `json:"own_chunks"`
|
||||
ForeignChunks int `json:"foreign_chunks"`
|
||||
// MetadataGuard names the protection of the volume's metadata changes:
|
||||
// filer_chunk_condition (the startup probe saw the filer enforce the
|
||||
// chunk condition) or page_reread_only (enforcement was not established
|
||||
// at startup; delete intent pages are re-read). Absent when the catalog
|
||||
// ran no probe.
|
||||
MetadataGuard string `json:"metadata_guard,omitempty"`
|
||||
}
|
||||
|
||||
// Usage reads the volume's usage from its HEAD and current root.
|
||||
@@ -387,7 +358,7 @@ func (c *BCatalog) Usage(ctx context.Context, v VolumeRef) (Usage, error) {
|
||||
if !found {
|
||||
return Usage{}, layout.ErrHeadAbsent
|
||||
}
|
||||
u := Usage{Snapshots: len(h.Snapshots), MetadataGuard: c.MetadataGuard()}
|
||||
u := Usage{Snapshots: len(h.Snapshots)}
|
||||
for _, sn := range h.Snapshots {
|
||||
u.Dependents += len(sn.Dependents)
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// ChunkGuard reports what changeMeta sends: a store over a filer that cannot
|
||||
// carry the chunk condition reports the guard off even when it was set on.
|
||||
func TestChunkGuardReportsOnlyAConditionTheFilerCanCarry(t *testing.T) {
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
filer Filer
|
||||
want bool
|
||||
}{
|
||||
{"a filer that carries it", newFakeFiler(), true},
|
||||
{"a client wrapper that cannot send it", hidesChunkCondition{newFakeFiler()}, false},
|
||||
} {
|
||||
st, err := NewLayoutStore(tc.filer, newFakeBlobs(), "/blocks/v1", id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st.SetChunkGuard(true)
|
||||
if got := st.ChunkGuard(); got != tc.want {
|
||||
t.Fatalf("%s: ChunkGuard()=%v after SetChunkGuard(true), want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A probe that fails leaves the guard off even after an earlier probe of the
|
||||
// same catalog turned it on.
|
||||
func TestAFailedChunkGuardProbeLeavesTheGuardOff(t *testing.T) {
|
||||
f := newFakeFiler()
|
||||
cat, err := NewBCatalog(f, newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cat.ProbeChunkGuard(context.Background())
|
||||
if got := cat.MetadataGuard(); got != MetadataGuardChunks {
|
||||
t.Fatalf("first probe: guard %q, want %q", got, MetadataGuardChunks)
|
||||
}
|
||||
f.failCreate = func(string) error { return errors.New("transport: lost answer") }
|
||||
cat.ProbeChunkGuard(context.Background())
|
||||
if got := cat.MetadataGuard(); got != MetadataGuardReread {
|
||||
t.Fatalf("failed probe: guard %q, want %q", got, MetadataGuardReread)
|
||||
}
|
||||
}
|
||||
@@ -64,9 +64,6 @@ type fakeFiler struct {
|
||||
// (lookups overlap) and bounded by ctx, as a remote filer's.
|
||||
slowLookup func(p string) time.Duration
|
||||
deferredCreates []deferredCreate
|
||||
// ignoreChunkCondition makes UpdateEntryIfChunks ignore its condition,
|
||||
// as a filer that predates IF_CHUNKS_EQUAL drops the unknown field.
|
||||
ignoreChunkCondition bool
|
||||
}
|
||||
|
||||
func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} }
|
||||
@@ -140,19 +137,6 @@ func (f *fakeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entr
|
||||
}
|
||||
|
||||
func (f *fakeFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
return f.updateEntry(dir, e, expected, nil)
|
||||
}
|
||||
|
||||
// UpdateEntryIfChunks evaluates IF_CHUNKS_EQUAL as the filer does (stored
|
||||
// chunk fids equal fids as a multiset), unless ignoreChunkCondition.
|
||||
func (f *fakeFiler) UpdateEntryIfChunks(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
|
||||
if fids == nil {
|
||||
fids = []string{}
|
||||
}
|
||||
return f.updateEntry(dir, e, expected, fids)
|
||||
}
|
||||
|
||||
func (f *fakeFiler) updateEntry(dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
p := path.Join(dir, e.Name)
|
||||
@@ -171,9 +155,6 @@ func (f *fakeFiler) updateEntry(dir string, e *filerpb.Entry, expected map[strin
|
||||
return fmt.Errorf("%w: extended %q changed", ErrPrecondition, k)
|
||||
}
|
||||
}
|
||||
if fids != nil && !f.ignoreChunkCondition && !fidsEqual(entryFids(cur), fids) {
|
||||
return fmt.Errorf("%w: chunks of %s changed", ErrPrecondition, p)
|
||||
}
|
||||
f.entries[p] = proto.Clone(e).(*filerpb.Entry)
|
||||
f.written = append(f.written, proto.Clone(e).(*filerpb.Entry))
|
||||
f.updates++
|
||||
|
||||
@@ -97,52 +97,6 @@ func (FilerError) EnumDescriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
type WriteCondition_Kind int32
|
||||
|
||||
const (
|
||||
WriteCondition_NONE WriteCondition_Kind = 0
|
||||
WriteCondition_IF_CHUNKS_EQUAL WriteCondition_Kind = 9 // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
|
||||
)
|
||||
|
||||
// Enum value maps for WriteCondition_Kind.
|
||||
var (
|
||||
WriteCondition_Kind_name = map[int32]string{
|
||||
0: "NONE",
|
||||
9: "IF_CHUNKS_EQUAL",
|
||||
}
|
||||
WriteCondition_Kind_value = map[string]int32{
|
||||
"NONE": 0,
|
||||
"IF_CHUNKS_EQUAL": 9,
|
||||
}
|
||||
)
|
||||
|
||||
func (x WriteCondition_Kind) Enum() *WriteCondition_Kind {
|
||||
p := new(WriteCondition_Kind)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x WriteCondition_Kind) String() string {
|
||||
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
|
||||
}
|
||||
|
||||
func (WriteCondition_Kind) Descriptor() protoreflect.EnumDescriptor {
|
||||
return file_filer_subset_proto_enumTypes[1].Descriptor()
|
||||
}
|
||||
|
||||
func (WriteCondition_Kind) Type() protoreflect.EnumType {
|
||||
return &file_filer_subset_proto_enumTypes[1]
|
||||
}
|
||||
|
||||
func (x WriteCondition_Kind) Number() protoreflect.EnumNumber {
|
||||
return protoreflect.EnumNumber(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WriteCondition_Kind.Descriptor instead.
|
||||
func (WriteCondition_Kind) EnumDescriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{9, 0}
|
||||
}
|
||||
|
||||
type LookupDirectoryEntryRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"`
|
||||
@@ -757,54 +711,6 @@ func (x *CreateEntryResponse) GetErrorCode() FilerError {
|
||||
return FilerError_OK
|
||||
}
|
||||
|
||||
// WriteCondition is copied from weed/pb/filer.proto (this repository): the
|
||||
// IF_CHUNKS_EQUAL clause only. A filer that predates it drops field 6 of
|
||||
// UpdateEntryRequest as unknown and applies the write unguarded, so the
|
||||
// chunkstore decides at startup, by a probe, whether it is enforced.
|
||||
type WriteCondition struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Clauses []*WriteCondition_Clause `protobuf:"bytes,1,rep,name=clauses,proto3" json:"clauses,omitempty"` // all must hold (logical AND)
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WriteCondition) Reset() {
|
||||
*x = WriteCondition{}
|
||||
mi := &file_filer_subset_proto_msgTypes[9]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *WriteCondition) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WriteCondition) ProtoMessage() {}
|
||||
|
||||
func (x *WriteCondition) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[9]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WriteCondition.ProtoReflect.Descriptor instead.
|
||||
func (*WriteCondition) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{9}
|
||||
}
|
||||
|
||||
func (x *WriteCondition) GetClauses() []*WriteCondition_Clause {
|
||||
if x != nil {
|
||||
return x.Clauses
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type UpdateEntryRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"`
|
||||
@@ -812,14 +718,13 @@ type UpdateEntryRequest struct {
|
||||
IsFromOtherCluster bool `protobuf:"varint,3,opt,name=is_from_other_cluster,json=isFromOtherCluster,proto3" json:"is_from_other_cluster,omitempty"`
|
||||
Signatures []int32 `protobuf:"varint,4,rep,packed,name=signatures,proto3" json:"signatures,omitempty"`
|
||||
ExpectedExtended map[string][]byte `protobuf:"bytes,5,rep,name=expected_extended,json=expectedExtended,proto3" json:"expected_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
Condition *WriteCondition `protobuf:"bytes,6,opt,name=condition,proto3" json:"condition,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *UpdateEntryRequest) Reset() {
|
||||
*x = UpdateEntryRequest{}
|
||||
mi := &file_filer_subset_proto_msgTypes[10]
|
||||
mi := &file_filer_subset_proto_msgTypes[9]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -831,7 +736,7 @@ func (x *UpdateEntryRequest) String() string {
|
||||
func (*UpdateEntryRequest) ProtoMessage() {}
|
||||
|
||||
func (x *UpdateEntryRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[10]
|
||||
mi := &file_filer_subset_proto_msgTypes[9]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -844,7 +749,7 @@ func (x *UpdateEntryRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use UpdateEntryRequest.ProtoReflect.Descriptor instead.
|
||||
func (*UpdateEntryRequest) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{10}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{9}
|
||||
}
|
||||
|
||||
func (x *UpdateEntryRequest) GetDirectory() string {
|
||||
@@ -882,13 +787,6 @@ func (x *UpdateEntryRequest) GetExpectedExtended() map[string][]byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *UpdateEntryRequest) GetCondition() *WriteCondition {
|
||||
if x != nil {
|
||||
return x.Condition
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type UpdateEntryResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -897,7 +795,7 @@ type UpdateEntryResponse struct {
|
||||
|
||||
func (x *UpdateEntryResponse) Reset() {
|
||||
*x = UpdateEntryResponse{}
|
||||
mi := &file_filer_subset_proto_msgTypes[11]
|
||||
mi := &file_filer_subset_proto_msgTypes[10]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -909,7 +807,7 @@ func (x *UpdateEntryResponse) String() string {
|
||||
func (*UpdateEntryResponse) ProtoMessage() {}
|
||||
|
||||
func (x *UpdateEntryResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[11]
|
||||
mi := &file_filer_subset_proto_msgTypes[10]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -922,7 +820,7 @@ func (x *UpdateEntryResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use UpdateEntryResponse.ProtoReflect.Descriptor instead.
|
||||
func (*UpdateEntryResponse) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{11}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{10}
|
||||
}
|
||||
|
||||
type DeleteEntryRequest struct {
|
||||
@@ -938,7 +836,7 @@ type DeleteEntryRequest struct {
|
||||
|
||||
func (x *DeleteEntryRequest) Reset() {
|
||||
*x = DeleteEntryRequest{}
|
||||
mi := &file_filer_subset_proto_msgTypes[12]
|
||||
mi := &file_filer_subset_proto_msgTypes[11]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -950,7 +848,7 @@ func (x *DeleteEntryRequest) String() string {
|
||||
func (*DeleteEntryRequest) ProtoMessage() {}
|
||||
|
||||
func (x *DeleteEntryRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[12]
|
||||
mi := &file_filer_subset_proto_msgTypes[11]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -963,7 +861,7 @@ func (x *DeleteEntryRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use DeleteEntryRequest.ProtoReflect.Descriptor instead.
|
||||
func (*DeleteEntryRequest) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{12}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{11}
|
||||
}
|
||||
|
||||
func (x *DeleteEntryRequest) GetDirectory() string {
|
||||
@@ -1010,7 +908,7 @@ type DeleteEntryResponse struct {
|
||||
|
||||
func (x *DeleteEntryResponse) Reset() {
|
||||
*x = DeleteEntryResponse{}
|
||||
mi := &file_filer_subset_proto_msgTypes[13]
|
||||
mi := &file_filer_subset_proto_msgTypes[12]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1022,7 +920,7 @@ func (x *DeleteEntryResponse) String() string {
|
||||
func (*DeleteEntryResponse) ProtoMessage() {}
|
||||
|
||||
func (x *DeleteEntryResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[13]
|
||||
mi := &file_filer_subset_proto_msgTypes[12]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1035,7 +933,7 @@ func (x *DeleteEntryResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use DeleteEntryResponse.ProtoReflect.Descriptor instead.
|
||||
func (*DeleteEntryResponse) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{13}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{12}
|
||||
}
|
||||
|
||||
func (x *DeleteEntryResponse) GetError() string {
|
||||
@@ -1063,7 +961,7 @@ type AssignVolumeRequest struct {
|
||||
|
||||
func (x *AssignVolumeRequest) Reset() {
|
||||
*x = AssignVolumeRequest{}
|
||||
mi := &file_filer_subset_proto_msgTypes[14]
|
||||
mi := &file_filer_subset_proto_msgTypes[13]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1075,7 +973,7 @@ func (x *AssignVolumeRequest) String() string {
|
||||
func (*AssignVolumeRequest) ProtoMessage() {}
|
||||
|
||||
func (x *AssignVolumeRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[14]
|
||||
mi := &file_filer_subset_proto_msgTypes[13]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1088,7 +986,7 @@ func (x *AssignVolumeRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use AssignVolumeRequest.ProtoReflect.Descriptor instead.
|
||||
func (*AssignVolumeRequest) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{14}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{13}
|
||||
}
|
||||
|
||||
func (x *AssignVolumeRequest) GetCount() int32 {
|
||||
@@ -1179,7 +1077,7 @@ type AssignVolumeResponse struct {
|
||||
|
||||
func (x *AssignVolumeResponse) Reset() {
|
||||
*x = AssignVolumeResponse{}
|
||||
mi := &file_filer_subset_proto_msgTypes[15]
|
||||
mi := &file_filer_subset_proto_msgTypes[14]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1191,7 +1089,7 @@ func (x *AssignVolumeResponse) String() string {
|
||||
func (*AssignVolumeResponse) ProtoMessage() {}
|
||||
|
||||
func (x *AssignVolumeResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[15]
|
||||
mi := &file_filer_subset_proto_msgTypes[14]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1204,7 +1102,7 @@ func (x *AssignVolumeResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use AssignVolumeResponse.ProtoReflect.Descriptor instead.
|
||||
func (*AssignVolumeResponse) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{15}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{14}
|
||||
}
|
||||
|
||||
func (x *AssignVolumeResponse) GetFileId() string {
|
||||
@@ -1286,7 +1184,7 @@ type LookupVolumeRequest struct {
|
||||
|
||||
func (x *LookupVolumeRequest) Reset() {
|
||||
*x = LookupVolumeRequest{}
|
||||
mi := &file_filer_subset_proto_msgTypes[16]
|
||||
mi := &file_filer_subset_proto_msgTypes[15]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1298,7 +1196,7 @@ func (x *LookupVolumeRequest) String() string {
|
||||
func (*LookupVolumeRequest) ProtoMessage() {}
|
||||
|
||||
func (x *LookupVolumeRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[16]
|
||||
mi := &file_filer_subset_proto_msgTypes[15]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1311,7 +1209,7 @@ func (x *LookupVolumeRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use LookupVolumeRequest.ProtoReflect.Descriptor instead.
|
||||
func (*LookupVolumeRequest) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{16}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{15}
|
||||
}
|
||||
|
||||
func (x *LookupVolumeRequest) GetVolumeIds() []string {
|
||||
@@ -1330,7 +1228,7 @@ type Locations struct {
|
||||
|
||||
func (x *Locations) Reset() {
|
||||
*x = Locations{}
|
||||
mi := &file_filer_subset_proto_msgTypes[17]
|
||||
mi := &file_filer_subset_proto_msgTypes[16]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1342,7 +1240,7 @@ func (x *Locations) String() string {
|
||||
func (*Locations) ProtoMessage() {}
|
||||
|
||||
func (x *Locations) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[17]
|
||||
mi := &file_filer_subset_proto_msgTypes[16]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1355,7 +1253,7 @@ func (x *Locations) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use Locations.ProtoReflect.Descriptor instead.
|
||||
func (*Locations) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{17}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{16}
|
||||
}
|
||||
|
||||
func (x *Locations) GetLocations() []*Location {
|
||||
@@ -1378,7 +1276,7 @@ type Location struct {
|
||||
|
||||
func (x *Location) Reset() {
|
||||
*x = Location{}
|
||||
mi := &file_filer_subset_proto_msgTypes[18]
|
||||
mi := &file_filer_subset_proto_msgTypes[17]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1390,7 +1288,7 @@ func (x *Location) String() string {
|
||||
func (*Location) ProtoMessage() {}
|
||||
|
||||
func (x *Location) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[18]
|
||||
mi := &file_filer_subset_proto_msgTypes[17]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1403,7 +1301,7 @@ func (x *Location) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use Location.ProtoReflect.Descriptor instead.
|
||||
func (*Location) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{18}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{17}
|
||||
}
|
||||
|
||||
func (x *Location) GetUrl() string {
|
||||
@@ -1450,7 +1348,7 @@ type LookupVolumeResponse struct {
|
||||
|
||||
func (x *LookupVolumeResponse) Reset() {
|
||||
*x = LookupVolumeResponse{}
|
||||
mi := &file_filer_subset_proto_msgTypes[19]
|
||||
mi := &file_filer_subset_proto_msgTypes[18]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1462,7 +1360,7 @@ func (x *LookupVolumeResponse) String() string {
|
||||
func (*LookupVolumeResponse) ProtoMessage() {}
|
||||
|
||||
func (x *LookupVolumeResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[19]
|
||||
mi := &file_filer_subset_proto_msgTypes[18]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1475,7 +1373,7 @@ func (x *LookupVolumeResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use LookupVolumeResponse.ProtoReflect.Descriptor instead.
|
||||
func (*LookupVolumeResponse) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{19}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{18}
|
||||
}
|
||||
|
||||
func (x *LookupVolumeResponse) GetLocationsMap() map[string]*Locations {
|
||||
@@ -1493,7 +1391,7 @@ type GetFilerConfigurationRequest struct {
|
||||
|
||||
func (x *GetFilerConfigurationRequest) Reset() {
|
||||
*x = GetFilerConfigurationRequest{}
|
||||
mi := &file_filer_subset_proto_msgTypes[20]
|
||||
mi := &file_filer_subset_proto_msgTypes[19]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1505,7 +1403,7 @@ func (x *GetFilerConfigurationRequest) String() string {
|
||||
func (*GetFilerConfigurationRequest) ProtoMessage() {}
|
||||
|
||||
func (x *GetFilerConfigurationRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[20]
|
||||
mi := &file_filer_subset_proto_msgTypes[19]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1518,7 +1416,7 @@ func (x *GetFilerConfigurationRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use GetFilerConfigurationRequest.ProtoReflect.Descriptor instead.
|
||||
func (*GetFilerConfigurationRequest) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{20}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{19}
|
||||
}
|
||||
|
||||
// Only the fields the single-filer startup check reads.
|
||||
@@ -1532,7 +1430,7 @@ type GetFilerConfigurationResponse struct {
|
||||
|
||||
func (x *GetFilerConfigurationResponse) Reset() {
|
||||
*x = GetFilerConfigurationResponse{}
|
||||
mi := &file_filer_subset_proto_msgTypes[21]
|
||||
mi := &file_filer_subset_proto_msgTypes[20]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -1544,7 +1442,7 @@ func (x *GetFilerConfigurationResponse) String() string {
|
||||
func (*GetFilerConfigurationResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GetFilerConfigurationResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[21]
|
||||
mi := &file_filer_subset_proto_msgTypes[20]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -1557,7 +1455,7 @@ func (x *GetFilerConfigurationResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use GetFilerConfigurationResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GetFilerConfigurationResponse) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{21}
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{20}
|
||||
}
|
||||
|
||||
func (x *GetFilerConfigurationResponse) GetMasters() []string {
|
||||
@@ -1574,58 +1472,6 @@ func (x *GetFilerConfigurationResponse) GetFilerGroup() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
type WriteCondition_Clause struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Kind WriteCondition_Kind `protobuf:"varint,1,opt,name=kind,proto3,enum=filer_pb.WriteCondition_Kind" json:"kind,omitempty"`
|
||||
Fids []string `protobuf:"bytes,9,rep,name=fids,proto3" json:"fids,omitempty"` // chunk fid strings for IF_CHUNKS_EQUAL
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WriteCondition_Clause) Reset() {
|
||||
*x = WriteCondition_Clause{}
|
||||
mi := &file_filer_subset_proto_msgTypes[23]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *WriteCondition_Clause) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WriteCondition_Clause) ProtoMessage() {}
|
||||
|
||||
func (x *WriteCondition_Clause) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_subset_proto_msgTypes[23]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WriteCondition_Clause.ProtoReflect.Descriptor instead.
|
||||
func (*WriteCondition_Clause) Descriptor() ([]byte, []int) {
|
||||
return file_filer_subset_proto_rawDescGZIP(), []int{9, 0}
|
||||
}
|
||||
|
||||
func (x *WriteCondition_Clause) GetKind() WriteCondition_Kind {
|
||||
if x != nil {
|
||||
return x.Kind
|
||||
}
|
||||
return WriteCondition_NONE
|
||||
}
|
||||
|
||||
func (x *WriteCondition_Clause) GetFids() []string {
|
||||
if x != nil {
|
||||
return x.Fids
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_filer_subset_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_filer_subset_proto_rawDesc = "" +
|
||||
@@ -1684,15 +1530,7 @@ const file_filer_subset_proto_rawDesc = "" +
|
||||
"\x13CreateEntryResponse\x12\x14\n" +
|
||||
"\x05error\x18\x01 \x01(\tR\x05error\x123\n" +
|
||||
"\n" +
|
||||
"error_code\x18\x03 \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\"\xc3\x01\n" +
|
||||
"\x0eWriteCondition\x129\n" +
|
||||
"\aclauses\x18\x01 \x03(\v2\x1f.filer_pb.WriteCondition.ClauseR\aclauses\x1aO\n" +
|
||||
"\x06Clause\x121\n" +
|
||||
"\x04kind\x18\x01 \x01(\x0e2\x1d.filer_pb.WriteCondition.KindR\x04kind\x12\x12\n" +
|
||||
"\x04fids\x18\t \x03(\tR\x04fids\"%\n" +
|
||||
"\x04Kind\x12\b\n" +
|
||||
"\x04NONE\x10\x00\x12\x13\n" +
|
||||
"\x0fIF_CHUNKS_EQUAL\x10\t\"\x8a\x03\n" +
|
||||
"error_code\x18\x03 \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\"\xd2\x02\n" +
|
||||
"\x12UpdateEntryRequest\x12\x1c\n" +
|
||||
"\tdirectory\x18\x01 \x01(\tR\tdirectory\x12%\n" +
|
||||
"\x05entry\x18\x02 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x121\n" +
|
||||
@@ -1700,8 +1538,7 @@ const file_filer_subset_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"signatures\x18\x04 \x03(\x05R\n" +
|
||||
"signatures\x12_\n" +
|
||||
"\x11expected_extended\x18\x05 \x03(\v22.filer_pb.UpdateEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x126\n" +
|
||||
"\tcondition\x18\x06 \x01(\v2\x18.filer_pb.WriteConditionR\tcondition\x1aC\n" +
|
||||
"\x11expected_extended\x18\x05 \x03(\v22.filer_pb.UpdateEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x1aC\n" +
|
||||
"\x15ExpectedExtendedEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"\x15\n" +
|
||||
@@ -1802,80 +1639,74 @@ func file_filer_subset_proto_rawDescGZIP() []byte {
|
||||
return file_filer_subset_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_filer_subset_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
|
||||
var file_filer_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 27)
|
||||
var file_filer_subset_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_filer_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 25)
|
||||
var file_filer_subset_proto_goTypes = []any{
|
||||
(FilerError)(0), // 0: filer_pb.FilerError
|
||||
(WriteCondition_Kind)(0), // 1: filer_pb.WriteCondition.Kind
|
||||
(*LookupDirectoryEntryRequest)(nil), // 2: filer_pb.LookupDirectoryEntryRequest
|
||||
(*LookupDirectoryEntryResponse)(nil), // 3: filer_pb.LookupDirectoryEntryResponse
|
||||
(*ListEntriesRequest)(nil), // 4: filer_pb.ListEntriesRequest
|
||||
(*ListEntriesResponse)(nil), // 5: filer_pb.ListEntriesResponse
|
||||
(*Entry)(nil), // 6: filer_pb.Entry
|
||||
(*FileChunk)(nil), // 7: filer_pb.FileChunk
|
||||
(*FuseAttributes)(nil), // 8: filer_pb.FuseAttributes
|
||||
(*CreateEntryRequest)(nil), // 9: filer_pb.CreateEntryRequest
|
||||
(*CreateEntryResponse)(nil), // 10: filer_pb.CreateEntryResponse
|
||||
(*WriteCondition)(nil), // 11: filer_pb.WriteCondition
|
||||
(*UpdateEntryRequest)(nil), // 12: filer_pb.UpdateEntryRequest
|
||||
(*UpdateEntryResponse)(nil), // 13: filer_pb.UpdateEntryResponse
|
||||
(*DeleteEntryRequest)(nil), // 14: filer_pb.DeleteEntryRequest
|
||||
(*DeleteEntryResponse)(nil), // 15: filer_pb.DeleteEntryResponse
|
||||
(*AssignVolumeRequest)(nil), // 16: filer_pb.AssignVolumeRequest
|
||||
(*AssignVolumeResponse)(nil), // 17: filer_pb.AssignVolumeResponse
|
||||
(*LookupVolumeRequest)(nil), // 18: filer_pb.LookupVolumeRequest
|
||||
(*Locations)(nil), // 19: filer_pb.Locations
|
||||
(*Location)(nil), // 20: filer_pb.Location
|
||||
(*LookupVolumeResponse)(nil), // 21: filer_pb.LookupVolumeResponse
|
||||
(*GetFilerConfigurationRequest)(nil), // 22: filer_pb.GetFilerConfigurationRequest
|
||||
(*GetFilerConfigurationResponse)(nil), // 23: filer_pb.GetFilerConfigurationResponse
|
||||
nil, // 24: filer_pb.Entry.ExtendedEntry
|
||||
(*WriteCondition_Clause)(nil), // 25: filer_pb.WriteCondition.Clause
|
||||
nil, // 26: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
|
||||
nil, // 27: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
|
||||
nil, // 28: filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
(*LookupDirectoryEntryRequest)(nil), // 1: filer_pb.LookupDirectoryEntryRequest
|
||||
(*LookupDirectoryEntryResponse)(nil), // 2: filer_pb.LookupDirectoryEntryResponse
|
||||
(*ListEntriesRequest)(nil), // 3: filer_pb.ListEntriesRequest
|
||||
(*ListEntriesResponse)(nil), // 4: filer_pb.ListEntriesResponse
|
||||
(*Entry)(nil), // 5: filer_pb.Entry
|
||||
(*FileChunk)(nil), // 6: filer_pb.FileChunk
|
||||
(*FuseAttributes)(nil), // 7: filer_pb.FuseAttributes
|
||||
(*CreateEntryRequest)(nil), // 8: filer_pb.CreateEntryRequest
|
||||
(*CreateEntryResponse)(nil), // 9: filer_pb.CreateEntryResponse
|
||||
(*UpdateEntryRequest)(nil), // 10: filer_pb.UpdateEntryRequest
|
||||
(*UpdateEntryResponse)(nil), // 11: filer_pb.UpdateEntryResponse
|
||||
(*DeleteEntryRequest)(nil), // 12: filer_pb.DeleteEntryRequest
|
||||
(*DeleteEntryResponse)(nil), // 13: filer_pb.DeleteEntryResponse
|
||||
(*AssignVolumeRequest)(nil), // 14: filer_pb.AssignVolumeRequest
|
||||
(*AssignVolumeResponse)(nil), // 15: filer_pb.AssignVolumeResponse
|
||||
(*LookupVolumeRequest)(nil), // 16: filer_pb.LookupVolumeRequest
|
||||
(*Locations)(nil), // 17: filer_pb.Locations
|
||||
(*Location)(nil), // 18: filer_pb.Location
|
||||
(*LookupVolumeResponse)(nil), // 19: filer_pb.LookupVolumeResponse
|
||||
(*GetFilerConfigurationRequest)(nil), // 20: filer_pb.GetFilerConfigurationRequest
|
||||
(*GetFilerConfigurationResponse)(nil), // 21: filer_pb.GetFilerConfigurationResponse
|
||||
nil, // 22: filer_pb.Entry.ExtendedEntry
|
||||
nil, // 23: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
|
||||
nil, // 24: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
|
||||
nil, // 25: filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
}
|
||||
var file_filer_subset_proto_depIdxs = []int32{
|
||||
6, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry
|
||||
6, // 1: filer_pb.ListEntriesResponse.entry:type_name -> filer_pb.Entry
|
||||
7, // 2: filer_pb.Entry.chunks:type_name -> filer_pb.FileChunk
|
||||
8, // 3: filer_pb.Entry.attributes:type_name -> filer_pb.FuseAttributes
|
||||
24, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry
|
||||
6, // 5: filer_pb.CreateEntryRequest.entry:type_name -> filer_pb.Entry
|
||||
5, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry
|
||||
5, // 1: filer_pb.ListEntriesResponse.entry:type_name -> filer_pb.Entry
|
||||
6, // 2: filer_pb.Entry.chunks:type_name -> filer_pb.FileChunk
|
||||
7, // 3: filer_pb.Entry.attributes:type_name -> filer_pb.FuseAttributes
|
||||
22, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry
|
||||
5, // 5: filer_pb.CreateEntryRequest.entry:type_name -> filer_pb.Entry
|
||||
0, // 6: filer_pb.CreateEntryResponse.error_code:type_name -> filer_pb.FilerError
|
||||
25, // 7: filer_pb.WriteCondition.clauses:type_name -> filer_pb.WriteCondition.Clause
|
||||
6, // 8: filer_pb.UpdateEntryRequest.entry:type_name -> filer_pb.Entry
|
||||
26, // 9: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
|
||||
11, // 10: filer_pb.UpdateEntryRequest.condition:type_name -> filer_pb.WriteCondition
|
||||
27, // 11: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
|
||||
20, // 12: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location
|
||||
20, // 13: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location
|
||||
0, // 14: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError
|
||||
20, // 15: filer_pb.Locations.locations:type_name -> filer_pb.Location
|
||||
28, // 16: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
1, // 17: filer_pb.WriteCondition.Clause.kind:type_name -> filer_pb.WriteCondition.Kind
|
||||
19, // 18: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
2, // 19: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
|
||||
4, // 20: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
|
||||
9, // 21: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
|
||||
12, // 22: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
|
||||
14, // 23: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
|
||||
16, // 24: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
|
||||
18, // 25: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
|
||||
22, // 26: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
|
||||
3, // 27: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
|
||||
5, // 28: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
|
||||
10, // 29: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
|
||||
13, // 30: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
|
||||
15, // 31: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
|
||||
17, // 32: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
|
||||
21, // 33: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
|
||||
23, // 34: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
|
||||
27, // [27:35] is the sub-list for method output_type
|
||||
19, // [19:27] is the sub-list for method input_type
|
||||
19, // [19:19] is the sub-list for extension type_name
|
||||
19, // [19:19] is the sub-list for extension extendee
|
||||
0, // [0:19] is the sub-list for field type_name
|
||||
5, // 7: filer_pb.UpdateEntryRequest.entry:type_name -> filer_pb.Entry
|
||||
23, // 8: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
|
||||
24, // 9: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
|
||||
18, // 10: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location
|
||||
18, // 11: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location
|
||||
0, // 12: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError
|
||||
18, // 13: filer_pb.Locations.locations:type_name -> filer_pb.Location
|
||||
25, // 14: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
17, // 15: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
1, // 16: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
|
||||
3, // 17: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
|
||||
8, // 18: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
|
||||
10, // 19: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
|
||||
12, // 20: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
|
||||
14, // 21: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
|
||||
16, // 22: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
|
||||
20, // 23: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
|
||||
2, // 24: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
|
||||
4, // 25: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
|
||||
9, // 26: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
|
||||
11, // 27: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
|
||||
13, // 28: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
|
||||
15, // 29: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
|
||||
19, // 30: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
|
||||
21, // 31: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
|
||||
24, // [24:32] is the sub-list for method output_type
|
||||
16, // [16:24] is the sub-list for method input_type
|
||||
16, // [16:16] is the sub-list for extension type_name
|
||||
16, // [16:16] is the sub-list for extension extendee
|
||||
0, // [0:16] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_filer_subset_proto_init() }
|
||||
@@ -1888,8 +1719,8 @@ func file_filer_subset_proto_init() {
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_filer_subset_proto_rawDesc), len(file_filer_subset_proto_rawDesc)),
|
||||
NumEnums: 2,
|
||||
NumMessages: 27,
|
||||
NumEnums: 1,
|
||||
NumMessages: 25,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -102,29 +102,12 @@ message CreateEntryResponse {
|
||||
FilerError error_code = 3;
|
||||
}
|
||||
|
||||
// WriteCondition is copied from weed/pb/filer.proto (this repository): the
|
||||
// IF_CHUNKS_EQUAL clause only. A filer that predates it drops field 6 of
|
||||
// UpdateEntryRequest as unknown and applies the write unguarded, so the
|
||||
// chunkstore decides at startup, by a probe, whether it is enforced.
|
||||
message WriteCondition {
|
||||
enum Kind {
|
||||
NONE = 0;
|
||||
IF_CHUNKS_EQUAL = 9; // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
|
||||
}
|
||||
message Clause {
|
||||
Kind kind = 1;
|
||||
repeated string fids = 9; // chunk fid strings for IF_CHUNKS_EQUAL
|
||||
}
|
||||
repeated Clause clauses = 1; // all must hold (logical AND)
|
||||
}
|
||||
|
||||
message UpdateEntryRequest {
|
||||
string directory = 1;
|
||||
Entry entry = 2;
|
||||
bool is_from_other_cluster = 3;
|
||||
repeated int32 signatures = 4;
|
||||
map<string, bytes> expected_extended = 5;
|
||||
WriteCondition condition = 6;
|
||||
}
|
||||
|
||||
message UpdateEntryResponse {
|
||||
|
||||
@@ -45,7 +45,6 @@ var headReaders = map[string]string{
|
||||
"core/frontend/chunkstore/layout_verify.go verifyHead -> LookupEntry": "absent or unknown generation makes verify incomplete and suppresses MISSING/ORPHAN (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
|
||||
"core/frontend/chunkstore/layout_verify.go verifyHead -> DecodeLayoutHeadEntry": "invalid inline envelope supplies no generation and cannot confirm findings (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
|
||||
"core/frontend/chunkstore/startup_head_probe.go checkConditionalHead -> ReadHead": "absent/unreadable/changed disposable HEAD refuses startup; no volume HEAD is read (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
|
||||
"core/frontend/chunkstore/startup_head_probe.go probeChunkCondition -> LookupEntry": "absent/unreadable disposable HEAD leaves the chunk guard off (page re-read only); no volume HEAD is read (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
|
||||
"cmd/blockvolume/chunk_maintenance.go newChunkMaintenance -> ReadHead": "diagnostic absent HEAD reports headGen0 and headGenError; it neither authorizes nor changes cleaning (TestMaintenanceStatusRealPassAndTimeout/head-absent)",
|
||||
"core/frontend/chunkstore/layout_remote.go ProbeSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion; open local activity skips the read (TestMaintenanceNoticesSnapshotDeleteWithoutNotification, TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD)",
|
||||
"core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)",
|
||||
|
||||
@@ -172,18 +172,6 @@ func RunDeleteSnapshotWithIntent(ctx context.Context, st ListChainStore, base ui
|
||||
if !found || meta.Volume != h.VolumeID || meta.Session != deleteIntentWriter(base, ref) || meta.Mark != "" {
|
||||
return ErrPrecondition
|
||||
}
|
||||
// Read the page again now that this run owns its tag. A stalled
|
||||
// update from another run of the same delete can land between
|
||||
// the read above and the adoption, putting a deleted page's data
|
||||
// reference on this entry; once this run's tag is on it, no such
|
||||
// update passes. An intent published over a page whose data is
|
||||
// gone could never be consumed. The filer frees chunks from a
|
||||
// deletion queue, so this sees only data already freed.
|
||||
again := c
|
||||
again.Ref = ref
|
||||
if _, err := readListPage(ctx, st, h.VolumeID, again); err != nil {
|
||||
return fmt.Errorf("%w: delete intent page changed during adoption: %w", ErrPrecondition, err)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return Head{}, false, err
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// staleUpdateBeforeAdoption is the store as the second run of a snapshot
|
||||
// delete sees it when the first run's stalled page update lands between the
|
||||
// second run's read of one page (rel) and its adoption: the page then
|
||||
// carries the first run's writer tag, and its data is whatever the update
|
||||
// left. This is a consequence-level projection of that update: it edits the
|
||||
// tag and decides what a later read of the page returns (mode). The backend
|
||||
// mechanism itself, a tag-conditional whole-entry update writing a deleted
|
||||
// object's chunk reference over a re-created one, is exercised on the real
|
||||
// store in package chunkstore: refused with the filer's chunk condition
|
||||
// (TestAStaleMetadataChangeDoesNotOverwriteARecreatedObject), and landing
|
||||
// without it (TestWithoutTheChunkGuardAStaleMetadataChangeOverwritesARecreatedObject).
|
||||
type staleUpdateBeforeAdoption struct {
|
||||
*chainStore
|
||||
rel string
|
||||
staleTag string
|
||||
mode string // "freed": the read fails; "wrong": it returns other bytes; "deadline": the caller's deadline ends the read; "valid": the bytes are intact
|
||||
wrong []byte
|
||||
landed bool
|
||||
}
|
||||
|
||||
func (s *staleUpdateBeforeAdoption) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) {
|
||||
if rel == s.rel && !s.landed {
|
||||
s.landed = true
|
||||
if o, ok := s.objs[s.full(rel)]; ok {
|
||||
o.meta.Session = s.staleTag
|
||||
}
|
||||
}
|
||||
return s.chainStore.Stat(ctx, rel)
|
||||
}
|
||||
|
||||
func (s *staleUpdateBeforeAdoption) ReadListPage(ctx context.Context, ref ListRef) ([]byte, bool, error) {
|
||||
if rel, _ := ref.Path(); s.landed && rel == s.rel {
|
||||
switch s.mode {
|
||||
case "freed":
|
||||
return nil, false, errors.New("the page's data was freed")
|
||||
case "wrong":
|
||||
return append([]byte(nil), s.wrong...), true, nil
|
||||
case "deadline":
|
||||
return nil, false, fmt.Errorf("lookup: %w", context.DeadlineExceeded)
|
||||
}
|
||||
}
|
||||
return s.chainStore.ReadListPage(ctx, ref)
|
||||
}
|
||||
|
||||
// rerunFixture stages a snapshot delete's intent at the first base, lets a
|
||||
// cleaning pass delete the unlinked pages, and stages them again at the new
|
||||
// base: the second run. With twoPages the intent has two pages and the
|
||||
// stale update hits the later one, the second page the chain visits.
|
||||
func rerunFixture(t *testing.T, twoPages bool) (s *chainStore, c ListCursor, hit ListRef, other []byte, firstBase, secondBase uint64) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
s, c, p := deleteIntentFixture(t)
|
||||
firstBase = s.h.Gen
|
||||
pages := []ListPage{p}
|
||||
if twoPages {
|
||||
tail := p
|
||||
tail.Entries = p.Entries[1:]
|
||||
tailRef, err := tail.Ref()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head := p
|
||||
head.Entries = p.Entries[:1]
|
||||
head.Pages = 2
|
||||
head.Next = &tailRef
|
||||
headRef, err := head.Ref()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pages = []ListPage{tail, head}
|
||||
c.Ref = headRef
|
||||
}
|
||||
stage := func(base uint64) {
|
||||
for _, pg := range pages {
|
||||
if _, err := StageSnapshotDeletePage(ctx, s, base, pg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
stage(firstBase)
|
||||
s.h.Gen = firstBase + 2 // a cleaning pass
|
||||
for _, pg := range pages {
|
||||
ref, _ := pg.Ref()
|
||||
rel, _ := ref.Path()
|
||||
delete(s.objs, s.full(rel))
|
||||
}
|
||||
secondBase = s.h.Gen
|
||||
stage(secondBase)
|
||||
hit, _ = pages[0].Ref() // the only page, or the tail: the later page visited
|
||||
for _, pg := range pages {
|
||||
if ref, _ := pg.Ref(); ref != hit {
|
||||
other, _, _ = s.ReadListPage(ctx, ref)
|
||||
}
|
||||
}
|
||||
if other == nil {
|
||||
other = []byte(`{"pages":1,"entries":["not this page"]}`)
|
||||
}
|
||||
return s, c, hit, other, firstBase, secondBase
|
||||
}
|
||||
|
||||
// The second run of a snapshot delete must not publish an intent whose page
|
||||
// lost its data, or holds other bytes, after a stalled update from the first
|
||||
// run landed between the second run's read of the page and its adoption.
|
||||
// The refusal comes after the adoption (the page carries this run's tag), is
|
||||
// a precondition, and writes nothing to HEAD: the snapshot stays. The same
|
||||
// schedule with the page's bytes intact publishes.
|
||||
func TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mode string
|
||||
twoPages bool
|
||||
publish bool
|
||||
cause error
|
||||
}{
|
||||
{"freed, one page", "freed", false, false, nil},
|
||||
{"other bytes, one page", "wrong", false, false, nil},
|
||||
{"freed, the later of two pages", "freed", true, false, nil},
|
||||
{"other bytes, the later of two pages", "wrong", true, false, nil},
|
||||
{"the caller's deadline ends the re-read", "deadline", false, false, context.DeadlineExceeded},
|
||||
{"intact bytes after the stale tag, one page", "valid", false, true, nil},
|
||||
{"intact bytes after the stale tag, two pages", "valid", true, true, nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, c, hit, other, firstBase, secondBase := rerunFixture(t, tc.twoPages)
|
||||
rel, err := hit.Path()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := &staleUpdateBeforeAdoption{chainStore: s, rel: rel, staleTag: deleteIntentWriter(firstBase, hit), mode: tc.mode, wrong: other}
|
||||
updates := s.updates
|
||||
_, publishErr := RunDeleteSnapshotWithIntent(ctx, st, secondBase, c)
|
||||
if !st.landed {
|
||||
t.Fatal("fixture: the stale update never landed (the adoption did not Stat the page)")
|
||||
}
|
||||
if tc.publish {
|
||||
if publishErr != nil || s.h.List == nil {
|
||||
t.Fatalf("an intact page after the stale tag did not publish: %v, list %+v", publishErr, s.h.List)
|
||||
}
|
||||
if _, kept := s.h.Snapshots["daily"]; kept {
|
||||
t.Fatal("published, but the snapshot is still named")
|
||||
}
|
||||
return
|
||||
}
|
||||
if !errors.Is(publishErr, ErrPrecondition) {
|
||||
t.Fatalf("publishing over a page whose data changed answered %v, want ErrPrecondition", publishErr)
|
||||
}
|
||||
if tc.cause != nil && !errors.Is(publishErr, tc.cause) {
|
||||
t.Fatalf("the refusal dropped the re-read's cause: %v, want it to keep %v", publishErr, tc.cause)
|
||||
}
|
||||
if s.h.List != nil || s.updates != updates {
|
||||
t.Fatalf("the refusal wrote HEAD: list %+v, %d update(s)", s.h.List, s.updates-updates)
|
||||
}
|
||||
if snap, kept := s.h.Snapshots["daily"]; !kept || snap.Gen != 4 {
|
||||
t.Fatalf("the refusal did not keep the snapshot: %+v (kept %v)", snap, kept)
|
||||
}
|
||||
if meta, found, _ := s.Stat(ctx, rel); !found || meta.Session != deleteIntentWriter(secondBase, hit) {
|
||||
t.Fatalf("the refusal came before the adoption: the page's tag is %+v, want this run's %q", meta, deleteIntentWriter(secondBase, hit))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// betweenLookupAndUpdate runs before, once, ahead of the first update: what
|
||||
// other writers do while a stale one is between its lookup and its
|
||||
// conditional update. It forwards the chunk condition, so a store over it can
|
||||
// run with the guard on.
|
||||
type betweenLookupAndUpdate struct {
|
||||
Filer
|
||||
once sync.Once
|
||||
before func()
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
f.once.Do(f.before)
|
||||
return f.Filer.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
|
||||
f.once.Do(f.before)
|
||||
return f.Filer.(ChunkConditionFiler).UpdateEntryIfChunks(ctx, dir, e, expected, fids)
|
||||
}
|
||||
|
||||
// recreatedObject is one object that a stale writer looked up, then (while
|
||||
// the writer was between its lookup and its update) a cleaner marked and
|
||||
// deleted, and another executor of the same operation created again with the
|
||||
// same producer tag and a new chunk.
|
||||
type recreatedObject struct {
|
||||
f *fakeFiler
|
||||
others, stale *LayoutStore
|
||||
rel string
|
||||
meta layout.ObjectMeta
|
||||
first, second string
|
||||
fid func() (string, bool)
|
||||
}
|
||||
|
||||
func newRecreatedObject(t *testing.T, guard bool) *recreatedObject {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
var id layout.VolumeID
|
||||
for i := range id {
|
||||
id[i] = 0x30 + byte(i)
|
||||
}
|
||||
others, err := NewLayoutStore(f, b, "/vol", id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hooked := &betweenLookupAndUpdate{Filer: f}
|
||||
stale, err := NewLayoutStore(hooked, b, "/vol", id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale.SetChunkGuard(guard)
|
||||
data := bytes.Repeat([]byte{0x5a}, 4096)
|
||||
o := &recreatedObject{f: f, others: others, stale: stale, rel: layout.NameChunk(1, data).Path()}
|
||||
dir, name, err := others.object(o.rel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.fid = func() (string, bool) {
|
||||
e, err := f.LookupEntry(ctx, dir, name)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return "", false
|
||||
}
|
||||
if err != nil || len(e.Chunks) != 1 {
|
||||
t.Fatalf("lookup %s: %+v %v", o.rel, e, err)
|
||||
}
|
||||
return e.Chunks[0].FileId, true
|
||||
}
|
||||
if err := others.Create(ctx, o.rel, data, "producer-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.first, _ = o.fid()
|
||||
meta, found, err := others.Stat(ctx, o.rel)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("stat: %v %v", found, err)
|
||||
}
|
||||
o.meta = meta
|
||||
hooked.before = func() {
|
||||
if err := others.Mark(ctx, o.rel, meta, "clean-1"); err != nil {
|
||||
t.Errorf("mark: %v", err)
|
||||
}
|
||||
if err := others.DeleteMarked(ctx, o.rel, "clean-1"); err != nil {
|
||||
t.Errorf("delete: %v", err)
|
||||
}
|
||||
if err := others.Create(ctx, o.rel, data, "producer-1"); err != nil {
|
||||
t.Errorf("re-create: %v", err)
|
||||
}
|
||||
o.second, _ = o.fid()
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *recreatedObject) checkRecreated(t *testing.T) {
|
||||
t.Helper()
|
||||
if o.second == "" || o.second == o.first {
|
||||
t.Fatalf("fixture: the object was not re-created with a new chunk (first %s, second %s)", o.first, o.second)
|
||||
}
|
||||
}
|
||||
|
||||
// A stale metadata change (a delete-intent page's adoption by an executor
|
||||
// that paused between its lookup and its update) must not write the entry it
|
||||
// looked up over an object deleted and created again with the same tags in
|
||||
// between: the update would put the deleted object's chunk on the new entry,
|
||||
// and the filer would free the new entry's chunk. With the filer's chunk
|
||||
// condition the write is refused, since a re-created object has a new chunk.
|
||||
func TestAStaleMetadataChangeDoesNotOverwriteARecreatedObject(t *testing.T) {
|
||||
o := newRecreatedObject(t, true)
|
||||
err := o.stale.Reuse(context.Background(), o.rel, o.meta, "writer-1")
|
||||
o.checkRecreated(t)
|
||||
if !errors.Is(err, layout.ErrPrecondition) {
|
||||
t.Fatalf("the stale update over a re-created object answered %v, want ErrPrecondition", err)
|
||||
}
|
||||
if got, _ := o.fid(); got != o.second {
|
||||
t.Fatalf("the stale update wrote chunk %s over the re-created object's %s", got, o.second)
|
||||
}
|
||||
}
|
||||
|
||||
// With the guard on, a metadata change of an object nobody touched since its
|
||||
// lookup still lands: adoption retags it, and a cleaner marks and deletes it.
|
||||
func TestWithTheChunkGuardAnUnchangedObjectIsStillAdoptedMarkedAndDeleted(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
var id layout.VolumeID
|
||||
for i := range id {
|
||||
id[i] = 0x40 + byte(i)
|
||||
}
|
||||
st, err := NewLayoutStore(f, b, "/vol", id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st.SetChunkGuard(true)
|
||||
data := bytes.Repeat([]byte{0x3c}, 4096)
|
||||
rel := layout.NameChunk(1, data).Path()
|
||||
if err := st.Create(ctx, rel, data, "producer-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
meta, _, err := st.Stat(ctx, rel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.Reuse(ctx, rel, meta, "writer-1"); err != nil {
|
||||
t.Fatalf("guarded adoption of an unchanged object: %v", err)
|
||||
}
|
||||
if meta, _, err = st.Stat(ctx, rel); err != nil || meta.Session != "writer-1" {
|
||||
t.Fatalf("after adoption: %+v %v", meta, err)
|
||||
}
|
||||
if err := st.Mark(ctx, rel, meta, "clean-1"); err != nil {
|
||||
t.Fatalf("guarded mark of an unchanged object: %v", err)
|
||||
}
|
||||
if err := st.DeleteMarked(ctx, rel, "clean-1"); err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if _, found, err := st.Stat(ctx, rel); err != nil || found {
|
||||
t.Fatalf("the marked object was not deleted: found %v %v", found, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A cleaner that looked up an object to mark it, then paused, must not
|
||||
// delete the object created again in between: its mark is refused, so its
|
||||
// delete (which expects that mark) is refused too.
|
||||
func TestAStaleCleanerMarkDoesNotDeleteARecreatedObject(t *testing.T) {
|
||||
o := newRecreatedObject(t, true)
|
||||
ctx := context.Background()
|
||||
markErr := o.stale.Mark(ctx, o.rel, o.meta, "clean-2")
|
||||
o.checkRecreated(t)
|
||||
if !errors.Is(markErr, layout.ErrPrecondition) {
|
||||
t.Fatalf("the stale mark over a re-created object answered %v, want ErrPrecondition", markErr)
|
||||
}
|
||||
if err := o.stale.DeleteMarked(ctx, o.rel, "clean-2"); !errors.Is(err, layout.ErrPrecondition) {
|
||||
t.Fatalf("deleting under the refused mark answered %v, want ErrPrecondition", err)
|
||||
}
|
||||
if got, found := o.fid(); !found || got != o.second {
|
||||
t.Fatalf("the re-created object is gone or changed: chunk %q found %v, want %s", got, found, o.second)
|
||||
}
|
||||
}
|
||||
|
||||
// Without the chunk condition (a filer that does not enforce it) both stale
|
||||
// writes land: the store behavior the delete intent page re-read exists for,
|
||||
// kept visible here.
|
||||
func TestWithoutTheChunkGuardAStaleMetadataChangeOverwritesARecreatedObject(t *testing.T) {
|
||||
t.Run("adoption", func(t *testing.T) {
|
||||
o := newRecreatedObject(t, false)
|
||||
err := o.stale.Reuse(context.Background(), o.rel, o.meta, "writer-1")
|
||||
o.checkRecreated(t)
|
||||
if err != nil {
|
||||
t.Fatalf("the unguarded stale update was refused (%v)", err)
|
||||
}
|
||||
if got, _ := o.fid(); got != o.first {
|
||||
t.Fatalf("the unguarded stale update left chunk %s, want the deleted object's %s", got, o.first)
|
||||
}
|
||||
})
|
||||
t.Run("cleaner", func(t *testing.T) {
|
||||
o := newRecreatedObject(t, false)
|
||||
ctx := context.Background()
|
||||
if err := o.stale.Mark(ctx, o.rel, o.meta, "clean-2"); err != nil {
|
||||
t.Fatalf("the unguarded stale mark was refused (%v)", err)
|
||||
}
|
||||
o.checkRecreated(t)
|
||||
if err := o.stale.DeleteMarked(ctx, o.rel, "clean-2"); err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if _, found := o.fid(); found {
|
||||
t.Fatal("the unguarded stale mark did not lead to the re-created object's deletion")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -36,9 +36,6 @@ type LayoutStore struct {
|
||||
b Blobs
|
||||
root string
|
||||
id layout.VolumeID
|
||||
// chunkGuard: the filer enforces IF_CHUNKS_EQUAL (the startup probe said
|
||||
// so), and metadata changes send the looked-up entry's chunk fids with it.
|
||||
chunkGuard bool
|
||||
}
|
||||
|
||||
func NewLayoutStore(f Filer, b Blobs, root string, id layout.VolumeID) (*LayoutStore, error) {
|
||||
@@ -365,38 +362,9 @@ func (s *LayoutStore) changeMeta(ctx context.Context, rel string, expect layout.
|
||||
e.Extended[layoutMark] = []byte(mark)
|
||||
// Preserve the original FileChunks: an UpdateEntry dropping them
|
||||
// would tell the filer to delete the object's immutable data.
|
||||
//
|
||||
// The update writes the whole looked-up entry back, chunks included, and
|
||||
// its tags alone do not tell this object from one deleted and created
|
||||
// again with the same tags since the lookup: written over that one, the
|
||||
// update would put the deleted object's chunks on it and the filer would
|
||||
// free the new chunks. A re-created object always has new chunks, so the
|
||||
// filer's chunk condition refuses that write. Without it (a filer that
|
||||
// does not enforce the condition), delete intent publication re-reads
|
||||
// each adopted page instead (layout.RunDeleteSnapshotWithIntent).
|
||||
if cf, ok := s.chunkCondition(); ok {
|
||||
return layoutError(cf.UpdateEntryIfChunks(ctx, dir, e, objectExpected(expect), entryFids(e)))
|
||||
}
|
||||
return layoutError(s.f.UpdateEntry(ctx, dir, e, objectExpected(expect)))
|
||||
}
|
||||
|
||||
// SetChunkGuard turns the filer chunk condition on or off for this store's
|
||||
// metadata changes; BCatalog sets it from its startup probe.
|
||||
func (s *LayoutStore) SetChunkGuard(on bool) { s.chunkGuard = on }
|
||||
|
||||
// ChunkGuard reports whether metadata changes send the chunk condition.
|
||||
func (s *LayoutStore) ChunkGuard() bool {
|
||||
_, ok := s.chunkCondition()
|
||||
return ok
|
||||
}
|
||||
|
||||
// chunkCondition is the filer metadata changes send the chunk condition
|
||||
// through: the guard is on and the filer can carry it.
|
||||
func (s *LayoutStore) chunkCondition() (ChunkConditionFiler, bool) {
|
||||
cf, ok := s.f.(ChunkConditionFiler)
|
||||
return cf, ok && s.chunkGuard
|
||||
}
|
||||
|
||||
func (s *LayoutStore) Reuse(ctx context.Context, rel string, expect layout.ObjectMeta, session string) error {
|
||||
if session == "" {
|
||||
return errors.New("chunkstore: reuse needs a session")
|
||||
|
||||
@@ -63,23 +63,6 @@ func (m *MemFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry,
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateEntryIfChunks is UpdateEntry that also requires the stored chunk
|
||||
// fids to equal fids as a multiset, as the filer's IF_CHUNKS_EQUAL does.
|
||||
func (m *MemFiler) UpdateEntryIfChunks(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
p := path.Join(dir, e.GetName())
|
||||
cur, ok := m.e[p]
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
if !extendedMatch(cur, expected) || !fidsEqual(entryFids(cur), fids) {
|
||||
return ErrPrecondition
|
||||
}
|
||||
m.e[p] = proto.Clone(e).(*filerpb.Entry)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemFiler) ListEntries(_ context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
@@ -35,49 +35,6 @@ type Filer interface {
|
||||
DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error
|
||||
}
|
||||
|
||||
// ChunkConditionFiler is a Filer that can also send the filer's
|
||||
// IF_CHUNKS_EQUAL write condition: UpdateEntryIfChunks applies e only if every
|
||||
// expected extended key still holds its value AND the stored entry's chunk
|
||||
// fids still equal fids as a multiset; otherwise ErrPrecondition. A filer
|
||||
// that predates the condition drops it and applies the write unguarded, which
|
||||
// only a probe can tell (BCatalog.checkConditionalHead); a wrapper that does
|
||||
// not forward this method is treated the same way.
|
||||
type ChunkConditionFiler interface {
|
||||
UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error
|
||||
}
|
||||
|
||||
// chunksEqual is the filer write condition that the stored chunk fids equal
|
||||
// fids as a multiset (no fids: the entry has no chunks).
|
||||
func chunksEqual(fids []string) *filerpb.WriteCondition {
|
||||
return &filerpb.WriteCondition{Clauses: []*filerpb.WriteCondition_Clause{{Kind: filerpb.WriteCondition_IF_CHUNKS_EQUAL, Fids: fids}}}
|
||||
}
|
||||
|
||||
// entryFids is the multiset of e's chunk fids, in its order.
|
||||
func entryFids(e *filerpb.Entry) []string {
|
||||
fids := make([]string, 0, len(e.GetChunks()))
|
||||
for _, c := range e.GetChunks() {
|
||||
fids = append(fids, c.GetFileId())
|
||||
}
|
||||
return fids
|
||||
}
|
||||
|
||||
// fidsEqual compares two fid lists as multisets, as the filer does.
|
||||
func fidsEqual(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
n := make(map[string]int, len(a))
|
||||
for _, f := range a {
|
||||
n[f]++
|
||||
}
|
||||
for _, f := range b {
|
||||
if n[f]--; n[f] < 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Blobs stores immutable chunk payloads as SeaweedFS needles.
|
||||
type Blobs interface {
|
||||
// Put stores data as a new needle and returns its fid. A fid is never
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// hidesChunkCondition is a Filer wrapper that does not forward
|
||||
// UpdateEntryIfChunks: to the probe it is a filer without the condition.
|
||||
type hidesChunkCondition struct{ Filer }
|
||||
|
||||
// chunkProbeFails answers every conditional update with err (the HEAD gate,
|
||||
// an unconditional update, is unaffected): no definite refusal.
|
||||
type chunkProbeFails struct {
|
||||
*fakeFiler
|
||||
err error
|
||||
}
|
||||
|
||||
func (f chunkProbeFails) UpdateEntryIfChunks(context.Context, string, *filerpb.Entry, map[string][]byte, []string) error {
|
||||
return f.err
|
||||
}
|
||||
|
||||
// The startup probe decides the metadata change guard from the filer's
|
||||
// answer alone: a filer that refuses a mismatched IF_CHUNKS_EQUAL update turns
|
||||
// the guard on for every store the catalog opens; a filer that drops the
|
||||
// condition (or a client that cannot send it) leaves the page re-read as the
|
||||
// only check. No version string is read.
|
||||
func TestTheStartupProbeTurnsTheChunkGuardOnOnlyForAFilerThatEnforcesIt(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
filer func() Filer
|
||||
guard string
|
||||
storeG bool
|
||||
}{
|
||||
{"a filer that enforces the condition", func() Filer { return newFakeFiler() }, MetadataGuardChunks, true},
|
||||
{"a filer that drops the condition", func() Filer { f := newFakeFiler(); f.ignoreChunkCondition = true; return f }, MetadataGuardReread, false},
|
||||
{"a client wrapper that cannot send it", func() Filer { return hidesChunkCondition{newFakeFiler()} }, MetadataGuardReread, false},
|
||||
// Enforcement not established: the probe got no definite refusal.
|
||||
{"a probe that times out", func() Filer { return chunkProbeFails{newFakeFiler(), context.DeadlineExceeded} }, MetadataGuardReread, false},
|
||||
{"a probe whose answer is lost", func() Filer { return chunkProbeFails{newFakeFiler(), errors.New("transport: lost answer")} }, MetadataGuardReread, false},
|
||||
{"a probe whose entry vanished", func() Filer { return chunkProbeFails{newFakeFiler(), ErrNotFound} }, MetadataGuardReread, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cat, err := NewBCatalog(tc.filer(), newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cat.checkConditionalHead(context.Background()); err != nil {
|
||||
t.Fatalf("the conditional HEAD probe failed: %v", err)
|
||||
}
|
||||
if got := cat.MetadataGuard(); got != tc.guard {
|
||||
t.Fatalf("metadata guard %q, want %q", got, tc.guard)
|
||||
}
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := VolumeRef{Name: "v1", ID: id}
|
||||
st, err := cat.Store(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.ChunkGuard() != tc.storeG {
|
||||
t.Fatalf("a store opened by the catalog has chunk guard %v, want %v", st.ChunkGuard(), tc.storeG)
|
||||
}
|
||||
// /status/chunk answers the catalog's usage: it names the guard.
|
||||
ctx := context.Background()
|
||||
if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := cat.Usage(ctx, v); err != nil || u.MetadataGuard != tc.guard {
|
||||
t.Fatalf("usage names guard %q (%v), want %q", u.MetadataGuard, err, tc.guard)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -152,48 +152,5 @@ func (c *BCatalog) checkConditionalHead(ctx context.Context) error {
|
||||
if err != nil || !bytes.Equal(before, after) {
|
||||
return fmt.Errorf("%w: wrong-generation update changed %s", ErrConditionalHead, root)
|
||||
}
|
||||
c.chunkGuard = probeChunkCondition(ctx, c.f, root)
|
||||
log.Printf("chunkstore: metadata change guard: %s", c.MetadataGuard())
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProbeChunkGuard runs the startup probe for a catalog NewBCatalog opened
|
||||
// (the sw-block commands that change metadata), so the stores it opens next
|
||||
// send the chunk condition as DialBCatalog's do; a store takes the guard when
|
||||
// it is opened. A failed probe leaves the guard off; it refuses nothing.
|
||||
func (c *BCatalog) ProbeChunkGuard(ctx context.Context) {
|
||||
c.chunkGuard = false
|
||||
if _, ok := c.f.(ChunkConditionFiler); !ok {
|
||||
return
|
||||
}
|
||||
if err := c.checkConditionalHead(ctx); err != nil {
|
||||
log.Printf("chunkstore: WARNING %v; metadata change guard: %s", err, c.MetadataGuard())
|
||||
}
|
||||
}
|
||||
|
||||
// probeChunkCondition asks the filer to rewrite the disposable probe HEAD
|
||||
// only if it holds a chunk it does not have. A filer that enforces
|
||||
// IF_CHUNKS_EQUAL refuses; one that predates it drops the unknown field and
|
||||
// applies the write (the same entry, in a directory nothing else reads).
|
||||
// Only a definite refusal turns the guard on; anything else leaves the
|
||||
// page re-read as the only check. No version string is consulted.
|
||||
func probeChunkCondition(ctx context.Context, f Filer, root string) bool {
|
||||
cf, ok := f.(ChunkConditionFiler)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
e, err := f.LookupEntry(ctx, root, layout.HeadName)
|
||||
if err != nil {
|
||||
log.Printf("chunkstore: WARNING chunk condition probe: read %s: %v", root, err)
|
||||
return false
|
||||
}
|
||||
absent := append(entryFids(e), "0,"+strings.TrimPrefix(path.Base(root), startupProbePrefix))
|
||||
err = cf.UpdateEntryIfChunks(ctx, root, e, nil, absent)
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
return true
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("chunkstore: WARNING chunk condition probe: update %s: %v", root, err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -23,13 +23,8 @@ type conditionalProbeServer struct {
|
||||
configFiler
|
||||
store *fakeFiler
|
||||
mode string
|
||||
updates int // updates without a write condition: the wrong-generation exchange
|
||||
// chunkProbes counts updates carrying a write condition: the chunk
|
||||
// condition probe. Only mode conditional-chunk-filer enforces it; the
|
||||
// other modes drop it, as a filer that predates it does.
|
||||
chunkProbes int
|
||||
headReadsAfterUpdate int
|
||||
creates []*filerpb.CreateEntryRequest
|
||||
updates int
|
||||
creates []*filerpb.CreateEntryRequest
|
||||
}
|
||||
|
||||
func (f *conditionalProbeServer) CreateEntry(ctx context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) {
|
||||
@@ -43,42 +38,9 @@ func (f *conditionalProbeServer) CreateEntry(ctx context.Context, r *filerpb.Cre
|
||||
}
|
||||
func (f *conditionalProbeServer) UpdateEntry(ctx context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
if r.GetCondition() != nil {
|
||||
f.chunkProbes++
|
||||
} else {
|
||||
f.updates++
|
||||
}
|
||||
f.updates++
|
||||
mode := f.mode
|
||||
f.mu.Unlock()
|
||||
if r.GetCondition() != nil {
|
||||
// The HEAD gate passed; only the chunk condition probe fails here.
|
||||
switch mode {
|
||||
case "chunk-probe-unavailable":
|
||||
return nil, status.Error(codes.Unavailable, "lost answer")
|
||||
case "chunk-probe-deadline":
|
||||
return nil, status.Error(codes.DeadlineExceeded, "no answer in time")
|
||||
case "chunk-probe-internal":
|
||||
return nil, status.Error(codes.Internal, "filer error")
|
||||
case "chunk-probe-not-found":
|
||||
return nil, status.Error(codes.NotFound, "update target absent")
|
||||
}
|
||||
}
|
||||
if mode == "conditional-chunk-filer" && r.GetCondition() != nil {
|
||||
var fids []string
|
||||
for _, c := range r.GetCondition().GetClauses() {
|
||||
if c.GetKind() != filerpb.WriteCondition_IF_CHUNKS_EQUAL {
|
||||
return nil, status.Error(codes.InvalidArgument, "unexpected clause")
|
||||
}
|
||||
fids = append(fids, c.GetFids()...)
|
||||
}
|
||||
if err := f.store.UpdateEntryIfChunks(ctx, r.Directory, r.Entry, r.ExpectedExtended, fids); err != nil {
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
return nil, status.Error(codes.FailedPrecondition, err.Error())
|
||||
}
|
||||
return nil, status.Error(codes.Internal, err.Error())
|
||||
}
|
||||
return &filerpb.UpdateEntryResponse{}, nil
|
||||
}
|
||||
if mode == "not-found" {
|
||||
return nil, status.Error(codes.NotFound, "update target absent")
|
||||
}
|
||||
@@ -102,17 +64,6 @@ func (f *conditionalProbeServer) UpdateEntry(ctx context.Context, r *filerpb.Upd
|
||||
return &filerpb.UpdateEntryResponse{}, nil
|
||||
}
|
||||
func (f *conditionalProbeServer) LookupDirectoryEntry(ctx context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
if r.Name == layout.HeadName && f.updates > 0 {
|
||||
f.headReadsAfterUpdate++
|
||||
}
|
||||
failProbeRead := f.mode == "chunk-probe-lookup-error" && f.headReadsAfterUpdate == 2
|
||||
f.mu.Unlock()
|
||||
// After the wrong-generation exchange the gate confirms HEAD (first read);
|
||||
// the second read is the chunk condition probe's.
|
||||
if failProbeRead {
|
||||
return nil, status.Error(codes.Unavailable, "lookup lost")
|
||||
}
|
||||
e, err := f.store.LookupEntry(ctx, r.Directory, r.Name)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.NotFound, err.Error())
|
||||
@@ -144,9 +95,7 @@ func (f *conditionalProbeServer) DeleteEntry(ctx context.Context, r *filerpb.Del
|
||||
return &filerpb.DeleteEntryResponse{}, nil
|
||||
}
|
||||
func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
|
||||
for _, mode := range []string{"ignores-conditions", "mutates-then-refuses", "transport-error", "not-found", "conditional-filer", "conditional-chunk-filer", "cleanup-head-error", "cleanup-dir-error",
|
||||
// The HEAD gate passes; the chunk condition probe gets no definite refusal.
|
||||
"chunk-probe-unavailable", "chunk-probe-deadline", "chunk-probe-internal", "chunk-probe-not-found", "chunk-probe-lookup-error"} {
|
||||
for _, mode := range []string{"ignores-conditions", "mutates-then-refuses", "transport-error", "not-found", "conditional-filer", "cleanup-head-error", "cleanup-dir-error"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previous := log.Writer()
|
||||
@@ -171,8 +120,7 @@ func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
|
||||
if client != nil {
|
||||
defer client.Close()
|
||||
}
|
||||
admitted := mode == "conditional-filer" || mode == "conditional-chunk-filer" || strings.HasPrefix(mode, "cleanup-") || strings.HasPrefix(mode, "chunk-probe-")
|
||||
if !admitted {
|
||||
if mode != "conditional-filer" && !strings.HasPrefix(mode, "cleanup-") {
|
||||
if !errors.Is(err, ErrConditionalHead) || cat != nil || !strings.Contains(err.Error(), "conditional HEAD") {
|
||||
t.Fatalf("broken conditional startup: cat=%v err=%v", cat, err)
|
||||
}
|
||||
@@ -183,36 +131,9 @@ func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
|
||||
t.Fatalf("cleanup warning missing: %s", logs.String())
|
||||
}
|
||||
f.mu.Lock()
|
||||
updates, chunkProbes := f.updates, f.chunkProbes
|
||||
updates := f.updates
|
||||
creates := append([]*filerpb.CreateEntryRequest(nil), f.creates...)
|
||||
f.mu.Unlock()
|
||||
// An admitted startup sends one chunk condition probe, over the
|
||||
// real client, and keeps the guard on only if the filer refused it.
|
||||
wantProbes, wantGuard := 0, ""
|
||||
if admitted {
|
||||
wantProbes, wantGuard = 1, MetadataGuardReread
|
||||
if mode == "chunk-probe-lookup-error" {
|
||||
wantProbes = 0 // the probe could not read HEAD, so it sent nothing
|
||||
}
|
||||
if mode == "conditional-chunk-filer" {
|
||||
wantGuard = MetadataGuardChunks
|
||||
}
|
||||
}
|
||||
if chunkProbes != wantProbes {
|
||||
t.Fatalf("chunk condition probes=%d want %d", chunkProbes, wantProbes)
|
||||
}
|
||||
if admitted && cat.MetadataGuard() != wantGuard {
|
||||
t.Fatalf("metadata guard %q want %q", cat.MetadataGuard(), wantGuard)
|
||||
}
|
||||
if admitted && !strings.Contains(logs.String(), "metadata change guard: "+wantGuard) {
|
||||
t.Fatalf("the startup log does not name the guard %q: %s", wantGuard, logs.String())
|
||||
}
|
||||
if admitted {
|
||||
st, err := cat.Store(VolumeRef{Name: "v1", ID: layout.VolumeID{1}})
|
||||
if err != nil || st.ChunkGuard() != (wantGuard == MetadataGuardChunks) {
|
||||
t.Fatalf("a store the catalog opens has chunk guard %v (%v), want %v", st.ChunkGuard(), err, wantGuard == MetadataGuardChunks)
|
||||
}
|
||||
}
|
||||
// This mint is a disposable HEAD label, not an alternate volume
|
||||
// creator. No VOLUME, lifecycle identity or real volume root is used.
|
||||
if len(creates) != 1 {
|
||||
|
||||
@@ -160,19 +160,8 @@ func (c *SWFS) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oE
|
||||
// FailedPrecondition. Any other error is ambiguous (the write may or may not
|
||||
// have applied) and is returned unwrapped from the sentinels.
|
||||
func (c *SWFS) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
return c.updateEntry(ctx, dir, e, expected, nil)
|
||||
}
|
||||
|
||||
// UpdateEntryIfChunks implements ChunkConditionFiler: UpdateEntry that also
|
||||
// sends the filer's IF_CHUNKS_EQUAL condition with fids. A failed condition
|
||||
// comes back as gRPC FailedPrecondition, like a failed expected_extended.
|
||||
func (c *SWFS) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
|
||||
return c.updateEntry(ctx, dir, e, expected, chunksEqual(fids))
|
||||
}
|
||||
|
||||
func (c *SWFS) updateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, cond *filerpb.WriteCondition) error {
|
||||
return maintenanceError(ctx, func(ctx context.Context) error {
|
||||
_, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected, Condition: cond})
|
||||
_, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
const finalizeSetupCheckpoint = "FINALIZE_SETUP_COMPLETE"
|
||||
const finalizeFaultCheckpoint = "FINALIZE_POST_RENAME_FAULT"
|
||||
const finalizeLogCheckpoint = "FINALIZE_LOG_ENTERED"
|
||||
const finalizeWindowCheckpoint = "FINALIZE_INTENT_AND_GRANTS_CHECKED"
|
||||
|
||||
type blockedFinalizeLog struct{ check func() }
|
||||
|
||||
func (w blockedFinalizeLog) Write([]byte) (int, error) {
|
||||
fmt.Fprintln(os.Stderr, finalizeLogCheckpoint)
|
||||
w.check()
|
||||
fmt.Fprintln(os.Stderr, finalizeWindowCheckpoint)
|
||||
select {}
|
||||
}
|
||||
|
||||
func qualifiedFinalizeFailure(out []byte, err, contextErr error, sink string) bool {
|
||||
var exit *exec.ExitError
|
||||
if contextErr != nil || !errors.As(err, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
|
||||
return false
|
||||
}
|
||||
for _, marker := range []string{finalizeSetupCheckpoint, finalizeFaultCheckpoint} {
|
||||
if strings.Count(string(out), marker) != 1 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if sink == "blocked" {
|
||||
return strings.Count(string(out), finalizeLogCheckpoint) == 1 && strings.Count(string(out), finalizeWindowCheckpoint) == 1
|
||||
}
|
||||
return strings.Contains(string(out), "ERROR") && strings.Contains(string(out), "supervisor restarts")
|
||||
}
|
||||
|
||||
func TestFormatFinalizeUncertainWriteFailStops(t *testing.T) {
|
||||
for _, sink := range []string{"normal", "blocked", "setup-failure", "setup-durability-failure"} {
|
||||
t.Run(sink, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFormatFinalizeUncertainWriteChild$", "-test.count=1")
|
||||
cmd.Env = append(os.Environ(), "FINALIZE_FAILURE_CHILD="+sink)
|
||||
out, err := cmd.CombinedOutput()
|
||||
qualified := qualifiedFinalizeFailure(out, err, ctx.Err(), sink)
|
||||
if sink == "setup-failure" || sink == "setup-durability-failure" {
|
||||
expected := 1
|
||||
if sink == "setup-durability-failure" {
|
||||
expected = authority.ExitDurabilityUnknown
|
||||
}
|
||||
var exit *exec.ExitError
|
||||
if qualified || ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != expected || !strings.Contains(string(out), "injected setup") {
|
||||
t.Fatalf("setup failure was not distinguished: %v ctx=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !qualified {
|
||||
t.Fatalf("fault/checkpoints did not qualify exit %d: %v ctx=%v\n%s", authority.ExitDurabilityUnknown, err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func finalizeFailureRig(t *testing.T) *isolationRig {
|
||||
t.Helper()
|
||||
dir := upgradedStoreDir(t)
|
||||
disk, err := authority.NewFileAuthorityStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1]}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := newIsolationRig(t, false, dir, t.TempDir())
|
||||
r.createVolume(t, "v")
|
||||
r.place(t, "v", "node-b")
|
||||
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestFormatFinalizeUncertainWriteChild(t *testing.T) {
|
||||
sink := os.Getenv("FINALIZE_FAILURE_CHILD")
|
||||
if sink == "" {
|
||||
t.Skip("bounded fault child")
|
||||
}
|
||||
if sink == "setup-durability-failure" {
|
||||
fmt.Fprintln(os.Stderr, "ERROR injected setup durability failure; supervisor restarts")
|
||||
os.Exit(authority.ExitDurabilityUnknown)
|
||||
}
|
||||
if sink == "setup-failure" {
|
||||
t.Fatal("injected setup failure before checkpoints")
|
||||
}
|
||||
r := finalizeFailureRig(t)
|
||||
fmt.Fprintln(os.Stderr, finalizeSetupCheckpoint)
|
||||
r.m.log = log.New(os.Stderr, "", 0)
|
||||
if sink == "blocked" {
|
||||
r.m.log = log.New(blockedFinalizeLog{check: func() {
|
||||
if !r.m.formatFinalizing.Load() || r.m.Publisher().FormatLevel() != 0 {
|
||||
t.Fatal("host intent lost or level raised before recovery")
|
||||
}
|
||||
// At level 0, refusal without a report observes the publisher's intent.
|
||||
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1); err == nil {
|
||||
t.Fatal("publisher intent reopened an unreported serving deadline")
|
||||
}
|
||||
proof := r.m.formatReadProof("v", "r1", "node-b", 1)
|
||||
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1, proof); err != nil {
|
||||
t.Fatalf("capable live renewal blanket-refused while logging blocked: %v", err)
|
||||
}
|
||||
}}, "", 0)
|
||||
}
|
||||
syncAttestationDir = func(string) error {
|
||||
onDisk, err := loadStoreAttestations(r.m.cfg.AuthorityStoreDir)
|
||||
if err != nil || onDisk.level() != 1 {
|
||||
t.Fatalf("fault did not follow the level-1 rename: %v", err)
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, finalizeFaultCheckpoint)
|
||||
return errors.New("injected post-rename directory barrier failure")
|
||||
}
|
||||
_, _, _ = r.m.FinalizeFormat(1)
|
||||
os.Exit(42)
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
func formatReviewLineRig(t *testing.T) *isolationRig {
|
||||
t.Helper()
|
||||
dir := upgradedStoreDir(t)
|
||||
disk, err := authority.NewFileAuthorityStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1,
|
||||
EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0],
|
||||
CtrlAddr: hbPorts["node-b"][1], Incarnation: "old-v"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := newIsolationRig(t, false, dir, t.TempDir())
|
||||
r.createVolume(t, "v")
|
||||
r.place(t, "v", "node-b")
|
||||
r.createVolume(t, "sibling")
|
||||
r.place(t, "sibling", "node-b")
|
||||
r.m.Publisher().FinalizeFormatLevel()
|
||||
r.m.format.v.Store(1)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestFormatRefreshUsesItsOwnReportDespiteAnOldSibling(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
r := formatReviewLineRig(t)
|
||||
if err := r.fgProcessHeartbeat("node-b", "old-sibling", "sibling", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "new-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line, ok := r.m.Publisher().VolumeAuthorityLine("v")
|
||||
if !ok {
|
||||
t.Fatal("missing existing line")
|
||||
}
|
||||
ask := authority.AssignmentAsk{VolumeID: "v", ReplicaID: line.ReplicaID,
|
||||
DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr, Intent: authority.IntentRefreshEndpoint,
|
||||
Incarnation: "new-v", ExpectCurrent: &authority.ExpectedLine{ReplicaID: line.ReplicaID,
|
||||
Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}}
|
||||
called := false
|
||||
if err := r.m.admitWorkspacePublicationNow(ask, func() error { called = true; return nil }); err != nil || !called {
|
||||
t.Fatalf("capable existing-holder refresh blocked by sibling: called=%v err=%v", called, err)
|
||||
}
|
||||
// A new placement still faces the server-wide known-old gate.
|
||||
ask.Intent, ask.ExpectCurrent = authority.IntentBind, nil
|
||||
if err := r.m.admitWorkspacePublicationNow(ask, func() error { t.Error("new placement admitted"); return nil }); err == nil {
|
||||
t.Fatal("new placement ignored the old sibling")
|
||||
}
|
||||
ask.Intent = authority.IntentRefreshEndpoint
|
||||
ask.ExpectCurrent = &authority.ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch,
|
||||
DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}
|
||||
if err := r.fgProcessHeartbeat("node-b", "old-v-replacement", "v", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.m.admitWorkspacePublicationNow(ask, func() error { t.Error("old refresh admitted"); return nil }); err == nil {
|
||||
t.Fatal("refresh ignored its own old report")
|
||||
}
|
||||
}
|
||||
|
||||
// A heal of the current holder and a failover to a replica's committed
|
||||
// holder give no new placement to their server: an old sibling process there
|
||||
// does not refuse them; the volume's own old process does.
|
||||
func TestFormatReassignUsesItsOwnReportDespiteAnOldSibling(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
r := formatReviewLineRig(t)
|
||||
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v", DesiredRF: 2, Candidates: []lifecycle.PlacementCandidate{
|
||||
{VolumeID: "v", ServerID: "node-b", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica},
|
||||
{VolumeID: "v", ServerID: "node-c", ReplicaID: "r2", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, ask := range map[string]authority.AssignmentAsk{
|
||||
"heal": {VolumeID: "v", ReplicaID: "r1", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Intent: authority.IntentReassign},
|
||||
"failover": {VolumeID: "v", ReplicaID: "r2", DataAddr: hbPorts["node-c"][0], CtrlAddr: hbPorts["node-c"][1], Intent: authority.IntentReassign},
|
||||
} {
|
||||
server := map[string]string{"r1": "node-b", "r2": "node-c"}[ask.ReplicaID]
|
||||
if err := r.fgProcessHeartbeat(server, "old-sibling", "sibling", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat(server, "new-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.m.admitWorkspacePublicationNow(ask, func() error { return nil }); err != nil {
|
||||
t.Fatalf("%s of a capable holder refused by its old sibling: %v", name, err)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat(server, "old-v", "v", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.m.admitWorkspacePublicationNow(ask, func() error { t.Errorf("%s by an old process admitted", name); return nil }); err == nil {
|
||||
t.Fatalf("%s ignored its own old report", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatPlacedLineKeepsItsReportWait(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
r := formatReviewLineRig(t)
|
||||
if err := r.fgProcessHeartbeat("node-b", "reported-sibling", "sibling", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
waits := r.m.grantWaits(start)["node-b"]
|
||||
if len(waits) != 1 || waits[0].volume != "v" {
|
||||
t.Fatalf("placed unreported holder disappeared from waits: %+v", waits)
|
||||
}
|
||||
late := r.m.grantWaits(start.Add(r.m.grantStartupWindow() + time.Second))["node-b"]
|
||||
if len(late) != 1 || late[0].volume != "v" || !late[0].late {
|
||||
t.Fatalf("placed holder has no overdue warning: %+v", late)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "reported-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if waits := r.m.grantWaits(start)["node-b"]; len(waits) != 0 {
|
||||
t.Fatalf("reported holder still waits: %+v", waits)
|
||||
}
|
||||
}
|
||||
|
||||
//go:noinline
|
||||
func queuedReviewFinalize(h *Host, result chan<- error) {
|
||||
_, _, err := h.FinalizeFormat(1)
|
||||
result <- err
|
||||
}
|
||||
|
||||
func TestQueuedFinalizeDoesNotHoldWorkspaceAdmission(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
|
||||
r.m.finalizeMu.Lock() // the serializer the active durable finalize holds
|
||||
release := sync.OnceFunc(r.m.finalizeMu.Unlock)
|
||||
t.Cleanup(release)
|
||||
done := make(chan error, 1)
|
||||
go queuedReviewFinalize(r.m, done)
|
||||
for {
|
||||
stacks := make([]byte, 1<<20)
|
||||
n := runtime.Stack(stacks, true)
|
||||
waiting := false
|
||||
for _, stack := range strings.Split(string(stacks[:n]), "\n\n") {
|
||||
if strings.Contains(stack, "queuedReviewFinalize") && strings.Contains(stack, "sync.(*Mutex).lockSlow") {
|
||||
waiting = true
|
||||
}
|
||||
}
|
||||
if waiting {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("second finalize never waited on serialization")
|
||||
default:
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
admitted := make(chan struct{})
|
||||
go func() { r.m.workspaceMu.Lock(); r.m.workspaceMu.Unlock(); close(admitted) }()
|
||||
select {
|
||||
case <-admitted:
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("queued finalize holds workspace admission behind the durable write")
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("queued finalize did not finish")
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
)
|
||||
|
||||
// A held persistence callback and all Host teardown stay in a bounded child.
|
||||
func finalizeServingChild(t *testing.T) bool {
|
||||
t.Helper()
|
||||
if os.Getenv("FINALIZE_SERVING_CHILD") == t.Name() {
|
||||
return true
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1")
|
||||
cmd.Env = append(os.Environ(), "FINALIZE_SERVING_CHILD="+t.Name())
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("bounded finalize child: %v\n%s", err, out)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestFinalizeRequiresTheGrantedHoldersReadReport(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
reported bool
|
||||
level uint32
|
||||
}{
|
||||
{"never-reported", false, 0}, {"stale-old", true, 0}, {"stale-capable", true, 1},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := upgradedStoreDir(t)
|
||||
disk, err := authority.NewFileAuthorityStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := newIsolationRig(t, false, dir, t.TempDir())
|
||||
r.createVolume(t, "v")
|
||||
r.place(t, "v", "node-b")
|
||||
var now atomic.Int64
|
||||
now.Store(time.Now().UnixNano())
|
||||
r.m.reads.now = func() time.Time { return time.Unix(0, now.Load()) }
|
||||
if tc.reported {
|
||||
if err := r.fgProcessHeartbeat("node-b", "holder-v", "v", tc.level); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// This is an actual level-0 grant, not just an unserved placement.
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now.Add(int64(time.Hour)) // old report remains tied to the serving volume
|
||||
response, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
|
||||
if tc.level == 1 {
|
||||
if err != nil || response.GetFormatLevel() != 1 {
|
||||
t.Fatalf("reported capable holder: %v %v", response, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(err.Error(), "node-b") || !strings.Contains(err.Error(), "volume v") {
|
||||
t.Fatalf("serving holder without a level-1 report: response=%v error=%v, want typed refusal naming node-b / volume v", response, err)
|
||||
}
|
||||
if r.m.formatLevel() != 0 {
|
||||
t.Fatal("refused finalize changed the level")
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "holder-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err != nil || response.GetFormatLevel() != 1 {
|
||||
t.Fatalf("capable holder cannot finalize: %v %v", response, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeSerializesTheLevelZeroPublicationBoundary(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
dir := upgradedStoreDir(t)
|
||||
disk, err := authority.NewFileAuthorityStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1]}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := newIsolationRig(t, false, dir, t.TempDir())
|
||||
r.createVolume(t, "v")
|
||||
r.place(t, "v", "node-b")
|
||||
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.createVolume(t, "fresh")
|
||||
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
releaseOnce := sync.OnceFunc(func() { close(release) })
|
||||
previous := syncAttestationDir
|
||||
syncAttestationDir = func(dir string) error { close(entered); <-release; return previous(dir) }
|
||||
t.Cleanup(func() { syncAttestationDir = previous })
|
||||
t.Cleanup(releaseOnce)
|
||||
finalized := make(chan error, 1)
|
||||
go func() { _, _, err := r.m.FinalizeFormat(1); finalized <- err }()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("finalize never reached its directory barrier")
|
||||
}
|
||||
// A valid renewal must complete while the actual durable raise is held.
|
||||
renewCtx, cancelRenew := context.WithTimeout(r.ctx, time.Second)
|
||||
_, renewErr := r.ws.RenewWorkspaceLease(renewCtx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"})
|
||||
cancelRenew()
|
||||
if renewErr != nil {
|
||||
t.Fatalf("renewal blocked by durable finalize: %v", renewErr)
|
||||
}
|
||||
// The holder restarts on a level-0 binary after the finalize check.
|
||||
if err := r.fgProcessHeartbeat("node-b", "old-v", "v", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err == nil {
|
||||
t.Fatal("replacement old process renewed the still-live lease during finalize")
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
|
||||
t.Fatalf("capable process could not resume memory-only renewal during finalize: %v", err)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "old-v", "v", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"}); reasonOf(err) != lifecycleclient.ReasonBinaryTooOld {
|
||||
t.Fatalf("known-old placement bypassed finalize intent: %v", err)
|
||||
}
|
||||
preview, err := r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "during-finalize", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
|
||||
if err != nil || preview.GetAdmitted() || preview.GetReasonCode() != lifecycleclient.ReasonBinaryTooOld {
|
||||
t.Fatalf("old guarded move bypassed finalize intent: %v %v", preview, err)
|
||||
}
|
||||
granted := make(chan error, 1)
|
||||
var published atomic.Bool
|
||||
go func() {
|
||||
granted <- r.m.admitWorkspacePublication(authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r1", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Intent: authority.IntentBind}, func() error { published.Store(true); return nil })
|
||||
}()
|
||||
// The intent must reject the old publication before the held write ends.
|
||||
select {
|
||||
case err := <-granted:
|
||||
if err == nil || published.Load() || !strings.Contains(err.Error(), "binary_too_old") {
|
||||
t.Fatalf("level-0 publication crossed the finalize barrier: published=%v error=%v", published.Load(), err)
|
||||
}
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("publication waited for the durable write instead of checking the intent")
|
||||
}
|
||||
releaseOnce()
|
||||
select {
|
||||
case err := <-finalized:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("finalize did not finish")
|
||||
}
|
||||
// Completing the durable raise keeps the renewal proof gate. Unknown
|
||||
// move targets remain placeable and still face the ordinary lease barrier.
|
||||
r.m.reads.forget("node-b")
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err == nil {
|
||||
t.Fatal("unreported process renewed after finalize completed")
|
||||
}
|
||||
preview, err = r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "after-finalize", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
|
||||
if err != nil || !strings.Contains(preview.GetReason(), "lease expiry plus clock-skew") {
|
||||
t.Fatalf("unreported guarded move did not reach its existing lease barrier: %v %v", preview, err)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
preview, err = r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "after-finalize-capable", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
|
||||
if err != nil || preview.GetReasonCode() == lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(preview.GetReason(), "lease expiry plus clock-skew") {
|
||||
t.Fatalf("reported capable guarded move did not reach its existing lease barrier: %v %v", preview, err)
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,12 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
@@ -38,10 +36,9 @@ type readsLevels struct {
|
||||
}
|
||||
|
||||
type procLevel struct {
|
||||
level uint32
|
||||
process string
|
||||
seen time.Time
|
||||
revision *atomic.Uint64
|
||||
level uint32
|
||||
process string
|
||||
seen time.Time
|
||||
}
|
||||
|
||||
func newReadsLevels(window time.Duration) *readsLevels {
|
||||
@@ -55,26 +52,13 @@ func (r *readsLevels) note(server, volume, process string, level uint32) {
|
||||
if r.procs[server] == nil {
|
||||
r.procs[server] = map[string]procLevel{}
|
||||
}
|
||||
previous, known := r.procs[server][volume]
|
||||
revision := previous.revision
|
||||
if revision == nil {
|
||||
revision = &atomic.Uint64{}
|
||||
}
|
||||
if !known || previous.level != level || previous.process != process {
|
||||
revision.Add(1)
|
||||
}
|
||||
r.procs[server][volume] = procLevel{level: level, process: process, seen: r.now(), revision: revision}
|
||||
r.procs[server][volume] = procLevel{level: level, process: process, seen: r.now()}
|
||||
}
|
||||
|
||||
// forget drops every entry of server (a retired host).
|
||||
func (r *readsLevels) forget(server string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, e := range r.procs[server] {
|
||||
if e.revision != nil {
|
||||
e.revision.Add(1)
|
||||
}
|
||||
}
|
||||
delete(r.procs, server)
|
||||
}
|
||||
|
||||
@@ -85,9 +69,6 @@ func (r *readsLevels) liveLocked(server string, served map[string]bool) map[stri
|
||||
cutoff := r.now().Add(-r.window)
|
||||
for v, e := range r.procs[server] {
|
||||
if e.seen.Before(cutoff) && !served[v] {
|
||||
if e.revision != nil {
|
||||
e.revision.Add(1)
|
||||
}
|
||||
delete(r.procs[server], v)
|
||||
}
|
||||
}
|
||||
@@ -190,21 +171,12 @@ type formatLevelState struct{ v atomic.Uint32 }
|
||||
// finalizes the v1.1 format.
|
||||
func (h *Host) formatLevel() uint32 { return h.format.v.Load() }
|
||||
|
||||
// Admission follows the target level during the in-flight finalize; replies
|
||||
// and persisted data still use the durable format level until it commits.
|
||||
func (h *Host) admissionFormatLevel() uint32 {
|
||||
if h.formatFinalizing.Load() {
|
||||
return 1
|
||||
}
|
||||
return h.formatLevel()
|
||||
}
|
||||
|
||||
// formatEligible reports whether server may be GRANTED work (an authority
|
||||
// line published to it, and with it its lease) at the cluster's format
|
||||
// level: its own report says its binary reads that level; no report means
|
||||
// no grant (NoStrand holds at the grant). At level 0 every server is.
|
||||
func (h *Host) formatEligible(server string) bool {
|
||||
level := h.admissionFormatLevel()
|
||||
level := h.formatLevel()
|
||||
if level == 0 {
|
||||
return true
|
||||
}
|
||||
@@ -231,7 +203,7 @@ func (h *Host) grantStartupWindow() time.Duration {
|
||||
}
|
||||
|
||||
// grantWaitEntry is a placed volume whose holder process on a server has
|
||||
// not reported (no serving grant before its report), even if a line was placed.
|
||||
// not reported (no grant before its report) and that has no line yet.
|
||||
type grantWaitEntry struct {
|
||||
volume string
|
||||
waited time.Duration
|
||||
@@ -240,10 +212,9 @@ type grantWaitEntry struct {
|
||||
|
||||
// grantWaits computes, once per status snapshot, the complete set of
|
||||
// (server, volume) grant waits at a level above 0: every placed slot without
|
||||
// a report from its own process on its server. A placed line is not a serving grant;
|
||||
// it waits on the line's owner only (a move leaves the placement). The
|
||||
// an authority line whose own process on its server has not reported. The
|
||||
// first-seen times are reconciled against that one set: an entry that left
|
||||
// it (reported, moved, unplaced, removed) is dropped, a new one starts
|
||||
// it (granted, reported, unplaced, removed) is dropped, a new one starts
|
||||
// now. The key is server and volume, so waits on different servers never
|
||||
// reset each other.
|
||||
func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
|
||||
@@ -268,23 +239,17 @@ func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
|
||||
if h.formatLevel() > 0 {
|
||||
window := h.grantStartupWindow()
|
||||
for _, p := range placements {
|
||||
var servers []string
|
||||
if line, ok := h.Publisher().PublishedAuthorityLine(p.VolumeID); ok {
|
||||
// A move does not rewrite the placement: a line waits on its owner.
|
||||
servers = []string{h.workspaceLineOwner(line, p.VolumeID, line.ReplicaID, line.Epoch)}
|
||||
} else {
|
||||
for _, slot := range p.Slots {
|
||||
servers = append(servers, slot.ServerID)
|
||||
}
|
||||
if _, granted := h.Publisher().VolumeAuthorityLine(p.VolumeID); granted {
|
||||
continue
|
||||
}
|
||||
for _, server := range servers {
|
||||
if server == "" {
|
||||
for _, slot := range p.Slots {
|
||||
if slot.ServerID == "" {
|
||||
continue
|
||||
}
|
||||
if _, reported := h.reads.entry(server, p.VolumeID, h.servedBy(server)); reported {
|
||||
if _, reported := h.reads.entry(slot.ServerID, p.VolumeID, h.servedBy(slot.ServerID)); reported {
|
||||
continue
|
||||
}
|
||||
key := server + "\x00" + p.VolumeID
|
||||
key := slot.ServerID + "\x00" + p.VolumeID
|
||||
live[key] = true
|
||||
first, seen := h.grantWait[key]
|
||||
if !seen {
|
||||
@@ -295,7 +260,7 @@ func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
|
||||
if waited < 0 { // a caller's now taken before another snapshot started this wait
|
||||
waited = 0
|
||||
}
|
||||
out[server] = append(out[server], grantWaitEntry{volume: p.VolumeID, waited: waited, late: waited > window})
|
||||
out[slot.ServerID] = append(out[slot.ServerID], grantWaitEntry{volume: p.VolumeID, waited: waited, late: waited > window})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -314,9 +279,9 @@ func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry {
|
||||
// (create, move, restore target, a failover candidate), or "" when it may:
|
||||
// only a KNOWN-old report refuses. An unknown server is placeable,
|
||||
// since with one process per volume and create-then-start a placement target
|
||||
// cannot have reported yet; a serving deadline still needs its own report.
|
||||
// cannot have reported yet; the grant (formatTooOld) still needs its report.
|
||||
func (h *Host) placementTooOld(server string) string {
|
||||
level := h.admissionFormatLevel()
|
||||
level := h.formatLevel()
|
||||
if level == 0 {
|
||||
return ""
|
||||
}
|
||||
@@ -339,6 +304,26 @@ func (h *Host) formatRefusal(prefix, server string) error {
|
||||
return lifecycleclient.WithReason(status.New(codes.FailedPrecondition, prefix+why), lifecycleclient.ReasonBinaryTooOld).Err()
|
||||
}
|
||||
|
||||
// grantTooOld names why the process that will serve volume on server may not
|
||||
// be granted its line, or "" when it may: the grant reads that process's own
|
||||
// report (the (server, volume) entry), never a sibling process's, since
|
||||
// with one process per volume a sibling's report says nothing about this
|
||||
// one's binary. No report means no grant; a lower one is binary_too_old.
|
||||
func (h *Host) grantTooOld(server, volume string) string {
|
||||
level := h.formatLevel()
|
||||
if level == 0 {
|
||||
return ""
|
||||
}
|
||||
reads, ok := h.reads.entry(server, volume, h.servedBy(server))
|
||||
if !ok {
|
||||
return fmt.Sprintf("node %q has not reported the format read level of its process for volume %q; the cluster's format level is %d (no grant before that process's report)", server, volume, level)
|
||||
}
|
||||
if reads < level {
|
||||
return fmt.Sprintf("node %q's process for volume %q reads format level %d; the cluster's format level is %d (binary_too_old)", server, volume, reads, level)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// formatTooOld names why server is not format-eligible, or "" when it is.
|
||||
func (h *Host) formatTooOld(server string) string {
|
||||
if h.formatEligible(server) {
|
||||
@@ -447,7 +432,7 @@ func (e errFormatHostsTooOld) Error() string {
|
||||
for i, b := range e.hosts {
|
||||
named[i] = fmt.Sprintf("%s (%s)", b.server, b.detail)
|
||||
}
|
||||
return fmt.Sprintf("format finalize refused: processes holding volumes have not reported reading level 1: %s; have each current process report reading level 1, or move/release its volumes, then retry", strings.Join(named, ", "))
|
||||
return fmt.Sprintf("format finalize refused: processes holding volumes report a level below 1: %s; upgrade each one, or move its volumes (sw-block ops workspace move)", strings.Join(named, ", "))
|
||||
}
|
||||
|
||||
// metadata keys each refused host, and each host not confirmed, for the
|
||||
@@ -489,10 +474,9 @@ func (e errHostHoldsWork) metadata() map[string]string {
|
||||
}
|
||||
|
||||
// FinalizeFormat raises the cluster's format level to 1 (FormatGate:
|
||||
// Finalize; FormatGateMaster: the one durable step). The existing known-old
|
||||
// work check remains; a possibly-serving current lease also needs its own
|
||||
// level-1 report. An admission intent closes level-0 grants during the store
|
||||
// write without holding either publisher grant lock. Otherwise, in order: the
|
||||
// Finalize; FormatGateMaster: the one durable step). It is refused only while
|
||||
// a process that holds work reports a lower level (finalizeCheck); the hosts
|
||||
// it cannot confirm are answered, not blocking. Otherwise, in order: the
|
||||
// attestation envelope is written durably (the level, and the fence against
|
||||
// v1.0.x masters, in one write); the publisher switches to level 1 under its
|
||||
// locks; then the answer. At level 1 it writes nothing (already).
|
||||
@@ -500,72 +484,24 @@ func (h *Host) FinalizeFormat(level uint32) (already bool, unconfirmed []hostBel
|
||||
if level != 1 {
|
||||
return false, nil, fmt.Errorf("format finalize: level %d; the only level to finalize is 1", level)
|
||||
}
|
||||
// Match RetireHost's lock order. Wait for serialization without holding
|
||||
// workspaceMu, so another finalize cannot block publications over this I/O.
|
||||
// Release workspaceMu before the store
|
||||
// write; the intent then makes every serving deadline use the level-1 gate.
|
||||
h.finalizeMu.Lock()
|
||||
defer h.finalizeMu.Unlock()
|
||||
h.workspaceMu.Lock()
|
||||
if h.formatLevel() >= 1 {
|
||||
h.workspaceMu.Unlock()
|
||||
return true, nil, nil
|
||||
}
|
||||
blocking, unconfirmed := h.finalizeCheck(1)
|
||||
byServer := map[string][]string{}
|
||||
for _, b := range h.Publisher().BeginFormatFinalize(h.finalizeReadProofs(), len(blocking) == 0) {
|
||||
byServer[b.Server] = append(byServer[b.Server], b.Detail)
|
||||
}
|
||||
servers := make([]string, 0, len(byServer))
|
||||
for server := range byServer {
|
||||
servers = append(servers, server)
|
||||
}
|
||||
sort.Strings(servers)
|
||||
for _, server := range servers {
|
||||
merged := false
|
||||
for i := range blocking {
|
||||
if blocking[i].server == server {
|
||||
blocking[i].detail += "; " + strings.Join(byServer[server], "; ")
|
||||
merged = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !merged {
|
||||
blocking = append(blocking, hostBelow{server, strings.Join(byServer[server], "; ")})
|
||||
}
|
||||
}
|
||||
sort.Slice(blocking, func(i, j int) bool { return blocking[i].server < blocking[j].server })
|
||||
if len(blocking) > 0 {
|
||||
h.workspaceMu.Unlock()
|
||||
return false, unconfirmed, errFormatHostsTooOld{hosts: blocking, unconfirmed: unconfirmed}
|
||||
}
|
||||
h.formatFinalizing.Store(true)
|
||||
h.workspaceMu.Unlock()
|
||||
if _, err := h.attest.finalize(); err != nil {
|
||||
var uncertain *attestationWriteUncertain
|
||||
if errors.As(err, &uncertain) {
|
||||
h.failUncertainFormatFinalize(err)
|
||||
}
|
||||
h.Publisher().CancelFormatFinalize()
|
||||
h.formatFinalizing.Store(false)
|
||||
return false, unconfirmed, fmt.Errorf("format finalize: %w", err)
|
||||
}
|
||||
h.Publisher().FinalizeFormatLevel()
|
||||
h.format.v.Store(1)
|
||||
h.formatFinalizing.Store(false)
|
||||
h.log.Printf("blockmaster: cluster format level finalized at 1 (%d hosts unconfirmed, not blocking)", len(unconfirmed))
|
||||
return false, unconfirmed, nil
|
||||
}
|
||||
|
||||
// failUncertainFormatFinalize never reopens level-0 grants over a file whose
|
||||
// rename may already have raised the durable level. Arm exit before logging:
|
||||
// diagnostic delivery is best effort if the sink or its output lock is blocked.
|
||||
func (h *Host) failUncertainFormatFinalize(err error) {
|
||||
time.AfterFunc(time.Second, func() { os.Exit(authority.ExitDurabilityUnknown) })
|
||||
h.log.Printf("ERROR format finalize persistence failure store=%q error=%q; exiting so the supervisor restarts from durable state", h.attest.path, err)
|
||||
os.Exit(authority.ExitDurabilityUnknown)
|
||||
}
|
||||
|
||||
// RetireHost removes server from the node inventory, so it no longer counts
|
||||
// for the format finalize or for placement. It is refused while server
|
||||
// holds a lease or an assignment for any volume (FormatGate r2: a retire
|
||||
@@ -580,8 +516,6 @@ func (h *Host) RetireHost(server, confirm string) error {
|
||||
}
|
||||
h.finalizeMu.Lock()
|
||||
defer h.finalizeMu.Unlock()
|
||||
h.workspaceMu.Lock()
|
||||
defer h.workspaceMu.Unlock()
|
||||
if _, ok := h.lifecycle.Nodes.GetNode(server); !ok {
|
||||
return fmt.Errorf("retire refused: host %q is not registered", server)
|
||||
}
|
||||
@@ -636,8 +570,9 @@ func (s *services) FormatLevel(ctx context.Context, _ *control.FormatLevelReques
|
||||
return &control.FormatLevelResponse{FormatLevel: s.host.formatLevel()}, nil
|
||||
}
|
||||
|
||||
// RetireHost is the RPC of Host.RetireHost. The host method holds the workspace
|
||||
// lock across its check and removal, after acquiring finalize serialization.
|
||||
// RetireHost is the RPC of Host.RetireHost. It holds the workspace lock, as
|
||||
// a placement does, so no placement onto the host lands between its check
|
||||
// and the removal.
|
||||
func (s *services) RetireHost(ctx context.Context, req *control.RetireHostRequest) (*control.RetireHostResponse, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
@@ -647,6 +582,8 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
}
|
||||
s.host.workspaceMu.Lock()
|
||||
defer s.host.workspaceMu.Unlock()
|
||||
err := s.host.RetireHost(req.GetServerId(), req.GetConfirm())
|
||||
var holds errHostHoldsWork
|
||||
var storage errRetireStorage
|
||||
@@ -660,33 +597,3 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques
|
||||
}
|
||||
return &control.RetireHostResponse{ServerId: req.GetServerId()}, nil
|
||||
}
|
||||
|
||||
// formatReadProof is captured before the publisher's grant locks. A concurrent
|
||||
// process/read-level change invalidates it through the atomic revision.
|
||||
func (h *Host) formatReadProof(volume, replica, server string, epoch uint64) authority.FormatReadProof {
|
||||
h.reads.mu.Lock()
|
||||
defer h.reads.mu.Unlock()
|
||||
entry, ok := h.reads.procs[server][volume]
|
||||
return authority.FormatReadProof{Server: server, Process: entry.process, Replica: replica, Epoch: epoch, Reads: entry.level, Reported: ok, Revision: entry.revision, Version: formatReportVersion(entry)}
|
||||
}
|
||||
|
||||
func (h *Host) finalizeReadProofs() map[string]authority.FormatReadProof {
|
||||
out := map[string]authority.FormatReadProof{}
|
||||
// workspaceMu is held, so placement and line-owner changes cannot race this
|
||||
// projection. Publisher validates the current line and lease under its locks.
|
||||
h.reads.mu.Lock()
|
||||
defer h.reads.mu.Unlock()
|
||||
for volume, line := range h.Publisher().PublishedAuthorityLines() {
|
||||
server := h.workspaceLineOwner(line, volume, line.ReplicaID, line.Epoch)
|
||||
e, ok := h.reads.procs[server][volume]
|
||||
out[volume] = authority.FormatReadProof{Server: server, Process: e.process, Replica: line.ReplicaID, Epoch: line.Epoch, Reads: e.level, Reported: ok, Revision: e.revision, Version: formatReportVersion(e)}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func formatReportVersion(e procLevel) uint64 {
|
||||
if e.revision == nil {
|
||||
return 0
|
||||
}
|
||||
return e.revision.Load()
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func binaryTooOld(err error) bool {
|
||||
// Every binary's heartbeat is taken and its read level recorded, at level 0
|
||||
// and at level 1 alike (the refusal is at the grant, never at the
|
||||
// heartbeat); at level 1 a host whose process reads only level 0 is then
|
||||
// known old, so placement skips it (publication is refused at the admission
|
||||
// known old, so placement skips it (its grant is refused at the publication
|
||||
// boundary: TestThePublicationBoundaryRefusesAnAskForAnOldServer).
|
||||
func TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1(t *testing.T) {
|
||||
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
|
||||
@@ -69,9 +69,8 @@ func TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1(t *testing.T) {
|
||||
}
|
||||
|
||||
// At level 1 no new work goes to a host that does not read it: a workspace
|
||||
// placement and a move onto a known-old host are
|
||||
// refused; an unreported target is allowed. At level 0 neither is refused
|
||||
// for the format (FormatGate:
|
||||
// placement and a move onto an old host (or one that never reported) are
|
||||
// refused; at level 0 they are not refused for the format (FormatGate:
|
||||
// Assign, NoStrand).
|
||||
func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
|
||||
for _, level := range []uint32{1, 0} {
|
||||
@@ -94,15 +93,10 @@ func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
|
||||
_, placeErr := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"})
|
||||
_, moveErr := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "m1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
|
||||
if level == 1 && !reported {
|
||||
// Neither placement nor a move record grants a serving deadline.
|
||||
// An unreported target may pass this placement check.
|
||||
if placeErr != nil || (moveErr != nil && strings.Contains(moveErr.Error(), "format")) {
|
||||
t.Fatalf("silent target: placement=%v move=%v", placeErr, moveErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if level == 0 {
|
||||
if level == 0 || !reported {
|
||||
// level 0, or an unknown (silent) host at level 1: placeable
|
||||
// (placement refuses only a known-old report; the
|
||||
// grant needs the holder's report).
|
||||
if placeErr != nil {
|
||||
t.Fatalf("%s: placement refused: %v", name, placeErr)
|
||||
}
|
||||
@@ -382,32 +376,24 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A failure before the rename leaves both levels at 0, reopens admission,
|
||||
// and permits a later finalize retry once the obstruction is removed.
|
||||
// A finalize whose durable write fails changes no level: the publisher and
|
||||
// the master stay at 0 (the switch follows the write; FormatGateMaster
|
||||
// finalize_not_atomic).
|
||||
func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
r := finalizeFailureRig(t)
|
||||
obstruction := r.m.attest.path + ".tmp"
|
||||
if err := os.Mkdir(obstruction, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
|
||||
for _, s := range []string{"node-a", "node-b"} {
|
||||
if err := r.fgHeartbeat(s, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
saved := syncAttestationDir
|
||||
t.Cleanup(func() { syncAttestationDir = saved })
|
||||
syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") }
|
||||
if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); status.Code(err) != codes.Internal {
|
||||
t.Fatalf("pre-rename failure: %v, want Internal", err)
|
||||
t.Fatalf("a finalize whose envelope write failed: %v, want Internal (a failure, not a transient answer)", err)
|
||||
}
|
||||
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 || r.m.formatFinalizing.Load() {
|
||||
t.Fatal("pre-rename failure changed level or left host intent set")
|
||||
}
|
||||
// A no-report level-0 deadline proves the publisher intent is clear too.
|
||||
if _, err := r.m.Publisher().RenewWorkspaceLease(r.ctx, "v", "r1", 1); err != nil {
|
||||
t.Fatalf("publisher intent was not cleared after pre-rename failure: %v", err)
|
||||
}
|
||||
if err := os.Remove(obstruction); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := r.m.FinalizeFormat(1); err != nil || r.m.formatLevel() != 1 || r.m.Publisher().FormatLevel() != 1 || r.m.formatFinalizing.Load() {
|
||||
t.Fatalf("finalize could not retry after removing obstruction: %v", err)
|
||||
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 {
|
||||
t.Fatalf("a failed finalize switched the level: master %d, publisher %d", r.m.formatLevel(), r.m.Publisher().FormatLevel())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,7 +516,8 @@ func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
old, silent bool
|
||||
}{{"old-process", true, false}, {"silent (placement only)", false, true}, {"control", false, false}} {
|
||||
}{{"old-process", true, false}, {"silent (no report: no grant)", false, true}, {"control", false, false}} {
|
||||
old := tc.old || tc.silent
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
|
||||
r.createVolume(t, "v")
|
||||
@@ -551,7 +538,10 @@ func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) {
|
||||
if tc.old && (err == nil || published || !strings.Contains(err.Error(), "binary_too_old")) {
|
||||
t.Fatalf("level 1, node-b's process reads 0: err %v, published %v; want refused before the publish", err, published)
|
||||
}
|
||||
if !tc.old && (err != nil || !published) {
|
||||
if tc.silent && (err == nil || published || !strings.Contains(err.Error(), "has not reported")) {
|
||||
t.Fatalf("level 1, node-b never reported: err %v, published %v; want no grant (refused before the publish)", err, published)
|
||||
}
|
||||
if !old && (err != nil || !published) {
|
||||
t.Fatalf("control: err %v, published %v; want published", err, published)
|
||||
}
|
||||
})
|
||||
@@ -586,8 +576,8 @@ func TestEveryVolumeOfAHeartbeatKeepsItsLevel(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.m.format.v.Store(1)
|
||||
if proof := r.m.formatReadProof("vb", "r-b", "node-b", 1); !proof.Reported || proof.Reads != 0 || proof.Process != "old-proc" {
|
||||
t.Fatalf("the grant proof lost vb's own stale old report: %+v", proof)
|
||||
if why := r.m.grantTooOld("node-b", "vb"); !strings.Contains(why, "binary_too_old") {
|
||||
t.Fatalf("level 1: the grant for vb, held by the silent old process: %q, want binary_too_old", why)
|
||||
}
|
||||
r.m.format.v.Store(0)
|
||||
resp, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
|
||||
@@ -851,7 +841,7 @@ func upgradedStoreDir(t *testing.T) string {
|
||||
// two servers report the same volume and replica at different endpoints, one
|
||||
// process reading level 1 and one reading level 0; the ask at the first's
|
||||
// endpoints is published, the ask at the second's is refused binary_too_old,
|
||||
// and an ask at unreported endpoints may publish, but grants no deadline.
|
||||
// and an ask at endpoints nobody reports is not granted (no report).
|
||||
func TestAnOwnerlessGrantIsJudgedOnTheServerAtTheAsksEndpoints(t *testing.T) {
|
||||
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
|
||||
if r.m.formatLevel() != 1 {
|
||||
@@ -875,8 +865,8 @@ func TestAnOwnerlessGrantIsJudgedOnTheServerAtTheAsksEndpoints(t *testing.T) {
|
||||
if published, err := grant("127.0.0.1:19601", "127.0.0.1:19602"); err == nil || published || !strings.Contains(err.Error(), "binary_too_old") {
|
||||
t.Fatalf("the ask at node-c's endpoints (its process reads 0): err %v, published %v; want refused binary_too_old", err, published)
|
||||
}
|
||||
if published, err := grant("127.0.0.1:19701", "127.0.0.1:19702"); err != nil || !published {
|
||||
t.Fatalf("the ask at unreported endpoints: err %v, published %v; want placement accepted", err, published)
|
||||
if published, err := grant("127.0.0.1:19701", "127.0.0.1:19702"); err == nil || published || !strings.Contains(err.Error(), "has not reported") {
|
||||
t.Fatalf("the ask at endpoints no server reports: err %v, published %v; want no grant", err, published)
|
||||
}
|
||||
if published, err := grant("127.0.0.1:19501", "127.0.0.1:19502"); err != nil || !published {
|
||||
t.Fatalf("the ask at node-b's endpoints (its process reads 1): err %v, published %v; want granted", err, published)
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// fgV100Heartbeat sends a heartbeat shaped as a v1.0 holder sends it: a slot
|
||||
// with no incarnation and no reads level.
|
||||
func (r *isolationRig) fgV100Heartbeat(server, vol string) error {
|
||||
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
|
||||
Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1]}}})
|
||||
return err
|
||||
}
|
||||
|
||||
// v100IdentityRig is a level-1 cluster whose volume v is held on node-b by a
|
||||
// capable process (its own report reads 1) with a live lease.
|
||||
func v100IdentityRig(t *testing.T) *isolationRig {
|
||||
t.Helper()
|
||||
dir := upgradedStoreDir(t)
|
||||
disk, err := authority.NewFileAuthorityStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1]}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := disk.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := newIsolationRig(t, false, dir, t.TempDir())
|
||||
r.createVolume(t, "v")
|
||||
r.place(t, "v", "node-b")
|
||||
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// Identity check (2) of the v1.1.2 bound: a v1.0-shaped heartbeat from a new
|
||||
// process on the holder's server supersedes the cached report of the capable
|
||||
// predecessor (as unreported or level 0), so that process's renewals are
|
||||
// refused at level 1 and during the finalize intent; it never renews on its
|
||||
// predecessor's proof. The capable process's next report renews again (twin).
|
||||
func TestAV100HeartbeatSupersedesTheCachedReportSoItsRenewalsAreRefused(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
for _, phase := range []string{"level-1", "finalize-intent"} {
|
||||
t.Run(phase, func(t *testing.T) {
|
||||
r := v100IdentityRig(t)
|
||||
renew := func() error {
|
||||
_, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"})
|
||||
return err
|
||||
}
|
||||
switch phase {
|
||||
case "level-1":
|
||||
if _, _, err := r.m.FinalizeFormat(1); err != nil || r.m.formatLevel() != 1 {
|
||||
t.Fatalf("finalize: level %d, %v", r.m.formatLevel(), err)
|
||||
}
|
||||
case "finalize-intent":
|
||||
// A real finalize, held at its durable barrier: the intent is
|
||||
// open (the publisher's own flag set by BeginFormatFinalize),
|
||||
// the level still 0 on disk.
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
releaseOnce := sync.OnceFunc(func() { close(release) })
|
||||
previous := syncAttestationDir
|
||||
syncAttestationDir = func(dir string) error { close(entered); <-release; return previous(dir) }
|
||||
t.Cleanup(func() { syncAttestationDir = previous })
|
||||
finalized := make(chan error, 1)
|
||||
go func() { _, _, err := r.m.FinalizeFormat(1); finalized <- err }()
|
||||
t.Cleanup(func() {
|
||||
releaseOnce()
|
||||
select {
|
||||
case <-finalized:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("finalize did not finish")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("finalize never reached its durable barrier")
|
||||
}
|
||||
if r.m.formatLevel() != 0 || !r.m.formatFinalizing.Load() {
|
||||
t.Fatalf("not in the intent: level %d finalizing %v", r.m.formatLevel(), r.m.formatFinalizing.Load())
|
||||
}
|
||||
}
|
||||
if err := renew(); err != nil {
|
||||
t.Fatalf("the capable holder could not renew: %v", err)
|
||||
}
|
||||
// A replacement process on a v1.0 binary reports before renewing.
|
||||
if err := r.fgV100Heartbeat("node-b", "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reads, reported := r.m.reads.entry("node-b", "v", r.m.servedBy("node-b")); reported && reads >= 1 {
|
||||
t.Fatalf("the v1.0-shaped heartbeat left the predecessor's report (reads %d) for the volume", reads)
|
||||
}
|
||||
if err := renew(); err == nil {
|
||||
t.Fatal("a v1.0 replacement renewed on its predecessor's proof")
|
||||
}
|
||||
// Twin: the capable process reports again and renews.
|
||||
if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := renew(); err != nil {
|
||||
t.Fatalf("the capable process could not renew after reporting again: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -72,8 +72,8 @@ func TestANewClusterStartsAtTheCurrentFormatLevel(t *testing.T) {
|
||||
// On a new cluster (level 1) a node that has not reported is placeable (one
|
||||
// process per volume, created then started, cannot have reported at its
|
||||
// placement) and shows as awaiting report; it is not granted until its own
|
||||
// report: publication alone grants no serving deadline; after its own first
|
||||
// heartbeat (reads level 1), its lease renewal grants a deadline and the
|
||||
// report: the publication of its line is refused and its publish never runs;
|
||||
// after its first heartbeat (reads level 1) the line is published and the
|
||||
// condition is gone.
|
||||
func TestANewClusterPlacesAnUnreportedNodeAndGrantsAfterItsReport(t *testing.T) {
|
||||
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
|
||||
@@ -109,22 +109,14 @@ func TestANewClusterPlacesAnUnreportedNodeAndGrantsAfterItsReport(t *testing.T)
|
||||
func() error { published = true; return nil })
|
||||
return published, err
|
||||
}
|
||||
if published, err := grant(); err != nil || !published {
|
||||
t.Fatalf("publication before node-b's report: err %v, published %v; want placed", err, published)
|
||||
}
|
||||
if err := r.m.Controller().SubmitAssignmentAsk(authority.AssignmentAsk{VolumeID: "fresh", ReplicaID: "r1", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322", Intent: authority.IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := waitAuthorityLine(t, r.m.Publisher(), "fresh")
|
||||
id := &control.WorkspaceIdentity{VolumeId: "fresh", ReplicaId: "r1", ServerId: "node-b", Epoch: line.Epoch}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err == nil {
|
||||
t.Fatal("unreported process obtained its first serving deadline")
|
||||
if published, err := grant(); err == nil || published {
|
||||
t.Fatalf("the grant before node-b's report: err %v, published %v; want no grant", err, published)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "proc-b", "fresh", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
|
||||
t.Fatalf("first deadline after node-b's report: %v", err)
|
||||
if published, err := grant(); err != nil || !published {
|
||||
t.Fatalf("the grant after node-b's report: err %v, published %v; want granted", err, published)
|
||||
}
|
||||
if awaiting() {
|
||||
t.Fatal("node-b still shows awaiting report after its first heartbeat")
|
||||
@@ -183,7 +175,7 @@ func TestAnEmptyAuthorityStoreOverAnExistingInventoryStartsAtLevel0(t *testing.T
|
||||
|
||||
// The grant reads the holder's own report: on a server whose process for
|
||||
// volume u reported level 1, a new process for volume v that has not
|
||||
// reported yet receives no serving deadline; once v's own process reports level
|
||||
// reported yet is not granted v's line; once v's own process reports level
|
||||
// 1 it is (a sibling's report says nothing about this process's binary).
|
||||
func TestTheGrantReadsTheHoldersOwnReportNotASiblings(t *testing.T) {
|
||||
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
|
||||
@@ -200,22 +192,14 @@ func TestTheGrantReadsTheHoldersOwnReportNotASiblings(t *testing.T) {
|
||||
func() error { published = true; return nil })
|
||||
return published, err
|
||||
}
|
||||
if published, err := grant(); err != nil || !published {
|
||||
t.Fatalf("v's placement on an unreported process: err %v, published %v", err, published)
|
||||
}
|
||||
if err := r.m.Controller().SubmitAssignmentAsk(authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r1", DataAddr: "127.0.0.1:19331", CtrlAddr: "127.0.0.1:19332", Intent: authority.IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := waitAuthorityLine(t, r.m.Publisher(), "v")
|
||||
id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", ServerId: "node-b", Epoch: line.Epoch}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err == nil {
|
||||
t.Fatal("v's first deadline used u's report")
|
||||
if published, err := grant(); err == nil || published {
|
||||
t.Fatalf("v's grant on u's report only: err %v, published %v; want no grant", err, published)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "proc-v", "v", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
|
||||
t.Fatalf("v's first deadline after its own report: %v", err)
|
||||
if published, err := grant(); err != nil || !published {
|
||||
t.Fatalf("v's grant after v's own report: err %v, published %v; want granted", err, published)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,40 +298,6 @@ func TestGrantWaitsAreReconciledPerServerAndVolume(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A move does not rewrite the placement: the moved line waits on its new
|
||||
// holder until that process reports, and the former host's slot never waits
|
||||
// once its report for the volume expired.
|
||||
func TestAMovedLineWaitsOnItsNewHolderOnly(t *testing.T) {
|
||||
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
|
||||
r.issueMove(t, "v", "m1")
|
||||
r.m.reads.forget("node-b")
|
||||
r.m.format.v.Store(1)
|
||||
now := time.Now().Add(r.m.reads.window + time.Second)
|
||||
r.m.reads.now = func() time.Time { return now }
|
||||
if _, ok := r.m.reads.entry("node-a", "v", r.m.servedBy("node-a")); ok {
|
||||
t.Fatal("fixture: node-a's report for the moved volume is still live")
|
||||
}
|
||||
late := now.Add(r.m.grantStartupWindow() + time.Second)
|
||||
waiting := func(at time.Time, server string) bool {
|
||||
for _, w := range r.m.grantWaits(at)[server] {
|
||||
if w.volume == "v" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if waiting(now, "node-a") || waiting(late, "node-a") {
|
||||
t.Fatal("the former host waits for the moved volume's report")
|
||||
}
|
||||
if !waiting(now, "node-b") {
|
||||
t.Fatal("the moved line's unreported holder shows no wait")
|
||||
}
|
||||
r.m.reads.note("node-b", "v", "proc-v", 1)
|
||||
if waiting(late, "node-a") || waiting(late, "node-b") {
|
||||
t.Fatal("a wait outlived the new holder's report")
|
||||
}
|
||||
}
|
||||
|
||||
// A status snapshot that read the placements before a newer one never
|
||||
// reconciles after it: snapshot A holds its read (no placement yet) while
|
||||
// vb is placed on an unreported node and snapshot B is started; B must wait
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
// The move's stored lease is a reservation, not the target's permission to
|
||||
// serve. Only an accepted renewal reply can open the production lease guard.
|
||||
func TestFormatMoveRecordCannotServeBeforeReportedRenewal(t *testing.T) {
|
||||
if !finalizeServingChild(t) {
|
||||
return
|
||||
}
|
||||
for _, phase := range []string{"intent", "committed"} {
|
||||
t.Run(phase, func(t *testing.T) { formatMoveRecordCannotServe(t, phase) })
|
||||
}
|
||||
}
|
||||
|
||||
func formatMoveRecordCannotServe(t *testing.T, phase string) {
|
||||
r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir())
|
||||
r.createVolume(t, "moved")
|
||||
r.place(t, "moved", "node-a")
|
||||
if err := ingestV11(r.m, authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(),
|
||||
Slots: []authority.SlotFact{{VolumeID: "moved", ReplicaID: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitAuthorityLine(t, r.m.Publisher(), "moved")
|
||||
source := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "moved", ReplicaId: "r1", Epoch: 1}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RevokeWorkspace(r.ctx, source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.AckWorkspaceRevoked(r.ctx, &control.WorkspaceRevocationAck{Identity: source, HeadGen: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
releaseOnce := sync.OnceFunc(func() { close(release) })
|
||||
previous := syncAttestationDir
|
||||
if phase == "intent" {
|
||||
syncAttestationDir = func(dir string) error { close(entered); <-release; return previous(dir) }
|
||||
t.Cleanup(func() { syncAttestationDir = previous })
|
||||
}
|
||||
finished := make(chan error, 1)
|
||||
go func() { _, _, err := r.m.FinalizeFormat(1); finished <- err }()
|
||||
joined := false
|
||||
t.Cleanup(func() {
|
||||
releaseOnce()
|
||||
if !joined {
|
||||
<-finished // the entire scenario is isolated in a bounded child
|
||||
}
|
||||
})
|
||||
if phase == "intent" {
|
||||
select {
|
||||
case <-entered:
|
||||
case <-r.ctx.Done():
|
||||
t.Fatal("finalize did not reach the held write")
|
||||
}
|
||||
} else {
|
||||
if err := <-finished; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
joined = true
|
||||
}
|
||||
// This target has never reported. Publication/move is Place, not a
|
||||
// serving deadline; both the intent and level 1 must allow the move.
|
||||
moved, err := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "lease-record-only", VolumeId: "moved", ExpectedReplicaId: "r1", ExpectedEpoch: 1,
|
||||
TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
|
||||
if err != nil || !moved.GetIssued() {
|
||||
t.Fatalf("unreported target move refused during %s: %v %v", phase, moved, err)
|
||||
}
|
||||
ws, err := r.ws.QueryWorkspace(r.ctx, &control.WorkspaceVolume{VolumeId: "moved"})
|
||||
if err != nil || ws.GetLease().GetEpoch() != moved.GetNewEpoch() || ws.GetLease().GetExpiresAtNs() <= time.Now().UnixNano() {
|
||||
t.Fatalf("move did not issue a possibly-live lease record: %v %v", ws, err)
|
||||
}
|
||||
// The issued move and its positive lease record exist, but no renewal
|
||||
// reply has reached the guard, and the target still has no report.
|
||||
id := &control.WorkspaceIdentity{VolumeId: "moved", ReplicaId: "r1", ServerId: "node-b", Epoch: moved.GetNewEpoch()}
|
||||
guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "moved", ReplicaID: "r1", Epoch: moved.GetNewEpoch(), Healthy: true}}, r.ws, id,
|
||||
func(context.Context) (uint64, error) {
|
||||
t.Fatal("a refused first renewal must not drain an ungranted guard")
|
||||
return 0, nil
|
||||
}, time.Now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if guard.Held() || guard.Projection().Healthy {
|
||||
t.Fatal("issued move record opened serving before a renewal reply")
|
||||
}
|
||||
if err := guard.Refresh(r.ctx); err == nil || guard.Held() || guard.Projection().Healthy {
|
||||
t.Fatalf("unreported target obtained serving from the issued record: %v", err)
|
||||
}
|
||||
if err := r.fgProcessHeartbeat("node-b", "", "moved", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := guard.Refresh(r.ctx); err != nil || !guard.Held() || !guard.Projection().Healthy {
|
||||
t.Fatalf("reported target did not serve after an accepted renewal: %v", err)
|
||||
}
|
||||
releaseOnce()
|
||||
if !joined {
|
||||
if err := <-finished; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
joined = true
|
||||
}
|
||||
}
|
||||
@@ -276,8 +276,8 @@ func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.finalize(); err == nil || s.level() != 1 {
|
||||
t.Fatalf("a failed directory fsync keeps the possibly-written envelope selected until fail-stop: err=%v level=%d", err, s.level())
|
||||
if _, err := s.finalize(); err == nil || s.level() != 0 {
|
||||
t.Fatalf("a failed directory fsync of the finalize's envelope: err=%v level=%d (want an error, level 0)", err, s.level())
|
||||
}
|
||||
// The process restarts: the envelope is on disk (the rename happened).
|
||||
s, err = loadStoreAttestations(dir)
|
||||
|
||||
@@ -121,11 +121,6 @@ type Config struct {
|
||||
// GET /status/workspace-lease on this loopback address.
|
||||
StatusListen string
|
||||
|
||||
// FailStopLifecycleWrites exits the process on uncertain lifecycle-store
|
||||
// persistence. The supervised blockmaster executable enables it; embedders
|
||||
// that leave it off must reopen a failed store before attempting mutations.
|
||||
FailStopLifecycleWrites bool
|
||||
|
||||
// Logger is used for structured startup and error logging. If
|
||||
// nil, the default log package logger is used.
|
||||
Logger *log.Logger
|
||||
@@ -169,7 +164,6 @@ type Host struct {
|
||||
grantWaitMu sync.Mutex // one status snapshot reads and reconciles the grant waits at a time
|
||||
grantWait map[string]time.Time // "server\x00volume" -> first seen waiting for its grant without its process's report (format_gate.go grantWaits)
|
||||
format formatLevelState // the cluster's format level (format_gate.go)
|
||||
formatFinalizing atomic.Bool // admission intent while durable format raise is in flight
|
||||
finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go)
|
||||
// testGrantWaitsRead, when a test sets it, runs after a status snapshot
|
||||
// has read its placements, still holding grantWaitMu.
|
||||
@@ -281,10 +275,6 @@ func New(cfg Config) (*Host, error) {
|
||||
if lg == nil {
|
||||
lg = log.Default()
|
||||
}
|
||||
var persistenceFailure lifecycle.PersistenceFailureHandler
|
||||
if cfg.FailStopLifecycleWrites {
|
||||
persistenceFailure = lifecycleFailStop(lg)
|
||||
}
|
||||
|
||||
holder := &publisherHolder{}
|
||||
ctrlCfg := cfg.ControllerConfig
|
||||
@@ -321,7 +311,6 @@ func New(cfg Config) (*Host, error) {
|
||||
return nil, fmt.Errorf("master.New: Bootstrap: %w", err)
|
||||
}
|
||||
holder.set(boot.Publisher)
|
||||
boot.Publisher.RequireFormatReadProofs()
|
||||
// Bootstrap creates a fresh store directory: sample its file system only
|
||||
// now, or a first start would compare against an unknown device forever.
|
||||
// An unknown identity (stat error, unsupported platform) never matches.
|
||||
@@ -334,18 +323,9 @@ func New(cfg Config) (*Host, error) {
|
||||
// the master's state it reads.
|
||||
lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir)
|
||||
if err != nil {
|
||||
var failure *lifecycle.RecordPersistenceError
|
||||
if persistenceFailure != nil && errors.As(err, &failure) {
|
||||
persistenceFailure(failure)
|
||||
}
|
||||
_ = boot.Close()
|
||||
return nil, fmt.Errorf("master.New: lifecycle stores: %w", err)
|
||||
}
|
||||
if lifecycleStores != nil && persistenceFailure != nil {
|
||||
lifecycleStores.Nodes.SetPersistenceFailureHandler(persistenceFailure)
|
||||
lifecycleStores.Placements.SetPersistenceFailureHandler(persistenceFailure)
|
||||
lifecycleStores.Volumes.SetPersistenceFailureHandler(persistenceFailure)
|
||||
}
|
||||
// A new cluster starts at the current level: with no prior
|
||||
// state in any master store (no authority record reloaded or skipped, no
|
||||
// attestation file, no volume, node, placement or deletion in the
|
||||
|
||||
@@ -52,7 +52,6 @@ func (r *isolationRig) issueMove(t *testing.T, vol, requestID string) (*control.
|
||||
}
|
||||
q := &control.WorkspaceMove{RequestId: requestID, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}
|
||||
r.m.reads.note("node-b", vol, "", 1) // the move target reports before its grant
|
||||
grant, err := r.ws.MoveWorkspace(r.ctx, q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
func lifecycleFailStop(logger *log.Logger) lifecycle.PersistenceFailureHandler {
|
||||
var once sync.Once
|
||||
return func(failure *lifecycle.RecordPersistenceError) {
|
||||
once.Do(func() {
|
||||
// Arm termination before touching the logger: its writer or output
|
||||
// mutex may be blocked. ERROR delivery is best effort in that case.
|
||||
time.AfterFunc(time.Second, func() { os.Exit(1) })
|
||||
logger.Printf("ERROR lifecycle persistence failure store=%q record=%q error=%q; exiting so the supervisor restarts from durable state", failure.Store, failure.Record, failure.Err)
|
||||
// A graceful close can wait on the writer that discovered the error.
|
||||
// The supervisor restarts; Open establishes the recovery barriers.
|
||||
os.Exit(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
func TestLifecyclePersistenceFailureStopsTheProcess(t *testing.T) {
|
||||
for _, kind := range []string{"nodes", "placements", "volumes", "concurrent"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceExitChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "LIFECYCLE_EXIT_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind)
|
||||
out, err := cmd.CombinedOutput()
|
||||
var exit *exec.ExitError
|
||||
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
|
||||
t.Fatalf("master failed to exit1: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
text := string(out)
|
||||
record := "new.json"
|
||||
if kind == "volumes" {
|
||||
record = "kept.json"
|
||||
}
|
||||
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, record) || !strings.Contains(text, filepath.Join(root, "lifecycle")) {
|
||||
t.Fatalf("missing single record/store/error line: %s", text)
|
||||
}
|
||||
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceRecoveryChild$", "-test.timeout=8s")
|
||||
recovery.Env = append(os.Environ(), "LIFECYCLE_RECOVERY_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind)
|
||||
if out, err := recovery.CombinedOutput(); err != nil {
|
||||
t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecyclePersistenceRecoveryChild(t *testing.T) {
|
||||
root := os.Getenv("LIFECYCLE_RECOVERY_ROOT")
|
||||
if root == "" {
|
||||
t.Skip("bounded recovery subprocess")
|
||||
}
|
||||
kind := os.Getenv("LIFECYCLE_EXIT_KIND")
|
||||
h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle"), FailStopLifecycleWrites: true})
|
||||
if err != nil {
|
||||
t.Fatal("restart", err)
|
||||
}
|
||||
h.Start()
|
||||
t.Cleanup(func() {
|
||||
c, stop := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer stop()
|
||||
if err := h.Close(c); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
kinds := []string{kind}
|
||||
if kind == "concurrent" {
|
||||
kinds = []string{"nodes", "placements"}
|
||||
}
|
||||
for _, part := range kinds {
|
||||
raw, err := os.ReadFile(filepath.Join(root, "lifecycle", part, "kept.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := os.ReadFile(filepath.Join(root, part+"-sha256"))
|
||||
if err != nil || fmt.Sprintf("%x", sha256.Sum256(raw)) != string(want) {
|
||||
t.Fatalf("restart changed committed %s: %v", part, err)
|
||||
}
|
||||
var kept, failed bool
|
||||
switch part {
|
||||
case "nodes":
|
||||
_, kept = h.Lifecycle().Nodes.GetNodeSnapshot("kept")
|
||||
_, failed = h.Lifecycle().Nodes.GetNodeSnapshot("new")
|
||||
case "placements":
|
||||
_, kept = h.Lifecycle().Placements.GetPlacementSnapshot("kept")
|
||||
_, failed = h.Lifecycle().Placements.GetPlacementSnapshot("new")
|
||||
case "volumes":
|
||||
_, kept = h.Lifecycle().Volumes.GetVolumeSnapshot("kept")
|
||||
_, failed = h.Lifecycle().Volumes.GetVolumeSnapshot("new")
|
||||
}
|
||||
if !kept || failed {
|
||||
t.Fatalf("restart published wrong %s records", part)
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(root, "lifecycle", part))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {
|
||||
raw, err := os.ReadFile(filepath.Join(root, "lifecycle", part, entry.Name()))
|
||||
if err != nil || !json.Valid(raw) {
|
||||
t.Fatalf("partial record %s: %v", entry.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type blockedLifecycleLog struct {
|
||||
entered chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (w *blockedLifecycleLog) Write(p []byte) (int, error) {
|
||||
w.once.Do(func() { close(w.entered) })
|
||||
select {}
|
||||
}
|
||||
|
||||
func TestLifecycleFailStopExitsWithBlockedLogger(t *testing.T) {
|
||||
for _, mode := range []string{"writer", "held-lock"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecycleBlockedLoggerChild$", "-test.timeout=4s")
|
||||
cmd.Env = append(os.Environ(), "LIFECYCLE_BLOCKED_LOG="+mode)
|
||||
out, err := cmd.CombinedOutput()
|
||||
exited := time.Now()
|
||||
var exit *exec.ExitError
|
||||
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
|
||||
t.Fatalf("blocked logger prevented own exit1: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
var triggered int64
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
if v, ok := strings.CutPrefix(line, "lifecycle-failure-triggered="); ok {
|
||||
triggered, _ = strconv.ParseInt(v, 10, 64)
|
||||
}
|
||||
}
|
||||
if triggered == 0 {
|
||||
t.Fatalf("child did not report its failure trigger:\n%s", out)
|
||||
}
|
||||
// One-second deadline plus one second of scheduler tolerance; the
|
||||
// subprocess watchdog above is separate and longer.
|
||||
if elapsed := exited.Sub(time.Unix(0, triggered)); elapsed > 2*time.Second {
|
||||
t.Fatalf("exit took %s after the failure, want within the one-second deadline", elapsed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleBlockedLoggerChild(t *testing.T) {
|
||||
mode := os.Getenv("LIFECYCLE_BLOCKED_LOG")
|
||||
if mode == "" {
|
||||
t.Skip("bounded blocked-sink child")
|
||||
}
|
||||
w := &blockedLifecycleLog{entered: make(chan struct{})}
|
||||
logger := log.New(w, "", 0)
|
||||
if mode == "held-lock" {
|
||||
go logger.Print("earlier message")
|
||||
<-w.entered
|
||||
}
|
||||
fail := lifecycleFailStop(logger)
|
||||
fmt.Printf("lifecycle-failure-triggered=%d\n", time.Now().UnixNano())
|
||||
go fail(&lifecycle.RecordPersistenceError{Store: "nodes", Record: "v.json", Err: errors.New("fixture")})
|
||||
fail(&lifecycle.RecordPersistenceError{Store: "placements", Record: "v.json", Err: errors.New("fixture")})
|
||||
os.Exit(91)
|
||||
}
|
||||
|
||||
func TestLifecyclePersistenceExitChild(t *testing.T) {
|
||||
root := os.Getenv("LIFECYCLE_EXIT_ROOT")
|
||||
if root == "" {
|
||||
t.Skip("bounded fail-stop subprocess")
|
||||
}
|
||||
h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle"), FailStopLifecycleWrites: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
put := func(kind, id string) error {
|
||||
switch kind {
|
||||
case "nodes":
|
||||
_, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"})
|
||||
return err
|
||||
case "placements":
|
||||
_, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}})
|
||||
return err
|
||||
default:
|
||||
_, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: id, SizeBytes: 1 << 20, ReplicationFactor: 1})
|
||||
return err
|
||||
}
|
||||
}
|
||||
kinds := []string{os.Getenv("LIFECYCLE_EXIT_KIND")}
|
||||
if kinds[0] == "concurrent" {
|
||||
kinds = []string{"nodes", "placements"}
|
||||
}
|
||||
for _, kind := range kinds {
|
||||
if err := put(kind, "kept"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(root, "lifecycle", kind, "kept.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, kind+"-sha256"), []byte(fmt.Sprintf("%x", sha256.Sum256(raw))), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kind == "volumes" {
|
||||
continue
|
||||
}
|
||||
block := filepath.Join(root, "lifecycle", kind, "new.json")
|
||||
if err := os.Mkdir(block, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var descriptors []*os.File
|
||||
if kinds[0] == "volumes" {
|
||||
// Attach has no pre-write record lookup on disk. Exhaust only this child's
|
||||
// descriptor budget so CreateTemp fails while its committed file stays intact.
|
||||
var limit syscall.Rlimit
|
||||
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if limit.Cur > 128 {
|
||||
limit.Cur = 128
|
||||
}
|
||||
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for {
|
||||
file, err := os.Open(os.DevNull)
|
||||
if errors.Is(err, syscall.EMFILE) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
descriptors = append(descriptors, file)
|
||||
}
|
||||
}
|
||||
start := make(chan struct{})
|
||||
done := make(chan error, len(kinds))
|
||||
for _, kind := range kinds {
|
||||
go func(kind string) {
|
||||
<-start
|
||||
if kind == "volumes" {
|
||||
_, err := h.Lifecycle().Volumes.AttachVolume("kept", "node")
|
||||
done <- err
|
||||
return
|
||||
}
|
||||
done <- put(kind, "new")
|
||||
}(kind)
|
||||
}
|
||||
close(start)
|
||||
for range kinds {
|
||||
if err := <-done; err != nil {
|
||||
fmt.Fprintln(os.Stderr, "persistence error returned instead of exiting:", err)
|
||||
os.Exit(91)
|
||||
}
|
||||
}
|
||||
runtime.KeepAlive(descriptors)
|
||||
fmt.Fprintln(os.Stderr, "failed persistence did not stop master")
|
||||
os.Exit(92)
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func TestObservationReportsACleanlyStoppedVolumeStopped(t *testing.T) {
|
||||
h, c, ctx := reviewBindingHost(t)
|
||||
reviewLegacyBind(t, h, c, ctx, "vs")
|
||||
p := h.Publisher()
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1, h.formatReadProof("vs", "r1", "node-a", 1)); err != nil {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "vs", "r1", 1); err != nil {
|
||||
@@ -58,7 +58,6 @@ func TestObservationReportsACleanlyStoppedVolumeStopped(t *testing.T) {
|
||||
if err := h.lifecycle.WorkspaceBindings.Register(target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.reads.note("node-b", "vs", "", 1) // capable target process, before move grant
|
||||
moved, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "move-1", VolumeID: "vs", ExpectedReplicaID: "r1", ExpectedHost: "node-a", ExpectedEpoch: 1, TargetReplicaID: "r1", TargetHost: target.ServerID, TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"}, head)
|
||||
if err != nil || !moved.Issued {
|
||||
t.Fatalf("move: %+v %v", moved, err)
|
||||
@@ -80,7 +79,7 @@ func TestObservationDeletionOutranksStoppedAndRetiredTopology(t *testing.T) {
|
||||
})
|
||||
reviewLegacyBind(t, h, c, ctx, "vs")
|
||||
p := h.Publisher()
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1, h.formatReadProof("vs", "r1", "node-a", 1)); err != nil {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "vs", "r1", 1); err != nil {
|
||||
|
||||
@@ -191,7 +191,6 @@ func TestRF1RefreshDecidedBeforeACrossHostMoveIsNotApplied(t *testing.T) {
|
||||
if _, err = ws.RegisterWorkspaceBinding(ctx, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.reads.note("node-b", "rt", "", 1) // target report precedes move grant
|
||||
grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "rt", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch,
|
||||
TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"})
|
||||
if err != nil || !grant.Issued {
|
||||
|
||||
@@ -72,7 +72,6 @@ func TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot(t *testing.T) {
|
||||
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.reads.note("node-a", "a2", "", 1) // target report precedes move grant
|
||||
g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "to-a", VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch,
|
||||
TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: "127.0.0.1:19111", TargetCtrlAddr: "127.0.0.1:19112", Kind: "clean"})
|
||||
if err != nil || !g.Issued || g.NewHost != "node-a" {
|
||||
|
||||
@@ -205,10 +205,7 @@ func (s *storeAttestations) finalize() (already bool, err error) {
|
||||
}
|
||||
s.enveloped = true
|
||||
if err := s.persist(s.vols); err != nil {
|
||||
var uncertain *attestationWriteUncertain
|
||||
if !errors.As(err, &uncertain) {
|
||||
s.enveloped = false
|
||||
}
|
||||
s.enveloped = false
|
||||
return false, err
|
||||
}
|
||||
return false, nil
|
||||
@@ -540,17 +537,9 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("store attestations: %w", werr)
|
||||
}
|
||||
if err := syncAttestationDir(filepath.Dir(s.path)); err != nil {
|
||||
return &attestationWriteUncertain{err}
|
||||
}
|
||||
return nil
|
||||
return syncAttestationDir(filepath.Dir(s.path))
|
||||
}
|
||||
|
||||
// attestationWriteUncertain means the rename landed but its durability is unknown.
|
||||
type attestationWriteUncertain struct{ error }
|
||||
|
||||
func (e *attestationWriteUncertain) Unwrap() error { return e.error }
|
||||
|
||||
// ingestStoreAttestation records a heartbeat's attestation when the
|
||||
// reporting server holds the volume's published primary line at the
|
||||
// attested epoch (the line's replica and owner). Anything else is not a
|
||||
|
||||
@@ -126,7 +126,7 @@ func TestReserveVolumeDeletionLiveLeaseIsDefiniteAndKeepsRenewing(t *testing.T)
|
||||
h, conn, ctx := reviewBindingHost(t)
|
||||
reviewLegacyBind(t, h, conn, ctx, "live-delete")
|
||||
establishVolume(t, h, "live-delete") // a volume past creation keeps the live-lease refusal
|
||||
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1, h.formatReadProof("live-delete", "r1", "node-a", 1)); err != nil {
|
||||
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lc := control.NewLifecycleServiceClient(conn)
|
||||
@@ -136,7 +136,7 @@ func TestReserveVolumeDeletionLiveLeaseIsDefiniteAndKeepsRenewing(t *testing.T)
|
||||
if h.lifecycle.Deletions.Reserved("live-delete") {
|
||||
t.Fatal("refusal persisted a reservation")
|
||||
}
|
||||
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1, h.formatReadProof("live-delete", "r1", "node-a", 1)); err != nil {
|
||||
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1); err != nil {
|
||||
t.Fatalf("refused delete interrupted renewal: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -281,40 +281,18 @@ func (h *Host) admitWorkspacePublicationNow(ask authority.AssignmentAsk, publish
|
||||
epoch = line.Epoch
|
||||
}
|
||||
server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch)
|
||||
// Publication places an authority line; only a renewal reply authorizes
|
||||
// serving. During finalize and at level 1, place only refuses known-old
|
||||
// targets. Resolve the target at the ask's endpoints, not another source.
|
||||
placeServer := ""
|
||||
if h.obs != nil {
|
||||
placeServer, _ = h.obs.Store().ServerOfSlotAt(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr)
|
||||
// The format gate at the grant: an authority line is published
|
||||
// only to a server whose own report reads the cluster's level; no report
|
||||
// means no grant (the ask waits for it), and an ask decided on
|
||||
// observations taken before its server reported a lower level is not
|
||||
// published.
|
||||
// A line with no recorded owner (a static topology's) goes to the process
|
||||
// the facts show at the ask's endpoints; its server is the one judged.
|
||||
grantServer := server
|
||||
if grantServer == "" && h.obs != nil {
|
||||
grantServer, _ = h.obs.Store().ServerOfSlotAt(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr)
|
||||
}
|
||||
if placeServer == "" {
|
||||
placeServer = server
|
||||
}
|
||||
why := h.placementTooOld(placeServer)
|
||||
// A same-owner endpoint refresh, or a reassign (heal, failover) to the
|
||||
// replica's committed holder, gives no new placement to this server.
|
||||
// Judge this volume's process rather than an unrelated sibling process.
|
||||
// Publisher still checks ExpectCurrent atomically before changing the line.
|
||||
line, ok := h.Publisher().VolumeAuthorityLine(ask.VolumeID)
|
||||
held := ok && line.Assigned && h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, line.Epoch) == placeServer
|
||||
if ask.Intent == authority.IntentRefreshEndpoint && ask.ExpectCurrent != nil {
|
||||
expected := ask.ExpectCurrent
|
||||
held = held && line.ReplicaID == ask.ReplicaID &&
|
||||
line.Epoch == expected.Epoch && line.ReplicaID == expected.ReplicaID &&
|
||||
line.DataAddr == ask.DataAddr && line.CtrlAddr == ask.CtrlAddr &&
|
||||
line.DataAddr == expected.DataAddr && line.CtrlAddr == expected.CtrlAddr
|
||||
} else if ask.Intent != authority.IntentReassign {
|
||||
held = false
|
||||
}
|
||||
if held {
|
||||
reads, reported := h.reads.entry(placeServer, ask.VolumeID, h.servedBy(placeServer))
|
||||
why = ""
|
||||
if reported && reads < h.admissionFormatLevel() {
|
||||
why = fmt.Sprintf("node %q's process for volume %q reads format level %d (binary_too_old)", placeServer, ask.VolumeID, reads)
|
||||
}
|
||||
}
|
||||
if why != "" {
|
||||
if why := h.grantTooOld(grantServer, ask.VolumeID); why != "" {
|
||||
return fmt.Errorf("workspace publication: %s", why)
|
||||
}
|
||||
b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr}
|
||||
|
||||
@@ -71,8 +71,7 @@ func bindingReconcileHistory(t *testing.T, legacySource bool) *Host {
|
||||
p := h.Publisher()
|
||||
ack := func(epoch uint64, server string) authority.WorkspaceHead {
|
||||
t.Helper()
|
||||
h.reads.note(server, "recover", "history-"+server, 1)
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "recover", "r1", epoch, h.formatReadProof("recover", "r1", server, epoch)); err != nil {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "recover", "r1", epoch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "recover", "r1", epoch); err != nil {
|
||||
@@ -90,7 +89,6 @@ func bindingReconcileHistory(t *testing.T, legacySource bool) *Host {
|
||||
epoch := uint64(i + 1)
|
||||
source := []string{"node-a", "node-b", "node-c"}[i]
|
||||
head := ack(epoch, source)
|
||||
h.reads.note(target.ServerID, "recover", "history-"+target.ServerID, 1)
|
||||
moved, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: fmt.Sprintf("move-%d", i), VolumeID: "recover", ExpectedReplicaID: "r1", ExpectedHost: source, ExpectedEpoch: epoch, TargetReplicaID: "r1", TargetHost: target.ServerID, TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"}, head)
|
||||
if err != nil || !moved.Issued || moved.NewEpoch != epoch+1 {
|
||||
t.Fatalf("history move: %+v %v", moved, err)
|
||||
|
||||
@@ -167,7 +167,6 @@ func workspaceBindingsMove(t *testing.T, forced bool) {
|
||||
if _, err = client.MoveWorkspace(ctx, q); err == nil {
|
||||
t.Fatal("explicit volume fell back to legacy node pair")
|
||||
}
|
||||
h.reads.note("node-b", vol, "", 1) // prepared target reports before the grant
|
||||
q.RequestId = vol + "-move"
|
||||
q.TargetDataAddr = target.DataAddr
|
||||
q.TargetCtrlAddr = target.CtrlAddr
|
||||
|
||||
@@ -138,7 +138,6 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
|
||||
if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-early"}); err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") {
|
||||
t.Fatalf("delete under the exited holder's live authority: %v; want the clean revocation ACK refusal", err)
|
||||
}
|
||||
m.reads.note("node-b", "vol-a", "", 1) // target report before the move grant
|
||||
move := &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"}
|
||||
if _, err := ws.MoveWorkspace(ctx, move); err == nil {
|
||||
@@ -162,7 +161,6 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
m.reads.note("node-b", "vol-a", "", 1) // unserved target keeps reporting across the lease wait
|
||||
grant, err := ws.MoveWorkspace(ctx, move)
|
||||
if err != nil {
|
||||
t.Fatal("forced move after the horizon:", err)
|
||||
|
||||
@@ -26,7 +26,6 @@ func TestWorkspaceLineOwnerIssuedAndHistorical(t *testing.T) {
|
||||
if _, err := ws.RegisterWorkspaceBinding(ctx, target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.reads.note("node-b", "v", "", 1) // target report before the move grant
|
||||
grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "owner-move", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -99,7 +99,6 @@ func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceS
|
||||
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.reads.note("node-b", "vol-f", "", 1) // capable target before the move grant
|
||||
return h, stop, client, &control.WorkspaceMove{RequestId: "force-1", VolumeId: "vol-f", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "forced", Force: true}
|
||||
}
|
||||
@@ -166,7 +165,6 @@ func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) {
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
h.reads.note("node-b", "vol-f", "", 1) // unserved target keeps reporting across the lease wait
|
||||
pv2, err := client.PreviewWorkspaceMove(ctx, move)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -120,7 +120,6 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) {
|
||||
}
|
||||
// Slot-0 and slot-1 targets on the node's host pass these preconditions
|
||||
// (they fail later, at the clean-move ACK check, for a different reason).
|
||||
m.reads.note("node-b", "placed", "", 1) // isolate the endpoint and clean-ACK checks
|
||||
for _, data := range []string{"127.0.0.1:19301", "127.0.0.1:19311"} {
|
||||
_, err = ws.MoveWorkspace(ctx, move("placed", "node-b", data, "127.0.0.1:19312"))
|
||||
if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") {
|
||||
|
||||
@@ -85,7 +85,6 @@ func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) {
|
||||
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.reads.note("node-a", "a2", "", 1) // isolate target endpoint/collision checks
|
||||
move := func(req, data, ctrl string) *control.WorkspaceMove {
|
||||
return &control.WorkspaceMove{RequestId: req, VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-a", TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"}
|
||||
|
||||
@@ -171,7 +171,7 @@ func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.Workspace
|
||||
}
|
||||
return nil, status.Error(codes.FailedPrecondition, text)
|
||||
}
|
||||
l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch(), s.host.formatReadProof(q.GetVolumeId(), q.GetReplicaId(), q.GetServerId(), q.GetEpoch()))
|
||||
l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch())
|
||||
if errors.Is(err, authority.ErrWorkspaceRevoked) {
|
||||
return nil, leaseRefusal(fmt.Sprintf("volume %s was moved or revoked; inspect sw-block ops workspace show --master MASTER --volume %s, complete the intended move, and leave this old unit stopped", q.GetVolumeId(), q.GetVolumeId()), control.WorkspaceLeaseRefusal_FINAL, 0)
|
||||
}
|
||||
@@ -465,7 +465,7 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho
|
||||
refusal.text = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID)
|
||||
case !replay && s.host.placementTooOld(target.ServerID) != "":
|
||||
// Only a known-old report refuses a move target; the
|
||||
// target receives a serving deadline only after its own report.
|
||||
// target's line is granted only after its own report.
|
||||
refusal = moveRefusal{"move target " + s.host.placementTooOld(target.ServerID), s.host.formatTooOldReason(target.ServerID)}
|
||||
case !matched:
|
||||
refusal.text = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit))
|
||||
|
||||
@@ -142,7 +142,6 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
|
||||
if err != nil || len(unchanged.GetMoves()) != 0 || unchanged.GetRevocationAck().GetHeadGen() != 9 {
|
||||
t.Fatal("refusal consumed ACK or wrote a move", unchanged, err)
|
||||
}
|
||||
h.reads.note("node-b", "vol-a", "", 1) // target process report before the grant
|
||||
q.TargetReplicaId = "r2"
|
||||
generation.Store(10) // operator metadata changed after the recorded ACK
|
||||
grant, err := client.MoveWorkspace(ctx, q)
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
|
||||
})
|
||||
reviewLegacyBind(t, h, c, ctx, "v")
|
||||
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "v", "r1", 1, h.formatReadProof("v", "r1", "node-a", 1)); err != nil {
|
||||
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "v", "r1", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := control.NewWorkspaceServiceClient(c)
|
||||
|
||||
@@ -105,7 +105,6 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
|
||||
if _, err = ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: oldID, HeadGen: seed.Gen}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.reads.note("node-b", "vol-a", "", 1) // target process report before the grant
|
||||
clean, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"})
|
||||
if err != nil {
|
||||
@@ -126,7 +125,6 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
|
||||
|
||||
// node-b dies before renewing or claiming. Before expiry plus skew the
|
||||
// forced move is refused, and HEAD is not read for it.
|
||||
m.reads.note("node-c", "vol-a", "", 1) // target process report before the forced grant
|
||||
forced := &control.WorkspaceMove{RequestId: "forced-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: grantee, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-c", TargetDataAddr: third.DataAddr, TargetCtrlAddr: third.CtrlAddr, Kind: "forced", Force: true}
|
||||
before := reads.Load()
|
||||
@@ -142,7 +140,6 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
m.reads.note("node-c", "vol-a", "", 1) // unserved target keeps reporting across the lease wait
|
||||
grant, err := ws.MoveWorkspace(ctx, forced)
|
||||
if err != nil {
|
||||
t.Fatal("forced move after the issued lease expired:", err)
|
||||
|
||||
@@ -227,12 +227,6 @@ type Host struct {
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
started atomic.Bool
|
||||
// heartbeatAnswered closes when the master first answers this process's
|
||||
// heartbeat (which names its incarnation): until then the master holds
|
||||
// only a predecessor's report for the volume, so the lease runtime does
|
||||
// not renew before it (identity check (1) of the format finalize bound).
|
||||
heartbeatAnswered chan struct{}
|
||||
heartbeatAnsweredOnce sync.Once
|
||||
|
||||
workspaceLeaseStarted atomic.Bool
|
||||
// Guard installation and terminal host fencing share this lock. Order:
|
||||
@@ -360,8 +354,6 @@ func New(cfg Config) (*Host, error) {
|
||||
conn: conn,
|
||||
obsCli: control.NewObservationServiceClient(conn),
|
||||
asnCli: control.NewAssignmentServiceClient(conn),
|
||||
|
||||
heartbeatAnswered: make(chan struct{}),
|
||||
}
|
||||
h.incarnation = newIncarnation()
|
||||
h.mw = newMasterWait(nil, lg.Printf)
|
||||
@@ -800,9 +792,6 @@ func (h *Host) runHeartbeat(ctx context.Context) {
|
||||
rpcCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
_, err := h.obsCli.ReportHeartbeat(rpcCtx, h.buildReport())
|
||||
if err == nil {
|
||||
h.heartbeatAnsweredOnce.Do(func() { close(h.heartbeatAnswered) })
|
||||
}
|
||||
if ctx.Err() == nil {
|
||||
h.mw.call(err)
|
||||
// The wait's reason reaches the journal on a change and every
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
// GET /status/chunk?volume= answers the served volume's space accounting
|
||||
// and retention policy; the usual chunk-route guards apply.
|
||||
func TestStatusServer_StatusChunkUsage(t *testing.T) {
|
||||
fake := &fakeChunkControl{usage: chunkstore.Usage{Snapshots: 1, Dependents: 2, OwnChunks: 3, ForeignChunks: 4, MetadataGuard: chunkstore.MetadataGuardChunks}}
|
||||
fake := &fakeChunkControl{usage: chunkstore.Usage{Snapshots: 1, Dependents: 2, OwnChunks: 3, ForeignChunks: 4}}
|
||||
s := chunkServer(t, fake, true)
|
||||
w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v1")
|
||||
if w.Code != http.StatusOK {
|
||||
|
||||
@@ -1,264 +0,0 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// orderServer is a master's two holder-facing services on one listener: it
|
||||
// records the order in which a holder's heartbeats and lease renewals
|
||||
// arrive, and holds the FIRST heartbeat open until released (a slow first
|
||||
// report, as after a master restart or a congested link). entered closes
|
||||
// when that first heartbeat is inside the handler: from then on the
|
||||
// heartbeat is in flight and not yet answered.
|
||||
type orderServer struct {
|
||||
control.UnimplementedObservationServiceServer
|
||||
control.UnimplementedWorkspaceServiceServer
|
||||
mu sync.Mutex
|
||||
events []string
|
||||
heartbeat int
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func newOrderServer() *orderServer {
|
||||
return &orderServer{entered: make(chan struct{}), release: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (s *orderServer) record(e string) {
|
||||
s.mu.Lock()
|
||||
s.events = append(s.events, e)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *orderServer) ReportHeartbeat(ctx context.Context, r *control.HeartbeatReport) (*control.HeartbeatAck, error) {
|
||||
s.mu.Lock()
|
||||
s.heartbeat++
|
||||
first := s.heartbeat == 1
|
||||
s.mu.Unlock()
|
||||
if first {
|
||||
close(s.entered)
|
||||
select {
|
||||
case <-s.release:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
incarnation := ""
|
||||
if slots := r.GetSlots(); len(slots) > 0 {
|
||||
incarnation = slots[0].GetIncarnation()
|
||||
}
|
||||
s.record("heartbeat incarnation=" + incarnation)
|
||||
return &control.HeartbeatAck{}, nil
|
||||
}
|
||||
|
||||
func (s *orderServer) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
|
||||
s.record("renewal")
|
||||
ttl := 5 * time.Second
|
||||
return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(ttl), ExpiresAtNs: time.Now().Add(ttl).UnixNano()}, nil
|
||||
}
|
||||
|
||||
func (s *orderServer) snapshot() []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]string(nil), s.events...)
|
||||
}
|
||||
|
||||
func (s *orderServer) renewed() bool {
|
||||
for _, e := range s.snapshot() {
|
||||
if e == "renewal" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// firstHeartbeatRig starts an already-assigned holder (epoch 3, so the lease
|
||||
// runtime may start at once) against s: its heartbeat loop and its lease
|
||||
// runtime. started is when the lease runtime was started; done closes when it
|
||||
// returns (any number of readers). Cleanup cancels the runtime and joins it
|
||||
// within a bound, before the host and the server close; a failed join stops
|
||||
// the test binary (joinOrFailStop), so nothing is torn down under it.
|
||||
func firstHeartbeatRig(t *testing.T, s *orderServer) (h *Host, started time.Time, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
control.RegisterObservationServiceServer(srv, s)
|
||||
control.RegisterWorkspaceServiceServer(srv, s)
|
||||
go srv.Serve(ln)
|
||||
t.Cleanup(srv.Stop)
|
||||
h = workspaceRuntimeHost(t, ln.Addr().String(), true) // its cleanup closes the host (joins the heartbeat loop)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ch := make(chan struct{})
|
||||
h.Start()
|
||||
started = time.Now()
|
||||
go func() {
|
||||
defer close(ch)
|
||||
_ = h.RunWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 0, nil })
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
joinOrFailStop(ch, 10*time.Second)
|
||||
})
|
||||
return h, started, ch
|
||||
}
|
||||
|
||||
// joinOrFailStop waits for done within bound. On timeout it ends the test
|
||||
// binary at once (os.Exit, no unwinding): a panic would still run the
|
||||
// cleanups after it (testing runs the rest when one panics), which close the
|
||||
// host and the server and restore shared settings under a lease runtime
|
||||
// that is still running.
|
||||
func joinOrFailStop(done <-chan struct{}, bound time.Duration) {
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(bound):
|
||||
fmt.Fprintln(os.Stderr, "the lease runtime did not return within "+bound.String()+" of its cancellation; refusing teardown under a live worker")
|
||||
os.Exit(3)
|
||||
}
|
||||
}
|
||||
|
||||
// The rig's join fail-stops before teardown. A child test binary registers a
|
||||
// teardown cleanup (it writes a marker file) and, after it, the join: with a
|
||||
// worker that never returns the child exits with status 3 and the marker is
|
||||
// absent (no teardown ran); with a worker that returned it passes and the
|
||||
// marker is present.
|
||||
func TestAFailedRuntimeJoinFailStopsBeforeTeardown(t *testing.T) {
|
||||
if marker := os.Getenv("JOIN_FAILSTOP_MARKER"); marker != "" {
|
||||
t.Cleanup(func() { _ = os.WriteFile(marker, []byte("teardown ran"), 0o644) }) // the later teardown
|
||||
done := make(chan struct{})
|
||||
if os.Getenv("JOIN_FAILSTOP_JOINED") == "true" {
|
||||
close(done)
|
||||
}
|
||||
t.Cleanup(func() { joinOrFailStop(done, 50*time.Millisecond) }) // runs first
|
||||
return
|
||||
}
|
||||
for _, joined := range []bool{false, true} {
|
||||
marker := filepath.Join(t.TempDir(), "teardown-ran")
|
||||
// The child is bounded: a join that hangs is killed at the deadline
|
||||
// and fails here as a timeout, never as the expected exit 3.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1", "-test.timeout=20s")
|
||||
cmd.WaitDelay = 5 * time.Second
|
||||
cmd.Env = append(os.Environ(), "JOIN_FAILSTOP_MARKER="+marker, "JOIN_FAILSTOP_JOINED="+strconv.FormatBool(joined))
|
||||
out, err := cmd.CombinedOutput() // returns only after the child is reaped (killed at the deadline if need be)
|
||||
timedOut := ctx.Err() != nil
|
||||
cancel()
|
||||
if timedOut {
|
||||
t.Fatalf("joined=%v: the child did not finish within 30s (killed): %v\n%s", joined, err, out)
|
||||
}
|
||||
_, statErr := os.Stat(marker)
|
||||
var exit *exec.ExitError
|
||||
switch {
|
||||
case joined && (err != nil || statErr != nil):
|
||||
t.Fatalf("a returned worker: child %v, teardown marker %v\n%s", err, statErr, out)
|
||||
case !joined && !(errors.As(err, &exit) && exit.ExitCode() == 3):
|
||||
t.Fatalf("a worker that never returned: child %v, want exit status 3\n%s", err, out)
|
||||
case !joined && statErr == nil:
|
||||
t.Fatalf("a worker that never returned: the later teardown ran\n%s", out)
|
||||
case !joined && !strings.Contains(string(out), "refusing teardown under a live worker"):
|
||||
t.Fatalf("a worker that never returned: no cause in the output\n%s", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Identity check (1) of the v1.1.2 bound: a v1.1 holder's first lease
|
||||
// renewal on start follows its first ANSWERED heartbeat, which names its
|
||||
// incarnation. Until then the master holds only its predecessor's report for
|
||||
// the volume, and a renewal would be judged on that report. The window is
|
||||
// witnessed open: the first heartbeat is inside the master's handler, held
|
||||
// there, while the lease runtime has every chance to renew; once it is
|
||||
// answered, a renewal follows.
|
||||
func TestAHolderRenewsOnlyAfterItsFirstHeartbeatWithItsIncarnation(t *testing.T) {
|
||||
s := newOrderServer()
|
||||
h, _, _ := firstHeartbeatRig(t, s)
|
||||
select {
|
||||
case <-s.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the holder's first heartbeat never reached the master")
|
||||
}
|
||||
// The heartbeat is in flight and unanswered: the window is open.
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
if s.renewed() {
|
||||
t.Fatalf("the holder renewed its lease while its first heartbeat was in flight: %v", s.snapshot())
|
||||
}
|
||||
close(s.release)
|
||||
runtimeAwait(t, "a renewal after the first heartbeat", s.renewed)
|
||||
events := s.snapshot()
|
||||
if len(events) == 0 || events[0] == "renewal" {
|
||||
t.Fatalf("first event %v, want the first heartbeat", events)
|
||||
}
|
||||
if events[0] != "heartbeat incarnation="+h.incarnation || h.incarnation == "" {
|
||||
t.Fatalf("the first heartbeat %q does not name this process's incarnation %q", events[0], h.incarnation)
|
||||
}
|
||||
}
|
||||
|
||||
// A holder whose first heartbeat is never answered does not renew and does
|
||||
// not serve: the lease runtime waits the configured bound (one lease
|
||||
// validity; shortened here), no less and not much more, then installs its
|
||||
// guard fenced and returns. The wait is measured from its own start (a test
|
||||
// hook), to its return; the tolerance covers the runtime's 50 ms poll and
|
||||
// the fenced guard's install and drain.
|
||||
func TestAHolderWhoseHeartbeatIsNeverAnsweredFencesRatherThanServes(t *testing.T) {
|
||||
const bound, tolerance = 300 * time.Millisecond, 500 * time.Millisecond
|
||||
previous, previousHook := firstHeartbeatWait, firstHeartbeatWaitStarted
|
||||
waitStarted := make(chan time.Time, 1)
|
||||
firstHeartbeatWait = bound
|
||||
firstHeartbeatWaitStarted = func(at time.Time) {
|
||||
select {
|
||||
case waitStarted <- at:
|
||||
default:
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { firstHeartbeatWait, firstHeartbeatWaitStarted = previous, previousHook })
|
||||
s := newOrderServer() // never released
|
||||
h, _, done := firstHeartbeatRig(t, s)
|
||||
select {
|
||||
case <-s.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the holder's first heartbeat never reached the master")
|
||||
}
|
||||
var start time.Time
|
||||
select {
|
||||
case start = <-waitStarted:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the lease runtime never started waiting for the first answered heartbeat")
|
||||
}
|
||||
select { // suite protection only; the bound is checked below
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the lease runtime kept waiting past the bound instead of fencing")
|
||||
}
|
||||
switch waited := time.Since(start); {
|
||||
case waited < bound:
|
||||
t.Fatalf("the lease runtime fenced after %s, before its %s bound", waited, bound)
|
||||
case waited > bound+tolerance:
|
||||
t.Fatalf("the lease runtime fenced after %s, past its %s bound plus %s", waited, bound, tolerance)
|
||||
}
|
||||
if s.renewed() {
|
||||
t.Fatalf("a holder with no answered heartbeat renewed: %v", s.snapshot())
|
||||
}
|
||||
guard := h.view.workspaceGuard.Load()
|
||||
if guard == nil || !strings.Contains(guard.FenceCause(), "no heartbeat of this process answered within "+bound.String()) {
|
||||
t.Fatalf("the guard was not installed fenced with the unanswered-heartbeat cause and its bound: %v", guard)
|
||||
}
|
||||
if h.ProjectionView().Projection().Healthy {
|
||||
t.Fatal("a holder with no answered heartbeat serves")
|
||||
}
|
||||
}
|
||||
@@ -26,28 +26,12 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
|
||||
}
|
||||
tick := time.NewTicker(50 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
var heartbeatWaitStart time.Time
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
p := h.view.Projection()
|
||||
// The first renewal waits for this process's first answered heartbeat,
|
||||
// at most one lease validity: past that the guard is installed fenced
|
||||
// (no renewal, no serving) rather than waiting for ever.
|
||||
unanswered := ""
|
||||
if p.Epoch > 0 && !h.firstHeartbeatAnswered() {
|
||||
if heartbeatWaitStart.IsZero() {
|
||||
heartbeatWaitStart = time.Now()
|
||||
if hook := firstHeartbeatWaitStarted; hook != nil {
|
||||
hook(heartbeatWaitStart)
|
||||
}
|
||||
}
|
||||
if time.Since(heartbeatWaitStart) >= firstHeartbeatWait {
|
||||
unanswered = fmt.Sprintf("no heartbeat of this process answered within %s; a renewal would be judged on another process's report", firstHeartbeatWait)
|
||||
}
|
||||
}
|
||||
if p.Epoch > 0 && (unanswered != "" || h.firstHeartbeatAnswered()) {
|
||||
if p.Epoch > 0 {
|
||||
id := &control.WorkspaceIdentity{VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, ServerId: h.cfg.ServerID, Epoch: p.Epoch}
|
||||
guard, err := NewWorkspaceLeaseGuard(h.view, control.NewWorkspaceServiceClient(h.conn), id, func(c context.Context) (uint64, error) { return stop(c, id) }, nil)
|
||||
if err != nil {
|
||||
@@ -68,9 +52,6 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
|
||||
if ctx.Err() != nil {
|
||||
guard.fenceLocked("shutdown requested (context cancelled)")
|
||||
}
|
||||
if unanswered != "" {
|
||||
guard.fenceLocked(unanswered)
|
||||
}
|
||||
guard.stopPending = h.workspaceStopPending
|
||||
h.view.workspaceGuard.Store(guard)
|
||||
h.workspaceLeaseMu.Unlock()
|
||||
@@ -84,32 +65,6 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
// firstHeartbeatWait bounds the wait for the first answered heartbeat: the
|
||||
// longest lease validity a renewal reply may carry (Refresh refuses more).
|
||||
// Tests shorten it.
|
||||
var firstHeartbeatWait = 30 * time.Second
|
||||
|
||||
// firstHeartbeatWaitStarted, when set (tests only), is told when the lease
|
||||
// runtime starts waiting for the first answered heartbeat.
|
||||
var firstHeartbeatWaitStarted func(time.Time)
|
||||
|
||||
// firstHeartbeatAnswered reports whether the lease runtime may renew: the
|
||||
// master has answered this process's first heartbeat (with its incarnation),
|
||||
// so a renewal is judged on this process's own report, never on a
|
||||
// predecessor's. A host whose heartbeat loop never started (Start not called)
|
||||
// has nothing to wait for.
|
||||
func (h *Host) firstHeartbeatAnswered() bool {
|
||||
if !h.started.Load() {
|
||||
return true
|
||||
}
|
||||
select {
|
||||
case <-h.heartbeatAnswered:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// WorkspaceStopPending is called when a graceful stop of volumeID has begun
|
||||
// (its chunk layer is being detached): the lease guard renews at once and
|
||||
// then sleeps at most stopPendingPoll between renewals, instead of its normal
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestImportRejectionNamesTheEntry(t *testing.T) {
|
||||
nodes, err := OpenNodeInventoryStore(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = nodes.ImportNodes([]NodeRegistration{{ServerID: "good", Addr: "127.0.0.1:19001"}, {ServerID: "no-addr"}})
|
||||
if !errors.Is(err, ErrInvalidNodeRegistration) || !strings.Contains(err.Error(), "no-addr") {
|
||||
t.Fatalf("node import error = %v, want ErrInvalidNodeRegistration naming no-addr", err)
|
||||
}
|
||||
if _, ok := nodes.GetNodeSnapshot("good"); ok {
|
||||
t.Fatal("rejected node step published an entry")
|
||||
}
|
||||
if err := nodes.ImportNodes([]NodeRegistration{{ServerID: "good", Addr: "127.0.0.1:19001"}}); err != nil {
|
||||
t.Fatalf("validation rejection blocked the next import: %v", err)
|
||||
}
|
||||
|
||||
placements, err := OpenPlacementIntentStore(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
valid := PlacementPlan{VolumeID: "good", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
|
||||
short := PlacementPlan{VolumeID: "short", DesiredRF: 2, Candidates: valid.Candidates}
|
||||
err = placements.ImportPlans([]PlacementPlan{valid, short})
|
||||
if !errors.Is(err, ErrInsufficientPlacementCandidates) || !strings.Contains(err.Error(), "short") {
|
||||
t.Fatalf("placement import error = %v, want ErrInsufficientPlacementCandidates naming short", err)
|
||||
}
|
||||
if _, ok := placements.GetPlacementSnapshot("good"); ok {
|
||||
t.Fatal("rejected placement step published an entry")
|
||||
}
|
||||
if err := placements.ImportPlans([]PlacementPlan{valid}); err != nil {
|
||||
t.Fatalf("validation rejection blocked the next import: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk(t *testing.T) {
|
||||
for _, kind := range []string{"nodes", "placements"} {
|
||||
for _, mode := range []string{"reopen-barrier", "single-directory", "batch-directory", "batch-second-file"} {
|
||||
t.Run(kind+"/"+mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordEqualityRecoveryChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "RECORD_RECOVERY_KIND="+kind, "RECORD_RECOVERY_MODE="+mode)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("recovery control: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordEqualityRecoveryChild(t *testing.T) {
|
||||
kind := os.Getenv("RECORD_RECOVERY_KIND")
|
||||
if kind == "" {
|
||||
t.Skip("isolated recovery hooks")
|
||||
}
|
||||
mode := os.Getenv("RECORD_RECOVERY_MODE")
|
||||
dir := t.TempDir()
|
||||
fault := errors.New("injected recovery barrier failure")
|
||||
var cause error = fault
|
||||
if mode == "syncfs-second-rename" {
|
||||
cause = os.ErrNotExist
|
||||
}
|
||||
useSyncfs := strings.HasPrefix(mode, "syncfs-")
|
||||
var apply func(bool) error
|
||||
var view func() any
|
||||
var reopen func() error
|
||||
var otherMutations func() []error
|
||||
var setPolicy func(PersistenceFailureHandler)
|
||||
var latched func() bool
|
||||
if kind == "nodes" {
|
||||
var store *NodeInventoryStore
|
||||
reopen = func() error { var err error; store, err = OpenNodeInventoryStore(dir); return err }
|
||||
apply = func(changed bool) error {
|
||||
nodes := []NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001", SeenAt: time.Unix(1, 0).UTC()}, {ServerID: "b", Addr: "127.0.0.1:19001", SeenAt: time.Unix(1, 0).UTC()}}
|
||||
if changed {
|
||||
for i := range nodes {
|
||||
nodes[i].Addr = "127.0.0.1:19002"
|
||||
}
|
||||
}
|
||||
if mode == "single-directory" {
|
||||
_, err := store.RegisterNode(nodes[0])
|
||||
return err
|
||||
}
|
||||
return store.ImportNodes(nodes)
|
||||
}
|
||||
view = func() any { return store.ListNodes() }
|
||||
setPolicy = func(handler PersistenceFailureHandler) { store.SetPersistenceFailureHandler(handler) }
|
||||
latched = func() bool { return store.writeErr != nil }
|
||||
otherMutations = func() []error {
|
||||
_, e := store.RegisterNode(NodeRegistration{ServerID: "c", Addr: "127.0.0.1:19001"})
|
||||
return []error{e, store.ImportNodes(nil), store.RemoveNode("a")}
|
||||
}
|
||||
} else {
|
||||
var store *PlacementIntentStore
|
||||
reopen = func() error { var err error; store, err = OpenPlacementIntentStore(dir); return err }
|
||||
apply = func(changed bool) error {
|
||||
plans := make([]PlacementPlan, 2)
|
||||
for i, id := range []string{"a", "b"} {
|
||||
plans[i] = PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
|
||||
if changed {
|
||||
plans[i].Candidates[0].ReplicaID = "r2"
|
||||
}
|
||||
}
|
||||
if mode == "single-directory" {
|
||||
_, err := store.ApplyPlan(plans[0])
|
||||
return err
|
||||
}
|
||||
return store.ImportPlans(plans)
|
||||
}
|
||||
view = func() any { return store.ListPlacements() }
|
||||
setPolicy = func(handler PersistenceFailureHandler) { store.SetPersistenceFailureHandler(handler) }
|
||||
latched = func() bool { return store.writeErr != nil }
|
||||
otherMutations = func() []error {
|
||||
_, e := store.ApplyPlan(PlacementPlan{VolumeID: "c", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}})
|
||||
return []error{e, store.ImportPlans(nil), store.DeletePlacement("a")}
|
||||
}
|
||||
}
|
||||
if err := reopen(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := apply(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := view()
|
||||
callbacks := 0
|
||||
setPolicy(func(failure *RecordPersistenceError) {
|
||||
callbacks++
|
||||
record := "<import-step>"
|
||||
if mode == "single-directory" {
|
||||
record = "a.json"
|
||||
}
|
||||
if mode == "batch-second-file" || mode == "syncfs-second-rename" {
|
||||
record = "b.json"
|
||||
}
|
||||
if !latched() || failure.Store != dir || failure.Record != record || !errors.Is(failure, cause) {
|
||||
t.Fatalf("incorrect failure-policy context: %+v", failure)
|
||||
}
|
||||
})
|
||||
if mode == "reopen-barrier" {
|
||||
called := 0
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{dirSync: func(path string) error {
|
||||
called++
|
||||
if path != dir {
|
||||
t.Fatal("recovery synced wrong directory")
|
||||
}
|
||||
return fault
|
||||
}})
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
if err := reopen(); !errors.Is(err, fault) {
|
||||
t.Fatalf("loaded records published without a successful recovery barrier: %v calls=%d", err, called)
|
||||
}
|
||||
if called != 1 {
|
||||
t.Fatalf("recovery directory barriers=%d want1", called)
|
||||
}
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
if err := reopen(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(view(), old) {
|
||||
t.Fatal("recovery barrier changed record contents")
|
||||
}
|
||||
return
|
||||
}
|
||||
files, filesystemSyncs, renames, directorySyncs, ioCalls := 0, 0, 0, 0, 0
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs,
|
||||
crash: func(point string) {
|
||||
ioCalls++
|
||||
if point == "before-rename" {
|
||||
renames++
|
||||
if mode == "syncfs-second-rename" && renames == 2 {
|
||||
temps, err := filepath.Glob(filepath.Join(dir, "b.json.*.tmp"))
|
||||
if err != nil || len(temps) != 1 {
|
||||
t.Fatalf("second rename has no unique staged file: %v %v", temps, err)
|
||||
}
|
||||
if err := os.Remove(temps[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
fileSync: func(f *os.File) error {
|
||||
ioCalls++
|
||||
files++
|
||||
if useSyncfs {
|
||||
t.Fatal("batch syncfs control fell back to per-file fsync")
|
||||
}
|
||||
if mode == "batch-second-file" && files == 2 {
|
||||
return fault
|
||||
}
|
||||
return f.Sync()
|
||||
},
|
||||
fsSync: func(fd *os.File) error {
|
||||
ioCalls++
|
||||
filesystemSyncs++
|
||||
if mode == "syncfs-failure" {
|
||||
return fault
|
||||
}
|
||||
return syncRecordFilesystem(fd)
|
||||
},
|
||||
dirSync: func(string) error { ioCalls++; directorySyncs++; return fault },
|
||||
})
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
if err := apply(true); !errors.Is(err, cause) {
|
||||
t.Fatalf("fixture did not expose the failed persistence: %v", err)
|
||||
}
|
||||
if callbacks != 1 {
|
||||
t.Fatalf("failure callbacks=%d want1", callbacks)
|
||||
}
|
||||
if !reflect.DeepEqual(view(), old) {
|
||||
t.Fatal("failed write published its records")
|
||||
}
|
||||
if useSyncfs {
|
||||
wantRenames, wantDirs := 0, 0
|
||||
if mode == "syncfs-second-rename" {
|
||||
wantRenames = 2
|
||||
}
|
||||
if mode == "syncfs-directory" {
|
||||
wantRenames = 2
|
||||
wantDirs = 1
|
||||
}
|
||||
if filesystemSyncs != 1 || renames != wantRenames || directorySyncs != wantDirs || files != 0 {
|
||||
t.Fatalf("failure boundary: syncfs=%d renames=%d dir=%d files=%d", filesystemSyncs, renames, directorySyncs, files)
|
||||
}
|
||||
}
|
||||
beforeRefusals := ioCalls
|
||||
for _, err := range otherMutations() {
|
||||
if !errors.Is(err, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("mutation after uncertainty: %v", err)
|
||||
}
|
||||
}
|
||||
if callbacks != 1 {
|
||||
t.Fatalf("refused mutation called policy again: %d", callbacks)
|
||||
}
|
||||
retryErr := apply(false)
|
||||
if !errors.Is(retryErr, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("old-value retry must require recovery: %v", retryErr)
|
||||
}
|
||||
if callbacks != 1 || ioCalls != beforeRefusals {
|
||||
t.Fatalf("poisoned mutation retried I/O/policy: io=%d/%d callbacks=%d", ioCalls, beforeRefusals, callbacks)
|
||||
}
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
if err := reopen(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if useSyncfs && !reflect.DeepEqual(view(), syncfsFailureReopenedView(old, mode)) {
|
||||
t.Fatalf("reopen did not expose complete records at the injected boundary: got=%+v want=%+v", view(), syncfsFailureReopenedView(old, mode))
|
||||
}
|
||||
if err := apply(false); err != nil {
|
||||
t.Fatalf("recovered store cannot restore the old value: %v", err)
|
||||
}
|
||||
if err := reopen(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(view(), old) {
|
||||
t.Fatal("successful post-recovery write did not match disk")
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestImportStepSyncsChangedFilesThenOneDirectory(t *testing.T) {
|
||||
for _, kind := range []string{"nodes", "placements"} {
|
||||
for _, failure := range []string{"none", "file", "second-file", "directory"} {
|
||||
t.Run(kind+"/"+failure, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportStepSyncChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "IMPORT_STEP_KIND="+kind, "IMPORT_STEP_FAILURE="+failure)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("import control: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportStepSyncChild(t *testing.T) {
|
||||
kind := os.Getenv("IMPORT_STEP_KIND")
|
||||
if kind == "" {
|
||||
t.Skip("isolated filesystem hooks")
|
||||
}
|
||||
failure := os.Getenv("IMPORT_STEP_FAILURE")
|
||||
dir := t.TempDir()
|
||||
var apply func(bool) error
|
||||
var snapshot func() any
|
||||
var reopen func() any
|
||||
var values func() []string
|
||||
var wantValues []string
|
||||
if kind == "nodes" {
|
||||
store, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodes := []NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19001"}, {ServerID: "unchanged", Addr: "127.0.0.1:19001"}}
|
||||
apply = func(change bool) error {
|
||||
next := append([]NodeRegistration(nil), nodes...)
|
||||
if change {
|
||||
next[0].Addr = "127.0.0.1:19002"
|
||||
next[1].Addr = "127.0.0.1:19002"
|
||||
}
|
||||
return store.ImportNodes(next)
|
||||
}
|
||||
snapshot = func() any {
|
||||
var got []NodeRegistration
|
||||
for _, node := range nodes {
|
||||
r, _ := store.GetNodeSnapshot(node.ServerID)
|
||||
got = append(got, r)
|
||||
}
|
||||
return got
|
||||
}
|
||||
values = func() []string {
|
||||
var got []string
|
||||
for _, node := range nodes {
|
||||
r, _ := store.GetNodeSnapshot(node.ServerID)
|
||||
got = append(got, r.Addr)
|
||||
}
|
||||
return got
|
||||
}
|
||||
wantValues = []string{"127.0.0.1:19002", "127.0.0.1:19002", "127.0.0.1:19001"}
|
||||
reopen = func() any {
|
||||
s, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store = s
|
||||
return s.ListNodes()
|
||||
}
|
||||
} else {
|
||||
store, err := OpenPlacementIntentStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plans := make([]PlacementPlan, 3)
|
||||
for i, id := range []string{"a", "b", "unchanged"} {
|
||||
plans[i] = PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
|
||||
}
|
||||
apply = func(change bool) error {
|
||||
next := make([]PlacementPlan, len(plans))
|
||||
copy(next, plans)
|
||||
for i := range next {
|
||||
next[i].Candidates = append([]PlacementCandidate(nil), plans[i].Candidates...)
|
||||
}
|
||||
if change {
|
||||
next[0].Candidates[0].ReplicaID = "r2"
|
||||
next[1].Candidates[0].ReplicaID = "r2"
|
||||
}
|
||||
return store.ImportPlans(next)
|
||||
}
|
||||
snapshot = func() any {
|
||||
var got []PlacementIntent
|
||||
for _, p := range plans {
|
||||
r, _ := store.GetPlacementSnapshot(p.VolumeID)
|
||||
got = append(got, r)
|
||||
}
|
||||
return got
|
||||
}
|
||||
values = func() []string {
|
||||
var got []string
|
||||
for _, p := range plans {
|
||||
r, _ := store.GetPlacementSnapshot(p.VolumeID)
|
||||
if len(r.Slots) != 1 {
|
||||
return nil
|
||||
}
|
||||
got = append(got, r.Slots[0].ReplicaID)
|
||||
}
|
||||
return got
|
||||
}
|
||||
wantValues = []string{"r2", "r2", "r1"}
|
||||
reopen = func() any {
|
||||
s, err := OpenPlacementIntentStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store = s
|
||||
return s.ListPlacements()
|
||||
}
|
||||
}
|
||||
if err := apply(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := snapshot()
|
||||
var events []string
|
||||
fault := errors.New("injected import sync failure")
|
||||
// Qualify the portable per-file fallback independently of the syncfs path.
|
||||
useSyncfs := false
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{
|
||||
batchSyncfs: &useSyncfs,
|
||||
fileSync: func(file *os.File) error {
|
||||
events = append(events, "file")
|
||||
if failure == "file" || failure == "second-file" && len(events) == 2 {
|
||||
return fault
|
||||
}
|
||||
return file.Sync()
|
||||
},
|
||||
dirSync: func(path string) error {
|
||||
events = append(events, "directory")
|
||||
if !reflect.DeepEqual(snapshot(), old) {
|
||||
t.Fatal("step published before its directory barrier")
|
||||
}
|
||||
if path != dir {
|
||||
t.Fatal("wrong import directory barrier")
|
||||
}
|
||||
if failure == "directory" {
|
||||
return fault
|
||||
}
|
||||
return syncBindingParent(path)
|
||||
},
|
||||
})
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
err := apply(true)
|
||||
want := []string{"file", "file", "directory"}
|
||||
if failure == "file" {
|
||||
want = []string{"file"}
|
||||
} else if failure == "second-file" {
|
||||
want = []string{"file", "file"}
|
||||
}
|
||||
if !reflect.DeepEqual(events, want) {
|
||||
t.Fatalf("events %v want %v", events, want)
|
||||
}
|
||||
if failure != "none" {
|
||||
if !errors.Is(err, fault) {
|
||||
t.Fatalf("sync failure hidden: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(snapshot(), old) {
|
||||
t.Fatal("failed step changed the published snapshot")
|
||||
}
|
||||
// A failed step requires recovery before any further mutations.
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
if err := apply(true); !errors.Is(err, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("mutation after failed persistence: %v", err)
|
||||
}
|
||||
reopen()
|
||||
if err := apply(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(); !reflect.DeepEqual(got, wantValues) {
|
||||
t.Fatalf("completed import published %v want %v", got, wantValues)
|
||||
}
|
||||
completed := snapshot()
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
if !reflect.DeepEqual(reopen(), completed) {
|
||||
t.Fatal("completed import did not survive reopen")
|
||||
}
|
||||
if got := values(); !reflect.DeepEqual(got, wantValues) {
|
||||
t.Fatalf("reopened store holds %v want %v", got, wantValues)
|
||||
}
|
||||
events = nil
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{fileSync: func(*os.File) error { return fmt.Errorf("unchanged file synced") }, dirSync: func(string) error { return fmt.Errorf("unchanged directory synced") }})
|
||||
if err := apply(true); err != nil {
|
||||
t.Fatalf("unchanged step did I/O: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,477 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestImportBatchStagesAllFilesBeforeAnyRename(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportBatchStageChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "IMPORT_BATCH_STAGE_CHILD=1")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("batch stage control: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportBatchStageChild(t *testing.T) {
|
||||
if os.Getenv("IMPORT_BATCH_STAGE_CHILD") == "" {
|
||||
t.Skip("isolated filesystem hooks")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
s, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checked := false
|
||||
useSyncfs := true
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs, crash: func(point string) {
|
||||
if point != "before-rename" || checked {
|
||||
return
|
||||
}
|
||||
checked = true
|
||||
temps, err := filepath.Glob(filepath.Join(dir, "*.tmp"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(temps) != 2 {
|
||||
t.Fatalf("first rename has %d staged files, want 2", len(temps))
|
||||
}
|
||||
}})
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
if err := s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !checked {
|
||||
t.Fatal("rename boundary not observed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportSyncfsFailureAndOrdering(t *testing.T) {
|
||||
for _, kind := range []string{"nodes", "placements"} {
|
||||
for _, mode := range []string{"success", "failure", "old-kernel"} {
|
||||
t.Run(kind+"/"+mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportSyncfsChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "IMPORT_SYNCFS_KIND="+kind, "IMPORT_SYNCFS_MODE="+mode)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("syncfs control: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportSyncfsChild(t *testing.T) {
|
||||
kind := os.Getenv("IMPORT_SYNCFS_KIND")
|
||||
if kind == "" {
|
||||
t.Skip("isolated filesystem hooks")
|
||||
}
|
||||
mode := os.Getenv("IMPORT_SYNCFS_MODE")
|
||||
dir := t.TempDir()
|
||||
var apply func() error
|
||||
var reopen func()
|
||||
var snapshot func() int
|
||||
if kind == "nodes" {
|
||||
var s *NodeInventoryStore
|
||||
reopen = func() {
|
||||
var err error
|
||||
s, err = OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
apply = func() error {
|
||||
return s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}})
|
||||
}
|
||||
snapshot = func() int {
|
||||
n := 0
|
||||
for _, id := range []string{"a", "b"} {
|
||||
if _, ok := s.GetNodeSnapshot(id); ok {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
} else {
|
||||
var s *PlacementIntentStore
|
||||
reopen = func() {
|
||||
var err error
|
||||
s, err = OpenPlacementIntentStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
apply = func() error {
|
||||
return s.ImportPlans([]PlacementPlan{{VolumeID: "a", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}, {VolumeID: "b", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}})
|
||||
}
|
||||
snapshot = func() int {
|
||||
n := 0
|
||||
for _, id := range []string{"a", "b"} {
|
||||
if _, ok := s.GetPlacementSnapshot(id); ok {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
}
|
||||
reopen()
|
||||
useSyncfs := mode != "old-kernel"
|
||||
fault := errors.New("injected filesystem writeback failure")
|
||||
var events []string
|
||||
var failedTemps []string
|
||||
install := func(fail bool) {
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{
|
||||
batchSyncfs: &useSyncfs,
|
||||
crash: func(point string) {
|
||||
if point == "batch-open" {
|
||||
temps, _ := filepath.Glob(filepath.Join(dir, "*.tmp"))
|
||||
if len(temps) != 0 {
|
||||
t.Fatal("syncfs fd opened after temp writes")
|
||||
}
|
||||
events = append(events, "open")
|
||||
}
|
||||
if point == "before-rename" {
|
||||
if useSyncfs && !reflect.DeepEqual(events, []string{"open", "syncfs"}) && !reflect.DeepEqual(events, []string{"open", "syncfs", "rename"}) {
|
||||
t.Fatalf("rename before syncfs completed: %v", events)
|
||||
}
|
||||
events = append(events, "rename")
|
||||
}
|
||||
},
|
||||
fileSync: func(f *os.File) error {
|
||||
if useSyncfs {
|
||||
t.Fatal("syncfs path used per-file fsync")
|
||||
}
|
||||
events = append(events, "file")
|
||||
return f.Sync()
|
||||
},
|
||||
fsSync: func(fd *os.File) error {
|
||||
if fd.Name() != dir {
|
||||
t.Fatal("wrong filesystem fd")
|
||||
}
|
||||
for _, name := range []string{"a.json", "b.json"} {
|
||||
if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
|
||||
t.Fatalf("final record visible before syncfs: %s %v", name, err)
|
||||
}
|
||||
}
|
||||
temps, _ := filepath.Glob(filepath.Join(dir, "*.tmp"))
|
||||
if len(temps) != 2 {
|
||||
t.Fatalf("staged temps=%v", temps)
|
||||
}
|
||||
if snapshot() != 0 {
|
||||
t.Fatal("published before syncfs")
|
||||
}
|
||||
if fail {
|
||||
failedTemps = temps
|
||||
events = append(events, "syncfs")
|
||||
return fault
|
||||
}
|
||||
for _, temp := range temps {
|
||||
for _, old := range failedTemps {
|
||||
if temp == old {
|
||||
t.Fatal("reused failed temp")
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := syncRecordFilesystem(fd); err != nil {
|
||||
return err
|
||||
}
|
||||
events = append(events, "syncfs")
|
||||
return nil
|
||||
},
|
||||
dirSync: func(path string) error {
|
||||
if snapshot() != 0 {
|
||||
t.Fatal("published before directory barrier")
|
||||
}
|
||||
events = append(events, "directory")
|
||||
return syncBindingParent(path)
|
||||
},
|
||||
})
|
||||
}
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
install(mode == "failure")
|
||||
err := apply()
|
||||
if mode == "failure" {
|
||||
if !errors.Is(err, fault) || !reflect.DeepEqual(events, []string{"open", "syncfs"}) {
|
||||
t.Fatalf("failed syncfs retried/renamed: %v %v", events, err)
|
||||
}
|
||||
if snapshot() != 0 {
|
||||
t.Fatal("failed import published")
|
||||
}
|
||||
if err := apply(); !errors.Is(err, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("failed store admitted retry: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(events, []string{"open", "syncfs"}) {
|
||||
t.Fatal("poisoned retry performed I/O")
|
||||
}
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
reopen()
|
||||
events = nil
|
||||
install(false)
|
||||
err = apply()
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"open", "syncfs", "rename", "rename", "directory"}
|
||||
if !useSyncfs {
|
||||
want = []string{"file", "rename", "file", "rename", "directory"}
|
||||
}
|
||||
if !reflect.DeepEqual(events, want) {
|
||||
t.Fatalf("events=%v want=%v", events, want)
|
||||
}
|
||||
if snapshot() != 2 {
|
||||
t.Fatal("successful import not published")
|
||||
}
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
reopen()
|
||||
if snapshot() != 2 {
|
||||
t.Fatal("completed import lost on reopen")
|
||||
}
|
||||
}
|
||||
|
||||
// Returned-error controls complement the process-crash ordering controls:
|
||||
// the published view stays old while complete disk records may be old or new.
|
||||
func TestImportSyncfsReturnedFailurePolicyAndReplay(t *testing.T) {
|
||||
for _, kind := range []string{"nodes", "placements"} {
|
||||
for _, mode := range []string{"syncfs-failure", "syncfs-second-rename", "syncfs-directory"} {
|
||||
t.Run(kind+"/"+mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordEqualityRecoveryChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "RECORD_RECOVERY_KIND="+kind, "RECORD_RECOVERY_MODE="+mode)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("returned syncfs failure control: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func syncfsFailureReopenedView(old any, mode string) any {
|
||||
changed := func(id string) bool {
|
||||
return mode == "syncfs-directory" || (mode == "syncfs-second-rename" && id == "a")
|
||||
}
|
||||
switch records := old.(type) {
|
||||
case []NodeRegistration:
|
||||
out := make([]NodeRegistration, len(records))
|
||||
for i, rec := range records {
|
||||
out[i] = copyNodeRegistration(rec)
|
||||
if changed(rec.ServerID) {
|
||||
out[i].Addr = "127.0.0.1:19002"
|
||||
}
|
||||
}
|
||||
return out
|
||||
case []PlacementIntent:
|
||||
out := make([]PlacementIntent, len(records))
|
||||
for i, rec := range records {
|
||||
out[i] = copyPlacementIntent(rec)
|
||||
if changed(rec.VolumeID) {
|
||||
out[i].Slots[0].ReplicaID = "r2"
|
||||
}
|
||||
}
|
||||
return out
|
||||
default:
|
||||
panic("unexpected fixture records")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncfsKernelGate(t *testing.T) {
|
||||
for release, want := range map[string]bool{"5.7.19": false, "5.8.0": true, "6.8.0-azure": true, "4.19.0": false, "unknown": false, "5.x.0": false} {
|
||||
if got := kernelHasSyncfsErrors(release); got != want {
|
||||
t.Errorf("%s: got %v want %v", release, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportSyncfsCrashBoundaries(t *testing.T) {
|
||||
for _, point := range []string{"before-syncfs", "after-syncfs", "after-rename"} {
|
||||
t.Run(point, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportSyncfsCrashChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "IMPORT_CRASH_DIR="+dir, "IMPORT_CRASH_POINT="+point)
|
||||
out, err := cmd.CombinedOutput()
|
||||
var exit *exec.ExitError
|
||||
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 86 {
|
||||
t.Fatalf("crash child: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
s, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := 0
|
||||
if point == "after-rename" {
|
||||
want = 1
|
||||
}
|
||||
if len(s.ListNodes()) != want {
|
||||
t.Fatalf("reopen records=%v want=%d", s.ListNodes(), want)
|
||||
}
|
||||
for _, rec := range s.ListNodes() {
|
||||
if rec.ServerID != "a" || rec.Addr != "127.0.0.1:19001" {
|
||||
t.Fatalf("incomplete record: %+v", rec)
|
||||
}
|
||||
}
|
||||
// A malformed final name is refused, never silently admitted; leftover
|
||||
// unsynced temp names are ignored. This is a process-crash ordering
|
||||
// control, not a claim to simulate a machine power loss.
|
||||
if err := os.WriteFile(filepath.Join(dir, "broken.json"), []byte(`{"server_id":`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := OpenNodeInventoryStore(dir); err == nil {
|
||||
t.Fatal("torn JSON accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportSyncfsCrashChild(t *testing.T) {
|
||||
dir := os.Getenv("IMPORT_CRASH_DIR")
|
||||
if dir == "" {
|
||||
t.Skip("bounded crash child")
|
||||
}
|
||||
s, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
useSyncfs := true
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs, crash: func(point string) {
|
||||
if point == os.Getenv("IMPORT_CRASH_POINT") {
|
||||
os.Exit(86)
|
||||
}
|
||||
}})
|
||||
if err := s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := json.Marshal(s.ListNodes())
|
||||
t.Fatalf("crash boundary not reached: %s", raw)
|
||||
}
|
||||
|
||||
func TestSyncfsFilesystemGate(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
magic uint32
|
||||
want bool
|
||||
}{
|
||||
"ext4": {unix.EXT4_SUPER_MAGIC, true}, "xfs": {unix.XFS_SUPER_MAGIC, true}, "btrfs": {unix.BTRFS_SUPER_MAGIC, true}, "tmpfs": {unix.TMPFS_MAGIC, true},
|
||||
"overlay": {unix.OVERLAYFS_SUPER_MAGIC, false}, "fuse": {unix.FUSE_SUPER_MAGIC, false}, "nfs": {unix.NFS_SUPER_MAGIC, false}, "unknown": {0, false},
|
||||
} {
|
||||
if got := filesystemReportsSyncfsErrors(tc.magic); got != tc.want {
|
||||
t.Errorf("%s: got %v want %v", name, got, tc.want)
|
||||
}
|
||||
}
|
||||
if recordBatchSyncfsSupported(filepath.Join(t.TempDir(), "missing")) {
|
||||
t.Error("an unreadable records directory selected syncfs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportBatchSelectsSyncfsByFilesystem(t *testing.T) {
|
||||
for _, fs := range []string{"overlay", "ext4"} {
|
||||
t.Run(fs, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportBatchSelectChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "IMPORT_BATCH_SELECT_FS="+fs)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("selector control: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportBatchSelectChild(t *testing.T) {
|
||||
fs := os.Getenv("IMPORT_BATCH_SELECT_FS")
|
||||
if fs == "" {
|
||||
t.Skip("isolated filesystem hooks")
|
||||
}
|
||||
if !recordKernelSyncfsErrors {
|
||||
t.Skip("kernel does not report writeback errors through syncfs")
|
||||
}
|
||||
magic, wantSyncfs := uint32(unix.OVERLAYFS_SUPER_MAGIC), false
|
||||
if fs == "ext4" {
|
||||
magic, wantSyncfs = unix.EXT4_SUPER_MAGIC, true
|
||||
}
|
||||
dir := t.TempDir()
|
||||
s, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var syncfsCalls, fileSyncs int
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{
|
||||
statfsType: func(string, uint32) uint32 { return magic },
|
||||
fsSync: func(f *os.File) error {
|
||||
syncfsCalls++
|
||||
return syncRecordFilesystem(f)
|
||||
},
|
||||
fileSync: func(f *os.File) error {
|
||||
fileSyncs++
|
||||
return f.Sync()
|
||||
},
|
||||
})
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
if mode := s.ImportDurabilityMode(); strings.HasPrefix(mode, "syncfs") != wantSyncfs {
|
||||
t.Fatalf("%s reports %q", fs, mode)
|
||||
}
|
||||
if err := s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if wantSyncfs && (syncfsCalls != 1 || fileSyncs != 0) || !wantSyncfs && (syncfsCalls != 0 || fileSyncs != 2) {
|
||||
t.Fatalf("%s import: %d syncfs, %d file syncs", fs, syncfsCalls, fileSyncs)
|
||||
}
|
||||
if len(s.ListNodes()) != 2 {
|
||||
t.Fatalf("imported %d nodes", len(s.ListNodes()))
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportDurabilityModeProbesEachStoreDirectory(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportDurabilityModeChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "IMPORT_MODE_CHILD=1")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("mode control: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportDurabilityModeChild(t *testing.T) {
|
||||
if os.Getenv("IMPORT_MODE_CHILD") == "" {
|
||||
t.Skip("isolated filesystem hooks")
|
||||
}
|
||||
if !recordKernelSyncfsErrors {
|
||||
t.Skip("kernel does not report writeback errors through syncfs")
|
||||
}
|
||||
root := t.TempDir()
|
||||
nodes, err := OpenNodeInventoryStore(filepath.Join(root, "nodes"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
placements, err := OpenPlacementIntentStore(filepath.Join(root, "placements"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{statfsType: func(dir string, _ uint32) uint32 {
|
||||
if dir == filepath.Join(root, "nodes") {
|
||||
return unix.EXT4_SUPER_MAGIC
|
||||
}
|
||||
return unix.OVERLAYFS_SUPER_MAGIC
|
||||
}})
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
nodeMode, placementMode := nodes.ImportDurabilityMode(), placements.ImportDurabilityMode()
|
||||
if !strings.HasPrefix(nodeMode, "syncfs") || strings.HasPrefix(placementMode, "syncfs") {
|
||||
t.Fatalf("nodes on ext4 report %q, placements on overlay report %q", nodeMode, placementMode)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 414 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user