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