mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
Compare 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.
|
||||
|
||||
+1042
-1030
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 54 KiB |
+4
-5
@@ -11,14 +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_store_file.go DeleteRetire.RetireLine
|
||||
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
|
||||
@@ -36,7 +36,7 @@ core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
|
||||
core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
|
||||
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
|
||||
@@ -187,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
|
||||
|
||||
|
@@ -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,113 +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/authority"
|
||||
"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() != authority.ExitDurabilityUnknown {
|
||||
t.Fatalf("master did not fail-stop with exit74: %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, "reason=lifecycle_persist_failed") || !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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,13 +26,6 @@ import (
|
||||
// refuses an interval above half the freshness window (a longer loop gap
|
||||
// reads as the master's own pause), so the window is 60 s: the dead
|
||||
// primary's loss then comes at most a window after its last report.
|
||||
//
|
||||
// The failover is predicted within gapLoop + gapWindow + gapLoop of the
|
||||
// kill: the tick that ends creation comes at most a loop after it, the
|
||||
// loss a window after that tick's silence floor, and the tick that reads
|
||||
// the loss at most a loop later. The test waits twice that.
|
||||
const gapLoop, gapWindow = 30 * time.Second, 60 * time.Second
|
||||
|
||||
func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
|
||||
bins := buildG54Binaries(t)
|
||||
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
|
||||
@@ -55,8 +48,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
|
||||
}
|
||||
master := h.start(t, "blockmaster", bins.master,
|
||||
"--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"),
|
||||
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", gapLoop.String(),
|
||||
"--freshness-window", gapWindow.String(), "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
|
||||
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s",
|
||||
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
|
||||
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
|
||||
for _, b := range hosts {
|
||||
lockDir := b.root + ".locks"
|
||||
@@ -91,8 +84,7 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
|
||||
// 3. The next tick reads the survivors' write: creation ended, and the
|
||||
// gate fails the volume over.
|
||||
var p2 *host
|
||||
predicted := gapLoop + gapWindow + gapLoop
|
||||
poll(t, 2*predicted, fmt.Sprintf("no survivor became primary at epoch 2 within %v, twice the predicted %v (the volume held as creating, or the gate's replace not acted on: see the master's 'decision=replace' lines)", 2*predicted, predicted), func() bool {
|
||||
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
|
||||
for _, b := range survivors {
|
||||
if statusIsPrimaryAt(b.status, 2) {
|
||||
p2 = b
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -32,9 +32,8 @@ func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) {
|
||||
// non-nil error replaces that step's result. Tests only.
|
||||
var dirFault atomic.Pointer[func(step string) error]
|
||||
|
||||
// ExitDurabilityUnknown is the process exit code of a fail-stop whose
|
||||
// persisted outcome is unknown (sysexits EX_IOERR): an authority record's
|
||||
// rename here, or blockmaster's lifecycle store persistence failure.
|
||||
// ExitDurabilityUnknown is the process exit code of the fail-stop after a
|
||||
// record's rename whose durability is unknown (sysexits EX_IOERR).
|
||||
const ExitDurabilityUnknown = 74
|
||||
|
||||
// failStopDurabilityUnknown ends the process: the rename is done but the
|
||||
|
||||
@@ -32,7 +32,6 @@ type TopologyController struct {
|
||||
unsupported map[string]UnsupportedEvidence
|
||||
convergenceStuck map[string]*ConvergenceStuckEvidence
|
||||
bootGrace map[string]*primaryBootGrace // volume/replica -> current incarnation's grace
|
||||
outcome map[string]string // volume -> what the last intake did with it (LastOutcome); kept like bootGrace
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
@@ -45,21 +44,10 @@ func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasi
|
||||
unsupported: make(map[string]UnsupportedEvidence),
|
||||
convergenceStuck: make(map[string]*ConvergenceStuckEvidence),
|
||||
bootGrace: make(map[string]*primaryBootGrace),
|
||||
outcome: make(map[string]string),
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// LastOutcome says what the last snapshot intake that carried the volume
|
||||
// as supported did with it: the ask it enqueued, or why it enqueued none
|
||||
// ("" before any). The master logs it beside a promotion gate's replace
|
||||
// decision, so a decision the controller did not act on says why.
|
||||
func (c *TopologyController) LastOutcome(volumeID string) string {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.outcome[volumeID]
|
||||
}
|
||||
|
||||
// SetNowForTest overrides the controller's clock source. Tests
|
||||
// use this to drive RetryWindow / Stuck transitions deterministically.
|
||||
// Production code MUST NOT call this.
|
||||
@@ -137,21 +125,6 @@ func (c *TopologyController) SubmitClusterSnapshot(snap ClusterSnapshot) error {
|
||||
// desired state live; SubmitObservedState always processes the
|
||||
// report.
|
||||
func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error {
|
||||
return c.submitObservedState(snap, report, nil)
|
||||
}
|
||||
|
||||
// SubmitObservedStateOutcomes is SubmitObservedState that also returns what
|
||||
// this intake did with each volume it carried (supported, pending or
|
||||
// unsupported), read while the intake still holds the controller's lock: a
|
||||
// later intake (the background observation host shares the controller)
|
||||
// cannot change it. A volume this intake did not carry has no entry.
|
||||
func (c *TopologyController) SubmitObservedStateOutcomes(snap ClusterSnapshot, report SupportabilityReport) (map[string]string, error) {
|
||||
out := map[string]string{}
|
||||
err := c.submitObservedState(snap, report, out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report SupportabilityReport, outcomes map[string]string) error {
|
||||
// Validate non-empty supported snapshots the same way
|
||||
// SubmitClusterSnapshot does. Empty supported + empty report
|
||||
// is allowed (no-op).
|
||||
@@ -190,7 +163,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
|
||||
// stale unsupported record from a prior build is cleared,
|
||||
// because pending is a transitional state, not a fault.
|
||||
delete(c.unsupported, vid)
|
||||
c.outcome[vid] = "no ask: supportability pending"
|
||||
}
|
||||
for vid, ev := range report.Unsupported {
|
||||
c.clearDesiredLocked(vid)
|
||||
@@ -208,7 +180,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
|
||||
Basis: AuthorityBasis{},
|
||||
Reason: joinReasons(ev.Reasons),
|
||||
}
|
||||
c.outcome[vid] = "no ask: unsupported: " + joinReasons(ev.Reasons)
|
||||
}
|
||||
|
||||
// Process supported volumes via the existing decision path.
|
||||
@@ -225,17 +196,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
|
||||
currentLine, hasLine := c.reader.VolumeAuthorityLine(vol.VolumeID)
|
||||
c.processSupportedVolumeLocked(vol, snap, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
|
||||
}
|
||||
if outcomes != nil {
|
||||
for vid := range report.Pending {
|
||||
outcomes[vid] = c.outcome[vid]
|
||||
}
|
||||
for vid := range report.Unsupported {
|
||||
outcomes[vid] = c.outcome[vid]
|
||||
}
|
||||
for _, vol := range volumes {
|
||||
outcomes[vol.VolumeID] = c.outcome[vol.VolumeID]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -292,13 +252,11 @@ func (c *TopologyController) processSupportedVolumeLocked(
|
||||
if vol.Authority.Assigned && !volumeIncludesReplica(vol, vol.Authority.ReplicaID) {
|
||||
c.recordUnsupportedLocked(vol.VolumeID, snap, vol.Authority, "snapshot authority outside accepted topology: "+vol.Authority.ReplicaID)
|
||||
c.clearDesiredLocked(vol.VolumeID)
|
||||
c.outcome[vol.VolumeID] = "no ask: snapshot authority outside accepted topology"
|
||||
return
|
||||
}
|
||||
if hasLine && !volumeIncludesReplica(vol, currentLine.ReplicaID) {
|
||||
c.recordUnsupportedLocked(vol.VolumeID, snap, currentLine, "publisher authority on replica outside accepted topology: "+currentLine.ReplicaID)
|
||||
c.clearDesiredLocked(vol.VolumeID)
|
||||
c.outcome[vol.VolumeID] = "no ask: publisher authority outside accepted topology"
|
||||
return
|
||||
}
|
||||
|
||||
@@ -311,44 +269,24 @@ func (c *TopologyController) processSupportedVolumeLocked(
|
||||
// Stale snapshot: do not emit from a stale basis, but keep any
|
||||
// existing desired (publish-until-observed convergence record).
|
||||
if !basisMatchesLine(vol.Authority, currentLine, hasLine) {
|
||||
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: stale snapshot basis %s@%d, line %s@%d", vol.Authority.ReplicaID, vol.Authority.Epoch, currentLine.ReplicaID, currentLine.Epoch)
|
||||
return
|
||||
}
|
||||
// Stale slot facts: likewise keep any existing desired and emit
|
||||
// nothing from this snapshot.
|
||||
if staleFacts {
|
||||
c.outcome[vol.VolumeID] = "no ask: superseded slot facts"
|
||||
return
|
||||
}
|
||||
|
||||
ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
|
||||
if !emit {
|
||||
c.clearDesiredLocked(vol.VolumeID)
|
||||
c.outcome[vol.VolumeID] = "no ask: " + reason
|
||||
return
|
||||
}
|
||||
// Same-ask dedupe: while the identical ask is pending (queued, or
|
||||
// taken by the publisher and still being applied), do not
|
||||
// re-enqueue. Without this guard, repeated identical supported
|
||||
// feeds would mint a new Reassign epoch each iteration —
|
||||
// authority churn. An identical ask that is no longer pending
|
||||
// ended without a publication (lost): enqueue it again, keeping
|
||||
// its DesiredAt so a repeatedly lost ask still reports Stuck.
|
||||
// Same-ask dedupe: if the identical ask is already the current
|
||||
// desired, do not re-enqueue. Without this guard, repeated
|
||||
// identical supported feeds would mint a new Reassign epoch
|
||||
// each iteration — authority churn.
|
||||
if prev, ok := c.desired[vol.VolumeID]; ok && sameAsk(prev.Ask, ask) {
|
||||
since := prev.DesiredAt.UTC().Format(time.RFC3339Nano)
|
||||
if c.queue.pending(vol.VolumeID) {
|
||||
c.outcome[vol.VolumeID] = fmt.Sprintf("already desired since %s: %s %s (%s)", since, ask.Intent, ask.ReplicaID, prev.Reason)
|
||||
return
|
||||
}
|
||||
// Not pending also after the publisher published it since the line
|
||||
// was read: lost only while the line is still the one decided against.
|
||||
if line, ok := c.reader.VolumeAuthorityLine(vol.VolumeID); ok != hasLine || line != currentLine {
|
||||
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: the line moved to %s@%d while deciding against %s@%d", line.ReplicaID, line.Epoch, currentLine.ReplicaID, currentLine.Epoch)
|
||||
return
|
||||
}
|
||||
c.queue.enqueue(ask)
|
||||
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued again %s %s (%s): desired since %s, its last ask ended without a publication", ask.Intent, ask.ReplicaID, prev.Reason, since)
|
||||
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -370,7 +308,6 @@ func (c *TopologyController) processSupportedVolumeLocked(
|
||||
}
|
||||
c.desired[vol.VolumeID] = desired
|
||||
c.queue.enqueue(ask)
|
||||
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued %s %s (%s)", ask.Intent, ask.ReplicaID, reason)
|
||||
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
|
||||
}
|
||||
|
||||
@@ -535,7 +472,7 @@ func (c *TopologyController) decideVolume(
|
||||
if !hasLine {
|
||||
cands := placeableCandidates(vol, serverIndex)
|
||||
if len(cands) == 0 {
|
||||
return AssignmentAsk{}, "no placeable candidate for the first line", false
|
||||
return AssignmentAsk{}, "", false
|
||||
}
|
||||
best := choosePlacementCandidate(cands, projectedLoad)
|
||||
return AssignmentAsk{
|
||||
@@ -550,7 +487,7 @@ func (c *TopologyController) decideVolume(
|
||||
|
||||
current, ok := candidateByReplica(vol, currentLine.ReplicaID)
|
||||
if !ok {
|
||||
return AssignmentAsk{}, "the line's replica is not in the snapshot", false
|
||||
return AssignmentAsk{}, "", false
|
||||
}
|
||||
|
||||
if candidateAcceptable(current, serverIndex) {
|
||||
@@ -563,20 +500,19 @@ func (c *TopologyController) decideVolume(
|
||||
// current primary is alive, so it is a planned move: the same
|
||||
// guard as a failback (the target in every acknowledgement set).
|
||||
if target.PromotionEvidence.Kind != adapter.PrimaryKindPromotion || !target.PlannedMoveAllowed {
|
||||
return AssignmentAsk{}, "the current primary is acceptable; rebalance target " + target.ReplicaID + " has no planned-move evidence", false
|
||||
return AssignmentAsk{}, "", false
|
||||
}
|
||||
return AssignmentAsk{
|
||||
VolumeID: vol.VolumeID,
|
||||
ReplicaID: target.ReplicaID,
|
||||
DataAddr: target.DataAddr,
|
||||
CtrlAddr: target.CtrlAddr,
|
||||
Intent: IntentReassign,
|
||||
Evidence: plannedEvidence(target.PromotionEvidence),
|
||||
Incarnation: target.Incarnation,
|
||||
ExpectCurrent: expectedLineOf(currentLine),
|
||||
VolumeID: vol.VolumeID,
|
||||
ReplicaID: target.ReplicaID,
|
||||
DataAddr: target.DataAddr,
|
||||
CtrlAddr: target.CtrlAddr,
|
||||
Intent: IntentReassign,
|
||||
Evidence: plannedEvidence(target.PromotionEvidence),
|
||||
Incarnation: target.Incarnation,
|
||||
}, "rebalance", true
|
||||
}
|
||||
return AssignmentAsk{}, "the current primary is acceptable", false
|
||||
return AssignmentAsk{}, "", false
|
||||
}
|
||||
|
||||
// A restarted current primary that is placeable but not ready yet
|
||||
@@ -586,13 +522,9 @@ func (c *TopologyController) decideVolume(
|
||||
if !superseded && endpointStale(current, currentLine) {
|
||||
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh (primary boot grace)", true
|
||||
}
|
||||
if superseded {
|
||||
return AssignmentAsk{}, "the current primary holds its boot grace (by its newer recorded fact)", false
|
||||
}
|
||||
return AssignmentAsk{}, "the current primary holds its boot grace", false
|
||||
return AssignmentAsk{}, "", false
|
||||
}
|
||||
|
||||
why := "no acceptable candidate besides the current primary"
|
||||
other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID)
|
||||
if len(other) > 0 {
|
||||
best := chooseFailoverCandidate(other, projectedLoad)
|
||||
@@ -600,17 +532,15 @@ func (c *TopologyController) decideVolume(
|
||||
// its target (one decider): no evidence, no promotion.
|
||||
if best.PromotionEvidence.Kind == adapter.PrimaryKindPromotion {
|
||||
return AssignmentAsk{
|
||||
VolumeID: vol.VolumeID,
|
||||
ReplicaID: best.ReplicaID,
|
||||
DataAddr: best.DataAddr,
|
||||
CtrlAddr: best.CtrlAddr,
|
||||
Intent: IntentReassign,
|
||||
Evidence: best.PromotionEvidence,
|
||||
Incarnation: best.Incarnation,
|
||||
ExpectCurrent: expectedLineOf(currentLine),
|
||||
VolumeID: vol.VolumeID,
|
||||
ReplicaID: best.ReplicaID,
|
||||
DataAddr: best.DataAddr,
|
||||
CtrlAddr: best.CtrlAddr,
|
||||
Intent: IntentReassign,
|
||||
Evidence: best.PromotionEvidence,
|
||||
Incarnation: best.Incarnation,
|
||||
}, "failover", true
|
||||
}
|
||||
why = "failover target " + best.ReplicaID + " has no promotion evidence"
|
||||
}
|
||||
// No promotion-ready peer exists. Keep the current authority endpoint fresh
|
||||
// when the current replica is still reachable/eligible; this preserves
|
||||
@@ -618,7 +548,7 @@ func (c *TopologyController) decideVolume(
|
||||
if candidatePlaceable(current, serverIndex) && endpointStale(current, currentLine) {
|
||||
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh", true
|
||||
}
|
||||
return AssignmentAsk{}, why, false
|
||||
return AssignmentAsk{}, "", false
|
||||
}
|
||||
|
||||
// endpointStale reports whether the current primary's line needs a new
|
||||
@@ -641,17 +571,10 @@ func refreshAsk(volumeID string, current ReplicaCandidate, line AuthorityBasis)
|
||||
CtrlAddr: current.CtrlAddr,
|
||||
Intent: IntentRefreshEndpoint,
|
||||
Incarnation: current.Incarnation,
|
||||
ExpectCurrent: expectedLineOf(line),
|
||||
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr},
|
||||
}
|
||||
}
|
||||
|
||||
// expectedLineOf conditions an ask on the line it was decided against: a
|
||||
// publication that lands while the ask waits in the queue (an operator's
|
||||
// failback) refuses it instead of being overwritten.
|
||||
func expectedLineOf(line AuthorityBasis) *ExpectedLine {
|
||||
return &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}
|
||||
}
|
||||
|
||||
func volumeIncludesReplica(vol VolumeTopologySnapshot, replicaID string) bool {
|
||||
for _, slot := range vol.Slots {
|
||||
if slot.ReplicaID == replicaID {
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
)
|
||||
|
||||
// The same-ask dedupe holds a desired Reassign only while that ask is
|
||||
// pending: queued, or taken by the publisher and still being applied. An
|
||||
// ask the publisher took and ended without publishing (its apply refused
|
||||
// it) is lost, and the next intake of the same state enqueues it again.
|
||||
// Holding the lost ask as "already desired" would keep the volume on its
|
||||
// old primary for good.
|
||||
func TestALostReassignIsEnqueuedAgainOnTheNextIntake(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
reader := newFakeBasisReader()
|
||||
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
|
||||
reader.Set("v1", "r1", line)
|
||||
ctrl := NewTopologyController(TopologyControllerConfig{}, reader)
|
||||
r1 := candidate("r1", "s1", "d1", "c1", 10)
|
||||
r1.Reachable = false
|
||||
snap := ClusterSnapshot{
|
||||
CollectedRevision: 2,
|
||||
Servers: []ServerObservation{
|
||||
{ServerID: "s1", Reachable: true, Eligible: true},
|
||||
{ServerID: "s2", Reachable: true, Eligible: true},
|
||||
{ServerID: "s3", Reachable: true, Eligible: true},
|
||||
},
|
||||
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
|
||||
}
|
||||
submit := func() {
|
||||
t.Helper()
|
||||
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
submit()
|
||||
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
|
||||
t.Fatalf("first intake: %+v, want Reassign r2", ask)
|
||||
}
|
||||
|
||||
// The publisher holds the ask (applying it): the same state again is
|
||||
// deduplicated, nothing is queued twice.
|
||||
submit()
|
||||
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "already desired since ") {
|
||||
t.Fatalf("while the ask is being applied: outcome %q, want already desired", out)
|
||||
}
|
||||
|
||||
// The apply ended without a publication (the line is still r1@1) and
|
||||
// the publisher waits for its next ask: the ask is lost.
|
||||
next := make(chan AssignmentAsk, 1)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
go func() {
|
||||
if ask, err := ctrl.Next(ctx); err == nil {
|
||||
next <- ask
|
||||
}
|
||||
}()
|
||||
synctest.Wait() // the publisher is back in Next, holding nothing
|
||||
submit()
|
||||
select {
|
||||
case ask := <-next:
|
||||
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
|
||||
t.Fatalf("after the loss: %+v, want Reassign r2 again", ask)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("a lost Reassign was never enqueued again; the controller's outcome: %q", ctrl.LastOutcome("v1"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A Reassign lost again and again keeps its first DesiredAt across every
|
||||
// re-enqueue, so it still becomes Stuck once the retry window passes from
|
||||
// that first desire: a retry that re-anchored DesiredAt would never report
|
||||
// the volume stuck however long its asks keep failing.
|
||||
func TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck(t *testing.T) {
|
||||
const window = 10 * time.Second
|
||||
reader := newFakeBasisReader()
|
||||
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
|
||||
reader.Set("v1", "r1", line)
|
||||
ctrl := NewTopologyController(TopologyControllerConfig{RetryWindow: window}, reader)
|
||||
clk := newFakeClock(time.Date(2026, 12, 5, 9, 0, 0, 0, time.UTC))
|
||||
ctrl.SetNowForTest(clk.Now)
|
||||
r1 := candidate("r1", "s1", "d1", "c1", 10)
|
||||
r1.Reachable = false
|
||||
snap := ClusterSnapshot{
|
||||
CollectedRevision: 2,
|
||||
Servers: []ServerObservation{
|
||||
{ServerID: "s1", Reachable: true, Eligible: true},
|
||||
{ServerID: "s2", Reachable: true, Eligible: true},
|
||||
{ServerID: "s3", Reachable: true, Eligible: true},
|
||||
},
|
||||
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
|
||||
}
|
||||
first := clk.Now()
|
||||
ended, cancel := context.WithCancel(context.Background())
|
||||
cancel() // the publisher's next call after an apply that published nothing
|
||||
for cycle := 0; cycle < 4; cycle++ {
|
||||
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cycle > 0 && !strings.HasPrefix(ctrl.LastOutcome("v1"), "enqueued again Reassign r2") {
|
||||
t.Fatalf("cycle %d: outcome %q, want the lost ask enqueued again", cycle, ctrl.LastOutcome("v1"))
|
||||
}
|
||||
if d, ok := ctrl.DesiredFor("v1"); !ok || !d.DesiredAt.Equal(first) {
|
||||
t.Fatalf("cycle %d at +%v: desired %+v (ok=%v), want DesiredAt kept at the first desire %v", cycle, clk.Now().Sub(first), d, ok, first)
|
||||
}
|
||||
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
|
||||
t.Fatalf("cycle %d: took %+v, want Reassign r2", cycle, ask)
|
||||
}
|
||||
_, _ = ctrl.Next(ended) // the apply ended without a publication: the ask is lost
|
||||
clk.Advance(4 * time.Second)
|
||||
}
|
||||
// +16 s since the first desire, past the 10 s window: the latest intake
|
||||
// (+12 s) found the desire unconfirmed past the window.
|
||||
ev, stuck := ctrl.LastConvergenceStuck("v1")
|
||||
if !stuck {
|
||||
t.Fatalf("a Reassign lost on every apply for %v is not reported stuck (window %v)", clk.Now().Sub(first), window)
|
||||
}
|
||||
if !ev.DesiredAt.Equal(first) || ev.Ask.ReplicaID != "r2" {
|
||||
t.Fatalf("stuck evidence %+v, want the first desire (%v) of Reassign r2", ev, first)
|
||||
}
|
||||
}
|
||||
|
||||
// publishOnRead runs publish once, right after the controller's skip+1-th
|
||||
// line read: the publisher applies its ask between the read an intake decides
|
||||
// against and that intake's dedupe.
|
||||
type publishOnRead struct {
|
||||
*fakeBasisReader
|
||||
skip int
|
||||
publish func()
|
||||
}
|
||||
|
||||
func (r *publishOnRead) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) {
|
||||
line, ok := r.fakeBasisReader.VolumeAuthorityLine(volumeID)
|
||||
if r.publish != nil {
|
||||
if r.skip > 0 {
|
||||
r.skip--
|
||||
} else {
|
||||
p := r.publish
|
||||
r.publish = nil
|
||||
p()
|
||||
}
|
||||
}
|
||||
return line, ok
|
||||
}
|
||||
|
||||
// An ask the publisher publishes, and then asks past, while an intake is
|
||||
// deciding against the line read before that publication is not lost: the
|
||||
// intake must not enqueue it again, or a planned move would be minted twice.
|
||||
func TestAnAskPublishedDuringTheIntakeIsNotEnqueuedAgain(t *testing.T) {
|
||||
reader := newFakeBasisReader()
|
||||
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
|
||||
reader.Set("v1", "r1", line)
|
||||
publishing := &publishOnRead{fakeBasisReader: reader}
|
||||
ctrl := NewTopologyController(TopologyControllerConfig{}, publishing)
|
||||
r1 := candidate("r1", "s1", "d1", "c1", 10)
|
||||
r1.Reachable = false
|
||||
snap := ClusterSnapshot{
|
||||
CollectedRevision: 2,
|
||||
Servers: []ServerObservation{
|
||||
{ServerID: "s1", Reachable: true, Eligible: true},
|
||||
{ServerID: "s2", Reachable: true, Eligible: true},
|
||||
{ServerID: "s3", Reachable: true, Eligible: true},
|
||||
},
|
||||
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
|
||||
}
|
||||
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
|
||||
t.Fatalf("first intake: %+v, want Reassign r2", ask)
|
||||
}
|
||||
ended, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
publishing.skip = 1 // the intake's load count reads the line first
|
||||
publishing.publish = func() {
|
||||
reader.Set("v1", "r2", AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"})
|
||||
_, _ = ctrl.Next(ended) // published: the publisher is back for its next ask
|
||||
}
|
||||
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out := ctrl.LastOutcome("v1"); strings.HasPrefix(out, "enqueued again") {
|
||||
t.Fatalf("an ask published during the intake was enqueued again: %q", out)
|
||||
}
|
||||
expectNoNext(t, ctrl)
|
||||
}
|
||||
|
||||
// A controller Reassign waits in the queue until the publisher takes it. A
|
||||
// publication that lands meanwhile outside the queue (an operator's failback)
|
||||
// is not overwritten by the ask decided against the older line, whether the
|
||||
// ask is a first one or a lost one enqueued again.
|
||||
func TestAQueuedReassignDoesNotOverwriteALaterPublication(t *testing.T) {
|
||||
for _, lost := range []bool{false, true} {
|
||||
holder := &basisReaderHolder{}
|
||||
ctrl := NewTopologyController(TopologyControllerConfig{}, holder)
|
||||
pub := NewPublisher(ctrl)
|
||||
holder.set(pub)
|
||||
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line, _ := pub.VolumeAuthorityLine("v1")
|
||||
r1 := candidate("r1", "s1", "d1", "c1", 10)
|
||||
r1.Reachable = false
|
||||
snap := ClusterSnapshot{
|
||||
CollectedRevision: 2,
|
||||
Servers: []ServerObservation{
|
||||
{ServerID: "s1", Reachable: true, Eligible: true},
|
||||
{ServerID: "s2", Reachable: true, Eligible: true},
|
||||
{ServerID: "s3", Reachable: true, Eligible: true},
|
||||
},
|
||||
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
|
||||
}
|
||||
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lost {
|
||||
nextAskOrFail(t, ctrl)
|
||||
ended, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, _ = ctrl.Next(ended) // the apply ended without a publication
|
||||
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "enqueued again Reassign r2") {
|
||||
t.Fatalf("outcome %q, want the lost ask enqueued again", out)
|
||||
}
|
||||
}
|
||||
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r3", DataAddr: "d3", CtrlAddr: "c3", Intent: IntentReassign,
|
||||
Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 10, Basis: adapter.BasisPlanned},
|
||||
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch}}); err != nil {
|
||||
t.Fatalf("failback: %v", err)
|
||||
}
|
||||
ask := nextAskOrFail(t, ctrl)
|
||||
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
|
||||
t.Fatalf("lost=%v: took %+v, want Reassign r2", lost, ask)
|
||||
}
|
||||
if err := pub.apply(ask); !errors.Is(err, ErrExpectedLineMoved) {
|
||||
t.Fatalf("lost=%v: the queued Reassign decided against %s@%d: err=%v, want ErrExpectedLineMoved", lost, line.ReplicaID, line.Epoch, err)
|
||||
}
|
||||
if after, _ := pub.VolumeAuthorityLine("v1"); after.ReplicaID != "r3" || after.Epoch != line.Epoch+1 {
|
||||
t.Fatalf("lost=%v: line %+v, want the failback's r3@%d", lost, after, line.Epoch+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -14,10 +14,6 @@ type assignmentQueue struct {
|
||||
items map[string]AssignmentAsk
|
||||
order []string
|
||||
wake chan struct{}
|
||||
// taken is the volume of the ask the publisher took last and is still
|
||||
// applying: it is cleared when the publisher asks for its next one (the
|
||||
// publisher applies one ask at a time, between two calls of next).
|
||||
taken string
|
||||
}
|
||||
|
||||
func newAssignmentQueue() *assignmentQueue {
|
||||
@@ -46,19 +42,7 @@ func (q *assignmentQueue) discard(volumeID string) {
|
||||
delete(q.items, volumeID)
|
||||
}
|
||||
|
||||
// pending reports whether volumeID's ask is queued or still being applied.
|
||||
// A desired ask that is neither ended without a publication (lost).
|
||||
func (q *assignmentQueue) pending(volumeID string) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
_, queued := q.items[volumeID]
|
||||
return queued || q.taken == volumeID
|
||||
}
|
||||
|
||||
func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
|
||||
q.mu.Lock()
|
||||
q.taken = "" // the publisher is done with the ask it took last
|
||||
q.mu.Unlock()
|
||||
for {
|
||||
q.mu.Lock()
|
||||
if len(q.order) > 0 {
|
||||
@@ -70,7 +54,6 @@ func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
|
||||
continue
|
||||
}
|
||||
delete(q.items, vid)
|
||||
q.taken = vid
|
||||
q.mu.Unlock()
|
||||
return ask, nil
|
||||
}
|
||||
|
||||
@@ -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,72 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
)
|
||||
|
||||
// bindingFailingProbe is switchProbe whose fencing round first makes the
|
||||
// master's workspace binding store fail a write (its file replaced by a
|
||||
// directory, so the write's rename fails), which latches the store
|
||||
// uncertain: every later read answers restart-required. It does this once.
|
||||
type bindingFailingProbe struct {
|
||||
*switchProbe
|
||||
once sync.Once
|
||||
fault func()
|
||||
}
|
||||
|
||||
func (p *bindingFailingProbe) FencePromotionCandidates(volume string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
|
||||
p.once.Do(p.fault)
|
||||
return p.switchProbe.FencePromotionCandidates(volume, current, survivors)
|
||||
}
|
||||
|
||||
// A binding store that turns uncertain while the gate probes (the probe runs
|
||||
// without the workspace lock) makes the tick's post-probe binding read fail.
|
||||
// The tick returns the error and its replace decision is reported as not
|
||||
// submitted, with the error, instead of vanishing with the tick.
|
||||
func TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted(t *testing.T) {
|
||||
buf := &lockedBuffer{}
|
||||
dir := t.TempDir()
|
||||
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0), LifecycleStoreDir: dir})
|
||||
defer closeTestMaster(t, h)
|
||||
base, ok := h.promotionProber.(*switchProbe)
|
||||
if !ok {
|
||||
t.Fatalf("fixture: the master's prober is %T, want *switchProbe", h.promotionProber)
|
||||
}
|
||||
var faultErr error
|
||||
h.SetPromotionEvidenceProvider(&bindingFailingProbe{switchProbe: base, fault: func() {
|
||||
file := filepath.Join(dir, "workspace-bindings", "bindings.json")
|
||||
if err := os.RemoveAll(file); err != nil {
|
||||
faultErr = err
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(file, 0o755); err != nil {
|
||||
faultErr = err
|
||||
return
|
||||
}
|
||||
if err := h.lifecycle.WorkspaceBindings.Retire("vol-other", "node-x", 1); err == nil {
|
||||
faultErr = os.ErrInvalid // the write was expected to fail
|
||||
}
|
||||
}})
|
||||
ineligible := restarting
|
||||
ineligible.eligible = false
|
||||
ingestRF3Incarnations(t, h, ineligible, readySlot("r2-a"), readySlot("r3-a"))
|
||||
_, err := h.RunLifecycleProductTick()
|
||||
if faultErr != nil {
|
||||
t.Fatalf("fixture: the binding store did not fail its write: %v", faultErr)
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "restart required") {
|
||||
t.Fatalf("tick error %v, want the binding store's restart-required error", err)
|
||||
}
|
||||
pattern := `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) not submitted: the workspace bindings could not be read after the probe: .*restart required`
|
||||
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
|
||||
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
|
||||
}
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"log"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
)
|
||||
|
||||
// A replace decision of the promotion gate is followed, on the master's
|
||||
// log, by what became of it: the ask the controller enqueued, why it
|
||||
// enqueued none, or that it was not submitted. A replace the controller
|
||||
// does not act on is otherwise silent until the volume fails to fail over.
|
||||
func TestAReplaceDecisionLogsWhatTheControllerDidWithIt(t *testing.T) {
|
||||
// The gate's replace of the lost r1, fed to a controller bound to r1@1.
|
||||
replaced := func(t *testing.T) (*Host, *lockedBuffer, *authority.TopologyController, authority.ClusterSnapshot) {
|
||||
t.Helper()
|
||||
ctrl, pub, stop := lossCluster(t, authority.TopologyControllerConfig{})
|
||||
stop() // the enqueued ask stays queued: the outcome is the controller's alone
|
||||
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
|
||||
h.ctrl = ctrl
|
||||
snap := lossTicks(h)
|
||||
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
|
||||
return h, buf, ctrl, snap
|
||||
}
|
||||
submit := func(t *testing.T, h *Host, ctrl *authority.TopologyController, snap authority.ClusterSnapshot) {
|
||||
t.Helper()
|
||||
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.reportReplaces("", nil, outcomes)
|
||||
}
|
||||
want := func(t *testing.T, buf *lockedBuffer, pattern string) {
|
||||
t.Helper()
|
||||
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
|
||||
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
|
||||
}
|
||||
}
|
||||
t.Run("enqueued", func(t *testing.T) {
|
||||
h, buf, ctrl, snap := replaced(t)
|
||||
submit(t, h, ctrl, snap)
|
||||
want(t, buf, `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
|
||||
})
|
||||
t.Run("the same decision again: already desired", func(t *testing.T) {
|
||||
h, buf, ctrl, snap := replaced(t)
|
||||
submit(t, h, ctrl, snap)
|
||||
h.noteGateReplace("vol-rf3", "replace(fenced_at=2)") // the next tick decides the same
|
||||
submit(t, h, ctrl, snap)
|
||||
want(t, buf, `decision=replace\(fenced_at=2\) controller: already desired since \S+: Reassign r[23] \(failover\)`)
|
||||
})
|
||||
t.Run("not acted on: says why", func(t *testing.T) {
|
||||
h, buf, ctrl, snap := replaced(t)
|
||||
for i := range snap.Volumes[0].Slots {
|
||||
snap.Volumes[0].Slots[i].PromotionEvidence = adapter.PrimaryEvidence{}
|
||||
}
|
||||
submit(t, h, ctrl, snap)
|
||||
want(t, buf, `decision=replace\(fenced_at=2\) controller: no ask: failover target r[23] has no promotion evidence`)
|
||||
})
|
||||
t.Run("not submitted", func(t *testing.T) {
|
||||
h, buf, _, _ := replaced(t)
|
||||
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
|
||||
want(t, buf, `decision=replace\(fenced_at=2\) not submitted: the placements changed during the probe`)
|
||||
})
|
||||
t.Run("an intake after the submission does not change its report", func(t *testing.T) {
|
||||
// The background observation host shares the controller: its intake
|
||||
// may land between the tick's submit and the report.
|
||||
h, buf, ctrl, snap := replaced(t)
|
||||
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale := snap
|
||||
stale.Volumes = append([]authority.VolumeTopologySnapshot(nil), snap.Volumes...)
|
||||
stale.Volumes[0].Authority.Epoch++ // a basis the publisher does not hold
|
||||
if err := ctrl.SubmitClusterSnapshot(stale); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if o := ctrl.LastOutcome("vol-rf3"); !strings.HasPrefix(o, "no ask: stale snapshot basis") {
|
||||
t.Fatalf("fixture: the intervening intake did not record its own outcome: %q", o)
|
||||
}
|
||||
h.reportReplaces("", nil, outcomes)
|
||||
want(t, buf, `decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
|
||||
if strings.Contains(buf.String(), "decision=replace(fenced_at=2) controller: no ask: stale") {
|
||||
t.Fatalf("the report took the later intake's outcome:\n%s", buf.String())
|
||||
}
|
||||
})
|
||||
t.Run("a submission that did not carry the volume", func(t *testing.T) {
|
||||
h, buf, _, _ := replaced(t)
|
||||
h.reportReplaces("", nil, map[string]string{})
|
||||
want(t, buf, `decision=replace\(fenced_at=2\) controller: no outcome \(the submission did not carry the volume\)`)
|
||||
})
|
||||
t.Run("one report per decision", func(t *testing.T) {
|
||||
h, buf, ctrl, snap := replaced(t)
|
||||
submit(t, h, ctrl, snap)
|
||||
h.reportReplaces("", nil, nil) // nothing decided since: nothing to report
|
||||
if n := strings.Count(buf.String(), "decision=replace(fenced_at=2) controller:"); n != 1 {
|
||||
t.Fatalf("%d reports of one decision:\n%s", n, buf.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The same through the production tick on the supported gate: an
|
||||
// established volume whose primary turns ineligible is replaced by a fencing
|
||||
// round; the gate's replace is reported with the controller's enqueued
|
||||
// failover, and the publication is logged. The publication line comes from
|
||||
// the publisher's observer after the line is visible, so it is waited for
|
||||
// (bounded); the two lines are not ordered against each other.
|
||||
func TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication(t *testing.T) {
|
||||
buf := &lockedBuffer{}
|
||||
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0)})
|
||||
defer closeTestMaster(t, h)
|
||||
ineligible := restarting
|
||||
ineligible.eligible = false
|
||||
supportedCreatingTick(t, h, ineligible)
|
||||
expectFailoverToR2(t, h, "fenced survivors")
|
||||
for _, pattern := range []string{
|
||||
`promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r2 \(failover\)`,
|
||||
`blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 \(Reassign\)`,
|
||||
} {
|
||||
waitLogLine(t, buf, pattern, 5*time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// waitLogLine waits up to limit for a line of buf matching pattern.
|
||||
func waitLogLine(t *testing.T, buf *lockedBuffer, pattern string, limit time.Duration) {
|
||||
t.Helper()
|
||||
re := regexp.MustCompile(pattern)
|
||||
for end := time.Now().Add(limit); !re.MatchString(buf.String()); time.Sleep(10 * time.Millisecond) {
|
||||
if time.Now().After(end) {
|
||||
t.Fatalf("no log line matching %q within %v:\n%s", pattern, limit, buf.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every publication is on the master's log, with or without an event log.
|
||||
func TestAPublicationIsLogged(t *testing.T) {
|
||||
h, buf := lossMaster(t, &fenceProbe{})
|
||||
h.recordAuthorityPublishedEvent(authority.PublishEvent{
|
||||
Info: adapter.AssignmentInfo{VolumeID: "vol-rf3", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1},
|
||||
Ask: authority.AssignmentAsk{VolumeID: "vol-rf3", ReplicaID: "r2", Intent: authority.IntentReassign},
|
||||
})
|
||||
if !strings.Contains(buf.String(), "blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 (Reassign)") {
|
||||
t.Fatalf("publication not logged:\n%s", buf.String())
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
|
||||
)
|
||||
|
||||
// A fenced replace decided by the gate reaches the controller as a failover
|
||||
// whatever the gate's reason. Here the gate replaces a primary only it reads
|
||||
// as unacceptable: its node reads format level 0 on a level-1 cluster (not
|
||||
// placement-eligible), while the primary's own slot flags still read
|
||||
// reachable and ready, and it still reports (no loss is recorded). The
|
||||
// controller judges acceptability by those flags alone, so unless the gate
|
||||
// marks the replaced primary unacceptable in what it submits, the controller
|
||||
// answers "the current primary is acceptable" on every tick and the fenced
|
||||
// decision never publishes.
|
||||
func TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign(t *testing.T) {
|
||||
ctrl, pub, _ := lossCluster(t, authority.TopologyControllerConfig{})
|
||||
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
|
||||
h.ctrl = ctrl
|
||||
h.boot = &bootstrap.DurableAuthorityBootstrap{Publisher: pub}
|
||||
h.reads = newReadsLevels(time.Hour)
|
||||
h.reads.note("s1", "vol-rf3", "p-r1", 0) // the primary's node reads the old level
|
||||
h.reads.note("s2", "vol-rf3", "p-r2", 1)
|
||||
h.reads.note("s3", "vol-rf3", "p-r3", 1)
|
||||
h.format.v.Store(1)
|
||||
t0 := time.Date(2026, 12, 5, 8, 0, 0, 0, time.UTC)
|
||||
for tick := range 3 {
|
||||
now := t0.Add(time.Duration(tick) * time.Second)
|
||||
snap := silentPrimary() // r1's flags read reachable and ready
|
||||
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
|
||||
if snap.Volumes[0].Authority.Epoch != 1 {
|
||||
break // published
|
||||
}
|
||||
heard := map[string]time.Time{"r1": now, "r2": now, "r3": now} // r1 still reports: no loss
|
||||
h.notePrimaryLosses(rx(heard, now), &snap)
|
||||
h.takeGateReplaces()
|
||||
h.applyPromotionEvidenceGate(&snap)
|
||||
if l := gateLine(t, buf.String(), "vol-rf3"); !regexp.MustCompile(`primary_lost=false decision=replace\(fenced_at=2\)$`).MatchString(l) {
|
||||
t.Fatalf("tick %d: gate line %q; want a fenced replace with no loss recorded", tick, l)
|
||||
}
|
||||
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.reportReplaces("", nil, outcomes)
|
||||
}
|
||||
if strings.Contains(buf.String(), "controller: no ask: the current primary is acceptable") {
|
||||
t.Fatalf("the controller kept a primary the gate replaced:\n%s", buf.String())
|
||||
}
|
||||
if !regexp.MustCompile(`decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`).MatchString(buf.String()) {
|
||||
t.Fatalf("the fenced replace was not enqueued as a failover:\n%s", buf.String())
|
||||
}
|
||||
waitLossLine(t, pub, "vol-rf3", func(l authority.AuthorityBasis) bool { return l.Epoch == 2 && l.ReplicaID != "r1" })
|
||||
}
|
||||
@@ -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
|
||||
@@ -152,9 +147,8 @@ type Host struct {
|
||||
attest *storeAttestations // primaries' attested write-ACK stores
|
||||
healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6)
|
||||
log *log.Logger
|
||||
gateNoteMu sync.Mutex // guards gateNoteLast and gateReplaces
|
||||
gateNoteMu sync.Mutex // guards gateNoteLast
|
||||
gateNoteLast map[string]string // per kind, the last skip or drop a product-loop tick logged (noteGate)
|
||||
gateReplaces []gateReplace // this tick's replace decisions, reported after the submit (reportReplaces)
|
||||
primaryLossMu sync.Mutex // guards primaryLoss
|
||||
primaryLoss primaryLosses // per volume, the recorded loss of the current primary (primary_loss.go)
|
||||
boot *bootstrap.DurableAuthorityBootstrap
|
||||
@@ -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
|
||||
@@ -333,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
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"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(authority.ExitDurabilityUnknown) })
|
||||
logger.Printf("ERROR reason=lifecycle_persist_failed 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(authority.ExitDurabilityUnknown)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,274 +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/authority"
|
||||
"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() != authority.ExitDurabilityUnknown {
|
||||
t.Fatalf("master failed to exit74: %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, "reason=lifecycle_persist_failed") || !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() != authority.ExitDurabilityUnknown {
|
||||
t.Fatalf("blocked logger prevented own exit74: %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)
|
||||
}
|
||||
@@ -263,7 +263,6 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
|
||||
receipts := h.obs.Store().Snapshot()
|
||||
build := authority.BuildSnapshot(receipts, topology, h.Publisher())
|
||||
h.notePrimaryLosses(receipts, &build.Snapshot)
|
||||
h.takeGateReplaces() // only this tick's decisions are reported
|
||||
probeCount, blockedCount, directAsks := h.applyPromotionEvidenceGate(&build.Snapshot)
|
||||
supported := supportedSnapshotVolumes(build.Snapshot)
|
||||
unsupportedProbeCount, unsupportedBlockedCount, unsupportedDirectAsks := h.applyUnsupportedPromotionEvidenceGate(placements, build.Report, supported)
|
||||
@@ -276,16 +275,13 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
|
||||
defer h.workspaceMu.Unlock()
|
||||
if !reflect.DeepEqual(captured, h.lifecycle.Placements.ListPlacements()) {
|
||||
h.noteGate(gateNoteTick, "decisions not submitted: the placements changed during the probe")
|
||||
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
|
||||
return false, probeCount, blockedCount, nil, nil
|
||||
}
|
||||
for _, p := range placements {
|
||||
if _, bound, err := h.lifecycle.WorkspaceBindings.Get(p.VolumeID); err != nil {
|
||||
h.reportReplaces("not submitted: the workspace bindings could not be read after the probe: "+err.Error(), nil, nil)
|
||||
return false, probeCount, blockedCount, nil, err
|
||||
} else if bound {
|
||||
h.noteGate(gateNoteTick, "decisions not submitted: volume "+p.VolumeID+" got a workspace binding during the probe")
|
||||
h.reportReplaces("not submitted: volume "+p.VolumeID+" got a workspace binding during the probe", nil, nil)
|
||||
return false, probeCount, blockedCount, nil, nil
|
||||
}
|
||||
}
|
||||
@@ -293,58 +289,12 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
|
||||
for _, slot := range v.Slots {
|
||||
if err := h.lifecycle.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: v.VolumeID, DataAddr: slot.DataAddr, CtrlAddr: slot.CtrlAddr}); err != nil {
|
||||
h.noteGate(gateNoteTick, fmt.Sprintf("decisions not submitted: volume %s replica %s endpoints are bound elsewhere: %v", v.VolumeID, slot.ReplicaID, err))
|
||||
h.reportReplaces(fmt.Sprintf("not submitted: volume %s replica %s endpoints are bound elsewhere", v.VolumeID, slot.ReplicaID), nil, nil)
|
||||
return false, probeCount, blockedCount, nil, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
h.noteGate(gateNoteTick, "")
|
||||
// The outcomes are this submission's own, read under the controller's
|
||||
// lock: the background observation host may submit right after it.
|
||||
outcomes, err := h.ctrl.SubmitObservedStateOutcomes(build.Snapshot, build.Report)
|
||||
h.reportReplaces("", err, outcomes)
|
||||
return true, probeCount, blockedCount, directAsks, err
|
||||
}
|
||||
|
||||
// gateReplace is one replace decision of a tick's promotion gate.
|
||||
type gateReplace struct{ volumeID, decision string }
|
||||
|
||||
func (h *Host) noteGateReplace(volumeID, decision string) {
|
||||
h.gateNoteMu.Lock()
|
||||
h.gateReplaces = append(h.gateReplaces, gateReplace{volumeID, decision})
|
||||
h.gateNoteMu.Unlock()
|
||||
}
|
||||
|
||||
func (h *Host) takeGateReplaces() []gateReplace {
|
||||
h.gateNoteMu.Lock()
|
||||
defer h.gateNoteMu.Unlock()
|
||||
out := h.gateReplaces
|
||||
h.gateReplaces = nil
|
||||
return out
|
||||
}
|
||||
|
||||
// reportReplaces logs what became of each replace decision of this tick:
|
||||
// not submitted (notSubmitted says why), a failed submit, or what the
|
||||
// controller did with the volume (an enqueued ask, or why none). A decision
|
||||
// the controller does not act on is otherwise silent until the volume is
|
||||
// seen not to fail over.
|
||||
func (h *Host) reportReplaces(notSubmitted string, submitErr error, outcomes map[string]string) {
|
||||
for _, d := range h.takeGateReplaces() {
|
||||
outcome := ""
|
||||
switch {
|
||||
case notSubmitted != "":
|
||||
outcome = notSubmitted
|
||||
case submitErr != nil:
|
||||
outcome = "submit failed: " + submitErr.Error()
|
||||
default:
|
||||
if o, ok := outcomes[d.volumeID]; ok {
|
||||
outcome = "controller: " + o
|
||||
} else {
|
||||
outcome = "controller: no outcome (the submission did not carry the volume)"
|
||||
}
|
||||
}
|
||||
h.log.Printf("blockmaster: promotion gate volume=%s decision=%s %s", d.volumeID, d.decision, outcome)
|
||||
}
|
||||
return true, probeCount, blockedCount, directAsks, h.ctrl.SubmitObservedState(build.Snapshot, build.Report)
|
||||
}
|
||||
|
||||
func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, int, []authority.AssignmentAsk) {
|
||||
@@ -426,7 +376,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
|
||||
// decision names, on the gate's line, the branch this tick took, so a
|
||||
// volume that keeps a lost primary says why.
|
||||
decision := ""
|
||||
replaceDecided := false // the gate decided to replace the primary (reported after the submit)
|
||||
switch {
|
||||
case !replaceWanted:
|
||||
decision = "keep_current(" + gateAcceptance(vol.Slots[currentIdx], serverIndex, h.placementEligible(vol.Slots[currentIdx].ServerID)) + ")"
|
||||
@@ -453,7 +402,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
|
||||
} else if (len(allowed) > 0 || emptyVolumeSurvivors(result, ok)) && replacing {
|
||||
result, allowed = h.fencedDecision(vol.VolumeID, vol.Authority, result, len(candidates))
|
||||
fencedReplace = len(allowed) > 0
|
||||
replaceDecided = true
|
||||
decision = fmt.Sprintf("replace(fenced_at=%d)", vol.Authority.Epoch+1)
|
||||
if len(allowed) == 0 {
|
||||
decision = "replace(fencing_round_published_nothing)"
|
||||
@@ -469,12 +417,8 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
|
||||
}
|
||||
}
|
||||
if decision == "" && replacing {
|
||||
replaceDecided = true
|
||||
decision = "replace(no_candidate_to_fence)"
|
||||
}
|
||||
if replaceDecided {
|
||||
h.noteGateReplace(vol.VolumeID, decision)
|
||||
}
|
||||
if ok {
|
||||
h.log.Printf("blockmaster: promotion gate volume=%s current=%s current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v primary_lost=%t decision=%s",
|
||||
vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed, lost, decision)
|
||||
@@ -500,15 +444,12 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
|
||||
slot.PlannedMoveAllowed = false
|
||||
}
|
||||
}
|
||||
// A fenced replacement reaches the controller as a failover,
|
||||
// whatever the gate's reason (a recorded loss, or a primary only
|
||||
// the gate reads as unacceptable, such as one on a node below the
|
||||
// cluster's format level): its slot no longer reads acceptable, so
|
||||
// the controller publishes the fenced target with its fenced
|
||||
// evidence (the line is minted only at the fenced epoch), never
|
||||
// keeping the old line by its own acceptability predicate nor
|
||||
// A fenced replacement of a lost primary reaches the controller as
|
||||
// a failover: its slot no longer reads acceptable, so the controller
|
||||
// publishes the fenced target with its fenced evidence (the line is
|
||||
// minted only at the fenced epoch), never keeping the old line nor
|
||||
// routing the target as a planned rebalance without that epoch.
|
||||
if fencedReplace {
|
||||
if lost && fencedReplace {
|
||||
current := &vol.Slots[currentIdx]
|
||||
current.Reachable, current.ReadyForPrimary = false, false
|
||||
}
|
||||
@@ -1016,19 +957,13 @@ func (h *Host) recordVolumeBlockedEvent(volumeID, reason string) {
|
||||
}
|
||||
|
||||
func (h *Host) recordAuthorityPublishedEvent(event authority.PublishEvent) {
|
||||
if h == nil {
|
||||
if h == nil || h.events == nil {
|
||||
return
|
||||
}
|
||||
message := fmt.Sprintf("authority published replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
|
||||
if event.Ask.Intent == authority.IntentReassign {
|
||||
message = fmt.Sprintf("authority reassigned to replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
|
||||
}
|
||||
if h.log != nil {
|
||||
h.log.Printf("blockmaster: volume=%s %s (%s)", event.Info.VolumeID, message, event.Ask.Intent)
|
||||
}
|
||||
if h.events == nil {
|
||||
return
|
||||
}
|
||||
h.events.append(ops.ClusterEvent{
|
||||
VolumeID: event.Info.VolumeID,
|
||||
ReplicaID: event.Info.ReplicaID,
|
||||
|
||||
@@ -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,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)
|
||||
}
|
||||
}
|
||||
@@ -126,13 +126,6 @@ func TestLifecycleLayoutIdentity(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed = false
|
||||
if _, err := loaded.CreateVolume(failedSpec); !errors.Is(err, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("retry before recovery: %v", err)
|
||||
}
|
||||
loaded, err = OpenFileStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err = loaded.CreateVolume(failedSpec)
|
||||
if err != nil || b.Spec.LayoutID != written.Spec.LayoutID {
|
||||
t.Fatalf("unknown put retry changed identity: %v %+v", err, b)
|
||||
|
||||
@@ -61,15 +61,8 @@ func TestRedrawPendingLayoutID(t *testing.T) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fail = false
|
||||
if _, e := s.CreateVolume(spec); !errors.Is(e, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("retry before recovery: %v", e)
|
||||
}
|
||||
s, e = OpenFileStore(s.dir)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Exercise the public retry path, including metadata enrichment. It
|
||||
// must preserve recovered disk B before a metadata put could overwrite it with A.
|
||||
// must settle disk B before a metadata put could overwrite it with A.
|
||||
retry := spec
|
||||
retry.PVCName, retry.PVName = "claim", "pv"
|
||||
public, retryErr := s.CreateVolume(retry)
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestUnchangedNodeRestartDoesNotRefreshAStaleObservation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now().UTC()
|
||||
oldSeen := now.Add(-2 * time.Hour)
|
||||
reg := NodeRegistration{ServerID: "node", Addr: "127.0.0.1:19001", SeenAt: oldSeen}
|
||||
store, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.RegisterNode(reg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.SeenAt = time.Time{} // cluster-spec registrations have no observation time
|
||||
if _, err := store.RegisterNode(reg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, ok := store.GetNodeSnapshot("node")
|
||||
if !ok {
|
||||
t.Fatal("node missing after re-import")
|
||||
}
|
||||
intent := PlacementIntent{VolumeID: "volume", DesiredRF: 1, Slots: []PlacementSlotIntent{{ServerID: "node", PoolID: "pool", Source: PlacementSourceBlankPool}}}
|
||||
verified := VerifyPlacementIntent(intent, []NodeRegistration{got}, VerificationConfig{Now: now, FreshnessWindow: time.Hour})
|
||||
if verified.Verified || verified.Reason != VerifyReasonStaleObservation {
|
||||
t.Fatalf("restart laundered a stale node fresh: seen=%s result=%+v", got.SeenAt, verified)
|
||||
}
|
||||
if !got.SeenAt.Equal(oldSeen) {
|
||||
t.Fatalf("observation changed: got %s want %s", got.SeenAt, oldSeen)
|
||||
}
|
||||
// An explicit timestamp on otherwise identical declarative input cannot
|
||||
// impersonate a heartbeat either.
|
||||
reg.SeenAt = now
|
||||
if _, err := store.RegisterNode(reg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = store.GetNodeSnapshot("node")
|
||||
if !got.SeenAt.Equal(oldSeen) {
|
||||
t.Fatal("timestamp-only registration refreshed the observation")
|
||||
}
|
||||
reopened, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = reopened.GetNodeSnapshot("node")
|
||||
if !got.SeenAt.Equal(oldSeen) {
|
||||
t.Fatal("reloaded observation did not retain its original time")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangedNodeImportDoesNotRefreshAStaleObservation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now().UTC()
|
||||
oldSeen := now.Add(-2 * time.Hour)
|
||||
store, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg := NodeRegistration{ServerID: "node", Addr: "127.0.0.1:19001", SeenAt: oldSeen, Pools: []StoragePool{{PoolID: "pool", BlockSize: 4096, TotalBytes: 1 << 30}}}
|
||||
if _, err := store.RegisterNode(reg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.SeenAt = time.Time{}
|
||||
reg.Pools = []StoragePool{{PoolID: "pool", BlockSize: 4096, TotalBytes: 2 << 30}}
|
||||
if err := store.ImportNodes([]NodeRegistration{reg}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, ok := store.GetNodeSnapshot("node")
|
||||
if !ok || got.Pools[0].TotalBytes != 2<<30 {
|
||||
t.Fatalf("changed declaration not imported: %+v", got)
|
||||
}
|
||||
if !got.SeenAt.Equal(oldSeen) {
|
||||
t.Fatalf("changed declaration refreshed the observation: got %s want %s", got.SeenAt, oldSeen)
|
||||
}
|
||||
intent := PlacementIntent{VolumeID: "volume", DesiredRF: 1, Slots: []PlacementSlotIntent{{ServerID: "node", PoolID: "pool", Source: PlacementSourceBlankPool}}}
|
||||
verified := VerifyPlacementIntent(intent, []NodeRegistration{got}, VerificationConfig{Now: now, FreshnessWindow: time.Hour})
|
||||
if verified.Verified || verified.Reason != VerifyReasonStaleObservation {
|
||||
t.Fatalf("restart laundered a stale node fresh: %+v", verified)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -66,13 +65,11 @@ type NodeRegistration struct {
|
||||
|
||||
// NodeInventoryStore persists one JSON registration record per server.
|
||||
type NodeInventoryStore struct {
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
writeErr error // failed persistence requires reopen before another mutation
|
||||
onPersistenceFailure PersistenceFailureHandler
|
||||
records map[string]NodeRegistration
|
||||
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
|
||||
failWrite func() error // tests: a non-nil error fails the next record write or removal
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
records map[string]NodeRegistration
|
||||
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
|
||||
failWrite func() error // tests: a non-nil error fails the next record write or removal
|
||||
}
|
||||
|
||||
// SetPersistHookForTest installs (nil clears) a callback that each later
|
||||
@@ -84,14 +81,6 @@ func (s *NodeInventoryStore) SetPersistHookForTest(hook func() error) {
|
||||
s.failWrite = hook
|
||||
}
|
||||
|
||||
// SetPersistenceFailureHandler installs the process host policy before serving.
|
||||
// The callback runs under the writer mutex and must not reenter the store.
|
||||
func (s *NodeInventoryStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.onPersistenceFailure = handler
|
||||
}
|
||||
|
||||
// OpenNodeInventoryStore opens or creates a node inventory store.
|
||||
func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) {
|
||||
if dir == "" {
|
||||
@@ -122,11 +111,6 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) {
|
||||
if err := s.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Loaded names may come from a failed rename/barrier attempt. Establish
|
||||
// their durability before exposing them or taking an equality shortcut.
|
||||
if err := syncRecordDirectory(dir); err != nil {
|
||||
return nil, &RecordPersistenceError{Store: dir, Record: "<recovery>", Err: err}
|
||||
}
|
||||
for id, rec := range s.records {
|
||||
s.published.Store(id, copyNodeRegistration(rec))
|
||||
}
|
||||
@@ -153,29 +137,24 @@ func (s *NodeInventoryStore) HoldWritesForTest() (release func()) {
|
||||
}
|
||||
|
||||
// RegisterNode records the latest observed inventory for a server.
|
||||
// Changed registration replaces observation fields, but still does not
|
||||
// publish authority or readiness. A declaration without SeenAt retains the
|
||||
// stored one (INV-NODE-REGISTRATION-FRESHNESS-001); only a heartbeat adds fresh evidence.
|
||||
// Repeating registration replaces observation fields, but still does not
|
||||
// publish authority or readiness.
|
||||
func (s *NodeInventoryStore) RegisterNode(reg NodeRegistration) (NodeRegistration, error) {
|
||||
if err := validateNodeRegistration(reg); err != nil {
|
||||
return NodeRegistration{}, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return NodeRegistration{}, err
|
||||
}
|
||||
reg, changed := s.registrationLocked(reg)
|
||||
if !changed {
|
||||
return copyNodeRegistration(reg), nil
|
||||
if reg.SeenAt.IsZero() {
|
||||
reg.SeenAt = time.Now().UTC()
|
||||
}
|
||||
reg = normalizeNodeRegistration(reg)
|
||||
if err := s.putLocked(reg); err != nil {
|
||||
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
|
||||
return NodeRegistration{}, err
|
||||
}
|
||||
s.records[reg.ServerID] = reg
|
||||
s.published.Store(reg.ServerID, copyNodeRegistration(reg)) // committed: the file is in place
|
||||
return copyNodeRegistration(reg), nil
|
||||
return reg, nil
|
||||
}
|
||||
|
||||
// RemoveNode deletes one registration record. Missing nodes are a
|
||||
@@ -186,18 +165,15 @@ func (s *NodeInventoryStore) RemoveNode(serverID string) error {
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.failWrite != nil {
|
||||
if err := s.failWrite(); err != nil {
|
||||
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
|
||||
}
|
||||
}
|
||||
delete(s.records, serverID)
|
||||
if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
|
||||
}
|
||||
delete(s.records, serverID)
|
||||
s.published.Delete(serverID) // committed: the file is gone
|
||||
return nil
|
||||
}
|
||||
@@ -351,85 +327,3 @@ func copyStringMap(in map[string]string) map[string]string {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ImportDurabilityMode reports the persistence path ImportNodes uses.
|
||||
func (s *NodeInventoryStore) ImportDurabilityMode() string { return importDurabilityMode(s.dir) }
|
||||
|
||||
// ImportNodes replays one startup node step. All changed data is durable before
|
||||
// rename; one directory barrier precedes publication of the changed snapshots.
|
||||
func (s *NodeInventoryStore) ImportNodes(nodes []NodeRegistration) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return err
|
||||
}
|
||||
changed := make(map[string]NodeRegistration)
|
||||
seen := make(map[string]bool)
|
||||
order := make([]string, 0, len(nodes))
|
||||
for _, node := range nodes {
|
||||
if err := validateNodeRegistration(node); err != nil {
|
||||
return fmt.Errorf("lifecycle: import node %s: %w", node.ServerID, err)
|
||||
}
|
||||
reg, differs := s.registrationLocked(node)
|
||||
if !seen[reg.ServerID] {
|
||||
order = append(order, reg.ServerID)
|
||||
seen[reg.ServerID] = true
|
||||
}
|
||||
if !differs {
|
||||
delete(changed, reg.ServerID)
|
||||
continue
|
||||
}
|
||||
changed[reg.ServerID] = reg
|
||||
}
|
||||
writes := make([]recordWrite, 0, len(order))
|
||||
for _, id := range order {
|
||||
if _, ok := changed[id]; !ok {
|
||||
continue
|
||||
}
|
||||
if s.failWrite != nil {
|
||||
if err := s.failWrite(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
raw, err := json.MarshalIndent(changed[id], "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("lifecycle: marshal node %s: %w", id, err)
|
||||
}
|
||||
writes = append(writes, recordWrite{name: id + ".json", raw: raw})
|
||||
}
|
||||
if err := writeRecordBatchDurably(s.dir, writes); err != nil {
|
||||
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
|
||||
return err
|
||||
}
|
||||
for _, id := range order {
|
||||
if _, ok := changed[id]; !ok {
|
||||
continue
|
||||
}
|
||||
reg := changed[id]
|
||||
s.records[id] = reg
|
||||
s.published.Store(id, copyNodeRegistration(reg))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *NodeInventoryStore) registrationLocked(reg NodeRegistration) (NodeRegistration, bool) {
|
||||
// Retain an independent value: a caller may reuse its pool slices.
|
||||
reg = copyNodeRegistration(reg)
|
||||
if old, ok := s.records[reg.ServerID]; ok {
|
||||
unchanged := reg
|
||||
unchanged.SeenAt = old.SeenAt
|
||||
if reflect.DeepEqual(old, unchanged) {
|
||||
// Declarative replay is not a new observation. Heartbeats supply
|
||||
// freshness independently of this durable registration.
|
||||
return copyNodeRegistration(old), false
|
||||
}
|
||||
if reg.SeenAt.IsZero() {
|
||||
// A changed declaration is not an observation either.
|
||||
reg.SeenAt = old.SeenAt
|
||||
}
|
||||
}
|
||||
if reg.SeenAt.IsZero() {
|
||||
reg.SeenAt = time.Now().UTC()
|
||||
}
|
||||
return reg, true
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
)
|
||||
@@ -37,20 +36,10 @@ type PlacementIntent struct {
|
||||
|
||||
// PlacementIntentStore persists one placement intent per volume.
|
||||
type PlacementIntentStore struct {
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
writeErr error // failed persistence requires reopen before another mutation
|
||||
onPersistenceFailure PersistenceFailureHandler
|
||||
records map[string]PlacementIntent
|
||||
published sync.Map // committed immutable PlacementIntent values; renewal never takes mu
|
||||
}
|
||||
|
||||
// SetPersistenceFailureHandler installs the process host policy before serving.
|
||||
// The callback runs under the writer mutex and must not reenter the store.
|
||||
func (s *PlacementIntentStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.onPersistenceFailure = handler
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
records map[string]PlacementIntent
|
||||
published sync.Map // committed immutable PlacementIntent values; renewal never takes mu
|
||||
}
|
||||
|
||||
// OpenPlacementIntentStore opens or creates a placement intent store.
|
||||
@@ -83,11 +72,6 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) {
|
||||
if err := s.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Loaded names may come from a failed rename/barrier attempt. Establish
|
||||
// their durability before exposing them or taking an equality shortcut.
|
||||
if err := syncRecordDirectory(dir); err != nil {
|
||||
return nil, &RecordPersistenceError{Store: dir, Record: "<recovery>", Err: err}
|
||||
}
|
||||
for volume, rec := range s.records {
|
||||
s.published.Store(volume, copyPlacementIntent(rec))
|
||||
}
|
||||
@@ -97,21 +81,32 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) {
|
||||
// ApplyPlan records placement intent from a sufficient plan. Insufficient
|
||||
// plans are rejected rather than persisted as partial authority-shaped state.
|
||||
func (s *PlacementIntentStore) ApplyPlan(plan PlacementPlan) (PlacementIntent, error) {
|
||||
intent, err := placementIntentFromPlan(plan)
|
||||
if err != nil {
|
||||
if !plan.EnoughCandidates() {
|
||||
return PlacementIntent{}, ErrInsufficientPlacementCandidates
|
||||
}
|
||||
intent := PlacementIntent{
|
||||
VolumeID: plan.VolumeID,
|
||||
DesiredRF: plan.DesiredRF,
|
||||
Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF),
|
||||
}
|
||||
for _, candidate := range plan.Candidates[:plan.DesiredRF] {
|
||||
intent.Slots = append(intent.Slots, PlacementSlotIntent{
|
||||
ServerID: candidate.ServerID,
|
||||
PoolID: candidate.PoolID,
|
||||
ReplicaID: candidate.ReplicaID,
|
||||
Source: candidate.Source,
|
||||
DataAddr: candidate.DataAddr,
|
||||
CtrlAddr: candidate.CtrlAddr,
|
||||
ISCSIListenPort: candidate.ISCSIListenPort,
|
||||
NVMeListenPort: candidate.NVMeListenPort,
|
||||
})
|
||||
}
|
||||
if err := validatePlacementIntent(intent); err != nil {
|
||||
return PlacementIntent{}, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return PlacementIntent{}, err
|
||||
}
|
||||
// Equal input already has a durable record; preserve it on restart.
|
||||
if old, ok := s.records[intent.VolumeID]; ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) {
|
||||
return copyPlacementIntent(old), nil
|
||||
}
|
||||
if err := s.putLocked(intent); err != nil {
|
||||
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
|
||||
return PlacementIntent{}, err
|
||||
}
|
||||
s.records[intent.VolumeID] = intent
|
||||
@@ -127,9 +122,6 @@ func (s *PlacementIntentStore) DeletePlacement(volumeID string) error {
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("lifecycle: remove placement intent %s: %w", volumeID, err)
|
||||
}
|
||||
@@ -270,86 +262,3 @@ func copyPlacementIntent(in PlacementIntent) PlacementIntent {
|
||||
out.Slots = append([]PlacementSlotIntent(nil), in.Slots...)
|
||||
return out
|
||||
}
|
||||
|
||||
// ImportDurabilityMode reports the persistence path ImportPlans uses.
|
||||
func (s *PlacementIntentStore) ImportDurabilityMode() string { return importDurabilityMode(s.dir) }
|
||||
|
||||
// ImportPlans replays one startup placement step and publishes only after
|
||||
// the changed files and their shared directory barrier have completed.
|
||||
func (s *PlacementIntentStore) ImportPlans(plans []PlacementPlan) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return err
|
||||
}
|
||||
changed := make(map[string]PlacementIntent)
|
||||
seen := make(map[string]bool)
|
||||
order := make([]string, 0, len(plans))
|
||||
for _, plan := range plans {
|
||||
intent, err := placementIntentFromPlan(plan)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lifecycle: import placement intent %s: %w", plan.VolumeID, err)
|
||||
}
|
||||
old, ok := s.records[intent.VolumeID]
|
||||
if !seen[intent.VolumeID] {
|
||||
order = append(order, intent.VolumeID)
|
||||
seen[intent.VolumeID] = true
|
||||
}
|
||||
if ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) {
|
||||
delete(changed, intent.VolumeID)
|
||||
continue
|
||||
}
|
||||
changed[intent.VolumeID] = intent
|
||||
}
|
||||
writes := make([]recordWrite, 0, len(order))
|
||||
for _, id := range order {
|
||||
if _, ok := changed[id]; !ok {
|
||||
continue
|
||||
}
|
||||
raw, err := json.MarshalIndent(changed[id], "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("lifecycle: marshal placement intent %s: %w", id, err)
|
||||
}
|
||||
writes = append(writes, recordWrite{name: id + ".json", raw: raw})
|
||||
}
|
||||
if err := writeRecordBatchDurably(s.dir, writes); err != nil {
|
||||
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
|
||||
return err
|
||||
}
|
||||
for _, id := range order {
|
||||
if _, ok := changed[id]; !ok {
|
||||
continue
|
||||
}
|
||||
intent := changed[id]
|
||||
s.records[id] = intent
|
||||
s.published.Store(id, copyPlacementIntent(intent))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func placementIntentFromPlan(plan PlacementPlan) (PlacementIntent, error) {
|
||||
if !plan.EnoughCandidates() {
|
||||
return PlacementIntent{}, ErrInsufficientPlacementCandidates
|
||||
}
|
||||
intent := PlacementIntent{
|
||||
VolumeID: plan.VolumeID,
|
||||
DesiredRF: plan.DesiredRF,
|
||||
Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF),
|
||||
}
|
||||
for _, candidate := range plan.Candidates[:plan.DesiredRF] {
|
||||
intent.Slots = append(intent.Slots, PlacementSlotIntent{
|
||||
ServerID: candidate.ServerID,
|
||||
PoolID: candidate.PoolID,
|
||||
ReplicaID: candidate.ReplicaID,
|
||||
Source: candidate.Source,
|
||||
DataAddr: candidate.DataAddr,
|
||||
CtrlAddr: candidate.CtrlAddr,
|
||||
ISCSIListenPort: candidate.ISCSIListenPort,
|
||||
NVMeListenPort: candidate.NVMeListenPort,
|
||||
})
|
||||
}
|
||||
if err := validatePlacementIntent(intent); err != nil {
|
||||
return PlacementIntent{}, err
|
||||
}
|
||||
return intent, nil
|
||||
}
|
||||
@@ -135,7 +135,6 @@ func TestPlacementSnapshotFailedCommitStaysCommitted(t *testing.T) {
|
||||
if ok != existed || !reflect.DeepEqual(got, before) {
|
||||
t.Fatal("reopen did not retain the committed placement")
|
||||
}
|
||||
s = reopened // failed persistence requires reopening before further writes
|
||||
if _, err = s.ApplyPlan(plan); err != nil {
|
||||
t.Fatal("unblocked commit", err)
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPlacementRepeatKeepsRecordAndChangedPlanReplacesIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store, err := OpenPlacementIntentStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plan := PlacementPlan{VolumeID: "volume", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
|
||||
if _, err := store.ApplyPlan(plan); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "volume.json")
|
||||
original, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Reloading must not cause an otherwise equal import to rewrite the file.
|
||||
store, err = OpenPlacementIntentStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.ApplyPlan(plan); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repeated, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !os.SameFile(original, repeated) || !original.ModTime().Equal(repeated.ModTime()) {
|
||||
t.Fatal("equal placement plan rewrote its durable record")
|
||||
}
|
||||
plan.Candidates[0].ReplicaID = "r2"
|
||||
if _, err := store.ApplyPlan(plan); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
changed, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if os.SameFile(repeated, changed) {
|
||||
t.Fatal("changed placement did not replace its record")
|
||||
}
|
||||
reopened, err := OpenPlacementIntentStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, ok := reopened.GetPlacementSnapshot("volume")
|
||||
if !ok || len(got.Slots) != 1 || got.Slots[0].ReplicaID != "r2" {
|
||||
t.Fatalf("changed plan did not survive reload: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -1,64 +1,18 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// ErrLifecycleRecoveryRequired means a failed persistence operation may have
|
||||
// changed disk. Reopen the store before making further mutations.
|
||||
var ErrLifecycleRecoveryRequired = errors.New("lifecycle: store recovery required")
|
||||
|
||||
// RecordPersistenceError identifies the operation whose durable outcome is
|
||||
// uncertain. A process host can fail-stop rather than remain alive and poisoned.
|
||||
type RecordPersistenceError struct {
|
||||
Store string
|
||||
Record string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *RecordPersistenceError) Error() string {
|
||||
return fmt.Sprintf("lifecycle: persist store %q record %q: %v", e.Store, e.Record, e.Err)
|
||||
}
|
||||
|
||||
func (e *RecordPersistenceError) Unwrap() error { return e.Err }
|
||||
|
||||
// PersistenceFailureHandler is called synchronously after a failed I/O has
|
||||
// poisoned a store. It must not reenter a store; production exits the process.
|
||||
type PersistenceFailureHandler func(*RecordPersistenceError)
|
||||
|
||||
// Only a write that may have touched disk poisons the store; a marshal error
|
||||
// happens before any I/O, so the caller can correct the input and retry.
|
||||
func latchPersistenceFailure(err error, prior *error, handler PersistenceFailureHandler) {
|
||||
var failure *RecordPersistenceError
|
||||
if !errors.As(err, &failure) {
|
||||
return
|
||||
}
|
||||
*prior = err
|
||||
if handler != nil {
|
||||
handler(failure)
|
||||
}
|
||||
}
|
||||
|
||||
func recoveryRequired(writeErr error) error {
|
||||
if writeErr == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: %v", ErrLifecycleRecoveryRequired, writeErr)
|
||||
}
|
||||
|
||||
// Hooks are installed only in isolated subprocess tests. Production uses
|
||||
// the real filesystem operations; one helper owns all publication seams.
|
||||
type durableRecordHooks struct {
|
||||
crash func(string)
|
||||
fileSync func(*os.File) error
|
||||
dirSync func(string) error
|
||||
batchSyncfs *bool
|
||||
fsSync func(*os.File) error
|
||||
statfsType func(dir string, fsType uint32) uint32
|
||||
crash func(string)
|
||||
fileSync func(*os.File) error
|
||||
dirSync func(string) error
|
||||
}
|
||||
|
||||
var durableRecordHooksForTest atomic.Pointer[durableRecordHooks]
|
||||
@@ -66,170 +20,42 @@ var durableRecordHooksForTest atomic.Pointer[durableRecordHooks]
|
||||
// writeRecordDurably implements INV-LIFECYCLE-STORE-DURABLE-001 for puts and
|
||||
// replacements. A post-rename error may leave the new record on disk.
|
||||
func writeRecordDurably(dir, name string, raw []byte) error {
|
||||
if err := writeRecordBeforeDirectorySync(dir, name, raw); err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: name, Err: err}
|
||||
}
|
||||
if err := syncRecordDirectory(dir); err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: name, Err: err}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type recordWrite struct {
|
||||
name string
|
||||
raw []byte
|
||||
}
|
||||
|
||||
// A startup import makes all changed data durable before rename, then shares
|
||||
// a directory barrier before publication. A failed step leaves complete old/new
|
||||
// names. Linux >= 5.8 on ext4, xfs, btrfs or tmpfs uses one syncfs for staged
|
||||
// temps; other systems sync each.
|
||||
func writeRecordBatchDurably(dir string, records []recordWrite) error {
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
}
|
||||
useSyncfs := recordBatchSyncfsSupported(dir)
|
||||
hooks := durableRecordHooksForTest.Load()
|
||||
if hooks != nil && hooks.batchSyncfs != nil {
|
||||
useSyncfs = *hooks.batchSyncfs
|
||||
}
|
||||
if useSyncfs {
|
||||
return writeRecordBatchWithSyncfs(dir, records)
|
||||
}
|
||||
for _, record := range records {
|
||||
if err := writeRecordBeforeDirectorySync(dir, record.name, record.raw); err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: record.name, Err: err}
|
||||
}
|
||||
}
|
||||
if err := syncRecordDirectory(dir); err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: err}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// importDurabilityMode reports the batch persistence path for records under dir.
|
||||
// Single-record mutations always retain their file and directory fsyncs.
|
||||
func importDurabilityMode(dir string) string {
|
||||
if recordBatchSyncfsSupported(dir) {
|
||||
return "syncfs (Linux >= 5.8, local filesystem)"
|
||||
}
|
||||
return "per-file fsync (syncfs writeback error reporting unavailable)"
|
||||
}
|
||||
|
||||
func writeRecordBatchWithSyncfs(dir string, records []recordWrite) error {
|
||||
// Opening before any write samples the filesystem's writeback errseq.
|
||||
fd, err := os.Open(dir)
|
||||
if err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: err}
|
||||
}
|
||||
defer fd.Close()
|
||||
hooks := durableRecordHooksForTest.Load()
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("batch-open")
|
||||
}
|
||||
temps := make([]string, 0, len(records))
|
||||
defer func() {
|
||||
for _, temp := range temps {
|
||||
_ = os.Remove(temp)
|
||||
}
|
||||
}()
|
||||
for _, record := range records {
|
||||
temp, err := writeRecordTemp(dir, record.name, record.raw, false)
|
||||
if err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: record.name, Err: err}
|
||||
}
|
||||
temps = append(temps, temp)
|
||||
}
|
||||
fsSync := syncRecordFilesystem
|
||||
if hooks != nil && hooks.fsSync != nil {
|
||||
fsSync = hooks.fsSync
|
||||
}
|
||||
// Never retry a failed syncfs: it consumes the writeback error. The caller
|
||||
// poisons the store; recovery creates fresh temps for any subsequent import.
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("before-syncfs")
|
||||
}
|
||||
if err := fsSync(fd); err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: fmt.Errorf("lifecycle: sync record filesystem: %w", err)}
|
||||
}
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("after-syncfs")
|
||||
}
|
||||
for i, record := range records {
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("before-rename")
|
||||
}
|
||||
if err := os.Rename(temps[i], filepath.Join(dir, record.name)); err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: record.name, Err: err}
|
||||
}
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("after-rename")
|
||||
}
|
||||
}
|
||||
if err := syncRecordDirectory(dir); err != nil {
|
||||
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: err}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeRecordBeforeDirectorySync(dir, name string, raw []byte) error {
|
||||
temp, err := writeRecordTemp(dir, name, raw, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(temp)
|
||||
hooks := durableRecordHooksForTest.Load()
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("before-rename")
|
||||
}
|
||||
if err := os.Rename(temp, filepath.Join(dir, name)); err != nil {
|
||||
return fmt.Errorf("lifecycle: rename record %s: %w", name, err)
|
||||
}
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("after-rename")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeRecordTemp(dir, name string, raw []byte, syncFile bool) (temp string, resultErr error) {
|
||||
f, err := os.CreateTemp(dir, name+".*.tmp")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("lifecycle: temp record %s: %w", name, err)
|
||||
return fmt.Errorf("lifecycle: temp record %s: %w", name, err)
|
||||
}
|
||||
defer func() {
|
||||
if resultErr != nil {
|
||||
_ = os.Remove(f.Name())
|
||||
}
|
||||
}()
|
||||
defer os.Remove(f.Name())
|
||||
if _, err := f.Write(raw); err != nil {
|
||||
_ = f.Close()
|
||||
return "", fmt.Errorf("lifecycle: write record %s: %w", name, err)
|
||||
return fmt.Errorf("lifecycle: write record %s: %w", name, err)
|
||||
}
|
||||
hooks := durableRecordHooksForTest.Load()
|
||||
fileSync := f.Sync
|
||||
if hooks != nil && hooks.fileSync != nil {
|
||||
fileSync = func() error { return hooks.fileSync(f) }
|
||||
}
|
||||
if syncFile {
|
||||
if err := fileSync(); err != nil {
|
||||
_ = f.Close()
|
||||
return "", fmt.Errorf("lifecycle: sync record %s: %w", name, err)
|
||||
}
|
||||
if err := fileSync(); err != nil {
|
||||
_ = f.Close()
|
||||
return fmt.Errorf("lifecycle: sync record %s: %w", name, err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return "", fmt.Errorf("lifecycle: close record %s: %w", name, err)
|
||||
return fmt.Errorf("lifecycle: close record %s: %w", name, err)
|
||||
}
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("before-rename")
|
||||
}
|
||||
if err := os.Rename(f.Name(), filepath.Join(dir, name)); err != nil {
|
||||
return fmt.Errorf("lifecycle: rename record %s: %w", name, err)
|
||||
}
|
||||
if hooks != nil && hooks.crash != nil {
|
||||
hooks.crash("after-rename")
|
||||
}
|
||||
return f.Name(), nil
|
||||
}
|
||||
|
||||
func syncRecordDirectory(dir string) error {
|
||||
hooks := durableRecordHooksForTest.Load()
|
||||
dirSync := syncBindingParent
|
||||
if hooks != nil && hooks.dirSync != nil {
|
||||
dirSync = hooks.dirSync
|
||||
}
|
||||
if err := dirSync(dir); err != nil {
|
||||
return fmt.Errorf("lifecycle: sync record directory %s: %w", dir, err)
|
||||
return fmt.Errorf("lifecycle: sync record directory %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var recordKernelSyncfsErrors = detectRecordSyncfs()
|
||||
|
||||
// recordBatchSyncfsSupported reports whether syncfs on dir's filesystem
|
||||
// returns the writeback errors a per-file fsync would. Overlay, FUSE and
|
||||
// network mounts keep per-file fsync: syncfs does not reach their backing files.
|
||||
func recordBatchSyncfsSupported(dir string) bool {
|
||||
if !recordKernelSyncfsErrors {
|
||||
return false
|
||||
}
|
||||
var st unix.Statfs_t
|
||||
if unix.Statfs(dir, &st) != nil {
|
||||
return false
|
||||
}
|
||||
fsType := uint32(st.Type)
|
||||
if hooks := durableRecordHooksForTest.Load(); hooks != nil && hooks.statfsType != nil {
|
||||
fsType = hooks.statfsType(dir, fsType)
|
||||
}
|
||||
return filesystemReportsSyncfsErrors(fsType)
|
||||
}
|
||||
|
||||
func filesystemReportsSyncfsErrors(fsType uint32) bool {
|
||||
switch fsType {
|
||||
case unix.EXT4_SUPER_MAGIC, unix.XFS_SUPER_MAGIC, unix.BTRFS_SUPER_MAGIC, unix.TMPFS_MAGIC:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func detectRecordSyncfs() bool {
|
||||
var u unix.Utsname
|
||||
if unix.Uname(&u) != nil {
|
||||
return false
|
||||
}
|
||||
return kernelHasSyncfsErrors(unix.ByteSliceToString(u.Release[:]))
|
||||
}
|
||||
|
||||
func kernelHasSyncfsErrors(release string) bool {
|
||||
parts := strings.SplitN(release, ".", 3)
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
major, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
minor, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return major > 5 || major == 5 && minor >= 8
|
||||
}
|
||||
|
||||
func syncRecordFilesystem(fd *os.File) error { return unix.Syncfs(int(fd.Fd())) }
|
||||
@@ -1,12 +0,0 @@
|
||||
//go:build !linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func recordBatchSyncfsSupported(string) bool { return false }
|
||||
|
||||
func syncRecordFilesystem(*os.File) error { return fmt.Errorf("syncfs unavailable on this platform") }
|
||||
@@ -1,106 +0,0 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFailedRemoveKeepsRecordForRetry(t *testing.T) {
|
||||
for _, kind := range []string{"node", "placement", "volume"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
var remove func() error
|
||||
var present func() (record, snapshot bool)
|
||||
switch kind {
|
||||
case "node":
|
||||
s, err := OpenNodeInventoryStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.RegisterNode(NodeRegistration{ServerID: "v", Addr: "127.0.0.1:19001"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remove = func() error { return s.RemoveNode("v") }
|
||||
present = func() (bool, bool) { _, a := s.GetNode("v"); _, b := s.GetNodeSnapshot("v"); return a, b }
|
||||
case "placement":
|
||||
s, err := OpenPlacementIntentStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ApplyPlan(PlacementPlan{VolumeID: "v", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remove = func() error { return s.DeletePlacement("v") }
|
||||
present = func() (bool, bool) { _, a := s.GetPlacement("v"); _, b := s.GetPlacementSnapshot("v"); return a, b }
|
||||
case "volume":
|
||||
s, err := OpenFileStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.CreateVolume(VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remove = func() error { return s.DeleteVolume("v") }
|
||||
present = func() (bool, bool) { _, a := s.GetVolume("v"); _, b := s.GetVolumeSnapshot("v"); return a, b }
|
||||
}
|
||||
path := filepath.Join(dir, "v.json")
|
||||
backup := path + ".saved"
|
||||
if err := os.Rename(path, backup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(path, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blocker := filepath.Join(path, "blocker")
|
||||
if err := os.WriteFile(blocker, []byte("fixture"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := remove(); err == nil {
|
||||
t.Fatal("nonempty-directory removal succeeded")
|
||||
}
|
||||
if record, snapshot := present(); !record || !snapshot {
|
||||
t.Fatalf("failed removal hid retry state: record=%v snapshot=%v", record, snapshot)
|
||||
}
|
||||
if err := os.Remove(blocker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(backup, path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := remove(); err != nil {
|
||||
t.Fatalf("later removal retry: %v", err)
|
||||
}
|
||||
if record, snapshot := present(); record || snapshot {
|
||||
t.Fatalf("successful removal left state: record=%v snapshot=%v", record, snapshot)
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("record file survived successful retry: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNodeMarshalErrorDoesNotRequireRecovery(t *testing.T) {
|
||||
s, err := OpenNodeInventoryStore(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var latched []*RecordPersistenceError
|
||||
s.SetPersistenceFailureHandler(func(f *RecordPersistenceError) { latched = append(latched, f) })
|
||||
reg := NodeRegistration{ServerID: "n", Addr: "127.0.0.1:19001", SeenAt: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)}
|
||||
if _, err := s.RegisterNode(reg); err == nil {
|
||||
t.Fatal("unencodable SeenAt was accepted")
|
||||
}
|
||||
reg.SeenAt = time.Now().UTC()
|
||||
if _, err := s.RegisterNode(reg); err != nil {
|
||||
t.Fatalf("corrected registration after a marshal error: %v", err)
|
||||
}
|
||||
if len(latched) != 0 {
|
||||
t.Fatalf("marshal error reached the persistence policy: %v", latched)
|
||||
}
|
||||
}
|
||||
@@ -67,11 +67,9 @@ type VolumeRecord struct {
|
||||
|
||||
// FileStore persists one JSON record per volume ID.
|
||||
type FileStore struct {
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
writeErr error // a failed put requires reopen before another mutation
|
||||
onPersistenceFailure PersistenceFailureHandler
|
||||
records map[string]VolumeRecord
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
records map[string]VolumeRecord
|
||||
// snap mirrors records as an immutable copy, republished at every change
|
||||
// of records, for lock-free renewal-path reads.
|
||||
snap atomic.Pointer[map[string]VolumeRecord]
|
||||
@@ -99,14 +97,6 @@ func (s *FileStore) GetVolumeSnapshot(volumeID string) (VolumeRecord, bool) {
|
||||
return rec, ok
|
||||
}
|
||||
|
||||
// SetPersistenceFailureHandler installs the process host policy before serving.
|
||||
// The callback runs under the writer mutex and must not reenter the store.
|
||||
func (s *FileStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.onPersistenceFailure = handler
|
||||
}
|
||||
|
||||
// OpenFileStore opens or creates a lifecycle intent store.
|
||||
func OpenFileStore(dir string) (*FileStore, error) {
|
||||
if dir == "" {
|
||||
@@ -137,11 +127,6 @@ func OpenFileStore(dir string) (*FileStore, error) {
|
||||
if err := s.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Visible names can come from a failed directory barrier. Recover their
|
||||
// durability before publication or an equal create can acknowledge them.
|
||||
if err := syncRecordDirectory(dir); err != nil {
|
||||
return nil, &RecordPersistenceError{Store: dir, Record: "<recovery>", Err: err}
|
||||
}
|
||||
s.publishLocked()
|
||||
return s, nil
|
||||
}
|
||||
@@ -152,9 +137,6 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) {
|
||||
spec = normalizeVolumeSpec(spec)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
if existing, ok := s.records[spec.VolumeID]; ok {
|
||||
if existing.Spec.SourceVolume != spec.SourceVolume || existing.Spec.SourceLayoutID != spec.SourceLayoutID || existing.Spec.SourceSnapshot != spec.SourceSnapshot || existing.Spec.CreateRequestID != spec.CreateRequestID {
|
||||
return VolumeRecord{}, ErrVolumeConflict
|
||||
@@ -239,9 +221,6 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) {
|
||||
func (s *FileStore) RedrawPendingLayoutID(volumeID, rejectedID string) (VolumeRecord, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
rec, ok := s.records[volumeID]
|
||||
if !ok {
|
||||
return VolumeRecord{}, ErrVolumeNotFound
|
||||
@@ -322,9 +301,6 @@ func (s *FileStore) settlePendingLayoutIDLocked(rec VolumeRecord) (VolumeRecord,
|
||||
func (s *FileStore) MarkStoreReady(volumeID, layoutID string) (VolumeRecord, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
rec, ok := s.records[volumeID]
|
||||
if !ok {
|
||||
return VolumeRecord{}, ErrVolumeNotFound
|
||||
@@ -386,14 +362,11 @@ func (s *FileStore) DeleteVolume(volumeID string) error {
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return err
|
||||
}
|
||||
delete(s.records, volumeID)
|
||||
s.publishLocked()
|
||||
if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("lifecycle: remove %s: %w", volumeID, err)
|
||||
}
|
||||
delete(s.records, volumeID)
|
||||
s.publishLocked()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -408,9 +381,6 @@ func (s *FileStore) AttachVolume(volumeID, nodeID string) (VolumeRecord, error)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
rec, ok := s.records[volumeID]
|
||||
if !ok {
|
||||
return VolumeRecord{}, ErrVolumeNotFound
|
||||
@@ -435,9 +405,6 @@ func (s *FileStore) DetachVolume(volumeID, nodeID string) (VolumeRecord, error)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := recoveryRequired(s.writeErr); err != nil {
|
||||
return VolumeRecord{}, err
|
||||
}
|
||||
rec, ok := s.records[volumeID]
|
||||
if !ok {
|
||||
return VolumeRecord{}, ErrVolumeNotFound
|
||||
@@ -513,11 +480,7 @@ func (s *FileStore) putLocked(rec VolumeRecord) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("lifecycle: marshal %s: %w", rec.Spec.VolumeID, err)
|
||||
}
|
||||
err = writeRecordDurably(s.dir, rec.Spec.VolumeID+".json", raw)
|
||||
if err != nil {
|
||||
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
|
||||
}
|
||||
return err
|
||||
return writeRecordDurably(s.dir, rec.Spec.VolumeID+".json", raw)
|
||||
}
|
||||
|
||||
func (s *FileStore) path(volumeID string) string {
|
||||
|
||||
@@ -60,8 +60,6 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) {
|
||||
want = append(want, "/"+strings.Join(parts[:n], "/"))
|
||||
}
|
||||
want = append(want, "/")
|
||||
ancestor := want[len(want)-2]
|
||||
want = append(want, abs)
|
||||
var calls []string
|
||||
var warnings bytes.Buffer
|
||||
log.SetOutput(&warnings)
|
||||
@@ -70,7 +68,7 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) {
|
||||
fault := &os.PathError{Op: "open", Path: want[0], Err: os.ErrPermission}
|
||||
syncBindingParent = func(path string) error {
|
||||
calls = append(calls, path)
|
||||
if shape == "ancestor-permission" && path == ancestor {
|
||||
if shape == "ancestor-permission" && path == want[len(want)-2] {
|
||||
return &os.PathError{Op: "open", Path: path, Err: os.ErrPermission}
|
||||
}
|
||||
if failFirst {
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestVolumeEqualityRequiresRecovery(t *testing.T) {
|
||||
for _, mode := range []string{"reopen", "failed-put"} {
|
||||
t.Run(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=^TestVolumeRecoveryChild$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), "VOLUME_RECOVERY_MODE="+mode)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("volume recovery: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeRecoveryChild(t *testing.T) {
|
||||
mode := os.Getenv("VOLUME_RECOVERY_MODE")
|
||||
if mode == "" {
|
||||
t.Skip("isolated recovery hooks")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
s, err := OpenFileStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec := VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}
|
||||
rec, err := s.CreateVolume(spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.MarkStoreReady("v", rec.Spec.LayoutID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old, _ := s.GetVolumeSnapshot("v")
|
||||
fault := errors.New("injected volume directory barrier failure")
|
||||
callbacks := 0
|
||||
s.SetPersistenceFailureHandler(func(failure *RecordPersistenceError) {
|
||||
callbacks++
|
||||
if s.writeErr == nil || failure.Store != dir || failure.Record != "v.json" || !errors.Is(failure, fault) {
|
||||
t.Fatalf("incorrect volume policy context: %+v", failure)
|
||||
}
|
||||
})
|
||||
durableRecordHooksForTest.Store(&durableRecordHooks{dirSync: func(string) error { return fault }})
|
||||
defer durableRecordHooksForTest.Store(nil)
|
||||
if mode == "reopen" {
|
||||
if _, err := OpenFileStore(dir); !errors.Is(err, fault) {
|
||||
t.Fatalf("loaded volume published without recovery barrier: %v", err)
|
||||
}
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
reopened, err := OpenFileStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := reopened.GetVolumeSnapshot("v"); got != old {
|
||||
t.Fatal("recovery changed volume")
|
||||
}
|
||||
return
|
||||
}
|
||||
if _, err := s.AttachVolume("v", "node"); !errors.Is(err, fault) {
|
||||
t.Fatalf("attachment did not fail at barrier: %v", err)
|
||||
}
|
||||
if callbacks != 1 {
|
||||
t.Fatalf("volume failure callbacks=%d want1", callbacks)
|
||||
}
|
||||
if got, _ := s.GetVolumeSnapshot("v"); got != old {
|
||||
t.Fatal("failed attach published")
|
||||
}
|
||||
durableRecordHooksForTest.Store(nil)
|
||||
if _, err := s.CreateVolume(spec); !errors.Is(err, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("equal create must refuse after possibly-applied failure: %v", err)
|
||||
}
|
||||
_, redrawErr := s.RedrawPendingLayoutID("v", rec.Spec.LayoutID)
|
||||
_, markErr := s.MarkStoreReady("v", rec.Spec.LayoutID)
|
||||
_, attachErr := s.AttachVolume("v", "node")
|
||||
_, detachErr := s.DetachVolume("v", "node")
|
||||
for _, err := range []error{redrawErr, markErr, attachErr, detachErr, s.DeleteVolume("v")} {
|
||||
if !errors.Is(err, ErrLifecycleRecoveryRequired) {
|
||||
t.Fatalf("mutation after uncertainty: %v", err)
|
||||
}
|
||||
}
|
||||
reopened, err := OpenFileStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := reopened.GetVolumeSnapshot("v"); got.AttachedTo != "node" {
|
||||
t.Fatal("fixture did not retain renamed attachment")
|
||||
}
|
||||
if _, err := reopened.DetachVolume("v", "node"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := OpenFileStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := again.GetVolumeSnapshot("v"); !reflect.DeepEqual(got, old) {
|
||||
t.Fatal("recovered successful detach differs on disk")
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ The design is described in three documents, and this one collects their machines
|
||||
**Conventions.** These are the same as in the design documents.
|
||||
|
||||
- Code references name a file and a function, not a line number. Test references name the test function and its file.
|
||||
- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it; an entry naming a model checked outside the repository says so. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)).
|
||||
- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)).
|
||||
- Status:
|
||||
- `ACTIVE`: a Go test in this repository asserts the statement.
|
||||
- `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row.
|
||||
@@ -48,59 +48,6 @@ The design is described in three documents, and this one collects their machines
|
||||
|
||||
Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types.
|
||||
|
||||
### Lifecycle record I/O and supervised master recovery
|
||||
|
||||
This is the process projection of `INV-LIFECYCLE-STORE-DURABLE-001` and
|
||||
`INV-LIFECYCLE-FAILSTOP-001`; it adds no record format or authority state.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Recovering: supervisor starts master
|
||||
Recovering --> Ready: complete records loaded, directory barriers succeed
|
||||
Ready --> Ready: changed files synced, renamed, directory synced
|
||||
Ready --> Faulted: record put/import persistence failure
|
||||
Recovering --> Faulted: recovery directory sync failure
|
||||
Faulted --> Exited: one ERROR attempt, exit 74 within 1 s
|
||||
Exited --> Recovering: supervisor restarts
|
||||
```
|
||||
|
||||
| From | To | Guard | Enforced in | Protects |
|
||||
|---|---|---|---|---|
|
||||
| — | Recovering | the supervisor starts blockmaster with a lifecycle store | `cmd/blockmaster/main.go` `run`; `deploy/systemd/sw-blockmaster.service` | `INV-LIFECYCLE-FAILSTOP-001` |
|
||||
| Recovering | Ready | each node, placement and volume store loads complete records and its records-directory barrier succeeds; the cluster-spec import completes before serving | `core/lifecycle/node_inventory.go` `OpenNodeInventoryStore`; `core/lifecycle/placement_intent.go` `OpenPlacementIntentStore`; `core/lifecycle/store.go` `OpenFileStore`; `cmd/blockmaster/main.go` `run` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
|
||||
| Ready | Ready | a changed put or import: changed files are durable before rename (per-file fsync, or one `syncfs` on a qualified filesystem) and one directory barrier precedes publication; an unchanged record does no I/O and keeps its SeenAt | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `core/lifecycle/node_inventory.go` `ImportNodes`, `registrationLocked`; `core/lifecycle/placement_intent.go` `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-NODE-REGISTRATION-FRESHNESS-001` |
|
||||
| Ready | Faulted | a put or import returns a `RecordPersistenceError`; the store latches it, so later mutations return `ErrLifecycleRecoveryRequired`, before calling the process policy; a marshal error before any I/O does not latch | `core/lifecycle/record_file.go` `latchPersistenceFailure`; each store's `putLocked`, `ImportNodes`, `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
|
||||
| Recovering | Faulted | a store open's records-directory sync fails; `New` hands the `RecordPersistenceError` to the process policy | `core/lifecycle/record_file.go` `syncRecordDirectory`; `core/host/master/host.go` `New` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
|
||||
| Faulted | Exited | the policy arms a one-second exit timer, attempts one ERROR line, then exits 74 | `core/host/master/lifecycle_failure.go` `lifecycleFailStop` | `INV-LIFECYCLE-FAILSTOP-001` |
|
||||
| Exited | Recovering | the supervisor restarts blockmaster (`Restart=on-failure`) | `deploy/systemd/sw-blockmaster.service` | `INV-LIFECYCLE-FAILSTOP-001` |
|
||||
|
||||
A store latches the error before calling the process policy. A failed step may
|
||||
leave a mix of complete old and new files; recovery syncs their directory and
|
||||
startup reconciles the declarative import before serving. Temporary files are
|
||||
not records. On Linux >= 5.8 with the records on ext4, xfs, btrfs or tmpfs,
|
||||
startup import opens the records-directory fd before writing, writes and
|
||||
closes every changed temp, calls one `syncfs`, then renames all temps and
|
||||
syncs the directory before publication. A failed `syncfs` is never retried
|
||||
within the step: its writeback error may have been consumed. Recovery writes
|
||||
fresh temps. Older kernels, other filesystems (overlay, FUSE, NFS: syncfs does
|
||||
not reach their backing files) and other platforms retain per-file fsync
|
||||
before rename; startup reports the chosen path for the node and placement
|
||||
stores, each probed at its own directory. The filesystem-wide sync can
|
||||
also wait for unrelated writeback on that filesystem.
|
||||
The executable arms a one-second process-exit timer before logging
|
||||
and exits with status 74 (durability unknown) immediately after the log
|
||||
returns. The best-effort log reason is `lifecycle_persist_failed`; status 74
|
||||
alone does not identify a lifecycle fault, since authority-store faults use
|
||||
the same status. The process does not wait for graceful
|
||||
shutdown behind a writer. Embedders without this process policy must reopen a
|
||||
failed store before any further mutation. Removal errors do not invoke this
|
||||
policy: the in-memory record and its published snapshot stay present until
|
||||
removal succeeds, so a later retirement tick can retry. This is covered by
|
||||
`TestFailedRemoveKeepsRecordForRetry` and
|
||||
`TestSpecRetirementLocalFailureDoesNotStopOtherVolumesOrProductTick`.
|
||||
A successful removal still has the separate directory-sync limitation
|
||||
recorded below.
|
||||
|
||||
### M1 walstore: open, recover, serve, fault
|
||||
|
||||
The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent).
|
||||
@@ -192,7 +139,7 @@ flowchart LR
|
||||
|---|---|---|---|---|
|
||||
| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
|
||||
| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; new addresses, or the same addresses for another primary process (the line's incarnation differs); a no-op when both are unchanged; refused (`ErrExpectedLineMoved`) when the ask names the line it was decided against and the volume's line is no longer that one (replica, epoch, addresses) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/directive.go` `expectedLineMoved` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`, `INV-AUTH-RESTART-REISSUE-001` |
|
||||
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move; refused (`ErrExpectedLineMoved`) when the ask names the line it was decided against (the controller's rebalance and failover, an operator's failback) and the volume's line is no longer that one, compared by replica and epoch, and by addresses only when the ask names them (the controller's moves do; an operator's failback names replica and epoch only, so an endpoint move to other addresses does not refuse it): a queued controller move never overwrites a reassign or an endpoint move to other addresses that landed after its decision; a same-address endpoint reissue (new endpoint version or incarnation, same addresses) still matches, and the move's epoch bump fences it | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume`; `core/authority/directive.go` `expectedLineMoved`; `core/authority/controller.go` `decideVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
|
||||
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
|
||||
| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing; a write whose outcome is unknown (the directory fsync after the rename failed) fail-stops blockmaster, so no caller is told it failed | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
|
||||
| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` |
|
||||
| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` |
|
||||
@@ -201,34 +148,6 @@ flowchart LR
|
||||
| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` |
|
||||
| DeleteReserved, removed from the desired spec | Retired metadata (reservation permanent) | no live lease, then a fresh bounded HEAD read proves deleted or absent; unread/live/deleting keeps the records. Remove authority durably, then placement and bindings, then the volume record; a crash retries the remaining removals. A startup lease skip schedules one more pass after the latest observed barrier, also without the product loop; full passes log skips. The store and its resweep inputs are untouched | `core/host/master/spec_retirement.go` `ReconcileDeletedSpecVolumes`, `startPostFloorRetirement`; `core/authority/workspace_retirement.go` `RetireDeletedWorkspace` | `INV-SPEC-DELETE-RETIRE-001`, `INV-SPEC-DELETE-RETRY-001` |
|
||||
|
||||
**Controller ask, per volume (between the promotion gate and the publisher).**
|
||||
|
||||
The topology controller turns a supported snapshot into at most one ask per volume. The publisher drains the controller's queue one ask at a time (its `Run` loop, between two calls of `next`). A fenced replace decided by the supported gate is submitted with the replaced primary's slot unacceptable, whatever the gate's reason, so the controller's own acceptability predicate never keeps that primary. An ask is pending while it is queued or held by the publisher; an identical ask is deduplicated only while it is pending.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Queued: intake decides an ask (desired, DesiredAt set)
|
||||
Queued --> Held: publisher takes it (next)
|
||||
Held --> Published: apply publishes (line moves)
|
||||
Held --> Lost: apply ends without a publication (publisher calls next again)
|
||||
Lost --> Queued: next intake decides the identical ask (DesiredAt kept)
|
||||
Queued --> Queued: identical ask decided (already desired)
|
||||
Held --> Held: identical ask decided (already desired)
|
||||
Published --> [*]: snapshot observes the new line (desired confirmed)
|
||||
```
|
||||
|
||||
| From | To | Event and guard | Enforced in | Protects |
|
||||
|---|---|---|---|---|
|
||||
| no desired ask | Queued | an intake of a supported snapshot decides an ask; the desired entry records DesiredAt. A fenced replace (with or without a recorded loss) reaches the controller with the replaced primary's slot unreachable and not ready, so its intake decides the failover to the fenced target | `core/authority/controller.go` `processSupportedVolumeLocked`, `decideVolume`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-PROMOTE-REPLACE-HANDOFF-001`, `INV-PROMOTE-REPLACE-HANDOFF-002` |
|
||||
| Queued | Held | the publisher takes the ask; the queue records the volume it holds | `core/authority/queue.go` `next` | `INV-AUTH-DESIRED-RETRY-001` |
|
||||
| Queued or Held | (no change) | an intake decides the identical ask while it is pending: deduplicated (`already desired since T`), nothing queued twice | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/queue.go` `pending` | `INV-AUTH-DESIRED-RETRY-001` |
|
||||
| Held | Published | the apply publishes the line (epoch minted by the publisher) | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-EPOCH-MINT-001` |
|
||||
| Held | Lost | the apply ends without a publication (refused, or dropped); the publisher asks for its next ask, which clears the held volume | `core/authority/queue.go` `next` | `INV-AUTH-DESIRED-RETRY-001` |
|
||||
| Lost | Queued (DesiredAt kept) | an intake decides the identical ask while the line, re-read after the pending check, is still the one it decided against (an ask published during the intake is not lost): enqueued again (`enqueued again ...`), the desired entry and its DesiredAt unchanged | `core/authority/controller.go` `processSupportedVolumeLocked` | `INV-AUTH-DESIRED-RETRY-001`, `INV-AUTH-DESIRED-RETRY-002` |
|
||||
| any desired (unconfirmed) | Stuck evidence | DesiredAt + retry window passed without the line observed; a repeatedly lost ask reaches it from its first desire | `core/authority/convergence.go` `evaluateStuckLocked` | `INV-AUTH-DESIRED-RETRY-002` |
|
||||
|
||||
Model: PromoLive r6, checked outside the repository (it is not in `docs/spec/`), models this handoff with the intake split as the code does it (read the line and decide; after the publisher may have run, enqueue only if the ask is not pending and the line is still the one read). `RoundProgress` and `QueuedMatchesLine` hold; the mutants `dedupe_keeps_lost`, `predicate_split` and `nonatomic_submit` are each caught. The retry window and the Stuck evidence are not modelled; their test is the evidence.
|
||||
|
||||
**Volume creation phase, in blockmaster's store record** (`core/host/master/store_attestation.go`, decided by `inCreationPhase` in `core/host/master/product_loop.go`). Every replacement entry (both promotion gates, the operator's failover and planned move, the rebalance) acts only on Established.
|
||||
|
||||
```mermaid
|
||||
@@ -426,7 +345,6 @@ stateDiagram-v2
|
||||
| (start) | Attaching, Refused | the volume's host lock `/run/sw-block/locks/<volume id>.lock` is taken before the store opens; held by another live process, or its directory or file cannot be created or opened, refuses (`storage.ErrWALStoreLocked`, `ErrVolumeLockDirUnavailable`) | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` (from `ensureHandle`) | `INV-WS-ONE-PROCESS-PER-HOST-001` |
|
||||
| Attaching | Refused | a local root from another claim or behind HEAD's position (`layout.ErrStaleLocalRoot`): final typed refusal with a cure, no serving or retry | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `provider_chunk.go` `recoverChunk`, `chunkAuthorityWait` | `INV-WS-STALE-LOCAL-ROOT-001` |
|
||||
| (startup) | Refused | The agreed leader lists another filer or several; or all configured masters cannot agree and confirm exactly the target within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` |
|
||||
| (startup) | (startup), chunk guard on or off | on only if the filer definitely refuses the probe's mismatched chunk-condition update of a disposable HEAD; then every store the catalog opens sends the chunk condition. Any other answer leaves it off (page re-read only) and refuses nothing. sw-block metadata writers run the same probe within their --timeout | `core/frontend/chunkstore/startup_head_probe.go` `checkConditionalHead`, `probeChunkCondition`, `ProbeChunkGuard`; `cmd/sw-block/chunk_b.go` `bCatalog` | `INV-WS-CHUNK-CONDITION-PROBE-001` |
|
||||
| Claiming | Holder | Start validates the local root against the HEAD it conditionally updates; a fresh root seeds before claim, an ordinary reopen keeps its acknowledged local WAL and HEAD identity; guest I/O waits for assignment and claim | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/chunkstore/layout/claim.go` `RunClaim`; `core/frontend/durable/provider_layout.go` `startLayoutRoot` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-SNAPK-HEAD-WRITE-001` |
|
||||
| Claiming | Detached (non-serving) | a same-epoch detached HEAD refuses Start without changing its sealed image; a higher-epoch claimant retains that image | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/chunkstore/layout/claim.go` `Claim` | `INV-WS-SEALED-REOPEN-001` |
|
||||
| Claiming | Holder, or not installed | an unknown transition outcome is resolved by its claim/session identity and the current HEAD; no unverified local success | `core/frontend/chunkstore/layout/claim.go` `RunClaim`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead` | `INV-WS-CAS-UNKNOWN-001` |
|
||||
@@ -629,6 +547,8 @@ Tests: `TestMaintenanceKickRunsAPassNow`, `TestMaintenanceKickedBusyPassRetriesS
|
||||
`TestDefaultConfigCleansAfterEachSnapshotDelete`. Detach/fence/Close cancels and joins before
|
||||
catalog/storage release; only a still-current handle may re-arm after safe abort.
|
||||
A pass has no total deadline. Its one-minute no-progress window renews only on a strict advance of this pass's finite (phase, cursor) work position; a stalled pass answers `no_progress`. Each remote request has a separate 30 s deadline; request attempts never renew the window. The existing cursor resumes later; retention failure skips cleaning.
|
||||
A scoped GC pass traces the whole catalog but mutates only its target volume,
|
||||
with a separate scope/config-bound mark. Incomplete marks carry no coverage.
|
||||
|
||||
The scheduled-snapshot worker runs beside it under the same owner and join, on
|
||||
in-process monotonic time: `Armed -> Due -> Running -> Armed`. A success sets the
|
||||
@@ -674,10 +594,8 @@ stateDiagram-v2
|
||||
idle --> clean: BeginClean(c)
|
||||
clean --> idle: EndClean(c)
|
||||
snap --> snap: PublishList (durable session pages, base CAS)
|
||||
idle --> idle: DeleteSnapshotWithIntent (adoption chunk-conditioned when the guard is on, pages read again, one CAS)
|
||||
snap --> snap: DeleteSnapshotWithIntent (adoption chunk-conditioned when the guard is on, pages read again, one CAS)
|
||||
clean --> clean: AdvanceList (effects then cursor CAS)
|
||||
clean --> clean: roots, segments, chunk shards and unreached list pages (mark chunk-conditioned when the guard is on, conditional removal)
|
||||
clean --> clean: roots, segments, chunk shards and unreached list pages (conditional removal)
|
||||
idle --> deleting: MarkDeleting (no holder, no dependents)
|
||||
deleting --> deleted: MarkDeleted (after release and pool)
|
||||
```
|
||||
@@ -689,8 +607,8 @@ stateDiagram-v2
|
||||
| any version-1 HEAD with reserved lists | same reserved lists after any existing HEAD transition | at most three additional checked cursors, no repeated Ref across list/lists; deep clone and exact preservation; never consumed or a reason to refuse serving | `head.go` `check`, `clone`, `runTransition`; `remove.go` `Cleaner.Page` retains list metadata | `INV-LIST-RESERVED-001` |
|
||||
| snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every page durable; full slot returns queue_full without replacing work; unknown reply retains protection | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` |
|
||||
| clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` |
|
||||
| clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark (with the chunk guard on, also on unchanged chunk fids) then delete | `remove.go` `Cleaner.Page`; `layout_store.go` `changeMeta` | `INV-LIST-RETIRE-001`, `INV-LAYOUT-META-CHUNKS-001` |
|
||||
| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only captured name/gen and names its durable chain; each page present, this attempt's tag, unmarked, then read and authenticated again after adoption; with the chunk guard on, an adoption also needs the page's looked-up chunk fids unchanged; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent`; `layout_store.go` `changeMeta` | `INV-SNAPSHOT-DELETE-INTENT-001`, `INV-SNAPSHOT-DELETE-ADOPT-001`, `INV-SNAPSHOT-DELETE-ADOPT-002`, `INV-LAYOUT-META-CHUNKS-001` |
|
||||
| clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` |
|
||||
| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only captured name/gen and names its durable chain; each page present, this attempt's tag, unmarked; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001`, `INV-SNAPSHOT-DELETE-ADOPT-001` |
|
||||
| idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `BCatalog.CleanSnapshotDeletePage`; `LayoutRemote.Clean` | `INV-SNAPSHOT-DELETE-CONSUME-001` |
|
||||
| idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` |
|
||||
| snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` |
|
||||
@@ -700,7 +618,7 @@ stateDiagram-v2
|
||||
| any (Start) | idle at epoch e, claim id k | Start only: at HEAD's epoch it continues on the root carrying HEAD's claim id at or above HEAD's position, else refuses; above, a fresh root or the continuing lineage claims, validated against the HEAD the claim updates | start.go `Start`; claim.go `RunClaim` | `INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-POSITION-001`, `INV-SNAPK-START-ACTIVITY-001` |
|
||||
| idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` |
|
||||
| clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` |
|
||||
| clean(c) | clean(c), names removed | holder at HEAD's epoch, server and claim id with clean(c) open; candidate tags precede each HEAD validation; unreachable roots, then segments, then chunks; mark conditional on the planned tag (with the chunk guard on, also on unchanged chunk fids), delete conditional on its own mark | remove.go `Cleaner.removePlanned`; layout_store.go `changeMeta` | `INV-SNAPK-REMOVE-MARK-001`, `INV-CLEAN-METADATA-001`, `INV-CLEAN-CURSOR-001`, `INV-LAYOUT-META-CHUNKS-001` |
|
||||
| clean(c) | clean(c), names removed | holder at HEAD's epoch, server and claim id with clean(c) open; candidate tags precede each HEAD validation; unreachable roots, then segments, then chunks; mark conditional on the planned tag, delete conditional on its own mark | remove.go `Cleaner.removePlanned` | `INV-SNAPK-REMOVE-MARK-001`, `INV-CLEAN-METADATA-001`, `INV-CLEAN-CURSOR-001` |
|
||||
| idle (live or detached) | deleting | the master reserved the volume for delete (no line granted after), then no line holds a live lease, checked between the HEAD read and the update; no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `RunMarkDeleting` (`DeleteAuthority`) | `INV-SNAPK-DELETE-ORDER-001` |
|
||||
| absent | deleted (tombstone) | the operator's remove-dependent, for a restore target without HEAD (never created, or a restore died between its two creates); one exclusive create, so a later HEAD create of the restore fails; a HEAD appearing first refuses | delete.go `OperatorReleaseDependent` (`TargetStore.CreateDeletedHead`) | `INV-SNAPK-TOMBSTONE-001`, `INV-SNAPK-HEAD-WRITE-001` |
|
||||
| source: any live | source: target released | by the target's volume id, from every snapshot: from DeleteVolume once the target's HEAD is deleting, or from the operator's command once the target is deleted, of another id, no longer naming the source, or tombstoned; an absent target writes nothing | delete.go `Head.ReleaseDependent`, `RunReleaseDependent`, `OperatorReleaseDependent` | `INV-SNAPK-RELEASE-001`, `INV-SNAPK-RELEASE-CALLERS-001`, `INV-SNAPK-RELEASE-OPERATOR-001` |
|
||||
@@ -1038,8 +956,6 @@ Notes:
|
||||
| `INV-CLI-TYPED-REFUSAL-001` | The chunk CLI reports a restore the master refused for a foreign source as `restore_source_not_own` (from the master's typed reason, never its text) and a volume the master does not know as `volume_not_found`. | M2 none → created (restore refusal); CLI volume resolve | `core/host/master/services.go` `CreateVolume`; `core/rpc/lifecycleclient/reason.go` `WithReason`, `Reason`; `cmd/sw-block/chunk_b.go` `chunkRestore`, `run` | `TestOpsChunkTypedRefusalCodes` (`cmd/sw-block/chunk_typed_codes_test.go`), `TestReasonRoundTrip` (`core/rpc/lifecycleclient/reason_test.go`), `TestARealCatalogRestoreOfARestoreTargetLeavesNothing` (`core/host/master/restore_refusal_catalog_test.go`) | — (reporting only; the refusal is `INV-CREATE-ONE-IDENTITY-001`'s). Limits: other FailedPrecondition refusals stay the generic `not_admitted` | ACTIVE |
|
||||
| `INV-CLI-RESTORE-VERB-001` | `volume restore --abort` changes nothing unless the master records this command's source, snapshot and request id for the target and this host's settings name exactly it (volume, master, `--layout-id` alone in the extra arguments); a re-run counts only this replica's published line as placed. | client (no state machine): the CLI side of M2 restore create, placement and delete | `cmd/sw-block/volume_backup.go` `volumeRestoreAbort`, `volumeRestore`, `restorePlaced`; `core/host/master/services.go` `lifecycleVolumeResponse` | `TestVolumeRestoreAbortRefusesAForeignTarget`, `TestVolumeRestoreAbortRefusesAnotherLocalInstallation`, `TestVolumeRestoreAbortInterruptedAtEveryStepCompletes`, `TestVolumeRestoreCrashTableBothWays`, `TestVolumeRestorePublicationDuringThePlacement`, `TestVolumeRestorePlacementOfAnotherLineRefuses`, `TestVolumeRestoreCreatesPlacesAndStarts`, `TestVolumeBackupTakesOneSnapshotAndRerunReplays`, `TestVolumeBackupRefusals`, `TestVolumeBackupIncompleteAnswerIsUnknown` (`cmd/sw-block/volume_backup_test.go`), `TestGetVolumeAnswersTheRecordedRestoreTuple` (`core/host/master/volume_restore_tuple_test.go`) | — (the command's model is checked outside the repository; its trace is on the pull request) | ACTIVE |
|
||||
| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`); also in `core/authority/layout_granted_epoch_guard_test.go` | `ControlPlane` `UniqueEpoch` | ACTIVE |
|
||||
| `INV-AUTH-DESIRED-RETRY-001` | The controller deduplicates a desired ask only while it is pending: queued, or taken by the publisher and still being applied. An identical ask that ended without a publication, the line still the one it was decided against, is enqueued again on the next intake. | M2 controller ask: Queued or Held (deduplicated); Held → Lost; Lost → Queued | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/queue.go` `pending`, `next` | `TestALostReassignIsEnqueuedAgainOnTheNextIntake`, `TestAnAskPublishedDuringTheIntakeIsNotEnqueuedAgain` (`core/authority/controller_lost_ask_test.go`) | PromoLive r6 (outside the repository) `QueuedMatchesLine`, `RoundProgress` (mutants `dedupe_keeps_lost`, `nonatomic_submit`) | ACTIVE |
|
||||
| `INV-AUTH-DESIRED-RETRY-002` | An ask enqueued again keeps its first DesiredAt, so an ask lost on every apply still becomes Stuck once the retry window passes from that first desire. | M2 controller ask: Lost → Queued (DesiredAt kept); Stuck evidence | `core/authority/controller.go` `processSupportedVolumeLocked`; `core/authority/convergence.go` `evaluateStuckLocked` | `TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck` (`core/authority/controller_lost_ask_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (the retry; the retry window and Stuck are not modelled: the test is the evidence) | ACTIVE |
|
||||
| `INV-AUTH-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`, `refreshAsk` (conditional on the line it read); `core/host/master/product_loop.go` `RunLifecycleProductTick`, `restartedHolderRefresh` (the product loop's direct path for a workspace-bound RF1 volume, conditional on the line it read); `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestRF1RuntimeVolumeIsReissuedToARestartedHolder`, `TestRF1RuntimeLineNamingNoProcessIsReissued`, `TestRF1RefreshDecidedBeforeACrossHostMoveIsNotApplied` (`core/host/master/rf1_restart_reissue_test.go`); `TestRefreshIsConditionalOnTheLineItWasDecidedAgainst`, `TestControllerRefreshNamesTheLineItWasDecidedAgainst` (`core/authority/refresh_expected_line_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | ACTIVE |
|
||||
| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
|
||||
| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE |
|
||||
@@ -1057,16 +973,14 @@ Notes:
|
||||
| `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE |
|
||||
| `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestACleanMoveReleasesTheTopologyHome`, `TestTheTopologyHomeHoldsTheVolumeBeforeAMove`, `TestTheTopologyHomeAloneHoldsTheVolumeBeforeAMove` (`core/host/master/served_topology_move_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |
|
||||
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
|
||||
| `INV-NODE-REGISTRATION-FRESHNESS-001` | Replaying a node registration without an observation time preserves its stored SeenAt; unchanged non-time fields do not rewrite its record. A restart is not a fresh observation, also when the declaration changed; a live heartbeat supplies freshness independently. | M2 lifecycle registration replay (no authority transition) | `core/lifecycle/node_inventory.go` `ImportNodes`, `RegisterNode`, `registrationLocked`; `core/host/master/observation_snapshot.go` `nodeHeartbeat`; `core/lifecycle/verified_placement.go` `VerifyPlacementIntent` | `TestUnchangedNodeRestartDoesNotRefreshAStaleObservation`, `TestChangedNodeImportDoesNotRefreshAStaleObservation` (`core/lifecycle/node_import_freshness_test.go`); `TestObservationNodesReportTheNewestHeartbeat` (`core/host/master/observation_heartbeat_test.go`); live-holder process restart qualification pending | Observation time is evidence, not authority; a declaration is not an observation | STUB |
|
||||
| `INV-LIFECYCLE-STORE-DURABLE-001` | A successful record put/import publishes only after complete replacement records and their directory are durable. Open syncs the records directory before publication. A possibly-applied failure blocks mutations until reopen; recovery reconciles complete old/new records. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `node_inventory.go` `ImportNodes`; `placement_intent.go` `ImportPlans`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`); `TestImportStepSyncsChangedFilesThenOneDirectory` (`core/lifecycle/import_step_sync_test.go`); `TestImportSyncfsFailureAndOrdering`, `TestImportSyncfsReturnedFailurePolicyAndReplay`, `TestImportSyncfsCrashBoundaries`, `TestSyncfsKernelGate`, `TestSyncfsFilesystemGate`, `TestImportBatchSelectsSyncfsByFilesystem`, `TestImportDurabilityModeProbesEachStoreDirectory` (`core/lifecycle/import_syncfs_test.go`); `TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk` (`core/lifecycle/import_recovery_test.go`); `TestVolumeEqualityRequiresRecovery` (`core/lifecycle/volume_recovery_test.go`); `TestNodeMarshalErrorDoesNotRequireRecovery` (`core/lifecycle/remove_retry_test.go`) | Lifecycle record publication, including startup-step durability barrier | ACTIVE |
|
||||
| `INV-LIFECYCLE-FAILSTOP-001` | A supervised master exits 74 (durability unknown) within one second of a lifecycle put/import or open-barrier persistence failure, independently of logging. It attempts one ERROR; restart completes recovery barriers and import before serving. | Lifecycle process ready/recovering → faulted → exited → recovering | `core/host/master/lifecycle_failure.go` `lifecycleFailStop`; `host.go` `New`; `cmd/blockmaster/main.go` `run`; lifecycle store failure handlers | `TestMasterImportPersistenceFailureExitsAndRecovers` (`cmd/blockmaster/persist_exit_test.go`); `TestLifecyclePersistenceFailureStopsTheProcess`, `TestLifecycleFailStopExitsWithBlockedLogger` (`core/host/master/lifecycle_failure_test.go`) | Manual process-fault/recovery projection of lifecycle record durability; no new wire or format state | ACTIVE |
|
||||
| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE |
|
||||
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
|
||||
| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE |
|
||||
| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners bind only loopback: --listen without mutual TLS, and the runtime HTTP listener always; a non-loopback address, and --insecure-external-bind, are refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_PlaintextControlListenersStayOnLoopback`, `TestManifests_NoPlaintextExternalBlockmasterBind` (`cmd/blockmaster/external_bind_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE |
|
||||
|
||||
Notes:
|
||||
|
||||
- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: Store-directory ancestor sync on Open is best-effort: failures are logged and do not block startup; a new directory entry may not survive an immediate crash when an ancestor cannot be synced. Record-file and store-directory sync after a put remain mandatory. `NodeInventoryStore.RemoveNode`, `PlacementIntentStore.DeletePlacement` and `FileStore.DeleteVolume` do not fsync their directory after deletion, so a removed node, placement or volume record can reappear after a crash. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record.
|
||||
- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: Store-directory ancestor sync on Open is best-effort: failures are logged and do not block startup; a new directory entry may not survive an immediate crash when an ancestor cannot be synced. Record-file and store-directory sync after a put remain mandatory. `NodeInventoryStore.RemoveNode` does not fsync its directory after deletion, so a removed node can reappear after a crash. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record.
|
||||
- `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`: a failure before the rename leaves the old record and is reported failed (the in-memory rollback test); a directory open or fsync failure after the rename leaves the outcome unknown and fail-stops the process, for every record type, so the restart reloads whatever survived and callers re-read. A workspace volume's uncertainty latch (`INV-AUTH-UNCERTAIN-001`) stays for its other causes.
|
||||
- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, then a failure; the file store fail-stops on a directory fsync failure instead, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`.
|
||||
- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2).
|
||||
@@ -1124,7 +1038,7 @@ Notes:
|
||||
| `INV-WS-HEAD-KEY-PROVENANCE-001` | RETIRED at the cut-over to the content-named store: intents are gone and a content name may be written again. Replaced by `INV-SNAPK-COMMIT-REACH-001`. | M5 Manifest → CAS | — (`PrepareManifest` and `core/frontend/chunkstore/manifest.go` were deleted) | — | — | ARCHIVED |
|
||||
| `INV-WS-REOPEN-FENCE-001` | Retired: the legacy same-holder reopen replaced HEAD generation. B fences by claim id and local-root lineage (`INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-CLAIM-001`, `INV-SNAPK-STALE-HOLDER-001`); an ordinary same-root reopen may leave HEAD unchanged. | legacy M4 | — | — | — | ARCHIVED |
|
||||
| `INV-WS-SEALED-REOPEN-001` | A same-epoch Start cannot reactivate a detached HEAD: it refuses before another HEAD update or serving, preserving its current root, position and detached state for a higher-epoch claimant. | M9 detached → higher-epoch idle | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition` (`core/frontend/chunkstore/layout/detached_test.go`); `TestRestoreEqualOwnerDetachedHEADStaysSealed` (`core/frontend/durable/provider_seed_order_test.go`) | `INV-SNAPK-DETACHED-001` | ACTIVE |
|
||||
| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after a same-epoch detached restart, succeeds only from a fresh B HEAD with exact epoch, holder and local claim id. It returns that HEAD/frontier without a new generation. An unreadable or mismatched proof cannot be answered from process memory. | B detached HEAD read | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`, `readLayoutSeal`; `cmd/blockvolume/workspace_lease.go` `workspaceLayoutDetachedGeneration` | `TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory` (`core/frontend/durable/provider_layout_plain_replay_test.go`); `TestWorkspaceLayoutDetachedProof` (`cmd/blockvolume/workspace_layout_proof_test.go`) | K1: detached proof belongs to the exact claim; `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` (mutants `PlainSealReplay_memory`, `PlainSealReplay_no_exact`, `PlainSealReplay_layer`) | ACTIVE |
|
||||
| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after a same-epoch detached restart, succeeds only from a fresh B HEAD with exact epoch, holder and local claim id. It returns that HEAD/frontier without a new generation. An unreadable or mismatched proof cannot be answered from process memory. | B detached HEAD read | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`, `readLayoutSeal`; `cmd/blockvolume/workspace_lease.go` `workspaceLayoutDetachedGeneration` | `TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory` (`core/frontend/durable/provider_layout_plain_replay_test.go`); `TestWorkspaceLayoutDetachedProof` (`cmd/blockvolume/workspace_layout_proof_test.go`) | K1: detached proof belongs to the exact claim | ACTIVE |
|
||||
| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its session stays open; settlement replays the same commit in it. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/frontend/chunkstore/layout_remote.go` | `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestSession_UncertainCommitIsNotAbortedUntilSettled` (`core/storage/chunk_layer_session_test.go`); `TestLayoutRemote_LostReplyOfTheFirstCutIsNotAFence`, `TestLayoutRemote_LostReplyOfALaterCutWithAnInheritedChunkIsNotAFence`, `TestLayoutRemote_LostReplyOfANoOpCutIsNotAFence` (`core/frontend/chunkstore/layout_remote_same_proposal_test.go`); `TestLevelZeroCutRefusalDoesNotBecomeAnUnresolvedPublication` (`core/frontend/chunkstore/layout_format_refusal_test.go`); `TestARefusedReproposalDoesNotSettleAnEarlierUnknownWrite`, `TestARefusedConfirmationReadDoesNotUnpublishTheSuccessfulWrite` (`core/storage/chunk_head_refusal_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new B holder claims HEAD at its issued epoch only after the local root is validated against the HEAD it updates; an older epoch or another holder at the same epoch is refused, and guest writes stay closed until assignment and claim. | M9 Start → Claim → Serving | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/durable/provider_layout.go` `startLayoutRoot` | `TestStart_ValidatesAgainstTheHeadItUpdates`, `TestStart_Refusals` (`core/frontend/chunkstore/layout/start_test.go`); `TestStart_TheClaimRechecksTheSeedRule` (`core/frontend/chunkstore/layout/start_seed_test.go`); `TestFreshStoreRefusesWriteBeforeAssignmentThenPublishesAfterClaim` (`core/frontend/durable/provider_restore_schedule_test.go`) | `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-CLAIM-001` | ACTIVE |
|
||||
| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go`; `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal`; `core/frontend/chunkstore/layout/volume.go`, `start.go`, `create.go`; `core/frontend/chunkstore/catalog_b.go` | `TestGeometryFlagsRefusalComparesTheRecord`, `TestVolumeRequiresGeometry`, `TestVolumeGeometryChecksAndIsImmutable`, `TestStartGeometryMismatchPrecedesClaim`, `TestBCatalogRestoreCopiesVolumeGeometry`, `TestVolumeGeometryLivesOnlyInVolume` | K3: immutable required VOLUME geometry; Start checks the local persisted shape before claim; restores copy source geometry; no resize or compatibility path. | ACTIVE |
|
||||
@@ -1132,7 +1046,6 @@ Notes:
|
||||
| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE |
|
||||
| `INV-CHUNK-LEASE-REQUIRED-001` | Blockvolume refuses walstore-chunk startup without --workspace-lease before any host or store is opened. The refusal names concurrent acknowledging writers and acknowledged-write loss after a forced move; plain walstore startup is unchanged. | M4 startup → Refused | `cmd/blockvolume/main.go` `parseFlags` | `TestChunkVolumeRequiresWorkspaceLeaseBeforeStart` | — | ACTIVE |
|
||||
| `INV-WS-CONDITIONAL-HEAD-001` | Catalog startup requires a wrong-generation conditional update of a disposable HEAD to be definitely refused and leave its bytes and generation unchanged. Unknown probe outcomes refuse admission; cleanup failures only warn with the leftover path. No volume HEAD is used. | M4 startup → Refused | `core/frontend/chunkstore/swfs_catalog.go` `DialBCatalog`; `startup_head_probe.go` `checkConditionalHead` | `TestCatalogStartupRequiresWrongGenerationHeadRefusal`, `TestConditionalHeadNextStartCleansCrashLeftovers`, `TestConditionalHeadSweepWaitsAndLeavesNewProbes`, `TestCatalogStartupDoesNotWaitForUndeletableProbe`, `TestLayoutIdentityWriterAndReaders` | — | ACTIVE |
|
||||
| `INV-WS-CHUNK-CONDITION-PROBE-001` | Catalog startup and sw-block metadata writers turn the chunk guard on only if the filer definitely refuses a mismatched chunk-condition update of a disposable HEAD; any other answer leaves the page re-read as the only check. No version string is read; the startup log and /status/chunk name it. | M4 startup | `core/frontend/chunkstore/startup_head_probe.go` `probeChunkCondition`, `ProbeChunkGuard`; `catalog_b.go` `Store`, `MetadataGuard`, `Usage`; `cmd/sw-block/chunk_b.go` `bCatalog` | `TestTheStartupProbeTurnsTheChunkGuardOnOnlyForAFilerThatEnforcesIt` (`core/frontend/chunkstore/startup_chunk_condition_probe_test.go`), `TestAFailedChunkGuardProbeLeavesTheGuardOff` (`core/frontend/chunkstore/chunk_guard_report_test.go`), `TestCatalogStartupRequiresWrongGenerationHeadRefusal` (`core/frontend/chunkstore/startup_head_probe_test.go`), `TestStatusServer_StatusChunkUsage` (`core/host/volume/status_chunk_test.go`), `TestOpsChunkWritingCatalogRunsTheChunkConditionProbe`, `TestOpsChunkWritingCatalogProbeIsBoundedByTheTimeout` (`cmd/sw-block/chunk_guard_probe_test.go`) | MetaABA r2, checked outside the repository: guard on = `safe_chunks_equal`; the fallback is the re-read, which a chunk still queued for deletion defeats (`mut_reread_delayed`) | ACTIVE |
|
||||
| `INV-WS-SINGLE-FILER-001` | Startup requires all configured masters to answer and agree on a leader; only that leader listing exactly the target filer and confirming leadership afterward admits. Followers' lists do not decide. Unknown views retry within 60 s. This census does not fence later filer registration. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestSingleFilerCensusUsesTheAgreedLeader`; `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerNeedsEveryMasterToAnswer`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
|
||||
| `INV-CLI-SINGLE-FILER-CLIENT-001` | Chunk metadata commands refuse missing, typed-nil and non-SWFS clients before catalog access; only a live SWFS client can run the census. | M4 startup client admission | `cmd/sw-block/chunk.go` `checkSingleFiler`, `refuseUnlessSingleFiler` | `TestSingleFilerCheckRefusesUnsupportedClients`, `TestOpsChunkWritingRefusesUnsupportedFilerBeforeCatalogAccess` | — (client capability guard) | ACTIVE |
|
||||
| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | ACTIVE |
|
||||
@@ -1295,8 +1208,8 @@ Notes:
|
||||
| `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused for held host slots, pending urgent work or an earlier ticket is a wait, not a failure: no backoff or minimum spacing; it retries at the next poll in ticket order, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitEndsTheWait`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestCutPolicy_TicketOrderWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
|
||||
| `INV-SNAPSHOT-ANSWER-COUNT-001` | Newly produced snapshot creation and listing answers omit the uncomputed chunk count; no manifest scan is added to answer a snapshot. | M9 snapshot answer projection (no transition change) | `core/frontend/chunkstore/control_types.go`, `api.go`; `core/host/volume/chunk_control.go` | `TestSnapshotAfter200MiBWritesOmitsUncomputedChunkCount` (`core/host/volume/snapshot_chunk_count_test.go`) | NONE (pure projection of the published snapshot; no authority or persisted format change) | STUB |
|
||||
| `INV-SPEC-DELETE-RETIRE-001` | Retire spec-removed metadata only under a permanent reservation after no-live-lease and a subsequent HEAD read proves deleted or absent. Read errors, live HEAD and deleting HEAD keep the records. Retirement never removes the reservation or store data. | M4 delete retirement | `core/host/master/spec_retirement.go`; `core/authority/workspace_retirement.go`, `authority_store_file.go` | `TestSpecRetirementReadsHeadOnlyAfterLeaseAndKeepsTombstone`, `TestSpecRetirementRequiresDeletedOrAbsentAndReadableHead`, `TestSpecRetirementDoesNotUseAbsentHeadWithoutReservation`, `TestRetirementKeepsReservationAndWaitsForLiveLease`, `TestFileAuthorityRetirementSurvivesReloadAndKeepsOtherRecords`, `TestSpecRetirementBackgroundBoundsReadsAndCachesTerminalProof`, `TestSpecRetirementLocalFailureDoesNotStopOtherVolumesOrProductTick` | DeleteRetire.ReadOK; DeleteRetire.RetireLine; DeleteRetire.RetirePlace; DeleteRetire.HostRetire | STUB |
|
||||
| `INV-SPEC-DELETE-RETRY-001` | Startup lease barriers schedule one more retirement pass after the latest observed barrier, independently of the product loop. The pass rechecks every lease and HEAD guard, logs skipped volumes, and is cancelled and joined before stores close. | M4 delete retirement scheduling | `core/host/master/host.go` `Start`, `Close`; `spec_retirement.go` `startPostFloorRetirement` | `TestStandaloneRestartRetriesSpecRetirementAfterLeaseFloor`, `TestRetirementLeaseBarrierIsOnlyASchedulingHint`, `TestPostFloorRetirementTimerJoinsOnCancellation` | DeleteRetire.ReadOK; DeleteRetire.RetireLine; DeleteRetire.RetirePlace | STUB |
|
||||
| `INV-SPEC-DELETE-RETIRE-001` | Retire spec-removed metadata only under a permanent reservation after no-live-lease and a subsequent HEAD read proves deleted or absent. Read errors, live HEAD and deleting HEAD keep the records. Retirement never removes the reservation or store data. | M4 delete retirement | `core/host/master/spec_retirement.go`; `core/authority/workspace_retirement.go`, `authority_store_file.go` | `TestSpecRetirementReadsHeadOnlyAfterLeaseAndKeepsTombstone`, `TestSpecRetirementRequiresDeletedOrAbsentAndReadableHead`, `TestSpecRetirementDoesNotUseAbsentHeadWithoutReservation`, `TestRetirementKeepsReservationAndWaitsForLiveLease`, `TestFileAuthorityRetirementSurvivesReloadAndKeepsOtherRecords`, `TestSpecRetirementBackgroundBoundsReadsAndCachesTerminalProof`, `TestSpecRetirementLocalFailureDoesNotStopOtherVolumesOrProductTick` | DeleteRetire.ReadOK; DeleteRetire.Retire; DeleteRetire.HostRetire | STUB |
|
||||
| `INV-SPEC-DELETE-RETRY-001` | Startup lease barriers schedule one more retirement pass after the latest observed barrier, independently of the product loop. The pass rechecks every lease and HEAD guard, logs skipped volumes, and is cancelled and joined before stores close. | M4 delete retirement scheduling | `core/host/master/host.go` `Start`, `Close`; `spec_retirement.go` `startPostFloorRetirement` | `TestStandaloneRestartRetriesSpecRetirementAfterLeaseFloor`, `TestRetirementLeaseBarrierIsOnlyASchedulingHint`, `TestPostFloorRetirementTimerJoinsOnCancellation` | DeleteRetire.ReadOK; DeleteRetire.Retire | STUB |
|
||||
| `INV-SPEC-UNUSED-PLACEMENT-001` | A spec startup prunes an undesired placement only before serving and with no volume record, authority line, binding or deletion reservation, and no skipped authority recovery. The desired spec and seed are one keep set. | M4 registration input | `cmd/blockmaster/main.go`; `core/host/master/spec_retirement.go` | `TestClusterSpecImportRemovesUnusedPlacementMissingFromSpec`, `TestClusterSpecCleanupKeepsRecordsBindingsAuthorityAndSeed` | NONE (registration-only cleanup before controller activity) | STUB |
|
||||
| `INV-CHECK-DELETING-001` | A post-lease reserved volume with HEAD deleting, deleted or absent holds no serving work. Its status is informational and checks issue no lease or holder requests for it. Another volume's failures remain visible. | M9 delete observation | `core/host/master/observation_snapshot.go`, `journal_isolation.go`; `cmd/sw-block/shell_check.go` | `TestSpecRetirementRequiresDeletedOrAbsentAndReadableHead`, `TestSpecRetirementReadsHeadOnlyAfterLeaseAndKeepsTombstone`, `TestClusterCheckDoesNotProbeDeletingOrDeletedVolumes` | DeleteRetire.HostRetire | STUB |
|
||||
| `INV-CLI-DELETE-RETRY-001` | Only the final lease barrier after a committed volume-delete reservation permits retryable true/exit 75 at its horizon. A live-holder Reserve refusal requires stopping the volume first (not_admitted, non-retryable, exit 1). No lease guard is bypassed. | M9 delete admission result projection | `cmd/sw-block/chunk_volume_delete.go` `authorityErr`; `cmd/sw-block/chunk.go` `chunkResult` | `TestVolumeDeleteAdmissionRetryAnswer`; `TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted` | MoveAdmission.DelRead; MoveAdmission.DelMark (unchanged guards) | STUB |
|
||||
@@ -1410,10 +1323,6 @@ Notes:
|
||||
| `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
|
||||
| `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | The automatic path never replaces a lost primary of a `best_effort` volume (a write may be on the primary alone, as for the operator's move): both gates hold it before any fencing round and show `best_effort_no_automatic_failover`. | M3 Supporting → promotion candidate (both gates) | `core/host/master/product_loop.go` `automaticFailoverHold` (supported gate before `fencedDecision`; unsupported gate before its candidates); `promotionAllowedReplicas` | `TestTheAutomaticPathHoldsABestEffortVolume` (`core/host/master/best_effort_hold_test.go`); `TestMountedFailover_ProductLoopRF3BestEffortIsHeldDespiteAHighestDurableSurvivor`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
|
||||
| `INV-PROMOTE-ACK-PROFILE-MATCH-001` | The automatic path holds a lost primary's volume, before any fencing round and showing `ack_profile_mismatch`, when a probe answer names no ack profile or another than blockmaster's `--launcher-replication-ack`; blockmaster refuses to start with an unknown one. | M3 Supporting → promotion candidate (both gates) | `core/host/master/probe_round.go` `profileMismatch`; `core/host/master/product_loop.go` `automaticFailoverHold` (plain round), `fencedDecision` (fencing round); `core/host/volume/probe_round.go` `probeAnswer`; `cmd/blockvolume/main.go` `hostConfig`; `cmd/blockmaster/main.go` `parseFlags` | `TestTheAutomaticPathHoldsOnAnAckProfileMismatch`, `TestProbeRound_ReportsAnAckProfileMismatch`, `TestTheFencingRoundsAckProfileIsCheckedToo` (`core/host/master/ack_profile_mismatch_test.go`); `TestProbeAnswerNamesTheVolumesAckProfile` (`core/host/volume/probe_ack_profile_test.go`); `TestHostConfigAnswersTheVolumesOwnAckProfile` (`cmd/blockvolume/probe_ack_profile_test.go`); `TestBlockmasterRefusesAnUnknownLauncherReplicationAck` (`cmd/blockmaster/launcher_replication_ack_flag_test.go`) | — | ACTIVE |
|
||||
| `INV-PROMOTE-DECISION-REPORTED-001` | Every replace decision of the supported promotion gate is logged once after its tick: with the controller's outcome from the same submission (read under its lock, so a later intake cannot change it), as not submitted and why, or as a failed submit. Diagnostics only: no decision changes. | M3 Supporting → promotion candidate (supported gate → controller → publisher) | `core/host/master/product_loop.go` `submitPlacementSnapshots`, `noteGateReplace`, `reportReplaces`; `core/authority/controller.go` `SubmitObservedStateOutcomes`, `LastOutcome` | `TestAReplaceDecisionLogsWhatTheControllerDidWithIt` (cases: enqueued, already desired, no ask with why, not submitted, an intake after the submission does not change its report, a submission that did not carry the volume, one report per decision), `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication`, `TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted` (`core/host/master/gate_controller_outcome_test.go`, `core/host/master/gate_binding_read_failure_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
|
||||
| `INV-AUTHORITY-PUBLICATION-LOGGED-001` | Every authority publication is logged on the master's log with its volume, replica, epoch, endpoint version and intent, also when no event sink is set. Diagnostics only: no decision changes. | M3 controller → publisher (publication observer) | `core/host/master/product_loop.go` `recordAuthorityPublishedEvent` | `TestAPublicationIsLogged`, `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication` (`core/host/master/gate_controller_outcome_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
|
||||
| `INV-PROMOTE-REPLACE-HANDOFF-001` | A fenced replace decided by the supported promotion gate, whatever its reason (a recorded loss, or a primary only the gate reads as unacceptable, such as one on a node below the cluster's format level), submits the replaced primary's slot as unreachable and not ready. | M2 controller ask: no desired ask → Queued (failover) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign` (`core/host/master/gate_controller_replace_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (mutant `predicate_split`) | ACTIVE |
|
||||
| `INV-PROMOTE-REPLACE-HANDOFF-002` | The controller never keeps a primary the gate replaced by its own acceptability predicate: it publishes the fenced target with its fenced evidence, the line minted only at the fenced epoch. | M2 controller ask: no desired ask → Queued (failover); M3 Primary → another replica Primary at e+1 | `core/authority/controller.go` `decideVolume` | `TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign` (`core/host/master/gate_controller_replace_test.go`); `TestALostPrimarysFencedReplacementIsPublished` (`core/host/master/primary_loss_publish_test.go`) | PromoLive r6 (outside the repository) `RoundProgress` (mutant `predicate_split`) | ACTIVE |
|
||||
| `INV-PRIMARY-ACK-PROFILE-001` | A primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (blockmaster's); otherwise its frontend is not Healthy and status names both profiles. So a lost primary, which does not answer, acknowledged under the master's profile. | M1 Primary → Serving (replicated line) | `core/host/master/services.go` `assignmentFact` (`ack_profile`); `core/host/volume/workspace_startup.go` `noteAckProfile`; `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/host/volume/status_server.go` | `TestPrimaryOfAReplicatedLineServesOnlyUnderTheMastersAckProfile` (`core/host/volume/ack_profile_refusal_test.go`); `TestAssignmentNamesTheMastersAckProfile` (`core/host/master/ack_profile_mismatch_test.go`) | — | ACTIVE |
|
||||
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
|
||||
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
|
||||
@@ -1435,7 +1344,6 @@ Notes:
|
||||
- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only.
|
||||
- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`.
|
||||
- `INV-PROMOTE-FRONTIER-PROBE-001`, `INV-PROMOTE-FRONTIER-UNKNOWN-001`, `INV-PROMOTE-FRONTIER-BEST-EFFORT-001`: new rows split from `INV-PROMOTE-FRONTIER-001`, kept beside it. N_peers is the number of replicas other than the current primary; for RF=3 (two peers) both must be seen under `sync_quorum`, one under `sync_all`. An unknown frontier is never read as zero. Heartbeat freshness is the observation store's rule (`FreshSlotCandidate`). The gate runs for every volume with two or more slots (RF=2 included); a primary change is published only with its evidence.
|
||||
- `INV-PROMOTE-DECISION-REPORTED-001`: a decision is not submitted when the placements changed during the probe, a volume got a workspace binding, a replica's endpoints are bound elsewhere, or the workspace bindings could not be read after the probe; the line names which. `INV-AUTHORITY-PUBLICATION-LOGGED-001` was split from it.
|
||||
- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values.
|
||||
- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only.
|
||||
- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence.
|
||||
@@ -1590,8 +1498,6 @@ Notes:
|
||||
| `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT |
|
||||
| `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `core/frontend/chunkstore/layout/delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.removePlanned`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Clean` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt`, `TestCatalogDeleteIntentResumesOnePageWithoutNamespaceScan`, `TestCatalogIntentCursorInterruptAndLostReply`, `TestHolderMaintenanceResumesThePersistedDeleteIntent`, `TestHolderMaintenanceIntentIsCancelledBeforeTheCutJoins` | PageChain r2 246,251-253 (az1 13/13); StaleClean 159-161 | ACTIVE |
|
||||
| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a fresh CAS-base tag and checks it is present, this attempt's and unmarked; stale cleaners/adopters cannot remove or retag a published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `RunDeleteSnapshotWithIntent`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags`, `TestDeleteIntentPublicationChecksAdoptedPageMetadata`, `TestGenericIntentStagingCannotUndoRefreshedPublication` | StaleClean 159-161; exact-head refinement read required | DORMANT |
|
||||
| `INV-SNAPSHOT-DELETE-ADOPT-002` | After adopting an intent page under its own tag, publication reads the page again and authenticates it; a page that no longer reads or holds other bytes refuses the publication. The filer frees chunks from a deletion queue, so a reference whose chunk is still queued reads intact and publishes. | M9 delete intent publication | `delete_intent.go` `RunDeleteSnapshotWithIntent`, `readListPage` | `TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed` (`core/frontend/chunkstore/layout/delete_intent_reread_test.go`); store witness `TestWithoutTheChunkGuardAStaleMetadataChangeOverwritesARecreatedObject` (`core/frontend/chunkstore/layout_change_meta_recreated_test.go`) | MetaABA r2, checked outside the repository: the re-read alone does not hold `PublishedReadable` once the filer frees chunks later from a queue (`mut_reread_delayed`); with the chunk guard it holds (`safe_chunks_equal`). r1's `safe_reread_only` held only for immediate frees (historical scope) | ACTIVE |
|
||||
| `INV-LAYOUT-META-CHUNKS-001` | With the chunk guard on, an adoption or mark writes its looked-up entry back only while the entry's chunk fids are unchanged, so it cannot land on an object deleted and created again since its lookup; a cleaner's delete expects its own mark, so it follows. | M9 delete intent publication; M9 clean(c) removal | `core/frontend/chunkstore/layout_store.go` `changeMeta`, `chunkCondition`; `swfs.go` `UpdateEntryIfChunks` | `TestAStaleMetadataChangeDoesNotOverwriteARecreatedObject`, `TestAStaleCleanerMarkDoesNotDeleteARecreatedObject`, `TestWithTheChunkGuardAnUnchangedObjectIsStillAdoptedMarkedAndDeleted` (`core/frontend/chunkstore/layout_change_meta_recreated_test.go`); `TestChunkGuardReportsOnlyAConditionTheFilerCanCarry` (`core/frontend/chunkstore/chunk_guard_report_test.go`); `TestOpsChunkStaleCLIAdoptionDoesNotOverwriteARecreatedObject` (`cmd/sw-block/chunk_guard_probe_test.go`) | MetaABA r2, checked outside the repository: `PublishedReadable` (`safe_chunks_equal`, `safe_legacy_chunks_equal`) | ACTIVE |
|
||||
|
||||
The snapshot-delete consumer and list-page retirement above are reachable through holder maintenance and covered by Go assertions. Their ACTIVE status describes that reachability and test coverage, not fresh Linux, composed-operation or release qualification. Cut and upload-intent producers remain deferred; their dormant publication rows are not activated by this consumer slice.
|
||||
|
||||
|
||||
@@ -117,22 +117,6 @@ systemd and root access.
|
||||
|
||||
## 1. Install the binaries and units
|
||||
|
||||
**Plan blockmaster's state storage before starting it.** Keep the holders' local data off both the state
|
||||
directory's filesystem and the filesystem holding its ancestors. In practice, put the holders' data on its own
|
||||
filesystem, not the root filesystem. With the shipped unit, the state directory is `/var/lib/sw-block-master`,
|
||||
including the authority and lifecycle stores. A different directory on the same filesystem is not enough. A
|
||||
dedicated state-directory mount alone does not isolate every startup sync: opening the store also syncs ancestor
|
||||
directories up to `/`, including `/var/lib` and `/var` with this layout. Keep write load low on those filesystems
|
||||
when restarting too. Under heavy writes, an `fsync` when blockmaster opens its state directory can wait for the
|
||||
filesystem journal. In v1.1.2, startup also runs a `syncfs` for each store with changed import records on ext4, XFS,
|
||||
btrfs or tmpfs (Linux 5.8 or later), which waits for every pending write on that filesystem, including the holders'
|
||||
data. Starts took from about 20 seconds to over 150 seconds in our tests (one start was not ready after 2 minutes);
|
||||
this is not an upper bound. A volume whose lease expires stops serving until blockmaster is back; it is then
|
||||
granted again on the same holder, with its data. A forced move during that time can lose writes after the last
|
||||
published HEAD (see [forced move](volume-lifecycle.md#after-a-crash)).
|
||||
Restart blockmaster at low write load, including when the cluster spec has not changed. See the
|
||||
[restart known issue](releases/v1.1.1.md#known-issue-blockmaster-restart-can-stall-on-a-busy-filesystem).
|
||||
|
||||
1. **Get the repository at the release tag, then the binaries.** The repository holds the units in `deploy/`. The
|
||||
binaries are `blockmaster`, `blockvolume` and `sw-block`, all three from the same release. `TAG` is the release,
|
||||
for example `v1.1.1`. Download the release tarball and check it:
|
||||
@@ -256,23 +240,7 @@ with its size and home placement. A volume's record comes from the cluster spec:
|
||||
```
|
||||
|
||||
blockmaster reads the cluster spec only when it starts. After editing the spec, run
|
||||
`sudo systemctl restart sw-blockmaster`. A restart that outlasts the running volumes' leases makes them fence;
|
||||
follow the state-storage and low-write-load guidance in section 1 before restarting.
|
||||
|
||||
blockmaster must run under systemd or an equivalent restart supervisor. A node, placement
|
||||
or volume lifecycle record write or recovery-directory sync failure attempts one `ERROR` naming the store,
|
||||
record and error, ending with `exiting so the supervisor restarts from durable state`,
|
||||
and exits with status 74 (durability unknown). The best-effort log reason
|
||||
`lifecycle_persist_failed` identifies a lifecycle fault; status 74 alone does not,
|
||||
because authority-store faults use the same status. Termination is armed before logging and occurs within one second even if the log writer or its lock is blocked; a blocked sink may lose that diagnostic. It does not remain alive with a failed store. The shipped
|
||||
`sw-blockmaster.service` has `Restart=on-failure` and `RestartSec=5s`; restart reloads
|
||||
complete records through the recovery barriers before serving again.
|
||||
|
||||
Deletion-reservation and workspace-binding write failures do not exit: the request returns
|
||||
the error and blockmaster keeps serving. A deletion reservation whose write outcome is unknown
|
||||
keeps a new exclusion in memory. A workspace-binding rename or directory-sync failure leaves
|
||||
the binding store uncertain, and every later binding operation fails with `restart required`
|
||||
until `sudo systemctl restart sw-blockmaster`.
|
||||
`sudo systemctl restart sw-blockmaster`. Serving volumes keep serving across that restart.
|
||||
|
||||
## 3. Create and attach a volume
|
||||
|
||||
@@ -598,9 +566,7 @@ writing the v1.0 format until you finalize. Until then you can go back.
|
||||
sw-block cluster format-level --master 127.0.0.1:9180 # format level 0
|
||||
```
|
||||
|
||||
Volumes keep serving only if the restart completes before their leases expire; otherwise they fence.
|
||||
Follow the [state-storage and low-write-load restart guidance](#1-install-the-binaries-and-units), including
|
||||
during upgrades.
|
||||
Volumes keep serving.
|
||||
|
||||
4. **Each holder.** Install the new binary once per host, then restart each volume on that host:
|
||||
|
||||
@@ -800,9 +766,9 @@ says otherwise.
|
||||
| `remote_full` | cuts, snapshots | The chunk store has no space. | Add capacity, then retry. |
|
||||
| `queue_full` | cuts, snapshots | Reclamation work must drain before another producer publishes. | Retry later. |
|
||||
| `format_level_below_head_version` | cuts, in the holder log | The holder still runs at the format level it attached at, from before the finalize. | A v1.1.1 holder adopts the finalized level at its next lease renewal; restart a v1.1.0 holder (section 7). |
|
||||
| `no_progress` (retryable) | snapshot, snapshot-delete | The operation has not settled: a snapshot stalled (for example right after a finalize, section 7), or a snapshot delete's work did not finish in this call. Retrying a snapshot with the same request id settles it, which can take several minutes. | For snapshot, keep retrying with the same id. For snapshot-delete, do not resume it by hand: a resume can stop the volume's snapshot deletes and cleaning (see the snapshot delete known issue in the [v1.1.1 notes](releases/v1.1.1.md)). |
|
||||
| `no_progress` (retryable) | snapshot, snapshot-delete | The operation has not settled: a snapshot stalled (for example right after a finalize, section 7), or a snapshot delete's work did not finish in this call. Retrying with the same request id settles it, which can take several minutes. | Keep retrying with the same id. |
|
||||
| `snapshot_has_dependents` (exit 1) | snapshot-delete | A restored volume depends on the snapshot. Not retryable: retrying does not help until that volume is deleted. | Delete the dependent volume first (section 6), then run the same command with the same request id; or keep the snapshot. |
|
||||
| `layout_busy` (retryable, exit 1) | snapshot-delete | `layout: another transaction is open`: an earlier snapshot delete on the same volume waits for its cleaning pass, which can take up to `--chunk-maintenance-interval` (1 h). | Keep retrying with the same id; it settles after that pass. If it does not settle after a cleaning pass, see the snapshot delete known issue in the [v1.1.1 notes](releases/v1.1.1.md). |
|
||||
| `layout_busy` (retryable, exit 1) | snapshot-delete | `layout: another transaction is open`: an earlier snapshot delete on the same volume waits for its cleaning pass, which can take up to `--chunk-maintenance-interval` (1 h). | Keep retrying with the same id; it settles after that pass. |
|
||||
| `outcome_unknown` | various | The request may or may not have taken effect. | See below. |
|
||||
| `snapshot_exists`, `snapshot_limit` | snapshot | The name is taken, or there are too many snapshots. | Use another name, or delete old snapshots. |
|
||||
| `snapshot_not_found` | restore | No snapshot has that name. (To see it, you need a target in the spec; there is no need to provoke it.) | Check `ops chunk snapshots`. |
|
||||
@@ -818,9 +784,7 @@ says otherwise.
|
||||
|
||||
- **Commands with `--request-id`** (`ops chunk snapshot`, `snapshot-delete`, `restore`, `volume-delete`,
|
||||
`ops workspace move` with or without `--clean`, and `ops workspace force-move`): repeat the command with the same
|
||||
request id until it answers. The answer settles what happened. This can take several minutes. Do not repeat an
|
||||
interrupted `snapshot-delete` by hand: a resume can stop the volume's snapshot deletes and cleaning (see the snapshot
|
||||
delete known issue in the [v1.1.1 notes](releases/v1.1.1.md)).
|
||||
request id until it answers. The answer settles what happened. This can take several minutes.
|
||||
- **`ops chunk cut`** has no request id. Repeat the cut: a later cut gives a later durable point. It does not tell you
|
||||
whether the earlier cut committed; for that, check the volume's snapshots and its last cut in status.
|
||||
- **`volume stop`**: run the same `sudo /usr/local/bin/sw-block volume stop <volume>` again. Before its cut succeeds
|
||||
|
||||
@@ -27,14 +27,6 @@ writing guest:
|
||||
5. **Under `best-effort`, a replica can fall behind while it shows `healthy`.** A `best-effort` write waits for no
|
||||
replica, so a replica whose connection dropped can keep showing `healthy` while it misses writes. Use `sync-quorum`
|
||||
when the replicas must hold the data.
|
||||
6. **An operator failover can be undone by an automatic rebalance.** With `sync-all`, or `sync-quorum` and two
|
||||
replicas, a rebalance blockmaster decided just before `sw-block ops failover` can still be applied after it and move
|
||||
the primary again. No acknowledged write is lost. After a failover, read the line with
|
||||
`sw-block ops volumes --master-api <addr> -o json`, and if the primary moved, repeat the failover against it. A
|
||||
read shows the line at that moment only: blockmaster applies the queued rebalance when its assignment queue reaches
|
||||
it, not at a fixed time, so the primary can still move after any read, and the guest is then started again on the
|
||||
new primary (item 4). Fixed in v1.1.2: blockmaster refuses a queued rebalance or failover when the volume's line
|
||||
moved after it was decided.
|
||||
|
||||
**Planned for a later release.** Supported replicated volumes are planned for a later release; v1.1.x keeps every replicated
|
||||
configuration a preview. Replicated volumes are a preview: a primary cut off from the block master is not stopped
|
||||
|
||||
@@ -14,58 +14,6 @@ v1.1.1 is a fix release of the v1.1 line. None of its changes alters a stored fo
|
||||
- The `sw-block` commands that `mini` prints assume it is on `PATH`: in the extracted directory, run
|
||||
`export PATH="$PWD:$PATH"`. Its `weed shell` hint needs the full path of the `weed` binary given to `--weed`.
|
||||
|
||||
## Known issue: restarting blockmaster with many declared volumes
|
||||
|
||||
- **What happens:** when blockmaster restarts, it rewrites every declared volume's node and placement records to disk, one by one, before it answers again. With a few hundred declared volumes this can take longer than a running volume's lease. Running volumes then stop (`lease_expired`, exit 75), and the guest sees I/O errors on those volumes while they are stopped.
|
||||
- In our test with 999 declared volumes, blockmaster answered again after about 45 s; the 8 running volumes stopped 12–20 s after the restart.
|
||||
- With 33 declared volumes, nothing stopped.
|
||||
- No acknowledged data is lost.
|
||||
- **Recovery:** a stopped volume comes back only if it is supervised. The shipped systemd unit restarts a volume that exits 75; in our test the volumes were serving again within a minute. Otherwise, start the volume again yourself.
|
||||
- **Where it starts:** we estimate around 150 declared volumes; it depends on the disk under blockmaster's state directory.
|
||||
- **What to do:** restart blockmaster in a maintenance window if a cluster declares more than about 150 volumes. A fix is planned for v1.1.2; in our test with it, 999 volumes restarted in under 6 s including the stop, and no volume stopped.
|
||||
|
||||
## Known issue: blockmaster restart can stall on a busy filesystem
|
||||
|
||||
- **Trigger:** blockmaster's state directory or its ancestors share a filesystem with heavy writes, such as the holders' local data.
|
||||
- **Effect:** opening the state directory calls `fsync`, which can wait for the filesystem journal. In v1.1.2, when the import has changed records, startup also runs a `syncfs` for each store with changed records on ext4, XFS, btrfs or tmpfs (Linux 5.8 or later), which waits for every pending write on that filesystem, including the holders' data. Starts took from about 20 seconds to over 150 seconds in our tests (one start was not ready after 2 minutes); this is not an upper bound. A volume whose lease expires stops serving until blockmaster is back; it is then granted again on the same holder, with its data. A forced move during that time can lose writes after the last published HEAD (see [forced move](../volume-lifecycle.md#after-a-crash)).
|
||||
- **What to do:** keep the holders' data off both the state directory's filesystem and the filesystem holding its ancestor directories. In practice, put the holders' data on its own filesystem, not the root filesystem. A different directory on the same filesystem is not enough. A dedicated state-directory mount alone does not isolate every startup sync: opening the store also syncs ancestors up to `/`, including `/var/lib` and `/var` with the shipped layout. Restart blockmaster at low write load on all those filesystems. This limitation also applies when the cluster spec has not changed.
|
||||
|
||||
## Known issue: blockmaster needs its filer to start
|
||||
|
||||
- blockmaster checks that its SeaweedFS filer answers before it starts. If the filer is unreachable, blockmaster stops with an error after about 60 s instead of starting.
|
||||
- While blockmaster cannot start, running volumes stop when their leases run out.
|
||||
- Start or fix the filer first, then start blockmaster.
|
||||
|
||||
## Known issue: `sw-block ops chunk detach --plain` waits for a scheduled periodic cut
|
||||
|
||||
- A scheduled periodic cut is not interrupted by `sw-block ops chunk detach --plain`. A detach issued while such a cut is capturing waits until the cut finishes, so on a volume with a long cut the detach takes correspondingly longer.
|
||||
- No data is lost. A fix is planned for a later v1.1.x release.
|
||||
|
||||
## Known issue: a walstore volume unit can reach its systemd start limit while blockmaster is unreachable
|
||||
|
||||
- Affects volumes on the walstore engine run by `sw-blockvolume.service`, `sw-blockvolume@.service` or `sw-blockvolume-ublk.service` (`StartLimitBurst=10` in 600 s, `RestartSec=5s`). Chunk-store volumes wait for blockmaster in process and are not affected.
|
||||
- A walstore volume that starts while blockmaster is unreachable exits with 75 after about 10 s and is restarted by systemd. After about 10 attempts (about 150 s) the unit stays failed, even once blockmaster is back.
|
||||
- No data is lost. Recover with `systemctl reset-failed <unit>`, then `systemctl start <unit>`. A fix is planned for v1.1.2.
|
||||
|
||||
## Known issue: startup retirement reads can delay blockmaster
|
||||
|
||||
- At startup blockmaster checks volumes that are reserved for deletion and hold no workspace lease, one at a time, before it serves. Each check reads the filer, so a slow filer delays the start: in our test, 100 such volumes with a 100 ms filer delay added about 20 s. Volumes in normal use are skipped without a read.
|
||||
- No data is lost. A fix is planned for v1.1.2.
|
||||
|
||||
## Known issue: replicated volumes (preview): a queued rebalance can undo an operator failover
|
||||
|
||||
- Affects replicated volumes (preview) whose acknowledgement profile allows a planned move: `sync-all`, or `sync-quorum` with two replicas.
|
||||
- blockmaster may decide an automatic rebalance, which moves the primary to a less loaded server, just before an operator's `sw-block ops failover`. If that rebalance is applied after the failover, it moves the primary again, away from the replica the operator chose.
|
||||
- No acknowledged write is lost: under these profiles every replica holds every acknowledged write.
|
||||
- What to do: after `sw-block ops failover`, read the volume's line with `sw-block ops volumes --master-api <addr> -o json`; if `primary_replica` moved again, repeat the failover with `--expect-current <primary_replica>@<epoch>`. No read confirms that the primary stays: blockmaster applies the queued rebalance when its assignment queue reaches it, not at a fixed time, so it can still move the primary after any read, and the guest is then started again on the new primary. Fixed in v1.1.2: blockmaster refuses a queued rebalance or failover when the volume's line moved after it was decided, so one decided before an operator's failover is no longer applied after it. A rebalance decided after the failover can still move the primary, as any rebalance can.
|
||||
|
||||
## Known issue: resuming an interrupted snapshot delete can stop the volume's snapshot deletes and cleaning
|
||||
|
||||
- **Trigger:** On a volume whose HEAD is version 1 (a version-0 HEAD takes v1.0's name-only delete and is not affected), two runs of the same snapshot delete overlap. A run is resumed (`--request-id`, as a `no_progress` answer suggests, or by the volume host) while an earlier run of the same delete still has a page update that has not landed: its process is paused before sending it, or it already sent it and the filer has not applied it, and a cleaning pass runs in between. In the second case the earlier run need not still be running: the write it already sent is what matters.
|
||||
- **Effect:** the snapshot delete is recorded with an intent page whose data was freed. From then on every snapshot delete on that volume fails with `layout_busy`, a retryable answer that does not clear on retry, and the volume's cleaning stops, so space is not reclaimed on that volume. The volume's data and its other snapshots stay readable.
|
||||
- **What to do:** v1.1.1 has no reliable workaround. To reduce exposure, do not re-run or resume an interrupted snapshot delete by hand (for example with `--request-id` after a `no_progress` answer). After a `no_progress` answer, a timeout, or the command's exit, a filer write the earlier run already sent can still land, so a later resume is not safe. On a volume whose HEAD is version 1, a delete sent to the volume host is retried by the host itself for about 30 seconds, but only while an attempt answers `layout_busy` or `head_conflict`; any other failure, including `no_progress`, is returned at once. The last retry can start just after the 30 seconds and run longer. On a version-0 HEAD the host runs v1.0's name-only delete, which it does not retry. The fix is planned for v1.1.2.
|
||||
- **Recovery:** none in v1.1.1. A volume that already shows this needs a repair that is planned for a later release. A fix that prevents the record is planned for v1.1.2.
|
||||
|
||||
## Upgrade notes
|
||||
|
||||
- **Order: the CLI first, then blockmaster, then each holder**, as in
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
# v1.1.2
|
||||
|
||||
v1.1.2 is not yet released.
|
||||
|
||||
## Fixed
|
||||
|
||||
- **Replicated volumes (preview): a queued rebalance no longer undoes an operator failover.** blockmaster's automatic
|
||||
rebalance and failover name the volume's line they were decided against, and blockmaster refuses one when that line
|
||||
moved since (another replica or epoch, or other addresses). A rebalance decided just before `sw-block ops failover`
|
||||
is no longer applied after it. This was a v1.1.1 known issue.
|
||||
|
||||
## Known issue: blockmaster restart can stall on a busy filesystem
|
||||
|
||||
- **Trigger:** blockmaster's state directory or its ancestors share a filesystem with heavy writes, such as the holders' local data.
|
||||
- **Effect:** blockmaster's start syncs its state directories, which can wait for the filesystem journal. When the import has changed records, it also runs a `syncfs` for each store with changed records on ext4, XFS, btrfs or tmpfs (Linux 5.8 or later), which waits for every pending write on that filesystem, including the holders' data. Starts took from about 20 seconds to over 150 seconds in our tests (one start was not ready after 2 minutes); this is not an upper bound. A volume whose lease expires stops serving until blockmaster is back; it is then granted again on the same holder, with its data. A forced move during that time can lose writes after the last published HEAD (see [forced move](../volume-lifecycle.md#after-a-crash)).
|
||||
- **What to do:** keep the holders' data off both the state directory's filesystem and the filesystem holding its ancestor directories. In practice, put the holders' data on its own filesystem, not the root filesystem. A different directory on the same filesystem is not enough. A dedicated state-directory mount alone does not isolate every startup sync: opening the store also syncs ancestors up to `/`, including `/var/lib` and `/var` with the shipped layout. Restart blockmaster at low write load on all those filesystems. This limitation also applies when the cluster spec has not changed.
|
||||
|
||||
## Lifecycle persistence failures
|
||||
|
||||
A blockmaster lifecycle put, import or open-barrier persistence failure exits with durability-unknown status 74 instead of generic status 1. Both immediate termination and the one-second fallback use that status. The best-effort ERROR diagnostic names `lifecycle_persist_failed`. Run blockmaster under supervision so a failed process restarts from durable state; record ordering, recovery barriers and import syncfs selection are unchanged.
|
||||
@@ -468,7 +468,6 @@ Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint
|
||||
| `dependents` | int | — |
|
||||
| `own_chunks` | int | — |
|
||||
| `foreign_chunks` | int | — |
|
||||
| `metadata_guard` | string | 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. (omitted when empty) |
|
||||
|
||||
### `GET /status/nvme`
|
||||
|
||||
|
||||
@@ -40,7 +40,6 @@ cmd/sw-block/chunk.go refuseUnlessSingleFilerWithin context.WithTimeoutCause 1 p
|
||||
cmd/sw-block/chunk.go chunkPost time.Now().Add 1 pending-fix CutTime.Poll remaining snapshot/detach HTTP waiter bound; fix #979 (manual cuts use chunkObserveCut)
|
||||
cmd/sw-block/chunk.go chunkPostUntil context.WithDeadline 1 pending-fix CutTime.Poll remaining snapshot/detach HTTP waiter bound; fix #979 (manual cuts use chunkObserveCut)
|
||||
cmd/sw-block/chunk.go chunkSnapshot time.Now().Add 1 control-timer CutTime.Poll snapshot expiry: a timestamp (validity, expiry or due time), not a wait
|
||||
cmd/sw-block/chunk_b.go bCatalog context.WithTimeout 1 per-call NONE: no model row maps this file yet the chunk condition probe of a writing command (operator --timeout; the probe's own 10 s and cleanup 5 s still apply)
|
||||
cmd/sw-block/chunk_b.go volumeFlags.ref context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
|
||||
cmd/sw-block/chunk_b.go bCommand.run context.WithTimeout 1 pending-fix NONE: no model row maps this file yet unmeasured: applies each catalog command's own budget (its newBCommand row); open while snapshot delete and retain are unmeasured
|
||||
cmd/sw-block/chunk_b.go chunkSnapshots newBCommand 1 per-call NONE: no model row maps this file yet lists one volume's snapshot names from one HEAD read (30 s)
|
||||
@@ -104,7 +103,7 @@ cmd/sw-block/volume_release.go releaseLease context.WithTimeout 1 per-call NONE:
|
||||
cmd/sw-block/volume_release.go releaseLease context.WithTimeout 2 availability-contract NONE: no model row maps this file yet the wait for the recorded release: one lease validity plus slack, since the holder acknowledges at its next renewal within the lease
|
||||
cmd/sw-block/volume_release.go releaseLease time.After 1 control-timer NONE: no model row maps this file yet lease record poll during the release wait
|
||||
cmd/sw-block/volume_resolve.go runOpsVolume context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
|
||||
cmd/sw-block/volume_start_release.go prepareVolumeStart context.WithTimeout 1 availability-contract StopAndRestart.IssueClean; StopAndRestart.ReadClean; StopAndRestart.CrashRestart lease-query/clean-move setup (10 s), before enabling the unit; no volume data is processed
|
||||
cmd/sw-block/volume_start_release.go prepareVolumeStart context.WithTimeout 1 availability-contract StopAndRestart.IssueClean; StopAndRestart.ReadClean; StopAndRestart.SameEpochReopen lease-query/clean-move setup (10 s), before enabling the unit; no volume data is processed
|
||||
cmd/sw-block/volume_verbs.go runVolume http.Client.Timeout 1 per-call CutTime.Poll one HTTP request
|
||||
cmd/sw-block/volume_verbs.go volumeStart time.Now().Add 1 per-call CutTime.Poll volume start: the operator's --wait for it to serve
|
||||
cmd/sw-block/volume_verbs.go volumeStart time.After 1 control-timer CutTime.Poll volume start poll
|
||||
@@ -202,11 +201,10 @@ core/host/master/host.go New http.Server.ReadHeaderTimeout 1 per-call NONE: no m
|
||||
core/host/master/host.go New http.Server.ReadTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
|
||||
core/host/master/host.go New http.Server.WriteTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
|
||||
core/host/master/host.go New http.Server.IdleTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
|
||||
core/host/master/lifecycle_failure.go lifecycleFailStop time.AfterFunc 1 availability-contract NONE: process-fault exit projection of INV-LIFECYCLE-FAILSTOP-001, no wire state one-second exit deadline armed before logger; independent of blocked sink
|
||||
core/host/master/probe_round.go roundEvidenceProvider.round time.NewTimer 1 per-call FencingRound.Deliver; FencingRound.Open one probe round's evidence wait
|
||||
core/host/master/services.go services.deleteHolderEvidence context.WithTimeout 1 per-call FormatGate.Report one RPC or request
|
||||
core/host/master/spec_retirement.go Host.reconcileDeletedSpecVolumes context.WithTimeout 1 per-call DeleteRetire.ReadOK one fresh HEAD read after the no-live-lease barrier
|
||||
core/host/master/spec_retirement.go Host.startPostFloorRetirement time.NewTimer 1 control-timer DeleteRetire.ReadOK; DeleteRetire.RetireLine one startup retry at the latest authority lease barrier; every guard is rechecked
|
||||
core/host/master/spec_retirement.go Host.startPostFloorRetirement time.NewTimer 1 control-timer DeleteRetire.ReadOK; DeleteRetire.Retire one startup retry at the latest authority lease barrier; every guard is rechecked
|
||||
core/host/master/spec_retirement.go Host.refreshHostDeletionProofs context.WithTimeout 1 per-call DeleteRetire.ReadOK one post-lease HEAD read for a requested host candidate; error retains work
|
||||
core/host/master/workspace_service.go services.AckWorkspaceRevoked context.WithTimeout 1 per-call FormatGate.Place; MoveAdmission.ReadForMove; StopAndRestart.ReadClean one RPC or request
|
||||
core/host/master/workspace_service.go services.MoveWorkspace context.WithTimeout 1 per-call FormatGate.Place; MoveAdmission.ReadForMove; StopAndRestart.ReadClean one RPC or request
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 49 and column 123.
|
@@ -439,9 +439,6 @@ Use this checklist when changing the feature.
|
||||
| `same-node-alpha-attach-chain.yaml` | loopback same-node accepted path |
|
||||
| `same-node-alpha-attach-negative-chain.yaml` | cross-node loopback blocked as unsupported |
|
||||
|
||||
The last three run only against the project's lab and are kept in a private test repository; the first three
|
||||
are in `testops/scenarios/`.
|
||||
|
||||
The runner must not pass a Stage 2 gate by grepping only lines it wrote itself.
|
||||
It needs independent evidence: pod UID, host sessions, multipath map, RTPG
|
||||
state, stale-I/O probe, and cleanup verifier.
|
||||
|
||||
@@ -85,6 +85,7 @@ Prefer gates that compare at least two surfaces:
|
||||
| Area | Path |
|
||||
|---|---|
|
||||
| scenario definitions | `testops/scenarios/` |
|
||||
| suites | `testops/suites/` |
|
||||
| runner contracts | `internal/docs/ref/testops-runner-binary-contract.md` |
|
||||
| control/data contract | `internal/docs/ref/testops-control-data-contract.md` |
|
||||
| QA sign-offs | `internal/docs/qa-assignments/` |
|
||||
|
||||
@@ -27,9 +27,6 @@ injection.
|
||||
| Cleanup | `cleanup-residue-chain.yaml` and cleanup verifier | zero-residue contract |
|
||||
| Protocol | `iscsi-*`, `nvme-*` | frontend-specific gates |
|
||||
|
||||
Scenarios that run against the project's lab are kept in a private test repository. This repository keeps
|
||||
the ones its own tests and scripts use; [testops/README.md](../../testops/README.md) lists them and the settings each needs.
|
||||
|
||||
## Release Evidence
|
||||
|
||||
Release claims should point to:
|
||||
|
||||
@@ -1164,11 +1164,11 @@ Approximate engineering effort if scope remains tight:
|
||||
baseline and corrects stale audit wording: ANA log/Identify/provider and CSI
|
||||
single-path NVMe stage/unstage are present. Phase 100 closed the Kubernetes
|
||||
CSI NVMe multipath attach follow-up for the supported lab path.
|
||||
- Operation milestone release readiness is blocked only on matching published
|
||||
images. Its readiness script ran against the project lab and is kept outside
|
||||
this repository with the lab scenarios; run it and the published-image Day-1
|
||||
smoke there before marking the operation milestone released. Development has
|
||||
moved ahead in parallel; this does not mark the operation milestone released.
|
||||
- Operation milestone release readiness is active and blocked only on matching
|
||||
published images. Run `scripts/run-operation-milestone-release-readiness.ps1`
|
||||
plus the published-image Day-1 smoke before marking the operation milestone
|
||||
released. Development has moved ahead in parallel; this does not mark the
|
||||
operation milestone released.
|
||||
- Phase 100 Kubernetes CSI NVMe Multipath Attach is closed. It implements and
|
||||
gates the path from dynamic PVC `protocol=nvme` and `replicationFactor=2` to
|
||||
master NVMe frontend grouping, CSI `nvmeAddrs` publish context, NodeStage
|
||||
|
||||
@@ -88,27 +88,25 @@ Default output:
|
||||
Validate a product-owned scenario:
|
||||
|
||||
```bash
|
||||
swblock validate testops/scenarios/nvme-p5-protocol-component-gate.yaml
|
||||
swblock validate testops/scenarios/csi-rf1-durable-restart-chain.yaml
|
||||
```
|
||||
|
||||
Run a product-owned scenario against a test node (every setting is required;
|
||||
testops/README.md lists them):
|
||||
Run a product-owned scenario against m02:
|
||||
|
||||
```bash
|
||||
swblock run testops/scenarios/nvme-p5-protocol-component-gate.yaml \
|
||||
--env product_root=/path/to/seaweed-block \
|
||||
--env node_host=<node address> \
|
||||
--env node_user=<ssh user> \
|
||||
--env ssh_key=/path/to/key \
|
||||
--env artifact_root=/path/to/shared/artifacts
|
||||
swblock run testops/scenarios/csi-rf1-durable-restart-chain.yaml \
|
||||
--env product_root=/tmp/seaweed_block \
|
||||
--env ssh_key=C:/work/dev_server/testdev_key
|
||||
```
|
||||
|
||||
Run the full protocol release gate (the four protocol chains in order):
|
||||
Run the full protocol release gate:
|
||||
|
||||
```bash
|
||||
SW_BLOCK_SSH_KEY=/path/to/key SW_BLOCK_NODE_HOST=<node address> \
|
||||
SW_BLOCK_NODE_USER=<ssh user> SW_BLOCK_NODE_ARTIFACT_ROOT=/path/to/shared/artifacts \
|
||||
bash scripts/testops-run-protocol-release-gate.sh
|
||||
swblock suite \
|
||||
--results-dir <evidence-store>/g15d-k8s/testops-runs/protocol-release-gate-native \
|
||||
--env product_root=/tmp/seaweed-block-nvme-p4l \
|
||||
--env ssh_key=C:/work/dev_server/testdev_key \
|
||||
C:/work/seaweed_block/testops/suites/protocol-release-gate.yaml
|
||||
```
|
||||
|
||||
Validate a finished protocol release gate bundle:
|
||||
|
||||
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user