Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omnet/blob/main/cmd/tkad/test/directory.py # omnet aien-dev/omnet Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omnet / cmd / tkad / test / directory.py` 143 lines ยท 6008 bytes Raw Blame History 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: Apache-2.0 3 """Directory replacement after open: the held descriptor, not the path, is the store.""" 4 import json 5 import os 6 import pathlib 7 import socket 8 import struct 9 import subprocess 10 import sys 11 import tempfile 12 import time 13 14 BIN = pathlib.Path(sys.argv[1]).resolve() 15 FIX = json.loads(pathlib.Path(__file__).with_name("fixture.json").read_text()) 16 checks = 0 17 18 19 def check(value, message): 20 global checks 21 assert value, message 22 checks += 1 23 24 25 def exact(sock, count): 26 result = b"" 27 while len(result) < count: 28 part = sock.recv(count - len(result)) 29 if not part: 30 raise AssertionError("truncated daemon reply") 31 result += part 32 return result 33 34 35 class Daemon: 36 def __init__(self, directory, initialize=False): 37 self.directory = pathlib.Path(directory) 38 self.p = subprocess.Popen([str(BIN), str(self.directory)] + (["--init"] if initialize else []), 39 stdout=subprocess.PIPE, stderr=subprocess.PIPE) 40 deadline = time.monotonic() + 30 41 while time.monotonic() < deadline: 42 if self.p.poll() is not None: 43 raise AssertionError(f"startup rc={self.p.returncode}: {self.p.communicate()}") 44 try: 45 with socket.socket(socket.AF_UNIX) as s: 46 s.settimeout(.2) 47 s.connect(str(self.directory / "tkad.sock")) 48 return 49 except (FileNotFoundError, ConnectionRefusedError, TimeoutError): 50 time.sleep(.02) 51 raise AssertionError("socket readiness timeout") 52 53 def stop(self): 54 if self.p.poll() is None: 55 self.p.kill() 56 return self.p.communicate(timeout=10) 57 58 def rpc(self, route, body=None, node=1, admin=False, expected=200): 59 payload = json.dumps(body or {}, separators=(",", ":")).encode() 60 frame = struct.pack("<4sBBHQI", b"TKA\x01", route, int(admin), 0, node, len(payload)) + payload 61 with socket.socket(socket.AF_UNIX) as s: 62 s.settimeout(30) 63 s.connect(str(self.directory / "tkad.sock")) 64 s.sendall(frame) 65 magic, status, reserved, size = struct.unpack("<4sHHI", exact(s, 12)) 66 check(magic == b"TKA\x01" and reserved == 0 and size <= 65536, "reply header") 67 answer = json.loads(exact(s, size)) 68 check(status == expected, f"route {route}: expected {expected}, got {status}: {answer}") 69 check(self.p.poll() is None, "daemon trapped/exited") 70 return answer 71 72 def register(self, index): 73 return self.rpc(9, dict(NodeID=index + 1, NodeKey=FIX["nodes"][index], RotationPubkey=FIX["rotations"][index]), node=0, admin=True) 74 75 def revision(self): 76 return self.rpc(11, node=0, admin=True)["Revision"] 77 78 def storeid(self): 79 return self.rpc(11, node=0, admin=True)["StoreID"] 80 81 82 def files(directory): 83 return sorted(p.name for p in pathlib.Path(directory).iterdir()) 84 85 86 def refused(directory): 87 run = subprocess.run([str(BIN), str(directory)], capture_output=True, timeout=20) 88 return run.returncode 89 90 91 with tempfile.TemporaryDirectory(prefix="tkad-replaced-") as top: 92 live = pathlib.Path(top) / "store" 93 live.mkdir(mode=0o700) 94 moved = pathlib.Path(top) / "store-moved" # where the opened directory went 95 daemon = Daemon(live, initialize=True) 96 try: 97 daemon.register(0) 98 check(daemon.revision() == 1, "first append committed") 99 inode = os.stat(live).st_ino 100 check("snapshot" in files(live), "snapshot on disk before replacement") 101 102 # An unprivileged racer replaces the path with a fresh directory of the 103 # same name while the daemon keeps its descriptor open. 104 os.rename(live, moved) 105 live.mkdir(mode=0o700) 106 check(os.stat(live).st_ino != inode and os.stat(moved).st_ino == inode, "path now names a different directory") 107 daemon.directory = moved 108 check(os.path.realpath(f"/proc/{daemon.p.pid}/cwd") == os.path.realpath(moved), "daemon cwd is the opened directory") 109 110 check(daemon.revision() == 1, "reads still served from the opened directory") 111 daemon.register(1) 112 check(daemon.revision() == 2, "append after replacement committed") 113 check(files(live) == [], f"replacement directory untouched: {files(live)}") 114 check("snapshot" in files(moved), "snapshot written beside the opened descriptor") 115 116 # The held directory still excludes a second store on the inode, whatever 117 # its path is now called. 118 check(refused(moved) == 73, "exclusion follows the inode, not the path") 119 # The replacement directory holds no store, so a resume there refuses 120 # instead of serving a fresh empty revision as if it were this store. 121 check(refused(live) == 73, "resume in the replacement directory refused") 122 check(files(live) == [], "refused resume wrote nothing into the replacement") 123 124 # The same path can host an unrelated store while the opened one is still 125 # live. Its identity is what tells a reconnecting client that the path it 126 # follows now names a different store. 127 other = Daemon(live, initialize=True) 128 try: 129 check(other.revision() == 0, "replacement path accepted an independent empty store") 130 check(other.storeid() != daemon.storeid(), "replacement store is distinguishable by identity") 131 finally: 132 other.stop() 133 finally: 134 daemon.stop() 135 136 # Nothing was lost by the rename: the committed revision is still there. 137 reopened = Daemon(moved) 138 try: 139 check(reopened.revision() == 2, "committed revision survives restart") 140 check(files(moved).count("snapshot") == 1, "single snapshot after restart") 141 finally: 142 reopened.stop() 143 print(f"PASS tkad directory replacement: {checks} checks, commits land beside the opened descriptor, replacement stays empty and refuses resume")