mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
145 lines
8.2 KiB
Python
145 lines
8.2 KiB
Python
"""Run fake recorders through the real group executor, without product tests."""
|
|
from pathlib import Path
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import time
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import Mock, patch
|
|
import importlib.util
|
|
import signal
|
|
|
|
SCRIPT = Path(__file__).with_name("run-unit-groups.py")
|
|
FAKE = r'''import json, os, sys, time
|
|
from pathlib import Path
|
|
out = Path(sys.argv[1]); group = out.parent.name
|
|
root = Path(os.environ["FIXTURE_ROOT"])
|
|
(root / (group + ".started")).write_text("started")
|
|
deadline = time.monotonic() + 5
|
|
while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()):
|
|
if time.monotonic() >= deadline: sys.exit(17)
|
|
time.sleep(.01)
|
|
flags = sys.argv[2:]
|
|
assert "-p=" + ("4" if group == "g3" else "1") in flags
|
|
assert "-short" in flags and "-count=1" in flags and "20m" in flags
|
|
if sys.platform == "linux":
|
|
wal = Path(os.environ["TMPDIR"]) / "v1.bin"
|
|
with wal.open("w") as descriptor:
|
|
assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found"
|
|
else:
|
|
assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory"
|
|
out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n")
|
|
out.with_suffix(".stderr").write_text("fixture stderr")
|
|
(root / (group + ".finished")).write_text("finished")
|
|
sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0)
|
|
'''
|
|
|
|
|
|
class GroupRunnerTests(unittest.TestCase):
|
|
def run_groups(self, fail="", empty=False, alias=False):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
|
for group in ("g1", "g2", "g3"):
|
|
(plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n")
|
|
fake = root / "fake.py"; fake.write_text(FAKE)
|
|
env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail)
|
|
scratch = root / "tmp"
|
|
if alias:
|
|
scratch.mkdir()
|
|
link = root / "runner-temp"
|
|
link.symlink_to(scratch, target_is_directory=True)
|
|
scratch = link
|
|
result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20)
|
|
self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr)
|
|
expected = ["g3"] if empty else ["g1", "g2", "g3"]
|
|
for group in expected:
|
|
self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr)
|
|
self.assertTrue((root / "evidence" / group / "go-test.stderr").exists())
|
|
self.assertTrue((root / "tmp" / group).is_dir())
|
|
events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()]
|
|
self.assertCountEqual([e["Package"] for e in events], expected)
|
|
statuses = json.loads((root / "evidence" / "unit-groups.json").read_text())
|
|
self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0)
|
|
|
|
@unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control")
|
|
def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True)
|
|
|
|
def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups()
|
|
def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2")
|
|
def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True)
|
|
|
|
|
|
def test_cancel_escalates_even_after_group_leader_exits(self):
|
|
spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT)
|
|
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
|
|
leader = Mock(pid=12345)
|
|
leader.wait.return_value = 0
|
|
with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]):
|
|
module.terminate([leader])
|
|
self.assertIn(unittest.mock.call(12345, signal.SIGTERM), killpg.call_args_list)
|
|
self.assertIn(unittest.mock.call(12345, 9), killpg.call_args_list)
|
|
leader.wait.assert_called()
|
|
|
|
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
|
|
def test_cancel_kills_resistant_child_after_recorder_exits(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
|
for group in ("g1", "g2", "g3"):
|
|
(plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "")
|
|
child = root / "child.py"
|
|
child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n")
|
|
fake = root / "recorder.py"
|
|
fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n")
|
|
marker = root / "child"
|
|
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
|
pid = None
|
|
try:
|
|
deadline = time.monotonic() + 5
|
|
while not marker.exists():
|
|
if time.monotonic() >= deadline: self.fail("resistant child did not start")
|
|
time.sleep(.01)
|
|
pid = int(marker.read_text())
|
|
runner.terminate()
|
|
self.assertEqual(runner.wait(timeout=12), 130)
|
|
deadline = time.monotonic() + 2
|
|
while True:
|
|
stat = Path(f"/proc/{pid}/stat")
|
|
if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break
|
|
if time.monotonic() >= deadline: self.fail("resistant child survived cancellation")
|
|
time.sleep(.01)
|
|
finally:
|
|
if pid is not None:
|
|
try: os.kill(pid, signal.SIGKILL)
|
|
except ProcessLookupError: pass
|
|
if runner.poll() is None: runner.kill()
|
|
runner.communicate(timeout=5)
|
|
|
|
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
|
|
def test_cancel_joins_every_started_group(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
|
for group in ("g1", "g2", "g3"):
|
|
(plan / (group + ".txt")).write_text("example/" + group + "\n")
|
|
fake = root / "held.py"
|
|
fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n")
|
|
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
|
try:
|
|
deadline = time.monotonic() + 5
|
|
markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")]
|
|
while not all(p.exists() for p in markers):
|
|
if time.monotonic() >= deadline: self.fail("groups did not start")
|
|
time.sleep(.01)
|
|
children = [int(p.read_text()) for p in markers]
|
|
runner.terminate()
|
|
self.assertEqual(runner.wait(timeout=10), 130)
|
|
for child in children:
|
|
with self.assertRaises(ProcessLookupError): os.kill(child, 0)
|
|
finally:
|
|
if runner.poll() is None: runner.terminate()
|
|
runner.communicate(timeout=10)
|
|
|
|
|
|
if __name__ == "__main__": unittest.main()
|