mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 19:17:28 +01:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71f5b6f440 | ||
|
|
ca22f937b5 | ||
|
|
4eb8b2a2fa | ||
|
|
799c5c1130 | ||
|
|
5ae2b8a56c |
No files matched your search
@@ -1,41 +0,0 @@
|
||||
# Block CI in the shared repository
|
||||
|
||||
The block module stays in `seaweed-block/` with its own `go.mod` and unchanged module path. Root `block-*.yml` workflows run shell commands there; action inputs name the subdirectory explicitly. The imported subtree is unchanged: every port file lives under root `.github/`. Existing module scripts and data remain base-owned inputs; only the Git adapters, unit-group coordinator and relative documentation link check live in root `.github/block/scripts/`. The existing nested workflows are inert because GitHub only discovers root workflows.
|
||||
|
||||
PR and master-push workflows select `seaweed-block/**` and their root block workflow files. All jobs default to `ubuntu-latest`. Set the repository variable `BLOCK_RUNNER_LABEL` only after the corresponding dedicated runner label is registered and available; same-repository/trusted events of the test, spec-trace and known-bugs jobs then use that label. The post-merge-review paths check and the release always run hosted. Fork PRs always use GitHub-hosted runners. GitHub Actions cannot fall back after requesting an unavailable label, so an unset variable is the explicit safe default. Unset it again if the registered pool is withdrawn. Runner discovery would require runner-management API access that the read-only workflow token does not have; no new credential is requested.
|
||||
|
||||
The unit check keeps `go test (linux)` and `process-level tests (real binaries)` under workflow `Block Test`. Module-relative diff/blob adapters preserve the block model map and allow list. Root block workflow/Docker recipe changes still pass the block trace/public-text checks; unrelated host code is excluded. No imported module paths or product formats change.
|
||||
|
||||
## Read-only merge checks
|
||||
|
||||
From a trusted current master checkout, run inside the module:
|
||||
|
||||
```sh
|
||||
python3 ../.github/block/scripts/safe-merge-check.py 123
|
||||
```
|
||||
|
||||
It requires an open, ready, mergeable PR, the latest successful `Block Test` run at its exact head against current master, both successful named jobs, and the base-owned spec-trace/public-text checks. It rechecks head/base after inspection. It never merges or comments. The manager performs the authorized squash merge with `--match-head-commit`.
|
||||
|
||||
For a batch, preserve its builder's exact order in a local manifest:
|
||||
|
||||
```json
|
||||
{"base":"BASE_SHA","batch_pr":123,"head":"BATCH_SHA","prs":[{"number":121,"head":"HEAD_121","evidence":"evidence/121.txt"},{"number":122,"head":"HEAD_122","evidence":"evidence/122.txt"}]}
|
||||
```
|
||||
|
||||
```sh
|
||||
python3 ../.github/block/scripts/safe-merge-check.py --batch batch.json
|
||||
# After the authorized ordered squash merges, compare master with the printed tested tree:
|
||||
python3 ../.github/block/scripts/safe-merge-check.py --verify-tree TESTED_TREE_SHA
|
||||
```
|
||||
|
||||
The manifest and acceptance files are operator inputs from the batch builder, never files supplied by a PR. Batch readiness refuses a moved master/head, changed order or missing evidence and runs each member's base-owned local checks. Building/pushing a batch and merging remain manager operations.
|
||||
|
||||
## Releases
|
||||
|
||||
Only `seaweed-block/vX.Y.Z[-pre]` tags publish. Image tags omit the namespace and retain the existing block/CSI image names. Only block stable tags decide whether `alpha` advances. Root-context Docker recipes preserve Git revision metadata while building the nested module and retain the lab-binary refusal.
|
||||
|
||||
The Linux amd64 tarball contains `blockmaster`, `blockvolume` and `sw-block` copied from the exact published image digest, with `SHA256SUMS`. The GitHub release uses the namespaced tag and does not replace the shared repository's latest release. Release notes must already exist in the module. No tag, image or release is created by preparation or local tests.
|
||||
|
||||
## Move-window checks
|
||||
|
||||
This revision targets the v1.1.0 import branch. Do not edit files under `seaweed-block/` here; development stays in its source repository until the v1.1.1 history update. The root unit-group helpers project the qualified #1001 source; refresh root CI adapters against the corresponding source when that later import arrives. Run the normal Test workflow, base-owned checks and a controlled nonproduction release rehearsal before enabling real publication. Validate organization runner registration, Docker, GHCR package access, and existing repository rulesets/check names. Existing host workflows are unchanged; their broad Go filters may also select a block-only PR. The first import needs its own reviewed bootstrap evidence: a pre-import master has no block scripts, so neither the new pull_request_target gates nor the base-owned local checker can qualify that initial import from an absent base module. Once the import/port is on the trusted base, subsequent block PRs use these checks.
|
||||
@@ -1,408 +0,0 @@
|
||||
"""Local-only checks for the nested-module CI port; no Go suites or publishing."""
|
||||
from pathlib import Path
|
||||
import copy
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[2]
|
||||
|
||||
|
||||
class PortTests(unittest.TestCase):
|
||||
def test_relative_documentation_links_are_checked(self):
|
||||
text = (ROOT / ".github/workflows/block-test.yml").read_text()
|
||||
marker = " - name: Relative documentation links\n"
|
||||
self.assertEqual(text.count(marker), 1)
|
||||
step = text.split(marker, 1)[1].split("\n - name:", 1)[0]
|
||||
self.assertIn("if: matrix.suite == 'unit'", step)
|
||||
self.assertIn("python3 -B ../.github/block/scripts/doc-links-check-test.py", step)
|
||||
self.assertIn("python3 -I ../.github/block/scripts/doc-links-check.py .", step)
|
||||
self.assertNotIn("continue-on-error", step)
|
||||
self.assertNotIn("|| true", step)
|
||||
|
||||
def test_root_workflows_use_module_run_and_action_paths(self):
|
||||
for name in ("test", "spec-trace", "post-merge-review", "known-bugs"):
|
||||
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
|
||||
self.assertIn("working-directory: seaweed-block", text)
|
||||
if name == "post-merge-review":
|
||||
self.assertIn("runs-on: ubuntu-latest", text)
|
||||
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
|
||||
else:
|
||||
self.assertIn("vars.BLOCK_RUNNER_LABEL", text)
|
||||
self.assertIn("|| 'ubuntu-latest'", text)
|
||||
if "go-version-file:" in text: self.assertIn("go-version-file: seaweed-block/go.mod", text)
|
||||
if name != "known-bugs":
|
||||
self.assertIn('"seaweed-block/**"', text)
|
||||
self.assertIn('".github/workflows/block-*.yml"', text)
|
||||
test = (ROOT / ".github/workflows/block-test.yml").read_text()
|
||||
self.assertIn("- master", test)
|
||||
self.assertIn("git diff --relative --name-only --no-renames HEAD^1 HEAD -- .", test)
|
||||
self.assertIn("go test (linux)", test)
|
||||
self.assertIn("process-level tests (real binaries)", test)
|
||||
scope = test.split(" - name: Docs-only pull request\n", 1)[1].split("\n", 2)[1]
|
||||
self.assertEqual(scope.strip(), "if: matrix.suite == 'process' && github.event_name == 'pull_request'")
|
||||
self.assertEqual(test.count("if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'"), 5)
|
||||
self.assertNotRegex(test, r"if: matrix\.suite == 'process'\s*\n")
|
||||
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
|
||||
self.assertIn("working-directory: ${{ github.workspace }}", post)
|
||||
|
||||
def test_labelled_post_merge_review_refuses_host_files(self):
|
||||
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
|
||||
step = post.split(" - name: Check changed paths\n", 1)[1].split(" run: |\n", 1)[1].split("\n\n - name:", 1)[0]
|
||||
script = "\n".join(line[10:] for line in step.splitlines())
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); module = root / "seaweed-block"
|
||||
def git(*args): return subprocess.check_output(["git", *args], cwd=root, timeout=15)
|
||||
git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false")
|
||||
for name in ("post-merge-review-check.sh", "post-merge-review-allow.txt"):
|
||||
source = ROOT / "seaweed-block/.github" / ("scripts/" + name if name.endswith(".sh") else name)
|
||||
target = module / ".github" / ("scripts/" + name if name.endswith(".sh") else name)
|
||||
target.parent.mkdir(parents=True, exist_ok=True); target.write_bytes(source.read_bytes())
|
||||
(module / ".github/scripts/post-merge-review-check-test.sh").write_text("exit 0\n")
|
||||
(root / ".github/block/scripts").mkdir(parents=True)
|
||||
(root / ".github/block/scripts/post-merge-review-changed.sh").write_bytes((HERE / "post-merge-review-changed.sh").read_bytes())
|
||||
git("add", "."); git("commit", "-m", "base"); git("remote", "add", "origin", str(root))
|
||||
base = git("rev-parse", "HEAD").decode().strip()
|
||||
def check(*paths):
|
||||
git("reset", "-q", "--hard", base)
|
||||
for path in paths: (root / path).parent.mkdir(parents=True, exist_ok=True); (root / path).write_text("changed\n")
|
||||
git("add", "--", *paths); git("commit", "-m", "change")
|
||||
git("update-ref", "refs/pull/1/head", "HEAD")
|
||||
env = dict(os.environ, BASE=base, HEAD=git("rev-parse", "HEAD").decode().strip(), PR="1")
|
||||
return subprocess.run(["bash", "-eo", "pipefail", "-c", script], cwd=module, env=env, capture_output=True, timeout=30)
|
||||
self.assertEqual(check("seaweed-block/docs/a.md").returncode, 0)
|
||||
for host in ("weed/example_test.go", "README.md", "docs/a.md"):
|
||||
out = check("seaweed-block/docs/a.md", host)
|
||||
self.assertEqual(out.returncode, 1, out)
|
||||
self.assertEqual([l for l in out.stdout.splitlines() if l.startswith(b"DENY")], [b"DENY host " + host.encode() + b" (outside seaweed-block)"])
|
||||
|
||||
def test_known_bugs_use_the_module_verdict_helper(self):
|
||||
text = (ROOT / ".github/workflows/block-known-bugs.yml").read_text()
|
||||
self.assertIn("bash .github/scripts/known-bugs-test.sh", text)
|
||||
self.assertIn("bash .github/scripts/known-bugs.sh <<'LIST'", text)
|
||||
rows = text.split("<<'LIST'\n", 1)[1].split("\n LIST", 1)[0].split("\n")
|
||||
self.assertTrue(rows)
|
||||
for row in rows:
|
||||
issue, pkg, test = row.split()
|
||||
sources = (ROOT / "seaweed-block" / pkg).glob("*_test.go")
|
||||
self.assertTrue(any("func " + test + "(" in s.read_text() for s in sources), row)
|
||||
|
||||
def test_release_tag_namespace_and_artifact_identity(self):
|
||||
text = (ROOT / ".github/workflows/block-release.yml").read_text()
|
||||
self.assertIn('"seaweed-block/v*"', text)
|
||||
self.assertNotIn('tags:\n - "v*"', text)
|
||||
self.assertIn("git tag -l 'seaweed-block/v*'", text)
|
||||
self.assertIn('docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"', text)
|
||||
self.assertIn('gh release create "$GITHUB_REF_NAME"', text)
|
||||
self.assertIn('--latest=false', text)
|
||||
self.assertIn('gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber', text)
|
||||
publish = 'gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false'
|
||||
self.assertLess(text.index("--clobber"), text.index(publish))
|
||||
self.assertIn("runs-on: ubuntu-latest", text)
|
||||
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
|
||||
self.assertIn('sw-block-${version}-linux-amd64.tar.gz', text)
|
||||
self.assertNotIn("go build", text)
|
||||
self.assertLess(text.index("refusing to publish: release notes"), text.index("docker/build-push-action"))
|
||||
for name in ("sw-block", "blockcsi"):
|
||||
recipe = (ROOT / (".github/dockerfiles/block-" + name + ".Dockerfile")).read_text()
|
||||
self.assertIn("WORKDIR /src/seaweed-block", recipe)
|
||||
self.assertIn("COPY . /src", recipe)
|
||||
self.assertGreater(recipe.index("RUN bash scripts/refuse-lab-binary.sh"), recipe.rindex("go build"))
|
||||
built = re.findall(r"go build -o (\S+)", recipe)
|
||||
refused = re.search(r"^RUN bash scripts/refuse-lab-binary\.sh (.+)$", recipe, re.M).group(1).split()
|
||||
self.assertTrue(built)
|
||||
self.assertEqual(sorted(built), sorted(refused))
|
||||
|
||||
def test_nested_git_paths_and_blobs_stay_module_relative(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); module = root / "seaweed-block"; module.mkdir()
|
||||
def git(*args):
|
||||
return subprocess.check_output(["git", *args], cwd=root, timeout=15)
|
||||
git("init", "-b", "master")
|
||||
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
|
||||
git("config", "commit.gpgsign", "false")
|
||||
(module / "core").mkdir(); (module / "docs").mkdir()
|
||||
code = module / "core/a.go"; code.write_text("package a\nconst N=1\n")
|
||||
(root / "host.go").write_text("package host\n")
|
||||
git("add", "."); git("commit", "-m", "base")
|
||||
base = git("rev-parse", "HEAD").decode().strip()
|
||||
(module / "docs/a.md").write_text("documentation\n")
|
||||
git("add", "."); git("commit", "-m", "docs")
|
||||
docs = git("rev-parse", "HEAD").decode().strip()
|
||||
def run(name, *args):
|
||||
return subprocess.check_output(["bash", str(HERE / name), *args], cwd=module, timeout=20)
|
||||
self.assertEqual(run("docs-only-scope.sh", base, docs), b"docs_only 1\n")
|
||||
code.write_text("package a\nconst N=2\n")
|
||||
(root / "host.go").write_text("package host\nconst Changed=true\n")
|
||||
git("add", "."); git("commit", "-m", "code")
|
||||
head = git("rev-parse", "HEAD").decode().strip()
|
||||
self.assertEqual(run("post-merge-review-changed.sh", docs, head), b"M\0core/a.go\0")
|
||||
self.assertTrue(run("chunkstore-scope.sh", docs, head).startswith(b"skip 1"))
|
||||
for durable in ("core/frontend/chunkstore/c.go", "core/storage/s.go", "core/frontend/durable/d.go"):
|
||||
(module / durable).parent.mkdir(parents=True, exist_ok=True); (module / durable).write_text("package x\n")
|
||||
git("add", "."); git("commit", "-m", "durable")
|
||||
self.assertEqual(run("chunkstore-scope.sh", head, "HEAD"), b"run 1 " + durable.encode() + b"\n")
|
||||
git("reset", "-q", "--hard", head)
|
||||
blobs = root / "blobs"
|
||||
run("changed-go-blobs.sh", docs, head, str(blobs))
|
||||
self.assertEqual((blobs / "old/core/a.go").read_text(), "package a\nconst N=1\n")
|
||||
self.assertEqual((blobs / "new/core/a.go").read_text(), "package a\nconst N=2\n")
|
||||
self.assertFalse((blobs / "new/host.go").exists())
|
||||
control = root / ".github/workflows/block-test.yml"
|
||||
control.parent.mkdir(parents=True)
|
||||
control.write_text("name: Block Test\n")
|
||||
git("add", ".github"); git("commit", "-m", "CI control")
|
||||
control_head = git("rev-parse", "HEAD").decode().strip()
|
||||
self.assertIn(b".github/workflows/block-test.yml\0", run("post-merge-review-changed.sh", docs, control_head))
|
||||
self.assertTrue(run("docs-only-scope.sh", base, control_head).startswith(b"run "))
|
||||
checker = root / ".github/block/scripts/public-text-check.sh"
|
||||
checker.parent.mkdir(parents=True)
|
||||
checker.write_text("pattern='disk" + "station'\n")
|
||||
git("add", ".github"); git("commit", "-m", "checker pattern")
|
||||
pattern_head = git("rev-parse", "HEAD").decode().strip()
|
||||
title, body = root / "title.txt", root / "body.txt"
|
||||
title.write_text("CI scope"); body.write_text("Checker patterns")
|
||||
self.assertEqual(run("public-text-check.sh", control_head, pattern_head, str(title), str(body)), b"public-text: clean\n")
|
||||
from_root = subprocess.check_output(["bash", str(HERE / "public-text-check.sh"), control_head, pattern_head, str(title), str(body)], cwd=root, timeout=20)
|
||||
self.assertEqual(from_root, b"public-text: clean\n")
|
||||
artifact_path = "docs/spec/" + "recorded-example.txt"
|
||||
artifact = module / artifact_path
|
||||
artifact.parent.mkdir(parents=True); artifact.write_text("")
|
||||
git("add", "."); git("commit", "-m", "artifact")
|
||||
artifact_head = git("rev-parse", "HEAD").decode().strip()
|
||||
command = ["bash", str(HERE / "public-text-check.sh"), pattern_head, artifact_head, str(title), str(body)]
|
||||
for cwd in (root, module):
|
||||
leak = subprocess.run(command, cwd=cwd, capture_output=True, timeout=20)
|
||||
self.assertEqual(leak.returncode, 1, (cwd, leak.stdout, leak.stderr))
|
||||
self.assertIn(b"artifact path: " + artifact_path.encode(), leak.stdout)
|
||||
git("rm", str(artifact.relative_to(root))); git("commit", "-m", "remove artifact")
|
||||
deleted = git("rev-parse", "HEAD").decode().strip()
|
||||
removal = ["bash", str(HERE / "public-text-check.sh"), artifact_head, deleted, str(title), str(body)]
|
||||
for cwd in (root, module):
|
||||
result = subprocess.run(removal, cwd=cwd, capture_output=True, timeout=20)
|
||||
self.assertEqual((result.returncode, result.stdout), (0, b"public-text: clean\n"), result.stderr)
|
||||
fakebin = root / "fakebin"; fakebin.mkdir()
|
||||
fakegit = fakebin / "git"
|
||||
fakegit.write_text("#!/bin/sh\nfor arg; do\n if [ \"$arg\" = --diff-filter=ACMT ]; then\n printf 'docs/spec/partial.txt\\0'\n exit 23\n fi\ndone\nexec \"$PUBLIC_TEXT_REAL_GIT\" \"$@\"\n")
|
||||
fakegit.chmod(0o755)
|
||||
env = dict(os.environ, PUBLIC_TEXT_REAL_GIT=shutil.which("git"), PATH=str(fakebin) + os.pathsep + os.environ["PATH"])
|
||||
for cwd in (root, module):
|
||||
result = subprocess.run(removal, cwd=cwd, env=env, capture_output=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 2, (cwd, result.stdout, result.stderr))
|
||||
self.assertIn(b"cannot enumerate artifact paths", result.stderr)
|
||||
self.assertNotIn(b"public-text: clean", result.stdout)
|
||||
|
||||
def test_public_text_adapter_passes_the_module_self_test(self):
|
||||
module = ROOT / "seaweed-block/.github/scripts"
|
||||
pattern = lambda path: [l for l in path.read_text().splitlines() if l.startswith("pat=")]
|
||||
self.assertEqual(pattern(HERE / "public-text-check.sh"), pattern(module / "public-text-check.sh"))
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for source in (module / "public-text-check-test.sh", HERE / "public-text-check.sh"):
|
||||
(Path(tmp) / source.name).write_bytes(source.read_bytes())
|
||||
subprocess.run(["bash", str(Path(tmp) / "public-text-check-test.sh")], check=True, capture_output=True, timeout=60)
|
||||
|
||||
|
||||
def test_root_block_ci_files_pass_the_public_text_scan(self):
|
||||
pat = next(l for l in (HERE / "public-text-check.sh").read_text().splitlines() if l.startswith("pat='"))[5:-1]
|
||||
files = [p for p in (ROOT / ".github/block").rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name != "public-text-check.sh"]
|
||||
files += sorted((ROOT / ".github/workflows").glob("block-*.yml")) + sorted((ROOT / ".github/dockerfiles").glob("block-*.Dockerfile"))
|
||||
hits = subprocess.run(["grep", "-E", "-i", "-n", "-H", "--", pat, *map(str, files)], capture_output=True, timeout=20)
|
||||
self.assertEqual(hits.returncode, 1, hits.stdout.decode() + hits.stderr.decode())
|
||||
|
||||
def test_safe_merge_refuses_wrong_head_base_and_incomplete_jobs(self):
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
|
||||
run = {"path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
|
||||
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
|
||||
check.validate(pr, run, jobs, "base")
|
||||
for key, value in (("head_sha", "other"), ("conclusion", "cancelled"), ("name", "Other Test")):
|
||||
wrong = copy.deepcopy(run); wrong[key] = value
|
||||
with self.assertRaises(ValueError): check.validate(pr, wrong, jobs, "base")
|
||||
with self.assertRaises(ValueError): check.validate(pr, run, jobs, "moved")
|
||||
with self.assertRaises(ValueError): check.validate(pr, run, jobs[:1], "base")
|
||||
failed = copy.deepcopy(jobs); failed[0]["conclusion"] = "failure"
|
||||
with self.assertRaises(ValueError): check.validate(pr, run, failed, "base")
|
||||
|
||||
def test_same_named_workflow_cannot_satisfy_the_gate(self):
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
|
||||
run = {"id": 1, "created_at": "1", "path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
|
||||
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
|
||||
duplicate = dict(run, id=2, created_at="2", path=".github/workflows/pretend.yml")
|
||||
with self.assertRaises(ValueError): check.validate(pr, duplicate, jobs, "base")
|
||||
missing = dict(run); del missing["path"]
|
||||
with self.assertRaises(ValueError): check.validate(pr, missing, jobs, "base")
|
||||
import json
|
||||
with patch.object(check, "api", return_value={"workflow_runs": [run, duplicate]}), patch.object(check.subprocess, "check_output", return_value=json.dumps([{"jobs": jobs}]).encode()):
|
||||
self.assertEqual(check.successful_run(pr, "base")["id"], 1)
|
||||
with patch.object(check, "api", return_value={"workflow_runs": [duplicate]}):
|
||||
with self.assertRaises(ValueError): check.successful_run(pr, "base")
|
||||
|
||||
def test_control_path_changes_need_independent_workflow_review(self):
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
real_output = subprocess.check_output
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
def git(*args): return real_output(["git", *args], cwd=root, timeout=15)
|
||||
git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false")
|
||||
(root / "code.go").write_text("package example")
|
||||
git("add", "."); git("commit", "-m", "base")
|
||||
base = git("rev-parse", "HEAD").decode().strip()
|
||||
for name in (".github/workflows/pretend.yml", ".github/block/scripts/check.py", ".github/dockerfiles/block-image.Dockerfile", "seaweed-block/.github/scripts/record-go-test.sh"):
|
||||
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text("control")
|
||||
git("add", "."); git("commit", "-m", "control")
|
||||
added = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.check_control_paths(base, added)
|
||||
git("rm", name); git("commit", "-m", "remove")
|
||||
removed = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.check_control_paths(added, removed)
|
||||
(root / "code.go").write_text("package example\nconst N=2")
|
||||
git("add", "."); git("commit", "-m", "code")
|
||||
head = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
check.check_control_paths(base, head)
|
||||
git("checkout", "-q", "-b", "master-later", base)
|
||||
(root / ".github/workflows").mkdir(parents=True, exist_ok=True)
|
||||
(root / ".github/workflows/block-test.yml").write_text("master control")
|
||||
git("add", "."); git("commit", "-m", "master control")
|
||||
master = git("rev-parse", "HEAD").decode().strip()
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
check.check_control_paths(master, head)
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.check_control_paths(head, master)
|
||||
with patch.object(check, "check_control_paths", side_effect=ValueError("workflow_review_required")), patch.object(check.subprocess, "check_output", side_effect=["base", "head"]), patch.object(check.subprocess, "run") as run:
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.local_checks({"number": 1, "body": "body", "title": "title", "head": {"sha": "head"}}, "base")
|
||||
self.assertEqual(run.call_count, 1) # fetch only; no checker certification
|
||||
|
||||
def test_control_path_diff_refuses_multiple_merge_bases(self):
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
real_output = subprocess.check_output
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
def git(*args): return real_output(["git", *args], cwd=root, timeout=15).decode().strip()
|
||||
git("init", "-b", "master")
|
||||
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
|
||||
git("config", "commit.gpgsign", "false")
|
||||
git("commit", "--allow-empty", "-m", "base"); base = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "-b", "left")
|
||||
(root / "left.txt").write_text("left")
|
||||
git("add", "."); git("commit", "-m", "left"); left = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "-b", "right", base)
|
||||
(root / "right.txt").write_text("right")
|
||||
git("add", "."); git("commit", "-m", "right"); right = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "left"); git("merge", "--no-ff", right, "-m", "left merge")
|
||||
left_merge = git("rev-parse", "HEAD")
|
||||
git("checkout", "-q", "right"); git("merge", "--no-ff", left, "-m", "right merge")
|
||||
right_merge = git("rev-parse", "HEAD")
|
||||
self.assertEqual(set(git("merge-base", "--all", left_merge, right_merge).splitlines()), {left, right})
|
||||
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
|
||||
with self.assertRaisesRegex(ValueError, "ambiguous_merge_base"):
|
||||
check.check_control_paths(left_merge, right_merge)
|
||||
check.check_control_paths(left, left_merge)
|
||||
|
||||
def test_fork_runner_guard_is_required_not_only_the_fallback(self):
|
||||
expected = "${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}"
|
||||
for name in ("test", "spec-trace", "known-bugs"):
|
||||
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip().startswith("runs-on:")]
|
||||
self.assertEqual(lines, ["runs-on: " + expected])
|
||||
|
||||
def test_rerun_during_local_checks_cannot_report_ready(self):
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
def pr(number):
|
||||
return {"number": number, "state": "open", "draft": False, "mergeable": True,
|
||||
"base": {"ref": "master"}, "head": {"sha": str(number)}}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
evidence = Path(tmp) / "acceptance"; evidence.write_text("accepted")
|
||||
members = [pr(1), pr(2)]
|
||||
manifest = {"base": "base", "head": "3", "batch_pr": 3,
|
||||
"prs": [{"number": n, "head": str(n), "evidence": str(evidence)} for n in (1, 2)]}
|
||||
path = Path(tmp) / "batch.json"; path.write_text(json.dumps(manifest))
|
||||
for batch in (False, True):
|
||||
for outcome in ("in_progress", "failed_run", "failed_job", "new_run", "success"):
|
||||
with self.subTest(batch=batch, outcome=outcome):
|
||||
changed = False
|
||||
observations = []
|
||||
number = 3 if batch else 1
|
||||
def api(endpoint):
|
||||
if endpoint == "git/ref/heads/master": return {"object": {"sha": "base"}}
|
||||
if endpoint.startswith("pulls/"): return pr(int(endpoint.split("/")[-1]))
|
||||
if endpoint == "git/commits/3": return {"tree": {"sha": "tree"}}
|
||||
observations.append(("run", changed))
|
||||
run = {"id": 10, "run_attempt": 2 if changed else 1, "created_at": "1",
|
||||
"path": check.WORKFLOW_PATH, "name": "Block Test", "head_sha": str(number),
|
||||
"status": "completed", "conclusion": "success",
|
||||
"pull_requests": [{"number": number, "base": {"sha": "base"}}]}
|
||||
if changed and outcome in ("in_progress", "new_run"):
|
||||
run.update(status="in_progress", conclusion=None)
|
||||
if outcome == "new_run": run.update(id=11, created_at="2")
|
||||
if changed and outcome == "failed_run": run["conclusion"] = "failure"
|
||||
return {"workflow_runs": [run]}
|
||||
def jobs(*args, **kwargs):
|
||||
observations.append(("jobs", changed))
|
||||
result = [{"name": name, "conclusion": "success"} for name in check.JOBS]
|
||||
if changed and outcome == "failed_job": result[0]["conclusion"] = "failure"
|
||||
return json.dumps([{"jobs": result}]).encode()
|
||||
def local(*args):
|
||||
nonlocal changed
|
||||
changed = True
|
||||
output = io.StringIO()
|
||||
with patch.object(check, "api", side_effect=api), patch.object(check.subprocess, "check_output", side_effect=jobs), patch.object(check, "fetch_review_head"), patch.object(check, "local_checks", side_effect=local), contextlib.redirect_stdout(output):
|
||||
if outcome == "success":
|
||||
check.main(["--batch", str(path)] if batch else ["1"])
|
||||
else:
|
||||
with self.assertRaises(ValueError):
|
||||
check.main(["--batch", str(path)] if batch else ["1"])
|
||||
if outcome == "success":
|
||||
self.assertTrue(json.loads(output.getvalue())["ready"])
|
||||
else:
|
||||
self.assertNotIn('"ready": true', output.getvalue())
|
||||
self.assertIn(("run", True), observations)
|
||||
self.assertIn(("jobs", True), observations)
|
||||
|
||||
def test_batch_preserves_pinned_base_heads_order_and_evidence(self):
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
evidence = Path(tmp) / "acceptance"; evidence.write_text("review accepted")
|
||||
prs = [{"number": n, "state": "open", "draft": False, "base": {"ref": "master"}, "head": {"sha": str(n)}} for n in (1, 2)]
|
||||
manifest = {"base": "base", "head": "batch", "prs": [{"number": p["number"], "head": p["head"]["sha"], "evidence": str(evidence)} for p in prs]}
|
||||
check.validate_batch(manifest, prs, "base")
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "moved")
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, list(reversed(prs)), "base")
|
||||
wrong = copy.deepcopy(prs); wrong[0]["head"]["sha"] = "new"
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, wrong, "base")
|
||||
batch_manifest = dict(manifest, batch_pr=3)
|
||||
manifest_path = Path(tmp) / "batch.json"
|
||||
import json
|
||||
manifest_path.write_text(json.dumps(batch_manifest))
|
||||
replies = {"git/ref/heads/master": {"object": {"sha": "base"}}, "pulls/1": prs[0], "pulls/2": prs[1], "pulls/3": {"number": 3, "head": {"sha": "batch"}}}
|
||||
with patch.object(check, "api", side_effect=lambda path: replies[path]), patch.object(check, "fetch_review_head", side_effect=ValueError("workflow_review_required")) as fetch, patch.object(check, "successful_run") as run:
|
||||
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
|
||||
check.main(["--batch", str(manifest_path)])
|
||||
fetch.assert_called_once_with(replies["pulls/3"], "base")
|
||||
run.assert_not_called()
|
||||
evidence.write_text("")
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base")
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -1,30 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Writes the old and new blob of each changed non-test Go file between two
|
||||
# commits under <out>/old/<path> and <out>/new/<path>, for the spec trace's
|
||||
# kind DOCS (objects only; nothing from the PR is built or run).
|
||||
#
|
||||
# usage: changed-go-blobs.sh <merge-base> <head> <out>
|
||||
#
|
||||
# The paths come from the PR's tree objects, which git does not check when it
|
||||
# prints a diff. A path that is absolute or has an empty, '.' or '..'
|
||||
# component would write outside <out>, so it is refused before anything is
|
||||
# written (exit 1).
|
||||
set -euo pipefail
|
||||
mb=$1 head=$2 out=$3
|
||||
prefix=$(git rev-parse --show-prefix)
|
||||
mkdir -p "$out"
|
||||
git diff --relative --name-only --no-renames -z "$mb" "$head" -- "*.go" ":(exclude)*_test.go" >"$out/.paths"
|
||||
while IFS= read -r -d "" p; do
|
||||
case "/$p/" in
|
||||
*//* | */./* | */../*)
|
||||
printf 'changed-go-blobs: refusing path %q\n' "$p" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done <"$out/.paths"
|
||||
while IFS= read -r -d "" p; do
|
||||
mkdir -p "$out/old/$(dirname "$p")" "$out/new/$(dirname "$p")"
|
||||
git show "$mb:$prefix$p" >"$out/old/$p" 2>/dev/null || rm -f "$out/old/$p"
|
||||
git show "$head:$prefix$p" >"$out/new/$p" 2>/dev/null || rm -f "$out/new/$p"
|
||||
done <"$out/.paths"
|
||||
rm -f "$out/.paths"
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run only from a trusted base checkout; HEAD code is inspected as Git objects.
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
base=${1:?BASE}; head=${2:?HEAD}; body=${3:?BODY}; title=${4:?TITLE}
|
||||
[ "$(git rev-parse HEAD)" = "$(git rev-parse "$base")" ] || { echo "refusing: checkout is not the trusted base" >&2; exit 2; }
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mb=$(git merge-base "$base" "$head")
|
||||
bash "$here/post-merge-review-changed.sh" "$mb" "$head" >"$work/changed.bin"
|
||||
bash "$here/changed-go-blobs.sh" "$mb" "$head" "$work/blobs"
|
||||
bash .github/scripts/spec-trace-check.sh "$body" "$work/blobs" .github/model-code-trace.tsv <"$work/changed.bin"
|
||||
bash "$here/public-text-check.sh" "$mb" "$head" "$title" "$body"
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# chunkstore-scope.sh BASE HEAD: decides whether a pull request runs the
|
||||
# real-filer integration tests. It prints one line:
|
||||
# "run N FIRST" at least one of the N changed files is under
|
||||
# core/frontend/chunkstore/, core/storage/ or
|
||||
# core/frontend/durable/ (FIRST is one)
|
||||
# "skip N" none of the N changed files is
|
||||
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
|
||||
# and the caller then runs the tests: an error never selects skip.
|
||||
#
|
||||
# The NUL-delimited list is written to a file first and read to its end, so
|
||||
# no pipe can stop early and leave a writer's error looking like an answer.
|
||||
set -euo pipefail
|
||||
[ "$#" -eq 2 ] || { echo "usage: chunkstore-scope.sh BASE HEAD" >&2; exit 2; }
|
||||
list=$(mktemp)
|
||||
trap 'rm -f "$list"' EXIT
|
||||
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
|
||||
echo "chunkstore-scope: git diff $1 $2 failed" >&2
|
||||
exit 2
|
||||
fi
|
||||
n=0
|
||||
hit=""
|
||||
while IFS= read -r -d '' f; do
|
||||
n=$((n + 1))
|
||||
case $f in
|
||||
core/frontend/chunkstore/* | core/storage/* | core/frontend/durable/*) [ -n "$hit" ] || hit=$f ;;
|
||||
esac
|
||||
done <"$list"
|
||||
if [ -n "$hit" ]; then
|
||||
echo "run $n $hit"
|
||||
else
|
||||
echo "skip $n"
|
||||
fi
|
||||
@@ -1,142 +0,0 @@
|
||||
"""Relative Markdown links must resolve; code, anchors and URLs are not paths."""
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location("links", Path(__file__).with_name("doc-links-check.py"))
|
||||
links = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(links)
|
||||
|
||||
|
||||
class DocLinksTests(unittest.TestCase):
|
||||
def check(self, files):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
for name, text in files.items():
|
||||
path = Path(root, name)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
return [(source, target) for source, _, target in links.broken_links(root)]
|
||||
|
||||
def test_existing_targets_pass(self):
|
||||
broken = self.check({
|
||||
"README.md": "[guide](docs/guide.md#start)  [dir](docs/) [ref][r]\n\n[r]: <docs/a b.md>\n",
|
||||
"docs/guide.md": "[up](../README.md) [root](/docs/d.svg) [esc](a%20b.md)\n",
|
||||
"docs/d.svg": "",
|
||||
"docs/a b.md": "",
|
||||
})
|
||||
self.assertEqual(broken, [])
|
||||
|
||||
def test_missing_targets_fail(self):
|
||||
broken = self.check({
|
||||
"README.md": "[gone](docs/gone.md) [nested [x]](docs/x.md#a)\n\n[r]: missing.md\n",
|
||||
"docs/guide.md": "[up](../nope.md)\n",
|
||||
})
|
||||
self.assertCountEqual(broken, [
|
||||
("README.md", "docs/gone.md"),
|
||||
("README.md", "docs/x.md#a"),
|
||||
("README.md", "missing.md"),
|
||||
("docs/guide.md", "../nope.md"),
|
||||
])
|
||||
|
||||
def test_urls_anchors_and_code_are_not_checked(self):
|
||||
broken = self.check({
|
||||
"README.md": "\n".join([
|
||||
"[web](https://example.invalid/x) [mail](mailto:a@example.invalid) [top](#top) [proto](//host/x)",
|
||||
"`[code](gone.md)` and ``[code](gone.md)``",
|
||||
"```",
|
||||
"[fenced](gone.md)",
|
||||
"```",
|
||||
"~~~md",
|
||||
"[tilde](gone.md)",
|
||||
"~~~",
|
||||
]) + "\n",
|
||||
})
|
||||
self.assertEqual(broken, [])
|
||||
|
||||
def test_wrapped_labels_parentheses_and_long_fences(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
Path(root, "guide(v2).md").write_text("")
|
||||
Path(root, "README.md").write_text("\n".join([
|
||||
"[guide](guide(v2).md) [old](guide(v1).md)",
|
||||
"",
|
||||
"see the [wrapped",
|
||||
"label](wrapped.md) here",
|
||||
"",
|
||||
"`[wrapped",
|
||||
"code](gone.md)` then [after](after.md)",
|
||||
"````md",
|
||||
"```",
|
||||
"[example](missing.md)",
|
||||
"```",
|
||||
"````",
|
||||
]) + "\n")
|
||||
broken = [(line, target) for _, line, target in links.broken_links(root)]
|
||||
self.assertEqual(broken, [(1, "guide(v1).md"), (3, "wrapped.md"), (7, "after.md")])
|
||||
|
||||
def test_code_spans_require_complete_equal_delimiter_runs(self):
|
||||
cases = [
|
||||
("`unmatched\n[real](real.md) ``", [(2, "real.md")]),
|
||||
("``unmatched\n[real](real.md) `", [(2, "real.md")]),
|
||||
("``unmatched\n[real](real.md) ```", [(2, "real.md")]),
|
||||
("`[wrapped\ncode](hidden.md)`\n[after](after.md)", [(3, "after.md")]),
|
||||
("``[wrapped `\ncode](hidden.md)``\n[after](after.md)", [(3, "after.md")]),
|
||||
]
|
||||
for text, expected in cases:
|
||||
with self.subTest(text=text), tempfile.TemporaryDirectory() as root:
|
||||
Path(root, "README.md").write_text(text + "\n", encoding="utf-8")
|
||||
broken = [(line, target) for _, line, target in links.broken_links(root)]
|
||||
self.assertEqual(broken, expected)
|
||||
|
||||
def test_escaped_backticks_do_not_hide_links(self):
|
||||
cases = [
|
||||
("\\`\n[real](real.md)\n\\`", [(2, "real.md")]),
|
||||
("\\\\`[code](hidden.md)`\n[after](after.md)", [(2, "after.md")]),
|
||||
("`[code](hidden.md)\\`\n[after](after.md)", [(2, "after.md")]),
|
||||
]
|
||||
for text, expected in cases:
|
||||
with self.subTest(text=text):
|
||||
self.assertEqual(list(links.link_targets(text)), expected)
|
||||
|
||||
def test_masked_code_preserves_reference_line_context(self):
|
||||
text = "Use `code\nmore`[r]: gone.md\n\n[r]: real.md\n"
|
||||
self.assertEqual(list(links.link_targets(text)), [(4, "real.md")])
|
||||
|
||||
def test_code_masking_contract(self):
|
||||
cases = [
|
||||
("unequal runs", "`unmatched\n[real](real.md) ``", [], [(2, "real.md")]),
|
||||
("escaped delimiters", "\\`\n[real](real.md)\n\\`", [], [(2, "real.md")]),
|
||||
("reference context", "Use `code\nmore`[r]: gone.md\n\n[r]: real.md", [], [(4, "real.md")]),
|
||||
("wrapped span", "`[code\nhere](hidden.md)`\n[after](after.md)", [], [(3, "after.md")]),
|
||||
("hidden-space invalid target", "[example](`foo bar`)", [], []),
|
||||
("hidden-space invalid reference", "[r]: `a b`", [], []),
|
||||
("existing literal target", "[example](`foo.md`)", ["`foo.md`"], []),
|
||||
("missing literal target", "[example](`foo.md`)", [], [(1, "`foo.md`")]),
|
||||
]
|
||||
for name, text, existing, expected in cases:
|
||||
with self.subTest(name=name), tempfile.TemporaryDirectory() as root:
|
||||
Path(root, "README.md").write_text(text + "\n", encoding="utf-8")
|
||||
for target in existing:
|
||||
Path(root, target).touch()
|
||||
broken = [(line, target) for _, line, target in links.broken_links(root)]
|
||||
self.assertEqual(broken, expected)
|
||||
masked = links.mask_code_spans(text)
|
||||
self.assertEqual(len(masked), len(text))
|
||||
self.assertEqual([i for i, c in enumerate(masked) if c == "\n"],
|
||||
[i for i, c in enumerate(text) if c == "\n"])
|
||||
|
||||
def test_main_exit_status(self):
|
||||
out = io.StringIO()
|
||||
with tempfile.TemporaryDirectory() as root, contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
|
||||
Path(root, "README.md").write_text("[gone](gone.md)\n")
|
||||
self.assertEqual(links.main(["doc-links-check.py", root]), 1)
|
||||
Path(root, "gone.md").write_text("")
|
||||
self.assertEqual(links.main(["doc-links-check.py", root]), 0)
|
||||
self.assertEqual(links.main(["doc-links-check.py"]), 2)
|
||||
self.assertIn("README.md:1: broken relative link gone.md", out.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,128 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail when a Markdown file links to a relative path that does not exist.
|
||||
|
||||
Usage: doc-links-check.py <root>
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
SKIP_DIRS = {".git", "node_modules", "vendor"}
|
||||
FENCE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$")
|
||||
BACKTICKS = re.compile(r"`+")
|
||||
INLINE_DESTINATION = r"<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+"
|
||||
REFERENCE_DESTINATION = r"<[^>]*>|\S+"
|
||||
INLINE_LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\[\]]*\])*\]\(\s*(" + INLINE_DESTINATION + r")")
|
||||
REFERENCE = re.compile(r"^[ \t]{0,3}\[[^\]]+\]:\s*(" + REFERENCE_DESTINATION + r")", re.M)
|
||||
SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
|
||||
|
||||
|
||||
def mask_code_spans(text):
|
||||
runs = list(BACKTICKS.finditer(text))
|
||||
masked = list(text)
|
||||
i = 0
|
||||
while i < len(runs):
|
||||
opening = runs[i]
|
||||
start = opening.start()
|
||||
# Only prose escapes delimiters; backslashes inside code are literal.
|
||||
preceding = start
|
||||
while preceding > 0 and text[preceding - 1] == "\\":
|
||||
preceding -= 1
|
||||
if (start - preceding) % 2:
|
||||
start += 1
|
||||
width = opening.end() - start
|
||||
if not width:
|
||||
i += 1
|
||||
continue
|
||||
closing = next((j for j in range(i + 1, len(runs))
|
||||
if len(runs[j].group()) == width), None)
|
||||
if closing is None:
|
||||
i += 1
|
||||
continue
|
||||
# Keep columns and non-whitespace line context as well as line numbers.
|
||||
for pos in range(start, runs[closing].end()):
|
||||
if text[pos] != "\n":
|
||||
masked[pos] = "\0"
|
||||
i = closing + 1
|
||||
return "".join(masked)
|
||||
|
||||
|
||||
def paragraph_targets(first, lines):
|
||||
# A link label may wrap, so links are matched per paragraph.
|
||||
original = "\n".join(lines)
|
||||
text = mask_code_spans(original)
|
||||
# Masked bytes are context only, never a synthetic filesystem destination.
|
||||
found = []
|
||||
for regex, syntax in ((INLINE_LINK, INLINE_DESTINATION), (REFERENCE, REFERENCE_DESTINATION)):
|
||||
for match in regex.finditer(text):
|
||||
target = original[match.start(1):match.end(1)]
|
||||
if re.fullmatch(syntax, target):
|
||||
found.append((match.start(), target))
|
||||
for pos, target in sorted(found):
|
||||
yield first + text.count("\n", 0, pos), target
|
||||
|
||||
|
||||
def link_targets(text):
|
||||
fence, block, first = None, [], 1
|
||||
for lineno, line in enumerate(text.splitlines() + [""], 1):
|
||||
m = FENCE.match(line)
|
||||
if fence is not None:
|
||||
# Only a fence of the same character, at least as long, closes it.
|
||||
if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not m.group(2).strip():
|
||||
fence = None
|
||||
continue
|
||||
if m or not line.strip():
|
||||
yield from paragraph_targets(first, block)
|
||||
block = []
|
||||
if m:
|
||||
fence = m.group(1)
|
||||
continue
|
||||
if not block:
|
||||
first = lineno
|
||||
block.append(line)
|
||||
|
||||
|
||||
def local_path(target):
|
||||
if target.startswith("<") and target.endswith(">"):
|
||||
target = target[1:-1]
|
||||
if not target or target.startswith(("#", "//")) or SCHEME.match(target):
|
||||
return None
|
||||
path = urllib.parse.unquote(target.split("#", 1)[0].split("?", 1)[0])
|
||||
return path or None
|
||||
|
||||
|
||||
def broken_links(root):
|
||||
root = os.path.abspath(root)
|
||||
for dirpath, dirnames, filenames in os.walk(root):
|
||||
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
|
||||
for name in sorted(filenames):
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
source = os.path.join(dirpath, name)
|
||||
with open(source, encoding="utf-8", errors="replace") as f:
|
||||
text = f.read()
|
||||
for lineno, target in link_targets(text):
|
||||
path = local_path(target)
|
||||
if path is None:
|
||||
continue
|
||||
if path.startswith("/"):
|
||||
resolved = os.path.join(root, path.lstrip("/"))
|
||||
else:
|
||||
resolved = os.path.join(dirpath, path)
|
||||
if not os.path.exists(resolved):
|
||||
yield os.path.relpath(source, root), lineno, target
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
broken = list(broken_links(argv[1]))
|
||||
for source, lineno, target in broken:
|
||||
print(f"{source}:{lineno}: broken relative link {target}")
|
||||
return 1 if broken else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -1,35 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# docs-only-scope.sh BASE HEAD: classifies the files changed between BASE and
|
||||
# HEAD for the process-level suite. It prints one line:
|
||||
# "docs_only N" every one of the N changed files is under docs/
|
||||
# "run N [FIRST-OTHER]" no file changed, or at least one is elsewhere
|
||||
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
|
||||
# and the caller then runs the tests: an error never selects docs_only.
|
||||
#
|
||||
# The NUL-delimited list is written to a file first and read to its end, so
|
||||
# no pipe can stop early and leave a writer's error looking like an answer.
|
||||
set -euo pipefail
|
||||
[ "$#" -eq 2 ] || { echo "usage: docs-only-scope.sh BASE HEAD" >&2; exit 2; }
|
||||
list=$(mktemp)
|
||||
trap 'rm -f "$list"' EXIT
|
||||
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
|
||||
echo "docs-only-scope: git diff $1 $2 failed" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [ -n "$(git rev-parse --show-prefix)" ]; then
|
||||
git -C "$(git rev-parse --show-toplevel)" diff --name-only --no-renames -z "$1" "$2" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' >>"$list"
|
||||
fi
|
||||
n=0
|
||||
other=""
|
||||
while IFS= read -r -d '' f; do
|
||||
n=$((n + 1))
|
||||
case $f in
|
||||
docs/*) ;;
|
||||
*) [ -n "$other" ] || other=$f ;;
|
||||
esac
|
||||
done <"$list"
|
||||
if [ "$n" -gt 0 ] && [ -z "$other" ]; then
|
||||
echo "docs_only $n"
|
||||
else
|
||||
echo "run $n${other:+ $other}"
|
||||
fi
|
||||
@@ -1,121 +0,0 @@
|
||||
"""Check that every code and test anchor of the invariants ledger exists at a git ref.
|
||||
|
||||
usage: python -I ledger_check.py <repo-dir> <git-ref> [<ledger path in repo>]
|
||||
|
||||
A ledger row is a table line whose first cell holds `INV-...`. In its cells, a
|
||||
backticked token that ends in .go is a FILE; a backticked identifier (or
|
||||
Type.Method) is a SYMBOL of the nearest file named before it in the same cell,
|
||||
or, in the test cell, of any file named in that cell. A file must exist at the
|
||||
ref; a symbol must occur in its file as a whole word (for a test: `func Name(`).
|
||||
A symbol with no file in its cell is looked up in the whole tree. A file may
|
||||
be a glob (`volume_lock*.go`). A lower-case token with an underscore (a build
|
||||
tag, a JSON key, a reason string) is not a Go symbol and is not checked.
|
||||
Prints one line per missing anchor and a summary. It reads; it changes nothing.
|
||||
Exit: 0 when every anchor exists; 1 when one is missing; 2 when git fails or no
|
||||
row or anchor was found (an error is never read as a pass).
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
"""git's output. A git failure ends the check with exit 2: an error must
|
||||
never read as "no anchors". `git grep` finding nothing (exit 1) is not one."""
|
||||
r = subprocess.run(["git", "-C", repo] + list(args), capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace")
|
||||
if r.returncode != 0 and not (args and args[0] == "grep" and r.returncode == 1):
|
||||
print("ledger_check: git %s failed (exit %d): %s" % (" ".join(args[:2]), r.returncode, r.stderr.strip()[:300]),
|
||||
file=sys.stderr)
|
||||
sys.exit(2)
|
||||
return r.stdout
|
||||
|
||||
|
||||
def main():
|
||||
repo, ref = sys.argv[1], sys.argv[2]
|
||||
ledger = sys.argv[3] if len(sys.argv) > 3 else "docs/design/invariants.md"
|
||||
text = git(repo, "show", "%s:%s" % (ref, ledger))
|
||||
prefix = sys.argv[4] if len(sys.argv) > 4 else ""
|
||||
files = set(git(repo, "ls-tree", "-r", "--name-only", ref, "--", prefix or ".").split("\n"))
|
||||
cache = {}
|
||||
|
||||
def body(path):
|
||||
if path not in cache:
|
||||
cache[path] = git(repo, "show", "%s:%s" % (ref, path))
|
||||
return cache[path]
|
||||
|
||||
def resolve(tok):
|
||||
"""A file token may be a full path or a bare file name."""
|
||||
if tok in files:
|
||||
return [tok]
|
||||
if "*" in tok:
|
||||
rx = re.compile("^(.*/)?" + "[^/]*".join(re.escape(x) for x in tok.split("*")) + "$")
|
||||
return [f for f in files if rx.match(f)]
|
||||
if "/" not in tok:
|
||||
return [f for f in files if f.endswith("/" + tok)]
|
||||
# a path with a directory matches whole path components only
|
||||
return [f for f in files if f.endswith("/" + tok)]
|
||||
|
||||
ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?(\(\))?$")
|
||||
go_all = None
|
||||
rows = missing = anchors = 0
|
||||
for n, line in enumerate(text.split("\n"), 1):
|
||||
if not line.startswith("|"):
|
||||
continue
|
||||
cells = [c.strip() for c in line.strip().strip("|").split("|")]
|
||||
m = re.match(r"`(INV-[A-Z0-9-]+)`", cells[0]) if cells else None
|
||||
if not m or len(cells) < 6:
|
||||
continue
|
||||
rows += 1
|
||||
inv, status = m.group(1), cells[-1]
|
||||
if "ARCHIVED" in status:
|
||||
continue
|
||||
for ci, kind in ((3, "code"), (4, "test")):
|
||||
toks = re.findall(r"`([^`]+)`", cells[ci])
|
||||
cell_files = []
|
||||
for t in toks:
|
||||
if t.endswith(".go"):
|
||||
cell_files.append(t)
|
||||
cur = None
|
||||
for t in toks:
|
||||
if t.endswith(".go"):
|
||||
cur = t
|
||||
anchors += 1
|
||||
if not resolve(t):
|
||||
missing += 1
|
||||
print("%s (line %d, %s, %s): file %s does not exist" % (inv, n, kind, status, t))
|
||||
continue
|
||||
if not ident.match(t):
|
||||
continue
|
||||
sym = t.rstrip("()").split(".")[-1]
|
||||
if sym in ("nil", "true", "false") or sym.isupper() or len(sym) < 3:
|
||||
continue
|
||||
if "_" in sym and sym == sym.lower():
|
||||
# a build tag, a JSON key or a reason string: not a Go symbol
|
||||
continue
|
||||
scope = [cur] if (cur and kind == "code") else cell_files
|
||||
paths = [p for f in scope for p in resolve(f)]
|
||||
anchors += 1
|
||||
if kind == "test" and sym.startswith(("Test", "Fuzz", "Benchmark")):
|
||||
pat = re.compile(r"func %s\(" % re.escape(sym))
|
||||
else:
|
||||
pat = re.compile(r"\b%s\b" % re.escape(sym))
|
||||
if paths:
|
||||
ok = any(pat.search(body(p)) for p in paths)
|
||||
else:
|
||||
if go_all is None:
|
||||
go_all = git(repo, "grep", "-h", "-E", r"^(func|type|var|const|\s+[A-Za-z_]+\s)", ref, "--", prefix + "*.go")
|
||||
ok = bool(pat.search(go_all))
|
||||
if not ok:
|
||||
missing += 1
|
||||
where = ", ".join(scope) if scope else "the tree"
|
||||
print("%s (line %d, %s, %s): %s not found in %s" % (inv, n, kind, status, t, where))
|
||||
print("%d rows, %d anchors, %d missing at %s" % (rows, anchors, missing, ref))
|
||||
if rows == 0 or anchors == 0:
|
||||
print("ledger_check: no ledger rows or anchors found: refusing to pass", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
sys.exit(1 if missing else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,14 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Usage: post-merge-review-changed.sh BASE HEAD
|
||||
#
|
||||
# Writes what a PR changes (BASE...HEAD) as NUL-separated STATUS, PATH pairs,
|
||||
# unquoted, so any byte in a name reaches the check as itself. --no-renames
|
||||
# reports a move as a delete of the old name and an add of the new one.
|
||||
set -euo pipefail
|
||||
base=${1:?usage: post-merge-review-changed.sh BASE HEAD}
|
||||
head=${2:?usage: post-merge-review-changed.sh BASE HEAD}
|
||||
git diff --relative -z --name-status --no-renames "$base...$head" -- .
|
||||
|
||||
if [ -n "$(git rev-parse --show-prefix)" ]; then
|
||||
git -C "$(git rev-parse --show-toplevel)" diff -z --name-status --no-renames "$base...$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**'
|
||||
fi
|
||||
@@ -1,70 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Refuses internal names in what a pull request makes public: the lines it
|
||||
# adds, its commit messages, its title and its description. This repository is
|
||||
# public; internal names, machine paths and raw run artifacts do not belong in it.
|
||||
#
|
||||
# Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE
|
||||
# Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage.
|
||||
#
|
||||
# The patterns live only here and in this check's own test; both files are
|
||||
# excluded from the scan of added lines.
|
||||
set -euo pipefail
|
||||
[ "$#" -eq 4 ] || { echo "usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE" >&2; exit 2; }
|
||||
mb=$1; head=$2; title=$3; body=$4
|
||||
for f in "$title" "$body"; do
|
||||
[ -f "$f" ] && [ -r "$f" ] || { echo "public-text: cannot read $f" >&2; exit 2; }
|
||||
done
|
||||
git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify "$head^{commit}" >/dev/null ||
|
||||
{ echo "public-text: unknown commit $mb or $head" >&2; exit 2; }
|
||||
# match: a grep error fails the check instead of reading as "no hit".
|
||||
match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; }
|
||||
pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation|/home/[^/[:space:]]+/|(^|[^[:alnum:]_])pid[[:space:]]*[:=][[:space:]]*[0-9]+|[0-9]+[[:space:]]+cores[[:space:]]+with[[:space:]]+[0-9]+([.][0-9]+)?[[:space:]]*(KB|MB|GB|KiB|MiB|GiB)?[[:space:]]+heap|docs/spec/([^/[:space:]]+/)*recorded-[^/[:space:]]+'
|
||||
out=$(mktemp); paths=; trap 'rm -f "$out" "$paths"' EXIT
|
||||
paths=$(mktemp)
|
||||
report() { # report WHERE < matching lines
|
||||
local where=$1 line
|
||||
while IFS= read -r line; do
|
||||
printf 'public-text: %s: %s
|
||||
' "$where" "${line:0:160}" >>"$out"
|
||||
done
|
||||
}
|
||||
# Raw run artifacts are not public specs, even with scrubbed contents.
|
||||
# Allow deletions so existing artifacts can be removed.
|
||||
repo_root=$(git rev-parse --show-toplevel)
|
||||
if ! (cd "$repo_root" && git diff --name-only -z --no-relative --no-renames --diff-filter=ACMT "$mb" "$head" -- docs/spec/ seaweed-block/docs/spec/) >"$paths"; then
|
||||
echo 'public-text: cannot enumerate artifact paths' >&2
|
||||
exit 2
|
||||
fi
|
||||
while IFS= read -r -d '' path; do
|
||||
# Match the module's paths the same way from either entry point.
|
||||
path=${path#seaweed-block/}
|
||||
if [[ $path =~ ^docs/spec/(.*/)?recorded-[^/]+(/|$) ]]; then
|
||||
printf '%s\n' "$path" | report "artifact path"
|
||||
fi
|
||||
done <"$paths"
|
||||
# Added lines of the diff, with file and line number.
|
||||
{
|
||||
git diff --relative --no-color --no-renames -U0 "$mb" "$head" -- . \
|
||||
':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh' \
|
||||
':(exclude,top).github/block/scripts/public-text-check.sh'
|
||||
if [ -n "$(git rev-parse --show-prefix)" ]; then
|
||||
git -C "$(git rev-parse --show-toplevel)" diff --no-color --no-renames -U0 "$mb" "$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' ':(exclude).github/block/scripts/public-text-check.sh'
|
||||
fi
|
||||
} |
|
||||
awk '
|
||||
/^diff --git / { hdr = 1; next }
|
||||
hdr && /^\+\+\+ / { f = substr($0, 7); next }
|
||||
/^@@ / { hdr = 0; split($3, a, ","); n = substr(a[1], 2) + 0; next }
|
||||
!hdr && /^\+/ { print f ":" n ": " substr($0, 2); n++ }
|
||||
' | match | report "added line"
|
||||
# Commit messages (subjects and bodies) of the pull request.
|
||||
git log --format='%h %s%n%b' "$mb..$head" | match | report "commit message"
|
||||
match "$title" | report "title"
|
||||
match "$body" | report "description"
|
||||
hits=$(wc -l <"$out" | tr -d ' ')
|
||||
if [ "$hits" -gt 0 ]; then
|
||||
cat "$out"
|
||||
echo "public-text: $hits hit(s). Say what the code or test does instead of who asked for it; keep internal paths out." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "public-text: clean"
|
||||
@@ -1,145 +0,0 @@
|
||||
"""Run fake recorders through the real group executor, without product tests."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
import importlib.util
|
||||
import signal
|
||||
|
||||
SCRIPT = Path(__file__).with_name("run-unit-groups.py")
|
||||
FAKE = r'''import json, os, sys, time
|
||||
from pathlib import Path
|
||||
out = Path(sys.argv[1]); group = out.parent.name
|
||||
root = Path(os.environ["FIXTURE_ROOT"])
|
||||
(root / (group + ".started")).write_text("started")
|
||||
deadline = time.monotonic() + 5
|
||||
while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()):
|
||||
if time.monotonic() >= deadline: sys.exit(17)
|
||||
time.sleep(.01)
|
||||
flags = sys.argv[2:]
|
||||
assert "-p=" + ("4" if group == "g3" else "1") in flags
|
||||
assert "-short" in flags and "-count=1" in flags and "20m" in flags
|
||||
if sys.platform == "linux":
|
||||
wal = Path(os.environ["TMPDIR"]) / "v1.bin"
|
||||
with wal.open("w") as descriptor:
|
||||
assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found"
|
||||
else:
|
||||
assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory"
|
||||
out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n")
|
||||
out.with_suffix(".stderr").write_text("fixture stderr")
|
||||
(root / (group + ".finished")).write_text("finished")
|
||||
sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0)
|
||||
'''
|
||||
|
||||
|
||||
class GroupRunnerTests(unittest.TestCase):
|
||||
def run_groups(self, fail="", empty=False, alias=False):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
||||
for group in ("g1", "g2", "g3"):
|
||||
(plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n")
|
||||
fake = root / "fake.py"; fake.write_text(FAKE)
|
||||
env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail)
|
||||
scratch = root / "tmp"
|
||||
if alias:
|
||||
scratch.mkdir()
|
||||
link = root / "runner-temp"
|
||||
link.symlink_to(scratch, target_is_directory=True)
|
||||
scratch = link
|
||||
result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr)
|
||||
expected = ["g3"] if empty else ["g1", "g2", "g3"]
|
||||
for group in expected:
|
||||
self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr)
|
||||
self.assertTrue((root / "evidence" / group / "go-test.stderr").exists())
|
||||
self.assertTrue((root / "tmp" / group).is_dir())
|
||||
events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()]
|
||||
self.assertCountEqual([e["Package"] for e in events], expected)
|
||||
statuses = json.loads((root / "evidence" / "unit-groups.json").read_text())
|
||||
self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0)
|
||||
|
||||
@unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control")
|
||||
def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True)
|
||||
|
||||
def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups()
|
||||
def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2")
|
||||
def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True)
|
||||
|
||||
|
||||
def test_cancel_escalates_even_after_group_leader_exits(self):
|
||||
spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT)
|
||||
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
|
||||
group = 12345
|
||||
leader = Mock(pid=group)
|
||||
leader.wait.return_value = 0
|
||||
with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]):
|
||||
module.terminate([leader])
|
||||
self.assertIn(unittest.mock.call(group, signal.SIGTERM), killpg.call_args_list)
|
||||
self.assertIn(unittest.mock.call(group, 9), killpg.call_args_list)
|
||||
leader.wait.assert_called()
|
||||
|
||||
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
|
||||
def test_cancel_kills_resistant_child_after_recorder_exits(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
||||
for group in ("g1", "g2", "g3"):
|
||||
(plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "")
|
||||
child = root / "child.py"
|
||||
child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n")
|
||||
fake = root / "recorder.py"
|
||||
fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n")
|
||||
marker = root / "child"
|
||||
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
pid = None
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
while not marker.exists():
|
||||
if time.monotonic() >= deadline: self.fail("resistant child did not start")
|
||||
time.sleep(.01)
|
||||
pid = int(marker.read_text())
|
||||
runner.terminate()
|
||||
self.assertEqual(runner.wait(timeout=12), 130)
|
||||
deadline = time.monotonic() + 2
|
||||
while True:
|
||||
stat = Path(f"/proc/{pid}/stat")
|
||||
if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break
|
||||
if time.monotonic() >= deadline: self.fail("resistant child survived cancellation")
|
||||
time.sleep(.01)
|
||||
finally:
|
||||
if pid is not None:
|
||||
try: os.kill(pid, signal.SIGKILL)
|
||||
except ProcessLookupError: pass
|
||||
if runner.poll() is None: runner.kill()
|
||||
runner.communicate(timeout=5)
|
||||
|
||||
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
|
||||
def test_cancel_joins_every_started_group(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
||||
for group in ("g1", "g2", "g3"):
|
||||
(plan / (group + ".txt")).write_text("example/" + group + "\n")
|
||||
fake = root / "held.py"
|
||||
fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n")
|
||||
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")]
|
||||
while not all(p.exists() for p in markers):
|
||||
if time.monotonic() >= deadline: self.fail("groups did not start")
|
||||
time.sleep(.01)
|
||||
children = [int(p.read_text()) for p in markers]
|
||||
runner.terminate()
|
||||
self.assertEqual(runner.wait(timeout=10), 130)
|
||||
for child in children:
|
||||
with self.assertRaises(ProcessLookupError): os.kill(child, 0)
|
||||
finally:
|
||||
if runner.poll() is None: runner.terminate()
|
||||
runner.communicate(timeout=10)
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -1,123 +0,0 @@
|
||||
"""Run the three default unit groups concurrently on the current runner.
|
||||
|
||||
Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...]
|
||||
The recorder accepts OUTPUT followed by go-test flags and packages. Each group
|
||||
owns its logs/events; they are combined only after all group processes exit.
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def stop(_signum, _frame):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
|
||||
def terminate(processes):
|
||||
for process in processes:
|
||||
try:
|
||||
if os.name == "posix": os.killpg(process.pid, signal.SIGTERM)
|
||||
elif process.poll() is None: process.terminate()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
if os.name == "posix":
|
||||
# The leader may exit on TERM while its descendants remain in the group.
|
||||
# Bound the grace period by group lifetime, never by leader lifetime.
|
||||
deadline = time.monotonic() + 5
|
||||
remaining = list(processes)
|
||||
while remaining and time.monotonic() < deadline:
|
||||
alive = []
|
||||
for process in remaining:
|
||||
process.poll() # Reap an exited leader without forgetting its PGID.
|
||||
try:
|
||||
os.killpg(process.pid, 0)
|
||||
alive.append(process)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
remaining = alive
|
||||
if remaining: time.sleep(.05)
|
||||
for process in remaining:
|
||||
try: os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError: pass
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
|
||||
def run(plan, evidence, temp, recorder):
|
||||
groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")}
|
||||
evidence.mkdir(parents=True, exist_ok=True)
|
||||
started = time.monotonic()
|
||||
processes, results, times = {}, {}, {}
|
||||
with ExitStack() as files:
|
||||
try:
|
||||
for group, packages in groups.items():
|
||||
results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0}
|
||||
if not packages:
|
||||
print(f"{group}: no packages selected by scope", flush=True)
|
||||
continue
|
||||
out = evidence / group; out.mkdir(parents=True, exist_ok=True)
|
||||
scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True)
|
||||
# /proc/self/fd exposes resolved paths; preserve fixture identity even
|
||||
# when the runner temp directory is a symlink to its data disk.
|
||||
scratch = scratch.resolve(strict=True)
|
||||
log = files.enter_context((out / "console.log").open("w", encoding="utf-8"))
|
||||
command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages]
|
||||
times[group] = time.monotonic()
|
||||
processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
|
||||
env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix")
|
||||
print(f"{group}: started {len(packages)} packages", flush=True)
|
||||
remaining = set(processes)
|
||||
while remaining:
|
||||
for group in tuple(remaining):
|
||||
status = processes[group].poll()
|
||||
if status is not None:
|
||||
results[group]["status"] = status
|
||||
results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3)
|
||||
remaining.remove(group)
|
||||
if remaining: time.sleep(.05)
|
||||
except BaseException:
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
terminate(processes.values())
|
||||
raise
|
||||
for group in processes:
|
||||
print(f"--- {group} ---", flush=True)
|
||||
print((evidence / group / "console.log").read_text(errors="replace"), flush=True)
|
||||
summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results}
|
||||
try:
|
||||
(evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
|
||||
with (evidence / "go-test.json").open("ab") as combined:
|
||||
for group in processes:
|
||||
events = evidence / group / "go-test.json"
|
||||
if events.exists(): combined.write(events.read_bytes())
|
||||
except OSError as error:
|
||||
print(f"test evidence unavailable: {error}", file=sys.stderr)
|
||||
print(json.dumps(summary), flush=True)
|
||||
return int(any(r["status"] != 0 for r in results.values()))
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 5:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
try:
|
||||
return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:])
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"unit groups: {error}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__": sys.exit(main(sys.argv))
|
||||
@@ -1,106 +0,0 @@
|
||||
"""Exercise the actual pre-checkout and always-run cleanup workflow bodies."""
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
WORKFLOWS = sorted((ROOT / ".github/workflows").glob("block-*.yml"))
|
||||
|
||||
|
||||
def step(text, name):
|
||||
marker = " - name: " + name + "\n"
|
||||
if text.count(marker) != 1:
|
||||
raise AssertionError("missing or duplicate " + name)
|
||||
return text.split(marker, 1)[1].split("\n - name:", 1)[0]
|
||||
|
||||
|
||||
def code(block):
|
||||
return textwrap.dedent(block.split(" run: |\n", 1)[1]).split("\n", 1)[1].rsplit("\nPY", 1)[0]
|
||||
|
||||
|
||||
def execute(source, workspace, temp, free=None):
|
||||
output = io.StringIO()
|
||||
with patch.dict(os.environ, {"GITHUB_WORKSPACE": str(workspace), "RUNNER_TEMP": str(temp)}), contextlib.redirect_stdout(output):
|
||||
with contextlib.ExitStack() as stack:
|
||||
if free is not None:
|
||||
stack.enter_context(patch("shutil.disk_usage", return_value=shutil._ntuple_diskusage(100_000_000_000, 0, free)))
|
||||
try:
|
||||
exec(compile(source, "<workflow>", "exec"), {})
|
||||
except SystemExit as err:
|
||||
return err.code, output.getvalue()
|
||||
return 0, output.getvalue()
|
||||
|
||||
|
||||
class RunnerWorkspaceTests(unittest.TestCase):
|
||||
def test_every_job_checks_before_checkout_and_cleans_last_even_on_failure(self):
|
||||
for path in WORKFLOWS:
|
||||
text = path.read_text()
|
||||
before = step(text, "Runner free space")
|
||||
after = step(text, "Clean job workspace")
|
||||
self.assertLess(text.index("- name: Runner free space"), text.index("- name: Checkout"), path.name)
|
||||
self.assertIn("if: always() && runner.environment == 'self-hosted'", after)
|
||||
self.assertNotIn("continue-on-error", after)
|
||||
self.assertNotIn("- name:", text.split("- name: Clean job workspace", 1)[1])
|
||||
self.assertIn("working-directory: ${{ runner.temp }}", before)
|
||||
self.assertIn("working-directory: ${{ runner.temp }}", after)
|
||||
self.assertIn("python3 -I -", before)
|
||||
self.assertIn("python3 -I -", after)
|
||||
|
||||
def test_low_space_refuses_and_boundary_admits(self):
|
||||
for path in WORKFLOWS:
|
||||
source = code(step(path.read_text(), "Runner free space"))
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
rc, out = execute(source, root, root, 9_999_999_999)
|
||||
self.assertEqual(rc, 75)
|
||||
self.assertIn("runner_disk_low", out)
|
||||
self.assertIn("required_bytes=10000000000", out)
|
||||
self.assertEqual(execute(source, root, root, 10_000_000_000)[0], 0)
|
||||
with patch("shutil.disk_usage", side_effect=[shutil._ntuple_diskusage(100, 0, 10_000_000_000), shutil._ntuple_diskusage(100, 0, 1)]):
|
||||
rc, out = execute(source, root / "work", root / "temp")
|
||||
self.assertEqual(rc, 75)
|
||||
self.assertIn("runner_disk_low", out)
|
||||
with patch("shutil.disk_usage", side_effect=OSError("probe failed")):
|
||||
rc, out = execute(source, root, root)
|
||||
self.assertEqual(rc, 75)
|
||||
self.assertIn("runner_disk_check_failed", out)
|
||||
|
||||
def test_cleanup_removes_hidden_and_build_files_but_not_symlink_targets(self):
|
||||
for path in WORKFLOWS:
|
||||
source = code(step(path.read_text(), "Clean job workspace"))
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp); work = root / "repo/repo"; work.mkdir(parents=True)
|
||||
(work / ".git").mkdir(); (work / ".git/config").write_text("config")
|
||||
(work / "binary").write_bytes(b"build")
|
||||
outside = root / "outside"; outside.mkdir(); (outside / "keep").write_text("keep")
|
||||
(work / "link").symlink_to(outside, target_is_directory=True)
|
||||
rc, out = execute(source, work, root)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual(list(work.iterdir()), [])
|
||||
self.assertTrue((outside / "keep").is_file())
|
||||
self.assertEqual(execute(source, root, root)[0], 1)
|
||||
self.assertEqual(execute(source, Path(root.anchor), root)[0], 1)
|
||||
alias = root / "alias"; alias.symlink_to(work, target_is_directory=True)
|
||||
self.assertEqual(execute(source, alias, root)[0], 1)
|
||||
|
||||
def test_cleanup_refuses_symlinked_ancestors_and_preserves_external_sentinel(self):
|
||||
for path in WORKFLOWS:
|
||||
with self.subTest(workflow=path.name), tempfile.TemporaryDirectory() as temp:
|
||||
base = Path(temp)
|
||||
external = base / "external/repo/repo"; external.mkdir(parents=True)
|
||||
sentinel = external / "keep"; sentinel.write_text("outside checkout")
|
||||
alias = base / "alias"; alias.symlink_to(base / "external", target_is_directory=True)
|
||||
source = code(step(path.read_text(), "Clean job workspace"))
|
||||
rc, out = execute(source, alias / "repo/repo", base)
|
||||
self.assertTrue(sentinel.is_file(), "cleanup followed a workspace ancestor outside the checkout")
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("runner_workspace_cleanup_refused", out)
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -1,132 +0,0 @@
|
||||
"""Read-only block merge readiness check. Run from a trusted master checkout.
|
||||
|
||||
Usage (inside seaweed-block/): python3 ../.github/block/scripts/safe-merge-check.py PR
|
||||
Never merges, posts comments, changes account config or pushes refs.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = "seaweedfs/seaweedfs"
|
||||
WORKFLOW_PATH = ".github/workflows/block-test.yml"
|
||||
JOBS = {"go test (linux)", "process-level tests (real binaries)"}
|
||||
|
||||
|
||||
def validate(pr, run, jobs, current):
|
||||
if pr["state"] != "open" or pr["draft"] or pr["mergeable"] is not True:
|
||||
raise ValueError("PR must be open, ready and mergeable")
|
||||
if pr["base"]["ref"] != "master": raise ValueError("expected master base")
|
||||
if run.get("path") != WORKFLOW_PATH or run["name"] != "Block Test" or run["head_sha"] != pr["head"]["sha"]:
|
||||
raise ValueError("wrong workflow or head")
|
||||
if run["status"] != "completed" or run["conclusion"] != "success":
|
||||
raise ValueError("Block Test is not successful")
|
||||
bases = [p["base"]["sha"] for p in run["pull_requests"] if p["number"] == pr["number"]]
|
||||
if bases != [current]: raise ValueError("tested base is not current master")
|
||||
required = [j for j in jobs if j["name"] in JOBS]
|
||||
if len(required) != 2 or {j["name"] for j in required} != JOBS or any(j["conclusion"] != "success" for j in required):
|
||||
raise ValueError("both block test jobs must succeed")
|
||||
|
||||
|
||||
def api(path):
|
||||
return json.loads(subprocess.check_output(["gh", "api", "repos/" + REPO + "/" + path]))
|
||||
|
||||
|
||||
def successful_run(pr, current):
|
||||
runs = api("actions/runs?head_sha=" + pr["head"]["sha"] + "&event=pull_request&per_page=100")["workflow_runs"]
|
||||
runs = [r for r in runs if r.get("path") == WORKFLOW_PATH and r["name"] == "Block Test"]
|
||||
if not runs: raise ValueError("no Block Test run")
|
||||
run = max(runs, key=lambda r: (r["created_at"], r["id"]))
|
||||
pages = json.loads(subprocess.check_output(["gh", "api", "--paginate", "--slurp", "repos/" + REPO + "/actions/runs/" + str(run["id"]) + "/jobs?per_page=100"]))
|
||||
validate(pr, run, [j for page in pages for j in page["jobs"]], current)
|
||||
return run
|
||||
|
||||
|
||||
def check_control_paths(base, head):
|
||||
# Inspect both sides of renames and fail on enumeration errors. These PRs
|
||||
# need independent workflow review; their own Actions results cannot waive it.
|
||||
# Diff from the merge base: master's later control changes are not the PR's,
|
||||
# and the tested merge commit already ran them.
|
||||
bases = subprocess.check_output(["git", "merge-base", "--all", base, head]).decode("ascii").splitlines()
|
||||
if len(bases) != 1:
|
||||
raise ValueError("ambiguous_merge_base: expected exactly one merge base")
|
||||
paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", bases[0], head]).split(b"\0")
|
||||
controls = [p.decode("utf-8", errors="replace") for p in paths if p.startswith((b".github/workflows/", b".github/block/", b".github/dockerfiles/block-", b"seaweed-block/.github/"))]
|
||||
if controls:
|
||||
raise ValueError("workflow_review_required: CI controls changed: " + ", ".join(controls))
|
||||
|
||||
|
||||
def fetch_review_head(pr, current):
|
||||
if subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() != current:
|
||||
raise ValueError("run from trusted current master checkout")
|
||||
subprocess.run(["git", "-c", "fetch.fsckObjects=true", "fetch", "--no-tags", "origin", "+refs/pull/" + str(pr["number"]) + "/head:refs/remotes/block-review/head"], check=True)
|
||||
actual = subprocess.check_output(["git", "rev-parse", "refs/remotes/block-review/head"], text=True).strip()
|
||||
if actual != pr["head"]["sha"]: raise ValueError("PR head moved; recheck")
|
||||
check_control_paths(current, actual)
|
||||
return actual
|
||||
|
||||
|
||||
def local_checks(pr, current):
|
||||
actual = fetch_review_head(pr, current)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
body, title = Path(tmp) / "body", Path(tmp) / "title"
|
||||
body.write_text(pr["body"] or "", encoding="utf-8")
|
||||
title.write_text(pr["title"], encoding="utf-8")
|
||||
subprocess.run(["bash", str(Path(__file__).resolve().with_name("check-pr-base.sh")), current, actual, str(body), str(title)], check=True)
|
||||
|
||||
|
||||
def validate_batch(manifest, prs, current):
|
||||
if manifest["base"] != current: raise ValueError("master moved since batch creation")
|
||||
if not manifest["head"] or len(manifest["prs"]) < 2: raise ValueError("expected pinned batch and at least two PRs")
|
||||
numbers = [p["number"] for p in manifest["prs"]]
|
||||
if len(set(numbers)) != len(numbers) or numbers != [p["number"] for p in prs]:
|
||||
raise ValueError("batch PR order differs or repeats")
|
||||
for saved, pr in zip(manifest["prs"], prs):
|
||||
if pr["state"] != "open" or pr["draft"] or pr["base"]["ref"] != "master" or pr["head"]["sha"] != saved["head"]:
|
||||
raise ValueError("batch member is not ready or its head changed")
|
||||
if not Path(saved["evidence"]).is_file() or not Path(saved["evidence"]).read_text().strip():
|
||||
raise ValueError("batch member has no acceptance evidence")
|
||||
|
||||
|
||||
def main(args):
|
||||
current = api("git/ref/heads/master")["object"]["sha"]
|
||||
if len(args) == 2 and args[0] == "--verify-tree":
|
||||
tree = api("git/commits/" + current)["tree"]["sha"]
|
||||
if tree != args[1]: raise ValueError("master tree differs from the tested batch")
|
||||
print(json.dumps({"tree_matches": True, "master": current, "tree": tree}))
|
||||
return
|
||||
if len(args) == 2 and args[0] == "--batch":
|
||||
manifest = json.loads(Path(args[1]).read_text())
|
||||
prs = [api("pulls/" + str(p["number"])) for p in manifest["prs"]]
|
||||
validate_batch(manifest, prs, current)
|
||||
batch = api("pulls/" + str(manifest["batch_pr"]))
|
||||
if batch["head"]["sha"] != manifest["head"]: raise ValueError("batch head changed")
|
||||
fetch_review_head(batch, current)
|
||||
run = successful_run(batch, current)
|
||||
for pr in prs: local_checks(pr, current)
|
||||
if api("git/ref/heads/master")["object"]["sha"] != current: raise ValueError("master moved; recheck")
|
||||
for pr in prs + [batch]:
|
||||
if api("pulls/" + str(pr["number"]))["head"]["sha"] != pr["head"]["sha"]: raise ValueError("head moved; recheck")
|
||||
tree = api("git/commits/" + manifest["head"])["tree"]["sha"]
|
||||
# A rerun can invalidate the earlier success while local checks execute.
|
||||
run = successful_run(batch, current)
|
||||
print(json.dumps({"ready": True, "base": current, "head": manifest["head"], "run": run["id"], "tree": tree, "order": [p["number"] for p in prs]}))
|
||||
return
|
||||
if len(args) != 1 or not args[0].isdecimal(): raise ValueError("expected PR, --batch MANIFEST or --verify-tree TREE")
|
||||
pr = api("pulls/" + args[0])
|
||||
run = successful_run(pr, current)
|
||||
local_checks(pr, current)
|
||||
if api("git/ref/heads/master")["object"]["sha"] != current or api("pulls/" + args[0])["head"]["sha"] != pr["head"]["sha"]:
|
||||
raise ValueError("base or head moved; recheck")
|
||||
# Refresh the latest run and both jobs after every potentially slow check.
|
||||
run = successful_run(pr, current)
|
||||
print(json.dumps({"ready": True, "head": pr["head"]["sha"], "base": current, "run": run["id"], "merge_mode": "squash"}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main(sys.argv[1:])
|
||||
except (IndexError, KeyError, ValueError, OSError, subprocess.SubprocessError) as error:
|
||||
print("REFUSED: " + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1,52 +0,0 @@
|
||||
"""Exact coverage before scope selection; old heavy-package rules afterward."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location("planner", Path(__file__).with_name("unit-test-shards.py"))
|
||||
planner = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(planner)
|
||||
MODULE = "example.invalid/product"
|
||||
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
|
||||
|
||||
|
||||
class UnitShardTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.packages = [MODULE + "/" + p for p in (*HEAVY, "cmd/sw-block", "core/frontend/chunkstore", "internal/newpackage", "core/storage/child")]
|
||||
self.groups = planner.partition(MODULE, self.packages)
|
||||
|
||||
def test_exact_cover_and_stable_order(self):
|
||||
flat = [p for group in self.groups.values() for p in group]
|
||||
self.assertCountEqual(flat, self.packages)
|
||||
self.assertEqual(len(flat), len(set(flat)))
|
||||
self.assertEqual(self.groups, planner.partition(MODULE, list(reversed(self.packages))))
|
||||
self.assertEqual(self.groups["g1"], [MODULE + "/core/storage"])
|
||||
self.assertEqual(self.groups["g2"], [MODULE + "/" + p for p in HEAVY[1:]])
|
||||
self.assertIn(MODULE + "/internal/newpackage", self.groups["g3"])
|
||||
self.assertIn(MODULE + "/core/storage/child", self.groups["g3"])
|
||||
|
||||
def test_existing_heavy_scope_on_main_train_and_prs(self):
|
||||
all_changed = [p + "/changed.go" for p in HEAVY]
|
||||
for event, ref in (("push", ""), ("pull_request", "train/next")):
|
||||
selected = planner.select(MODULE, self.groups, event, ref, all_changed)
|
||||
self.assertEqual(selected["g1"], [])
|
||||
self.assertEqual(selected["g2"], [])
|
||||
self.assertEqual(selected["g3"], self.groups["g3"])
|
||||
self.assertEqual(planner.select(MODULE, self.groups, "pull_request", "fix/x", all_changed), self.groups)
|
||||
for path in HEAVY:
|
||||
selected = planner.select(MODULE, self.groups, "pull_request", "fix/x", [path + "/x.go"])
|
||||
heavy = selected["g1"] + selected["g2"]
|
||||
self.assertEqual(heavy, [MODULE + "/" + path])
|
||||
nested = planner.select(MODULE, self.groups, "pull_request", "fix/x", ["core/storage/child/x.go", "core/storage/"])
|
||||
self.assertEqual(nested["g1"], [])
|
||||
self.assertEqual(nested["g2"], [])
|
||||
self.assertEqual(nested["g3"], self.groups["g3"])
|
||||
|
||||
def test_invalid_inventory_is_refused(self):
|
||||
for packages in ([], self.packages + [self.packages[0]], self.packages[1:], self.packages + ["other/pkg"]):
|
||||
with self.subTest(packages=packages), self.assertRaises(ValueError):
|
||||
planner.partition(MODULE, packages)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,55 +0,0 @@
|
||||
"""Plan the default unit groups from the full go-list inventory.
|
||||
|
||||
Usage: go list ./... | python3 unit-test-shards.py MODULE OUT_DIR EVENT HEAD_REF CHANGED_FILE
|
||||
The complete partition covers every package exactly once. Existing scope rules
|
||||
then select heavy packages only on ordinary PRs that touch their direct files.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
|
||||
|
||||
|
||||
def partition(module, packages):
|
||||
if not module or any(c.isspace() for c in module):
|
||||
raise ValueError("expected one module path")
|
||||
if not packages or len(packages) != len(set(packages)):
|
||||
raise ValueError("empty package list or duplicate package")
|
||||
if any(p != module and not p.startswith(module + "/") for p in packages):
|
||||
raise ValueError("package outside the selected module")
|
||||
heavy = [module + "/" + p for p in HEAVY]
|
||||
if not set(heavy) <= set(packages):
|
||||
raise ValueError("required heavy packages missing from go list")
|
||||
return {"g1": heavy[:1], "g2": heavy[1:], "g3": sorted(set(packages) - set(heavy))}
|
||||
|
||||
|
||||
def select(module, groups, event, head_ref, changed):
|
||||
selected = set()
|
||||
if event != "push" and not head_ref.startswith("train/"):
|
||||
for p in HEAVY:
|
||||
if any(f.startswith(p + "/") and f[len(p) + 1:] and "/" not in f[len(p) + 1:] for f in changed):
|
||||
selected.add(module + "/" + p)
|
||||
return {name: [p for p in packages if name == "g3" or p in selected]
|
||||
for name, packages in groups.items()}
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 6:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
groups = partition(argv[1], sys.stdin.read().split())
|
||||
groups = select(argv[1], groups, argv[3], argv[4], Path(argv[5]).read_text().splitlines())
|
||||
out = Path(argv[2])
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
for name, packages in groups.items():
|
||||
(out / (name + ".txt")).write_text("".join(p + "\n" for p in packages), encoding="utf-8")
|
||||
print(f"{name}: {len(packages)} packages")
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"unit-test-shards: {error}", file=sys.stderr)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -1,27 +0,0 @@
|
||||
FROM golang:1.25-bookworm AS build
|
||||
|
||||
WORKDIR /src/seaweed-block
|
||||
COPY seaweed-block/go.mod seaweed-block/go.sum ./
|
||||
RUN go mod download
|
||||
COPY . /src
|
||||
RUN CGO_ENABLED=0 go build -o /out/blockcsi ./cmd/blockcsi
|
||||
# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the
|
||||
# runtime stage, so neither a build nor a push of this image can complete.
|
||||
RUN bash scripts/refuse-lab-binary.sh /out/blockcsi
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
e2fsprogs \
|
||||
kmod \
|
||||
multipath-tools \
|
||||
nvme-cli \
|
||||
open-iscsi \
|
||||
sg3-utils \
|
||||
util-linux && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=build /out/blockcsi /usr/local/bin/blockcsi
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/blockcsi"]
|
||||
@@ -1,24 +0,0 @@
|
||||
FROM golang:1.25-bookworm AS build
|
||||
|
||||
WORKDIR /src/seaweed-block
|
||||
COPY seaweed-block/go.mod seaweed-block/go.sum ./
|
||||
RUN go mod download
|
||||
COPY . /src
|
||||
RUN CGO_ENABLED=0 go build -o /out/blockmaster ./cmd/blockmaster && \
|
||||
CGO_ENABLED=0 go build -o /out/blockvolume ./cmd/blockvolume && \
|
||||
CGO_ENABLED=0 go build -o /out/sw-block ./cmd/sw-block
|
||||
# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the
|
||||
# runtime stage, so neither a build nor a push of this image can complete.
|
||||
RUN bash scripts/refuse-lab-binary.sh /out/blockmaster /out/blockvolume /out/sw-block
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends kmod && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=build /out/blockmaster /usr/local/bin/blockmaster
|
||||
COPY --from=build /out/blockvolume /usr/local/bin/blockvolume
|
||||
COPY --from=build /out/sw-block /usr/local/bin/sw-block
|
||||
|
||||
USER 65532:65532
|
||||
@@ -1,127 +0,0 @@
|
||||
name: Block known bugs
|
||||
|
||||
# Nightly: every open-issue reproduction that is skipped by default (t.Skip unless
|
||||
# SEAWEED_KNOWN_BUGS=1) runs and is EXPECTED TO FAIL. If one passes, its bug is
|
||||
# fixed but its skip is still in place: this job fails and names it, so the skip
|
||||
# is removed in the fix PR (or right after). A fix PR removes the test's line here
|
||||
# together with its skip.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 6 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: seaweed-block
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
known-bugs:
|
||||
name: known-bug reproductions still fail
|
||||
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
SEAWEED_KNOWN_BUGS: "1"
|
||||
steps:
|
||||
- name: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Runner disk is NVMe
|
||||
# A self-hosted runner whose work, temp or Go cache directory sits on a
|
||||
# SATA system disk times the process-level tests out under disk load;
|
||||
# this names the runner and stops the job before it starts.
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: |
|
||||
bash .github/scripts/require-nvme-test.sh
|
||||
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: seaweed-block/go.mod
|
||||
cache: false
|
||||
|
||||
- name: Known-bug verdict controls
|
||||
run: bash .github/scripts/known-bugs-test.sh
|
||||
|
||||
- name: Each reproduction still fails
|
||||
run: |
|
||||
bash .github/scripts/known-bugs.sh <<'LIST'
|
||||
#186 ./cmd/blockmaster/ TestChartOptInLoopbackFlagIsAcceptedByBlockmaster
|
||||
LIST
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,146 +0,0 @@
|
||||
name: Block post-merge-review paths
|
||||
|
||||
# A PR labelled "post-merge-review" may merge before its full review only if
|
||||
# every changed file is allowed by .github/post-merge-review-allow.txt.
|
||||
# This check fails such a PR otherwise; without the label it passes.
|
||||
#
|
||||
# pull_request_target: the workflow, the allow list and the script all come
|
||||
# from the base branch, so a PR cannot change its own check. The PR's code is
|
||||
# never checked out or run: only its commit is fetched, for the file list.
|
||||
on:
|
||||
pull_request_target:
|
||||
paths:
|
||||
- "seaweed-block/**"
|
||||
- ".github/workflows/block-*.yml"
|
||||
- ".github/block/**"
|
||||
- ".github/dockerfiles/block-*.Dockerfile"
|
||||
# edited: a retarget changes the base, and with it the diff.
|
||||
types: [opened, synchronize, reopened, labeled, unlabeled, edited]
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: seaweed-block
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: block-post-merge-review-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
paths:
|
||||
name: post-merge-review paths
|
||||
# GitHub-hosted: on the self-hosted runners this job ended in 'Set up
|
||||
# job' with no log on every runner (2026-11-29), while spec trace, on the
|
||||
# same runners, passes. Unlabelled PRs only echo here, so the hosted
|
||||
# queue costs little; the merge gate does not wait for it unless the PR
|
||||
# is labelled.
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- name: Not labelled
|
||||
if: ${{ !contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
|
||||
working-directory: ${{ github.workspace }}
|
||||
run: echo "no post-merge-review label; nothing to check"
|
||||
|
||||
- name: Checkout base
|
||||
if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.base.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check changed paths
|
||||
if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
|
||||
env:
|
||||
BASE: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD: ${{ github.event.pull_request.head.sha }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash .github/scripts/post-merge-review-check-test.sh
|
||||
git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head"
|
||||
bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
|
||||
# The allow list speaks for the module only: any host file keeps the full review.
|
||||
git -C .. diff -z --name-only --no-renames "$BASE...$HEAD" -- . ':(exclude)seaweed-block/' \
|
||||
':(exclude).github/workflows/block-*.yml' ':(exclude).github/dockerfiles/block-*.Dockerfile' ':(exclude).github/block/**' >host.bin
|
||||
host=0
|
||||
while IFS= read -r -d '' path; do
|
||||
printf 'DENY host %q (outside seaweed-block)\n' "$path"
|
||||
host=1
|
||||
done <host.bin
|
||||
bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt <changed.bin
|
||||
exit "$host"
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,220 +0,0 @@
|
||||
name: Publish block release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- "seaweed-block/v*"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
BLOCK_IMAGE: ghcr.io/seaweedfs/seaweed-block
|
||||
CSI_IMAGE: ghcr.io/seaweedfs/seaweed-block-csi
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
# Publish only from a version tag; a manual run from a branch must not move :alpha.
|
||||
if: startsWith(github.ref, 'refs/tags/seaweed-block/v')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # the tag list decides whether :alpha moves
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Compute image tags
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# vX.Y.Z-pre (a release candidate) publishes only its own version tag. A stable vX.Y.Z also
|
||||
# publishes sha-*, and moves :alpha only when it is the highest stable version tag, so a later
|
||||
# patch on an older line never moves :alpha back.
|
||||
short_sha="${GITHUB_SHA::12}"
|
||||
version="${GITHUB_REF_NAME#seaweed-block/}"
|
||||
if [[ ! "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then
|
||||
echo "refusing to publish: tag ${version} is not vX.Y.Z or vX.Y.Z-pre" >&2
|
||||
exit 1
|
||||
fi
|
||||
notes="seaweed-block/docs/releases/${version%%-*}.md"
|
||||
if [[ ! -s "${notes}" ]]; then
|
||||
echo "refusing to publish: release notes ${notes} are missing or empty" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "notes=${notes}" >> "$GITHUB_OUTPUT"
|
||||
stable=false
|
||||
move_alpha=false
|
||||
if [[ "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
stable=true
|
||||
highest="$(git tag -l 'seaweed-block/v*' | sed 's|^seaweed-block/||' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)"
|
||||
if [[ "${version}" == "${highest}" ]]; then
|
||||
move_alpha=true
|
||||
fi
|
||||
fi
|
||||
{
|
||||
echo "block_tags<<EOF"
|
||||
echo "${BLOCK_IMAGE}:${version}"
|
||||
if [[ "${stable}" == true ]]; then echo "${BLOCK_IMAGE}:sha-${short_sha}"; fi
|
||||
if [[ "${move_alpha}" == true ]]; then echo "${BLOCK_IMAGE}:alpha"; fi
|
||||
echo "EOF"
|
||||
echo "csi_tags<<EOF"
|
||||
echo "${CSI_IMAGE}:${version}"
|
||||
if [[ "${stable}" == true ]]; then echo "${CSI_IMAGE}:sha-${short_sha}"; fi
|
||||
if [[ "${move_alpha}" == true ]]; then echo "${CSI_IMAGE}:alpha"; fi
|
||||
echo "EOF"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push block image
|
||||
id: block
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: .github/dockerfiles/block-sw-block.Dockerfile
|
||||
platforms: linux/amd64
|
||||
push: true
|
||||
tags: ${{ steps.tags.outputs.block_tags }}
|
||||
|
||||
- name: Build and push CSI image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: .github/dockerfiles/block-blockcsi.Dockerfile
|
||||
platforms: linux/amd64
|
||||
push: true
|
||||
tags: ${{ steps.tags.outputs.csi_tags }}
|
||||
|
||||
- name: Publish matching binary tarball
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
BLOCK_DIGEST: ${{ steps.block.outputs.digest }}
|
||||
NOTES: ${{ steps.tags.outputs.notes }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#seaweed-block/}"
|
||||
out="$RUNNER_TEMP/block-release"
|
||||
mkdir -p "$out/bin"
|
||||
docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"
|
||||
container=$(docker create "${BLOCK_IMAGE}@${BLOCK_DIGEST}")
|
||||
trap 'docker rm "$container" >/dev/null' EXIT
|
||||
for binary in blockmaster blockvolume sw-block; do
|
||||
docker cp "$container:/usr/local/bin/$binary" "$out/bin/$binary"
|
||||
done
|
||||
bash seaweed-block/scripts/refuse-lab-binary.sh "$out/bin/"*
|
||||
cp seaweed-block/deploy/systemd/sw-block.tmpfiles.conf "$out/bin/sw-block.tmpfiles.conf"
|
||||
asset="sw-block-${version}-linux-amd64.tar.gz"
|
||||
tar -C "$out/bin" -czf "$out/$asset" blockmaster blockvolume sw-block sw-block.tmpfiles.conf
|
||||
# Before any upload: every binary in the asset is executable as shipped (tar tvf).
|
||||
# The listing is taken first, so a failed listing stops the job here.
|
||||
listing=$(tar -tvzf "$out/$asset")
|
||||
executables=0
|
||||
while read -r perms _ _ _ _ name; do
|
||||
case "$name" in
|
||||
blockmaster|blockvolume|sw-block)
|
||||
if [[ ! "$perms" =~ ^-..x..x..x$ ]]; then
|
||||
echo "refusing to publish: $name in $asset is $perms, not executable" >&2
|
||||
exit 1
|
||||
fi
|
||||
executables=$((executables + 1)) ;;
|
||||
esac
|
||||
done <<<"$listing"
|
||||
if [ "$executables" != 3 ]; then
|
||||
echo "refusing to publish: $asset lists $executables of 3 binaries" >&2
|
||||
exit 1
|
||||
fi
|
||||
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
|
||||
prerelease=false
|
||||
if [[ "$version" == *-* ]]; then prerelease=true; fi
|
||||
# A rerun replaces the assets, then publishes a draft an interrupted run left.
|
||||
if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber
|
||||
gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --verify-tag --latest=false \
|
||||
--prerelease="$prerelease" --title "Seaweed Block $version" --notes-file "$NOTES"
|
||||
fi
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,164 +0,0 @@
|
||||
name: Block spec trace
|
||||
|
||||
# Every PR description carries the spec trace (see the PR template); this
|
||||
# check fails a PR whose description does not.
|
||||
#
|
||||
# pull_request_target: the workflow and the script come from the base branch,
|
||||
# so a PR cannot change its own check. The PR's code is never checked out or
|
||||
# run: only its commit is fetched, for the file list. The description is read
|
||||
# from the event through an environment variable, never interpolated.
|
||||
on:
|
||||
pull_request_target:
|
||||
paths:
|
||||
- "seaweed-block/**"
|
||||
- ".github/workflows/block-*.yml"
|
||||
- ".github/block/**"
|
||||
- ".github/dockerfiles/block-*.Dockerfile"
|
||||
# edited: the check reads the description and the base.
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: seaweed-block
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: block-spec-trace-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
trace:
|
||||
name: spec trace
|
||||
# The base-owned check defaults to a disposable hosted runner. Only a
|
||||
# same-repository PR may opt into the registered BLOCK_RUNNER_LABEL.
|
||||
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
# github.sha is the tip of the base branch when the event fires; the
|
||||
# PR's base.sha can predate this workflow's own scripts.
|
||||
ref: ${{ github.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
# spec-trace-check.sh builds the trusted sametokens.go; a self-hosted
|
||||
# runner has no Go on its PATH unless the job sets it up.
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: seaweed-block/go.mod
|
||||
cache: false
|
||||
|
||||
- name: Check spec trace
|
||||
env:
|
||||
BASE: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD: ${{ github.event.pull_request.head.sha }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
BODY: ${{ github.event.pull_request.body }}
|
||||
TITLE: ${{ github.event.pull_request.title }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash .github/scripts/spec-trace-check-test.sh
|
||||
python3 -B .github/scripts/model-trace-check-test.py
|
||||
bash .github/scripts/changed-go-blobs-test.sh
|
||||
# fsckObjects: a PR's objects are checked as they arrive, so a tree
|
||||
# with a '..' or '.git' entry is refused here.
|
||||
git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head"
|
||||
printf '%s' "$BODY" >body.txt
|
||||
bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
|
||||
# Old and new blobs of each changed non-test Go file, for kind DOCS
|
||||
# (objects only; a path that would leave blobs/ is refused).
|
||||
mb=$(git merge-base "$BASE" "$HEAD")
|
||||
bash ../.github/block/scripts/changed-go-blobs.sh "$mb" "$HEAD" blobs
|
||||
# Mapping and validator come from the trusted base checkout above.
|
||||
bash .github/scripts/spec-trace-check.sh body.txt blobs .github/model-code-trace.tsv <changed.bin
|
||||
# Internal names stay out of this public repository: added lines,
|
||||
# commit messages, title and description (no PR code is run).
|
||||
bash .github/scripts/public-text-check-test.sh
|
||||
printf '%s' "$TITLE" >title.txt
|
||||
bash ../.github/block/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt
|
||||
|
||||
- name: Invariants ledger anchors (report only)
|
||||
# Every code and test anchor of docs/design/invariants.md must exist at
|
||||
# the PR's commit (git objects only; nothing from the PR is run). It
|
||||
# reports and does not fail the check while the known imprecise
|
||||
# anchors are being corrected; then this step becomes gating.
|
||||
continue-on-error: true
|
||||
env:
|
||||
HEAD: ${{ github.event.pull_request.head.sha }}
|
||||
run: python3 -I ../.github/block/scripts/ledger_check.py "$GITHUB_WORKSPACE" "$HEAD" seaweed-block/docs/design/invariants.md seaweed-block/ || true
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -1,449 +0,0 @@
|
||||
name: Block Test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "seaweed-block/**"
|
||||
- ".github/workflows/block-*.yml"
|
||||
- ".github/block/**"
|
||||
- ".github/dockerfiles/block-*.Dockerfile"
|
||||
# ready_for_review: a Draft runs no Go suite (below); marking it ready starts one.
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
push:
|
||||
paths:
|
||||
- "seaweed-block/**"
|
||||
- ".github/workflows/block-*.yml"
|
||||
- ".github/block/**"
|
||||
- ".github/dockerfiles/block-*.Dockerfile"
|
||||
branches:
|
||||
- master
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: seaweed-block
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# One run per PR (or per commit for pushes). A new push to a PR cancels the
|
||||
# superseded run; a queued master run would be replaced by a newer one in a
|
||||
# shared group, so each merge gets its own group and its own result.
|
||||
concurrency:
|
||||
group: block-test-${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
# One job, two suites, one runner selection. 'unit' is the Go suite below;
|
||||
# 'process' runs the process-level tests: real blockmaster, blockvolume and
|
||||
# sw-block against a pinned SeaweedFS release. Those tests are named in
|
||||
# .github/process-level-tests.txt, and every one must PASS, so a test that
|
||||
# skips, fails, never starts or is cut off by the timeout fails the suite.
|
||||
# Tests that need root or systemd are not in the list (see its header).
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
suite: [unit, process]
|
||||
name: ${{ matrix.suite == 'unit' && 'go test (linux)' || 'process-level tests (real binaries)' }}
|
||||
# The suite writes heavily to the runner disk (real files, fsync), so a
|
||||
# Draft PR skips it; its author tests locally until the PR is ready.
|
||||
if: github.event_name == 'push' || !github.event.pull_request.draft
|
||||
# Hosted by default until this repository has a registered block pool.
|
||||
# Set BLOCK_RUNNER_LABEL only for an available dedicated label. Forks
|
||||
# always stay on disposable GitHub-hosted runners.
|
||||
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
|
||||
# process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence).
|
||||
timeout-minutes: ${{ matrix.suite == 'unit' && 60 || 90 }}
|
||||
env:
|
||||
# Pure-Go build: no package in the default build needs cgo, and the
|
||||
# hosted runner should not depend on a C toolchain being present.
|
||||
CGO_ENABLED: "0"
|
||||
steps:
|
||||
- name: Runner free space
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
required = 10_000_000_000
|
||||
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
|
||||
try:
|
||||
free = shutil.disk_usage(path).free
|
||||
except OSError as err:
|
||||
print(f"runner_disk_check_failed path={path!r} error={err}")
|
||||
sys.exit(75)
|
||||
if free < required:
|
||||
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
|
||||
sys.exit(75)
|
||||
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
|
||||
PY
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
# Two commits: the PR merge commit and its base parent, so the test
|
||||
# step can see which packages the PR touches.
|
||||
fetch-depth: 2
|
||||
|
||||
- name: Nested module CI contracts
|
||||
run: |
|
||||
python3 -I ../.github/block/scripts/block-ci-port-test.py
|
||||
python3 -B ../.github/block/scripts/runner-workspace-test.py
|
||||
|
||||
- name: Relative documentation links
|
||||
if: matrix.suite == 'unit'
|
||||
run: |
|
||||
python3 -B ../.github/block/scripts/doc-links-check-test.py
|
||||
python3 -I ../.github/block/scripts/doc-links-check.py .
|
||||
|
||||
- name: Release binary archive contract
|
||||
if: matrix.suite == 'unit'
|
||||
run: python3 -I .github/scripts/release-binary-assets-test.py
|
||||
|
||||
- name: Runner disk is NVMe
|
||||
# A self-hosted runner whose work, temp or Go cache directory sits on a
|
||||
# SATA system disk times the process-level tests out under disk load;
|
||||
# this names the runner and stops the job before it starts.
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: |
|
||||
bash .github/scripts/require-nvme-test.sh
|
||||
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
|
||||
|
||||
- name: Start whole-job load evidence
|
||||
# Begins after checkout, before toolchain setup/build/tests. No host
|
||||
# installation or privileged reads. A job-sized lifetime also bounds
|
||||
# the sampler if cancellation prevents the stop step.
|
||||
continue-on-error: true
|
||||
env:
|
||||
CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
run: |
|
||||
echo "CI_EVIDENCE_DIR=$CI_EVIDENCE_DIR" >>"$GITHUB_ENV"
|
||||
mkdir -p "$CI_EVIDENCE_DIR"
|
||||
: >"$CI_EVIDENCE_DIR/go-test.json"
|
||||
python3 -I .github/scripts/ci-load.py start "$CI_EVIDENCE_DIR/load.tsv" --duration ${{ matrix.suite == 'unit' && 2400 || 5400 }}
|
||||
|
||||
- name: Self-test evidence capture
|
||||
run: |
|
||||
python3 -B .github/scripts/ci-load-test.py
|
||||
bash .github/scripts/record-go-test-test.sh
|
||||
|
||||
- name: Docs-only pull request
|
||||
id: scope
|
||||
if: matrix.suite == 'process' && github.event_name == 'pull_request'
|
||||
# A pull request that changes only files under docs/ runs no product
|
||||
# code the process-level tests could exercise, so they are skipped and
|
||||
# the job still reports success. HEAD is the merge commit, HEAD^1 its
|
||||
# base parent (fetch-depth 2 above). Pushes to main always run them, and
|
||||
# so does any error of the check (../.github/block/scripts/docs-only-scope.sh).
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash .github/scripts/docs-only-scope-test.sh
|
||||
if out=$(bash ../.github/block/scripts/docs-only-scope.sh HEAD^1 HEAD); then
|
||||
case $out in
|
||||
"docs_only "*)
|
||||
echo "skipped: docs only (${out#docs_only } files under docs/); the process-level tests run on the merge to main"
|
||||
echo "docs_only=1" >>"$GITHUB_OUTPUT" ;;
|
||||
*) echo "process-level tests run: $out" ;;
|
||||
esac
|
||||
else
|
||||
echo "process-level tests run: the docs-only check failed"
|
||||
fi
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: seaweed-block/go.mod
|
||||
# The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk;
|
||||
# uploading them as an Actions cache (~4 GB) in the post step
|
||||
# outlasted the job timeout after every test had passed. Only the
|
||||
# GitHub-hosted (fork PR) runner uses the Actions cache.
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
cache-dependency-path: seaweed-block/go.sum
|
||||
|
||||
- name: Go version
|
||||
if: matrix.suite == 'unit'
|
||||
run: go version
|
||||
|
||||
- name: Build
|
||||
if: matrix.suite == 'unit'
|
||||
run: go build ./...
|
||||
|
||||
- name: Vet
|
||||
if: matrix.suite == 'unit'
|
||||
run: go vet ./...
|
||||
|
||||
- name: Lab build tags stay out of images and releases
|
||||
if: matrix.suite == 'unit'
|
||||
# swblock_lab_bigvol lifts the 1 TiB create cap and the local
|
||||
# headroom refusal for scale rehearsals only; swblock_v11_format turns
|
||||
# on the draft v1.1 store format. The default test run pins the
|
||||
# release cap (TestReleaseBuildKeepsTheCreateCap) and the release
|
||||
# format. This step checks the tags' allowlist and that every image
|
||||
# Dockerfile refuses a lab binary (scripts/refuse-lab-binary.sh) after
|
||||
# its build, with controls, then tests each tag alone and both.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash .github/scripts/lab-tag-check.sh .
|
||||
bash .github/scripts/lab-tag-check-test.sh
|
||||
for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do
|
||||
go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/
|
||||
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'Lab|Headroom|Revision|LegacyBound' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/
|
||||
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/
|
||||
done
|
||||
|
||||
- name: Test default configuration
|
||||
if: matrix.suite == 'unit'
|
||||
# Preserve the existing scope: main/train omit the four heavy packages;
|
||||
# ordinary PRs add each only when its direct package files are touched.
|
||||
# Three subprocesses share this ONE runner: storage, durable plus touched
|
||||
# master/authority, and the remaining selected packages at -p=4.
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
HEAD_REF: ${{ github.head_ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 -I ../.github/block/scripts/unit-test-shards-test.py
|
||||
python3 -I ../.github/block/scripts/run-unit-groups-test.py
|
||||
plan="$RUNNER_TEMP/unit-groups"
|
||||
mkdir -p "$plan"
|
||||
go list ./... >"$plan/all.txt"
|
||||
mod=$(go list -m)
|
||||
# Main pushes need no changed-path list; a shallow initial push may
|
||||
# have no parent. Ordinary PRs use the merge commit's base parent.
|
||||
: >"$plan/changed.txt"
|
||||
if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then
|
||||
git diff --relative --name-only --no-renames HEAD^1 HEAD -- . >"$plan/changed.txt"
|
||||
fi
|
||||
python3 -I ../.github/block/scripts/unit-test-shards.py "$mod" "$plan" "$EVENT" "$HEAD_REF" "$plan/changed.txt" <"$plan/all.txt"
|
||||
python3 -I ../.github/block/scripts/run-unit-groups.py "$plan" "$CI_EVIDENCE_DIR" "$RUNNER_TEMP/unit-group-tmp" \
|
||||
bash .github/scripts/record-go-test.sh
|
||||
|
||||
- name: Format v3 tagged tests
|
||||
if: matrix.suite == 'unit'
|
||||
# The swblock_format_v3_test tests of the four packages that carry them.
|
||||
# Five durable tests are skipped by name: each installs a BASE on a chunk
|
||||
# store, which no production path does (its invariant row is DORMANT);
|
||||
# they are rewritten at the start of the next release, then this skip
|
||||
# goes.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
skip='^(TestDurableProviderV3_AttachesCompletedChunkBASE|TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD|TestDurableProviderV3_DefersBASERetirementUntilLocalPresence|TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE|TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE)$'
|
||||
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -count=1 -timeout 20m -tags swblock_format_v3_test -skip "$skip" \
|
||||
./core/frontend/durable/ ./core/recovery/ ./core/replication/ ./core/transport/
|
||||
|
||||
- name: Self-test of the required-tests gate
|
||||
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
|
||||
# The gate must fail on a skip, a failure, a test that never ran, one
|
||||
# cut off mid-run, and one that reports PASS and then exits nonzero or
|
||||
# hangs; this proves it before it judges the real run.
|
||||
run: |
|
||||
python3 -I .github/scripts/required-tests-check-test.py
|
||||
bash .github/scripts/chunkstore-scope-test.sh
|
||||
bash .github/scripts/run-named-tests-test.sh
|
||||
python3 -I .github/scripts/shard-named-tests-test.py
|
||||
|
||||
- name: Pinned SeaweedFS
|
||||
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
|
||||
# The release archive is checked against its sha256 before every use,
|
||||
# also when taken from the runner's cache; a mismatch fails the step.
|
||||
# Nothing else is fetched.
|
||||
env:
|
||||
WEED_VERSION: "4.53"
|
||||
WEED_SHA256: d1a7dec9f48d8b33895a0ea8951971defc2dc5312906dcc76fa5a5f74a6ee90d
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cache="${RUNNER_TOOL_CACHE:-$RUNNER_TEMP}/seaweedfs-weed/$WEED_VERSION"
|
||||
tgz="$cache/linux_amd64.tar.gz"
|
||||
mkdir -p "$cache"
|
||||
if ! echo "$WEED_SHA256 $tgz" | sha256sum -c --status - 2>/dev/null; then
|
||||
part="$tgz.$$.part"
|
||||
curl -fsSL --retry 3 -o "$part" "https://github.com/seaweedfs/seaweedfs/releases/download/$WEED_VERSION/linux_amd64.tar.gz"
|
||||
echo "$WEED_SHA256 $part" | sha256sum -c - || { rm -f "$part"; exit 1; }
|
||||
mv -f "$part" "$tgz"
|
||||
fi
|
||||
bin="$RUNNER_TEMP/weed-$WEED_VERSION"
|
||||
mkdir -p "$bin"
|
||||
tar -xzf "$tgz" -C "$bin" weed
|
||||
echo "CHUNKSTORE_WEED=$bin/weed" >>"$GITHUB_ENV"
|
||||
|
||||
- name: Real-filer integration tests
|
||||
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
|
||||
# The chunkstore_integration tests run against the pinned weed above
|
||||
# (master, volume and filer as real processes): the conditional HEAD
|
||||
# writes, cut uploads and object deletes of the chunk store, and the
|
||||
# layout sync crash cases of the durable provider. They fail, never
|
||||
# skip, without the binary. Pushes to main and train PRs always run
|
||||
# them; another PR runs them when it touches core/frontend/chunkstore/,
|
||||
# core/storage/ or core/frontend/durable/.
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
HEAD_REF: ${{ github.head_ref }}
|
||||
# ../.github/block/scripts/chunkstore-scope.sh decides; an error of that check
|
||||
# runs the tests. Each filtered run must PASS at least one test, so a
|
||||
# filter that matches nothing fails instead of passing empty.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then
|
||||
if out=$(bash ../.github/block/scripts/chunkstore-scope.sh HEAD^1 HEAD); then
|
||||
case $out in
|
||||
"skip "*) echo "skipped: the PR touches neither core/frontend/chunkstore/ nor core/storage/ ($out)"; exit 0 ;;
|
||||
*) echo "real-filer integration tests run: $out" ;;
|
||||
esac
|
||||
else
|
||||
echo "real-filer integration tests run: the scope check failed"
|
||||
fi
|
||||
fi
|
||||
for spec in "./core/frontend/chunkstore/ ^TestIntegration" "./core/frontend/durable/ ^TestQD1LayoutSync"; do
|
||||
pkg=${spec%% *}; filter=${spec#* }
|
||||
log="$RUNNER_TEMP/integration-$(basename "$pkg").log"
|
||||
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -v -timeout 20m -tags chunkstore_integration -run "$filter" "$pkg" 2>&1 | tee "$log"
|
||||
grep -q '^--- PASS: ' "$log" || { echo "no test of $pkg matched $filter"; exit 1; }
|
||||
done
|
||||
|
||||
- name: Build the binaries and the test binary once
|
||||
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bins="$RUNNER_TEMP/swblock-bins"
|
||||
mkdir -p "$bins"
|
||||
for b in blockmaster blockvolume sw-block; do go build -o "$bins/$b" "./cmd/$b"; done
|
||||
go test -c -tags 'subprocess chunkstore_integration' -o "$bins/blockvolume.test" ./cmd/blockvolume
|
||||
go test -c -o "$bins/blockcsi.test" ./cmd/blockcsi
|
||||
# The known-zero acceptance's first-start crash step holds a test-only
|
||||
# blockvolume (build tag kzhold, never released) at a chosen point.
|
||||
go build -tags kzhold -o "$RUNNER_TEMP/blockvolume-kzhold" ./cmd/blockvolume
|
||||
echo "SWBLOCK_TEST_BINS=$bins" >>"$GITHUB_ENV"
|
||||
echo "KZ_HOLD_BIN=$RUNNER_TEMP/blockvolume-kzhold" >>"$GITHUB_ENV"
|
||||
|
||||
- name: Run the named process-level tests
|
||||
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
|
||||
# Each named test in its own process of the one test binary, in
|
||||
# sequence, so a panic or a hang in one cannot hide the others; each
|
||||
# is bounded (TEST_TIMEOUT, then killed) and its exit status is kept:
|
||||
# the gate needs a PASS event AND exit 0 for every named test. The known-zero acceptance
|
||||
# runs its small shape (1 GiB, user-space client, no device); the
|
||||
# 1 TiB run is lab only.
|
||||
env:
|
||||
KZ_RUN: "1"
|
||||
KZ_SIZE: 1G
|
||||
F1_RUN: "1"
|
||||
TEST_TIMEOUT: 15m
|
||||
# A failed test copies each daemon's whole log here (keepFullLog);
|
||||
# the step below keeps them as the run's artifact.
|
||||
SWBLOCK_TEST_LOG_DIR: ${{ env.CI_EVIDENCE_DIR }}/daemon-logs
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# SHARDS parallel shards, balanced by their last measured times
|
||||
# (.github/process-level-seconds.txt). Each shard is its own sequence
|
||||
# of test processes with its own slice of the test port ranges
|
||||
# (SWBLOCK_TEST_PORT_SHARD) and its own TMPDIR; the gate judges every
|
||||
# named test from all the shards together.
|
||||
names=.github/process-level-tests.txt
|
||||
# The manifest tags CSI entries; every other name uses blockvolume.test.
|
||||
# The final checker still requires the complete, unsplit manifest.
|
||||
awk '!/# package=blockcsi/' "$names" > "$RUNNER_TEMP/blockvolume-names.txt"
|
||||
awk '/# package=blockcsi/ {sub(/#.*/, ""); if ($0 ~ /[^[:space:]]/) print}' "$names" > "$RUNNER_TEMP/blockcsi-names.txt"
|
||||
test -s "$RUNNER_TEMP/blockcsi-names.txt"
|
||||
shards=4
|
||||
python3 -I .github/scripts/shard-named-tests.py "$RUNNER_TEMP/blockvolume-names.txt" .github/process-level-seconds.txt "$shards" "$RUNNER_TEMP/shard"
|
||||
pids=()
|
||||
for k in $(seq 1 "$shards"); do
|
||||
mkdir -p "$RUNNER_TEMP/tmp-$k"
|
||||
SWBLOCK_TEST_PORT_SHARD=$k SWBLOCK_TEST_PORT_SHARDS=$shards TMPDIR="$RUNNER_TEMP/tmp-$k" \
|
||||
bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockvolume.test" "$RUNNER_TEMP/shard/$k.txt" \
|
||||
"$RUNNER_TEMP/process-level-$k.json" "$RUNNER_TEMP/process-level-$k.status" "$TEST_TIMEOUT" cmd/blockvolume \
|
||||
>"$RUNNER_TEMP/process-level-$k.log" 2>&1 &
|
||||
pids+=($!)
|
||||
done
|
||||
for p in "${pids[@]}"; do wait "$p" || true; done
|
||||
for k in $(seq 1 "$shards"); do sed "s/^/[shard $k] /" "$RUNNER_TEMP/process-level-$k.log"; done
|
||||
# CSI uses the same per-case isolation, timeout and verdict as the shards.
|
||||
TEST_PKG=github.com/seaweedfs/seaweed-block/cmd/blockcsi \
|
||||
bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockcsi.test" "$RUNNER_TEMP/blockcsi-names.txt" \
|
||||
"$RUNNER_TEMP/process-level-csi.json" "$RUNNER_TEMP/process-level-csi.status" "$TEST_TIMEOUT" cmd/blockcsi \
|
||||
>"$RUNNER_TEMP/process-level-csi.log" 2>&1 || true
|
||||
cat "$RUNNER_TEMP/process-level-csi.log"
|
||||
cat "$RUNNER_TEMP"/process-level-*.status >"$RUNNER_TEMP/process-level.status"
|
||||
python3 -I .github/scripts/required-tests-check.py --status "$RUNNER_TEMP/process-level.status" \
|
||||
"$names" "$RUNNER_TEMP"/process-level-*.json
|
||||
|
||||
- name: Stop load evidence and collect raw process events
|
||||
if: always()
|
||||
continue-on-error: true
|
||||
env:
|
||||
SUITE: ${{ matrix.suite }}
|
||||
run: |
|
||||
if [ -z "${CI_EVIDENCE_DIR:-}" ]; then exit 0; fi
|
||||
python3 -I .github/scripts/ci-load.py stop "$CI_EVIDENCE_DIR/load.tsv" || true
|
||||
if [ "$SUITE" = process ]; then
|
||||
mkdir -p "$CI_EVIDENCE_DIR/shards"
|
||||
shopt -s nullglob
|
||||
for file in "$RUNNER_TEMP"/process-level-*.json "$RUNNER_TEMP"/process-level-*.log "$RUNNER_TEMP"/process-level*.status; do
|
||||
cp "$file" "$CI_EVIDENCE_DIR/shards/"
|
||||
done
|
||||
for file in "$CI_EVIDENCE_DIR"/shards/*.json; do cat "$file" >>"$CI_EVIDENCE_DIR/go-test.json"; done
|
||||
fi
|
||||
|
||||
- name: Keep failed-job tests, load, daemon logs and shard results
|
||||
# Both suites retain timed events and whole-job load. Process evidence
|
||||
# also retains the original shard receipts and full daemon logs.
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: ${{ env.CI_EVIDENCE_DIR }}
|
||||
retention-days: 14
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Clean job workspace
|
||||
# Hosted runners are disposable; their setup-go cache upload runs in
|
||||
# a post action and still needs the checkout. Persistent runners do not
|
||||
# upload that cache, and must release their checkout/build files here.
|
||||
if: always() && runner.environment == 'self-hosted'
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
python3 -I - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
root = Path(os.environ["GITHUB_WORKSPACE"])
|
||||
# Refuse aliases rather than resolving them. Open EVERY component without
|
||||
# following symlinks, then keep cleanup anchored to the verified directory fd.
|
||||
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
|
||||
sys.exit(1)
|
||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
fd = os.open(root.anchor, flags)
|
||||
previous = os.open(".", flags)
|
||||
errors = []
|
||||
try:
|
||||
for part in root.parts[1:]:
|
||||
child = os.open(part, flags, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise OSError("descriptor-safe directory removal is unavailable")
|
||||
os.fchdir(fd)
|
||||
for entry in os.scandir("."):
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
shutil.rmtree(entry.name)
|
||||
else:
|
||||
os.unlink(entry.name)
|
||||
except OSError as err:
|
||||
errors.append(f"{entry.name}: {err}")
|
||||
except OSError as err:
|
||||
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
os.fchdir(previous)
|
||||
os.close(previous)
|
||||
os.close(fd)
|
||||
if errors:
|
||||
print("runner_workspace_cleanup_failed " + "; ".join(errors))
|
||||
sys.exit(1)
|
||||
print(f"runner_workspace_clean path={str(root)!r}")
|
||||
PY
|
||||
@@ -9,7 +9,6 @@ on:
|
||||
- 'weed/storage/volume_vacuum*.go'
|
||||
- 'weed/storage/volume_loading.go'
|
||||
- 'weed/storage/disk_location.go'
|
||||
- 'weed/server/filer_grpc_server_rename.go'
|
||||
- 'test/winfsp/**'
|
||||
- '.github/workflows/mount-windows.yml'
|
||||
# No base branch filter: this is the only thing that runs the Windows mount,
|
||||
@@ -21,7 +20,6 @@ on:
|
||||
- 'weed/storage/volume_vacuum*.go'
|
||||
- 'weed/storage/volume_loading.go'
|
||||
- 'weed/storage/disk_location.go'
|
||||
- 'weed/server/filer_grpc_server_rename.go'
|
||||
- 'test/winfsp/**'
|
||||
- '.github/workflows/mount-windows.yml'
|
||||
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
name: "release: bump version and cut the release"
|
||||
|
||||
# One entry point for a SeaweedFS release:
|
||||
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, point the
|
||||
# chart's cosi.image at the newest COSI driver release, commit to master
|
||||
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, commit to master
|
||||
# 2. push the <appVersion> tag, which fans out to the workflows that trigger on
|
||||
# `push: tags` (binaries_release*, container_release_unified, helm_manual_release)
|
||||
# 3. create the GitHub release, with GitHub's generated notes
|
||||
# 4. dispatch "Prepare release" in seaweedfs-csi-driver, seaweedfs-operator and
|
||||
# seaweedfs-cosi-driver, which pick up the new master through `go get`, and
|
||||
# wait for all three. The COSI driver image cut here reaches the chart at
|
||||
# the next release, through step 1.
|
||||
# 4. dispatch "Prepare release" in seaweedfs-csi-driver and seaweedfs-operator,
|
||||
# which pick up the new master through `go get -u`, and wait for both
|
||||
#
|
||||
# Events raised by the default GITHUB_TOKEN do not start other workflows, and it
|
||||
# cannot reach the other repositories at all. Add a repo secret RELEASE_PAT
|
||||
# with `contents: write` here and `actions: write` on the csi-driver, operator
|
||||
# and cosi-driver repos. Without it the tag is still pushed, but nothing
|
||||
# downstream of it runs.
|
||||
# cannot reach the other two repositories at all. Add a repo secret RELEASE_PAT
|
||||
# with `contents: write` here and `actions: write` on the csi-driver and operator
|
||||
# repos. Without it the tag is still pushed, but nothing downstream of it runs.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -32,7 +28,7 @@ on:
|
||||
type: string
|
||||
required: false
|
||||
downstream:
|
||||
description: "Also release the CSI driver, the operator and the COSI driver"
|
||||
description: "Also release the CSI driver and the operator"
|
||||
type: boolean
|
||||
default: true
|
||||
dry_run:
|
||||
@@ -138,43 +134,6 @@ jobs:
|
||||
sed -i -E "s/^version:.*/version: ${CHART_VERSION}/" "$CHART"
|
||||
cat "$CHART"
|
||||
|
||||
- name: Point the chart at the newest COSI driver release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REPO: seaweedfs/seaweedfs-cosi-driver
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VALUES=k8s/charts/seaweedfs/values.yaml
|
||||
IMAGE="ghcr.io/${REPO}"
|
||||
CUR=$(grep -oP "^ image: \"${IMAGE}:\K[^\"]+" "$VALUES" || true)
|
||||
if [ -z "$CUR" ]; then
|
||||
echo "::warning::no ${IMAGE} image line in ${VALUES}; cosi.image is left alone"
|
||||
exit 0
|
||||
fi
|
||||
# Not worth failing a release over: keep the current image instead.
|
||||
if ! NEW=$(timeout 60 gh release view -R "$REPO" --json tagName --jq .tagName); then
|
||||
echo "::warning::could not read the latest ${REPO} release; cosi.image stays ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$NEW" = "$CUR" ]; then
|
||||
echo "cosi.image is already ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$(printf '%s\n%s\n' "${CUR#v}" "${NEW#v}" | sort -V | tail -n1)" != "${NEW#v}" ]; then
|
||||
echo "::warning::the latest ${REPO} release ${NEW} is older than ${CUR}; cosi.image stays ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
# A release without its image would break every chart install with cosi.enabled.
|
||||
TOKEN=$(curl -sf --connect-timeout 10 --max-time 30 "https://ghcr.io/token?scope=repository:${REPO}:pull" | jq -r .token || true)
|
||||
if ! curl -sfI -o /dev/null --connect-timeout 10 --max-time 30 -H "Authorization: Bearer ${TOKEN}" \
|
||||
-H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \
|
||||
"https://ghcr.io/v2/${REPO}/manifests/${NEW}"; then
|
||||
echo "::warning::${IMAGE}:${NEW} is not pullable; cosi.image stays ${CUR}"
|
||||
exit 0
|
||||
fi
|
||||
sed -i -E "s|^( image: \"${IMAGE}:)[^\"]+\"|\1${NEW}\"|" "$VALUES"
|
||||
grep -n "^ image: \"${IMAGE}:" "$VALUES"
|
||||
|
||||
- name: Commit, and push the tag
|
||||
id: tag
|
||||
env:
|
||||
@@ -197,7 +156,7 @@ jobs:
|
||||
if git diff --quiet; then
|
||||
echo "::warning::Version files are already at ${TAG}; tagging the current HEAD."
|
||||
else
|
||||
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml k8s/charts/seaweedfs/values.yaml
|
||||
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml
|
||||
git commit -m "${TAG}"
|
||||
git push
|
||||
fi
|
||||
@@ -228,20 +187,14 @@ jobs:
|
||||
include:
|
||||
- repo: seaweedfs/seaweedfs-csi-driver
|
||||
workflow: prepare_release.yaml
|
||||
ref: master
|
||||
- repo: seaweedfs/seaweedfs-operator
|
||||
workflow: prepare_release.yml
|
||||
ref: master
|
||||
- repo: seaweedfs/seaweedfs-cosi-driver
|
||||
workflow: prepare_release.yaml
|
||||
ref: main
|
||||
steps:
|
||||
- name: Release ${{ matrix.repo }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.RELEASE_PAT }}
|
||||
REPO: ${{ matrix.repo }}
|
||||
WORKFLOW: ${{ matrix.workflow }}
|
||||
REF: ${{ matrix.ref }}
|
||||
SHA: ${{ needs.release.outputs.sha }}
|
||||
MODULE: github.com/seaweedfs/seaweedfs
|
||||
run: |
|
||||
@@ -251,7 +204,7 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The dispatched workflow pins seaweedfs with `go get ...@latest`, so
|
||||
# The dispatched workflow pins seaweedfs with `go get -u ...@latest`, so
|
||||
# wait until the proxy serves the release commit as the tip. Asking for
|
||||
# the commit by name is what makes the proxy fetch it. The proxy can
|
||||
# take longer than five minutes to refresh @latest after a new tag.
|
||||
@@ -278,7 +231,7 @@ jobs:
|
||||
BEFORE=$(released)
|
||||
# A minute early, so runner clock skew cannot hide the run.
|
||||
DISPATCHED_AT=$(date -u -d '1 minute ago' '+%Y-%m-%dT%H:%M:%SZ')
|
||||
gh workflow run -R "$REPO" "$WORKFLOW" --ref "$REF" -f bump=patch -f update_seaweedfs=true
|
||||
gh workflow run -R "$REPO" "$WORKFLOW" --ref master -f bump=patch -f update_seaweedfs=true
|
||||
|
||||
RUN_ID=""
|
||||
for _ in $(seq 12); do
|
||||
|
||||
@@ -56,26 +56,6 @@ 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,53 +722,6 @@ The chart does not enable `runAsNonRoot` by default because its default `hostPat
|
||||
|
||||
Security contexts configured for a component also apply to the chart-managed helper containers for that component. User-provided init containers and sidecars must define their own container security context and writable mounts.
|
||||
|
||||
### Run as a non-root user with PVC storage
|
||||
|
||||
The standard SeaweedFS image creates a `seaweed` user and group with UID/GID `1000`. Configure the pod security context so kubelet gives that user access to the mounted volumes. kubelet applies `fsGroup` to claims and `emptyDir`, but not to `hostPath`, which the master, volume and filer data and logs use by default, so move those off `hostPath` as well:
|
||||
|
||||
```yaml
|
||||
master:
|
||||
data:
|
||||
type: "persistentVolumeClaim"
|
||||
size: "1Gi"
|
||||
logs:
|
||||
type: "emptyDir"
|
||||
podSecurityContext:
|
||||
enabled: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
runAsNonRoot: true
|
||||
fsGroup: 1000
|
||||
|
||||
volume:
|
||||
dataDirs:
|
||||
- name: data1
|
||||
type: "persistentVolumeClaim"
|
||||
size: "100Gi"
|
||||
maxVolumes: 0
|
||||
podSecurityContext:
|
||||
enabled: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
runAsNonRoot: true
|
||||
fsGroup: 1000
|
||||
|
||||
filer:
|
||||
data:
|
||||
type: "persistentVolumeClaim"
|
||||
size: "25Gi"
|
||||
logs:
|
||||
type: "emptyDir"
|
||||
podSecurityContext:
|
||||
enabled: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
runAsNonRoot: true
|
||||
fsGroup: 1000
|
||||
```
|
||||
|
||||
Apply the same `podSecurityContext` to every other enabled workload, such as `s3`, `admin`, `worker`, or `sftp`, and set `s3.logs` and `sftp.logs` to `emptyDir`; for an all-in-one deployment, use the `allInOne` values key. If you use a custom image with a different UID/GID, replace `1000` with the values for that image. Storage classes that do not support `fsGroup` may need permissions adjusted on the storage backend. A release that already runs on `hostPath` cannot switch its claims in place; see [Master data](#master-data-hostpath-vs-a-claim).
|
||||
|
||||
## OpenShift Support
|
||||
|
||||
SeaweedFS can be deployed on OpenShift or any cluster enforcing the Kubernetes "restricted" Pod Security Standard. By default, OpenShift blocks containers that run as root or use `hostPath` volumes.
|
||||
|
||||
+1042
-1030
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 54 KiB |
+5
-18
@@ -1,6 +1,4 @@
|
||||
# Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
|
||||
# FormatGate.Finalize: BeginFormatFinalize checks and sets its memory-only intent atomically under Publisher mu + leaseMu; the durable raise holds neither lock.
|
||||
# FormatGate.Grant: grants/regrants and deadline-extending renewals require GrantReport (a current process report) during intent and at level 1.
|
||||
cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall
|
||||
cmd/sw-block/chunk.go CutTime.Poll
|
||||
cmd/sw-block/cut_progress_poll.go CutTime.CliGiveUp
|
||||
@@ -13,18 +11,14 @@ cmd/sw-block/volume_backup.go RestoreCommand.Abort
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.Run
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.Start
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.CrashRestart
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen
|
||||
cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
|
||||
cmd/sw-block/volume_verbs.go CutTime.Poll
|
||||
cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
|
||||
core/authority/authority.go DeleteRetire.RetireLine
|
||||
core/authority/authority.go FormatGate.Finalize
|
||||
core/authority/authority.go FormatGate.Place
|
||||
core/authority/authority_store_file.go DeleteRetire.RetireLine
|
||||
core/authority/format_finalize.go FormatGate.Finalize
|
||||
core/authority/format_finalize.go FormatGate.Grant
|
||||
core/authority/authority.go DeleteRetire.Retire
|
||||
core/authority/authority_store_file.go DeleteRetire.Retire
|
||||
core/authority/workspace.go HolderInterface.ForcedMove
|
||||
core/authority/workspace.go HolderInterface.PlannedMove
|
||||
core/authority/workspace.go MoveAdmission.Ack
|
||||
@@ -40,12 +34,9 @@ core/authority/workspace.go StopAndRestart.LeaseEnds
|
||||
core/authority/workspace.go StopAndRestart.ReadForced
|
||||
core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
|
||||
core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
|
||||
core/authority/workspace_lease_v100.go FormatGate.Finalize
|
||||
core/authority/workspace_lease_view.go FormatGate.Grant
|
||||
core/authority/workspace_lease_view.go FormatGate.Renew
|
||||
core/authority/workspace_lease_view.go HolderInterface.Grant
|
||||
core/authority/workspace_lease_view.go HolderInterface.Regrant
|
||||
core/authority/workspace_retirement.go DeleteRetire.RetireLine
|
||||
core/authority/workspace_retirement.go DeleteRetire.Retire
|
||||
core/engine/apply.go ReplicationPeer.Reconcile
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Request
|
||||
@@ -196,7 +187,6 @@ core/frontend/durable/provider_layout.go EngineAdapter.SettleDown
|
||||
core/frontend/durable/provider_layout.go StopAndRestart.SettleDown
|
||||
core/frontend/durable/provider_preempt.go CutTime.Preempt
|
||||
core/frontend/durable/provider_preempt.go CutTime.Settle
|
||||
core/frontend/durable/provider_seal_replay.go PlainSealReplay.Reply
|
||||
core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite
|
||||
core/frontend/durable/storage_adapter.go HolderInterface.Write
|
||||
core/frontend/durable/storage_adapter.go WALHold.Resubmit
|
||||
@@ -216,12 +206,9 @@ core/host/master/product_loop.go FencingRound.Decide
|
||||
core/host/master/product_loop.go Promotion.Decide
|
||||
core/host/master/services.go FormatGate.Report
|
||||
core/host/master/spec_retirement.go DeleteRetire.ReadOK
|
||||
core/host/master/spec_retirement.go DeleteRetire.RetirePlace
|
||||
core/host/master/store_attestation.go FormatGate.Finalize
|
||||
core/host/master/store_attestation.go ReplicationPeer.Attest
|
||||
core/host/master/workspace_binding.go FormatGate.Place
|
||||
core/host/master/workspace_binding.go FormatGate.Grant
|
||||
core/host/master/workspace_binding.go MoveAdmission.Ack
|
||||
core/host/master/workspace_service.go FormatGate.Grant
|
||||
core/host/master/workspace_service.go FormatGate.Place
|
||||
core/host/master/workspace_service.go FormatGate.Renew
|
||||
core/host/master/workspace_service.go MoveAdmission.ReadForMove
|
||||
|
||||
|
@@ -97,11 +97,3 @@ TestWeedClustersSideBySideKeepTheirOwnFilerCensus
|
||||
# Kubernetes state: a holder on a wiped state directory never comes up empty.
|
||||
TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost
|
||||
TestRF3WipedPrimaryRefusesAndASurvivorServesItsData
|
||||
|
||||
# Non-root mini startup and owned cleanup controls.
|
||||
TestMiniStartsWithoutRootAndNamesItsBinaries
|
||||
TestMiniOwnedGroupCleanupStopsDescendants
|
||||
TestMiniSettledCleanupDoesNotSignal
|
||||
TestMiniCleanupFailStopAndSettlement
|
||||
TestMiniContextAllowsChildShutdownGrace
|
||||
TestMiniLockProofRequiresContention
|
||||
+1
-66
@@ -1,76 +1,12 @@
|
||||
"""Exercise release packaging without Docker, GitHub writes or product builds."""
|
||||
from pathlib import Path
|
||||
import json, os, shutil, subprocess, tarfile, tempfile, unittest
|
||||
import json, os, subprocess, tarfile, tempfile, unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REV = "a" * 40
|
||||
DIGEST = "example.invalid/block@sha256:" + "b" * 64
|
||||
|
||||
class ReleaseAssets(unittest.TestCase):
|
||||
def test_active_root_release_contains_tmpfiles(self):
|
||||
self.run_active_root()
|
||||
|
||||
def test_active_root_release_refuses_an_archive_without_exec_bits(self):
|
||||
# An archive whose binaries lost their exec bits (as a tar made off the
|
||||
# Linux job does) stops the job before SHA256SUMS or any upload.
|
||||
self.run_active_root(fault='strip-exec')
|
||||
|
||||
def test_active_root_release_stops_when_the_listing_fails(self):
|
||||
# Three valid rows and then a failed listing still stop the job.
|
||||
self.run_active_root(fault='list-fails')
|
||||
|
||||
def run_active_root(self, fault=None):
|
||||
repo = HERE.parents[2]
|
||||
workflow = (repo / '.github/workflows/block-release.yml').read_text()
|
||||
step = workflow.split(' - name: Publish matching binary tarball\n', 1)[1]
|
||||
script = step.split(' run: |\n', 1)[1].split('\n - name:', 1)[0]
|
||||
script = '\n'.join(line[10:] for line in script.splitlines())
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
tools = root / 'tools'; tools.mkdir()
|
||||
image = root / 'image'; image.mkdir()
|
||||
for name in ('blockmaster', 'blockvolume', 'sw-block'):
|
||||
(image / name).write_bytes(('#!/bin/sh\necho '+name+' release\n').encode())
|
||||
(image / name).chmod(0o755)
|
||||
real = shutil.which('tar')
|
||||
if fault == 'strip-exec':
|
||||
(tools / 'tar').write_text('#!/bin/sh\ncase "$*" in *-czf*) exec ' + real + ' --mode=a-x "$@";; esac\nexec ' + real + ' "$@"\n')
|
||||
elif fault == 'list-fails':
|
||||
(tools / 'tar').write_text('#!/bin/sh\ncase "$*" in *-tvzf*) ' + real + ' "$@"; exit 2;; esac\nexec ' + real + ' "$@"\n')
|
||||
(tools / 'docker').write_text('''#!/usr/bin/env python3
|
||||
import os,pathlib,shutil,sys
|
||||
a=sys.argv[1:]
|
||||
if a[0]=='create': print('owned-container')
|
||||
elif a[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/a[1].rsplit('/',1)[1],a[2])
|
||||
''')
|
||||
(tools / 'gh').write_text('#!/bin/sh\necho "$@" >>"$GH_CALLS"\nexit 0\n')
|
||||
for tool in tools.iterdir(): tool.chmod(0o755)
|
||||
env = dict(os.environ, PATH=str(tools)+os.pathsep+os.environ['PATH'],
|
||||
IMAGE=str(image), RUNNER_TEMP=str(root), BLOCK_IMAGE='example/block',
|
||||
BLOCK_DIGEST='sha256:'+'b'*64, GITHUB_REF_NAME='seaweed-block/v1.1.2',
|
||||
GITHUB_REPOSITORY='example/block', NOTES=str(root/'notes'),
|
||||
GH_CALLS=str(root/'gh-calls'))
|
||||
result = subprocess.run(['bash', '-c', script], cwd=repo, env=env,
|
||||
capture_output=True, text=True, timeout=15)
|
||||
if fault:
|
||||
self.assertNotEqual(result.returncode, 0, result.stderr)
|
||||
if fault == 'strip-exec':
|
||||
self.assertIn('refusing to publish: blockmaster', result.stderr)
|
||||
self.assertFalse((root/'block-release/SHA256SUMS').exists())
|
||||
self.assertFalse((root/'gh-calls').exists(), 'gh ran after a refused asset')
|
||||
return
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue((root/'gh-calls').exists(), 'the control never reached gh')
|
||||
with tarfile.open(root/'block-release/sw-block-v1.1.2-linux-amd64.tar.gz') as tar:
|
||||
for member in tar.getmembers():
|
||||
if member.name != 'sw-block.tmpfiles.conf':
|
||||
self.assertEqual(member.mode & 0o111, 0o111, member.name)
|
||||
self.assertEqual(set(tar.getnames()), {'blockmaster', 'blockvolume', 'sw-block', 'sw-block.tmpfiles.conf'})
|
||||
self.assertEqual(tar.extractfile('sw-block.tmpfiles.conf').read(),
|
||||
(repo/'seaweed-block/deploy/systemd/sw-block.tmpfiles.conf').read_bytes())
|
||||
subprocess.run(['sha256sum', '--check', 'SHA256SUMS'], cwd=root/'block-release',
|
||||
check=True, capture_output=True)
|
||||
|
||||
def run_case(self, bad=None, mode="revision", existing=True, tag="v1.1.1",
|
||||
docker_rm_rc=0, rm_rc=0, publish_rc=0):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@@ -87,7 +23,6 @@ elif a[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/a[1].rsplit('/',
|
||||
else: self.fail("invalid fixture mode")
|
||||
data=(f"#!/bin/sh\necho '{name} revision={revision} modified={modified}{suffix}'\nexit {status}\n").encode()
|
||||
(image/name).write_bytes(data); (image/name).chmod(0o755); expected[name]=data
|
||||
expected["sw-block.tmpfiles.conf"]=(HERE.parent.parent/"deploy"/"systemd"/"sw-block.tmpfiles.conf").read_bytes()
|
||||
log=root/"calls.jsonl"; state=root/"release.json"; state.write_text(json.dumps({"prerelease":"-" not in tag}))
|
||||
common="""#!/usr/bin/env python3
|
||||
import json,os,pathlib,shutil,sys
|
||||
|
||||
+1
-3
@@ -33,11 +33,9 @@ for binary in blockmaster blockvolume sw-block; do
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
# The tmpfiles.d entry that creates the host volume lock directory for the units.
|
||||
cp -- "$(dirname -- "$0")/../../deploy/systemd/sw-block.tmpfiles.conf" "$work/bin/sw-block.tmpfiles.conf"
|
||||
mkdir -p "$out"
|
||||
asset="sw-block-${tag}-linux-amd64.tar.gz"
|
||||
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block sw-block.tmpfiles.conf
|
||||
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
|
||||
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
|
||||
prerelease=false
|
||||
if [[ "$tag" == *-* ]]; then prerelease=true; fi
|
||||
|
||||
+8
-10
@@ -116,25 +116,23 @@ TAG=v1.1.1
|
||||
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/sw-block-$TAG-linux-amd64.tar.gz
|
||||
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/SHA256SUMS
|
||||
sha256sum -c --ignore-missing SHA256SUMS && tar -xzf sw-block-$TAG-linux-amd64.tar.gz
|
||||
# v1.1.1 prerequisite: its child lookup uses PATH and its lock is host-wide.
|
||||
export PATH="$PWD:$PATH"
|
||||
sudo install -d -m 0755 /run/sw-block
|
||||
sudo install -d -m 0700 -o "$(id -u)" -g "$(id -g)" /run/sw-block/locks
|
||||
export PATH="$PWD:$PATH" # so the sw-block commands that mini prints run as shown
|
||||
./blockvolume --version # must print the tag's commit
|
||||
# blockvolume keeps one lock per volume here, so only one live process serves a volume on a host:
|
||||
sudo install -d -m 0755 -o root -g root /run/sw-block
|
||||
sudo install -d -m 0755 -o "$USER" -g "$(id -gn)" /run/sw-block/locks
|
||||
./sw-block mini --dir ./swb-mini --weed /path/to/weed
|
||||
```
|
||||
|
||||
From v1.1.2 `mini` needs no `sudo` to start: it keeps the volume lock under `--dir`, prints every command with the
|
||||
absolute paths of `sw-block` and `weed`, and on a failed start prints the `--reuse` command that starts again on the
|
||||
same `--dir`. With v1.1.1, see its [known issue](docs/releases/v1.1.1.md#known-issue-sw-block-mini-as-a-non-root-user-fixed-in-v112).
|
||||
A failed start leaves `--dir` behind: start again with a new `--dir`, or on the same one with `--reuse`.
|
||||
|
||||
**What it shows today:**
|
||||
- `mini` starts `weed mini`, `blockmaster` and one `blockvolume`: volume `v1`, 256 MiB, on loopback.
|
||||
- It never runs `sudo` itself. It prints the `nvme connect` command that attaches `v1`, and the status, check and
|
||||
snapshot commands. After the connect, `sudo nvme list` shows the disk's device (for example `/dev/nvme0n1`).
|
||||
- Snapshots of `v1` work at once, through the `sw-block ops chunk snapshot` command it prints. From v1.1.2 `mini`
|
||||
takes no scheduled snapshot (with v1.1.1 a scheduled `sched-<time>` snapshot appears soon after the start). A
|
||||
restore into a new volume does not run inside `mini` yet; use the standalone setup for it.
|
||||
- Snapshots of `v1` work at once, through the `sw-block ops chunk snapshot` command it prints. A scheduled
|
||||
`sched-<time>` snapshot also appears soon after the start. A restore into a new volume does not run inside `mini`
|
||||
yet; use the standalone setup for it.
|
||||
- To stop: unmount `v1`, run the `sudo nvme disconnect` that `mini` printed, then press Ctrl-C.
|
||||
|
||||
**Next:**
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
// Re-importing the same declarative spec must preserve the durable records,
|
||||
// including the registration observation time. This checks replacement, not
|
||||
// just equal JSON: an identical rewrite still pays the durability barriers.
|
||||
func TestUnchangedSpecRestartKeepsAll999ImportRecords(t *testing.T) {
|
||||
const count = 999
|
||||
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
|
||||
open := func() *master.Host {
|
||||
t.Helper()
|
||||
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
closeHost := func(h *master.Host) {
|
||||
t.Helper()
|
||||
h.Start()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := h.Close(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
nodes := make([]lifecycle.NodeRegistration, count)
|
||||
intents := make([]lifecycle.PlacementIntent, count)
|
||||
for i := range nodes {
|
||||
id := fmt.Sprintf("n%04d", i)
|
||||
nodes[i] = lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"}
|
||||
intents[i] = lifecycle.PlacementIntent{VolumeID: fmt.Sprintf("v%04d", i), DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: id, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}
|
||||
}
|
||||
importSpec := func(h *master.Host) {
|
||||
t.Helper()
|
||||
if err := importLifecycleNodeInventory(h, nodes); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := importLifecyclePlacementIntents(h, intents); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h := open()
|
||||
importSpec(h)
|
||||
closeHost(h)
|
||||
before := make(map[string]os.FileInfo, 2*count)
|
||||
for _, kind := range []string{"nodes", "placements"} {
|
||||
entries, err := os.ReadDir(filepath.Join(lifecycleDir, kind))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != count {
|
||||
t.Fatalf("%s records=%d, want %d", kind, len(entries), count)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
path := filepath.Join(lifecycleDir, kind, entry.Name())
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before[path] = info
|
||||
}
|
||||
}
|
||||
h = open()
|
||||
importSpec(h)
|
||||
closeHost(h)
|
||||
rewritten := map[string]int{}
|
||||
for path, info := range before {
|
||||
after, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !os.SameFile(info, after) || !info.ModTime().Equal(after.ModTime()) {
|
||||
rewritten[filepath.Base(filepath.Dir(path))]++
|
||||
}
|
||||
}
|
||||
if rewritten["nodes"] != 0 || rewritten["placements"] != 0 {
|
||||
t.Fatalf("unchanged restart replaced records: nodes=%d placements=%d; want zero", rewritten["nodes"], rewritten["placements"])
|
||||
}
|
||||
}
|
||||
@@ -71,19 +71,3 @@ 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,7 +274,6 @@ func run(f flags) int {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster: dynamic lifecycle topology enabled by cluster-spec node inventory; assignments will be derived from verified placement intents")
|
||||
}
|
||||
cfg := master.Config{
|
||||
FailStopLifecycleWrites: true,
|
||||
EphemeralLauncherState: (f.launcherManifestDir != "" || f.launcherKubernetesApply) && f.launcherStateHostPath == "",
|
||||
AuthorityStoreDir: f.authorityStore,
|
||||
LifecycleStoreDir: f.lifecycleStore,
|
||||
@@ -296,8 +295,8 @@ func run(f flags) int {
|
||||
return 1
|
||||
}
|
||||
cfg.Auth, cfg.ServerOptions = authn, serverOpts
|
||||
// Foreground catalog operations share their serving connection. Retirement
|
||||
// owns a separate connection so outage reads do not alter its backoff.
|
||||
// The layout catalog is the master's one HEAD source (create, restore and
|
||||
// the workspace reader all read through it).
|
||||
var layoutCat *chunkstore.BCatalog
|
||||
if f.workspaceRPC {
|
||||
cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{
|
||||
@@ -312,17 +311,6 @@ 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
|
||||
}
|
||||
@@ -351,9 +339,6 @@ func run(f flags) int {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster:", err)
|
||||
return 1
|
||||
}
|
||||
if st := h.Lifecycle(); st != nil {
|
||||
fmt.Fprintf(os.Stderr, "blockmaster: lifecycle import durability: nodes %s; placements %s\n", st.Nodes.ImportDurabilityMode(), st.Placements.ImportDurabilityMode())
|
||||
}
|
||||
// Every promotion decides on the probe round's answers: each candidate
|
||||
// answers a fresh round over its authenticated node stream.
|
||||
h.SetPromotionEvidenceProvider(h.NewRoundPromotionEvidenceProvider(f.launcherReplicationAck, nil))
|
||||
@@ -404,6 +389,12 @@ 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",
|
||||
@@ -487,8 +478,10 @@ func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistra
|
||||
if stores == nil {
|
||||
return fmt.Errorf("lifecycle node import requires --lifecycle-store")
|
||||
}
|
||||
if err := stores.Nodes.ImportNodes(nodes); err != nil {
|
||||
return fmt.Errorf("import lifecycle nodes: %w", err)
|
||||
for _, node := range nodes {
|
||||
if _, err := stores.Nodes.RegisterNode(node); err != nil {
|
||||
return fmt.Errorf("register lifecycle node %s: %w", node.ServerID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -517,7 +510,6 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
|
||||
if stores == nil {
|
||||
return fmt.Errorf("lifecycle placement import requires --lifecycle-store")
|
||||
}
|
||||
plans := make([]lifecycle.PlacementPlan, 0, len(intents))
|
||||
for _, intent := range intents {
|
||||
if stores.Deletions.Reserved(intent.VolumeID) {
|
||||
continue // never placed again (see importLifecycleVolumes)
|
||||
@@ -536,10 +528,9 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
|
||||
Source: slot.Source,
|
||||
})
|
||||
}
|
||||
plans = append(plans, plan)
|
||||
}
|
||||
if err := stores.Placements.ImportPlans(plans); err != nil {
|
||||
return fmt.Errorf("import lifecycle placement seeds: %w", err)
|
||||
if _, err := stores.Placements.ApplyPlan(plan); err != nil {
|
||||
return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// only a host that holds no volume: a retired id is then unregistered, so a
|
||||
// holder RPC under it is refused (refuseWorkspaceHolderHost) and the checks
|
||||
// only get stricter. This guard fails when any other non-test caller of
|
||||
// RegisterNode, ImportNodes or RemoveNode appears anywhere.
|
||||
// RegisterNode or RemoveNode appears anywhere.
|
||||
func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
@@ -56,7 +56,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "ImportNodes" || sel.Sel.Name == "RemoveNode") {
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "RemoveNode") {
|
||||
sites = append(sites, filepath.ToSlash(rel)+":"+fn.Name.Name+"."+sel.Sel.Name)
|
||||
}
|
||||
return true
|
||||
@@ -68,7 +68,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sort.Strings(sites)
|
||||
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.ImportNodes", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
|
||||
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
|
||||
if strings.Join(sites, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want)
|
||||
}
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
func TestMasterImportPersistenceFailureExitsAndRecovers(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
nodeDir := filepath.Join(root, "lifecycle", "nodes")
|
||||
store, err := lifecycle.OpenNodeInventoryStore(nodeDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := lifecycle.NodeRegistration{ServerID: "kept", Addr: "127.0.0.1:19001"}
|
||||
old, err = store.RegisterNode(old)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A real rename failure, even as root; the preceding committed record
|
||||
// stays untouched. Directories are not parsed as JSON records on reload.
|
||||
block := filepath.Join(nodeDir, "new.json")
|
||||
if err := os.Mkdir(block, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec := filepath.Join(root, "spec.yaml")
|
||||
if err := os.WriteFile(spec, []byte("nodes:\n - server_id: new\n addr: 127.0.0.1:19002\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := []string{"--listen", "127.0.0.1:0", "--authority-store", filepath.Join(root, "authority"), "--lifecycle-store", filepath.Join(root, "lifecycle"), "--cluster-spec", spec}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$", "-test.timeout=8s")
|
||||
cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep))
|
||||
out, runErr := cmd.CombinedOutput()
|
||||
var exit *exec.ExitError
|
||||
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
|
||||
t.Fatalf("master did not fail-stop with exit74: %v context=%v\n%s", runErr, ctx.Err(), out)
|
||||
}
|
||||
text := string(out)
|
||||
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "reason=lifecycle_persist_failed") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
|
||||
t.Fatalf("missing single persistence ERROR: %s", text)
|
||||
}
|
||||
oldRaw, err := json.Marshal(old)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMasterImportPersistenceRecoveryChild$", "-test.timeout=8s")
|
||||
recovery.Env = append(os.Environ(), "MASTER_RECOVERY_ROOT="+root, "MASTER_RECOVERY_OLD="+string(oldRaw))
|
||||
if out, err := recovery.CombinedOutput(); err != nil {
|
||||
t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMasterImportPersistenceRecoveryChild(t *testing.T) {
|
||||
root := os.Getenv("MASTER_RECOVERY_ROOT")
|
||||
if root == "" {
|
||||
t.Skip("bounded recovery subprocess")
|
||||
}
|
||||
nodeDir := filepath.Join(root, "lifecycle", "nodes")
|
||||
var old lifecycle.NodeRegistration
|
||||
if err := json.Unmarshal([]byte(os.Getenv("MASTER_RECOVERY_OLD")), &old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A new master must load the complete committed record, not a speculative
|
||||
// new registration or partial JSON from the failed write.
|
||||
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
t.Cleanup(func() {
|
||||
closeCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer stop()
|
||||
if err := h.Close(closeCtx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if got, ok := h.Lifecycle().Nodes.GetNodeSnapshot("kept"); !ok || got.ServerID != old.ServerID || got.Addr != old.Addr || !got.SeenAt.Equal(old.SeenAt) {
|
||||
t.Fatalf("committed record lost on restart: %+v %v", got, ok)
|
||||
}
|
||||
if _, ok := h.Lifecycle().Nodes.GetNodeSnapshot("new"); ok {
|
||||
t.Fatal("failed record appeared on restart")
|
||||
}
|
||||
entries, err := os.ReadDir(nodeDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {
|
||||
raw, err := os.ReadFile(filepath.Join(nodeDir, entry.Name()))
|
||||
if err != nil || !json.Valid(raw) {
|
||||
t.Fatalf("partial record %s: %v", entry.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
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,13 +26,6 @@ import (
|
||||
// refuses an interval above half the freshness window (a longer loop gap
|
||||
// reads as the master's own pause), so the window is 60 s: the dead
|
||||
// primary's loss then comes at most a window after its last report.
|
||||
//
|
||||
// The failover is predicted within gapLoop + gapWindow + gapLoop of the
|
||||
// kill: the tick that ends creation comes at most a loop after it, the
|
||||
// loss a window after that tick's silence floor, and the tick that reads
|
||||
// the loss at most a loop later. The test waits twice that.
|
||||
const gapLoop, gapWindow = 30 * time.Second, 60 * time.Second
|
||||
|
||||
func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
|
||||
bins := buildG54Binaries(t)
|
||||
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
|
||||
@@ -55,8 +48,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
|
||||
}
|
||||
master := h.start(t, "blockmaster", bins.master,
|
||||
"--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"),
|
||||
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", gapLoop.String(),
|
||||
"--freshness-window", gapWindow.String(), "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
|
||||
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s",
|
||||
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
|
||||
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
|
||||
for _, b := range hosts {
|
||||
lockDir := b.root + ".locks"
|
||||
@@ -91,8 +84,7 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
|
||||
// 3. The next tick reads the survivors' write: creation ended, and the
|
||||
// gate fails the volume over.
|
||||
var p2 *host
|
||||
predicted := gapLoop + gapWindow + gapLoop
|
||||
poll(t, 2*predicted, fmt.Sprintf("no survivor became primary at epoch 2 within %v, twice the predicted %v (the volume held as creating, or the gate's replace not acted on: see the master's 'decision=replace' lines)", 2*predicted, predicted), func() bool {
|
||||
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
|
||||
for _, b := range survivors {
|
||||
if statusIsPrimaryAt(b.status, 2) {
|
||||
p2 = b
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -25,7 +26,7 @@ import (
|
||||
type storeRecordMaster struct {
|
||||
control.UnimplementedLifecycleServiceServer
|
||||
mu sync.Mutex
|
||||
mode string // "creating", "ended", "older", "unavailable"
|
||||
mode string // "creating", "ended", "older", "unreadable", "unavailable"
|
||||
}
|
||||
|
||||
func (m *storeRecordMaster) set(mode string) { m.mu.Lock(); m.mode = mode; m.mu.Unlock() }
|
||||
@@ -42,6 +43,8 @@ func (m *storeRecordMaster) GetReplicaStore(_ context.Context, q *control.GetRep
|
||||
return &control.GetReplicaStoreResponse{Listed: true, CreationEnded: true}, nil
|
||||
case "older":
|
||||
return nil, status.Error(codes.Unimplemented, "unknown method GetReplicaStore")
|
||||
case "unreadable":
|
||||
return nil, status.Error(codes.FailedPrecondition, "the replica's store record is unreadable")
|
||||
}
|
||||
return nil, status.Error(codes.Unavailable, "lifecycle store unavailable")
|
||||
}
|
||||
@@ -102,7 +105,10 @@ func runHolder(t *testing.T, bin, master, root, locks string, until func() bool,
|
||||
// the volume is creating an empty state directory creates the store; once
|
||||
// creation ended, a store other than the recorded one, and a wiped state
|
||||
// directory, exit 78 store_lost; an older master (no GetReplicaStore) and an
|
||||
// unreadable record exit 75 with an empty state directory left empty.
|
||||
// unreadable record exit 75 with an empty state directory left empty. A
|
||||
// master that gives no reply is waited out inside the process, writing
|
||||
// nothing, so a start during an outage does not burn the unit's start limit;
|
||||
// once it answers creating, the same process creates its store.
|
||||
func TestBlockvolumeAsksTheMasterBeforeCreatingItsStore(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("builds and runs the blockvolume binary")
|
||||
@@ -184,11 +190,64 @@ func TestBlockvolumeAsksTheMasterBeforeCreatingItsStore(t *testing.T) {
|
||||
}
|
||||
empty(t)
|
||||
|
||||
for mode, reason := range map[string]string{"older": "master_too_old", "unavailable": "store_record_unreadable"} {
|
||||
for mode, reason := range map[string]string{"older": "master_too_old", "unreadable": "store_record_unreadable"} {
|
||||
m.set(mode)
|
||||
if code, _, out := runHolder(t, bin, ln.Addr().String(), root, locks, nil, 60*time.Second); code != exitWorkspaceRetry || !strings.Contains(out, reason) {
|
||||
t.Fatalf("%s master, empty state: exit %d, want 75 %s\n%s", mode, code, reason, out)
|
||||
}
|
||||
empty(t)
|
||||
}
|
||||
|
||||
// No reply for longer than the old 10 s read bound plus the unit's 5 s
|
||||
// restart delay: the process stays, writes nothing, and creates its
|
||||
// store once the master answers creating.
|
||||
m.set("unavailable")
|
||||
start, answered := time.Now(), false
|
||||
answer := func() bool {
|
||||
if !answered && time.Since(start) > 25*time.Second {
|
||||
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
|
||||
t.Errorf("the waiting holder wrote into its state directory: %v %v", entries, err)
|
||||
}
|
||||
m.set("creating")
|
||||
answered = true
|
||||
}
|
||||
return created()
|
||||
}
|
||||
if code, running, out := runHolder(t, bin, ln.Addr().String(), root, locks, answer, 90*time.Second); !running || !created() || !strings.Contains(out, "waiting for the master at "+ln.Addr().String()) {
|
||||
t.Fatalf("a master with no reply, then creating: exit %d running %v created %v\n%s", code, running, created(), out)
|
||||
}
|
||||
|
||||
// A stop during the wait is a clean stop: exit 0, nothing created.
|
||||
if runtime.GOOS == "windows" {
|
||||
return // no SIGTERM to another process
|
||||
}
|
||||
if err := os.RemoveAll(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.set("unavailable")
|
||||
var buf bytes.Buffer
|
||||
cmd := exec.Command(bin, "--master", ln.Addr().String(), "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
|
||||
"--data-addr", "127.0.0.1:0", "--ctrl-addr", "127.0.0.1:0", "--durable-root", root, "--durable-impl", "walstore",
|
||||
"--durable-blocks", "64", "--"+volumeLockDirTestOnlyFlag, locks)
|
||||
cmd.Stdout, cmd.Stderr = &buf, &buf
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
time.Sleep(5 * time.Second)
|
||||
_ = cmd.Process.Signal(syscall.SIGTERM)
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil || !strings.Contains(buf.String(), "stopped while waiting for the master") {
|
||||
t.Fatalf("SIGTERM during the wait: %v\n%s", err, buf.String())
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
killAndJoin(cmd, done)
|
||||
t.Fatalf("SIGTERM did not end the wait\n%s", buf.String())
|
||||
}
|
||||
empty(t)
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
@@ -129,8 +130,8 @@ type flags struct {
|
||||
durableBlockSize uint
|
||||
durableWALMultiBlockRecords bool
|
||||
durableWALRecoveryTestDisableFlusher bool
|
||||
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden, for
|
||||
// tests and sw-block mini's one-user trial; refused under systemd).
|
||||
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden,
|
||||
// test-only; refused under systemd).
|
||||
volumeLockDirTestOnly string
|
||||
|
||||
// WAL retention window past checkpoint LSN. Zero = strict
|
||||
@@ -333,7 +334,7 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error))
|
||||
return flags{}, err
|
||||
}
|
||||
if f.volumeLockDirTestOnly != "" && os.Getenv("INVOCATION_ID") != "" {
|
||||
return flags{}, fmt.Errorf("--%s is for tests and trial runs and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir)
|
||||
return flags{}, fmt.Errorf("--%s is test-only and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir)
|
||||
}
|
||||
if f.recoveryMode != "legacy" && f.recoveryMode != "dual-lane" {
|
||||
return flags{}, fmt.Errorf("--recovery-mode=%q invalid; want \"legacy\" or \"dual-lane\"", f.recoveryMode)
|
||||
@@ -757,7 +758,7 @@ func runVolume(f flags, exits *processExit) int {
|
||||
VolumeLockDirTestOnly: f.volumeLockDirTestOnly,
|
||||
}
|
||||
if f.volumeLockDirTestOnly != "" {
|
||||
fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is an override: one process per volume is enforced only among processes using it\n", f.volumeLockDirTestOnly)
|
||||
fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is a test override: the one-process-per-host guarantee does not hold\n", f.volumeLockDirTestOnly)
|
||||
}
|
||||
var chunkErr error
|
||||
var chunk chunkWiring
|
||||
@@ -926,9 +927,24 @@ func runVolume(f flags, exits *processExit) int {
|
||||
if xErr == nil && f.durableImpl != "walstore-chunk" {
|
||||
// A plain walstore store is the volume's only copy: ask the master
|
||||
// before anything is created or written (GetReplicaStore).
|
||||
qctx, qcancel := context.WithTimeout(context.Background(), replicaStoreQueryTimeout)
|
||||
rec, qerr := h.ReplicaStoreRecord(qctx)
|
||||
qcancel()
|
||||
var storeWait atomic.Bool
|
||||
if status != nil {
|
||||
status.SetStartupWait(storeWait.Load)
|
||||
}
|
||||
rec, qerr := readReplicaStore(exits.parent, f.masterAddr, h.ReplicaStoreRecord, log.Printf, storeWait.Store)
|
||||
if exits.parent.Err() != nil {
|
||||
// Stopped while waiting for the master: nothing was opened or
|
||||
// created, and a stop is not a failure.
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: stopped while waiting for the master's store record; nothing was created")
|
||||
_ = closeProviderAfterSnapshotOperations(status, dp.Close)
|
||||
if status != nil {
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = status.Close(shutCtx)
|
||||
shutCancel()
|
||||
}
|
||||
_ = h.Close()
|
||||
return 0
|
||||
}
|
||||
admission, refuse := decideStoreAdmission(rec, qerr, exists)
|
||||
if refuse != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: durable storage open refused:", refuse.reason, refuse.detail)
|
||||
|
||||
@@ -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: rpc error: code = FailedPrecondition desc = workspace move: missing or changed authority/lease; resolve the server's stated precondition before retrying" {
|
||||
if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: workspace move: missing or changed authority/lease" {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// A master restart must not replace live holders while rebuilding its
|
||||
// heartbeat view. Registration time is deliberately older than the window;
|
||||
// only the new process's received heartbeats make its node evidence fresh.
|
||||
func TestMasterImportRestartKeepsLiveHoldersAcrossFreshnessWindow(t *testing.T) {
|
||||
const window = 6 * time.Second
|
||||
env := startHandoffEnvVolumes(t, 1, []string{"v2"}, "--freshness-window", window.String(), "--lifecycle-product-loop-interval", "100ms")
|
||||
env.volExtra = append(env.volExtra, "--heartbeat-interval", "250ms")
|
||||
for id, volume := range map[string]string{"s1": "v1", "n-v2": "v2"} {
|
||||
host := env.hosts[id]
|
||||
host.volume, host.replica = volume, "r1"
|
||||
env.hosts[id] = host
|
||||
}
|
||||
first, second := f1Up(t, env, "s1"), f1Up(t, env, "n-v2")
|
||||
epochs := map[string]uint64{}
|
||||
for volume, holder := range map[string]*daemon{"v1": first, "v2": second} {
|
||||
epoch, err := adoptedEpochOf(volume, holder.line("blockvolume: volume "+volume+" adopted as PRIMARY at r1@"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
epochs[volume] = epoch
|
||||
}
|
||||
// Both durable registrations now age beyond freshness while holders keep
|
||||
// reporting; a restart must not renew these durable observation times.
|
||||
time.Sleep(window + 100*time.Millisecond)
|
||||
env.masterProcess.term(t, 10*time.Second)
|
||||
started := time.Now()
|
||||
env.masterProcess = env.h.start(t, "blockmaster-import-restarted", env.h.master, env.masterArgs...)
|
||||
conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
client := control.NewClusterEvidenceServiceClient(conn)
|
||||
fresh := map[string]bool{}
|
||||
verified := map[string]bool{}
|
||||
observed := map[string]bool{}
|
||||
samples := 0
|
||||
for time.Since(started) < window {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
status, err := client.GetClusterStatus(ctx, &control.GetClusterStatusRequest{})
|
||||
cancel()
|
||||
if err == nil {
|
||||
samples++
|
||||
for _, node := range status.Nodes {
|
||||
if at := node.GetLastHeartbeatAt(); at != nil && at.AsTime().After(started) {
|
||||
fresh[node.GetNodeName()] = true
|
||||
}
|
||||
}
|
||||
for _, volume := range status.Volumes {
|
||||
if epoch, ok := epochs[volume.VolumeId]; ok && volume.Epoch != 0 {
|
||||
observed[volume.VolumeId] = true
|
||||
if volume.Epoch != epoch {
|
||||
t.Fatalf("%s changed epoch after restart: %d -> %d", volume.VolumeId, epoch, volume.Epoch)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, event := range status.Events {
|
||||
if event.EventType == "placement_verified" {
|
||||
verified[event.VolumeId] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"primary lost:", "decision=replace("} {
|
||||
if env.masterProcess.has(bad) {
|
||||
t.Fatalf("live-holder restart made a loss/replacement decision: %s", bad)
|
||||
}
|
||||
}
|
||||
for id, d := range map[string]*daemon{"s1": first, "n-v2": second} {
|
||||
select {
|
||||
case <-d.done:
|
||||
t.Fatalf("live holder %s exited during master restart: %v", id, d.err)
|
||||
default:
|
||||
}
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if samples == 0 {
|
||||
t.Fatal("no successful status sample in the freshness window")
|
||||
}
|
||||
for _, id := range []string{"s1", "n-v2"} {
|
||||
if !fresh[id] {
|
||||
t.Fatalf("live node %s never became fresh after restart", id)
|
||||
}
|
||||
}
|
||||
for id := range epochs {
|
||||
if !observed[id] {
|
||||
t.Fatalf("volume %s never showed its authoritative epoch again", id)
|
||||
}
|
||||
if !verified[id] {
|
||||
t.Fatalf("placement %s did not verify again within one window", id)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{"s1", "n-v2"} {
|
||||
block := pattern("restart-live-io!")
|
||||
env.writeBlock(t, id, 0, block)
|
||||
}
|
||||
t.Logf("master restart: %d status samples, both nodes fresh, both placements verified, no loss/replacement or holder exit within %s", samples, window)
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sw-block mini starts as any user on a host without /run/sw-block: the
|
||||
// holder takes its volume lock under --dir and serves, every sw-block and
|
||||
// weed command mini prints names the binary by its absolute path, and no
|
||||
// scheduled snapshot runs. A start that fails after --dir was made stops what
|
||||
// it started and prints the --reuse command for the same --dir.
|
||||
func TestMiniStartsWithoutRootAndNamesItsBinaries(t *testing.T) {
|
||||
assertMiniUnprivileged(t)
|
||||
weed := os.Getenv("CHUNKSTORE_WEED")
|
||||
if weed == "" {
|
||||
t.Fatal("CHUNKSTORE_WEED must name the pinned real SeaweedFS binary")
|
||||
}
|
||||
var err error
|
||||
weed, err = filepath.Abs(weed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The real startup/output assertion must exercise the production hint,
|
||||
// even when CI supplied an ordinary path. Both spaces and apostrophes need
|
||||
// POSIX quoting; exec still receives the path as one argument.
|
||||
quotedWeed := filepath.Join(t.TempDir(), "weed's tools")
|
||||
if err := os.Symlink(weed, quotedWeed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
weed = quotedWeed
|
||||
bins := os.Getenv("SWBLOCK_TEST_BINS")
|
||||
if bins == "" {
|
||||
bins = t.TempDir()
|
||||
for _, b := range []string{"blockmaster", "blockvolume", "sw-block"} {
|
||||
miniGoBuild(t, filepath.Join(bins, b), "github.com/seaweedfs/seaweed-block/cmd/"+b)
|
||||
}
|
||||
}
|
||||
bins, err = filepath.Abs(bins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cli := filepath.Join(bins, "sw-block")
|
||||
shift := miniPortShift(t)
|
||||
dir := filepath.Join(t.TempDir(), "mini")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
|
||||
defer cancel()
|
||||
p := startOwnedMini(t, ctx, cli, "mini", "--dir", dir, "--bin", bins, "--weed", weed, "--port-shift", fmt.Sprint(shift))
|
||||
for !strings.Contains(p.output.String(), "sw-block mini: running") {
|
||||
select {
|
||||
case <-p.done:
|
||||
t.Fatalf("mini did not reach running: %v\n%s", p.err, p.output.String())
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("mini startup expired: %s", p.output.String())
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
// The running line precedes the hints; await the last hint without reading
|
||||
// a buffer concurrently with its writer.
|
||||
for !strings.Contains(p.output.String(), miniHintWord(weed)+" shell -master=") {
|
||||
select {
|
||||
case <-p.done:
|
||||
t.Fatalf("mini exited before its hints: %s", p.output.String())
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("mini hints expired: %s", p.output.String())
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
if err := miniLockConflict(filepath.Join(dir, "locks", "v1.lock")); err != nil {
|
||||
t.Fatalf("serving holder does not own its trial lock: %v", err)
|
||||
}
|
||||
if err := p.signalLeader(syscall.SIGINT); err != nil {
|
||||
t.Fatalf("could not deliver Ctrl-C: %v", err)
|
||||
}
|
||||
if err := p.join(t, 40*time.Second); err != nil {
|
||||
t.Fatalf("mini after Ctrl-C: %v\n%s", err, p.output.String())
|
||||
}
|
||||
p.assertStopped(t) // before the safety-net cleanup: product shutdown owns this
|
||||
t.Logf("sw-block mini output:\n%s", p.output.String())
|
||||
if !exists(filepath.Join(dir, "locks", "v1.lock")) {
|
||||
t.Fatalf("the holder's lock is not under --dir")
|
||||
}
|
||||
text := p.output.String()
|
||||
if strings.Contains(text, "+ sw-block ") || strings.Contains(text, " sw-block ") {
|
||||
t.Errorf("mini prints a sw-block command without its absolute path")
|
||||
}
|
||||
for _, want := range []string{" " + miniHintWord(cli) + " ops workspace show", " " + miniHintWord(cli) + " ops chunk snapshot", miniHintWord(weed) + " shell -master=", "mini takes no scheduled snapshot", miniHintWord(cli) + " mini --dir "} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Errorf("mini's output lacks %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
// A start that fails after --dir exists names the --reuse command.
|
||||
broken := t.TempDir()
|
||||
for _, b := range []string{"blockmaster", "sw-block"} {
|
||||
if err := os.Symlink(filepath.Join(bins, b), filepath.Join(broken, b)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(broken, "blockvolume"), []byte("#!/bin/sh"+string(rune(10))+"echo refused >&2; exit 1"+string(rune(10))), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir2 := filepath.Join(t.TempDir(), "mini")
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel2()
|
||||
p2 := startOwnedMini(t, ctx2, cli, "mini", "--dir", dir2, "--bin", broken, "--weed", weed, "--port-shift", fmt.Sprint(miniPortShift(t)))
|
||||
err = p2.join(t, 3*time.Minute+miniShutdownGrace+10*time.Second)
|
||||
p2.assertNaturalExit(t)
|
||||
b2 := p2.output.String()
|
||||
t.Logf("failed start:\n%s", b2)
|
||||
if err == nil || !strings.Contains(b2, "start again on it with") || !strings.Contains(b2, miniHintWord(cli)+" mini --dir "+miniHintWord(dir2)+" --reuse") {
|
||||
t.Fatalf("a failed start: %v", err)
|
||||
}
|
||||
for _, binary := range []string{weed, filepath.Join(broken, "blockmaster"), filepath.Join(broken, "blockvolume")} {
|
||||
if !strings.Contains(b2, "+ "+miniHintWord(binary)+" ") {
|
||||
t.Fatalf("failed-start path did not reach %s: %s", binary, b2)
|
||||
}
|
||||
}
|
||||
p2.assertStopped(t) // rejects a failed start which left weed/master running
|
||||
|
||||
}
|
||||
|
||||
func miniGoBuild(t *testing.T, out, pkg string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
p := startOwnedMini(t, ctx, "go", "build", "-o", out, pkg)
|
||||
if err := p.join(t, 3*time.Minute+miniShutdownGrace+10*time.Second); err != nil {
|
||||
t.Fatalf("build %s: %v\n%s", pkg, err, p.output.String())
|
||||
}
|
||||
p.assertStopped(t)
|
||||
|
||||
}
|
||||
|
||||
// miniPortShift picks a --port-shift whose every mini port (defaultMiniPorts
|
||||
// in cmd/sw-block) is claimed host-wide and free now, as the other harnesses'
|
||||
// ports are, so a parallel process-level shard never binds one of them.
|
||||
func miniPortShift(t *testing.T) int {
|
||||
t.Helper()
|
||||
defaults := []int{9180, 9201, 9202, 9203, 4420, 9333, 19333, 9340, 19340, 8888, 18888, 12535, 22535}
|
||||
for i := 0; i < 200; i++ {
|
||||
shift := 3000 + rand.Intn(6000)
|
||||
free := true
|
||||
for _, p := range defaults {
|
||||
if !claimHostPort(p + shift) {
|
||||
free = false
|
||||
break
|
||||
}
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p+shift))
|
||||
if err != nil {
|
||||
free = false
|
||||
break
|
||||
}
|
||||
ln.Close()
|
||||
}
|
||||
if free {
|
||||
return shift
|
||||
}
|
||||
}
|
||||
t.Fatal("no --port-shift with every mini port claimed and free")
|
||||
return 0
|
||||
}
|
||||
|
||||
func exists(p string) bool {
|
||||
_, err := os.Stat(p)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Expected command words follow the printed POSIX-shell contract.
|
||||
func miniHintWord(s string) string {
|
||||
if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" {
|
||||
return s
|
||||
}
|
||||
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||
}
|
||||
|
||||
func miniLockConflict(path string) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if err == syscall.EWOULDBLOCK || err == syscall.EAGAIN {
|
||||
return nil
|
||||
}
|
||||
if err == nil {
|
||||
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
|
||||
return fmt.Errorf("lock was available")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func TestMiniLockProofRequiresContention(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "v1.lock")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if err := miniLockConflict(path); err == nil {
|
||||
t.Fatal("unheld file passed the serving-lock proof")
|
||||
}
|
||||
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := miniLockConflict(path); err != nil {
|
||||
t.Fatalf("held lock failed proof: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,615 +0,0 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// Preconditions are assertions: a privileged run is not non-root evidence.
|
||||
func assertMiniUnprivileged(t *testing.T) {
|
||||
t.Helper()
|
||||
if os.Getuid() == 0 || os.Geteuid() == 0 {
|
||||
t.Fatal("non-root qualification must run without uid 0")
|
||||
}
|
||||
p := "/run/sw-block/locks"
|
||||
// A read-only existing file can still be flocked without a directory write.
|
||||
// Refuse qualification if it can even be opened; never mutate the host path.
|
||||
lock, err := os.Open(filepath.Join(p, "v1.lock"))
|
||||
if err == nil {
|
||||
_ = lock.Close()
|
||||
t.Fatal("existing host lock is readable; old host-lock path is usable")
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
|
||||
t.Fatalf("host lock file preflight: %v", err)
|
||||
}
|
||||
for {
|
||||
_, err := os.Stat(p)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if errors.Is(err, syscall.EACCES) || errors.Is(err, syscall.EPERM) {
|
||||
t.Logf("non-root uid=%d euid=%d; host lock path %s is inaccessible: %v", os.Getuid(), os.Geteuid(), p, err)
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("host lock preflight: %v", err)
|
||||
}
|
||||
p = filepath.Dir(p)
|
||||
}
|
||||
if err := syscall.Access(p, 3); err == nil {
|
||||
t.Fatalf("host lock path/ancestor %s is writable; non-root precondition is unproved", p)
|
||||
} else if !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
|
||||
t.Fatalf("host lock access preflight: %v", err)
|
||||
}
|
||||
t.Logf("non-root uid=%d euid=%d; host lock ancestor %s is not writable", os.Getuid(), os.Geteuid(), p)
|
||||
}
|
||||
|
||||
type miniOutput struct {
|
||||
mu sync.Mutex
|
||||
b bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *miniOutput) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.b.Write(p)
|
||||
}
|
||||
func (b *miniOutput) String() string { b.mu.Lock(); defer b.mu.Unlock(); return b.b.String() }
|
||||
|
||||
const miniFailStopExit = 86
|
||||
|
||||
func miniFailStop(t *testing.T, why string) {
|
||||
fmt.Fprintf(os.Stderr, "%s: %s; stopping tests before directory cleanup\n", t.Name(), why)
|
||||
os.Exit(miniFailStopExit)
|
||||
}
|
||||
|
||||
type ownedMini struct {
|
||||
cmd *exec.Cmd
|
||||
done chan struct{}
|
||||
err error
|
||||
output miniOutput
|
||||
stopOnce sync.Once
|
||||
mu sync.Mutex
|
||||
settled bool
|
||||
leaderFD int
|
||||
leaderKey string
|
||||
dispatches atomic.Int64
|
||||
watchdog atomic.Bool
|
||||
// Only the isolated fail-stop controls replace the census or its window.
|
||||
groupExists func() bool
|
||||
census func() []int
|
||||
censusWait time.Duration
|
||||
captureLeader func(int) (miniProcInfo, error)
|
||||
}
|
||||
|
||||
const miniShutdownGrace = 35 * time.Second // three 10-second child stops plus margin
|
||||
|
||||
// Probe before starting any workload. CLONE_PIDFD then obtains the child's
|
||||
// immutable reference atomically with creation, before a cancellation can run.
|
||||
func miniPidfdSupport() error {
|
||||
fd, err := unix.PidfdOpen(os.Getpid(), 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unix.Close(fd)
|
||||
return unix.PidfdSendSignal(fd, 0, nil, 0)
|
||||
}
|
||||
func startOwnedMini(t *testing.T, ctx context.Context, bin string, args ...string) *ownedMini {
|
||||
t.Helper()
|
||||
if err := miniPidfdSupport(); err != nil {
|
||||
t.Fatalf("pidfd ownership unavailable before start: %v", err)
|
||||
}
|
||||
p := &ownedMini{cmd: exec.CommandContext(ctx, bin, args...), done: make(chan struct{}), leaderFD: -1}
|
||||
p.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, PidFD: &p.leaderFD}
|
||||
p.cmd.Stdout, p.cmd.Stderr = &p.output, &p.output
|
||||
// os/exec must not kill only the leader after a short WaitDelay. Our
|
||||
// watchdog grants the full product shutdown window, then owns group cleanup.
|
||||
p.cmd.Cancel = func() error { p.watchdog.Store(true); go p.stop(t); return nil }
|
||||
p.mu.Lock() // a context cancellation cannot observe the unopened pidfd
|
||||
if err := p.cmd.Start(); err != nil {
|
||||
p.mu.Unlock()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.leaderFD < 0 {
|
||||
p.mu.Unlock()
|
||||
p.ownershipFailed(t, "atomic leader pidfd missing")
|
||||
}
|
||||
info, err := miniProc(p.cmd.Process.Pid)
|
||||
if err != nil {
|
||||
p.mu.Unlock()
|
||||
p.ownershipFailed(t, fmt.Sprintf("cannot record leader incarnation: %v", err))
|
||||
}
|
||||
p.leaderKey = info.key
|
||||
p.mu.Unlock()
|
||||
go func() { p.err = p.cmd.Wait(); close(p.done) }()
|
||||
t.Cleanup(func() { p.stop(t) })
|
||||
return p
|
||||
}
|
||||
|
||||
// No Wait goroutine exists yet: the unreaped direct child cannot have its
|
||||
// PID recycled. Stop and reap it before failing closed with directories kept.
|
||||
func (p *ownedMini) ownershipFailed(t *testing.T, why string) {
|
||||
_ = p.cmd.Process.Kill()
|
||||
p.cmd.WaitDelay = time.Second
|
||||
reaped := make(chan struct{})
|
||||
go func() { _ = p.cmd.Wait(); close(reaped) }()
|
||||
select {
|
||||
case <-reaped:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
miniFailStop(t, why)
|
||||
}
|
||||
func (p *ownedMini) signalFD(fd int, sig unix.Signal) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.settled {
|
||||
return os.ErrProcessDone
|
||||
}
|
||||
p.dispatches.Add(1)
|
||||
return unix.PidfdSendSignal(fd, sig, nil, 0)
|
||||
}
|
||||
func (p *ownedMini) signalLeader(sig unix.Signal) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.settled {
|
||||
return os.ErrProcessDone
|
||||
}
|
||||
p.dispatches.Add(1)
|
||||
return unix.PidfdSendSignal(p.leaderFD, sig, nil, 0)
|
||||
}
|
||||
func (p *ownedMini) isSettled() bool { p.mu.Lock(); defer p.mu.Unlock(); return p.settled }
|
||||
func (p *ownedMini) settle() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if !p.settled {
|
||||
p.settled = true
|
||||
if p.leaderFD >= 0 {
|
||||
_ = unix.Close(p.leaderFD)
|
||||
p.leaderFD = -1
|
||||
}
|
||||
}
|
||||
}
|
||||
func (p *ownedMini) join(t *testing.T, bound time.Duration) error {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-p.done:
|
||||
return p.err
|
||||
case <-time.After(bound):
|
||||
miniFailStop(t, fmt.Sprintf("owned process did not join in %s", bound))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func (p *ownedMini) assertNaturalExit(t *testing.T) {
|
||||
t.Helper()
|
||||
if p.watchdog.Load() {
|
||||
t.Fatal("watchdog intervened; failed-start cleanup was not completed by mini")
|
||||
}
|
||||
}
|
||||
func (p *ownedMini) stop(t *testing.T) {
|
||||
p.stopOnce.Do(func() {
|
||||
if p.isSettled() {
|
||||
return
|
||||
}
|
||||
_ = p.signalLeader(unix.SIGTERM)
|
||||
select {
|
||||
case <-p.done:
|
||||
p.assertStopped(t)
|
||||
return
|
||||
case <-time.After(miniShutdownGrace):
|
||||
}
|
||||
p.stopGroup(t)
|
||||
})
|
||||
}
|
||||
|
||||
// Never signal a numeric PGID. While the original leader is stopped, its
|
||||
// group identity cannot disappear; capture and stop each member by pidfd.
|
||||
// After resuming, TERM/KILL use those immutable references even if a PID is
|
||||
// recycled. Unknown late members or an exited leader with live residue cause
|
||||
// fail-stop rather than guessing ownership and signaling an unrelated group.
|
||||
func (p *ownedMini) stopGroup(t *testing.T) {
|
||||
t.Helper()
|
||||
if p.isSettled() {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-p.done:
|
||||
p.assertStopped(t)
|
||||
return
|
||||
default:
|
||||
}
|
||||
if err := p.signalLeader(unix.SIGSTOP); err != nil {
|
||||
select {
|
||||
case <-p.done:
|
||||
p.assertStopped(t)
|
||||
return
|
||||
default:
|
||||
miniFailStop(t, fmt.Sprintf("cannot stop owned leader: %v", err))
|
||||
}
|
||||
}
|
||||
pgid := p.cmd.Process.Pid
|
||||
leaderFD := p.leaderFD
|
||||
refs := map[string]int{}
|
||||
defer func() {
|
||||
for _, fd := range refs {
|
||||
if fd != leaderFD {
|
||||
_ = unix.Close(fd)
|
||||
}
|
||||
}
|
||||
}()
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for {
|
||||
select {
|
||||
case <-p.done:
|
||||
p.assertStopped(t)
|
||||
return
|
||||
default:
|
||||
}
|
||||
readLeader := miniProc
|
||||
if p.captureLeader != nil {
|
||||
readLeader = p.captureLeader
|
||||
}
|
||||
leader, err := readLeader(pgid)
|
||||
if err != nil || leader.key != p.leaderKey || (leader.state != "T" && leader.state != "t") || unix.PidfdSendSignal(leaderFD, 0, nil, 0) != nil {
|
||||
if time.Now().After(deadline) {
|
||||
p.captureExpired(t, "leader incarnation not held during member capture")
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
refs[leader.key] = leaderFD
|
||||
members := miniGroupMembers(t, pgid)
|
||||
stopped := true
|
||||
for _, m := range members {
|
||||
fd, ok := refs[m.key]
|
||||
if !ok {
|
||||
fd, err = unix.PidfdOpen(m.pid, 0)
|
||||
if err != nil {
|
||||
if errors.Is(err, unix.ESRCH) {
|
||||
stopped = false
|
||||
continue
|
||||
}
|
||||
miniFailStop(t, fmt.Sprintf("cannot own descendant: %v", err))
|
||||
}
|
||||
current, err := miniProc(m.pid)
|
||||
if err != nil || current.key != m.key || current.group != pgid {
|
||||
_ = unix.Close(fd)
|
||||
stopped = false
|
||||
continue
|
||||
}
|
||||
refs[m.key] = fd
|
||||
}
|
||||
if m.state != "T" && m.state != "t" {
|
||||
stopped = false
|
||||
if err := p.signalFD(fd, unix.SIGSTOP); err != nil && !errors.Is(err, unix.ESRCH) {
|
||||
miniFailStop(t, fmt.Sprintf("cannot stop descendant: %v", err))
|
||||
}
|
||||
}
|
||||
}
|
||||
if stopped {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
p.captureExpired(t, "descendant capture did not quiesce")
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
for _, fd := range refs {
|
||||
_ = p.signalFD(fd, unix.SIGTERM)
|
||||
}
|
||||
for _, fd := range refs {
|
||||
_ = p.signalFD(fd, unix.SIGCONT)
|
||||
}
|
||||
select {
|
||||
case <-p.done:
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
for _, fd := range refs {
|
||||
_ = p.signalFD(fd, unix.SIGKILL)
|
||||
}
|
||||
_ = p.join(t, 5*time.Second)
|
||||
p.assertStopped(t)
|
||||
}
|
||||
|
||||
// A leader that exits as the capture window closes settles through assertStopped.
|
||||
func (p *ownedMini) captureExpired(t *testing.T, why string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-p.done:
|
||||
p.assertStopped(t)
|
||||
default:
|
||||
miniFailStop(t, why)
|
||||
}
|
||||
}
|
||||
func (p *ownedMini) assertStopped(t *testing.T) {
|
||||
t.Helper()
|
||||
wait := p.censusWait
|
||||
if wait == 0 {
|
||||
wait = 5 * time.Second
|
||||
}
|
||||
deadline := time.Now().Add(wait)
|
||||
census := func() []int {
|
||||
if p.census != nil {
|
||||
return p.census()
|
||||
}
|
||||
return miniGroupLive(t, p.cmd.Process.Pid)
|
||||
}
|
||||
for {
|
||||
live := census()
|
||||
// A /proc listing is not atomic: a member can fork then disappear
|
||||
// between list and stat. Signal 0 is only an existence query (never a
|
||||
// numeric effect signal); ESRCH proves the entire group is now absent.
|
||||
absent := false
|
||||
if p.groupExists != nil {
|
||||
absent = !p.groupExists()
|
||||
} else {
|
||||
err := unix.Kill(-p.cmd.Process.Pid, 0)
|
||||
absent = errors.Is(err, unix.ESRCH)
|
||||
}
|
||||
// A member counted before ESRCH may have exited in between: count
|
||||
// again, so only a member still listed holds the settlement.
|
||||
if len(live) != 0 && absent {
|
||||
live = census()
|
||||
}
|
||||
if len(live) == 0 && absent {
|
||||
select {
|
||||
case <-p.done:
|
||||
p.settle()
|
||||
return
|
||||
default:
|
||||
miniFailStop(t, "empty group but leader not joined")
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
if len(live) == 0 {
|
||||
miniFailStop(t, "owned group still exists with no live member listed: a member the census missed, or zombies its new parent does not reap")
|
||||
}
|
||||
miniFailStop(t, fmt.Sprintf("owned group has live residue %v", live))
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
type miniProcInfo struct {
|
||||
pid, group int
|
||||
state, key string
|
||||
}
|
||||
|
||||
func miniProc(pid int) (miniProcInfo, error) {
|
||||
b, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
|
||||
if err != nil {
|
||||
return miniProcInfo{}, err
|
||||
}
|
||||
end := strings.LastIndexByte(string(b), ')')
|
||||
if end < 0 {
|
||||
return miniProcInfo{}, fmt.Errorf("invalid proc stat")
|
||||
}
|
||||
fields := strings.Fields(string(b[end+1:]))
|
||||
if len(fields) < 20 {
|
||||
return miniProcInfo{}, fmt.Errorf("short proc stat")
|
||||
}
|
||||
group, err := strconv.Atoi(fields[2])
|
||||
if err != nil {
|
||||
return miniProcInfo{}, err
|
||||
}
|
||||
return miniProcInfo{pid: pid, group: group, state: fields[0], key: strconv.Itoa(pid) + ":" + fields[19]}, nil
|
||||
}
|
||||
func miniGroupMembers(t *testing.T, pgid int) []miniProcInfo {
|
||||
entries, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
miniFailStop(t, err.Error())
|
||||
}
|
||||
var members []miniProcInfo
|
||||
for _, entry := range entries {
|
||||
pid, err := strconv.Atoi(entry.Name())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
info, err := miniProc(pid)
|
||||
if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
miniFailStop(t, err.Error())
|
||||
}
|
||||
if info.group == pgid && info.state != "Z" && info.state != "X" {
|
||||
members = append(members, info)
|
||||
}
|
||||
}
|
||||
return members
|
||||
}
|
||||
func miniGroupLive(t *testing.T, pgid int) []int {
|
||||
var live []int
|
||||
for _, m := range miniGroupMembers(t, pgid) {
|
||||
live = append(live, m.pid)
|
||||
}
|
||||
return live
|
||||
}
|
||||
|
||||
// An intentionally TERM-ignoring descendant exercises the safety net itself.
|
||||
func TestMiniOwnedGroupCleanupStopsDescendants(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap '' TERM; sleep 60 & echo ready; wait")
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !strings.Contains(p.output.String(), "ready") {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("fixture did not start")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if live := miniGroupLive(t, p.cmd.Process.Pid); len(live) < 2 {
|
||||
t.Fatalf("descendant fixture not reached: %v", live)
|
||||
}
|
||||
p.stop(t)
|
||||
select {
|
||||
case <-p.done:
|
||||
default:
|
||||
t.Fatal("leader not joined")
|
||||
}
|
||||
}
|
||||
|
||||
// This real process settles normally before its registered cleanup runs. A
|
||||
// later cleanup must not dispatch anything to its old group or descriptor.
|
||||
func TestMiniSettledCleanupDoesNotSignal(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
p := startOwnedMini(t, ctx, "/bin/true")
|
||||
if err := p.join(t, 3*time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.assertStopped(t)
|
||||
before := p.dispatches.Load()
|
||||
p.stop(t)
|
||||
if got := p.dispatches.Load(); got != before {
|
||||
t.Fatalf("settled cleanup dispatched %d signals", got-before)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiniCleanupFailStopAndSettlement(t *testing.T) {
|
||||
for _, mode := range []string{"join", "residue", "missed-member", "settled", "late-exit-settled", "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue", "natural", "watchdog"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "cleanup-ran")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("MINI_CLEANUP_CONTROL", mode)
|
||||
t.Setenv("MINI_CLEANUP_MARKER", marker)
|
||||
p := startOwnedMini(t, ctx, self, "-test.run=^TestMiniCleanupFailStopHelper$")
|
||||
err = p.join(t, 3*time.Second)
|
||||
p.assertStopped(t)
|
||||
_, statErr := os.Stat(marker)
|
||||
if mode == "settled" || mode == "late-exit-settled" || mode == "capture-settled" || mode == "capture-expired-settled" || mode == "natural" {
|
||||
if err != nil || statErr != nil {
|
||||
t.Fatalf("positive cleanup twin: err=%v marker=%v", err, statErr)
|
||||
}
|
||||
} else if mode == "watchdog" {
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) || exit.ExitCode() != 1 || !strings.Contains(p.output.String(), "watchdog intervened") || statErr != nil {
|
||||
t.Fatalf("watchdog cannot prove natural cleanup: err=%v marker=%v output=%s", err, statErr, p.output.String())
|
||||
}
|
||||
} else {
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) || exit.ExitCode() != miniFailStopExit || !errors.Is(statErr, os.ErrNotExist) {
|
||||
t.Fatalf("fail-stop %s: err=%v marker=%v output=%s", mode, err, statErr, p.output.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestMiniCleanupFailStopHelper(t *testing.T) {
|
||||
mode := os.Getenv("MINI_CLEANUP_CONTROL")
|
||||
if mode == "" {
|
||||
t.Skip("isolated fail-stop helper")
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := os.WriteFile(os.Getenv("MINI_CLEANUP_MARKER"), []byte("cleanup ran"), 0o600); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
p := &ownedMini{done: make(chan struct{}), leaderFD: -1, censusWait: 10 * time.Millisecond, groupExists: func() bool { return false }}
|
||||
switch mode {
|
||||
case "join":
|
||||
p.join(t, 10*time.Millisecond)
|
||||
case "residue":
|
||||
close(p.done)
|
||||
p.census = func() []int { return []int{1234} }
|
||||
p.assertStopped(t)
|
||||
case "missed-member":
|
||||
close(p.done)
|
||||
p.census = func() []int { return nil }
|
||||
p.groupExists = func() bool { return true }
|
||||
p.assertStopped(t)
|
||||
case "settled":
|
||||
close(p.done)
|
||||
p.census = func() []int { return nil }
|
||||
p.assertStopped(t)
|
||||
case "late-exit-settled":
|
||||
close(p.done)
|
||||
counted := false
|
||||
p.census = func() []int {
|
||||
if counted {
|
||||
return nil
|
||||
}
|
||||
counted = true
|
||||
time.Sleep(2 * p.censusWait) // the member exits as the window closes
|
||||
return []int{1234}
|
||||
}
|
||||
p.assertStopped(t)
|
||||
case "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue":
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
p := startOwnedMini(t, ctx, "/bin/sleep", "60")
|
||||
p.censusWait = 10 * time.Millisecond
|
||||
if strings.HasSuffix(mode, "-residue") {
|
||||
p.census = func() []int { return []int{1234} }
|
||||
p.groupExists = func() bool { return true }
|
||||
}
|
||||
p.captureLeader = func(int) (miniProcInfo, error) {
|
||||
if strings.HasPrefix(mode, "capture-expired") {
|
||||
time.Sleep(1100 * time.Millisecond) // past the one-second capture window
|
||||
}
|
||||
_ = p.signalLeader(unix.SIGKILL)
|
||||
_ = p.join(t, time.Second)
|
||||
return miniProcInfo{}, os.ErrNotExist
|
||||
}
|
||||
p.stopGroup(t)
|
||||
case "natural", "watchdog":
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
bin, args := "/bin/false", []string{}
|
||||
if mode == "watchdog" {
|
||||
bin, args = "/bin/sleep", []string{"60"}
|
||||
}
|
||||
p := startOwnedMini(t, ctx, bin, args...)
|
||||
if mode == "watchdog" {
|
||||
cancel()
|
||||
}
|
||||
_ = p.join(t, time.Second)
|
||||
p.assertStopped(t)
|
||||
p.assertNaturalExit(t)
|
||||
default:
|
||||
t.Fatal("invalid control")
|
||||
}
|
||||
}
|
||||
|
||||
// A four-second shutdown exceeds the old WaitDelay. The context watchdog
|
||||
// must let it finish rather than kill its leader before children are stopped.
|
||||
func TestMiniContextAllowsChildShutdownGrace(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap 'sleep 4; echo graceful; exit 0' TERM; echo ready; while :; do sleep .05; done")
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !strings.Contains(p.output.String(), "ready") {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("shutdown fixture not ready")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
_ = p.join(t, miniShutdownGrace+10*time.Second)
|
||||
p.assertStopped(t)
|
||||
if !strings.Contains(p.output.String(), "graceful") {
|
||||
t.Fatalf("shutdown killed prematurely: %s", p.output.String())
|
||||
}
|
||||
}
|
||||
@@ -169,21 +169,6 @@ 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,7 +10,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -536,9 +535,6 @@ 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,157 @@
|
||||
//go:build linux && subprocess && chunkstore_integration && systemd_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A plain walstore holder started under the shipped unit's restart policy and
|
||||
// start limit while blockmaster gives no reply (nothing listens on its
|
||||
// address) waits inside the process for its store record: through a
|
||||
// 5-minute outage the unit stays active with no restart, /status says
|
||||
// waiting_for_master and the journal names the wait; once blockmaster
|
||||
// starts, the volume serves with no restart. Before, the start exited 75 at
|
||||
// once, the unit restarted every RestartSec, and after StartLimitBurst
|
||||
// starts it stayed failed even once the master came back.
|
||||
//
|
||||
// A runtime unit file (/run/systemd/system) stands for the installed unit.
|
||||
func TestWalstoreUnitWaitsForAnUnreachableMasterWithoutBurningItsStartLimit(t *testing.T) {
|
||||
if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" {
|
||||
t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof")
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
t.Fatal("systemd qualification needs root")
|
||||
}
|
||||
shipped := gap1ShippedPolicy(t)
|
||||
interval, burst := shippedStartLimit(t)
|
||||
|
||||
exe := filepath.Join(t.TempDir(), "blockvolume")
|
||||
if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" {
|
||||
exe = filepath.Join(d, "blockvolume")
|
||||
} else {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
out, err := exec.CommandContext(ctx, "go", "build", "-o", exe, "github.com/seaweedfs/seaweed-block/cmd/blockvolume").CombinedOutput()
|
||||
cancel()
|
||||
if err != nil {
|
||||
t.Fatalf("build blockvolume: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
masterBin := filepath.Join(filepath.Dir(exe), "blockmaster")
|
||||
if os.Getenv("SWBLOCK_TEST_BINS") == "" {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
out, err := exec.CommandContext(ctx, "go", "build", "-o", masterBin, "github.com/seaweedfs/seaweed-block/cmd/blockmaster").CombinedOutput()
|
||||
cancel()
|
||||
if err != nil {
|
||||
t.Fatalf("build blockmaster: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
master, data, ctrl, statusAddr, nvme := handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t)
|
||||
// nothing listens at master until blockmaster starts below
|
||||
|
||||
unit := fmt.Sprintf("swb-c04-walstore-wait-%d.service", os.Getpid())
|
||||
writeRuntimeUnit(t, unit, exe, []string{"--master", master, "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
|
||||
"--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--durable-impl", "walstore",
|
||||
"--durable-blocks", "64", "--nvme-listen", nvme, "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"}, []string{
|
||||
"StartLimitIntervalSec=" + interval,
|
||||
"StartLimitBurst=" + burst,
|
||||
}, []string{
|
||||
"Restart=on-failure",
|
||||
"RestartSec=" + shipped["RestartSec"],
|
||||
"RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"],
|
||||
"TimeoutStopSec=" + shipped["TimeoutStopSec"],
|
||||
})
|
||||
if out, err := runSystemctl("start", unit); err != nil {
|
||||
t.Fatalf("start %s: %v %s", unit, err, out)
|
||||
}
|
||||
// A 5-minute outage: on the old behaviour the unit has failed after
|
||||
// StartLimitBurst starts RestartSec apart, well before this.
|
||||
window := 5 * time.Minute
|
||||
started := time.Now()
|
||||
var state map[string]string
|
||||
for time.Since(started) < window {
|
||||
time.Sleep(2 * time.Second)
|
||||
s, err := gap1ReadUnit(unit)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
state = s
|
||||
if s["ActiveState"] == "failed" {
|
||||
t.Fatalf("the unit gave up %v into the master outage: NRestarts %s Result %s; journal: %s",
|
||||
time.Since(started).Round(time.Second), s["NRestarts"], s["Result"], lastLines(unitJournal(unit), 15))
|
||||
}
|
||||
}
|
||||
journal := unitJournal(unit)
|
||||
t.Logf("walstore unit after %v with no master: ActiveState %s NRestarts %s", window, state["ActiveState"], state["NRestarts"])
|
||||
if state["ActiveState"] != "active" || state["NRestarts"] != "0" {
|
||||
t.Fatalf("after %v: ActiveState %s NRestarts %s; want active with no restart; journal: %s", window, state["ActiveState"], state["NRestarts"], lastLines(journal, 15))
|
||||
}
|
||||
if !strings.Contains(journal, "waiting for the master at "+master+" to answer this replica's store record: no reply for") {
|
||||
t.Fatalf("the journal does not name the wait: %s", lastLines(journal, 15))
|
||||
}
|
||||
if reason := statusNotReadyReason(statusAddr, "v1"); reason != "waiting_for_master" {
|
||||
t.Fatalf("/status NotReadyReason %q during the wait; want waiting_for_master", reason)
|
||||
}
|
||||
|
||||
// blockmaster starts: the waiting process goes on and serves, with no restart.
|
||||
dir := t.TempDir()
|
||||
topo := filepath.Join(dir, "topology.yaml")
|
||||
nl := string(rune(10))
|
||||
if err := os.WriteFile(topo, []byte("volumes:"+nl+" - volume_id: v1"+nl+" slots:"+nl+" - replica_id: r1"+nl+" server_id: s1"+nl), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mlog, err := os.Create(filepath.Join(dir, "blockmaster.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc := exec.Command(masterBin, "--authority-store", filepath.Join(dir, "master"), "--listen", master, "--topology", topo, "--expected-slots-per-volume", "1")
|
||||
mc.Stdout, mc.Stderr = mlog, mlog
|
||||
if err := mc.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = mc.Process.Kill(); _ = mc.Wait(); mlog.Close() })
|
||||
back := time.Now()
|
||||
for !volumeFrontendReady(statusAddr, "v1") {
|
||||
if time.Since(back) > 2*time.Minute {
|
||||
b, _ := os.ReadFile(mlog.Name())
|
||||
t.Fatalf("v1 never served after blockmaster started; journal: %s; blockmaster: %s", lastLines(unitJournal(unit), 15), lastLines(string(b), 10))
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
s, _ := gap1ReadUnit(unit)
|
||||
t.Logf("walstore unit served %v after blockmaster started: ActiveState %s NRestarts %s", time.Since(back).Round(time.Second), s["ActiveState"], s["NRestarts"])
|
||||
if s["ActiveState"] != "active" || s["NRestarts"] != "0" {
|
||||
t.Fatalf("after serving: ActiveState %s NRestarts %s; want active with no restart", s["ActiveState"], s["NRestarts"])
|
||||
}
|
||||
}
|
||||
|
||||
// statusNotReadyReason is /status's NotReadyReason for vol ("" when unreadable).
|
||||
func statusNotReadyReason(statusAddr, vol string) string {
|
||||
resp, err := http.Get("http://" + statusAddr + "/status?volume=" + vol)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var p struct{ NotReadyReason string }
|
||||
if json.NewDecoder(resp.Body).Decode(&p) != nil {
|
||||
return ""
|
||||
}
|
||||
return p.NotReadyReason
|
||||
}
|
||||
|
||||
func lastLines(s string, n int) string {
|
||||
lines := strings.Split(strings.TrimSpace(s), string(rune(10)))
|
||||
if len(lines) > n {
|
||||
lines = lines[len(lines)-n:]
|
||||
}
|
||||
return strings.Join(lines, " | ")
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -13,6 +15,57 @@ import (
|
||||
// its durable open.
|
||||
const replicaStoreQueryTimeout = 10 * time.Second
|
||||
|
||||
// replicaStoreRetryEvery paces the store record read while blockmaster gives
|
||||
// no reply, and replicaStoreWaitLogEvery its log line. Vars only so a test
|
||||
// can shorten them.
|
||||
var (
|
||||
replicaStoreRetryEvery = 2 * time.Second
|
||||
replicaStoreWaitLogEvery = 30 * time.Second
|
||||
)
|
||||
|
||||
// readReplicaStore reads the master's record of this replica's store. While
|
||||
// blockmaster gives no reply (volume.MasterCallClass: neither contact nor a
|
||||
// credentials refusal) the process waits and reads again, with no bound, so
|
||||
// a start during a master outage does not exit and burn the unit's start
|
||||
// limit. It runs before the store is opened or created, so nothing is
|
||||
// written meanwhile; waiting reports the wait (for /status) and the log
|
||||
// repeats it every replicaStoreWaitLogEvery with the master's address and the
|
||||
// time waited. Any answer, a credentials refusal, or ctx's end returns the
|
||||
// last result.
|
||||
func readReplicaStore(ctx context.Context, master string, read func(context.Context) (*control.GetReplicaStoreResponse, error), logf func(string, ...any), waiting func(bool)) (*control.GetReplicaStoreResponse, error) {
|
||||
var since, logged time.Time
|
||||
defer func() {
|
||||
if !since.IsZero() {
|
||||
waiting(false)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
qctx, cancel := context.WithTimeout(ctx, replicaStoreQueryTimeout)
|
||||
rec, err := read(qctx)
|
||||
cancel()
|
||||
contact, credentials := volume.MasterCallClass(err)
|
||||
if contact || credentials || ctx.Err() != nil {
|
||||
if !since.IsZero() && ctx.Err() == nil {
|
||||
logf("blockvolume: the master at %s answered this replica's store record after %s", master, time.Since(since).Round(time.Second))
|
||||
}
|
||||
return rec, err
|
||||
}
|
||||
if since.IsZero() {
|
||||
since = time.Now()
|
||||
waiting(true)
|
||||
}
|
||||
if logged.IsZero() || time.Since(logged) >= replicaStoreWaitLogEvery {
|
||||
logged = time.Now()
|
||||
logf("blockvolume: waiting for the master at %s to answer this replica's store record: no reply for %s (%v); nothing is created or written meanwhile", master, time.Since(since).Round(time.Second), err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return rec, err
|
||||
case <-time.After(replicaStoreRetryEvery):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// storeAdmission is how the durable open may treat the local store: with
|
||||
// mustExist it never creates one (a missing store is refused at the open
|
||||
// itself), and a nonzero id is the store it must find.
|
||||
@@ -27,7 +80,8 @@ type storeAdmission struct {
|
||||
// exists:
|
||||
//
|
||||
// answer store present store absent
|
||||
// error / timeout refuse 75 refuse 75
|
||||
// no reply (waited out in-process by readReplicaStore; only a shutdown ends the wait)
|
||||
// other error refuse 75 refuse 75
|
||||
// older master (Unimplemented) open as before refuse 75 master_too_old
|
||||
// not listed open as before refuse 75 volume_not_listed
|
||||
// listed, replicated, non-primary open or create (peer rebuild path, as before)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// The store record read waits inside the process while blockmaster gives no
|
||||
// reply (Unavailable, DeadlineExceeded, a timed-out read), logging once, and
|
||||
// returns the first answer; any other result returns at once (a credentials
|
||||
// refusal, an older master, an answered error), and so does a shutdown.
|
||||
func TestReadReplicaStoreWaitsOnlyWhileTheMasterGivesNoReply(t *testing.T) {
|
||||
prev := replicaStoreRetryEvery
|
||||
replicaStoreRetryEvery = time.Millisecond
|
||||
t.Cleanup(func() { replicaStoreRetryEvery = prev })
|
||||
want := &control.GetReplicaStoreResponse{Listed: true}
|
||||
script := func(errs ...error) (func(context.Context) (*control.GetReplicaStoreResponse, error), *int) {
|
||||
calls := 0
|
||||
return func(context.Context) (*control.GetReplicaStoreResponse, error) {
|
||||
calls++
|
||||
if calls <= len(errs) {
|
||||
return nil, errs[calls-1]
|
||||
}
|
||||
return want, nil
|
||||
}, &calls
|
||||
}
|
||||
logs := 0
|
||||
logf := func(string, ...any) { logs++ }
|
||||
var states []bool
|
||||
waiting := func(w bool) { states = append(states, w) }
|
||||
|
||||
read, calls := script(status.Error(codes.Unavailable, "connection refused"), status.Error(codes.DeadlineExceeded, "deadline"), context.DeadlineExceeded)
|
||||
if rec, err := readReplicaStore(context.Background(), "127.0.0.1:9180", read, logf, waiting); err != nil || rec != want || *calls != 4 || logs != 2 {
|
||||
t.Fatalf("no reply three times, then an answer: rec %v err %v calls %d logs %d (want the answer after 4 reads, 2 log lines)", rec, err, *calls, logs)
|
||||
}
|
||||
if len(states) != 2 || !states[0] || states[1] {
|
||||
t.Fatalf("the wait was reported %v; want waiting, then not", states)
|
||||
}
|
||||
// The log line repeats at its cadence, not at every read.
|
||||
prevLog := replicaStoreWaitLogEvery
|
||||
replicaStoreWaitLogEvery = 50 * time.Millisecond
|
||||
t.Cleanup(func() { replicaStoreWaitLogEvery = prevLog })
|
||||
logs, slow := 0, 0
|
||||
slowRead := func(context.Context) (*control.GetReplicaStoreResponse, error) {
|
||||
slow++
|
||||
if slow > 60 {
|
||||
return want, nil
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
return nil, status.Error(codes.Unavailable, "down")
|
||||
}
|
||||
if _, err := readReplicaStore(context.Background(), "m", slowRead, logf, func(bool) {}); err != nil || logs < 3 || logs > 12 {
|
||||
t.Fatalf("about 300 ms of no reply at a 50 ms cadence logged %d lines (err %v); want a few, not one per read", logs, err)
|
||||
}
|
||||
for _, e := range []error{status.Error(codes.Unauthenticated, "bad cert"), status.Error(codes.Unimplemented, "older"), status.Error(codes.Internal, "boom"), errors.New("plain")} {
|
||||
read, calls := script(e)
|
||||
if _, err := readReplicaStore(context.Background(), "m", read, logf, func(bool) {}); !errors.Is(err, e) || *calls != 1 {
|
||||
t.Fatalf("%v: waited (%d reads) instead of returning it", e, *calls)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
never := func(context.Context) (*control.GetReplicaStoreResponse, error) {
|
||||
cancel()
|
||||
return nil, status.Error(codes.Unavailable, "down")
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := readReplicaStore(ctx, "m", never, logf, func(bool) {}); done <- err }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if status.Code(err) != codes.Unavailable {
|
||||
t.Fatalf("a shutdown during the wait: %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("a shutdown did not end the wait")
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,6 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
)
|
||||
|
||||
// The test lock directory override is refused under systemd
|
||||
@@ -52,42 +50,3 @@ func TestVolumeLockDirTestOnlyHiddenFromHelp(t *testing.T) {
|
||||
t.Fatalf("--help lists the test override:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// Without the override the lock directory stays the host one: the provider
|
||||
// gets no override, so it uses durable.HostVolumeLockDir.
|
||||
func TestVolumeLockDirDefaultIsTheHostDirectory(t *testing.T) {
|
||||
t.Setenv("INVOCATION_ID", "")
|
||||
f, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.volumeLockDirTestOnly != "" {
|
||||
t.Fatalf("a default start overrides the lock directory: %q", f.volumeLockDirTestOnly)
|
||||
}
|
||||
if durable.HostVolumeLockDir != "/run/sw-block/locks" {
|
||||
t.Fatalf("the host lock directory moved: %s", durable.HostVolumeLockDir)
|
||||
}
|
||||
}
|
||||
|
||||
// INV-WS-ONE-PROCESS-PER-HOST-001, the normal start: a start under systemd
|
||||
// (INVOCATION_ID set, as every shipped unit runs) keeps the host-wide volume
|
||||
// lock. Without the override it gets no lock directory of its own, so the
|
||||
// provider uses the host one; with the hidden test-only override it is
|
||||
// refused, naming the host lock directory it would have bypassed. Only a
|
||||
// start outside systemd (a test, or mini, which drops INVOCATION_ID from its
|
||||
// children and keeps data and lock under its --dir) may move the lock.
|
||||
func TestNormalStartKeepsTheHostVolumeLock(t *testing.T) {
|
||||
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore")
|
||||
t.Setenv("INVOCATION_ID", "0123456789abcdef")
|
||||
f, err := parseFlags(append([]string(nil), base...))
|
||||
if err != nil || f.volumeLockDirTestOnly != "" {
|
||||
t.Fatalf("a unit start without the override: lock dir %q, err %v; want the host directory", f.volumeLockDirTestOnly, err)
|
||||
}
|
||||
if durable.HostVolumeLockDir != "/run/sw-block/locks" {
|
||||
t.Fatalf("the host lock directory moved: %s", durable.HostVolumeLockDir)
|
||||
}
|
||||
_, err = parseFlags(append(append([]string(nil), base...), "--"+volumeLockDirTestOnlyFlag+"="+t.TempDir()))
|
||||
if err == nil || !strings.Contains(err.Error(), durable.HostVolumeLockDir) {
|
||||
t.Fatalf("a unit start with the override: %v; want a refusal naming %s", err, durable.HostVolumeLockDir)
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
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,7 +11,6 @@ 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"
|
||||
)
|
||||
@@ -19,7 +18,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", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")))
|
||||
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", status.Error(codes.Unavailable, "connection refused"))
|
||||
}
|
||||
|
||||
func TestOpsChunkCatalogUnavailableIsTyped(t *testing.T) {
|
||||
@@ -98,14 +97,14 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
|
||||
code string
|
||||
retry bool
|
||||
}{
|
||||
{"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},
|
||||
{"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},
|
||||
{"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"), "not_authorized", false},
|
||||
{"permission", status.Error(codes.PermissionDenied, "refused"), "internal", false},
|
||||
{"unknown", errors.New("unexpected implementation error"), "internal", false},
|
||||
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "bad_request", false},
|
||||
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "internal", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var out, diag bytes.Buffer
|
||||
@@ -115,15 +114,6 @@ 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 knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) {
|
||||
if chunkTransportFailure(err) || chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -25,7 +25,6 @@ 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 (
|
||||
@@ -68,15 +67,6 @@ 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) {
|
||||
@@ -86,7 +76,7 @@ func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunks
|
||||
switch {
|
||||
case err == nil:
|
||||
return -1
|
||||
case knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled):
|
||||
case chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) || chunkTransportFailure(err):
|
||||
return chunkResult(name, nil, err, stdout, stderr)
|
||||
case errors.Is(err, chunkstore.ErrNotSingleFiler):
|
||||
return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
@@ -187,41 +177,25 @@ 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 := answer.DoHTTP(chunkHTTPClient, req, answer.Unsent)
|
||||
resp, err := chunkHTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return chunkResult(name, nil, err, stdout, stderr)
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
responseFailure := func(cause error) int {
|
||||
// A 409 body can describe work after admission; status alone cannot
|
||||
// settle the original operation or authorize a new request identity.
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
if id, ok := body["requestID"].(string); ok && id != "" {
|
||||
cause = fmt.Errorf("HTTP 409 body is unusable; recover original request %s: %w", id, cause)
|
||||
} else {
|
||||
cause = fmt.Errorf("HTTP 409 body is unusable: %w", cause)
|
||||
}
|
||||
}
|
||||
if resp.StatusCode >= http.StatusBadRequest && resp.StatusCode != http.StatusConflict {
|
||||
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 responseFailure(err)
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "read the response: "+err.Error(), true)
|
||||
}
|
||||
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 responseFailure(fmt.Errorf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit))
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI,
|
||||
fmt.Sprintf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit), false)
|
||||
}
|
||||
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 responseFailure(fmt.Errorf("snapshot request %v: invalid operation admission; retry with the same --request-id against the original status address", body["requestID"]))
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid snapshot operation admission", false)
|
||||
}
|
||||
a.Raw = append([]byte(nil), out...)
|
||||
a.Location = resp.Header.Get("Location")
|
||||
@@ -242,20 +216,15 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
|
||||
}
|
||||
var e chunkErrBody
|
||||
if json.Unmarshal(out, &e) != nil || e.Code == "" {
|
||||
return responseFailure(fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))))
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))), false)
|
||||
}
|
||||
// The route's error body is already the CLI's error body: relay it.
|
||||
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)
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, chunkErrorAdvice(e.Code, e.Retryable, e.Message))
|
||||
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 policy.Exit
|
||||
return chunkErrorExit(chunkExitFailed, e.Code, e.Retryable)
|
||||
}
|
||||
|
||||
func chunkCut(args []string, stdout, stderr io.Writer) int {
|
||||
@@ -398,12 +367,27 @@ 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 {
|
||||
contract := answer.Chunk
|
||||
if name == "verify" {
|
||||
contract = answer.ChunkVerify
|
||||
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)
|
||||
}
|
||||
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 {
|
||||
@@ -438,11 +422,6 @@ 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
|
||||
@@ -470,15 +449,13 @@ 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 {
|
||||
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, "")))
|
||||
return policy.Exit
|
||||
return 75
|
||||
}
|
||||
return exit
|
||||
}
|
||||
func chunkErrorAdvice(code string, retryable bool, message string) string {
|
||||
if code == codeUnavailableCLI && retryable {
|
||||
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, message)))
|
||||
return policy.Cure
|
||||
return message + "; retry the same operation when the remote is reachable"
|
||||
}
|
||||
return message
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
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,7 +17,6 @@ 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"
|
||||
@@ -37,16 +36,15 @@ var restoreCreateRPC = func(ctx context.Context, master string, req *control.Cre
|
||||
}
|
||||
|
||||
// bCatalog dials the filer and opens the volume catalog; a command that
|
||||
// writes first passes the single-filer start check, then runs the chunk
|
||||
// condition probe; each runs within timeout. It returns exit -1 on success,
|
||||
// else the exit code after reporting.
|
||||
// writes first passes the single-filer start check. It returns exit -1 on
|
||||
// success, else the exit code after reporting.
|
||||
func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.BCatalog, func() error, int) {
|
||||
if filer == "" {
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false)
|
||||
}
|
||||
f, closeFn, err := dialChunkFiler(filer)
|
||||
if err != nil {
|
||||
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
|
||||
if chunkCanceled(err) || chunkTransportFailure(err) {
|
||||
return nil, nil, chunkResult(name, nil, err, stdout, stderr)
|
||||
}
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
@@ -69,11 +67,6 @@ func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdo
|
||||
if err != nil {
|
||||
return fail(err.Error())
|
||||
}
|
||||
if writes {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
cat.ProbeChunkGuard(ctx)
|
||||
cancel()
|
||||
}
|
||||
return cat, closeFn, -1
|
||||
}
|
||||
|
||||
@@ -152,7 +145,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 knownChunkFailure(err) && status.Code(err) != codes.NotFound {
|
||||
if chunkCanceled(err) || chunkTransportFailure(err) {
|
||||
return chunkResult(name, nil, err, c.stdout, c.stderr)
|
||||
}
|
||||
if status.Code(err) == codes.NotFound { // the master does not know the volume
|
||||
@@ -361,9 +354,7 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int {
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
var ref chunkstore.VolumeRef
|
||||
return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
u, err := cat.Usage(ctx, ref)
|
||||
u.MetadataGuard = ""
|
||||
return u, err
|
||||
return cat.Usage(ctx, ref)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -394,10 +385,21 @@ func chunkRestore(args []string, stdout, stderr io.Writer) int {
|
||||
VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID,
|
||||
})
|
||||
if err != nil {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
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`) || strings.Contains(out, "metadata_guard") {
|
||||
if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) {
|
||||
t.Fatalf("target usage: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" {
|
||||
|
||||
@@ -4,10 +4,7 @@ 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"
|
||||
@@ -15,47 +12,13 @@ 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 := link.Dial("127.0.0.1:1")
|
||||
conn, err := grpc.NewClient("127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A 409 can follow admission. Without its typed body, keep the original
|
||||
// operation unknown and preserve its request identity for recovery.
|
||||
func TestChunkUnusableConflictAnswerIsUnknown(t *testing.T) {
|
||||
for _, mode := range []string{"truncated", "malformed"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
receivedIDs := make(chan string, 1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var request struct {
|
||||
ID string `json:"requestID"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
receivedIDs <- request.ID
|
||||
if mode == "truncated" {
|
||||
w.Header().Set("Content-Length", "1000")
|
||||
}
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
fmt.Fprint(w, `{`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
var out, diag bytes.Buffer
|
||||
var admission snapshotCLIAdmission
|
||||
exit := chunkPost("snapshot", srv.URL, "/chunk/snapshot", time.Second, map[string]any{"volumeID": "v1", "name": "s1", "requestID": "original"}, &out, &diag, &admission)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
var receivedID string
|
||||
select {
|
||||
case receivedID = <-receivedIDs:
|
||||
default:
|
||||
t.Fatal("server did not receive the request")
|
||||
}
|
||||
if exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || admission.Accepted || receivedID != "original" || !strings.Contains(got.Message, "original") || !strings.Contains(got.Message, "recover") || strings.Contains(got.Message, "nothing applied") {
|
||||
t.Fatalf("exit=%d answer=%+v accepted=%v stderr=%s", exit, got, admission.Accepted, &diag)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkConflictLoopKeepsOriginalRequest(t *testing.T) {
|
||||
for _, row := range []struct {
|
||||
name, body string
|
||||
truncated bool
|
||||
posts, exit int
|
||||
}{
|
||||
{"unreadable", `{`, true, 2, 0},
|
||||
{"malformed", `{`, false, 2, 0},
|
||||
{"typed-retryable", `{"code":"head_conflict","retryable":true,"message":"HEAD changed"}`, false, 2, 0},
|
||||
{"typed-terminal", `{"code":"snapshot_limit","retryable":false,"message":"limit reached"}`, false, 1, 1},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
shortLoop(t, 200*time.Millisecond, time.Millisecond, 2*time.Millisecond)
|
||||
var mu sync.Mutex
|
||||
var received []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
fmt.Fprint(w, `{}`)
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
received = append(received, body)
|
||||
n := len(received)
|
||||
mu.Unlock()
|
||||
if n == 1 {
|
||||
if row.truncated {
|
||||
w.Header().Set("Content-Length", "1000")
|
||||
}
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
fmt.Fprint(w, row.body)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"volumeID":"v1","name":"s1","headGen":7}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
var out, diag bytes.Buffer
|
||||
exit := chunkPostLoop("snapshot", srv.URL, "/chunk/snapshot", time.Second, map[string]any{"volumeID": "v1", "name": "s1", "requestID": "original"}, &out, &diag)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if exit != row.exit || len(received) != row.posts {
|
||||
t.Fatalf("exit=%d posts=%d wantExit=%d wantPosts=%d out=%s stderr=%s", exit, len(received), row.exit, row.posts, &out, &diag)
|
||||
}
|
||||
for _, q := range received {
|
||||
if q["volumeID"] != "v1" || q["name"] != "s1" || q["requestID"] != "original" {
|
||||
t.Fatalf("recovery changed request: %+v", q)
|
||||
}
|
||||
}
|
||||
if row.name == "typed-terminal" {
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if got.Code != "snapshot_limit" || got.Retryable {
|
||||
t.Fatalf("terminal answer changed: %+v", got)
|
||||
}
|
||||
} else if row.name != "typed-retryable" && !strings.Contains(diag.String(), "request 1 ended: outcome_unknown") {
|
||||
t.Fatalf("lost conflict must remain unknown: %s", &diag)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -12,30 +13,28 @@ import (
|
||||
"testing/synctest"
|
||||
)
|
||||
|
||||
// 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 {
|
||||
// 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 {
|
||||
t.Helper()
|
||||
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)
|
||||
}
|
||||
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}
|
||||
}}
|
||||
old := chunkHTTPClient
|
||||
chunkHTTPClient = &http.Client{}
|
||||
t.Cleanup(func() { chunkHTTPClient = old })
|
||||
return "http://" + addr
|
||||
chunkHTTPClient = &http.Client{Transport: transport}
|
||||
t.Cleanup(func() { transport.CloseIdleConnections(); chunkHTTPClient = old })
|
||||
return calls
|
||||
}
|
||||
|
||||
func TestPlainDetachRefusedDialIsRemoteUnavailable(t *testing.T) {
|
||||
addr := installRefusedHolderDial(t)
|
||||
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", addr)
|
||||
calls := installRefusedHolderDial(t)
|
||||
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder")
|
||||
e := chunkErrorOut(t, out)
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ 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"
|
||||
)
|
||||
@@ -33,7 +32,7 @@ func TestChunkErrorFamilyAnswerTable(t *testing.T) {
|
||||
advice string
|
||||
only string
|
||||
}{
|
||||
{"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", ""},
|
||||
{"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", ""},
|
||||
{"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(), ""},
|
||||
@@ -157,7 +156,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 != 3 || answer.Code != "outcome_unknown" || !answer.Retryable {
|
||||
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
|
||||
t.Fatalf("exit=%d answer=%+v", exit, answer)
|
||||
}
|
||||
retained, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
|
||||
@@ -177,20 +176,8 @@ 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; 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" {
|
||||
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" {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// A command that changes chunk metadata runs the chunk condition probe on
|
||||
// the catalog it opens, so its adoptions and marks send the filer's chunk
|
||||
// condition as blockvolume's do; a read-only command writes nothing.
|
||||
func TestOpsChunkWritingCatalogRunsTheChunkConditionProbe(t *testing.T) {
|
||||
mem := newMemChunkStore()
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
|
||||
for _, tc := range []struct {
|
||||
writes bool
|
||||
guard string
|
||||
}{{true, chunkstore.MetadataGuardChunks}, {false, chunkstore.MetadataGuardReread}} {
|
||||
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", tc.writes, time.Minute, io.Discard, io.Discard)
|
||||
if exit >= 0 {
|
||||
t.Fatalf("writes=%v: catalog open exited %d", tc.writes, exit)
|
||||
}
|
||||
_ = closeFn()
|
||||
if got := cat.MetadataGuard(); got != tc.guard {
|
||||
t.Fatalf("writes=%v: metadata guard %q, want %q", tc.writes, got, tc.guard)
|
||||
}
|
||||
left, err := mem.ListEntries(context.Background(), "/blocks", "", "", 100)
|
||||
if err != nil || len(left) != 0 {
|
||||
t.Fatalf("writes=%v: %d entries left under the catalog base (%v)", tc.writes, len(left), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stalledProbeFiler stalls the probe's disposable HEAD create until its
|
||||
// context ends.
|
||||
type stalledProbeFiler struct{ *memChunkStore }
|
||||
|
||||
func (f stalledProbeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
|
||||
if inStartupProbe(dir, e.GetName()) {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
return f.memChunkStore.CreateEntry(ctx, dir, e, oExcl)
|
||||
}
|
||||
|
||||
// The probe runs within the command's --timeout: after a passing census, a
|
||||
// probe stalled on its filer ends at the timeout, leaves the guard off and
|
||||
// refuses nothing.
|
||||
func TestOpsChunkWritingCatalogProbeIsBoundedByTheTimeout(t *testing.T) {
|
||||
mem := newMemChunkStore()
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
return stalledProbeFiler{mem}, func() error { return nil }, nil
|
||||
}
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
|
||||
start := time.Now()
|
||||
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", true, 200*time.Millisecond, io.Discard, io.Discard)
|
||||
if exit >= 0 {
|
||||
t.Fatalf("a stalled probe refused the command: exit %d", exit)
|
||||
}
|
||||
_ = closeFn()
|
||||
if took := time.Since(start); took > 5*time.Second {
|
||||
t.Fatalf("a stalled probe held the command %v past its 200ms --timeout", took)
|
||||
}
|
||||
if got := cat.MetadataGuard(); got != chunkstore.MetadataGuardReread {
|
||||
t.Fatalf("metadata guard %q after a stalled probe, want %q", got, chunkstore.MetadataGuardReread)
|
||||
}
|
||||
}
|
||||
|
||||
// betweenLookupAndUpdate runs before, once it is set, ahead of the next
|
||||
// update: what other writers do while a stale one is between its lookup and
|
||||
// its update.
|
||||
type betweenLookupAndUpdate struct {
|
||||
*memChunkStore
|
||||
before func()
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) runBefore() {
|
||||
if b := f.before; b != nil {
|
||||
f.before = nil
|
||||
b()
|
||||
}
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
f.runBefore()
|
||||
return f.memChunkStore.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
|
||||
func (f *betweenLookupAndUpdate) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
|
||||
f.runBefore()
|
||||
return f.memChunkStore.UpdateEntryIfChunks(ctx, dir, e, expected, fids)
|
||||
}
|
||||
|
||||
// A writing command's adoption that paused between its lookup and its update
|
||||
// does not land on an object a cleaner deleted and another executor created
|
||||
// again in between, through the store of the catalog bCatalog opens. An
|
||||
// unchanged object is still adopted; a catalog that ran no probe lets the
|
||||
// stale write through.
|
||||
func TestOpsChunkStaleCLIAdoptionDoesNotOverwriteARecreatedObject(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
writes, recreate bool
|
||||
}{
|
||||
{"probed catalog, recreated object", true, true},
|
||||
{"probed catalog, unchanged object", true, false},
|
||||
{"catalog without the probe, recreated object", false, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := newMemChunkStore()
|
||||
hooked := &betweenLookupAndUpdate{memChunkStore: mem}
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return hooked, func() error { return nil }, nil }
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
|
||||
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", tc.writes, time.Minute, io.Discard, io.Discard)
|
||||
if exit >= 0 {
|
||||
t.Fatalf("catalog open exited %d", exit)
|
||||
}
|
||||
defer closeFn()
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: "v", ID: id}
|
||||
stale, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
others, err := chunkstore.NewLayoutStore(mem, mem, path.Join("/blocks", ref.Dir()), id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := bytes.Repeat([]byte{0x5a}, 4096)
|
||||
rel := layout.NameChunk(1, data).Path()
|
||||
obj := path.Join("/blocks", ref.Dir(), rel)
|
||||
fid := func() string {
|
||||
e, err := mem.LookupEntry(ctx, path.Dir(obj), path.Base(obj))
|
||||
if err != nil || len(e.Chunks) != 1 {
|
||||
t.Fatalf("lookup %s: %+v %v", rel, e, err)
|
||||
}
|
||||
return e.Chunks[0].FileId
|
||||
}
|
||||
if err := others.Create(ctx, rel, data, "producer-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := fid()
|
||||
meta, found, err := others.Stat(ctx, rel)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("stat: %v %v", found, err)
|
||||
}
|
||||
second := first
|
||||
if tc.recreate {
|
||||
hooked.before = func() {
|
||||
if err := others.Mark(ctx, rel, meta, "clean-1"); err != nil {
|
||||
t.Errorf("mark: %v", err)
|
||||
}
|
||||
if err := others.DeleteMarked(ctx, rel, "clean-1"); err != nil {
|
||||
t.Errorf("delete: %v", err)
|
||||
}
|
||||
if err := others.Create(ctx, rel, data, "producer-1"); err != nil {
|
||||
t.Errorf("re-create: %v", err)
|
||||
}
|
||||
second = fid()
|
||||
}
|
||||
}
|
||||
err = stale.Reuse(ctx, rel, meta, "writer-1")
|
||||
if tc.recreate && second == first {
|
||||
t.Fatalf("fixture: the object was not re-created with a new chunk (%s)", first)
|
||||
}
|
||||
switch {
|
||||
case tc.writes && tc.recreate:
|
||||
if !errors.Is(err, layout.ErrPrecondition) {
|
||||
t.Fatalf("the stale CLI adoption over a re-created object answered %v, want ErrPrecondition", err)
|
||||
}
|
||||
if got := fid(); got != second {
|
||||
t.Fatalf("the stale CLI adoption wrote chunk %s over the re-created object's %s", got, second)
|
||||
}
|
||||
case tc.recreate:
|
||||
if err != nil || fid() != first {
|
||||
t.Fatalf("control: without the probe the stale adoption should land (err %v, chunk %s, first %s)", err, fid(), first)
|
||||
}
|
||||
default:
|
||||
if err != nil {
|
||||
t.Fatalf("adoption of an unchanged object: %v", err)
|
||||
}
|
||||
if m, _, err := others.Stat(ctx, rel); err != nil || m.Session != "writer-1" {
|
||||
t.Fatalf("after adoption: %+v %v", m, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// inStartupProbe reports whether dir/name lies in a catalog probe's
|
||||
// disposable directory: a fake that stalls object deletes lets the probe's
|
||||
// own cleanup through, as a real filer deletes its inline HEAD at once.
|
||||
func inStartupProbe(dir, name string) bool {
|
||||
return strings.Contains(path.Join(dir, name), "/.startup-head-probe-")
|
||||
}
|
||||
@@ -13,7 +13,6 @@ 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.
|
||||
@@ -185,7 +184,7 @@ func chunkStats(statusAddr, volumeID string, deadline time.Time) (chunkStagedSta
|
||||
if err != nil {
|
||||
return chunkStagedStats{}, false
|
||||
}
|
||||
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
|
||||
resp, err := chunkHTTPClient.Do(req)
|
||||
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, 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)
|
||||
return chunkFail("detach", stdout, stderr, chunkExitFailed, codeInternalCLI, "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation", false)
|
||||
}
|
||||
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 != 3 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), "outcome_unknown") {
|
||||
if code := run(args, &out, &errs); code != 75 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
|
||||
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) {
|
||||
addr := installRefusedHolderDial(t)
|
||||
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", addr); code != 75 {
|
||||
installRefusedHolderDial(t)
|
||||
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://holder"); 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"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"net"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -29,9 +29,17 @@ func chunkTransportFailure(err error) bool {
|
||||
if layoutCode(err) != "" && !errors.Is(err, layout.ErrHolderActive) {
|
||||
return false
|
||||
}
|
||||
kind, listed := answer.ErrorKind(err)
|
||||
return listed && (kind == answer.Connection || kind == answer.PlaintextConnection || kind == answer.DNS || kind == answer.Timeout)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// gRPC cancellation does not wrap context.Canceled. Keep it distinct from an
|
||||
@@ -46,10 +54,3 @@ 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,7 +14,6 @@ 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"
|
||||
@@ -57,7 +56,6 @@ 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")
|
||||
@@ -86,18 +84,18 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
|
||||
case "resolve":
|
||||
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) {
|
||||
calls.Add(1)
|
||||
return layout.VolumeID{}, fixtureErr
|
||||
return layout.VolumeID{}, failure.err
|
||||
}
|
||||
case "dial":
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, fixtureErr }
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, failure.err }
|
||||
case "census":
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
|
||||
calls.Add(1)
|
||||
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, fixtureErr)
|
||||
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, failure.err)
|
||||
}
|
||||
case "read":
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
return transportLookupStore{mem, fixtureErr, &calls}, func() error { return nil }, nil
|
||||
return transportLookupStore{mem, failure.err, &calls}, func() error { return nil }, nil
|
||||
}
|
||||
case "restore":
|
||||
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
|
||||
@@ -112,11 +110,6 @@ 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. A resolve failure
|
||||
// without admission evidence requires recovery of the same operation.
|
||||
// volume the master does not know is volume_not_found (any other resolve
|
||||
// transport failure is retryable remote_unavailable).
|
||||
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"), 3, "outcome_unknown"},
|
||||
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 75, codeUnavailableCLI},
|
||||
} {
|
||||
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{}, c.err }
|
||||
var out, errs bytes.Buffer
|
||||
|
||||
@@ -14,7 +14,6 @@ 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
|
||||
@@ -22,9 +21,8 @@ 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. 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.
|
||||
// the pass completed with findings; 1: it could not complete (the partial
|
||||
// result is printed with the reason); 2: usage.
|
||||
func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("verify", stderr)
|
||||
var (
|
||||
@@ -116,7 +114,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
f, closeFn, err := dialChunkFiler(filer)
|
||||
if err != nil {
|
||||
if knownChunkFailure(err) {
|
||||
if chunkCanceled(err) || chunkTransportFailure(err) {
|
||||
return verifyIncomplete(layout.VerifyResult{}, err, stdout, stderr)
|
||||
}
|
||||
return usage(err.Error())
|
||||
@@ -292,9 +290,17 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ
|
||||
chunkErrBody
|
||||
Verify layout.VerifyResult `json:"verify"`
|
||||
}{Verify: res}
|
||||
policy, detail := chunkAnswerFor(err, answer.ChunkVerify)
|
||||
body.Code, body.Message, body.Retryable = policy.Code, detail, policy.Retryable
|
||||
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)
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
|
||||
chunkResult("verify", body, nil, stdout, stderr)
|
||||
return policy.Exit
|
||||
return chunkErrorExit(chunkExitFailed, body.Code, body.Retryable)
|
||||
}
|
||||
@@ -14,7 +14,6 @@ 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"
|
||||
)
|
||||
@@ -96,7 +95,15 @@ 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 {
|
||||
return leaseRefusal(err, false)
|
||||
// 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
|
||||
}
|
||||
|
||||
func deleteLeaseBarrierDetail(err error) bool {
|
||||
@@ -111,12 +118,6 @@ 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
|
||||
@@ -126,15 +127,7 @@ func leaseRefusal(err error, committed bool) 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 {
|
||||
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)}
|
||||
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)}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -234,10 +227,7 @@ func deleteVolumeWithProgress(ctx context.Context, cat *chunkstore.BCatalog, ref
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
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))
|
||||
transient := errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Unavailable
|
||||
if !transient {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ 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"
|
||||
)
|
||||
@@ -41,11 +40,7 @@ func (f *transientDeleteFiler) DeleteEntry(ctx context.Context, dir, name string
|
||||
return err
|
||||
}
|
||||
}
|
||||
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 status.Error(f.code, "object deadline")
|
||||
}
|
||||
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
@@ -105,9 +100,6 @@ type waitingDeleteFiler struct {
|
||||
}
|
||||
|
||||
func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if inStartupProbe(dir, name) {
|
||||
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
f.calls++
|
||||
if f.calls == 1 {
|
||||
timer := time.NewTimer(f.bound / 2)
|
||||
@@ -124,7 +116,7 @@ func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string,
|
||||
return err
|
||||
}
|
||||
if f.stall {
|
||||
return answer.Record(answer.Unsent, status.Error(codes.Unavailable, "stalled after first removal"))
|
||||
return status.Error(codes.Unavailable, "stalled after first removal")
|
||||
}
|
||||
if !f.waited {
|
||||
f.waited = true
|
||||
@@ -174,9 +166,6 @@ func TestVolumeDeleteRefreshesAnExpiredSweepAndWaitsFromLastRemoval(t *testing.T
|
||||
type blockedDeleteFiler struct{ *memChunkStore }
|
||||
|
||||
func (f *blockedDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
if inStartupProbe(dir, name) {
|
||||
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ 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"
|
||||
@@ -41,8 +40,7 @@ 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 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},
|
||||
{"remote unknown", authorityErr(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,8 +152,7 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
|
||||
}
|
||||
c, closeFn, err := clusterLifecycleDial(*master)
|
||||
if err != nil {
|
||||
p, detail := operatorAnswer(err, policy.Cluster)
|
||||
return fail("failed", p.Code, detail.Error(), p.Exit)
|
||||
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
@@ -165,15 +164,15 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
|
||||
if reason == "" {
|
||||
reason = status.Code(err).String()
|
||||
}
|
||||
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" {
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition:
|
||||
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(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
|
||||
return fail("failed", reason, msg, finalizeExitFailed)
|
||||
}
|
||||
answer.FormatLevel = resp.GetFormatLevel()
|
||||
for _, u := range resp.GetUnconfirmed() {
|
||||
@@ -290,8 +289,7 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
|
||||
answer.Server = *server
|
||||
c, closeFn, err := clusterLifecycleDial(*master)
|
||||
if err != nil {
|
||||
p, detail := operatorAnswer(err, policy.Cluster)
|
||||
return fail("failed", p.Code, detail.Error(), p.Exit)
|
||||
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
@@ -302,14 +300,14 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
|
||||
if reason == "" {
|
||||
reason = status.Code(err).String()
|
||||
}
|
||||
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" {
|
||||
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)
|
||||
}
|
||||
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
|
||||
return fail("failed", reason, msg, finalizeExitFailed)
|
||||
}
|
||||
answer.Result, answer.Message = "retired", "host retired from the node inventory"
|
||||
if !jsonMode {
|
||||
@@ -318,23 +316,6 @@ 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,7 +4,6 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"reflect"
|
||||
"sort"
|
||||
"testing"
|
||||
@@ -51,12 +50,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: 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"},
|
||||
{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"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
|
||||
return tc.resp, answer.Record(answer.Unsent, tc.err)
|
||||
return tc.resp, tc.err
|
||||
}}
|
||||
withClusterMaster(t, f)
|
||||
if tc.dialErr != nil {
|
||||
@@ -180,8 +179,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: 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: "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: "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) {
|
||||
@@ -189,7 +188,7 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
|
||||
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
|
||||
calls++
|
||||
if tc.err != nil {
|
||||
return nil, answer.Record(answer.Unsent, tc.err)
|
||||
return nil, tc.err
|
||||
}
|
||||
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
|
||||
}}
|
||||
|
||||
@@ -4,15 +4,16 @@ 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
|
||||
@@ -83,16 +84,15 @@ func chunkObserveHandle(name, route, addr string, window time.Duration, deadline
|
||||
if method == http.MethodPost {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
phase := answer.Unsent
|
||||
if id != "" {
|
||||
phase = answer.PossiblyAdmitted
|
||||
}
|
||||
resp, err := answer.DoHTTP(&client, req, phase)
|
||||
resp, err := client.Do(req)
|
||||
var raw []byte
|
||||
if err != nil && id == "" {
|
||||
cancel()
|
||||
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)
|
||||
// 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)
|
||||
}
|
||||
return unknown(name + " admission answer was not received (" + err.Error() + "); no second one was started")
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -10,8 +11,9 @@ 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"
|
||||
@@ -49,12 +51,10 @@ 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 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.
|
||||
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).
|
||||
`
|
||||
|
||||
func runOpsFailover(args []string, stdout, stderr io.Writer) int {
|
||||
@@ -93,13 +93,11 @@ 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 {
|
||||
p, detail := operatorAnswer(err, answer.Failover)
|
||||
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, detail)
|
||||
return p.Exit
|
||||
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, err)
|
||||
return 2
|
||||
} 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)
|
||||
p, _ := operatorAnswer(answer.LocalCredential(fmt.Errorf("admin client certificate is required")), answer.Failover)
|
||||
return p.Exit
|
||||
return 2
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
@@ -121,15 +119,14 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
|
||||
EvidenceRefs: []string{"sw-block ops failover", "operator_confirmed_old_node_off=" + volume},
|
||||
})
|
||||
if err != nil {
|
||||
policy, detail := operatorAnswer(err, answer.Failover)
|
||||
if policy.Retry == answer.Recover {
|
||||
if failoverOutcomeUnknown(err) {
|
||||
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 policy.Exit
|
||||
return 3
|
||||
}
|
||||
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch)
|
||||
fmt.Fprintf(stderr, "%s: %v (a refused fencing round may have fenced the survivors)\n", opsFailoverName, detail)
|
||||
return policy.Exit
|
||||
fmt.Fprintf(stderr, "%s: refused: %v (no line published; a refused fencing round may have fenced the survivors)\n", opsFailoverName, err)
|
||||
return 1
|
||||
}
|
||||
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",
|
||||
@@ -153,3 +150,21 @@ 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,7 +11,6 @@ import (
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -20,7 +19,6 @@ 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"
|
||||
@@ -171,42 +169,6 @@ 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.
|
||||
@@ -240,8 +202,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 != 78 {
|
||||
t.Fatalf("rc=%d; want 78", rc)
|
||||
if c.calls == 0 && rc != 2 {
|
||||
t.Fatalf("rc=%d; want 2", rc)
|
||||
}
|
||||
if c.calls == 1 && rc != 0 {
|
||||
t.Fatalf("rc=%d stderr %q; want 0", rc, errb.String())
|
||||
@@ -326,27 +288,3 @@ 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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
func TestSnapshotProxyUnlistedHTTPStatusIsUnknown(t *testing.T) {
|
||||
for _, code := range []int{408, 421, 423, 431, 499, 505, 520, 524} {
|
||||
t.Run(fmt.Sprint(code), func(t *testing.T) {
|
||||
received := make(chan string, 1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
RequestID string `json:"requestID"`
|
||||
}
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/chunk/snapshot" {
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
received <- body.RequestID
|
||||
w.WriteHeader(code)
|
||||
fmt.Fprint(w, "<html>proxy could not observe the origin outcome</html>")
|
||||
}))
|
||||
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": "same-original-snapshot"}, &out, &diag, &admission)
|
||||
got := chunkErrorOut(t, out.String())
|
||||
if exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || admission.Accepted || !strings.Contains(got.Message, "replay key") {
|
||||
t.Fatalf("exit=%d answer=%+v accepted=%v stderr=%s", exit, got, admission.Accepted, &diag)
|
||||
}
|
||||
select {
|
||||
case id := <-received:
|
||||
if id != "same-original-snapshot" {
|
||||
t.Fatalf("wire ID=%q", id)
|
||||
}
|
||||
default:
|
||||
t.Fatal("POST never reached proxy")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperatorUnlistedHTTPStatusIsUnknown(t *testing.T) {
|
||||
p, err := operatorAnswer(answer.HTTPStatusFailure(418, fmt.Errorf("proxy lost origin answer")), answer.Failover)
|
||||
if p.Code != "outcome_unknown" || !p.Retryable || p.Retry != answer.Recover || p.Exit != 3 || !strings.Contains(err.Error(), "current authority line") {
|
||||
t.Fatalf("policy=%+v err=%v", p, err)
|
||||
}
|
||||
}
|
||||
@@ -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 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, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --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,7 +18,6 @@ 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
|
||||
@@ -84,9 +83,6 @@ type miniConfig struct {
|
||||
// Explicit names the flags given on the command line (fs.Visit); a
|
||||
// --reuse refuses one that differs from the recorded run.
|
||||
Explicit map[string]bool
|
||||
// Self and WeedPath are the absolute paths of this sw-block and of the
|
||||
// weed it runs, for the commands mini prints; empty in unit tests.
|
||||
Self, WeedPath string
|
||||
}
|
||||
|
||||
// miniRecord is what a fresh start records in <dir>/mini.json and --reuse
|
||||
@@ -102,23 +98,6 @@ type miniRecord struct {
|
||||
|
||||
const miniRecordFile = "mini.json"
|
||||
|
||||
// Make an executable path absolute without collapsing symlink/.. components.
|
||||
func miniExecutablePath(path string) (string, error) {
|
||||
if filepath.IsAbs(path) {
|
||||
return path, nil
|
||||
}
|
||||
volume := filepath.VolumeName(path)
|
||||
base, err := filepath.Abs(volume + ".")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
relative := strings.TrimPrefix(path, volume)
|
||||
if len(relative) > 0 && os.IsPathSeparator(relative[0]) {
|
||||
return filepath.VolumeName(base) + relative, nil
|
||||
}
|
||||
return base + string(os.PathSeparator) + relative, nil
|
||||
}
|
||||
|
||||
func writeMiniRecord(dir string, r miniRecord) error {
|
||||
b, err := json.MarshalIndent(r, "", " ")
|
||||
if err != nil {
|
||||
@@ -139,20 +118,6 @@ func reuseMiniRecord(c *miniConfig, weedFound string) (string, error) {
|
||||
if err := json.Unmarshal(b, &r); err != nil {
|
||||
return "", fmt.Errorf("--reuse: %s/%s: %w", c.Dir, miniRecordFile, err)
|
||||
}
|
||||
if r.Weed != "" {
|
||||
abs, err := miniExecutablePath(r.Weed)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("--reuse: resolve weed path: %w", err)
|
||||
}
|
||||
r.Weed = abs
|
||||
}
|
||||
if c.Weed != r.Weed && c.Weed != "" && r.Weed != "" {
|
||||
now, errNow := os.Stat(c.Weed)
|
||||
then, errThen := os.Stat(r.Weed)
|
||||
if errNow == nil && errThen == nil && os.SameFile(now, then) {
|
||||
c.Weed = r.Weed
|
||||
}
|
||||
}
|
||||
differs := func(flag string, now, then any) error {
|
||||
if c.Explicit[flag] && fmt.Sprint(now) != fmt.Sprint(then) {
|
||||
return fmt.Errorf("--reuse: --%s %v differs from this dir's run (%v); drop it to reuse the run as recorded", flag, now, then)
|
||||
@@ -221,16 +186,9 @@ func miniMasterArgs(c miniConfig, chunk bool) []string {
|
||||
}
|
||||
|
||||
// miniVolumeArgs is blockvolume as swb_start runs it, plus, with a chunk
|
||||
// store, the walstore-chunk settings and the volume's layout id. Its volume
|
||||
// lock is under the run's dir, so mini needs no root and no tmpfiles.d entry
|
||||
// (a trial override, which blockvolume refuses under systemd); with a chunk
|
||||
// store it takes no scheduled snapshot (mini prints how to take one).
|
||||
// store, the walstore-chunk settings and the volume's layout id.
|
||||
func miniVolumeArgs(c miniConfig, chunk bool, layoutID string) []string {
|
||||
a := append(miniVolumeSpec(c, chunk, layoutID).args(), "--volume-lock-dir-test-only", filepath.Join(c.Dir, "locks"))
|
||||
if chunk {
|
||||
a = append(a, "--chunk-snapshot-schedule", "off")
|
||||
}
|
||||
return a
|
||||
return miniVolumeSpec(c, chunk, layoutID).args()
|
||||
}
|
||||
|
||||
// miniVolumeSpec is mini's v1: the same settings volume start writes for a
|
||||
@@ -310,25 +268,13 @@ type miniRun struct {
|
||||
|
||||
// start prints the command, then starts it with its output in <dir>/<name>.log.
|
||||
func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) {
|
||||
words := []string{shQuote(bin)}
|
||||
for _, a := range args {
|
||||
words = append(words, shQuote(a))
|
||||
}
|
||||
fmt.Fprintf(r.out, "+ %s\n", strings.Join(words, " "))
|
||||
fmt.Fprintf(r.out, "+ %s %s\n", bin, strings.Join(args, " "))
|
||||
lf, err := os.Create(filepath.Join(r.cfg.Dir, name+".log"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cmd := exec.Command(bin, args...)
|
||||
cmd.Stdout, cmd.Stderr, cmd.Stdin = lf, lf, nil
|
||||
cmd.Env = []string{}
|
||||
// mini's children are not systemd units even when mini runs under one;
|
||||
// blockvolume refuses mini's lock directory while INVOCATION_ID is set.
|
||||
for _, kv := range os.Environ() {
|
||||
if !strings.HasPrefix(kv, "INVOCATION_ID=") {
|
||||
cmd.Env = append(cmd.Env, kv)
|
||||
}
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
lf.Close()
|
||||
return nil, fmt.Errorf("start %s: %w", name, err)
|
||||
@@ -346,7 +292,6 @@ 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)
|
||||
@@ -355,7 +300,6 @@ 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
|
||||
}
|
||||
@@ -365,40 +309,16 @@ 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): %w", c.name, miniStartWait, ports, c.name, answer.Present(lastErr, answer.Ops))
|
||||
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log)", c.name, miniStartWait, ports, c.name)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
|
||||
return ctx.Err()
|
||||
case <-time.After(250 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// resolveLayoutID looks up volume's layout id through blockmaster,
|
||||
// retrying while blockmaster registers it, bounded by miniResolveWait.
|
||||
func (r *miniRun) resolveLayoutID(ctx context.Context, master, volume string) (string, error) {
|
||||
deadline := time.Now().Add(miniResolveWait)
|
||||
for {
|
||||
rctx, rcancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
id, err := resolveVolumeID(rctx, master, volume)
|
||||
rcancel()
|
||||
if err == nil {
|
||||
return id.String(), nil
|
||||
}
|
||||
if d := r.dead(); d != nil {
|
||||
return "", fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, volume, d.err)
|
||||
}
|
||||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||||
return "", fmt.Errorf("resolve %s's layout id: %v", volume, err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dead is the first child that has exited, if any.
|
||||
func (r *miniRun) dead() *miniChild {
|
||||
for _, c := range r.children {
|
||||
@@ -491,26 +411,10 @@ func runMini(args []string, stdout, stderr io.Writer) int {
|
||||
func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, error) {
|
||||
weed := cfg.Weed
|
||||
if weed == "" {
|
||||
var err error
|
||||
if weed, err = exec.LookPath("weed"); errors.Is(err, exec.ErrDot) {
|
||||
if !cfg.Reuse {
|
||||
return ops.VolumeStatusExitInvalid, fmt.Errorf("weed on PATH is in the current directory (%v); pass --weed %s to use it", err, shQuote("./"+weed))
|
||||
}
|
||||
weed = ""
|
||||
}
|
||||
weed, _ = exec.LookPath("weed")
|
||||
} else if st, err := os.Stat(weed); err != nil || st.IsDir() {
|
||||
return ops.VolumeStatusExitInvalid, fmt.Errorf("--weed %s not found", weed)
|
||||
}
|
||||
if weed != "" {
|
||||
abs, err := miniExecutablePath(weed)
|
||||
if err != nil {
|
||||
return ops.VolumeStatusExitInvalid, fmt.Errorf("resolve weed path: %w", err)
|
||||
}
|
||||
weed = abs
|
||||
if cfg.Weed != "" {
|
||||
cfg.Weed = abs
|
||||
}
|
||||
}
|
||||
// A reuse takes the recorded run (its binaries included) before any
|
||||
// lookup; a fresh start finds the binaries next to sw-block by default.
|
||||
if cfg.Reuse {
|
||||
@@ -578,11 +482,7 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
|
||||
return 1, err
|
||||
}
|
||||
}
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
cfg.Self = exe
|
||||
}
|
||||
cfg.WeedPath = weed
|
||||
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol"), filepath.Join(cfg.Dir, "locks")} {
|
||||
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol")} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
@@ -591,8 +491,6 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
|
||||
defer r.stop()
|
||||
fail := func(err error) (int, error) {
|
||||
r.tail(20)
|
||||
r.stop()
|
||||
fmt.Fprintf(stderr, "sw-block mini: stopped; logs in %s/*.log. After fixing the cause, start again on it with\n %s\nRemoving %s deletes the trial volume's data (and SeaweedFS's); do that only to start over without it.\n", shQuote(cfg.Dir), miniResume(cfg), shQuote(cfg.Dir))
|
||||
return 1, err
|
||||
}
|
||||
if chunk {
|
||||
@@ -621,9 +519,26 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
|
||||
}
|
||||
layoutID := ""
|
||||
if chunk {
|
||||
fmt.Fprintf(stdout, "+ %s ops volume resolve --master %s %s\n", miniSelf(cfg), loopback(cfg.Ports.Master), miniVolume)
|
||||
if layoutID, err = r.resolveLayoutID(ctx, loopback(cfg.Ports.Master), miniVolume); err != nil {
|
||||
return fail(err)
|
||||
fmt.Fprintf(stdout, "+ sw-block ops volume resolve --master %s %s\n", loopback(cfg.Ports.Master), miniVolume)
|
||||
deadline := time.Now().Add(miniResolveWait)
|
||||
for {
|
||||
rctx, rcancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
id, err := resolveVolumeID(rctx, loopback(cfg.Ports.Master), miniVolume)
|
||||
rcancel()
|
||||
if err == nil {
|
||||
layoutID = id.String()
|
||||
break
|
||||
}
|
||||
if d := r.dead(); d != nil {
|
||||
return fail(fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, miniVolume, d.err))
|
||||
}
|
||||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||||
return fail(fmt.Errorf("resolve %s's layout id: %v", miniVolume, err))
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
vc, err := r.start("blockvolume", volume, miniVolumeArgs(cfg, chunk, layoutID))
|
||||
@@ -683,18 +598,9 @@ func shQuote(s string) string {
|
||||
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||
}
|
||||
|
||||
// miniSelf is how a printed command names this sw-block: its absolute path
|
||||
// when known, so the command runs from any directory.
|
||||
func miniSelf(c miniConfig) string {
|
||||
if c.Self == "" {
|
||||
return "sw-block"
|
||||
}
|
||||
return shQuote(c.Self)
|
||||
}
|
||||
|
||||
// miniResume is the command that starts the recorded run in c.Dir again.
|
||||
func miniResume(c miniConfig) string {
|
||||
return miniSelf(c) + " mini --dir " + shQuote(c.Dir) + " --reuse"
|
||||
return "sw-block mini --dir " + shQuote(c.Dir) + " --reuse"
|
||||
}
|
||||
|
||||
// miniNextSteps prints what to run next; mini runs none of it.
|
||||
@@ -710,14 +616,9 @@ func miniNextSteps(w io.Writer, c miniConfig, chunk bool) {
|
||||
return
|
||||
}
|
||||
cmds := miniCommands(c, chunk)
|
||||
self := miniSelf(c)
|
||||
fmt.Fprintf(w, "\nCheck the volume:\n %s %s\n %s %s\n", self, strings.Join(cmds[0], " "), self, strings.Join(cmds[1], " "))
|
||||
fmt.Fprintf(w, "\nSnapshot (mini takes no scheduled snapshot):\n %s %s\n", self, strings.Join(cmds[2], " "))
|
||||
weed := "weed"
|
||||
if c.WeedPath != "" {
|
||||
weed = shQuote(c.WeedPath)
|
||||
}
|
||||
fmt.Fprintf(w, "\nSeaweedFS itself: %s shell -master=%s\n", weed, loopback(c.Ports.WeedMaster))
|
||||
fmt.Fprintf(w, "\nCheck the volume:\n sw-block %s\n sw-block %s\n", strings.Join(cmds[0], " "), strings.Join(cmds[1], " "))
|
||||
fmt.Fprintf(w, "\nSnapshot:\n sw-block %s\n", strings.Join(cmds[2], " "))
|
||||
fmt.Fprintf(w, "\nSeaweedFS itself: weed shell -master=%s\n", loopback(c.Ports.WeedMaster))
|
||||
}
|
||||
|
||||
// miniBeforeStop reminds the user, before the target goes away, to have
|
||||
|
||||
@@ -3,7 +3,6 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -58,9 +57,6 @@ func fakeMiniChild(mode string) int {
|
||||
term := make(chan os.Signal, 1)
|
||||
signal.Notify(term, syscall.SIGTERM)
|
||||
if mode == "die-"+name {
|
||||
if marker := os.Getenv("SWB_MINI_FAKE_RAN"); marker != "" {
|
||||
_ = os.WriteFile(marker, []byte(name), 0o644)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
return 9
|
||||
}
|
||||
@@ -149,9 +145,7 @@ func TestMiniWalstoreFlagsAreThePage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
for f := range got {
|
||||
// mini keeps the volume lock under --dir, so it needs no root
|
||||
// (the page's unit uses the host lock directory).
|
||||
if _, ok := page[f]; !ok && f != "--volume-lock-dir-test-only" {
|
||||
if _, ok := page[f]; !ok {
|
||||
t.Errorf("%s: mini passes %s; the page's swb_start does not", c.binary, f)
|
||||
}
|
||||
}
|
||||
@@ -334,7 +328,7 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
|
||||
}
|
||||
})
|
||||
waitOutput(t, out, "sw-block mini: running")
|
||||
for _, want := range []string{"+ " + shQuote(filepath.Join(c.Bin, "blockmaster")) + " ", "+ " + shQuote(filepath.Join(c.Bin, "blockvolume")) + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1",
|
||||
for _, want := range []string{"+ " + filepath.Join(c.Bin, "blockmaster") + " ", "+ " + filepath.Join(c.Bin, "blockvolume") + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1",
|
||||
"sw-block mini: no chunk store: snapshots unavailable", "trial setup: one host, loopback, no authentication"} {
|
||||
if !strings.Contains(out.String(), want) {
|
||||
t.Fatalf("output lacks %q:\n%s", want, out.String())
|
||||
@@ -350,12 +344,7 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("mini did not stop")
|
||||
}
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resume := miniResume(miniConfig{Dir: c.Dir, Self: self})
|
||||
for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + resume + "\n"} {
|
||||
for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + miniResume(c) + "\n"} {
|
||||
if !strings.Contains(out.String(), want) {
|
||||
t.Fatalf("at stop, output lacks %q:\n%s", want, out.String())
|
||||
}
|
||||
@@ -453,8 +442,7 @@ func wantChunkCommands(dir, id string) map[string][]string {
|
||||
"--data-addr", "127.0.0.1:9201", "--ctrl-addr", "127.0.0.1:9202", "--status-addr", "127.0.0.1:9203",
|
||||
"--durable-root", filepath.Join(dir, "vol"), "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096",
|
||||
"--chunk-filer", "127.0.0.1:18888", "--chunk-path", "/swblock/chunks", "--chunk-control-endpoint", "--workspace-lease", "--layout-id", id,
|
||||
"--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1",
|
||||
"--volume-lock-dir-test-only", filepath.Join(dir, "locks"), "--chunk-snapshot-schedule", "off"},
|
||||
"--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -589,52 +577,6 @@ func TestMiniWeedDyingDuringStartupStopsTheRest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("signals and listening children: Linux")
|
||||
}
|
||||
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
|
||||
ran := filepath.Join(t.TempDir(), "ran")
|
||||
t.Setenv("SWB_MINI_FAKE_RAN", ran)
|
||||
bin := fakeBin(t)
|
||||
abs := filepath.Join(bin, "weed")
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rel, err := filepath.Rel(cwd, abs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: rel, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
out := &syncBuf{}
|
||||
code, err := mini(ctx, c, out, io.Discard)
|
||||
if code == 0 || err == nil {
|
||||
t.Fatalf("fixture must reach the dying weed: code=%d err=%v", code, err)
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var record miniRecord
|
||||
if err := json.Unmarshal(b, &record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
selected, selectedErr := os.Stat(abs)
|
||||
recorded, recordedErr := os.Stat(record.Weed)
|
||||
if selectedErr != nil || recordedErr != nil || !filepath.IsAbs(record.Weed) || !os.SameFile(selected, recorded) {
|
||||
t.Errorf("record weed=%q changed selected executable %q", record.Weed, abs)
|
||||
}
|
||||
if !strings.Contains(out.String(), "+ "+shQuote(record.Weed)+" ") {
|
||||
t.Errorf("relative weed command: %s", out.String())
|
||||
}
|
||||
if _, err := os.Stat(ran); err != nil {
|
||||
t.Errorf("the selected weed did not run: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// --reuse starts the recorded run again: its size, ports, mode (its weed)
|
||||
// and NQN, whatever the defaults are; a flag that differs from the record
|
||||
// is refused, and so are a recorded weed that is gone and a walstore run
|
||||
@@ -858,107 +800,3 @@ func TestMiniPrintedResumeRunsOnASpacedDir(t *testing.T) {
|
||||
t.Fatalf("control: the unquoted line reached the dir too (exit %d)", code)
|
||||
}
|
||||
}
|
||||
|
||||
// mini started from a systemd service's process tree (a CI runner unit, a
|
||||
// terminal server) inherits INVOCATION_ID; blockvolume refuses the lock-dir
|
||||
// override under it, so mini's children must start without it.
|
||||
func TestMiniChildrenStartWithoutInvocationID(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix child environment and signals")
|
||||
}
|
||||
t.Setenv("INVOCATION_ID", "0123456789abcdef")
|
||||
dir := t.TempDir()
|
||||
r := &miniRun{cfg: miniConfig{Dir: dir}, out: io.Discard, log: io.Discard}
|
||||
c, err := r.start("env", "/bin/sh", []string{"-c", `echo "id=${INVOCATION_ID-unset}"`})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
joined := false
|
||||
stop := func() {
|
||||
if joined {
|
||||
return
|
||||
}
|
||||
_ = c.cmd.Process.Signal(syscall.SIGTERM)
|
||||
select {
|
||||
case <-c.done:
|
||||
joined = true
|
||||
return
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
_ = c.cmd.Process.Kill()
|
||||
select {
|
||||
case <-c.done:
|
||||
joined = true
|
||||
case <-time.After(2 * time.Second):
|
||||
fmt.Fprintln(os.Stderr, "mini child did not join; stopping tests before directory cleanup")
|
||||
os.Exit(86)
|
||||
}
|
||||
}
|
||||
t.Cleanup(stop)
|
||||
select {
|
||||
case <-c.done:
|
||||
joined = true
|
||||
case <-time.After(2 * time.Second):
|
||||
stop()
|
||||
t.Fatal("mini environment child did not finish")
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(dir, "env.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(string(b)); got != "id=unset" {
|
||||
t.Fatalf("mini's child saw %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An empty filtered environment must be explicit: nil would inherit again.
|
||||
func TestMiniOnlyInvocationIDDoesNotLeak(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix environment child")
|
||||
}
|
||||
saved := os.Environ()
|
||||
t.Cleanup(func() {
|
||||
os.Clearenv()
|
||||
for _, kv := range saved {
|
||||
key, value, _ := strings.Cut(kv, "=")
|
||||
_ = os.Setenv(key, value)
|
||||
}
|
||||
})
|
||||
os.Clearenv()
|
||||
TestMiniChildrenStartWithoutInvocationID(t)
|
||||
}
|
||||
|
||||
// Assert the actual weed-hint call site, not only the quoting helper. This
|
||||
// stays sensitive if formatting is correct but the hint stops calling it.
|
||||
func TestMiniProductionWeedHintQuotesItsExecutable(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
miniNextSteps(&out, miniConfig{WeedPath: "/tmp/weed's tools/weed"}, true)
|
||||
const want = `SeaweedFS itself: '/tmp/weed'\''s tools/weed' shell -master=`
|
||||
if !strings.Contains(out.String(), want) {
|
||||
t.Fatalf("production weed hint lacks %q:\n%s", want, out.String())
|
||||
}
|
||||
}
|
||||
|
||||
// A run that stops on a failure offers the --reuse command for its dir
|
||||
// first; removing the dir is named only with the warning that it deletes
|
||||
// the trial volume's data, never as a plain "start fresh".
|
||||
func TestMiniFailureOffersReuseBeforeRemoval(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("signals and listening children: Linux")
|
||||
}
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
t.Setenv("SWB_MINI_FAKE_CHILD", "die-blockvolume")
|
||||
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: fakeBin(t), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
||||
errb := &syncBuf{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
if code, _ := mini(ctx, c, io.Discard, errb); code == 0 {
|
||||
t.Fatal("a dead blockvolume: exit 0")
|
||||
}
|
||||
text := errb.String()
|
||||
reuse := strings.Index(text, " --reuse")
|
||||
warn := strings.Index(text, "deletes the trial volume's data")
|
||||
if reuse < 0 || warn < 0 || warn < reuse || strings.Contains(text, "start fresh") {
|
||||
t.Fatalf("failure text %q: want the --reuse command first and removal only with the data warning", text)
|
||||
}
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMiniWeedSymlinkParentKeepsSelectedExecutable(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix symlink and child-process fixture")
|
||||
}
|
||||
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
|
||||
bin := fakeBin(t)
|
||||
root := t.TempDir()
|
||||
for _, dir := range []string{"tools", "releases/v2"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
selected := filepath.Join(root, "releases", "weed")
|
||||
if err := os.Symlink(filepath.Join(bin, "weed"), selected); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "tools", "weed"), []byte("wrong executable"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(root, "releases", "v2"), filepath.Join(root, "tools", "current")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(root)
|
||||
rel := "tools/current/../weed"
|
||||
want, err := os.Stat(selected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check := func(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
got, err := os.Stat(path)
|
||||
if err != nil || !filepath.IsAbs(path) || !os.SameFile(want, got) {
|
||||
t.Fatalf("selected executable changed: path=%q stat=%v", path, err)
|
||||
}
|
||||
}
|
||||
t.Run("fresh", func(t *testing.T) {
|
||||
ran := filepath.Join(t.TempDir(), "ran")
|
||||
t.Setenv("SWB_MINI_FAKE_RAN", ran)
|
||||
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: rel, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
out := &syncBuf{}
|
||||
_, _ = mini(ctx, c, out, io.Discard)
|
||||
data, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
|
||||
if err != nil {
|
||||
t.Fatalf("did not reach record publication: %v; %s", err, out.String())
|
||||
}
|
||||
var record miniRecord
|
||||
if err := json.Unmarshal(data, &record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(t, record.Weed)
|
||||
if !strings.Contains(out.String(), "+ "+shQuote(record.Weed)+" ") {
|
||||
t.Fatalf("selected executable was not launched: %s", out.String())
|
||||
}
|
||||
if _, err := os.Stat(ran); err != nil {
|
||||
t.Fatalf("the selected weed did not run: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("legacy", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := writeMiniRecord(dir, miniRecord{Weed: rel, Bin: bin, SizeBytes: 1 << 20, NQN: "n"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := miniConfig{Dir: dir}
|
||||
weed, err := reuseMiniRecord(&c, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(t, weed)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMiniRefusesWeedFoundThroughDotInPath(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix PATH lookup")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "weed"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(dir)
|
||||
t.Setenv("PATH", ".")
|
||||
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
||||
code, err := mini(context.Background(), c, io.Discard, io.Discard)
|
||||
if code == 0 || err == nil || !strings.Contains(err.Error(), "current directory") {
|
||||
t.Fatalf("weed found only through . in PATH: code %d err %v; want a refusal", code, err)
|
||||
}
|
||||
if _, err := os.Stat(c.Dir); !os.IsNotExist(err) {
|
||||
t.Fatalf("refused start created %s: %v", c.Dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiniReuseAcceptsSameWeedFromAnotherDirectory(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix paths")
|
||||
}
|
||||
root := t.TempDir()
|
||||
for _, d := range []string{"a", "b", "bin"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, d), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "bin", "weed"), []byte("x"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "bin", "other"), []byte("x"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
recorded := filepath.Join(root, "a") + "/../bin/weed"
|
||||
if err := writeMiniRecord(dir, miniRecord{Weed: recorded, Bin: t.TempDir(), SizeBytes: 1 << 20, NQN: "n"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(filepath.Join(root, "b"))
|
||||
weedNow := func(t *testing.T, rel string) (string, error) {
|
||||
t.Helper()
|
||||
abs, err := miniExecutablePath(rel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := miniConfig{Dir: dir, Weed: abs, Explicit: map[string]bool{"weed": true}}
|
||||
return reuseMiniRecord(&c, abs)
|
||||
}
|
||||
if weed, err := weedNow(t, "../bin/weed"); err != nil || weed != recorded {
|
||||
t.Fatalf("same weed through another cwd: weed %q err %v; want the recorded %q", weed, err, recorded)
|
||||
}
|
||||
if _, err := weedNow(t, "../bin/other"); err == nil || !strings.Contains(err.Error(), "differs") {
|
||||
t.Fatalf("a different executable: err %v; want a refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiniStartTraceQuotesPathsWithSpaces(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "my tools")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := &syncBuf{}
|
||||
r := &miniRun{cfg: miniConfig{Dir: dir}, out: out}
|
||||
if _, err := r.start("weed", filepath.Join(dir, "absent"), []string{"mini", "-dir=" + dir}); err == nil {
|
||||
t.Fatal("an absent executable started")
|
||||
}
|
||||
want := "+ " + shQuote(filepath.Join(dir, "absent")) + " mini " + shQuote("-dir="+dir) + "\n"
|
||||
if got := out.String(); got != want || !strings.Contains(got, "'") {
|
||||
t.Fatalf("start trace %q; want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiniReuseIgnoresWeedFoundThroughDotInPath(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix PATH lookup")
|
||||
}
|
||||
bin := fakeBin(t)
|
||||
cwd := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(cwd, "weed"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(cwd)
|
||||
t.Setenv("PATH", ".")
|
||||
for name, recorded := range map[string]string{"chunk": filepath.Join(bin, "weed"), "walstore": ""} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n", Bin: bin, Weed: recorded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ports := freePorts(t)
|
||||
l, err := net.Listen("tcp", loopback(ports.NVMe))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
c := miniConfig{Dir: dir, NQN: "n", SizeBytes: 1 << 20, Ports: ports, Reuse: true, Explicit: map[string]bool{}}
|
||||
code, err := mini(context.Background(), c, io.Discard, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "in use") {
|
||||
t.Fatalf("--reuse with ./weed only through . in PATH: code %d err %v; want the recorded run (then the busy port)", code, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The refusal's hint is a pastable shell word: a relative PATH entry with a
|
||||
// space ("my tools") prints its --weed path quoted, as mini's other printed
|
||||
// commands are.
|
||||
func TestMiniDotWeedHintQuotesAPathWithASpace(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix PATH lookup")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
tools := filepath.Join(dir, "my tools")
|
||||
if err := os.MkdirAll(tools, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nl := string(rune(10))
|
||||
if err := os.WriteFile(filepath.Join(tools, "weed"), []byte("#!/bin/sh"+nl+"exit 0"+nl), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(dir)
|
||||
t.Setenv("PATH", "my tools")
|
||||
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
||||
_, err := mini(context.Background(), c, io.Discard, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "pass --weed './my tools/weed' to use it") {
|
||||
t.Fatalf("weed found through a relative PATH entry with a space: %v; want the quoted --weed hint", err)
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
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"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
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-conflict", 409, "{", 3, "outcome_unknown"},
|
||||
{"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-conflict", 409, "oversized", 3, "outcome_unknown"},
|
||||
{"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,7 +13,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
)
|
||||
|
||||
type inspectionShell struct {
|
||||
@@ -208,9 +207,8 @@ func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int {
|
||||
defer cancel()
|
||||
cluster, err := readMasterClusterEvidence(ctx, s.master)
|
||||
if err != nil {
|
||||
policy, detail := operatorAnswer(err, answer.Shell)
|
||||
fmt.Fprintf(stderr, "%s: %v\n", name, detail)
|
||||
return policy.Exit
|
||||
fmt.Fprintf(stderr, "%s: %v\n", name, err)
|
||||
return 1
|
||||
}
|
||||
var value any = cluster
|
||||
text := ops.RenderClusterEvidenceText(cluster)
|
||||
|
||||
@@ -14,7 +14,6 @@ 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"
|
||||
@@ -192,11 +191,6 @@ 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 {
|
||||
@@ -303,7 +297,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 := answer.DoHTTP(client, req, answer.Unsent)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -45,16 +44,9 @@ 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 unobserved(fmt.Errorf("operation has no result"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
|
||||
}
|
||||
if err := writeAll(stdout, a.Answer.Result); err != nil {
|
||||
return chunkExitFailed
|
||||
@@ -67,19 +59,16 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
|
||||
}
|
||||
origin, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return unobserved(fmt.Errorf("invalid original operation origin"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
loc, err := url.Parse(a.Location)
|
||||
if err != nil {
|
||||
return unobserved(fmt.Errorf("invalid operation handle URI"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid operation handle URI", false)
|
||||
}
|
||||
handle := origin.ResolveReference(loc)
|
||||
if handle.Scheme != origin.Scheme || handle.Host != origin.Host || handle.User != nil {
|
||||
return unobserved(fmt.Errorf("operation handle changed origin"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation handle changed origin", false)
|
||||
}
|
||||
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 {
|
||||
@@ -87,28 +76,32 @@ 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 unobserved(fmt.Errorf("invalid operation status request"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
|
||||
}
|
||||
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
|
||||
resp, err := chunkHTTPClient.Do(req)
|
||||
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 = answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("operation status HTTP %d", resp.StatusCode))
|
||||
err = 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 unobserved(err)
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
|
||||
}
|
||||
if current.ID != a.Answer.ID {
|
||||
return unobserved(fmt.Errorf("operation status changed identity"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation status changed identity", false)
|
||||
}
|
||||
switch current.State {
|
||||
case "succeeded":
|
||||
if len(current.Result) == 0 || !json.Valid(current.Result) {
|
||||
return unobserved(fmt.Errorf("operation has no result"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
|
||||
}
|
||||
if err := writeAll(stdout, current.Result); err != nil {
|
||||
return chunkExitFailed
|
||||
@@ -124,7 +117,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 unobserved(fmt.Errorf("unknown operation state"))
|
||||
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "unknown operation state", false)
|
||||
}
|
||||
timer := time.NewTimer(100 * time.Millisecond)
|
||||
select {
|
||||
@@ -132,7 +125,7 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
|
||||
if !timer.Stop() {
|
||||
<-timer.C
|
||||
}
|
||||
return unobserved(ctx.Err())
|
||||
return chunkExitFailed
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -24,37 +22,11 @@ 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
|
||||
@@ -116,9 +88,6 @@ func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool)
|
||||
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)
|
||||
@@ -144,9 +113,8 @@ func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool)
|
||||
if err := cmd.Process.Signal(os.Interrupt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var observerErr error
|
||||
select {
|
||||
case observerErr = <-done:
|
||||
case <-done:
|
||||
joined = true
|
||||
case <-ctx.Done():
|
||||
t.Fatal("interrupt did not stop the observer")
|
||||
@@ -160,18 +128,6 @@ func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool)
|
||||
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()
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
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,9 +130,8 @@ 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 {
|
||||
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(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
|
||||
}
|
||||
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))
|
||||
@@ -164,13 +163,8 @@ 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, 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
|
||||
unknown := func(why string) (snapshotAnswer, *snapshotRefusal, error) {
|
||||
return snapshotAnswer{}, nil, fmt.Errorf("the snapshot's outcome is unknown (%s)", why)
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
req, err := http.NewRequestWithContext(rctx, http.MethodPost, "http://"+status+"/chunk/snapshot", bytes.NewReader(body))
|
||||
@@ -180,16 +174,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 := answer.DoHTTP(&client, req, answer.Unsent)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return unknown("snapshot admission answer not received", err)
|
||||
return unknown(err.Error())
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
resp.Body.Close()
|
||||
cancel()
|
||||
if err != nil {
|
||||
return unknown("snapshot answer unreadable", err)
|
||||
return unknown("answer unreadable: " + err.Error())
|
||||
}
|
||||
if resp.StatusCode == http.StatusAccepted {
|
||||
var adm snapshotOperationIdentity
|
||||
@@ -197,7 +191,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("snapshot observation failed", err)
|
||||
return unknown(err.Error())
|
||||
}
|
||||
var op struct {
|
||||
State string `json:"state"`
|
||||
@@ -278,7 +272,7 @@ func observeSnapshotOperation(ctx context.Context, env verbEnv, client http.Clie
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
resp, err := answer.DoHTTP(&client, req, answer.PossiblyAdmitted)
|
||||
resp, err := client.Do(req)
|
||||
var b []byte
|
||||
if err == nil {
|
||||
b, err = io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
@@ -408,9 +402,8 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
unknown := func(step string, err error) int {
|
||||
policy, detail := operatorAnswer(err, answer.VolumeJob)
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, detail, ways)
|
||||
return policy.Exit
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, err, ways)
|
||||
return 1
|
||||
}
|
||||
src, err := readEnvFile(filepath.Join(env.EtcDir, o.Source+".env"))
|
||||
if err != nil {
|
||||
@@ -432,11 +425,10 @@ 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 policy, detail := operatorAnswer(err, answer.VolumeJob); !policy.Retryable {
|
||||
fmt.Fprintf(stderr, "sw-block volume restore: restore: %v\n", detail)
|
||||
return policy.Exit
|
||||
if code := restoreRefusal(err); code != "" {
|
||||
return refuse("restore", code+": "+err.Error())
|
||||
}
|
||||
return unknown("restore", err)
|
||||
return unknown("restore", fmt.Errorf("the outcome is unknown (%v)", err))
|
||||
}
|
||||
if resp.GetVolumeId() != v.VolumeID || !resp.GetStoreReady() {
|
||||
return unknown("restore", errors.New("the master did not confirm the new volume store-ready"))
|
||||
@@ -484,14 +476,10 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
|
||||
break
|
||||
}
|
||||
}
|
||||
policy, detail := operatorAnswer(err, answer.VolumePlacement)
|
||||
// Only blockmaster's own refusal settles that the volume stays
|
||||
// unplaced. An interrupted step (Ctrl-C) or one that failed here
|
||||
// before an answer (a credential or connection error) leaves both
|
||||
// ways open: the same command finishes the restore.
|
||||
if restoreStepAnswered(ctx, err) && 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
|
||||
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
|
||||
}
|
||||
return unknown(step, err)
|
||||
}
|
||||
@@ -643,6 +631,25 @@ 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
|
||||
@@ -715,21 +722,3 @@ var workspaceBindPlace = func(ctx context.Context, master string, b *control.Wor
|
||||
defer conn.Close()
|
||||
return bindAndPlace(ctx, control.NewWorkspaceServiceClient(conn), b, replica)
|
||||
}
|
||||
|
||||
// restoreStepAnswered says whether err is blockmaster's own answer to a
|
||||
// restore step, not an interruption or a failure on this side before an
|
||||
// answer (cancellation, a deadline, no connection, refused credentials).
|
||||
func restoreStepAnswered(ctx context.Context, err error) bool {
|
||||
if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return false
|
||||
}
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
switch st.Code() {
|
||||
case codes.Canceled, codes.DeadlineExceeded, codes.Unavailable, codes.Unknown, codes.Unauthenticated:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -28,23 +28,17 @@ 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 {
|
||||
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
|
||||
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 {
|
||||
@@ -85,12 +79,14 @@ func newSnapHolder(t *testing.T) *snapHolder {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
var q backupWireRequest
|
||||
var q struct {
|
||||
VolumeID, Name, RequestID string
|
||||
Labels map[string]string
|
||||
}
|
||||
_ = 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)
|
||||
@@ -323,11 +319,6 @@ func (m *restoreMaster) RegisterWorkspaceBinding(_ context.Context, q *control.W
|
||||
m.failNext = ""
|
||||
return nil, status.Error(codes.FailedPrecondition, "server not registered")
|
||||
}
|
||||
if m.failNext == "bind-canceled" || m.failNext == "bind-unauthenticated" {
|
||||
code := map[string]codes.Code{"bind-canceled": codes.Canceled, "bind-unauthenticated": codes.Unauthenticated}[m.failNext]
|
||||
m.failNext = ""
|
||||
return nil, status.Error(code, "the step ended before blockmaster answered")
|
||||
}
|
||||
m.binds++
|
||||
m.bound[q.VolumeId] = q
|
||||
return q, nil
|
||||
@@ -395,7 +386,7 @@ func (m *restoreMaster) QueryVolumeStatus(_ context.Context, q *control.StatusRe
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func serveRestoreMaster(t *testing.T, options ...grpc.ServerOption) (*restoreMaster, string) {
|
||||
func serveRestoreMaster(t *testing.T) (*restoreMaster, string) {
|
||||
t.Helper()
|
||||
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
|
||||
t.Setenv(key, "")
|
||||
@@ -415,7 +406,7 @@ func serveRestoreMaster(t *testing.T, options ...grpc.ServerOption) (*restoreMas
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := grpc.NewServer(options...)
|
||||
server := grpc.NewServer()
|
||||
control.RegisterLifecycleServiceServer(server, m)
|
||||
control.RegisterWorkspaceServiceServer(server, m)
|
||||
control.RegisterEvidenceServiceServer(server, m)
|
||||
@@ -512,12 +503,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, options ...grpc.ServerOption) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
|
||||
func restoreSetup(t *testing.T) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
|
||||
h := newFakeHost(t)
|
||||
h.name = "vol-r"
|
||||
env := h.env(t)
|
||||
base := env.Systemctl
|
||||
m, master := serveRestoreMaster(t, options...)
|
||||
m, master := serveRestoreMaster(t)
|
||||
// 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
|
||||
@@ -599,9 +590,6 @@ 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
|
||||
}
|
||||
@@ -629,7 +617,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 != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
|
||||
if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
|
||||
t.Fatalf("missing %s: %d %s %s", f, code, out, errs)
|
||||
}
|
||||
sh.setMode("")
|
||||
@@ -732,11 +720,7 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
|
||||
}
|
||||
m.failNext = r.fail
|
||||
code, _, errs := runRestore(env, restoreArgs(h)...)
|
||||
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") ||
|
||||
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") ||
|
||||
!strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
t.Fatalf("interrupted restore: %d\n%s", code, errs)
|
||||
}
|
||||
@@ -802,7 +786,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 != 1 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
|
||||
t.Fatalf("restore after abort: %d %s", code, errs)
|
||||
}
|
||||
})
|
||||
@@ -838,11 +822,7 @@ 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"},
|
||||
} {
|
||||
wantExit := 2
|
||||
if c.name == "missing snapshot" {
|
||||
wantExit = 1
|
||||
}
|
||||
if code, _, errs := runRestore(env, c.args...); code != wantExit || !strings.Contains(errs, c.want) {
|
||||
if code, _, errs := runRestore(env, c.args...); code != 2 || !strings.Contains(errs, c.want) {
|
||||
t.Errorf("%s: %d %s", c.name, code, errs)
|
||||
}
|
||||
}
|
||||
@@ -851,11 +831,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 != 1 || !strings.Contains(errs, "restore_source_not_own") {
|
||||
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 2 || !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 != 1 || !strings.Contains(errs, "target_exists") {
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "target_exists") {
|
||||
t.Errorf("target of another request: %d %s", code, errs)
|
||||
}
|
||||
delete(m.vols, "vol-r")
|
||||
@@ -873,7 +853,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 != 1 || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
t.Fatalf("refused placement: %d %s", code, errs)
|
||||
}
|
||||
if h.called("enable") != 0 {
|
||||
@@ -881,62 +861,6 @@ func TestVolumeRestoreRefusedPlacementNamesTheAbort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A step interrupted (Ctrl-C) or failed here before blockmaster answered
|
||||
// leaves the restore finishable: the failure names both ways, the same
|
||||
// command first and the irreversible abort second, never "refused".
|
||||
func TestVolumeRestoreInterruptedPlacementNamesBothWays(t *testing.T) {
|
||||
for _, fail := range []string{"bind-canceled", "bind-unauthenticated"} {
|
||||
h, env, m, _ := restoreSetup(t)
|
||||
m.failNext = fail
|
||||
code, _, errs := runRestore(env, restoreArgs(h)...)
|
||||
if code == 0 || strings.Contains(errs, "refused") || !strings.Contains(errs, "to finish, run the same command: ") || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
t.Fatalf("%s: %d %s; want both ways and no refusal", fail, code, errs)
|
||||
}
|
||||
if h.called("enable") != 0 {
|
||||
t.Fatalf("%s: started after an interrupted placement", fail)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ctrl-C after the restore-create succeeded but before the binding call goes
|
||||
// out, or a local failure at the connect step (a credential file it cannot
|
||||
// load), leaves the restore finishable: both ways, no refusal.
|
||||
func TestVolumeRestoreCtrlCAtPlacementNamesBothWays(t *testing.T) {
|
||||
orig := workspaceBindPlace
|
||||
t.Cleanup(func() { workspaceBindPlace = orig })
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
hook func(cancel context.CancelFunc) func(context.Context, string, *control.WorkspaceBinding, string) (string, error)
|
||||
}{
|
||||
{"ctrl-c before the binding call", func(cancel context.CancelFunc) func(context.Context, string, *control.WorkspaceBinding, string) (string, error) {
|
||||
return func(ctx context.Context, master string, b *control.WorkspaceBinding, replica string) (string, error) {
|
||||
cancel()
|
||||
return orig(ctx, master, b, replica)
|
||||
}
|
||||
}},
|
||||
{"local connect failure", func(context.CancelFunc) func(context.Context, string, *control.WorkspaceBinding, string) (string, error) {
|
||||
return func(context.Context, string, *control.WorkspaceBinding, string) (string, error) {
|
||||
return "connect", errors.New("load the client certificate: open /etc/sw-block/tls/client.key: no such file or directory")
|
||||
}
|
||||
}},
|
||||
} {
|
||||
h, env, _, _ := restoreSetup(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
workspaceBindPlace = c.hook(cancel)
|
||||
var out, errb bytes.Buffer
|
||||
o, err := parseVolumeRestore(restoreArgs(h), &errb)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code := volumeRestore(ctx, env, o, restoreArgs(h), &out, &errb)
|
||||
cancel()
|
||||
errs := errb.String()
|
||||
if code == 0 || strings.Contains(errs, "refused") || !strings.Contains(errs, "to finish, run the same command: ") || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
t.Fatalf("%s: %d %s; want both ways and no refusal", c.name, code, errs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --abort acts only on this restore's own target: a volume the master
|
||||
// records for another source, snapshot or request, or a plain volume, is
|
||||
// refused before anything changes (no systemctl, settings kept, no delete
|
||||
@@ -1070,7 +994,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 != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
|
||||
if code != 1 || !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 {
|
||||
@@ -1142,7 +1066,7 @@ func TestVolumeRestoreRefusesAMalformedLayoutAnswer(t *testing.T) {
|
||||
h, env, m, _ := restoreSetup(t)
|
||||
m.failNext = "create-badlayout"
|
||||
code, _, errs := runRestore(env, restoreArgs(h)...)
|
||||
if code != 3 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
|
||||
if code != 1 || !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,7 +11,6 @@ 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"
|
||||
@@ -54,30 +53,20 @@ func runOpsVolumeCreate(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
conn, err := link.DialMasterFromEnv(*master)
|
||||
if err != nil {
|
||||
policy, detail := operatorAnswer(err, answer.VolumeCreate)
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", detail)
|
||||
return policy.Exit
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
fail := func(step string, err error) int {
|
||||
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
|
||||
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"
|
||||
}
|
||||
outcome := "refused"
|
||||
if policy.Retryable {
|
||||
outcome = "unknown"
|
||||
}
|
||||
cure := policy.Cure
|
||||
if step != "create" && step != "create reply" && !policy.Retryable {
|
||||
// CreateVolume already succeeded: the volume record exists.
|
||||
cure += "; earlier steps may remain recorded; retry the identical name, geometry and placement"
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; %s\n", step, outcome, err, cure)
|
||||
return policy.Exit
|
||||
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
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -209,27 +209,6 @@ func TestOpsVolumeCreateStopsAfterRefusedOrUnknownStep(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A binding or placement refused after CreateVolume succeeded leaves the
|
||||
// created record: the refusal says so and names the identical retry, so an
|
||||
// operator does not move to a new name and orphan it.
|
||||
func TestOpsVolumeCreateRefusalAfterCreateNamesTheIdenticalRetry(t *testing.T) {
|
||||
for _, step := range []string{"bind", "place"} {
|
||||
s := &createAndPlaceReceiver{failStep: step, failErr: status.Error(codes.FailedPrecondition, "injected")}
|
||||
addr := serveCreateAndPlace(t, s)
|
||||
var out, errout bytes.Buffer
|
||||
code := run(createAndPlaceArgs(addr), &out, &errout)
|
||||
if code != 78 || !strings.Contains(errout.String(), "earlier steps may remain recorded; retry the identical name, geometry and placement") {
|
||||
t.Fatalf("%s refused: code=%d err=%q", step, code, &errout)
|
||||
}
|
||||
}
|
||||
s := &createAndPlaceReceiver{failStep: "create", failErr: status.Error(codes.FailedPrecondition, "injected")}
|
||||
addr := serveCreateAndPlace(t, s)
|
||||
var out, errout bytes.Buffer
|
||||
if code := run(createAndPlaceArgs(addr), &out, &errout); code != 78 || strings.Contains(errout.String(), "earlier steps may remain recorded") {
|
||||
t.Fatalf("a refused create claims earlier steps: code=%d err=%q", code, &errout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpsVolumeCreateRefusesUnreadyOrMismatchedAnswers(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
|
||||
Loaded 100 of 656 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user