mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2046ae4a2d | ||
|
|
08776a447f | ||
|
|
4f311d2a18 | ||
|
|
2a5d0e3801 | ||
|
|
4180a14b10 | ||
|
|
99d2116564 | ||
|
|
eb19e93f7b | ||
|
|
02f4c8dfe0 | ||
|
|
6820fdafea | ||
|
|
687c2844c3 | ||
|
|
79e99e7865 | ||
|
|
ee547ef399 | ||
|
|
2a7cee5dda | ||
|
|
6ecc5c0ed0 | ||
|
|
b807d48e2f | ||
|
|
49d8243eba | ||
|
|
10b949183c | ||
|
|
08aeac6b53 | ||
|
|
7d960d01a3 | ||
|
|
759b7f3a36 | ||
|
|
b30537483f | ||
|
|
d4e1ca4bed | ||
|
|
94e6fcf61c | ||
|
|
cccad8d5ce | ||
|
|
de239e7404 | ||
|
|
1fe0429d05 | ||
|
|
0a30cfada1 | ||
|
|
e4321a3e89 | ||
|
|
4a4651007a | ||
|
|
ff9c9ca007 | ||
|
|
6e91dc97b8 | ||
|
|
2637ff09c5 | ||
|
|
68f99dc114 | ||
|
|
16a6a70a08 | ||
|
|
120d786818 | ||
|
|
373eb29e59 | ||
|
|
ca5c659d9b | ||
|
|
90aae21e6b | ||
|
|
adb07ee3ce | ||
|
|
04a93bd7dd | ||
|
|
6c0859349b | ||
|
|
ba4370183a | ||
|
|
20854b3a66 | ||
|
|
ab25506331 | ||
|
|
acc22a4270 |
No files matched your search
@@ -0,0 +1,41 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,408 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/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"
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/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"
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/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
|
||||
@@ -0,0 +1,142 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/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))
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/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
|
||||
@@ -0,0 +1,121 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/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
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/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"
|
||||
@@ -0,0 +1,145 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,123 @@
|
||||
"""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))
|
||||
@@ -0,0 +1,106 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,132 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""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))
|
||||
@@ -0,0 +1,27 @@
|
||||
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"]
|
||||
@@ -0,0 +1,24 @@
|
||||
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
|
||||
@@ -0,0 +1,127 @@
|
||||
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
|
||||
@@ -0,0 +1,146 @@
|
||||
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
|
||||
@@ -0,0 +1,201 @@
|
||||
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
|
||||
@@ -0,0 +1,164 @@
|
||||
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
|
||||
@@ -0,0 +1,445 @@
|
||||
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,6 +9,7 @@ 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,
|
||||
@@ -20,6 +21,7 @@ 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,17 +1,21 @@
|
||||
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, commit to master
|
||||
# 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
|
||||
# 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 and seaweedfs-operator,
|
||||
# which pick up the new master through `go get -u`, and wait for both
|
||||
# 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.
|
||||
#
|
||||
# Events raised by the default GITHUB_TOKEN do not start other workflows, and it
|
||||
# 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.
|
||||
# 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.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -28,7 +32,7 @@ on:
|
||||
type: string
|
||||
required: false
|
||||
downstream:
|
||||
description: "Also release the CSI driver and the operator"
|
||||
description: "Also release the CSI driver, the operator and the COSI driver"
|
||||
type: boolean
|
||||
default: true
|
||||
dry_run:
|
||||
@@ -134,6 +138,43 @@ 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:
|
||||
@@ -156,7 +197,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
|
||||
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml k8s/charts/seaweedfs/values.yaml
|
||||
git commit -m "${TAG}"
|
||||
git push
|
||||
fi
|
||||
@@ -187,14 +228,20 @@ 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: |
|
||||
@@ -204,7 +251,7 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The dispatched workflow pins seaweedfs with `go get -u ...@latest`, so
|
||||
# The dispatched workflow pins seaweedfs with `go get ...@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.
|
||||
@@ -231,7 +278,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 master -f bump=patch -f update_seaweedfs=true
|
||||
gh workflow run -R "$REPO" "$WORKFLOW" --ref "$REF" -f bump=patch -f update_seaweedfs=true
|
||||
|
||||
RUN_ID=""
|
||||
for _ in $(seq 12); do
|
||||
|
||||
@@ -56,6 +56,26 @@ jobs:
|
||||
tofu -chdir="$ex" validate
|
||||
done
|
||||
|
||||
provider:
|
||||
name: provider build, vet and unit tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: terraform/provider/go.mod
|
||||
cache-dependency-path: terraform/provider/go.sum
|
||||
|
||||
- name: vet
|
||||
working-directory: terraform/provider
|
||||
run: go vet ./...
|
||||
|
||||
- name: unit tests
|
||||
working-directory: terraform/provider
|
||||
run: go test -race ./...
|
||||
|
||||
smoke:
|
||||
name: local cluster smoke test (real weed)
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -722,6 +722,53 @@ 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.
|
||||
|
||||
+1030
-1042
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 53 KiB |
+1
@@ -207,6 +207,7 @@ core/host/master/product_loop.go FencingRound.Decide
|
||||
core/host/master/product_loop.go Promotion.Decide
|
||||
core/host/master/services.go FormatGate.Report
|
||||
core/host/master/spec_retirement.go DeleteRetire.ReadOK
|
||||
core/host/master/spec_retirement.go DeleteRetire.RetirePlace
|
||||
core/host/master/store_attestation.go ReplicationPeer.Attest
|
||||
core/host/master/workspace_binding.go FormatGate.Grant
|
||||
core/host/master/workspace_binding.go MoveAdmission.Ack
|
||||
|
||||
|
@@ -0,0 +1,91 @@
|
||||
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"])
|
||||
}
|
||||
}
|
||||
@@ -71,3 +71,19 @@ func layoutTargetCreator(cat *chunkstore.BCatalog) func(context.Context, lifecyc
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// newRetirementHeadReader opens only a read transport. The serving catalog has
|
||||
// already validated the endpoint; retirement must not repeat its write probes
|
||||
// or start another probe-cleanup worker.
|
||||
func newRetirementHeadReader(cfg chunkstore.SWFSConfig) (func(context.Context, lifecycle.VolumeSpec) (layout.Head, error), *chunkstore.SWFS, error) {
|
||||
client, err := chunkstore.DialSWFS(cfg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cat, err := chunkstore.NewBCatalog(client, client, cfg.AssignPath)
|
||||
if err != nil {
|
||||
_ = client.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return layoutHeadReader(cat), client, nil
|
||||
}
|
||||
@@ -274,6 +274,7 @@ 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,
|
||||
@@ -295,8 +296,8 @@ func run(f flags) int {
|
||||
return 1
|
||||
}
|
||||
cfg.Auth, cfg.ServerOptions = authn, serverOpts
|
||||
// The layout catalog is the master's one HEAD source (create, restore and
|
||||
// the workspace reader all read through it).
|
||||
// Foreground catalog operations share their serving connection. Retirement
|
||||
// owns a separate connection so outage reads do not alter its backoff.
|
||||
var layoutCat *chunkstore.BCatalog
|
||||
if f.workspaceRPC {
|
||||
cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{
|
||||
@@ -311,6 +312,17 @@ func run(f flags) int {
|
||||
cfg.LayoutCreateVolume = layoutVolumeCreator(cat)
|
||||
cfg.LayoutReadVolume = layoutVolumeReader(cat)
|
||||
cfg.LayoutReadHead = layoutHeadReader(cat)
|
||||
retirementRead, retirementClient, err := newRetirementHeadReader(chunkstore.SWFSConfig{
|
||||
FilerGRPC: f.chunkFiler, Collection: f.chunkCollection,
|
||||
Replication: f.chunkReplication, AssignPath: f.chunkPath,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster: retirement filer:", err)
|
||||
return 1
|
||||
}
|
||||
// Host.Close cancels and joins retirement before these clients close.
|
||||
defer retirementClient.Close()
|
||||
cfg.LayoutRetirementReadHead = retirementRead
|
||||
cfg.LayoutCreateTarget = layoutTargetCreator(cat)
|
||||
layoutCat = cat
|
||||
}
|
||||
@@ -339,6 +351,9 @@ 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))
|
||||
@@ -389,12 +404,6 @@ func run(f flags) int {
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.ReconcileDeletedSpecVolumes(context.Background()); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster:", err)
|
||||
_ = h.Close(context.Background())
|
||||
return 1
|
||||
}
|
||||
|
||||
if f.printReadyLine {
|
||||
_ = json.NewEncoder(os.Stdout).Encode(readyLine{
|
||||
Component: "blockmaster",
|
||||
@@ -478,10 +487,8 @@ func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistra
|
||||
if stores == nil {
|
||||
return fmt.Errorf("lifecycle node import requires --lifecycle-store")
|
||||
}
|
||||
for _, node := range nodes {
|
||||
if _, err := stores.Nodes.RegisterNode(node); err != nil {
|
||||
return fmt.Errorf("register lifecycle node %s: %w", node.ServerID, err)
|
||||
}
|
||||
if err := stores.Nodes.ImportNodes(nodes); err != nil {
|
||||
return fmt.Errorf("import lifecycle nodes: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -510,6 +517,7 @@ 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)
|
||||
@@ -528,9 +536,10 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
|
||||
Source: slot.Source,
|
||||
})
|
||||
}
|
||||
if _, err := stores.Placements.ApplyPlan(plan); err != nil {
|
||||
return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err)
|
||||
}
|
||||
plans = append(plans, plan)
|
||||
}
|
||||
if err := stores.Placements.ImportPlans(plans); err != nil {
|
||||
return fmt.Errorf("import lifecycle placement seeds: %w", 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 or RemoveNode appears anywhere.
|
||||
// RegisterNode, ImportNodes 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 == "RemoveNode") {
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "ImportNodes" || 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.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
|
||||
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.ImportNodes", "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)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
"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"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type retirementTransportFiler struct {
|
||||
filerpb.UnimplementedSeaweedFilerServer
|
||||
mu sync.Mutex
|
||||
peers []string
|
||||
}
|
||||
|
||||
func (f *retirementTransportFiler) LookupDirectoryEntry(ctx context.Context, _ *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) {
|
||||
p, _ := peer.FromContext(ctx)
|
||||
f.mu.Lock()
|
||||
f.peers = append(f.peers, p.Addr.String())
|
||||
f.mu.Unlock()
|
||||
return nil, status.Error(codes.NotFound, "absent")
|
||||
}
|
||||
|
||||
// Exercise actual transports: retirement opens a different HTTP/2 connection,
|
||||
// performs no conditional write probe, and leaves the serving client usable
|
||||
// after its own connection closes.
|
||||
func TestRetirementCatalogOwnsItsConnection(t *testing.T) {
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &retirementTransportFiler{}
|
||||
srv := grpc.NewServer()
|
||||
filerpb.RegisterSeaweedFilerServer(srv, f)
|
||||
go srv.Serve(lis)
|
||||
defer srv.Stop()
|
||||
cfg := chunkstore.SWFSConfig{FilerGRPC: lis.Addr().String(), AssignPath: "/blocks"}
|
||||
serving, err := chunkstore.DialSWFS(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer serving.Close()
|
||||
cat, err := chunkstore.NewBCatalog(serving, serving, cfg.AssignPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
retireRead, retireClient, err := newRetirementHeadReader(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer retireClient.Close()
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec := lifecycle.VolumeSpec{VolumeID: "v", LayoutID: id.String()}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
for _, read := range []func(context.Context, lifecycle.VolumeSpec) (layout.Head, error){layoutHeadReader(cat), retireRead} {
|
||||
if _, err := read(ctx, spec); !errors.Is(err, layout.ErrHeadAbsent) {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
}
|
||||
if err := retireClient.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layoutHeadReader(cat)(ctx, spec); !errors.Is(err, layout.ErrHeadAbsent) {
|
||||
t.Fatalf("serving read after retirement close: %v", err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if len(f.peers) != 3 || f.peers[0] == f.peers[1] || f.peers[0] != f.peers[2] {
|
||||
t.Fatalf("serving, retirement, serving connections: %v", f.peers)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,13 @@ 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}
|
||||
@@ -48,8 +55,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", "30s",
|
||||
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
|
||||
"--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)
|
||||
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
|
||||
for _, b := range hosts {
|
||||
lockDir := b.root + ".locks"
|
||||
@@ -84,7 +91,8 @@ 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
|
||||
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
|
||||
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 {
|
||||
for _, b := range survivors {
|
||||
if statusIsPrimaryAt(b.status, 2) {
|
||||
p2 = b
|
||||
|
||||
@@ -40,7 +40,7 @@ func TestProcedureMasterKilledAfterMoveBeforeTargetStarts(t *testing.T) {
|
||||
{"s2", "different-request"}, {"s3", "different-target"},
|
||||
} {
|
||||
out, stderr, code := env.h.run(t, env.moveClean(e, conflict.target, conflict.request)...)
|
||||
if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: workspace move: missing or changed authority/lease" {
|
||||
if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: rpc error: code = FailedPrecondition desc = workspace move: missing or changed authority/lease; resolve the server's stated precondition before retrying" {
|
||||
t.Fatalf("competing move to %s: exit=%d stdout=%q stderr=%q; want the definite-refusal exit and changed-authority answer", conflict.target, code, out, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//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)
|
||||
}
|
||||
@@ -169,6 +169,21 @@ func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCLIPreservesTheHarnessTLSIdentity(t *testing.T) {
|
||||
env := startTLSEnv(t, 1, nil, nil)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if out, errOut, code, err := runCLI(ctx, env.h, env.show...); err != nil || code != 0 {
|
||||
t.Fatalf("CLI with the harness identity: exit %d, error %v:\n%s\n%s", code, err, out, errOut)
|
||||
}
|
||||
admin := env.h.cliEnv
|
||||
defer func() { env.h.cliEnv = admin }()
|
||||
env.h.cliEnv = []string{"SW_BLOCK_TLS_CERT=", "SW_BLOCK_TLS_KEY=", "SW_BLOCK_TLS_CA="}
|
||||
if _, errOut, code, err := runCLI(ctx, env.h, env.show...); err != nil || code != 5 {
|
||||
t.Fatalf("CLI with the identity explicitly cleared: exit %d, error %v, stderr %q; want 5", code, err, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
// fencedHolderThenForcedMove is T6/T7's flow: s1 serves and publishes block 0
|
||||
// (seal), then lose() takes its certificate away. s1 fences and exits; when
|
||||
// operatorFirst, an operator's forced move is refused as not authorized; the
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -535,6 +536,9 @@ func (env *handoffEnv) hydrate(t *testing.T, target string) {
|
||||
func runCLI(ctx context.Context, h *plannedHandoffHarness, args ...string) (string, string, int, error) {
|
||||
cmd := exec.CommandContext(ctx, h.cli, args...)
|
||||
cmd.Dir = h.dir
|
||||
if len(h.cliEnv) > 0 {
|
||||
cmd.Env = append(os.Environ(), h.cliEnv...)
|
||||
}
|
||||
cmd.WaitDelay = 5 * time.Second
|
||||
var stdout, stderr strings.Builder
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// These are independent wire expectations at command entry boundaries, not
|
||||
// expected values obtained by calling the policy being tested.
|
||||
var entryRPCAnswers = []struct {
|
||||
name string
|
||||
kind codes.Code
|
||||
exit int
|
||||
text string
|
||||
}{
|
||||
{"argument", codes.InvalidArgument, 2, "bad_request"},
|
||||
{"precondition", codes.FailedPrecondition, 1, "not_admitted"},
|
||||
{"permission", codes.PermissionDenied, 5, "not_authorized"},
|
||||
{"identity", codes.Unauthenticated, 5, "not_authorized"},
|
||||
{"data", codes.DataLoss, 4, "readout_unproven"},
|
||||
{"missing", codes.NotFound, 1, "not_found"},
|
||||
{"unsupported", codes.Unimplemented, 1, "unsupported"},
|
||||
{"connection_after_send", codes.Unavailable, 3, "outcome is unknown"},
|
||||
}
|
||||
|
||||
func TestAnswerEntryRestoreFailureTable(t *testing.T) {
|
||||
for _, row := range entryRPCAnswers {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
var received atomic.Pointer[control.CreateVolumeRequest]
|
||||
h, env, _, _ := restoreSetup(t, grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) {
|
||||
if strings.HasSuffix(info.FullMethod, "/CreateVolume") {
|
||||
calls.Add(1)
|
||||
q := req.(*control.CreateVolumeRequest)
|
||||
received.Store(&control.CreateVolumeRequest{VolumeId: q.VolumeId, SourceVolume: q.SourceVolume, SourceSnapshot: q.SourceSnapshot, CreateRequestId: q.CreateRequestId})
|
||||
return nil, status.Error(row.kind, "entry restore answer")
|
||||
}
|
||||
return next(ctx, req)
|
||||
}))
|
||||
code, _, diagnostic := runRestore(env, restoreArgs(h)...)
|
||||
if code != row.exit || !strings.Contains(diagnostic, row.text) || calls.Load() != 1 || h.called("enable") != 0 {
|
||||
t.Fatalf("exit=%d want=%d calls=%d started=%d: %s", code, row.exit, calls.Load(), h.called("enable"), diagnostic)
|
||||
}
|
||||
q := received.Load()
|
||||
if q == nil || q.VolumeId != "vol-r" || q.SourceVolume != "vol-a" || q.SourceSnapshot != "s1" || q.CreateRequestId != "restore-07b3764162e18f1c4ba7faad0d8c6360" {
|
||||
t.Fatalf("wire restore tuple/identity changed: %+v", q)
|
||||
}
|
||||
if row.exit == 3 && !strings.Contains(diagnostic, "to finish, run the same command:") {
|
||||
t.Fatalf("restore recovery lost: %s", diagnostic)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnswerEntryPlacementFailureTable(t *testing.T) {
|
||||
for _, method := range []string{"RegisterWorkspaceBinding", "PlaceWorkspace"} {
|
||||
for _, row := range entryRPCAnswers {
|
||||
t.Run(method+"/"+row.name, func(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
h, env, _, _ := restoreSetup(t, grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) {
|
||||
if strings.HasSuffix(info.FullMethod, "/"+method) {
|
||||
calls.Add(1)
|
||||
return nil, status.Error(row.kind, "entry placement answer")
|
||||
}
|
||||
return next(ctx, req)
|
||||
}))
|
||||
code, _, diagnostic := runRestore(env, restoreArgs(h)...)
|
||||
if code != row.exit || !strings.Contains(diagnostic, row.text) || calls.Load() != 1 || h.called("enable") != 0 || !strings.Contains(diagnostic, abortCmd) {
|
||||
t.Fatalf("exit=%d want=%d calls=%d started=%d: %s", code, row.exit, calls.Load(), h.called("enable"), diagnostic)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnswerEntryBackupFailureTable(t *testing.T) {
|
||||
for _, row := range []struct {
|
||||
name, mode, text string
|
||||
exit int
|
||||
}{
|
||||
{"definite_refusal", "refuse", "not_primary", 2},
|
||||
{"admitted_lost_answer", "async-gone", "outcome is unknown", 3},
|
||||
{"wrong_operation", "async-foreign", "outcome is unknown", 3},
|
||||
{"incomplete_success", "missing-headGen", "outcome is unknown", 3},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
h := newFakeHost(t)
|
||||
env := h.env(t)
|
||||
holder := newSnapHolder(t)
|
||||
sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(holder.srv.URL, "http://"), true)
|
||||
holder.setMode(row.mode)
|
||||
code, _, diagnostic := runBackup(env, "vol-a", "--name", "n1")
|
||||
if code != row.exit || !strings.Contains(diagnostic, row.text) || holder.postCount() != 1 || !strings.Contains(diagnostic, "volume backup vol-a --name n1") {
|
||||
t.Fatalf("exit=%d want=%d posts=%d: %s", code, row.exit, holder.postCount(), diagnostic)
|
||||
}
|
||||
holder.mu.Lock()
|
||||
q := holder.lastRequest
|
||||
holder.mu.Unlock()
|
||||
if q.VolumeID != "vol-a" || q.Name != "n1" || q.RequestID != "backup-ba5271cb955c6497fcae4d87e745f030" {
|
||||
t.Fatalf("wire backup tuple/identity changed: %+v", q)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type answerEntryCluster struct {
|
||||
control.UnimplementedClusterEvidenceServiceServer
|
||||
err error
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *answerEntryCluster) GetClusterStatus(context.Context, *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) {
|
||||
s.calls.Add(1)
|
||||
return nil, s.err
|
||||
}
|
||||
|
||||
func TestAnswerEntryShellInspectionFailureTable(t *testing.T) {
|
||||
for _, row := range entryRPCAnswers {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := grpc.NewServer()
|
||||
fixture := &answerEntryCluster{err: status.Error(row.kind, "entry shell answer")}
|
||||
control.RegisterClusterEvidenceServiceServer(server, fixture)
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() {
|
||||
server.Stop()
|
||||
_ = listener.Close()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("inspection server did not join")
|
||||
}
|
||||
})
|
||||
var out, diagnostic bytes.Buffer
|
||||
code := run([]string{"shell", "-master", listener.Addr().String(), "-c", "cluster.status -o json"}, &out, &diagnostic)
|
||||
if code != row.exit || !strings.Contains(diagnostic.String(), row.text) || fixture.calls.Load() != 1 || out.Len() != 0 {
|
||||
t.Fatalf("exit=%d want=%d calls=%d out=%s: %s", code, row.exit, fixture.calls.Load(), &out, &diagnostic)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnswerLegacyStopKeepsAcquiredCutHandle(t *testing.T) {
|
||||
for _, mode := range []string{"idless-refusal-after-progress", "unversioned-stalled-after-progress"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
h, env := startedHost(t, true)
|
||||
env.Poll = time.Millisecond
|
||||
h.cutMode.Store(mode)
|
||||
code, progress, diagnostic := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second})
|
||||
if code != 2 || !strings.Contains(diagnostic, "outcome is unknown") || !strings.Contains(progress+diagnostic, "cut id c1") || h.posts.Load() != 1 || h.called("stop ") != 0 {
|
||||
t.Fatalf("legacy refusal must retain admitted cut and leave serving unchanged: exit=%d posts=%d output=%s %s", code, h.posts.Load(), progress, diagnostic)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnswerLegacyPublicationUnknownNamesExistingTarget(t *testing.T) {
|
||||
for _, mode := range []string{"status_saved", "status_failed"} {
|
||||
t.Run(mode, func(t *testing.T) { testAnswerPublicationUnknownTarget(t, mode == "status_failed") })
|
||||
}
|
||||
}
|
||||
|
||||
type answerEntryPublicationClient struct {
|
||||
*lifecycleOwnerTestClient
|
||||
failStatus bool
|
||||
statusAttempts int
|
||||
statusFailures int
|
||||
attemptedRef ops.OperatorObjectRef
|
||||
attemptedReason string
|
||||
}
|
||||
|
||||
func (c *answerEntryPublicationClient) WriteFrontendPublicationStatus(ctx context.Context, ref ops.OperatorObjectRef, value ops.SwBlockFrontendPublicationCRDStatus) error {
|
||||
c.statusAttempts++
|
||||
c.attemptedRef, c.attemptedReason = ref, value.ReasonCode
|
||||
if c.failStatus && value.ReasonCode == "frontend_publication_runtime_failed" {
|
||||
c.statusFailures++
|
||||
return errors.New("status save failed")
|
||||
}
|
||||
return c.lifecycleOwnerTestClient.WriteFrontendPublicationStatus(ctx, ref, value)
|
||||
}
|
||||
|
||||
func testAnswerPublicationUnknownTarget(t *testing.T, failStatus bool) {
|
||||
t.Helper()
|
||||
target := cmdFrontendPublicationFailbackExecutableTarget()
|
||||
client := &answerEntryPublicationClient{lifecycleOwnerTestClient: &lifecycleOwnerTestClient{frontendTargets: []ops.SwBlockFrontendPublicationObject{target}}, failStatus: failStatus}
|
||||
previous := opsFrontendPublicationExecutorClientFactory
|
||||
opsFrontendPublicationExecutorClientFactory = func() (ops.FrontendPublicationExecutorClient, error) { return client, nil }
|
||||
t.Cleanup(func() { opsFrontendPublicationExecutorClientFactory = previous })
|
||||
var received atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var request ops.FrontendPublicationRuntimeRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.VolumeID != target.Spec.VolumeID {
|
||||
t.Errorf("request did not reach runtime: %+v %v", request, err)
|
||||
http.Error(w, "bad request", 400)
|
||||
return
|
||||
}
|
||||
received.Add(1)
|
||||
connection, _, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
_ = connection.Close()
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
var out, diagnostic bytes.Buffer
|
||||
code := run([]string{"ops", "frontend-publication-executor", "--enable-execution", "--execution-policy", "--frontend-publication-runtime-url", server.URL, "--namespace", "kube-system"}, &out, &diagnostic)
|
||||
if code != 2 || received.Load() != 1 || !strings.Contains(diagnostic.String(), "outcome_unknown") || !strings.Contains(diagnostic.String(), target.Ref.Namespace+"/"+target.Ref.Name) || !strings.Contains(diagnostic.String(), target.Spec.VolumeID) {
|
||||
t.Fatalf("legacy outer refusal must keep inner unknown and existing target: exit=%d received=%d out=%s diagnostic=%s", code, received.Load(), &out, &diagnostic)
|
||||
}
|
||||
wantSaved, wantFailures := 1, 0
|
||||
if failStatus {
|
||||
wantSaved, wantFailures = 0, 1
|
||||
}
|
||||
if client.statusAttempts != 1 || client.attemptedRef != target.Ref || client.attemptedReason != "frontend_publication_runtime_failed" || client.statusFailures != wantFailures || len(client.frontendPublicationStatusWrites) != wantSaved {
|
||||
t.Fatalf("status branch not exercised: attempts=%d ref=%+v reason=%s failures=%d saved=%d wantFailures=%d wantSaved=%d", client.statusAttempts, client.attemptedRef, client.attemptedReason, client.statusFailures, len(client.frontendPublicationStatusWrites), wantFailures, wantSaved)
|
||||
}
|
||||
if failStatus {
|
||||
if !strings.Contains(diagnostic.String(), "status save failed") {
|
||||
t.Fatalf("status-write failure lost: %s", &diagnostic)
|
||||
}
|
||||
} else {
|
||||
saved := client.frontendPublicationStatusWrites[0]
|
||||
if saved.ref != target.Ref || saved.status.ReasonCode != "frontend_publication_runtime_failed" || strings.Contains(diagnostic.String(), "status save failed") {
|
||||
t.Fatalf("wrong saved status: %+v diagnostic=%s", saved, &diagnostic)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCanonicalCredentialExitAtCommandEntries(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("SW_BLOCK_TLS_CERT", filepath.Join(dir, "missing-cert"))
|
||||
t.Setenv("SW_BLOCK_TLS_KEY", filepath.Join(dir, "missing-key"))
|
||||
t.Setenv("SW_BLOCK_TLS_CA", filepath.Join(dir, "missing-ca"))
|
||||
for _, args := range [][]string{
|
||||
{"ops", "workspace", "show", "--master", "m:1", "--volume", "v"},
|
||||
{"ops", "volume", "resolve", "--master", "m:1", "v"},
|
||||
createAndPlaceArgs("m:1"),
|
||||
{"cluster", "finalize-format", "--master", "m:1"},
|
||||
{"cluster", "retire-host", "--master", "m:1", "--server", "h", "--confirm", "h"},
|
||||
failoverArgs(),
|
||||
} {
|
||||
t.Run(args[0]+"/"+args[1]+"/"+args[2], func(t *testing.T) {
|
||||
var out, diag bytes.Buffer
|
||||
if exit := run(args, &out, &diag); exit != 78 {
|
||||
t.Fatalf("args=%v exit=%d out=%s diag=%s", args, exit, &out, &diag)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type lostRestoreAnswer struct {
|
||||
control.UnimplementedLifecycleServiceServer
|
||||
calls atomic.Int64
|
||||
id atomic.Value
|
||||
}
|
||||
|
||||
func TestChunkHTTPPostLostAnswerIsUnknown(t *testing.T) {
|
||||
var calls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
conn, _, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
_ = conn.Close()
|
||||
}))
|
||||
defer server.Close()
|
||||
var out, diag bytes.Buffer
|
||||
exit := chunkPost("snapshot", server.URL, "/chunk/snapshot", time.Second, map[string]any{"requestID": "same-snapshot"}, &out, &diag)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if calls.Load() != 1 || exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "replay key") {
|
||||
t.Fatalf("calls=%d exit=%d answer=%+v", calls.Load(), exit, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkHTTPRejectsAnUnlistedServerErrorCode(t *testing.T) {
|
||||
var calls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = w.Write([]byte(`{"code":"unlisted_server_code","message":"retry this new error","retryable":true}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
var out, diag bytes.Buffer
|
||||
exit := chunkPost("snapshot", server.URL, "/chunk/snapshot", time.Second, map[string]any{"requestID": "same-snapshot"}, &out, &diag)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if calls.Load() != 1 || exit != 3 || got.Code != "unsupported_error_code" || got.Retryable || !strings.Contains(got.Message, "unlisted") {
|
||||
t.Fatalf("calls=%d exit=%d answer=%+v", calls.Load(), exit, got)
|
||||
}
|
||||
}
|
||||
|
||||
func (server *lostRestoreAnswer) CreateVolume(_ context.Context, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
|
||||
server.calls.Add(1)
|
||||
server.id.Store(req.GetCreateRequestId())
|
||||
return nil, status.Error(codes.Unavailable, "reply unavailable after request was received")
|
||||
}
|
||||
|
||||
func TestRestoreUnavailableAfterSendIsUnknown(t *testing.T) {
|
||||
for _, env := range []string{link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA} {
|
||||
t.Setenv(env, "")
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := &lostRestoreAnswer{}
|
||||
server := link.NewServer(link.ServerConfig{})
|
||||
control.RegisterLifecycleServiceServer(server, service)
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(server.Stop)
|
||||
var out, diag bytes.Buffer
|
||||
exit := runOpsChunk([]string{"restore", "--source", "source", "--target", "target", "--snapshot", "daily", "--request-id", "same-restore", "--master", listener.Addr().String(), "--timeout", "5s"}, &out, &diag)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if service.calls.Load() != 1 || service.id.Load() != "same-restore" || exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "replay key") {
|
||||
t.Fatalf("calls=%d id=%v exit=%d answer=%+v", service.calls.Load(), service.id.Load(), exit, got)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"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"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
@@ -18,7 +19,7 @@ import (
|
||||
type unavailableCatalogRead struct{ *memChunkStore }
|
||||
|
||||
func (s unavailableCatalogRead) LookupEntry(context.Context, string, string) (*filerpb.Entry, error) {
|
||||
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", status.Error(codes.Unavailable, "connection refused"))
|
||||
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")))
|
||||
}
|
||||
|
||||
func TestOpsChunkCatalogUnavailableIsTyped(t *testing.T) {
|
||||
@@ -97,14 +98,14 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
|
||||
code string
|
||||
retry bool
|
||||
}{
|
||||
{"wrapped", fmt.Errorf("lookup: %w", unavailable), "remote_unavailable", true},
|
||||
{"deadline", errors.Join(context.DeadlineExceeded, unavailable), "deadline_exceeded", true},
|
||||
{"caller cancellation", errors.Join(context.Canceled, unavailable), "canceled", false},
|
||||
{"wrapped", fmt.Errorf("lookup: %w", unavailable), "outcome_unknown", true},
|
||||
{"deadline", errors.Join(context.DeadlineExceeded, unavailable), "outcome_unknown", true},
|
||||
{"caller cancellation", errors.Join(context.Canceled, unavailable), "outcome_unknown", true},
|
||||
{"identity", errors.Join(layout.ErrIdentity, unavailable), "identity_mismatch", false},
|
||||
{"catalog", &chunkstore.CatalogError{Code: "outcome_unknown", Retryable: true, Err: unavailable}, "outcome_unknown", true},
|
||||
{"permission", status.Error(codes.PermissionDenied, "refused"), "internal", false},
|
||||
{"permission", status.Error(codes.PermissionDenied, "refused"), "not_authorized", false},
|
||||
{"unknown", errors.New("unexpected implementation error"), "internal", false},
|
||||
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "internal", false},
|
||||
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "bad_request", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var out, diag bytes.Buffer
|
||||
@@ -114,6 +115,15 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
|
||||
if tc.code == codeUnavailableCLI {
|
||||
wantExit = 75
|
||||
}
|
||||
if tc.code == "outcome_unknown" {
|
||||
wantExit = 3
|
||||
}
|
||||
if tc.code == "bad_request" {
|
||||
wantExit = 78
|
||||
}
|
||||
if tc.code == "not_authorized" {
|
||||
wantExit = 5
|
||||
}
|
||||
if exit != wantExit || e.Code != tc.code || e.Retryable != tc.retry {
|
||||
t.Fatalf("exit=%d answer=%+v", exit, e)
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCata
|
||||
if errors.Is(err, layout.ErrHasDependents) {
|
||||
return nil, &chunkstore.CatalogError{Code: "snapshot_has_dependents", Message: "remove dependent volumes or release their dependency before resuming the same --request-id", Err: err}
|
||||
}
|
||||
if chunkTransportFailure(err) || chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) {
|
||||
if knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -67,6 +68,15 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat
|
||||
func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int {
|
||||
ctx, cancel := context.WithTimeoutCause(parent, timeout, chunkstore.ErrSingleFilerWindowExpired)
|
||||
defer cancel()
|
||||
if cause := context.Cause(ctx); cause != nil {
|
||||
// No census call was started. Preserve the caller's own completion.
|
||||
// The pass's silence sentinel and the historical explicit deadline
|
||||
// signal keep their owned mappings; opaque caller causes need Err too.
|
||||
if !errors.Is(cause, errVerifyStalled) && !errors.Is(cause, context.DeadlineExceeded) {
|
||||
cause = answer.RecordContext(ctx, answer.Unsent, errors.Join(ctx.Err(), cause))
|
||||
}
|
||||
return chunkResult(name, nil, cause, stdout, stderr)
|
||||
}
|
||||
err := checkSingleFiler(ctx, f)
|
||||
if err != nil && !errors.Is(err, chunkstore.ErrSingleFilerWindowExpired) && parent.Err() != nil {
|
||||
if c := context.Cause(parent); c != nil && !errors.Is(err, c) {
|
||||
@@ -76,7 +86,7 @@ func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunks
|
||||
switch {
|
||||
case err == nil:
|
||||
return -1
|
||||
case chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) || chunkTransportFailure(err):
|
||||
case knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled):
|
||||
return chunkResult(name, nil, err, stdout, stderr)
|
||||
case errors.Is(err, chunkstore.ErrNotSingleFiler):
|
||||
return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
@@ -177,25 +187,32 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
|
||||
if len(admission) == 1 && admission[0] != nil {
|
||||
req.Header.Set("Prefer", "respond-async")
|
||||
}
|
||||
resp, err := chunkHTTPClient.Do(req)
|
||||
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.Unsent)
|
||||
if err != nil {
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
|
||||
return chunkResult(name, nil, err, stdout, stderr)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
responseFailure := func(cause error) int {
|
||||
if resp.StatusCode >= http.StatusBadRequest {
|
||||
cause = answer.HTTPStatusFailure(resp.StatusCode, cause)
|
||||
} else {
|
||||
cause = answer.Rekind(answer.Record(answer.PossiblyAdmitted, cause), answer.Connection)
|
||||
}
|
||||
return chunkResult(name, nil, cause, stdout, stderr)
|
||||
}
|
||||
out, err := io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit+1))
|
||||
if err != nil {
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "read the response: "+err.Error(), true)
|
||||
return responseFailure(err)
|
||||
}
|
||||
if int64(len(out)) > chunkResponseLimit {
|
||||
// Refuse rather than relay a truncated body; the operation may have
|
||||
// happened, and its result is what would be lost.
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI,
|
||||
fmt.Sprintf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit), false)
|
||||
return responseFailure(fmt.Errorf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit))
|
||||
}
|
||||
if resp.StatusCode == http.StatusAccepted && len(admission) == 1 && admission[0] != nil {
|
||||
a := admission[0]
|
||||
if err := json.Unmarshal(out, &a.Answer); err != nil || a.Answer.ID != body["requestID"] || resp.Header.Get("Location") == "" {
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid snapshot operation admission", false)
|
||||
return responseFailure(fmt.Errorf("snapshot request %v: invalid operation admission; retry with the same --request-id against the original status address", body["requestID"]))
|
||||
}
|
||||
a.Raw = append([]byte(nil), out...)
|
||||
a.Location = resp.Header.Get("Location")
|
||||
@@ -216,15 +233,20 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
|
||||
}
|
||||
var e chunkErrBody
|
||||
if json.Unmarshal(out, &e) != nil || e.Code == "" {
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))), false)
|
||||
return responseFailure(fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))))
|
||||
}
|
||||
// The route's error body is already the CLI's error body: relay it.
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, chunkErrorAdvice(e.Code, e.Retryable, e.Message))
|
||||
policy, check := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Domain(e.Code, e.Retryable, e.Message)))
|
||||
if check != nil {
|
||||
policy, _ = answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Guard("unsupported_error_code")))
|
||||
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, check.Error()+"; "+policy.Cure, false)
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, policy.Cure)
|
||||
if err := writeAll(stdout, out); err != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the error: %v\n", name, err)
|
||||
return chunkExitFailed
|
||||
}
|
||||
return chunkErrorExit(chunkExitFailed, e.Code, e.Retryable)
|
||||
return policy.Exit
|
||||
}
|
||||
|
||||
func chunkCut(args []string, stdout, stderr io.Writer) int {
|
||||
@@ -367,27 +389,12 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
|
||||
// chunkResult prints v as JSON, or err as "<code>: <message>".
|
||||
func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
|
||||
if err != nil {
|
||||
var ce *chunkstore.CatalogError
|
||||
switch {
|
||||
case errors.As(err, &ce):
|
||||
exit := chunkExitFailed
|
||||
if name == "volume-delete" && ce.Code == "not_admitted" && ce.Retryable {
|
||||
exit = 75 // temporary admission refusal; retry the same request ID
|
||||
}
|
||||
return chunkFail(name, stdout, stderr, exit, ce.Code, ce.Detail(), ce.Retryable)
|
||||
case chunkCanceled(err):
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeCanceledCLI, "operation interrupted by its caller", false)
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
|
||||
case chunkTransportFailure(err):
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
|
||||
case errors.Is(err, errVerifyStalled):
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
|
||||
case layoutCode(err) != "":
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition) || errors.Is(err, layout.ErrBusy))
|
||||
default:
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
|
||||
contract := answer.Chunk
|
||||
if name == "verify" {
|
||||
contract = answer.ChunkVerify
|
||||
}
|
||||
policy, detail := chunkAnswerFor(err, contract)
|
||||
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, detail, policy.Retryable)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := json.NewEncoder(&buf).Encode(v); err != nil {
|
||||
@@ -422,6 +429,11 @@ type chunkErrBody struct {
|
||||
func chunkFail(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int {
|
||||
exit = chunkErrorExit(exit, code, retryable)
|
||||
message = chunkErrorAdvice(code, retryable, message)
|
||||
return chunkWriteFailure(name, stdout, stderr, exit, code, message, retryable)
|
||||
}
|
||||
|
||||
// chunkWriteFailure only renders an already-decided policy or server answer.
|
||||
func chunkWriteFailure(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int {
|
||||
prefix := "sw-block ops chunk"
|
||||
if name != "" {
|
||||
prefix += " " + name
|
||||
@@ -449,13 +461,15 @@ func writeAll(w io.Writer, p []byte) error {
|
||||
// CLI temporary remote failures use EX_TEMPFAIL consistently across commands.
|
||||
func chunkErrorExit(exit int, code string, retryable bool) int {
|
||||
if code == codeUnavailableCLI && retryable {
|
||||
return 75
|
||||
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, "")))
|
||||
return policy.Exit
|
||||
}
|
||||
return exit
|
||||
}
|
||||
func chunkErrorAdvice(code string, retryable bool, message string) string {
|
||||
if code == codeUnavailableCLI && retryable {
|
||||
return message + "; retry the same operation when the remote is reachable"
|
||||
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, message)))
|
||||
return policy.Cure
|
||||
}
|
||||
return message
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// Translate domain facts and transport evidence; the registry owns the
|
||||
// output code, retry decision and exit. Partial verify uses the same path.
|
||||
func chunkAnswer(err error) (answer.Policy, string) {
|
||||
return chunkAnswerFor(err, answer.Chunk)
|
||||
}
|
||||
|
||||
func chunkAnswerFor(err error, contract answer.Contract) (answer.Policy, string) {
|
||||
var domain *chunkstore.CatalogError
|
||||
hasDomain := errors.As(err, &domain)
|
||||
guard := layoutCode(err)
|
||||
_, recordedPolicy := answer.PolicyOf(err, contract)
|
||||
if !hasDomain && guard == "" && recordedPolicy != nil && errors.Is(err, errVerifyStalled) {
|
||||
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(contract, answer.Guard("deadline_exceeded")))
|
||||
return policy, err.Error() + "; " + policy.Cure
|
||||
}
|
||||
if (!hasDomain || domain.Code == chunkstore.CodeRemoteUnavailable) && (guard == "" || errors.Is(err, layout.ErrHolderActive)) {
|
||||
observed := err
|
||||
if kind, listed := answer.ErrorKind(err); listed && kind == answer.Configuration {
|
||||
observed = answer.EnsureEvidence(answer.Unsent, err)
|
||||
}
|
||||
if _, remote := status.FromError(err); remote {
|
||||
observed = answer.EnsureEvidence(answer.PossiblyAdmitted, err)
|
||||
}
|
||||
var network *net.OpError
|
||||
if errors.As(err, &network) {
|
||||
observed = answer.EnsureEvidence(answer.PossiblyAdmitted, observed)
|
||||
}
|
||||
if policy, check := answer.PolicyOf(observed, contract); check == nil {
|
||||
if policy.Code == codeCanceledCLI {
|
||||
return policy, policy.Cure
|
||||
}
|
||||
detail := err.Error()
|
||||
if hasDomain {
|
||||
detail = domain.Detail()
|
||||
}
|
||||
return policy, detail + "; " + policy.Cure
|
||||
}
|
||||
}
|
||||
kind, detail := answer.Guard("internal"), err.Error()
|
||||
switch {
|
||||
case hasDomain:
|
||||
kind = answer.Domain(domain.Code, domain.Retryable, domain.Detail())
|
||||
case guard != "":
|
||||
kind = answer.Guard(guard)
|
||||
case errors.Is(err, context.Canceled):
|
||||
kind = answer.Canceled
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
kind = answer.CallerDeadline
|
||||
case errors.Is(err, errVerifyStalled):
|
||||
kind = answer.Guard("deadline_exceeded")
|
||||
}
|
||||
policy, check := answer.Lookup(answer.Unsent, answer.ForContract(contract, kind))
|
||||
if check != nil {
|
||||
policy, _ = answer.Lookup(answer.Unsent, answer.ForContract(contract, answer.Guard("unsupported_error_code")))
|
||||
return policy, detail + "; " + check.Error()
|
||||
}
|
||||
if hasDomain || policy.Code == codeCanceledCLI {
|
||||
detail = policy.Cure
|
||||
}
|
||||
return policy, detail
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
@@ -36,15 +37,16 @@ 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. It returns exit -1 on
|
||||
// success, else the exit code after reporting.
|
||||
// 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.
|
||||
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)
|
||||
}
|
||||
f, closeFn, err := dialChunkFiler(filer)
|
||||
if err != nil {
|
||||
if chunkCanceled(err) || chunkTransportFailure(err) {
|
||||
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
|
||||
return nil, nil, chunkResult(name, nil, err, stdout, stderr)
|
||||
}
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
@@ -67,6 +69,11 @@ 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
|
||||
}
|
||||
|
||||
@@ -145,7 +152,7 @@ func (c *bCommand) run(args []string, writes bool, refs func() error, do func(co
|
||||
return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if err := refs(); err != nil {
|
||||
if chunkCanceled(err) || chunkTransportFailure(err) {
|
||||
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
|
||||
return chunkResult(name, nil, err, c.stdout, c.stderr)
|
||||
}
|
||||
if status.Code(err) == codes.NotFound { // the master does not know the volume
|
||||
@@ -354,7 +361,9 @@ 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) {
|
||||
return cat.Usage(ctx, ref)
|
||||
u, err := cat.Usage(ctx, ref)
|
||||
u.MetadataGuard = ""
|
||||
return u, err
|
||||
})
|
||||
}
|
||||
|
||||
@@ -385,21 +394,10 @@ func chunkRestore(args []string, stdout, stderr io.Writer) int {
|
||||
VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID,
|
||||
})
|
||||
if err != nil {
|
||||
switch status.Code(err) {
|
||||
case codes.NotFound:
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, "snapshot_not_found", err.Error(), false)
|
||||
case codes.AlreadyExists:
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, "target_exists", err.Error(), false)
|
||||
case codes.InvalidArgument:
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
case codes.FailedPrecondition:
|
||||
if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, layoutCode(layout.ErrForeignSource), err.Error(), false)
|
||||
}
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, "not_admitted", err.Error(), false)
|
||||
default:
|
||||
return chunkResult("restore", nil, err, stdout, stderr)
|
||||
if policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.Restore); check == nil {
|
||||
return chunkWriteFailure("restore", stdout, stderr, policy.Exit, policy.Code, err.Error()+"; "+policy.Cure, policy.Retryable)
|
||||
}
|
||||
return chunkResult("restore", nil, err, stdout, stderr)
|
||||
}
|
||||
if resp.GetVolumeId() != target || !resp.GetStoreReady() {
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, "master did not confirm the restored target is store-ready", true)
|
||||
|
||||
@@ -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`) {
|
||||
if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) || strings.Contains(out, "metadata_guard") {
|
||||
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" {
|
||||
|
||||
@@ -4,7 +4,10 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"net"
|
||||
@@ -12,13 +15,47 @@ import (
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/health/grpc_health_v1"
|
||||
)
|
||||
|
||||
func TestChunkCensusPreflightPreservesOpaqueContextCause(t *testing.T) {
|
||||
previous := checkSingleFiler
|
||||
t.Cleanup(func() { checkSingleFiler = previous })
|
||||
calls := 0
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error { calls++; return nil }
|
||||
for _, deadline := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint("deadline=", deadline), func(t *testing.T) {
|
||||
cause := errors.New("opaque caller reason")
|
||||
var ctx context.Context
|
||||
if deadline {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), cause)
|
||||
defer cancel()
|
||||
} else {
|
||||
var cancel context.CancelCauseFunc
|
||||
ctx, cancel = context.WithCancelCause(context.Background())
|
||||
cancel(cause)
|
||||
}
|
||||
var out, diag bytes.Buffer
|
||||
exit := refuseUnlessSingleFilerWithin(ctx, "verify", nil, time.Second, &out, &diag)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
code := "canceled"
|
||||
if deadline {
|
||||
code = "deadline_exceeded"
|
||||
}
|
||||
if exit != 1 || got.Code != code || got.Retryable != deadline {
|
||||
t.Fatalf("exit=%d answer=%+v", exit, got)
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("census calls=%d want zero", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A real gRPC call canceled by its caller keeps a cancellation answer.
|
||||
func TestChunkCallerCancelIsNotTransport(t *testing.T) {
|
||||
conn, err := grpc.NewClient("127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
conn, err := link.Dial("127.0.0.1:1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -13,28 +12,30 @@ import (
|
||||
"testing/synctest"
|
||||
)
|
||||
|
||||
// Keep the refused-dial fixture independent of port reuse and host forwarding:
|
||||
// net/http still builds and sends the request through its real Transport,
|
||||
// whose dial boundary supplies the kernel's typed refusal.
|
||||
func installRefusedHolderDial(t *testing.T) *atomic.Int32 {
|
||||
// Exercise the owned native dial path, not a caller-supplied transport whose
|
||||
// partial tracing cannot establish whether the request was sent.
|
||||
func installRefusedHolderDial(t *testing.T) string {
|
||||
t.Helper()
|
||||
calls := new(atomic.Int32)
|
||||
transport := &http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||
calls.Add(1)
|
||||
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
|
||||
}}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := listener.Addr().String()
|
||||
if err := listener.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := chunkHTTPClient
|
||||
chunkHTTPClient = &http.Client{Transport: transport}
|
||||
t.Cleanup(func() { transport.CloseIdleConnections(); chunkHTTPClient = old })
|
||||
return calls
|
||||
chunkHTTPClient = &http.Client{}
|
||||
t.Cleanup(func() { chunkHTTPClient = old })
|
||||
return "http://" + addr
|
||||
}
|
||||
|
||||
func TestPlainDetachRefusedDialIsRemoteUnavailable(t *testing.T) {
|
||||
calls := installRefusedHolderDial(t)
|
||||
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder")
|
||||
addr := installRefusedHolderDial(t)
|
||||
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", addr)
|
||||
e := chunkErrorOut(t, out)
|
||||
if code != 75 || e.Code != codeUnavailableCLI || !e.Retryable || strings.Contains(errOut, "outcome_unknown") || calls.Load() != 1 {
|
||||
t.Fatalf("refused dial: exit=%d dials=%d stdout=%s stderr=%s", code, calls.Load(), out, errOut)
|
||||
if code != 75 || e.Code != codeUnavailableCLI || !e.Retryable || strings.Contains(errOut, "outcome_unknown") {
|
||||
t.Fatalf("refused dial: exit=%d stdout=%s stderr=%s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
@@ -32,7 +33,7 @@ func TestChunkErrorFamilyAnswerTable(t *testing.T) {
|
||||
advice string
|
||||
only string
|
||||
}{
|
||||
{"remote", status.Error(codes.Unavailable, "connection refused"), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
|
||||
{"remote", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
|
||||
{"caller timeout", context.DeadlineExceeded, "deadline_exceeded", 1, true, context.DeadlineExceeded.Error(), ""},
|
||||
{"caller cancel", context.Canceled, "canceled", 1, false, "operation interrupted by its caller", ""},
|
||||
{"dependents", layout.ErrHasDependents, "snapshot_has_dependents", 1, false, layout.ErrHasDependents.Error(), ""},
|
||||
@@ -156,7 +157,7 @@ func TestSnapshotDeleteWorkTransportUsesSharedClassifier(t *testing.T) {
|
||||
return status.Error(codes.Unavailable, "filer stopped after admission")
|
||||
}, false, &out, &diag)
|
||||
answer := chunkErrorOut(t, out.String())
|
||||
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
|
||||
if exit != 3 || answer.Code != "outcome_unknown" || !answer.Retryable {
|
||||
t.Fatalf("exit=%d answer=%+v", exit, answer)
|
||||
}
|
||||
retained, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
|
||||
@@ -176,8 +177,20 @@ func TestVerifyIncompleteTransportPreservesPartialProgress(t *testing.T) {
|
||||
if err := json.Unmarshal(out.Bytes(), &answer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const message = "rpc error: code = Unavailable desc = filer stopped; retry the same operation when the remote is reachable"
|
||||
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: remote_unavailable: "+message+" (incomplete)\n" {
|
||||
const message = "rpc error: code = Unavailable desc = filer stopped; verification is read-only; after resolving the failure, run verification again; do not treat the incomplete scan as a clean result"
|
||||
if exit != 1 || answer.Code != "outcome_unknown" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: outcome_unknown: "+message+" (incomplete)\n" {
|
||||
t.Fatalf("exit=%d answer=%+v stderr=%q", exit, answer, diag.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyStartCheckLostAnswerNeverLooksLikeFindings(t *testing.T) {
|
||||
useMemChunkStore(t, newMemChunkStore())
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
|
||||
return answer.Record(answer.PossiblyAdmitted, status.Error(codes.Unavailable, "census answer lost"))
|
||||
}
|
||||
exit, out, diag := runChunk("verify", "--volume", "verify-00112233", "--chunk-filer", "fake:18888")
|
||||
body := chunkErrorOut(t, out)
|
||||
if exit != 1 || body.Code != "outcome_unknown" {
|
||||
t.Fatalf("exit=%d body=%+v diag=%s", exit, body, diag)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
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-")
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
// chunkTimeoutHelp is the --timeout text of the commands that use chunkPostLoop.
|
||||
@@ -184,7 +185,7 @@ func chunkStats(statusAddr, volumeID string, deadline time.Time) (chunkStagedSta
|
||||
if err != nil {
|
||||
return chunkStagedStats{}, false
|
||||
}
|
||||
resp, err := chunkHTTPClient.Do(req)
|
||||
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
|
||||
if err != nil {
|
||||
return chunkStagedStats{}, false
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func chunkPlainDetachPost(addr, volume string, timeout time.Duration, deadline t
|
||||
HeadGen uint64 `json:"headGen"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &seal); err != nil || seal.VolumeID != volume || seal.HeadGen == 0 {
|
||||
return chunkFail("detach", stdout, stderr, chunkExitFailed, codeInternalCLI, "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation", false)
|
||||
return chunkFail("detach", stdout, stderr, chunkExitUnknown, "outcome_unknown", "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation; retry the same plain detach to settle it", true)
|
||||
}
|
||||
if err := writeAll(stdout, out.Bytes()); err != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err)
|
||||
|
||||
@@ -107,7 +107,7 @@ func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) {
|
||||
return nil, status.Error(codes.Unavailable, "filer unreachable")
|
||||
}
|
||||
var out, errs bytes.Buffer
|
||||
if code := run(args, &out, &errs); code != 75 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
|
||||
if code := run(args, &out, &errs); code != 3 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), "outcome_unknown") {
|
||||
t.Fatalf("uncertain restore must be retryable: code=%d out=%q err=%q", code, out.String(), errs.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,8 +135,8 @@ func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) {
|
||||
t.Fatalf("unknown flag: exit %d %q", code, out)
|
||||
}
|
||||
t.Run("refused holder dial", func(t *testing.T) {
|
||||
installRefusedHolderDial(t)
|
||||
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://holder"); code != 75 {
|
||||
addr := installRefusedHolderDial(t)
|
||||
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", addr); code != 75 {
|
||||
t.Fatalf("unreachable blockvolume: exit %d %q", code, out)
|
||||
} else if e := chunkErrorOut(t, out); e.Code != codeUnavailableCLI || !e.Retryable {
|
||||
t.Fatalf("unreachable blockvolume: %+v, want remote_unavailable and retryable", e)
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"net"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -29,17 +29,9 @@ func chunkTransportFailure(err error) bool {
|
||||
if layoutCode(err) != "" && !errors.Is(err, layout.ErrHolderActive) {
|
||||
return false
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.Unavailable, codes.DeadlineExceeded:
|
||||
return true
|
||||
}
|
||||
var address *net.AddrError
|
||||
var syntax *net.ParseError
|
||||
if errors.As(err, &address) || errors.As(err, &syntax) {
|
||||
return false
|
||||
}
|
||||
var network net.Error
|
||||
return errors.As(err, &network)
|
||||
kind, listed := answer.ErrorKind(err)
|
||||
return listed && (kind == answer.Connection || kind == answer.PlaintextConnection || kind == answer.DNS || kind == answer.Timeout)
|
||||
|
||||
}
|
||||
|
||||
// gRPC cancellation does not wrap context.Canceled. Keep it distinct from an
|
||||
@@ -54,3 +46,10 @@ func chunkCanceled(err error) bool {
|
||||
}
|
||||
return errors.Is(err, context.Canceled) || status.Code(err) == codes.Canceled
|
||||
}
|
||||
|
||||
// Routing only: known error facts go to the shared policy; unknown local
|
||||
// argument errors remain with the command's validation path.
|
||||
func knownChunkFailure(err error) bool {
|
||||
_, listed := answer.ErrorKind(err)
|
||||
return listed
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"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"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -56,6 +57,7 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
t.Run(failure.name+"/"+phase+"/"+command, func(t *testing.T) {
|
||||
fixtureErr := answer.Record(answer.Unsent, failure.err)
|
||||
mem := newMemChunkStore()
|
||||
useMemChunkStore(t, mem)
|
||||
v := cliVolume(t, mem, "transport-source", "daily")
|
||||
@@ -84,18 +86,18 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
|
||||
case "resolve":
|
||||
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) {
|
||||
calls.Add(1)
|
||||
return layout.VolumeID{}, failure.err
|
||||
return layout.VolumeID{}, fixtureErr
|
||||
}
|
||||
case "dial":
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, failure.err }
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, fixtureErr }
|
||||
case "census":
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
|
||||
calls.Add(1)
|
||||
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, failure.err)
|
||||
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, fixtureErr)
|
||||
}
|
||||
case "read":
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
return transportLookupStore{mem, failure.err, &calls}, func() error { return nil }, nil
|
||||
return transportLookupStore{mem, fixtureErr, &calls}, func() error { return nil }, nil
|
||||
}
|
||||
case "restore":
|
||||
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
|
||||
@@ -110,6 +112,11 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
|
||||
if failure.name == "rpc-canceled" {
|
||||
wantCode, wantRetry, wantExit = "canceled", false, 1
|
||||
}
|
||||
if phase == "reserve" || phase == "no-lease" || phase == "restore" {
|
||||
// These are real server RPCs: the server received the
|
||||
// request before returning its ambiguous transport status.
|
||||
wantCode, wantRetry, wantExit = "outcome_unknown", true, 3
|
||||
}
|
||||
if calls.Load() == 0 || exit != wantExit || e.Code != wantCode || e.Retryable != wantRetry || (wantCode == codeUnavailableCLI && !strings.Contains(e.Message, "retry")) {
|
||||
t.Errorf("calls=%d exit=%d answer=%+v", calls.Load(), exit, e)
|
||||
}
|
||||
|
||||
@@ -25,8 +25,8 @@ func jsonCode(t *testing.T, out []byte) string {
|
||||
// The JSON codes a runner decides by, never the message text: a restore the
|
||||
// master refused for a foreign source is restore_source_not_own (from its
|
||||
// typed reason; an untyped FailedPrecondition stays not_admitted), and a
|
||||
// volume the master does not know is volume_not_found (any other resolve
|
||||
// transport failure is retryable remote_unavailable).
|
||||
// volume the master does not know is volume_not_found. A resolve failure
|
||||
// without admission evidence requires recovery of the same operation.
|
||||
func TestOpsChunkTypedRefusalCodes(t *testing.T) {
|
||||
prevRestore, prevResolve := restoreCreateRPC, resolveVolumeID
|
||||
t.Cleanup(func() { restoreCreateRPC, resolveVolumeID = prevRestore, prevResolve })
|
||||
@@ -55,7 +55,7 @@ func TestOpsChunkTypedRefusalCodes(t *testing.T) {
|
||||
code string
|
||||
}{
|
||||
{"unknown volume", status.Error(codes.NotFound, "volume not found"), chunkExitFailed, "volume_not_found"},
|
||||
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 75, codeUnavailableCLI},
|
||||
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 3, "outcome_unknown"},
|
||||
} {
|
||||
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{}, c.err }
|
||||
var out, errs bytes.Buffer
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
// chunkVerify: sw-block ops chunk verify --master master:9180 --volume v --chunk-filer host:port
|
||||
@@ -21,8 +22,9 @@ import (
|
||||
// (the current image and every snapshot), their segments and chunks
|
||||
// (chunkstore.VerifyLayout). --orphans also reports the volume's own names
|
||||
// that no reachable root names (it never deletes them). Exit 0: clean; 3:
|
||||
// the pass completed with findings; 1: it could not complete (the partial
|
||||
// result is printed with the reason); 2: usage.
|
||||
// the pass completed with findings. Incomplete failures retain their typed
|
||||
// class and partial result: unknown/operational 1, arguments 2, integrity 4,
|
||||
// auth 5, unsent/retryable remote 75, local configuration 78; never findings 3.
|
||||
func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("verify", stderr)
|
||||
var (
|
||||
@@ -114,7 +116,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
f, closeFn, err := dialChunkFiler(filer)
|
||||
if err != nil {
|
||||
if chunkCanceled(err) || chunkTransportFailure(err) {
|
||||
if knownChunkFailure(err) {
|
||||
return verifyIncomplete(layout.VerifyResult{}, err, stdout, stderr)
|
||||
}
|
||||
return usage(err.Error())
|
||||
@@ -290,17 +292,9 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ
|
||||
chunkErrBody
|
||||
Verify layout.VerifyResult `json:"verify"`
|
||||
}{Verify: res}
|
||||
body.Code, body.Message = codeInternalCLI, err.Error()
|
||||
if chunkCanceled(err) {
|
||||
body.Code, body.Message = codeCanceledCLI, "operation interrupted by its caller"
|
||||
} else if chunkTransportFailure(err) {
|
||||
body.Code, body.Retryable = codeUnavailableCLI, true
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || (errors.Is(err, errVerifyStalled) && !chunkTransportFailure(err)) {
|
||||
body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true
|
||||
}
|
||||
body.Message = chunkErrorAdvice(body.Code, body.Retryable, body.Message)
|
||||
policy, detail := chunkAnswerFor(err, answer.ChunkVerify)
|
||||
body.Code, body.Message, body.Retryable = policy.Code, detail, policy.Retryable
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
|
||||
chunkResult("verify", body, nil, stdout, stderr)
|
||||
return chunkErrorExit(chunkExitFailed, body.Code, body.Retryable)
|
||||
return policy.Exit
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
)
|
||||
@@ -95,15 +96,7 @@ func (m *masterAuthority) NoLiveLease(ctx context.Context) error {
|
||||
// Anything else (unavailable, deadline, a lost response) leaves
|
||||
// the outcome unknown and a rerun decides.
|
||||
func authorityErr(err error) error {
|
||||
// A serving holder can renew its horizon indefinitely. A clean stop is
|
||||
// distinguished by the master's typed detail, never by a dated message.
|
||||
result := finalLeaseBarrierErr(err)
|
||||
var refusal *chunkstore.CatalogError
|
||||
if errors.As(result, &refusal) && refusal.Code == "not_admitted" && refusal.Retryable && !deleteLeaseBarrierDetail(err) {
|
||||
refusal.Retryable = false
|
||||
refusal.Message = "stop the volume first"
|
||||
}
|
||||
return result
|
||||
return leaseRefusal(err, false)
|
||||
}
|
||||
|
||||
func deleteLeaseBarrierDetail(err error) bool {
|
||||
@@ -118,6 +111,12 @@ func deleteLeaseBarrierDetail(err error) bool {
|
||||
// finalLeaseBarrierErr projects the dated deletion barrier. Reserve callers
|
||||
// additionally require the clean-stop detail before allowing timed retry.
|
||||
func finalLeaseBarrierErr(err error) error {
|
||||
return leaseRefusal(err, true)
|
||||
}
|
||||
|
||||
// Translate the master's dated refusal and the admission step into facts.
|
||||
// Retry policy and cure text belong to the shared registry.
|
||||
func leaseRefusal(err error, committed bool) error {
|
||||
switch status.Code(err) {
|
||||
case codes.OK:
|
||||
return nil
|
||||
@@ -127,7 +126,15 @@ func finalLeaseBarrierErr(err error) error {
|
||||
if _, rest, ok := strings.Cut(status.Convert(err).Message(), "workspace delete: live until "); ok {
|
||||
if stamp, reason, ok := strings.Cut(rest, ": "); ok && reason != "" {
|
||||
if until, parseErr := time.Parse(time.RFC3339Nano, stamp); parseErr == nil {
|
||||
return &chunkstore.CatalogError{Code: "not_admitted", Message: "retry the same --request-id after " + until.UTC().Format(time.RFC3339Nano), Retryable: true, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
|
||||
kind := answer.LeaseBarrier(until.UTC().Format(time.RFC3339Nano))
|
||||
if !committed && !deleteLeaseBarrierDetail(err) {
|
||||
kind = answer.Guard("delete_live_holder")
|
||||
}
|
||||
policy, check := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, kind))
|
||||
if check != nil {
|
||||
return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, check)
|
||||
}
|
||||
return &chunkstore.CatalogError{Code: policy.Code, Message: policy.Cure, Retryable: policy.Retryable, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,7 +234,10 @@ func deleteVolumeWithProgress(ctx context.Context, cat *chunkstore.BCatalog, ref
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
transient := errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Unavailable
|
||||
policy, _ := chunkAnswer(err)
|
||||
// This is reconciliation of the same full volume ID under the same
|
||||
// deletion reservation, never admission of a second operation.
|
||||
transient := policy.Retryable && (chunkTransportFailure(err) || errors.Is(err, context.DeadlineExceeded))
|
||||
if !transient {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
@@ -40,7 +41,11 @@ func (f *transientDeleteFiler) DeleteEntry(ctx context.Context, dir, name string
|
||||
return err
|
||||
}
|
||||
}
|
||||
return status.Error(f.code, "object deadline")
|
||||
phase := answer.Unsent // this fixture refuses before applying any delete
|
||||
if f.lost {
|
||||
phase = answer.PossiblyAdmitted
|
||||
}
|
||||
return answer.Record(phase, status.Error(f.code, "object deadline"))
|
||||
}
|
||||
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
@@ -100,6 +105,9 @@ 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)
|
||||
@@ -116,7 +124,7 @@ func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string,
|
||||
return err
|
||||
}
|
||||
if f.stall {
|
||||
return status.Error(codes.Unavailable, "stalled after first removal")
|
||||
return answer.Record(answer.Unsent, status.Error(codes.Unavailable, "stalled after first removal"))
|
||||
}
|
||||
if !f.waited {
|
||||
f.waited = true
|
||||
@@ -166,6 +174,9 @@ func TestVolumeDeleteRefreshesAnExpiredSweepAndWaitsFromLastRemoval(t *testing.T
|
||||
type blockedDeleteFiler struct{ *memChunkStore }
|
||||
|
||||
func (f *blockedDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if inStartupProbe(dir, name) {
|
||||
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
@@ -40,7 +41,8 @@ func TestVolumeDeleteAdmissionRetryAnswer(t *testing.T) {
|
||||
{"HEAD boundary horizon", fmt.Errorf("%w: %w", layout.ErrHolderActive, lease), 75, "not_admitted", true},
|
||||
{"invalid admission", authorityErr(status.Error(codes.InvalidArgument, "invalid token")), 1, "not_admitted", false},
|
||||
{"dependents", layout.ErrHasDependents, 1, "snapshot_has_dependents", false},
|
||||
{"remote unknown", authorityErr(status.Error(codes.Unavailable, "connection refused")), 75, "remote_unavailable", true},
|
||||
{"remote unknown without phase proof", authorityErr(status.Error(codes.Unavailable, "connection refused")), 3, "outcome_unknown", true},
|
||||
{"remote proven unsent", authorityErr(answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused"))), 75, "remote_unavailable", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var out, diag bytes.Buffer
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
policy "github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
@@ -152,7 +152,8 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
|
||||
}
|
||||
c, closeFn, err := clusterLifecycleDial(*master)
|
||||
if err != nil {
|
||||
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
|
||||
p, detail := operatorAnswer(err, policy.Cluster)
|
||||
return fail("failed", p.Code, detail.Error(), p.Exit)
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
@@ -164,15 +165,15 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
|
||||
if reason == "" {
|
||||
reason = status.Code(err).String()
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition:
|
||||
p, check := policy.PolicyOf(policy.EnsureEvidence(policy.PossiblyAdmitted, err), policy.Cluster)
|
||||
if check != nil {
|
||||
return fail("failed", reason, check.Error(), finalizeExitFailed)
|
||||
}
|
||||
if p.Code == "not_admitted" {
|
||||
answer.Hosts = metadataHosts(md, lifecycleclient.HostMetadataPrefix)
|
||||
answer.Listed = metadataHosts(md, lifecycleclient.UnconfirmedMetadataPrefix)
|
||||
return fail("refused", reason, msg, finalizeExitRefused)
|
||||
case codes.Unavailable, codes.DeadlineExceeded:
|
||||
return fail("unavailable", reason, msg, finalizeExitTempFail)
|
||||
}
|
||||
return fail("failed", reason, msg, finalizeExitFailed)
|
||||
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
|
||||
}
|
||||
answer.FormatLevel = resp.GetFormatLevel()
|
||||
for _, u := range resp.GetUnconfirmed() {
|
||||
@@ -289,7 +290,8 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
|
||||
answer.Server = *server
|
||||
c, closeFn, err := clusterLifecycleDial(*master)
|
||||
if err != nil {
|
||||
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
|
||||
p, detail := operatorAnswer(err, policy.Cluster)
|
||||
return fail("failed", p.Code, detail.Error(), p.Exit)
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
@@ -300,14 +302,14 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
|
||||
if reason == "" {
|
||||
reason = status.Code(err).String()
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition:
|
||||
answer.Volumes = retireVolumes(md)
|
||||
return fail("refused", reason, msg, finalizeExitRefused)
|
||||
case codes.Unavailable, codes.DeadlineExceeded:
|
||||
return fail("unavailable", reason, msg, finalizeExitTempFail)
|
||||
p, check := policy.PolicyOf(policy.EnsureEvidence(policy.PossiblyAdmitted, err), policy.Cluster)
|
||||
if check != nil {
|
||||
return fail("failed", reason, check.Error(), finalizeExitFailed)
|
||||
}
|
||||
return fail("failed", reason, msg, finalizeExitFailed)
|
||||
if p.Code == "not_admitted" {
|
||||
answer.Volumes = retireVolumes(md)
|
||||
}
|
||||
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
|
||||
}
|
||||
answer.Result, answer.Message = "retired", "host retired from the node inventory"
|
||||
if !jsonMode {
|
||||
@@ -316,6 +318,23 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
|
||||
return finalizeExitOK
|
||||
}
|
||||
|
||||
// Serialize the shared class in the cluster command's existing result field.
|
||||
func clusterPolicyResult(p policy.Policy) string {
|
||||
switch p.Code {
|
||||
case "not_admitted":
|
||||
return "refused"
|
||||
case "remote_unavailable":
|
||||
return "unavailable"
|
||||
case "outcome_unknown":
|
||||
if p.Exit == finalizeExitFailed {
|
||||
return "failed"
|
||||
}
|
||||
return "unknown"
|
||||
default:
|
||||
return "failed"
|
||||
}
|
||||
}
|
||||
|
||||
// retireVolumes reads the held volumes from the refusal's typed metadata,
|
||||
// sorted.
|
||||
func retireVolumes(md map[string]string) []string {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"reflect"
|
||||
"sort"
|
||||
"testing"
|
||||
@@ -50,12 +51,12 @@ func TestClusterFinalizeFormatTypedAnswer(t *testing.T) {
|
||||
listed: []finalizeHost{{"node-d", "no report"}}},
|
||||
{name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"},
|
||||
{name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"},
|
||||
{name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"},
|
||||
{name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 1, result: "failed", reason: "Internal"},
|
||||
{name: "dial", dialErr: answer.LocalConfiguration(errors.New("bad address")), exit: 78, result: "failed", reason: "bad_request"},
|
||||
{name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 3, result: "unknown", reason: "Internal"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
|
||||
return tc.resp, tc.err
|
||||
return tc.resp, answer.Record(answer.Unsent, tc.err)
|
||||
}}
|
||||
withClusterMaster(t, f)
|
||||
if tc.dialErr != nil {
|
||||
@@ -179,8 +180,8 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
|
||||
{name: "not-registered", err: status.Error(codes.FailedPrecondition, "retire refused: host is not registered"), exit: 2, result: "refused", reason: "FailedPrecondition"},
|
||||
{name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"},
|
||||
{name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"},
|
||||
{name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"},
|
||||
{name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 1, result: "failed", reason: "Internal"},
|
||||
{name: "dial", dialErr: answer.LocalConfiguration(errors.New("bad address")), exit: 78, result: "failed", reason: "bad_request"},
|
||||
{name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 3, result: "unknown", reason: "Internal"},
|
||||
{name: "usage", args: []string{"cluster", "retire-host", "--json", "--bogus", "--master", "m:1"}, exit: 1, result: "failed", reason: "usage"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -188,7 +189,7 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
|
||||
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
|
||||
calls++
|
||||
if tc.err != nil {
|
||||
return nil, tc.err
|
||||
return nil, answer.Record(answer.Unsent, tc.err)
|
||||
}
|
||||
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
|
||||
}}
|
||||
|
||||
@@ -4,16 +4,15 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
const cutObservationSlack = 5 * time.Second
|
||||
@@ -84,15 +83,16 @@ func chunkObserveHandle(name, route, addr string, window time.Duration, deadline
|
||||
if method == http.MethodPost {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
phase := answer.Unsent
|
||||
if id != "" {
|
||||
phase = answer.PossiblyAdmitted
|
||||
}
|
||||
resp, err := answer.DoHTTP(&client, req, phase)
|
||||
var raw []byte
|
||||
if err != nil && id == "" {
|
||||
cancel()
|
||||
// A failed dial sent no admission request. Other transport
|
||||
// failures may have lost an applied request's answer.
|
||||
var network *net.OpError
|
||||
if errors.As(err, &network) && network.Op == "dial" && chunkTransportFailure(err) {
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
|
||||
if policy, check := answer.PolicyOf(err, answer.Chunk); check == nil {
|
||||
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, err.Error()+"; "+policy.Cure, policy.Retryable)
|
||||
}
|
||||
return unknown(name + " admission answer was not received (" + err.Error() + "); no second one was started")
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -11,9 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const opsFailoverName = "sw-block ops failover"
|
||||
@@ -51,10 +49,12 @@ volumes); a line that moved since is refused.
|
||||
Needs an admin client certificate: SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and
|
||||
SW_BLOCK_TLS_CA, all three; without them the command refuses before dialing.
|
||||
|
||||
Exit: 0 moved; 1 refused by blockmaster, or the line did not move; 2 bad
|
||||
arguments or identity (no call made); 3 outcome unknown (the connection or the
|
||||
deadline failed: the line may have moved; read it with sw-block ops volumes
|
||||
before retrying).
|
||||
Exit: 0 moved; 1 definite precondition refusal, caller cancellation before
|
||||
sending, or the line did not move; 2 bad arguments or a server argument
|
||||
refusal; 3 outcome unknown (or an unsent connection failure or caller
|
||||
deadline): read the current line with sw-block ops volumes before another
|
||||
move; 4 unproven integrity readout; 5 authentication rejection; 78 local
|
||||
credential/configuration error.
|
||||
`
|
||||
|
||||
func runOpsFailover(args []string, stdout, stderr io.Writer) int {
|
||||
@@ -93,11 +93,13 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
// An admin command never falls back to a plaintext link.
|
||||
if tls, err := link.MasterTLSFromEnv(); err != nil {
|
||||
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, err)
|
||||
return 2
|
||||
p, detail := operatorAnswer(err, answer.Failover)
|
||||
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, detail)
|
||||
return p.Exit
|
||||
} else if tls == nil {
|
||||
fmt.Fprintf(stderr, "%s: needs an admin client certificate: set %s, %s and %s\n", opsFailoverName, link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)
|
||||
return 2
|
||||
p, _ := operatorAnswer(answer.LocalCredential(fmt.Errorf("admin client certificate is required")), answer.Failover)
|
||||
return p.Exit
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
@@ -119,14 +121,15 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
|
||||
EvidenceRefs: []string{"sw-block ops failover", "operator_confirmed_old_node_off=" + volume},
|
||||
})
|
||||
if err != nil {
|
||||
if failoverOutcomeUnknown(err) {
|
||||
policy, detail := operatorAnswer(err, answer.Failover)
|
||||
if policy.Retry == answer.Recover {
|
||||
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=unknown\n", volume, target, curReplica, curEpoch)
|
||||
fmt.Fprintf(stderr, "%s: outcome unknown (%v): the line may have moved; read it with sw-block ops volumes before retrying\n", opsFailoverName, err)
|
||||
return 3
|
||||
return policy.Exit
|
||||
}
|
||||
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch)
|
||||
fmt.Fprintf(stderr, "%s: refused: %v (no line published; a refused fencing round may have fenced the survivors)\n", opsFailoverName, err)
|
||||
return 1
|
||||
fmt.Fprintf(stderr, "%s: %v (a refused fencing round may have fenced the survivors)\n", opsFailoverName, detail)
|
||||
return policy.Exit
|
||||
}
|
||||
moved := res.FailbackStarted && res.AuthorityEpochAdvanced && res.SinglePrimaryAfterFailback
|
||||
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=%s epoch_advanced=%t single_primary=%t publish_target_swapped=%t\n",
|
||||
@@ -150,21 +153,3 @@ func parseReplicaAtEpoch(s string) (string, uint64, bool) {
|
||||
}
|
||||
return s[:i], e, true
|
||||
}
|
||||
|
||||
// failoverOutcomeUnknown: the call did not get blockmaster's decision back
|
||||
// (connection, deadline, cancellation or an internal failure), so the line
|
||||
// may or may not have moved. A decided refusal is any other status.
|
||||
func failoverOutcomeUnknown(err error) bool {
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return true
|
||||
}
|
||||
s, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
switch s.Code() {
|
||||
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss, codes.ResourceExhausted:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -169,6 +171,42 @@ func TestOpsFailoverReportsAnUnknownOutcome(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A master that never answers the handshake leaves the call unsent when the
|
||||
// caller's deadline passes; the operator must still read the line first.
|
||||
func TestOpsFailoverUnsentCallerDeadlineIsUnknown(t *testing.T) {
|
||||
cert, key, ca := writeClientIdentity(t, t.TempDir())
|
||||
t.Setenv(link.EnvTLSCert, cert)
|
||||
t.Setenv(link.EnvTLSKey, key)
|
||||
t.Setenv(link.EnvTLSCA, ca)
|
||||
silent, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held := make(chan net.Conn, 16)
|
||||
go func() {
|
||||
for {
|
||||
conn, err := silent.Accept()
|
||||
if err != nil {
|
||||
close(held)
|
||||
return
|
||||
}
|
||||
held <- conn
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
silent.Close()
|
||||
for conn := range held {
|
||||
conn.Close()
|
||||
}
|
||||
})
|
||||
args := failoverArgs("--timeout", "300ms")
|
||||
args[3] = silent.Addr().String()
|
||||
var out, errb bytes.Buffer
|
||||
if rc := run(args, &out, &errb); rc != 3 || !strings.Contains(out.String(), "result=unknown") {
|
||||
t.Fatalf("rc=%d stdout=%q stderr=%q; want 3 and result=unknown", rc, out.String(), errb.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The admin command never dials without a complete, valid client identity:
|
||||
// unset, partial or unreadable TLS settings are refused locally (exit 2, no
|
||||
// call); a valid identity makes the call.
|
||||
@@ -202,8 +240,8 @@ func TestOpsFailoverRequiresAClientIdentity(t *testing.T) {
|
||||
if len(f.calls) != c.calls {
|
||||
t.Fatalf("calls=%d; want %d (rc=%d stderr %q)", len(f.calls), c.calls, rc, errb.String())
|
||||
}
|
||||
if c.calls == 0 && rc != 2 {
|
||||
t.Fatalf("rc=%d; want 2", rc)
|
||||
if c.calls == 0 && rc != 78 {
|
||||
t.Fatalf("rc=%d; want 78", rc)
|
||||
}
|
||||
if c.calls == 1 && rc != 0 {
|
||||
t.Fatalf("rc=%d stderr %q; want 0", rc, errb.String())
|
||||
@@ -288,3 +326,27 @@ func TestAlphaFailbackExecutorRendersTheSelectedImage(t *testing.T) {
|
||||
t.Fatalf("rendered executor does not run the selected image: %s", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpsFailoverUsesSharedDefiniteExitProjection(t *testing.T) {
|
||||
for _, row := range []struct {
|
||||
name string
|
||||
err error
|
||||
exit int
|
||||
}{
|
||||
{"certificate", status.Error(codes.Unauthenticated, "certificate rejected"), 5},
|
||||
{"role", status.Error(codes.PermissionDenied, "admin required"), 5},
|
||||
{"integrity", status.Error(codes.DataLoss, "line readout unproven"), 4},
|
||||
{"arguments", status.Error(codes.InvalidArgument, "invalid target"), 2},
|
||||
{"precondition", status.Error(codes.FailedPrecondition, "target not ready"), 1},
|
||||
{"unknown", status.Error(codes.Unavailable, "answer lost"), 3},
|
||||
{"unsent", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection unavailable")), 3},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
withFailoverRuntime(t, &fakeFailoverRuntime{err: row.err})
|
||||
var out, diag bytes.Buffer
|
||||
if exit := run(failoverArgs(), &out, &diag); exit != row.exit {
|
||||
t.Fatalf("exit=%d want=%d out=%s diag=%s", exit, row.exit, out.String(), diag.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2340,7 +2340,7 @@ func usage(w io.Writer) {
|
||||
fmt.Fprintln(w, " sw-block ops chunk snapshots|snapshot-delete --volume <id> [--name <name>] --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk show --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk verify --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks] [--depth meta|bindings|data] [--orphans] [--timeout <d>]")
|
||||
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)")
|
||||
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 completed findings; incomplete: 1 operational/unknown, 2 usage/server arguments, 4 unproven readout, 5 auth, 75 unsent/retryable remote, 78 local config; --depth data needs --timeout)")
|
||||
fmt.Fprintln(w, " sw-block ops volume resolve --master <addr> [--timeout 10s] <name> (prints the master layout id)")
|
||||
fmt.Fprintln(w, " sw-block ops volume-unheld --path <volume-file> (exit 0: no process on this host holds it; local filesystems only)")
|
||||
fmt.Fprintln(w, " sw-block ops failover --master <addr> --volume <id> --target <replica> --target-data <addr> --target-ctrl <addr> --expect-current <replica>@<epoch> --confirm-old-node-off <volume>")
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
// sw-block mini starts the single-host configuration in one command, after
|
||||
@@ -292,6 +293,7 @@ func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) {
|
||||
// ready waits until every port listens, while c is alive, bounded.
|
||||
func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
|
||||
deadline := time.Now().Add(miniStartWait)
|
||||
var lastErr error
|
||||
for {
|
||||
if d := r.dead(); d != nil {
|
||||
return fmt.Errorf("%s exited during startup: %v (see %s.log)", d.name, d.err, d.name)
|
||||
@@ -300,6 +302,7 @@ func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
|
||||
for _, p := range ports {
|
||||
conn, err := net.DialTimeout("tcp", loopback(p), 200*time.Millisecond)
|
||||
if err != nil {
|
||||
lastErr = answer.Record(answer.Unsent, err) // TCP probe writes no application request
|
||||
up = false
|
||||
break
|
||||
}
|
||||
@@ -309,11 +312,11 @@ func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log)", c.name, miniStartWait, ports, c.name)
|
||||
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log): %w", c.name, miniStartWait, ports, c.name, answer.Present(lastErr, answer.Ops))
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
|
||||
case <-time.After(250 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestReviewInitialPostBodyFailurePreservesStatus(t *testing.T) {
|
||||
oldBound, oldPause, oldMax := chunkRequestBound, chunkPauseStart, chunkPauseMax
|
||||
chunkRequestBound, chunkPauseStart, chunkPauseMax = 2*time.Second, 20*time.Millisecond, 20*time.Millisecond
|
||||
t.Cleanup(func() { chunkRequestBound, chunkPauseStart, chunkPauseMax = oldBound, oldPause, oldMax })
|
||||
for _, row := range []struct {
|
||||
status int
|
||||
code string
|
||||
exit int
|
||||
}{
|
||||
{403, "not_authorized", 5}, {401, "not_authorized", 5}, {400, "bad_request", 2},
|
||||
{200, "outcome_unknown", 3}, {503, "outcome_unknown", 3},
|
||||
} {
|
||||
t.Run(fmt.Sprint(row.status), func(t *testing.T) {
|
||||
var posts atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
fmt.Fprint(w, `{}`)
|
||||
return
|
||||
}
|
||||
posts.Add(1)
|
||||
w.Header().Set("Content-Length", "1000")
|
||||
w.WriteHeader(row.status)
|
||||
fmt.Fprint(w, `{`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
var out, diag bytes.Buffer
|
||||
body := map[string]any{"volumeID": "v1", "requestID": "same-operation"}
|
||||
var exit int
|
||||
if row.status == 403 {
|
||||
exit = chunkPostLoop("snapshot", srv.URL, "/chunk/snapshot", 4*time.Second, body, &out, &diag)
|
||||
} else {
|
||||
exit = chunkPost("snapshot", srv.URL, "/chunk/snapshot", time.Second, body, &out, &diag)
|
||||
}
|
||||
answer := chunkErrorOut(t, out.String())
|
||||
if exit != row.exit || answer.Code != row.code || posts.Load() != 1 || (row.exit != 3 && answer.Retryable) {
|
||||
t.Fatalf("HTTP%d: exit=%d answer=%+v posts=%d", row.status, exit, answer, posts.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewForceMovePreservesServerPolicyExit(t *testing.T) {
|
||||
for _, row := range []struct {
|
||||
code codes.Code
|
||||
exit int
|
||||
}{{codes.InvalidArgument, 2}, {codes.FailedPrecondition, 1}} {
|
||||
t.Run(row.code.String(), func(t *testing.T) {
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
return nil, status.Error(row.code, "server refuses this move")
|
||||
}}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
exit, out, diag := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--json"))
|
||||
if exit != row.exit || !strings.Contains(out, `"admitted":false`) || !strings.Contains(out, `"code":"`+row.code.String()+`"`) || f.n("MoveWorkspace") != 1 || !strings.Contains(diag, "refused by the master") {
|
||||
t.Fatalf("exit=%d out=%s diag=%s moves=%d", exit, out, diag, f.n("MoveWorkspace"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestReviewCompleteBodyKeepsStatusAndAdmission(t *testing.T) {
|
||||
for _, row := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
exit int
|
||||
code string
|
||||
}{
|
||||
{"malformed-forbidden", 403, "{", 5, "not_authorized"},
|
||||
{"malformed-arguments", 400, "{", 2, "bad_request"},
|
||||
{"malformed-missing", 404, "{", 1, "not_found"},
|
||||
{"malformed-precondition", 409, "{", 1, "not_admitted"},
|
||||
{"malformed-rate-limit", 429, "{", 3, "outcome_unknown"},
|
||||
{"malformed-server", 500, "{", 3, "outcome_unknown"},
|
||||
{"malformed-gateway", 502, "{", 3, "outcome_unknown"},
|
||||
{"malformed-unavailable", 503, "{", 3, "outcome_unknown"},
|
||||
{"malformed-gateway-timeout", 504, "{", 3, "outcome_unknown"},
|
||||
{"empty-success", 204, "", 3, "outcome_unknown"},
|
||||
{"malformed-redirect", 302, "{", 3, "outcome_unknown"},
|
||||
{"oversized-forbidden", 403, "oversized", 5, "not_authorized"},
|
||||
{"oversized-success", 200, "oversized", 3, "outcome_unknown"},
|
||||
{"oversized-admission", 202, "oversized", 3, "outcome_unknown"},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
if row.body == "oversized" && testing.Short() {
|
||||
t.Skip("64 MiB production body limit: run in native qualification")
|
||||
}
|
||||
var posts atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
posts.Add(1)
|
||||
w.WriteHeader(row.status)
|
||||
if row.body == "oversized" {
|
||||
_, _ = io.CopyN(w, repeatResponseByte{}, chunkResponseLimit+1)
|
||||
} else {
|
||||
fmt.Fprint(w, row.body)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
var out, diag bytes.Buffer
|
||||
var admission snapshotCLIAdmission
|
||||
exit := chunkPost("snapshot", srv.URL, "/chunk/snapshot", 3*time.Second, map[string]any{"requestID": "original"}, &out, &diag, &admission)
|
||||
a := chunkErrorOut(t, out.String())
|
||||
if exit != row.exit || a.Code != row.code || posts.Load() != 1 || (row.exit == 3 && !a.Retryable) {
|
||||
t.Fatalf("exit=%d answer=%+v posts=%d stderr=%s", exit, a, posts.Load(), &diag)
|
||||
}
|
||||
if admission.Accepted {
|
||||
t.Fatalf("unusable response was accepted: answer=%+v admission=%+v", a, admission)
|
||||
}
|
||||
if row.body == "oversized" {
|
||||
want := fmt.Sprintf("HTTP %d response exceeds %d bytes; not relaying a truncated body", row.status, chunkResponseLimit)
|
||||
if !strings.Contains(a.Message, want) {
|
||||
t.Fatalf("oversized response was not observed: want diagnostic %q, answer=%+v stderr=%s", want, a, &diag)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type repeatResponseByte struct{}
|
||||
|
||||
func (repeatResponseByte) Read(p []byte) (int, error) {
|
||||
for i := range p {
|
||||
p[i] = 'x'
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestReviewInvalidAdmissionKeepsOriginalRequest(t *testing.T) {
|
||||
for _, row := range []struct{ name, body, location string }{
|
||||
{"malformed", "{", "/operations/original"},
|
||||
{"wrong-id", `{"operation_id":"other","state":"running"}`, "/operations/other"},
|
||||
{"missing-location", `{"operation_id":"original","state":"running"}`, ""},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", row.location)
|
||||
w.WriteHeader(202)
|
||||
fmt.Fprint(w, row.body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
var out, diag bytes.Buffer
|
||||
var a snapshotCLIAdmission
|
||||
exit := chunkPost("snapshot", srv.URL, "/chunk/snapshot", 3*time.Second, map[string]any{"requestID": "original"}, &out, &diag, &a)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if exit != 3 || got.Code != "outcome_unknown" || !strings.Contains(got.Message, "original") || a.Accepted {
|
||||
t.Fatalf("exit=%d answer=%+v accepted=%v", exit, got, a.Accepted)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewUnsafeSnapshotLocationKeepsOriginalUnknown(t *testing.T) {
|
||||
var foreignGets atomic.Int32
|
||||
foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
foreignGets.Add(1)
|
||||
fmt.Fprint(w, `{"operation_id":"original","state":"succeeded","result":{"ok":true}}`)
|
||||
}))
|
||||
defer foreign.Close()
|
||||
for _, location := range []string{"%zz", foreign.URL + "/operations/original"} {
|
||||
t.Run(location, func(t *testing.T) {
|
||||
var posts, gets atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
gets.Add(1)
|
||||
http.Error(w, "unexpected poll", 500)
|
||||
return
|
||||
}
|
||||
posts.Add(1)
|
||||
w.Header().Set("Location", location)
|
||||
w.WriteHeader(202)
|
||||
fmt.Fprint(w, `{"operation_id":"original","state":"running"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
var out, diag bytes.Buffer
|
||||
exit := chunkObserveSnapshot(srv.URL, 3*time.Second, map[string]any{"requestID": "original"}, false, &out, &diag)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "original") || !strings.Contains(got.Message, "--request-id") || posts.Load() != 1 || gets.Load() != 0 || foreignGets.Load() != 0 {
|
||||
t.Fatalf("exit=%d answer=%+v posts=%d polls=%d foreign=%d stderr=%s", exit, got, posts.Load(), gets.Load(), foreignGets.Load(), &diag)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An observed success without a usable result does not settle the original operation.
|
||||
func TestReviewAdmittedMissingResultKeepsUnknown(t *testing.T) {
|
||||
for _, mode := range []string{"detach", "snapshot-admission", "snapshot-poll"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
var posts, gets atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
posts.Add(1)
|
||||
} else {
|
||||
gets.Add(1)
|
||||
}
|
||||
if mode == "detach" {
|
||||
fmt.Fprint(w, `{"apiVersion":1,"volumeID":"vol-a","headGen":0}`)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Location", "/operations/original")
|
||||
if r.Method == http.MethodPost {
|
||||
w.WriteHeader(202)
|
||||
if mode == "snapshot-poll" {
|
||||
fmt.Fprint(w, `{"operation_id":"original","state":"running"}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
fmt.Fprint(w, `{"operation_id":"original","state":"succeeded"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
var out, diag bytes.Buffer
|
||||
var exit int
|
||||
if mode == "detach" {
|
||||
exit = chunkPlainDetachPost(srv.URL, "vol-a", time.Second, time.Time{}, map[string]any{"volumeID": "vol-a"}, &out, &diag)
|
||||
} else {
|
||||
exit = chunkObserveSnapshot(srv.URL, time.Second, map[string]any{"requestID": "original"}, false, &out, &diag)
|
||||
}
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || posts.Load() != 1 {
|
||||
t.Fatalf("exit=%d answer=%+v posts=%d polls=%d stderr=%s", exit, got, posts.Load(), gets.Load(), &diag)
|
||||
}
|
||||
if mode != "detach" && (!strings.Contains(got.Message, "original") || !strings.Contains(got.Message, "--request-id")) {
|
||||
t.Fatalf("original recovery lost: %+v", got)
|
||||
}
|
||||
wantGets := int32(0)
|
||||
if mode == "snapshot-poll" {
|
||||
wantGets = 1
|
||||
}
|
||||
if gets.Load() != wantGets {
|
||||
t.Fatalf("polls=%d want=%d", gets.Load(), wantGets)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
type inspectionShell struct {
|
||||
@@ -207,8 +208,9 @@ func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int {
|
||||
defer cancel()
|
||||
cluster, err := readMasterClusterEvidence(ctx, s.master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s: %v\n", name, err)
|
||||
return 1
|
||||
policy, detail := operatorAnswer(err, answer.Shell)
|
||||
fmt.Fprintf(stderr, "%s: %v\n", name, detail)
|
||||
return policy.Exit
|
||||
}
|
||||
var value any = cluster
|
||||
text := ops.RenderClusterEvidenceText(cluster)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -191,6 +192,11 @@ func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObse
|
||||
}
|
||||
o.filerErr = err
|
||||
}
|
||||
o.masterErr, o.lifecycleErr, o.filerErr = inspectionError(o.masterErr), inspectionError(o.lifecycleErr), inspectionError(o.filerErr)
|
||||
for i := range o.volumes {
|
||||
v := &o.volumes[i]
|
||||
v.leaseErr, v.holderErr, v.durableErr = inspectionError(v.leaseErr), inspectionError(v.holderErr), inspectionError(v.durableErr)
|
||||
}
|
||||
rows := make([]inspectionResult, 0, len(inspectionChecks))
|
||||
code := 0
|
||||
for _, c := range inspectionChecks {
|
||||
@@ -297,7 +303,7 @@ func (s inspectionShell) readHolderAt(ctx context.Context, addr, path, volume st
|
||||
return err
|
||||
}
|
||||
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("status redirects are refused") }}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := answer.DoHTTP(client, req, answer.Unsent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -44,9 +45,16 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
|
||||
}
|
||||
return 0
|
||||
}
|
||||
// Until a handle is validated, retain only the original admission identity.
|
||||
// An unsafe Location is never a recovery address and must not be followed.
|
||||
recovery := "retry with --request-id " + a.Answer.ID + " against the original status address"
|
||||
unobserved := func(err error) int {
|
||||
err = fmt.Errorf("snapshot operation %s: %s: %w", a.Answer.ID, recovery, err)
|
||||
return chunkResult("snapshot", nil, answer.Rekind(answer.Record(answer.PossiblyAdmitted, err), answer.Connection), stdout, stderr)
|
||||
}
|
||||
if a.Answer.State == "succeeded" {
|
||||
if len(a.Answer.Result) == 0 || !json.Valid(a.Answer.Result) {
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
|
||||
return unobserved(fmt.Errorf("operation has no result"))
|
||||
}
|
||||
if err := writeAll(stdout, a.Answer.Result); err != nil {
|
||||
return chunkExitFailed
|
||||
@@ -59,16 +67,19 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
|
||||
}
|
||||
origin, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeBadRequestCLI, err.Error(), false)
|
||||
return unobserved(fmt.Errorf("invalid original operation origin"))
|
||||
}
|
||||
loc, err := url.Parse(a.Location)
|
||||
if err != nil {
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid operation handle URI", false)
|
||||
return unobserved(fmt.Errorf("invalid operation handle URI"))
|
||||
}
|
||||
handle := origin.ResolveReference(loc)
|
||||
if handle.Scheme != origin.Scheme || handle.Host != origin.Host || handle.User != nil {
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation handle changed origin", false)
|
||||
return unobserved(fmt.Errorf("operation handle changed origin"))
|
||||
}
|
||||
recovery = "status at " + handle.String() + "; " + recovery
|
||||
// A failed handle read says nothing definite about the admitted POST.
|
||||
// Keep its identity and recovery contract even for a definite GET refusal.
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
for {
|
||||
@@ -76,32 +87,28 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
|
||||
req, err := http.NewRequestWithContext(callCtx, http.MethodGet, handle.String(), nil)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
|
||||
return unobserved(fmt.Errorf("invalid operation status request"))
|
||||
}
|
||||
resp, err := chunkHTTPClient.Do(req)
|
||||
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
|
||||
var current snapshotCLIAnswer
|
||||
if err == nil {
|
||||
err = json.NewDecoder(io.LimitReader(resp.Body, chunkResponseLimit+1)).Decode(¤t)
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
err = fmt.Errorf("operation status HTTP %d", resp.StatusCode)
|
||||
err = answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("operation status HTTP %d", resp.StatusCode))
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
if ctx.Err() != nil {
|
||||
fmt.Fprintf(stderr, "snapshot observation interrupted; resume with --request-id %s\n", a.Answer.ID)
|
||||
return chunkExitFailed
|
||||
}
|
||||
if err != nil {
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
|
||||
return unobserved(err)
|
||||
}
|
||||
if current.ID != a.Answer.ID {
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation status changed identity", false)
|
||||
return unobserved(fmt.Errorf("operation status changed identity"))
|
||||
}
|
||||
switch current.State {
|
||||
case "succeeded":
|
||||
if len(current.Result) == 0 || !json.Valid(current.Result) {
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
|
||||
return unobserved(fmt.Errorf("operation has no result"))
|
||||
}
|
||||
if err := writeAll(stdout, current.Result); err != nil {
|
||||
return chunkExitFailed
|
||||
@@ -117,7 +124,7 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, "no_progress", "snapshot stalled; repeat with --request-id "+a.Answer.ID, true)
|
||||
case "accepted", "running":
|
||||
default:
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "unknown operation state", false)
|
||||
return unobserved(fmt.Errorf("unknown operation state"))
|
||||
}
|
||||
timer := time.NewTimer(100 * time.Millisecond)
|
||||
select {
|
||||
@@ -125,7 +132,7 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
|
||||
if !timer.Stop() {
|
||||
<-timer.C
|
||||
}
|
||||
return chunkExitFailed
|
||||
return unobserved(ctx.Err())
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -22,11 +24,37 @@ func TestSnapshotOperationCLIObserverProcess(t *testing.T) {
|
||||
if os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_CHILD") != "1" {
|
||||
return
|
||||
}
|
||||
if os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_TLS") == "1" {
|
||||
chunkHTTPClient = &http.Client{Transport: interruptedSnapshotTLS{base: http.DefaultTransport}}
|
||||
}
|
||||
args := []string{"ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_URL"), "--name", "s1", "--timeout", "5s"}
|
||||
os.Exit(run(args, os.Stdout, os.Stderr))
|
||||
}
|
||||
|
||||
func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
|
||||
testSnapshotOperationCLIInterruptThenResume(t, false)
|
||||
}
|
||||
|
||||
func TestSnapshotOperationCLIInterruptedTLSKeepsUnknownAndHandle(t *testing.T) {
|
||||
testSnapshotOperationCLIInterruptThenResume(t, true)
|
||||
}
|
||||
|
||||
type interruptedSnapshotTLS struct{ base http.RoundTripper }
|
||||
|
||||
func (p interruptedSnapshotTLS) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
response, err := p.base.RoundTrip(r)
|
||||
if r.Method != http.MethodGet {
|
||||
return response, err
|
||||
}
|
||||
if response != nil {
|
||||
_ = response.Body.Close()
|
||||
}
|
||||
// The real GET has entered the server and is held until the parent's
|
||||
// SIGINT cancels its context. Deliver the certificate failure afterwards.
|
||||
return nil, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
|
||||
}
|
||||
|
||||
func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool) {
|
||||
var mu sync.Mutex
|
||||
var ids []string
|
||||
var pollIDs []string
|
||||
@@ -88,6 +116,9 @@ func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotOperationCLIObserverProcess$", "-test.timeout=7s")
|
||||
cmd.Env = append(os.Environ(), "SW_BLOCK_SNAPSHOT_OBSERVER_CHILD=1", "SW_BLOCK_SNAPSHOT_OBSERVER_URL="+srv.URL)
|
||||
if tlsFailure {
|
||||
cmd.Env = append(cmd.Env, "SW_BLOCK_SNAPSHOT_OBSERVER_TLS=1")
|
||||
}
|
||||
cmd.Stdout, cmd.Stderr = out, errs
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -113,8 +144,9 @@ func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
|
||||
if err := cmd.Process.Signal(os.Interrupt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var observerErr error
|
||||
select {
|
||||
case <-done:
|
||||
case observerErr = <-done:
|
||||
joined = true
|
||||
case <-ctx.Done():
|
||||
t.Fatal("interrupt did not stop the observer")
|
||||
@@ -128,6 +160,18 @@ func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
|
||||
t.Fatalf("one resumable printed ID required: %s", b)
|
||||
}
|
||||
id := printed[0][1]
|
||||
var exited *exec.ExitError
|
||||
if !errors.As(observerErr, &exited) || exited.ExitCode() != 3 {
|
||||
t.Fatalf("admitted interruption must remain unknown: exit=%v stderr=%s", observerErr, b)
|
||||
}
|
||||
result, err := os.ReadFile(out.Name())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer := chunkErrorOut(t, string(result))
|
||||
if answer.Code != "outcome_unknown" || !answer.Retryable || !strings.Contains(answer.Message, id) || !strings.Contains(answer.Message, srv.URL+"/operations/"+id) {
|
||||
t.Fatalf("admitted identity lost: %+v stderr=%s", answer, b)
|
||||
}
|
||||
code, stdout, stderr := runChunkWithin(t, 4*time.Second, "snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", id, "--timeout", "2s")
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type snapshotPollFailure struct {
|
||||
base http.RoundTripper
|
||||
mode string
|
||||
polls *atomic.Int32
|
||||
invalid *atomic.Bool
|
||||
}
|
||||
|
||||
func snapshotPollRequestError(r *http.Request) error {
|
||||
if r.Method == http.MethodPost {
|
||||
if r.URL.Path != "/chunk/snapshot" {
|
||||
return fmt.Errorf("wrong POST path: %s", r.URL.Path)
|
||||
}
|
||||
var body struct {
|
||||
ID string `json:"requestID"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
if body.ID != "original" {
|
||||
return fmt.Errorf("changed replay ID: %s", body.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if r.Method != http.MethodGet || r.URL.RequestURI() != "/operations/original" {
|
||||
return fmt.Errorf("wrong handle: %s %s", r.Method, r.URL.RequestURI())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p snapshotPollFailure) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
if r.Method != http.MethodGet {
|
||||
return p.base.RoundTrip(r)
|
||||
}
|
||||
p.polls.Add(1)
|
||||
if snapshotPollRequestError(r) != nil {
|
||||
p.invalid.Store(true)
|
||||
}
|
||||
if p.mode == "tls" {
|
||||
return nil, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
|
||||
}
|
||||
if p.mode == "body-tls" {
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: pollCertificateBody{}, Request: r}, nil
|
||||
}
|
||||
return p.base.RoundTrip(r)
|
||||
}
|
||||
|
||||
type pollCertificateBody struct{}
|
||||
|
||||
func (pollCertificateBody) Read([]byte) (int, error) {
|
||||
return 0, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
|
||||
}
|
||||
func (pollCertificateBody) Close() error { return nil }
|
||||
|
||||
// Each observer runs in an owned child: a polling regression cannot prevent
|
||||
// the parent from joining it, nor restore a client while it is still in use.
|
||||
func TestSnapshotAdmittedPollFailureKeepsOriginalOperation(t *testing.T) {
|
||||
for _, mode := range []string{"401", "403", "404", "409", "412", "428", "503", "tls", "body-tls", "success", "refused", "wrong-id"} {
|
||||
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=^TestSnapshotAdmittedPollChild$", "-test.count=1")
|
||||
cmd.Env = append(os.Environ(), "SWBLOCK_POLL_CONTROL="+mode)
|
||||
cmd.WaitDelay = time.Second
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("bounded observer: %v (context %v): %s", err, ctx.Err(), output)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotAdmittedPollChild(t *testing.T) {
|
||||
mode := os.Getenv("SWBLOCK_POLL_CONTROL")
|
||||
if mode == "" {
|
||||
t.Skip("owned child only")
|
||||
}
|
||||
var posts, polls atomic.Int32
|
||||
var invalid atomic.Bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := snapshotPollRequestError(r); err != nil {
|
||||
invalid.Store(true)
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
posts.Add(1)
|
||||
w.Header().Set("Location", "/operations/original")
|
||||
w.WriteHeader(202)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"operation_id": "original", "state": "running"})
|
||||
return
|
||||
}
|
||||
if mode == "success" || mode == "refused" || mode == "wrong-id" || mode == "loop" {
|
||||
id, state := "original", "succeeded"
|
||||
if mode == "wrong-id" {
|
||||
id = "changed"
|
||||
}
|
||||
if mode == "loop" {
|
||||
state = "running"
|
||||
fmt.Fprintln(os.Stderr, "poll-loop-entered")
|
||||
}
|
||||
if mode == "refused" {
|
||||
state = "refused"
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"operation_id": id, "state": state, "result": map[string]bool{"ok": true}, "code": "not_admitted", "message": "definite operation refusal"})
|
||||
return
|
||||
}
|
||||
code, err := strconv.Atoi(mode)
|
||||
if err != nil {
|
||||
http.Error(w, "unexpected mode", 500)
|
||||
return
|
||||
}
|
||||
http.Error(w, "status read refused", code)
|
||||
}))
|
||||
defer server.Close()
|
||||
previous := chunkHTTPClient
|
||||
defer func() { chunkHTTPClient = previous }()
|
||||
chunkHTTPClient = &http.Client{Transport: snapshotPollFailure{base: http.DefaultTransport, mode: mode, polls: &polls, invalid: &invalid}}
|
||||
var out, diag bytes.Buffer
|
||||
exit := chunkObserveSnapshot(server.URL, time.Second, map[string]any{"requestID": "original"}, false, &out, &diag)
|
||||
if posts.Load() != 1 || polls.Load() != 1 || invalid.Load() {
|
||||
t.Fatalf("wire proof: posts=%d polls=%d invalid=%v", posts.Load(), polls.Load(), invalid.Load())
|
||||
}
|
||||
if mode == "success" {
|
||||
if exit != 0 || !strings.Contains(out.String(), `"ok":true`) {
|
||||
t.Fatalf("terminal success: exit=%d out=%s", exit, out.String())
|
||||
}
|
||||
return
|
||||
}
|
||||
body := chunkErrorOut(t, out.String())
|
||||
if mode == "refused" {
|
||||
if exit != 1 || body.Code != "not_admitted" || body.Retryable {
|
||||
t.Fatalf("terminal refusal: exit=%d answer=%+v", exit, body)
|
||||
}
|
||||
return
|
||||
}
|
||||
if exit != 3 || body.Code != "outcome_unknown" || !body.Retryable || !strings.Contains(body.Message, "replay key") || !strings.Contains(body.Message, "original") || posts.Load() != 1 || polls.Load() != 1 || invalid.Load() {
|
||||
t.Fatalf("exit=%d answer=%+v posts=%d polls=%d invalid=%v", exit, body, posts.Load(), polls.Load(), invalid.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotPollWireControlRejectsChangedIdentityAndRoute(t *testing.T) {
|
||||
for _, row := range []struct{ method, path, body string }{
|
||||
{"POST", "/wrong", `{"requestID":"original"}`},
|
||||
{"POST", "/chunk/snapshot", `{"requestID":"changed"}`},
|
||||
{"GET", "/operations/changed", ""},
|
||||
} {
|
||||
req, _ := http.NewRequest(row.method, "http://example"+row.path, strings.NewReader(row.body))
|
||||
if err := snapshotPollRequestError(req); err == nil {
|
||||
t.Fatalf("wire control accepted %+v", row)
|
||||
}
|
||||
}
|
||||
for _, row := range []struct{ method, path, body string }{
|
||||
{"POST", "/chunk/snapshot", `{"requestID":"original"}`},
|
||||
{"GET", "/operations/original", ""},
|
||||
} {
|
||||
req, _ := http.NewRequest(row.method, "http://example"+row.path, strings.NewReader(row.body))
|
||||
if err := snapshotPollRequestError(req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _ io.ReadCloser = pollCertificateBody{}
|
||||
|
||||
// Negative control: an observer that never reaches a terminal state is killed
|
||||
// and joined before any parent-side fixtures can be reclaimed.
|
||||
func TestSnapshotPollWatchdogJoinsAnUnfinishedObserver(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotAdmittedPollChild$", "-test.count=1")
|
||||
cmd.Env = append(os.Environ(), "SWBLOCK_POLL_CONTROL=loop")
|
||||
cmd.WaitDelay = time.Second
|
||||
output, err := cmd.CombinedOutput()
|
||||
if ctx.Err() != context.DeadlineExceeded || err == nil || cmd.ProcessState == nil || !strings.Contains(string(output), "poll-loop-entered") {
|
||||
t.Fatalf("watchdog did not terminate and join: ctx=%v err=%v state=%v output=%s", ctx.Err(), err, cmd.ProcessState, output)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
// A whole-job command has stable derived operation identities. Preserve its
|
||||
// existing wire exit while obtaining its failure class and cure centrally.
|
||||
func operatorAnswer(err error, contract answer.Contract) (answer.Policy, error) {
|
||||
var presented *operatorFailure
|
||||
if errors.As(err, &presented) && presented.contract == contract {
|
||||
return presented.policy, err
|
||||
}
|
||||
observed := answer.EnsureEvidence(answer.PossiblyAdmitted, err)
|
||||
if _, listed := answer.ErrorKind(observed); !listed {
|
||||
// These callers have already checked a reply's identity/completeness
|
||||
// or lost their workflow's observation; this is not a transport guess.
|
||||
observed = answer.Rekind(observed, answer.Guard("outcome_unknown"))
|
||||
}
|
||||
policy, check := answer.PolicyOf(observed, contract)
|
||||
if check != nil {
|
||||
policy, _ = answer.Lookup(answer.Unsent, answer.Guard("internal"))
|
||||
return policy, fmt.Errorf("%w; %v", err, check)
|
||||
}
|
||||
if policy.Code == "outcome_unknown" {
|
||||
return policy, &operatorFailure{policy, contract, fmt.Errorf("the outcome is unknown (%w); %s", err, policy.Cure)}
|
||||
}
|
||||
return policy, &operatorFailure{policy, contract, fmt.Errorf("%s: %w; %s", policy.Code, err, policy.Cure)}
|
||||
}
|
||||
|
||||
type operatorFailure struct {
|
||||
policy answer.Policy
|
||||
contract answer.Contract
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *operatorFailure) Error() string { return e.err.Error() }
|
||||
func (e *operatorFailure) Unwrap() error { return e.err }
|
||||
|
||||
func inspectionError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if _, listed := answer.ErrorKind(err); !listed {
|
||||
return err
|
||||
} // explicit business finding, not a transport failure
|
||||
_, detail := operatorAnswer(err, answer.Shell)
|
||||
return detail
|
||||
}
|
||||
@@ -19,8 +19,8 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -130,8 +130,9 @@ func volumeBackup(ctx context.Context, env verbEnv, o backupOpts, stdout, stderr
|
||||
return refuse("snapshot", fmt.Sprintf("%s; a cut that timed out keeps what it uploaded; after correcting the refusal, run the same command (it resumes the same request and reuses completed uploads): %s", text, again))
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", err, again)
|
||||
return 1
|
||||
policy, detail := operatorAnswer(err, answer.VolumeJob)
|
||||
fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", detail, again)
|
||||
return policy.Exit
|
||||
}
|
||||
fmt.Fprintf(stdout, "sw-block volume backup: snapshot %s of %s: head generation %d, cut LSN %d, at %s\n",
|
||||
shQuote(a.Name), o.Volume, *a.HeadGen, *a.CutLSN, time.Unix(0, *a.CreatedNs).UTC().Format(time.RFC3339))
|
||||
@@ -163,8 +164,13 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
|
||||
client := *env.HTTP
|
||||
client.Timeout = timeout + 5*time.Second
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
unknown := func(why string) (snapshotAnswer, *snapshotRefusal, error) {
|
||||
return snapshotAnswer{}, nil, fmt.Errorf("the snapshot's outcome is unknown (%s)", why)
|
||||
unknown := func(why string, causes ...error) (snapshotAnswer, *snapshotRefusal, error) {
|
||||
cause := error(errors.New(why))
|
||||
if len(causes) == 1 {
|
||||
cause = fmt.Errorf("%s: %w", why, causes[0])
|
||||
}
|
||||
_, detail := operatorAnswer(cause, answer.VolumeJob)
|
||||
return snapshotAnswer{}, nil, detail
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
req, err := http.NewRequestWithContext(rctx, http.MethodPost, "http://"+status+"/chunk/snapshot", bytes.NewReader(body))
|
||||
@@ -174,16 +180,16 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Prefer", "respond-async")
|
||||
resp, err := client.Do(req)
|
||||
resp, err := answer.DoHTTP(&client, req, answer.Unsent)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return unknown(err.Error())
|
||||
return unknown("snapshot admission answer not received", err)
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
resp.Body.Close()
|
||||
cancel()
|
||||
if err != nil {
|
||||
return unknown("answer unreadable: " + err.Error())
|
||||
return unknown("snapshot answer unreadable", err)
|
||||
}
|
||||
if resp.StatusCode == http.StatusAccepted {
|
||||
var adm snapshotOperationIdentity
|
||||
@@ -191,7 +197,7 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
|
||||
return unknown("the admission answer does not identify this backup's operation")
|
||||
}
|
||||
if b, err = observeSnapshotOperation(ctx, env, client, status, adm, timeout); err != nil {
|
||||
return unknown(err.Error())
|
||||
return unknown("snapshot observation failed", err)
|
||||
}
|
||||
var op struct {
|
||||
State string `json:"state"`
|
||||
@@ -272,7 +278,7 @@ func observeSnapshotOperation(ctx context.Context, env verbEnv, client http.Clie
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := answer.DoHTTP(&client, req, answer.PossiblyAdmitted)
|
||||
var b []byte
|
||||
if err == nil {
|
||||
b, err = io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
@@ -402,8 +408,9 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
unknown := func(step string, err error) int {
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, err, ways)
|
||||
return 1
|
||||
policy, detail := operatorAnswer(err, answer.VolumeJob)
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, detail, ways)
|
||||
return policy.Exit
|
||||
}
|
||||
src, err := readEnvFile(filepath.Join(env.EtcDir, o.Source+".env"))
|
||||
if err != nil {
|
||||
@@ -425,10 +432,11 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
|
||||
resp, err := restoreCreateRPC(rctx, master, &control.CreateVolumeRequest{VolumeId: v.VolumeID, SourceVolume: o.Source, SourceSnapshot: o.Snapshot, CreateRequestId: id})
|
||||
cancel()
|
||||
if err != nil {
|
||||
if code := restoreRefusal(err); code != "" {
|
||||
return refuse("restore", code+": "+err.Error())
|
||||
if policy, detail := operatorAnswer(err, answer.VolumeJob); !policy.Retryable {
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: restore: %v\n", detail)
|
||||
return policy.Exit
|
||||
}
|
||||
return unknown("restore", fmt.Errorf("the outcome is unknown (%v)", err))
|
||||
return unknown("restore", err)
|
||||
}
|
||||
if resp.GetVolumeId() != v.VolumeID || !resp.GetStoreReady() {
|
||||
return unknown("restore", errors.New("the master did not confirm the new volume store-ready"))
|
||||
@@ -476,10 +484,10 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
|
||||
break
|
||||
}
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition, codes.InvalidArgument, codes.AlreadyExists, codes.PermissionDenied:
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: %s: refused: %v; the new volume exists but is not placed; to undo it: %s\n", step, err, abort)
|
||||
return ops.VolumeStatusExitInvalid
|
||||
policy, detail := operatorAnswer(err, answer.VolumePlacement)
|
||||
if policy.Retry == answer.Never && !policy.Retryable {
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: %s: refused: %v; the new volume exists but is not placed; to undo it: %s\n", step, detail, abort)
|
||||
return policy.Exit
|
||||
}
|
||||
return unknown(step, err)
|
||||
}
|
||||
@@ -631,25 +639,6 @@ var (
|
||||
runOpsRelease = chunkRelease
|
||||
)
|
||||
|
||||
// restoreRefusal maps a refused restore create to its JSON code (the codes
|
||||
// ops chunk restore reports); "" for an outcome a re-run may change.
|
||||
func restoreRefusal(err error) string {
|
||||
if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
|
||||
return "restore_source_not_own"
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.NotFound:
|
||||
return "snapshot_not_found"
|
||||
case codes.AlreadyExists:
|
||||
return "target_exists"
|
||||
case codes.InvalidArgument:
|
||||
return codeBadRequestCLI
|
||||
case codes.FailedPrecondition:
|
||||
return "not_admitted"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// restorePlaced reads the volume's published authority line at the master
|
||||
// (QueryVolumeStatus: the publisher's line itself, which exists before any
|
||||
// lease is granted on it) and its bindings (QueryWorkspace): placed when
|
||||
|
||||
@@ -28,17 +28,23 @@ import (
|
||||
|
||||
// --- fakes: the holder's snapshot route and the master's restore ---
|
||||
|
||||
type backupWireRequest struct {
|
||||
VolumeID, Name, RequestID string
|
||||
Labels map[string]string
|
||||
}
|
||||
|
||||
// snapHolder is the holder's POST /chunk/snapshot: one snapshot per name,
|
||||
// a replay of the same request id answers the same snapshot.
|
||||
type snapHolder struct {
|
||||
mu sync.Mutex
|
||||
snaps map[string]string // name -> its backup label ("" for a snapshot without one)
|
||||
posts int
|
||||
mode string // "", "lost" (taken, answer lost), "refuse", "unknown", "missing-<field>", "async" (runs two reads), "async-stalled", "async-gone" (handle lost), "async-silent" (reads fail), "async-foreign" (another operation answers), "sync" (no operations)
|
||||
srv *httptest.Server
|
||||
op map[string]any // the asynchronous operation's result
|
||||
opID string // its request id
|
||||
reads int // operation status reads
|
||||
lastRequest backupWireRequest
|
||||
mu sync.Mutex
|
||||
snaps map[string]string // name -> its backup label ("" for a snapshot without one)
|
||||
posts int
|
||||
mode string // "", "lost" (taken, answer lost), "refuse", "unknown", "missing-<field>", "async" (runs two reads), "async-stalled", "async-gone" (handle lost), "async-silent" (reads fail), "async-foreign" (another operation answers), "sync" (no operations)
|
||||
srv *httptest.Server
|
||||
op map[string]any // the asynchronous operation's result
|
||||
opID string // its request id
|
||||
reads int // operation status reads
|
||||
}
|
||||
|
||||
func newSnapHolder(t *testing.T) *snapHolder {
|
||||
@@ -79,14 +85,12 @@ func newSnapHolder(t *testing.T) *snapHolder {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
var q struct {
|
||||
VolumeID, Name, RequestID string
|
||||
Labels map[string]string
|
||||
}
|
||||
var q backupWireRequest
|
||||
_ = json.NewDecoder(r.Body).Decode(&q)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.posts++
|
||||
h.lastRequest = q
|
||||
switch h.mode {
|
||||
case "refuse":
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
@@ -386,7 +390,7 @@ func (m *restoreMaster) QueryVolumeStatus(_ context.Context, q *control.StatusRe
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func serveRestoreMaster(t *testing.T) (*restoreMaster, string) {
|
||||
func serveRestoreMaster(t *testing.T, options ...grpc.ServerOption) (*restoreMaster, string) {
|
||||
t.Helper()
|
||||
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
|
||||
t.Setenv(key, "")
|
||||
@@ -406,7 +410,7 @@ func serveRestoreMaster(t *testing.T) (*restoreMaster, string) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := grpc.NewServer()
|
||||
server := grpc.NewServer(options...)
|
||||
control.RegisterLifecycleServiceServer(server, m)
|
||||
control.RegisterWorkspaceServiceServer(server, m)
|
||||
control.RegisterEvidenceServiceServer(server, m)
|
||||
@@ -503,12 +507,12 @@ func restoreArgs(h *fakeHost) []string {
|
||||
|
||||
const abortCmd = "sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r --abort"
|
||||
|
||||
func restoreSetup(t *testing.T) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
|
||||
func restoreSetup(t *testing.T, options ...grpc.ServerOption) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
|
||||
h := newFakeHost(t)
|
||||
h.name = "vol-r"
|
||||
env := h.env(t)
|
||||
base := env.Systemctl
|
||||
m, master := serveRestoreMaster(t)
|
||||
m, master := serveRestoreMaster(t, options...)
|
||||
// Restore owns a separate RPC master; the source lease fixture is r3,
|
||||
// while the restore target is r9. Start must query the target master.
|
||||
oldQuery := releaseQuery
|
||||
@@ -590,6 +594,9 @@ func TestVolumeBackupInterruptedResumesWithTheSameCommand(t *testing.T) {
|
||||
}
|
||||
code, _, errs := runBackup(env, "vol-a", "--name", "nightly")
|
||||
wantCode := 1
|
||||
if c == "lost" || c == "unknown" {
|
||||
wantCode = 3
|
||||
}
|
||||
if c == "refuse" {
|
||||
wantCode = 2
|
||||
}
|
||||
@@ -617,7 +624,7 @@ func TestVolumeBackupIncompleteAnswerIsUnknown(t *testing.T) {
|
||||
sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), true)
|
||||
sh.setMode("missing-" + f)
|
||||
code, out, errs := runBackup(env, "vol-a", "--name", "n1")
|
||||
if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
|
||||
if code != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
|
||||
t.Fatalf("missing %s: %d %s %s", f, code, out, errs)
|
||||
}
|
||||
sh.setMode("")
|
||||
@@ -720,7 +727,11 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
|
||||
}
|
||||
m.failNext = r.fail
|
||||
code, _, errs := runRestore(env, restoreArgs(h)...)
|
||||
if code != 1 || !strings.Contains(errs, "to finish, run the same command: sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r") ||
|
||||
wantExit := 1
|
||||
if r.step == "restore" || r.step == "place" || r.fail != "" {
|
||||
wantExit = 3
|
||||
}
|
||||
if code != wantExit || !strings.Contains(errs, "to finish, run the same command: sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r") ||
|
||||
!strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
t.Fatalf("interrupted restore: %d\n%s", code, errs)
|
||||
}
|
||||
@@ -786,7 +797,7 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
|
||||
// After an abort the name is never created again: the master
|
||||
// refuses the deleting target, and the catalog's tombstone
|
||||
// refuses a target that never had HEAD (FailedPrecondition).
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
|
||||
t.Fatalf("restore after abort: %d %s", code, errs)
|
||||
}
|
||||
})
|
||||
@@ -822,7 +833,11 @@ func TestVolumeRestoreRefusals(t *testing.T) {
|
||||
{"no snapshot flag", []string{"vol-a", "--as", "vol-r"}, "--snapshot is required"},
|
||||
{"unknown source", append([]string{"vol-z"}, restoreArgs(h)[1:]...), "was vol-z started"},
|
||||
} {
|
||||
if code, _, errs := runRestore(env, c.args...); code != 2 || !strings.Contains(errs, c.want) {
|
||||
wantExit := 2
|
||||
if c.name == "missing snapshot" {
|
||||
wantExit = 1
|
||||
}
|
||||
if code, _, errs := runRestore(env, c.args...); code != wantExit || !strings.Contains(errs, c.want) {
|
||||
t.Errorf("%s: %d %s", c.name, code, errs)
|
||||
}
|
||||
}
|
||||
@@ -831,11 +846,11 @@ func TestVolumeRestoreRefusals(t *testing.T) {
|
||||
if raw, err := os.ReadFile(filepath.Join(env.EtcDir, "vol-a.env")); err != nil || os.WriteFile(sourceT, raw, 0o640) != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 2 || !strings.Contains(errs, "restore_source_not_own") {
|
||||
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 1 || !strings.Contains(errs, "restore_source_not_own") {
|
||||
t.Errorf("restore target as source: %d %s", code, errs)
|
||||
}
|
||||
m.vols["vol-r"] = &restoreRec{source: "vol-a", snap: "s1", req: "another", ready: true}
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "target_exists") {
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "target_exists") {
|
||||
t.Errorf("target of another request: %d %s", code, errs)
|
||||
}
|
||||
delete(m.vols, "vol-r")
|
||||
@@ -853,7 +868,7 @@ func TestVolumeRestoreRefusals(t *testing.T) {
|
||||
func TestVolumeRestoreRefusedPlacementNamesTheAbort(t *testing.T) {
|
||||
h, env, m, _ := restoreSetup(t)
|
||||
m.failNext = "bind-refuse"
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
t.Fatalf("refused placement: %d %s", code, errs)
|
||||
}
|
||||
if h.called("enable") != 0 {
|
||||
@@ -994,7 +1009,7 @@ func TestVolumeRestorePublicationDuringThePlacement(t *testing.T) {
|
||||
h3, env3, m3, _ := restoreSetup(t)
|
||||
m3.failNext = "publish-race-reread-fails"
|
||||
code, _, errs = runRestore(env3, restoreArgs(h3)...)
|
||||
if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
|
||||
if code != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
|
||||
t.Fatalf("failed re-read: %d %s", code, errs)
|
||||
}
|
||||
if code, _, errs := runRestore(env3, restoreArgs(h3)...); code != 0 {
|
||||
@@ -1066,7 +1081,7 @@ func TestVolumeRestoreRefusesAMalformedLayoutAnswer(t *testing.T) {
|
||||
h, env, m, _ := restoreSetup(t)
|
||||
m.failNext = "create-badlayout"
|
||||
code, _, errs := runRestore(env, restoreArgs(h)...)
|
||||
if code != 1 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
if code != 3 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
t.Fatalf("malformed layout answer: %d %s", code, errs)
|
||||
}
|
||||
if m.binds != 0 || h.called("enable") != 0 {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -53,20 +54,25 @@ func runOpsVolumeCreate(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
conn, err := link.DialMasterFromEnv(*master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", err)
|
||||
return 2
|
||||
policy, detail := operatorAnswer(err, answer.VolumeCreate)
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", detail)
|
||||
return policy.Exit
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
fail := func(step string, err error) int {
|
||||
code, outcome := 78, "refused"
|
||||
switch status.Code(err) {
|
||||
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss:
|
||||
code, outcome = 75, "unknown"
|
||||
policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.VolumeCreate)
|
||||
if check != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: %s: %v\n", step, check)
|
||||
return 75
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; earlier steps may remain recorded; retry the identical name, geometry and placement\n", step, outcome, err)
|
||||
return code
|
||||
outcome := "refused"
|
||||
if policy.Retryable {
|
||||
outcome = "unknown"
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; %s\n", step, outcome, err, policy.Cure)
|
||||
return policy.Exit
|
||||
}
|
||||
q := &control.CreateVolumeRequest{VolumeId: binding.VolumeId, SizeBytes: *size, ReplicationFactor: 1, Protocol: *protocol, FrontendTransport: *transport, BlockSize: geometry.BlockSize, ChunkBytes: geometry.ChunkBytes}
|
||||
v, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, q)
|
||||
|
||||
@@ -8,8 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
// runOpsVolume exposes the same master name binding used by ops chunk.
|
||||
@@ -38,15 +37,11 @@ func runOpsVolume(args []string, stdout, stderr io.Writer) int {
|
||||
defer cancel()
|
||||
id, err := resolveVolumeID(ctx, *master, fs.Arg(0))
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v\n", err)
|
||||
// Match blockvolume: an unavailable or unknown master answer is retryable;
|
||||
// a definite refusal or invalid local configuration needs correction.
|
||||
if s, ok := status.FromError(err); ok {
|
||||
switch s.Code() {
|
||||
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal:
|
||||
return 75
|
||||
}
|
||||
if policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.VolumeResolve); check == nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v; %s\n", err, policy.Cure)
|
||||
return policy.Exit
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v\n", err)
|
||||
return 78
|
||||
}
|
||||
fmt.Fprintln(stdout, id.String())
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"io"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
|
||||
)
|
||||
|
||||
const unknownStartOwnerCost = "The master could not prove the current authority holder. START refuses rather than guessing from issued moves, ACKs or prepared bindings. An operator who independently knows the correct host can use the force-move operation's --target-host option; START cannot choose or print that target."
|
||||
@@ -73,13 +72,13 @@ func prepareVolumeStart(ctx context.Context, v volumeSpec, stdout, stderr io.Wri
|
||||
client, err := workspaceDial(v.Master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "sw-block volume start: volume_start_move_not_sent: %v\n", err)
|
||||
return 1
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
defer client.Close()
|
||||
grant, err := client.CleanMove(setup, q)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "sw-block volume start: volume_start_move: %v; rerun the same volume start (request %s)\n", err, q.RequestId)
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
if grant.GetNewEpoch() != epoch+1 || grant.GetOldHost() != v.ServerID {
|
||||
fmt.Fprintln(stderr, "sw-block volume start: volume_start_move_outcome_unknown: grant is not epoch+1; the unit was not started")
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
// The whole-job volume commands: each runs on the volume's host, prints
|
||||
@@ -386,7 +387,7 @@ func getJSON(ctx context.Context, env verbEnv, url string, into any) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := env.HTTP.Do(req)
|
||||
resp, err := answer.DoHTTP(env.HTTP, req, answer.Unsent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -633,20 +634,32 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
|
||||
payload["deadlineNs"] = deadline.UnixNano()
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
unknown := func(why string) (cutAnswer, error) {
|
||||
return cutAnswer{}, fmt.Errorf("the cut's outcome is unknown (%s): it may have published", why)
|
||||
id := ""
|
||||
unknown := func(why string, causes ...error) (cutAnswer, error) {
|
||||
if id != "" {
|
||||
why = "cut id " + id + ": " + why
|
||||
}
|
||||
cause := error(errors.New(why))
|
||||
if len(causes) == 1 {
|
||||
cause = fmt.Errorf("%s: %w", why, causes[0])
|
||||
}
|
||||
policy, detail := operatorAnswer(cause, answer.VolumeStop)
|
||||
if policy.Retry == answer.Recover {
|
||||
detail = fmt.Errorf("%w: it may have published", detail)
|
||||
}
|
||||
return cutAnswer{}, detail
|
||||
}
|
||||
client := *env.HTTP
|
||||
client.Timeout = timeout + slack
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
id, seen, last := "", uint64(0), time.Now()
|
||||
seen, last := uint64(0), time.Now()
|
||||
for {
|
||||
until := last.Add(timeout + slack)
|
||||
if !deadline.IsZero() && deadline.Before(until) {
|
||||
until = deadline
|
||||
}
|
||||
if !time.Now().Before(until) {
|
||||
return unknown("no progress within the window, or the deadline passed; cut id " + id)
|
||||
return unknown("no progress within the window, or the deadline passed")
|
||||
}
|
||||
method, url := http.MethodPost, "http://"+status+"/chunk/cut"
|
||||
var reqBody io.Reader = bytes.NewReader(body)
|
||||
@@ -662,11 +675,15 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
|
||||
if method == http.MethodPost {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
phase := answer.Unsent
|
||||
if id != "" {
|
||||
phase = answer.PossiblyAdmitted
|
||||
}
|
||||
resp, err := answer.DoHTTP(&client, req, phase)
|
||||
if err != nil {
|
||||
cancel()
|
||||
if id == "" {
|
||||
return unknown(err.Error())
|
||||
return unknown("cut admission answer not received", err)
|
||||
}
|
||||
time.Sleep(min(env.Poll, time.Until(until)))
|
||||
continue
|
||||
@@ -675,7 +692,7 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
|
||||
resp.Body.Close()
|
||||
cancel()
|
||||
if err != nil {
|
||||
return unknown("answer unreadable: " + err.Error())
|
||||
return unknown("cut answer unreadable", err)
|
||||
}
|
||||
// Every answer speaks this CLI's integer cut API version (this
|
||||
// CLI's or the one before). Only the first answer may lack it, as a
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
|
||||
)
|
||||
@@ -67,12 +68,12 @@ lost-range prints the stored lost ranges of the volume's issued forced moves, in
|
||||
issue order (all of them, or the one of --request-id). It never prints "no loss"
|
||||
for a forced move whose record is missing or fails its checks.
|
||||
|
||||
exit: 0 done; 1 refused by the master (nothing moved); 2 refused locally (usage
|
||||
or confirmation; nothing sent); 3 outcome unknown: rerun with the SAME
|
||||
--request-id; 4 the move is issued but its lost range is not proven (or a
|
||||
stored range is unreadable); 5 not authorized by blockmaster (no client
|
||||
certificate where it requires mutual TLS, or a certificate or role its role
|
||||
file does not admit; set SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY, SW_BLOCK_TLS_CA).
|
||||
exit: 0 done; 1 definite refusal or caller cancellation/deadline before send;
|
||||
2 local usage/confirmation or server argument refusal; 3 outcome unknown:
|
||||
rerun with the SAME --request-id; 4 unproven lost-range readout; 5 certificate
|
||||
or role rejection; 75 proven unsent remote failure; 78 local credential or
|
||||
configuration error. Set SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and SW_BLOCK_TLS_CA
|
||||
for a master that requires mutual TLS.
|
||||
`
|
||||
|
||||
// workspaceDial is swapped by tests.
|
||||
@@ -105,20 +106,16 @@ func runOpsWorkspace(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
}
|
||||
|
||||
func workspaceExit(o wsclient.Outcome) int {
|
||||
switch o {
|
||||
case wsclient.OutcomeOK:
|
||||
// Render the shared projection without a second outcome-to-exit table.
|
||||
func workspaceErrorExit(err error) int {
|
||||
if err == nil {
|
||||
return wsExitOK
|
||||
case wsclient.OutcomeRefusedLocally:
|
||||
return wsExitRefusedLocally
|
||||
case wsclient.OutcomeRefused:
|
||||
return wsExitRefused
|
||||
case wsclient.OutcomeReadoutUnproven:
|
||||
return wsExitReadoutUnproven
|
||||
case wsclient.OutcomeNotAuthorized:
|
||||
return wsExitNotAuthorized
|
||||
}
|
||||
return wsExitUnknown
|
||||
if code, ok := wsclient.ExitOf(err); ok {
|
||||
return code
|
||||
}
|
||||
policy, _ := operatorAnswer(err, answer.Workspace)
|
||||
return policy.Exit
|
||||
}
|
||||
|
||||
// workspaceForceMoveAnswer is output only; admission and exit policy stay in
|
||||
@@ -199,7 +196,7 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int {
|
||||
c, err := workspaceDial(master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s: refused locally, nothing sent: master address: %v\n", workspaceForceMoveName, err)
|
||||
return wsExitRefusedLocally
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
defer c.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
@@ -239,14 +236,17 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int {
|
||||
answer.Until = wsclient.FormatTime(at.UnixNano())
|
||||
fmt.Fprintf(stderr, "%s: admissible at %s, master clock (the lease horizon plus clock skew); wait, there is no bypass\n", workspaceForceMoveName, wsclient.FormatTime(at.UnixNano()))
|
||||
}
|
||||
return wsExitRefused
|
||||
return workspaceErrorExit(err)
|
||||
case wsclient.OutcomeUnsent:
|
||||
fmt.Fprintf(stderr, "%s: nothing sent: %v\n", workspaceForceMoveName, err)
|
||||
return workspaceErrorExit(err)
|
||||
case wsclient.OutcomeUnknown:
|
||||
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
|
||||
fmt.Fprintf(stderr, "%s: outcome unknown: rerun with the SAME --request-id %s\n", workspaceForceMoveName, m.RequestID)
|
||||
return wsExitUnknown
|
||||
default:
|
||||
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
|
||||
return workspaceExit(o)
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +287,7 @@ func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.Forced
|
||||
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
|
||||
fmt.Fprintf(stderr, "%s --dry-run: the preview failed; nothing was written\n", workspaceForceMoveName)
|
||||
}
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
if answer != nil {
|
||||
answer.Admitted, answer.Code = p.GetAdmitted(), p.GetCode()
|
||||
@@ -350,7 +350,7 @@ func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int {
|
||||
c, err := workspaceDial(master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s: master address: %v\n", workspaceLostRangeName, err)
|
||||
return wsExitRefusedLocally
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
defer c.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
@@ -361,7 +361,7 @@ func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int {
|
||||
if wsclient.OutcomeOf(err) == wsclient.OutcomeReadoutUnproven {
|
||||
fmt.Fprintf(stderr, "%s: a forced move's lost range is missing or unreadable: the readout is NOT proven; do not assume no loss\n", workspaceLostRangeName)
|
||||
}
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
if len(ranges) == 0 {
|
||||
fmt.Fprintf(stdout, "volume %s has no issued forced move\n", volume)
|
||||
|
||||
@@ -54,7 +54,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int {
|
||||
c, err := workspaceDial(master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "workspace move: refused locally, nothing sent: %v\n", err)
|
||||
return wsExitRefusedLocally
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
defer c.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
@@ -66,7 +66,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int {
|
||||
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
|
||||
fmt.Fprintf(stderr, "workspace move: outcome unknown; rerun with the SAME --request-id %s\n", q.RequestId)
|
||||
}
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
answer.Issued, answer.MoveID, answer.NewHost, answer.NewReplica = true, g.GetRequestId(), g.GetNewHost(), g.GetNewReplicaId()
|
||||
epoch := g.GetNewEpoch()
|
||||
|
||||
@@ -44,7 +44,7 @@ func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int {
|
||||
c, err := workspaceDial(master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "workspace revoke: refused locally, nothing sent: %v\n", err)
|
||||
return wsExitRefusedLocally
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
defer c.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
@@ -55,7 +55,7 @@ func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int {
|
||||
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
|
||||
fmt.Fprintln(stderr, "workspace revoke: outcome unknown; inspect workspace show before proceeding")
|
||||
}
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
fmt.Fprintf(stdout, "revocation requested: volume %s holder %s@%d expiry_ns %d\n", id.VolumeId, id.ReplicaId, id.Epoch, lease.GetExpiresAtNs())
|
||||
if withoutSeal {
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
|
||||
)
|
||||
|
||||
// Read-only M2 Granted -> Revoking -> Acked -> Moved (clean) facts,
|
||||
@@ -31,7 +30,7 @@ func runWorkspaceShow(args []string, stdout, stderr io.Writer) int {
|
||||
c, err := workspaceDial(master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "workspace show: refused locally, nothing sent: %v\n", err)
|
||||
return wsExitRefusedLocally
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
defer c.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
@@ -39,7 +38,7 @@ func runWorkspaceShow(args []string, stdout, stderr io.Writer) int {
|
||||
view, err := c.Show(ctx, volume)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "workspace show: %v\n", err)
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
return workspaceErrorExit(err)
|
||||
}
|
||||
printWorkspaceView(stdout, volume, view)
|
||||
return wsExitOK
|
||||
|
||||
@@ -453,3 +453,48 @@ func TestWorkspaceHelpText(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A master that never answers leaves the call unsent when the caller's
|
||||
// deadline passes: nothing was refused, and no admission preview is read.
|
||||
func TestWorkspaceForceMoveUnsentCallerDeadlineIsNotARefusal(t *testing.T) {
|
||||
silent, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held := make(chan net.Conn, 16)
|
||||
go func() {
|
||||
for {
|
||||
conn, err := silent.Accept()
|
||||
if err != nil {
|
||||
close(held)
|
||||
return
|
||||
}
|
||||
held <- conn
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
silent.Close()
|
||||
for conn := range held {
|
||||
conn.Close()
|
||||
}
|
||||
})
|
||||
code, out, errOut := runCLI(forceMoveArgs(silent.Addr().String(), "--confirm-forced", "vol@3", "--timeout", "300ms"))
|
||||
if code != wsExitRefused || out != "" || strings.Contains(errOut, "refused by the master") || !strings.Contains(errOut, "nothing sent") {
|
||||
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
// A master that refuses the connection proves the move unsent: exit 75 and
|
||||
// "nothing sent", never the unknown outcome's rerun advice.
|
||||
func TestWorkspaceForceMoveRefusedConnectionIsUnsent(t *testing.T) {
|
||||
closed, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := closed.Addr().String()
|
||||
closed.Close()
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--timeout", "2s"))
|
||||
if code != 75 || out != "" || !strings.Contains(errOut, "nothing sent") || strings.Contains(errOut, "outcome unknown") {
|
||||
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,9 @@ 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 the fail-stop after a
|
||||
// record's rename whose durability is unknown (sysexits EX_IOERR).
|
||||
// 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.
|
||||
const ExitDurabilityUnknown = 74
|
||||
|
||||
// failStopDurabilityUnknown ends the process: the rename is done but the
|
||||
|
||||
@@ -32,6 +32,7 @@ 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
|
||||
}
|
||||
|
||||
@@ -44,10 +45,21 @@ 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.
|
||||
@@ -125,6 +137,21 @@ 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).
|
||||
@@ -163,6 +190,7 @@ 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)
|
||||
@@ -180,6 +208,7 @@ 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.
|
||||
@@ -196,6 +225,17 @@ 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
|
||||
}
|
||||
|
||||
@@ -252,11 +292,13 @@ 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
|
||||
}
|
||||
|
||||
@@ -269,24 +311,44 @@ 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: 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.
|
||||
// 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.
|
||||
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
|
||||
}
|
||||
|
||||
@@ -308,6 +370,7 @@ 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)
|
||||
}
|
||||
|
||||
@@ -472,7 +535,7 @@ func (c *TopologyController) decideVolume(
|
||||
if !hasLine {
|
||||
cands := placeableCandidates(vol, serverIndex)
|
||||
if len(cands) == 0 {
|
||||
return AssignmentAsk{}, "", false
|
||||
return AssignmentAsk{}, "no placeable candidate for the first line", false
|
||||
}
|
||||
best := choosePlacementCandidate(cands, projectedLoad)
|
||||
return AssignmentAsk{
|
||||
@@ -487,7 +550,7 @@ func (c *TopologyController) decideVolume(
|
||||
|
||||
current, ok := candidateByReplica(vol, currentLine.ReplicaID)
|
||||
if !ok {
|
||||
return AssignmentAsk{}, "", false
|
||||
return AssignmentAsk{}, "the line's replica is not in the snapshot", false
|
||||
}
|
||||
|
||||
if candidateAcceptable(current, serverIndex) {
|
||||
@@ -500,19 +563,20 @@ 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{}, "", false
|
||||
return AssignmentAsk{}, "the current primary is acceptable; rebalance target " + target.ReplicaID + " has no planned-move evidence", false
|
||||
}
|
||||
return AssignmentAsk{
|
||||
VolumeID: vol.VolumeID,
|
||||
ReplicaID: target.ReplicaID,
|
||||
DataAddr: target.DataAddr,
|
||||
CtrlAddr: target.CtrlAddr,
|
||||
Intent: IntentReassign,
|
||||
Evidence: plannedEvidence(target.PromotionEvidence),
|
||||
Incarnation: target.Incarnation,
|
||||
VolumeID: vol.VolumeID,
|
||||
ReplicaID: target.ReplicaID,
|
||||
DataAddr: target.DataAddr,
|
||||
CtrlAddr: target.CtrlAddr,
|
||||
Intent: IntentReassign,
|
||||
Evidence: plannedEvidence(target.PromotionEvidence),
|
||||
Incarnation: target.Incarnation,
|
||||
ExpectCurrent: expectedLineOf(currentLine),
|
||||
}, "rebalance", true
|
||||
}
|
||||
return AssignmentAsk{}, "", false
|
||||
return AssignmentAsk{}, "the current primary is acceptable", false
|
||||
}
|
||||
|
||||
// A restarted current primary that is placeable but not ready yet
|
||||
@@ -522,9 +586,13 @@ func (c *TopologyController) decideVolume(
|
||||
if !superseded && endpointStale(current, currentLine) {
|
||||
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh (primary boot grace)", true
|
||||
}
|
||||
return AssignmentAsk{}, "", false
|
||||
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
|
||||
}
|
||||
|
||||
why := "no acceptable candidate besides the current primary"
|
||||
other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID)
|
||||
if len(other) > 0 {
|
||||
best := chooseFailoverCandidate(other, projectedLoad)
|
||||
@@ -532,15 +600,17 @@ 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,
|
||||
VolumeID: vol.VolumeID,
|
||||
ReplicaID: best.ReplicaID,
|
||||
DataAddr: best.DataAddr,
|
||||
CtrlAddr: best.CtrlAddr,
|
||||
Intent: IntentReassign,
|
||||
Evidence: best.PromotionEvidence,
|
||||
Incarnation: best.Incarnation,
|
||||
ExpectCurrent: expectedLineOf(currentLine),
|
||||
}, "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
|
||||
@@ -548,7 +618,7 @@ func (c *TopologyController) decideVolume(
|
||||
if candidatePlaceable(current, serverIndex) && endpointStale(current, currentLine) {
|
||||
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh", true
|
||||
}
|
||||
return AssignmentAsk{}, "", false
|
||||
return AssignmentAsk{}, why, false
|
||||
}
|
||||
|
||||
// endpointStale reports whether the current primary's line needs a new
|
||||
@@ -571,10 +641,17 @@ func refreshAsk(volumeID string, current ReplicaCandidate, line AuthorityBasis)
|
||||
CtrlAddr: current.CtrlAddr,
|
||||
Intent: IntentRefreshEndpoint,
|
||||
Incarnation: current.Incarnation,
|
||||
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr},
|
||||
ExpectCurrent: expectedLineOf(line),
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
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,6 +106,35 @@ 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.now())
|
||||
d := at.Sub(h.store.clock())
|
||||
if d < 10*time.Millisecond {
|
||||
d = 10 * time.Millisecond
|
||||
}
|
||||
|
||||
@@ -285,6 +285,14 @@ 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,6 +14,10 @@ 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 {
|
||||
@@ -42,7 +46,19 @@ 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 {
|
||||
@@ -54,6 +70,7 @@ func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
|
||||
continue
|
||||
}
|
||||
delete(q.items, vid)
|
||||
q.taken = vid
|
||||
q.mu.Unlock()
|
||||
return ask, nil
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -97,7 +98,7 @@ func (r *InClusterPVCMetadataResolver) ResolvePVCUID(ctx context.Context, name,
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+r.token)
|
||||
resp, err := r.client.Do(req)
|
||||
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -150,7 +151,7 @@ func (r *InClusterSwBlockVolumeRegistrar) EnsureVolumeObject(ctx context.Context
|
||||
return err
|
||||
}
|
||||
r.setJSONHeaders(req)
|
||||
resp, err := r.client.Do(req)
|
||||
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -177,7 +178,7 @@ func (r *InClusterSwBlockVolumeRegistrar) patchVolumeSpec(ctx context.Context, n
|
||||
}
|
||||
r.setJSONHeaders(req)
|
||||
req.Header.Set("Content-Type", "application/merge-patch+json")
|
||||
resp, err := r.client.Do(req)
|
||||
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ 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.
|
||||
@@ -49,9 +52,29 @@ 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 {
|
||||
@@ -343,6 +366,12 @@ 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.
|
||||
@@ -358,7 +387,7 @@ func (c *BCatalog) Usage(ctx context.Context, v VolumeRef) (Usage, error) {
|
||||
if !found {
|
||||
return Usage{}, layout.ErrHeadAbsent
|
||||
}
|
||||
u := Usage{Snapshots: len(h.Snapshots)}
|
||||
u := Usage{Snapshots: len(h.Snapshots), MetadataGuard: c.MetadataGuard()}
|
||||
for _, sn := range h.Snapshots {
|
||||
u.Dependents += len(sn.Dependents)
|
||||
}
|
||||
|
||||
Loaded 100 of 375 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user