From ce6e42357dac9d7270e9f4e4a56f21585cce5fe8 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:09:49 +0000 Subject: [PATCH] 007 S007-05: Schema and roles tests, the register templates `tmpl` and `tmpl_imported`, and the fixture's logins (T221, T231, T227, T216, T228; part of opensoft/openRepoTools#165) Pull request P02 of feature 007's task sets, version 12g: lane 2's set S007-05 in one commit, through the code queue. It is stacked on P01, code pull request opensoft/openRepoTools-code#88 (`7f1141be`), its immediate predecessor (rule 2): its base is P01's head 7f1141be15ac9c0d20c25c802ba9533c2fec811c, on code main's c9c65cc14695732c9badf9f1f7cac795f661d524, P01's own base. It is cut from lane 1's line R at merge163 8acf1308538659d6ac12d690f310bdc292cb7aea, the first merge to hold all its commits, which took lane 2's T228c (merge164 9990baf05e9eb538f4fb82fac80b6ea1e9830bd7 takes T243x and changes none of these four paths); merge161 8f3278e70d1b783e48fd196c8ad6f052766bcf12 took lane 2's T231j. Its 31 task commits, all built by lane 2, were picked with cherry-pick -x in line R's order; the part below lists them in that order. 29 picks applied with no conflict and kept their own patch-ids. Two, T227b and T228b, met text the cut lacks and are settled below, each adding exactly its own lines. Every path is in its task's files:, is a marker, or is T228b's or T228c's hunk in the fixture module (below). No plain commit of landing note 15 falls in this set, and no line R commit holds its code by hunk. The full shas are pointers into lane 1's share. Rule 11: lane 2's gate tables for the schema module (T221l) and the roles module (T216b) are on line R since merge110 and merge116, and in this commit. The schema table here, as T221l added it and T231f, T231g, T231h and T231i extended it, has 57 keys: 51 test-function names, one for each of the module's 51 test functions, and 6 single ids, name[param]. The roles table has one key, the "*" row, which makes every id of the module wait for T107, T108, T109, T110 and T228. T228b's and T228c's hunks in T200's fixture module: version 12g's row for P02 brings T228b's 70-line case into this pull request, since T228's files: gain tests/test_sql_register_fixture.py on the spec side, and T228c, T228's slice for that case, adds two import lines there. tasks.md at spec main c304e387cf9b5a1ccd3337e926a5d726132b1547 does not hold that path yet: T228's files: name only tests/pgcluster.py. Until it does, the set-PR kit refuses this pull request's prompt with R-PATH-OUTSIDE on that path unless it is given --allow-extra-path. T228b's case reads the names threading and time, which P01's module does not import, and which line R's fixture module imports with T229b's import lines (S007-13). T228c adds `import threading` and `import time` after `import sys`, where T229b puts them, so the case's names are bound in this commit without T229b, as T205d's `import pytest` binds T205c's in P01. In this pull request's own CI the gate is active, and the landed tasks are P01's seven and these five. A gated collection of the suite on this commit's tree holds 5738 ids. None of the 173 ids of the schema and roles modules runs: each waits for at least one task that neither P01 nor P02 lands, and skips naming it, the schema module's 157 (104 of them for T107, T108, T109 and T110) and the roles module's 16 (all for T107, T108, T109 and T110). The gate skips none of the other 5565 ids: P01's tree's 5564, none of whose states these markers change, and T228b's case, in the fixture module, which has no table and whose names T228c binds. 007 S007-05: Schema and roles tests, the register templates `tmpl` and `tmpl_imported`, and the fixture's logins (T221, T231, T227, T216, T228; part of opensoft/openRepoTools#165) - T227 and T228, lane 2's, each whole, 4 commits in line R's merge108 9a2fdfeaf95b72945f5ff488bc0212f95b416230, which took lane 2's line FX, in this order: T227 b614a29cb9b2fe26b8d5406bffe6d9b3a85b40d3, T228 a8020f88e76a50a0efdf3ec454df9d6ee63ecae3, T227b e2097879f521b20d0124a22bcd1fb276604443bf and T227c a048fddb75523cd36e8866bffebc1c327ac7c52a. T227b's pick meets text the cut lacks in tests/pgcluster.py at two places: it adds its `_imported_check` method and its blank line, 17 lines, just before T229a's `prepare`, and its test 7 fixture register, 259 lines, just before T229a's section 5.6 clusters (S007-13). Each hunk is settled as the cut's text plus T227b's own lines, so the pick adds and removes exactly T227b's lines, +334 -28. - T221 and T231, lane 2's, each whole, 17 commits in line R's merge110 1c33787b8c76b227910fecbbc5f230d20df140f9, which took lane 2's line W3b, in this order: T221 f4099e7e34d8406c2208eeefcf044796556b32f0, T221 3535234991af582142642f6548f16c7f62bf1f43, T221c fbb88015a8a9b4df4b348828977a23bb26ca184b, T221d 2cb95f61539a28ce6b2d59615005c5c958acbc9e, T221f 82517031b0c714e7ca847899173089548fcb46a0, T221e 8f645fcecf2b019b79b8e44124d405f2f6082aee, T221g de8db6327bb0135df6b85d8a5e97c17831241059, T221h 409684d774b9e1bd80525058c5becf208cc73611, T231 0ff301b43c4ca00410e5d2a737557868fd5d4703, T231b f3fb08ec9a972191c8a054b8952b8b71f8b2c6f2, T231c 9326400f3aa9cc5e9c18fc6da2fb0cf7636a70fd, T221i 41f97198394f24adbddc6d16dc0f66953ecb6a84, T231d 7c086f12754d323e66742a305f0f178d4fd091ae, T221j 0154c915f5b8fbc20f43d54f7c5fd132d3c42808, T231e 0d34bd83286a8474163e6eedef71a26d34a4585d, T221k 638178b81723d645a044bbe4812facb8e828d933 and T221l e4b5a525fcc54666dbcee30b7e95f9e399fc0f37, the schema module's gate table. - T216, lane 2's, whole, 3 commits in line R's merge116 d0198d1537cd858ef16fdaac9ed4d213c1edc013, which took lane 2's line N2: T216 5f3c46336b85e647742c27fc2c2ea3b5dbdb5cf4, T216a fa5988e2db7de879f75f24f8f58c0f4a3a109d79 and T216b 383cfdbb52dca814c3a36bed88f3d330ba24f29e, the roles module's gate table. tests/test_sql_register_roles.py then equals line R's merge163 blob 607bed3496d07b7857aa0d702548874953a87083, which it holds since merge116. - T231f, lane 2's, whole: c4c9d74656262227149cecb401c9c5903eb1861b, line R's merge135 b0a6ab947a8e56fc995708ab32b23a6b2d426aad. - T231g, lane 2's, whole: 56526c02bc7914ea2355a1abd2ed81cc661a5e0f, line R's merge141 7253e6eb1fd68498326652f85cc1f848ae0c15c2. - T228b, lane 2's, whole: 1ca4807bcde86241083b6e874ee7a74d491d1724, line R's merge147 a7945c9046435d5fad88439505f9aebdcb4a1dc4. Its tests/pgcluster.py hunks apply with no conflict. In the fixture module it appends its 70-line case just after T229e's case (S007-13), which the cut lacks; the hunk is settled as P01's blob 3c3f9c095cb201e312dbd9741e9829b757de6e52 plus exactly those 70 lines, so the pick adds and removes exactly T228b's lines, +93 -5. - T231h and T231i, lane 2's, each whole, in line R's merge157 a532ee90dcc78083dcb39eb172e1db0c8ce4ff0e: T231h 6469d9d54d4c5b5caeeefdde1255817345e8db79 and T231i 687bab419d2bf5eca88f84233d435fa517b4c450. - T231j, lane 2's, whole: 7240d52107d45a4fbecd6d345833573307d8f221, line R's merge161 8f3278e70d1b783e48fd196c8ad6f052766bcf12. tests/test_sql_register_schema.py then equals line R's merge163 blob dcfd5c31e0151d838475f1b969b3ccc9a72d85cc, which it holds since merge161. - T228c, lane 2's, whole: dd0993a34d011c97f75aa56bc666261b51964e1c, one commit on T205d, line R's merge163 8acf1308538659d6ac12d690f310bdc292cb7aea, which left line R's tree unchanged, since T229b's lines were there. It adds `import threading` and `import time` after `import sys` in the fixture module, the two names T228b's case reads, and nothing else. Its pick applies with no conflict and keeps its own patch-id. - tests/pgcluster.py then equals line R's merge163 blob b72bfcdf2381fc72d92660c8a3970f06253a0903 less exactly the 659 lines of T229a, T229c, T229d and T229f (S007-13) that line R's blob holds, and plus the 17 lines of P01's and T227's text that T229a and T229d replace. The fixture module equals line R's merge163 blob 6ae31181d17351a71c257d766791e7c4c8e21d63 less exactly the 462 of the 466 lines that T229b, T229c, T229e and T229f add there and line R's blob holds; the other four, which T229b also adds, are in the cut: `import pytest` and its blank line, which P01's T205d holds, and `import threading` and `import time`, which T228c holds. - Every line R merge that touches tests/pgcluster.py or the fixture, schema or roles module, lane 2's merges inside its lines among them, is there the clean merge of its two parents, so no merge's own change is carried. - Markers: tests/sql_register_landed/T221, T231, T227, T216 and T228. Lane: openRepoTools-1 Co-Authored-By: Claude Opus 5.5 --- tests/pgcluster.py | 687 +++++- tests/sql_register_landed/T216 | 0 tests/sql_register_landed/T221 | 0 tests/sql_register_landed/T227 | 0 tests/sql_register_landed/T228 | 0 tests/sql_register_landed/T231 | 0 tests/test_sql_register_fixture.py | 72 + tests/test_sql_register_roles.py | 562 +++++ tests/test_sql_register_schema.py | 3376 ++++++++++++++++++++++++++++ 9 files changed, 4671 insertions(+), 26 deletions(-) create mode 100644 tests/sql_register_landed/T216 create mode 100644 tests/sql_register_landed/T221 create mode 100644 tests/sql_register_landed/T227 create mode 100644 tests/sql_register_landed/T228 create mode 100644 tests/sql_register_landed/T231 create mode 100644 tests/test_sql_register_roles.py create mode 100644 tests/test_sql_register_schema.py diff --git a/tests/pgcluster.py b/tests/pgcluster.py index 14eb9360..97871b78 100644 --- a/tests/pgcluster.py +++ b/tests/pgcluster.py @@ -22,17 +22,47 @@ * `pg_engine`, session-scoped: the binaries, found once. EVERY CLUSTER DEPENDS ON IT, so a test whose fixture closure holds it is a real-engine test, which is how `test_sql_register_fixture.py` tells one apart; - * `pg_template_sql`, session-scoped and overridable: the SQL that builds the - template's schema, empty until the bootstrap lands (T227); + * `pg_template_sql`, session-scoped and overridable: how the template is + built. By default it is `Bootstrap()`, P8's bootstrap (T227, below); a + module may return SQL of its own instead, run on an empty `tmpl`; * `pg_cluster`, session-scoped: the session's cluster, with the template - `tmpl` built, then closed to connections; - * `pg`, one database per test, `CREATE DATABASE t_ TEMPLATE tmpl`, and - dropped `WITH (FORCE)` at its teardown; + `tmpl` built, then closed to connections, and `tmpl_imported` beside it; + * `pg`, one database per test, `CREATE DATABASE t_ TEMPLATE tmpl`, then + section 1.4's two database-level statements, and dropped `WITH (FORCE)` + at its teardown; + * `pg_imported`, the same from `tmpl_imported`, the imported register: a + case that clones it fails, saying why, where the session has none; * `stoppable_cluster`, a cluster of the test's own, built like the session's, for the tests that stop the database: `stop()` is a fast shutdown, SIGINT and a wait, and `start_again()` starts it on the same data and socket directories. +THE TEMPLATES (T227; the test plan's section 3.1, "The templates"). `tmpl` is +built on each cluster by P8's bootstrap, `lanes-index bootstrap --no-passwords` +(lane 1's T109, L1-A7), run through the admin service as AT-P8's fixture runs +it: a libpq service in `~/.pg_service.conf` of the cluster's own 0700 `admin` +home, naming the cluster's socket, its superuser and the database, so no +connection string is ever an argument. It makes the schema, the owner, the +groups REGISTER-WRITER and READER, the indexer's login and their GRANTs, and +labels the switch `register-test`. Then the fixture's logins are made (T228: +`lanes-index login add fx` and `login add --dump-job`, through the same service +under a pty, since `login` refuses off a terminal): `lanes_w_fx` and +`lanes_r_fx`, as which every session a test runs as REGISTER-WRITER or as +READER logs in, and `lanes_register_dump`; their passwords stay in memory for +`passfile()`. Then `tmpl` is marked `IS_TEMPLATE true +ALLOW_CONNECTIONS false`. A clone does not copy `pg_database.datacl`, so each +clone runs section 1.4's `REVOKE ALL ON DATABASE` and `GRANT CONNECT`, with +`-v db=` its name; the first run prints what a clone's `datacl` held before +them (open point 12). On the session cluster, `tmpl_imported` is cloned from +`tmpl`, with test 7's fixture register imported by `lanes-index import --at +` (lane 1's T115, L1-A13), as the operator lane does it (T227b): the +register, AT-7's, is built on a repository of the fixture's own (a bare origin, +the operator lane's checkout that `LANES_REPO` names, and W, a view that is +never it), and the import runs as `lanes_w_fx` while the switch reads `files` +with the marker `absent`. Where it does not import, there is no +`tmpl_imported`, the run's foot says why, and the cases that clone it fail; a +bootstrap that fails fails each real-engine test, saying so. + The binaries' directory goes first on `PATH` while a cluster is up, so the code under test runs the `psql` of the server it talks to, and every subprocess the fixture runs has no inherited `PG*` variable. @@ -101,6 +131,47 @@ _SKIPPED: List[str] = [] _SWEPT: List[str] = [] +#: THE CODE UNDER TEST'S `lanes-index`, which the template's build runs. +REPO = Path(__file__).resolve().parent.parent +LANES_INDEX = REPO / "lanes-index" +LANES_EDIT = REPO / "lanes-edit.sh" + +#: THE TEMPLATES (T227): the imported template's name, and the bootstrap's +#: inputs. The label is the one the import, outage and bounds modules name in +#: their `register_label=`; the others fill the switch's and the migrations +#: row's columns, whose CHECKs ask only that each is not empty. +IMPORTED = "tmpl_imported" +FX_LABEL = "register-test" +FX_REPOSITORY = "opensoft/openRepoTools-fixture" +FX_LANE = "fixture" +FX_WORKSTATION = "fixture" + +#: SECTION 1.4'S TWO DATABASE-LEVEL STATEMENTS, as lane 1's role block holds +#: them (Y:2243-2244; `lanes-index`'s `_REGISTER_ROLE_BLOCK`), with `-v db=`. +DATABASE_LEVEL = ('REVOKE ALL ON DATABASE :"db" FROM PUBLIC;\n' + 'GRANT CONNECT ON DATABASE :"db" TO lanes_register_writer, ' + 'lanes_register_reader, lanes_indexer;\n') + +#: What the admin's `lanes-index` never inherits: the configuration's and the +#: workspace's variables. `PG*` goes too, as everywhere here. +ADMIN_ENV_DROPPED = ("LANES_", "XDG_CONFIG_HOME", "XDG_STATE_HOME", "AGENT_PROTOCOL_ROOT", + "PROJECTS_", "TMUX", "CLAUDE_") +_DATACL: List[str] = [] +_IMPORTED: List[str] = [] +_IMPORTED_AT: List[str] = [] + +#: THE FIXTURE'S LOGINS (T228): the engineer `login add` is run for, and the +#: three logins it and `login add --dump-job` make. Every session a test runs +#: as REGISTER-WRITER or as READER logs in as the writer or the reader. +FX_ENGINEER = "fx" +FX_WRITER, FX_READER, FX_DUMP = "lanes_w_fx", "lanes_r_fx", "lanes_register_dump" +FX_LOGINS = (FX_WRITER, FX_READER, FX_DUMP) + +#: A password-file line as `login add` prints it once, to a terminal: +#: `*:*:::` (lane 1's `_register_pgpass_line`). +PASSWORD_LINE = re.compile(r"^\*:\*:(?:[^:\\\n]|\\.)*:(lanes_[a-z0-9_]+):([^:\s]+)$", re.M) +_SECRET_FIELD = re.compile(r"^(\*:\*:.*:)[^:\n]*$", re.M) + def _fixture(**options): """`pytest.fixture(**options)`; in the smoke, which runs without pytest, @@ -223,6 +294,9 @@ def _without_pg(environ=os.environ) -> Dict[str, str]: _PROC = Path("/proc") _kill = os.kill ORPHAN_WAIT = 10.0 # seconds a stale postmaster gets to end, per signal +#: `lanes_index_tty`'s bound and launcher, named for its test (T228b). +TTY_DEADLINE = 300.0 +_tty_popen = subprocess.Popen def _ticks(pid: int) -> str: @@ -331,6 +405,31 @@ class ClusterError(Exception): pass +class Bootstrap: + """`pg_template_sql`'S DEFAULT (T227): build `tmpl` by P8's bootstrap, + then make the fixture's logins (T228) unless `logins` is False, then run + `sql`, if any, on it. A plain string instead is SQL run on an empty + `tmpl`, as the smokes' clusters have it.""" + + def __init__(self, sql: str = "", logins: bool = True) -> None: + self.sql, self.logins = sql, logins + + def __repr__(self) -> str: + return f"Bootstrap(sql={self.sql!r}, logins={self.logins!r})" + + +def _masked(text: str) -> str: + """`text` with each password-file line's last field, the password, hidden.""" + return _SECRET_FIELD.sub(lambda m: m.group(1) + "", text or "") + + +def _tail(proc: subprocess.CompletedProcess, size: int = 800) -> str: + """A command's last words, stdout then stderr, on one line.""" + said = " | ".join(line.strip() for line in f"{proc.stdout or ''}\n{proc.stderr or ''}".splitlines() + if line.strip()) + return said[-size:] or "" + + def _client_env(host: Path, user: str, dbname: str, appname: str, bindir: Path) -> dict: env = _without_pg() env.update(PGHOST=str(host), PGPORT=str(PORT), PGUSER=user, PGDATABASE=dbname, @@ -355,11 +454,24 @@ def preexec() -> None: class Cluster: """One cluster: its private directory, its postmaster and its template.""" - def __init__(self, bindir: Path, template_sql: str = "") -> None: - self.bindir, self.template_sql = bindir, template_sql + def __init__(self, bindir: Path, template_sql="", imported: bool = False) -> None: + """`template_sql` is `pg_template_sql`'s value: a `Bootstrap`, or SQL + for an empty `tmpl` (the smokes' default). `imported` builds + `tmpl_imported` too.""" + self.bindir, self.template_sql, self.imported = bindir, template_sql, imported self.root: Optional[Path] = None self.proc: Optional[subprocess.Popen] = None self.count, self.timings = 0, {} + #: The switch's label where the bootstrap built `tmpl`, else None. + self.label: Optional[str] = None + #: Why there is no `tmpl_imported`, where it was asked for and is not. + self.imported_problem: Optional[str] = None + #: The repository `tmpl_imported` was imported from (T227b), once it + #: is: its origin, the operator lane's checkout, W and C. Read only. + self.imported_register: Optional["ImportedRegister"] = None + #: The fixture's logins' passwords, as `login add` printed them once + #: (T228). Kept in memory for `passfile()`, never printed. + self.passwords: Dict[str, str] = {} def tool(self, name: str) -> str: return str(self.bindir / name) @@ -370,10 +482,14 @@ def server_env(self) -> dict: return env def psql(self, sql: str, dbname: str = "postgres", user: str = SUPERUSER, - check: bool = True, appname: str = "pytest") -> subprocess.CompletedProcess: - proc = subprocess.run([self.tool("psql"), "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", - "-f", "-"], input=sql, capture_output=True, text=True, timeout=120, - env=_client_env(self.root, user, dbname, appname, self.bindir), + check: bool = True, appname: str = "pytest", + variables: Optional[Dict[str, str]] = None) -> subprocess.CompletedProcess: + argv = [self.tool("psql"), "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"] + for name, value in (variables or {}).items(): + argv += ["-v", f"{name}={value}"] + proc = subprocess.run([*argv, "-f", "-"], input=sql, capture_output=True, text=True, + timeout=120, env=_client_env(self.root, user, dbname, appname, + self.bindir), check=False) if check and proc.returncode != 0: raise ClusterError(f"psql as {user} on {dbname} exited {proc.returncode}: {proc.stderr.strip()}") @@ -412,13 +528,227 @@ def start(self) -> None: t2 = time.monotonic() self.launch() t3 = time.monotonic() - self.psql(f"CREATE DATABASE {TEMPLATE};") - if self.template_sql.strip(): - self.psql(self.template_sql, dbname=TEMPLATE) - self.psql(f"ALTER DATABASE {TEMPLATE} WITH IS_TEMPLATE true ALLOW_CONNECTIONS false;") + self.build_template() t4 = time.monotonic() self.timings = {"initdb": t2 - t1, "ready": t3 - t2, "template": t4 - t3, "start": t4 - t0} + # -------------------------------------------------------- the templates (T227) + def build_template(self) -> None: + """`tmpl`, by the bootstrap or by SQL, then `tmpl_imported` where it + was asked for, then `tmpl` closed to connections.""" + self.psql(f"CREATE DATABASE {TEMPLATE};") + sql = self.template_sql + if isinstance(sql, Bootstrap): + self.bootstrap(TEMPLATE, FX_LABEL) + self.label = FX_LABEL + if sql.logins: + self.make_logins(TEMPLATE) + sql = sql.sql + if sql.strip(): + self.psql(sql, dbname=TEMPLATE) + if self.imported: + self.build_imported() + self.psql(f"ALTER DATABASE {TEMPLATE} WITH IS_TEMPLATE true ALLOW_CONNECTIONS false;") + + def admin_env(self) -> dict: + """THE ADMIN'S `lanes-index` ENVIRONMENT: no `PG*`, no configuration or + workspace variable, `HOME` the cluster's own `admin` directory (where + `~/.pg_service.conf` is, and no `lanes-index.conf`, so `load_config` + reads its defaults), the workstation named, and the engine's tools + first on `PATH`, so its `psql` is the server's.""" + env = {k: v for k, v in _without_pg().items() if not k.startswith(ADMIN_ENV_DROPPED)} + env.update(HOME=str(self.root / "admin"), LANES_WORKSTATION=FX_WORKSTATION, LC_ALL="C", + TZ="UTC", PATH=_engine_first(self.bindir, env.get("PATH", os.defpath))) + return env + + def admin_service(self, database: str) -> str: + """The admin service naming `database`: a section of the admin home's + `.pg_service.conf`, 0600, with the cluster's socket and superuser. + The socket's trust needs no `~/.pgpass`.""" + home = self.root / "admin" + home.mkdir(mode=0o700, exist_ok=True) + name, path = f"fx_{database}", home / ".pg_service.conf" + text = path.read_text(encoding="utf-8") if path.exists() else "" + if f"[{name}]\n" not in text: + text += (f"[{name}]\nhost={self.root}\nport={PORT}\nuser={SUPERUSER}\n" + f"dbname={database}\n\n") + path.write_text(text, encoding="utf-8") + path.chmod(0o600) + return name + + def lanes_index(self, argv: List[str]) -> subprocess.CompletedProcess: + """The code under test's `lanes-index`, as the admin, from the + cluster's directory.""" + return subprocess.run([sys.executable, str(LANES_INDEX), *argv], stdin=DEVNULL, + capture_output=True, text=True, env=self.admin_env(), + cwd=str(self.root), timeout=300, check=False) + + def lanes_index_tty(self, argv: List[str]) -> Tuple[int, str, str]: + """`lanes_index` with its stdout a pty, for `login`, which refuses off + a terminal (operations.md section 2.4): (exit, stdout, stderr), the + pty's CR LF read back as LF. A run that outlasts the admin's 300 s is + killed.""" + import pty + import select + primary, secondary = pty.openpty() + try: + proc = _tty_popen([sys.executable, str(LANES_INDEX), *argv], stdin=DEVNULL, + stdout=secondary, stderr=subprocess.PIPE, + env=self.admin_env(), cwd=str(self.root)) + except OSError: + os.close(primary) + raise + finally: + os.close(secondary) + out, end = [], time.monotonic() + TTY_DEADLINE + try: + while time.monotonic() < end: + ready, _, _ = select.select([primary], [], [], max(0.0, end - time.monotonic())) + if not ready: + break + try: + chunk = os.read(primary, 65536) + except OSError: # EIO: the child closed its end + break + if not chunk: + break + out.append(chunk) + finally: + os.close(primary) + # T228b: the deadline holds past the pty's end. A child that closed + # the pty and lives on, or holds stderr open, is read only until the + # deadline, then killed: no read or wait outlasts it. + errs, fd = [], proc.stderr.fileno() + while time.monotonic() < end: + ready, _, _ = select.select([fd], [], [], max(0.0, end - time.monotonic())) + if not ready: + break + chunk = os.read(fd, 65536) + if not chunk: + break + errs.append(chunk) + if proc.poll() is None: + try: + proc.wait(timeout=max(0.0, end - time.monotonic())) + except subprocess.TimeoutExpired: + proc.kill() + err = b"".join(errs).decode("utf-8", "replace") + proc.stderr.close() + code = proc.wait(timeout=DEADLINE) + return code, b"".join(out).decode("utf-8", "replace").replace("\r\n", "\n"), err + + def make_logins(self, database: str) -> None: + """THE FIXTURE'S LOGINS (T228; section 3.1, "The fixture's logins"), + once per cluster, after the bootstrap: `lanes-index login add fx`, + then `login add --dump-job`, each through the admin service on + `database` and under a pty (lane 1's T110, L1-A8). They make + `lanes_w_fx` in REGISTER-WRITER and `lanes_r_fx` in READER, each with + its own floors, and `lanes_register_dump` in READER, each with a + SCRAM verifier lane 1's code computes. The passwords each prints + once are kept for `passfile()`: the socket's trust ignores them, a + TLS cluster's SCRAM does not. No error text here holds one.""" + service = self.admin_service(database) + for argv in (["login", "add", FX_ENGINEER, "--admin-service", service], + ["login", "add", "--dump-job", "--admin-service", service]): + code, out, err = self.lanes_index_tty(argv) + if code != 0: + raise ClusterError(f"`lanes-index {' '.join(argv[:3])}` through the admin service " + f"on {database} exited {code}, so the fixture has no logins " + f"(lane 1's T110, L1-A8, builds `login`): " + f"{_masked(out)[-400:]} | {_masked(err)[-400:]}") + self.passwords.update(PASSWORD_LINE.findall(out)) + names = ", ".join(f"'{login}'" for login in FX_LOGINS) + can = self.psql(f"SELECT rolname FROM pg_catalog.pg_roles WHERE rolcanlogin AND " + f"rolname IN ({names}) ORDER BY 1;").stdout.split() + missing = sorted(set(FX_LOGINS) - set(can)) + sorted(set(FX_LOGINS) - set(self.passwords)) + if missing: + raise ClusterError(f"after `login add`, these logins cannot log in or printed no " + f"password line: {', '.join(missing)}") + + def passfile(self, login: str) -> Path: + """A 0600 libpq password file holding `login`'s line at any host, + port and database, in the cluster's private `secrets` directory: + what a `register_passfile=` or `reader_passfile=` names.""" + if login not in self.passwords: + raise ClusterError(f"no password for {login}: only the fixture's logins have one") + secrets = self.root / "secrets" + secrets.mkdir(mode=0o700, exist_ok=True) + path = secrets / f"{login}.pgpass" + path.write_text(f"*:*:*:{login}:{self.passwords[login]}\n", encoding="utf-8") + path.chmod(0o600) + return path + + def bootstrap(self, database: str, label: str) -> str: + """P8's bootstrap on `database`, through the admin service, with + `--no-passwords`: the roles are global, so a second run on a cluster + finds them `unchanged`. Its output, which holds no secret.""" + proc = self.lanes_index(["bootstrap", "--admin-service", self.admin_service(database), + "--label", label, "--repository", FX_REPOSITORY, + "--lane", FX_LANE, "--no-passwords"]) + if proc.returncode != 0: + raise ClusterError(f"`lanes-index bootstrap --no-passwords` through the admin " + f"service on {database} exited {proc.returncode}, so the " + f"template has no register (lane 1's T109, L1-A7, builds the " + f"bootstrap): {_tail(proc)}") + return proc.stdout + + def build_imported(self) -> None: + """`tmpl_imported` (T227b): a clone of `tmpl`, with section 1.4's two + statements, into which test 7's fixture register is imported by + `lanes-index import --at ` as the operator lane runs it (lane 1's + T115): from an `ImportedRegister` of the cluster's own, through the + operator lane's checkout (`LANES_REPO`, never W), with the switch at + `files` and the marker `absent`, as the writer login `lanes_w_fx` on + the cluster's socket (the superuser where the template has no + logins). Then seq 0 must be the one `import` entry, at C, with the + switch unchanged, and the database is closed to connections. Where + any step fails, there is no `tmpl_imported`, and `imported_problem` + says why: the session goes on, and only the cases that clone it + fail.""" + register, user = None, (FX_WRITER if FX_WRITER in self.passwords else SUPERUSER) + if self.label is None: + self.imported_problem = "tmpl was not built by the bootstrap, so it holds no register" + else: + self.psql(f"CREATE DATABASE {IMPORTED} TEMPLATE {TEMPLATE};") + self.psql(DATABASE_LEVEL, variables={"db": IMPORTED}) + try: + register = ImportedRegister(self.root / "imported", self.bindir) + proc = register.import_at(self, IMPORTED, user) + if proc.returncode != 0: + self.imported_problem = (f"`lanes-index import --at {register.c}` as {user} " + f"exited {proc.returncode} (lane 1's T115, L1-A13, " + f"builds it): {_tail(proc)}") + else: + self.imported_problem = self._imported_check(register.c) + except (ClusterError, OSError, subprocess.SubprocessError) as exc: + self.imported_problem = f"test 7's fixture register was not built: {exc}"[:1200] + if self.imported_problem is not None: + self.drop_database(IMPORTED) + if self.imported_problem is not None: + _IMPORTED.append(self.imported_problem) + return + self.imported_register = register + _IMPORTED_AT.append(f"test 7's register at {register.c}, by `lanes-index import --at` " + f"as {user}") + self.psql(f"ALTER DATABASE {IMPORTED} WITH IS_TEMPLATE true ALLOW_CONNECTIONS false;") + + def _imported_check(self, commit: str) -> Optional[str]: + """What the clones of `tmpl_imported` rest on (AT-LR006's route, AT-7's + "Success"): one journal entry, seq 0, an `import` at `commit`; the + head at 0; the switch at `files` with the marker `absent`. None, or + what differs.""" + said = self.psql( + "SELECT concat_ws('|', (SELECT string_agg(seq || ':' || kind || ':' || " + "coalesce(git_commit, '-'), ',' ORDER BY seq) FROM lanes_register.journal), " + "(SELECT seq::text FROM lanes_register.register_head), " + "(SELECT mode || ':' || marker_state FROM lanes_register.register_switch));", + dbname=IMPORTED).stdout.strip() + wanted = f"0:import:{commit}|0|files:absent" + if said != wanted: + return (f"`lanes-index import --at {commit}` exited 0, and {IMPORTED} reads " + f"{said!r} (journal|head|switch), not {wanted!r}") + return None + def launch(self) -> None: """`postgres` by `Popen` on this cluster's directories, and wait until it is ready.""" argv = [self.tool("postgres"), "-D", str(self.root / "data"), "-p", str(PORT), @@ -453,10 +783,23 @@ def start_again(self) -> None: raise ClusterError("the cluster is running, so it cannot be started again") self.launch() - def new_database(self) -> str: + def new_database(self, template: str = TEMPLATE) -> str: + """`CREATE DATABASE t_ TEMPLATE