diff --git a/tests/conftest.py b/tests/conftest.py index 5c4e3d18..551ae334 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -534,6 +534,15 @@ def pytest_configure(config): raise pytest.UsageError(refusal) if not config.pluginmanager.has_plugin(pgcluster.PLUGIN_NAME): config.pluginmanager.register(pgcluster, pgcluster.PLUGIN_NAME) + # SHORT TRACEBACKS UNLESS ASKED (#165, lane 3's ruling 6949488277 on lane + # 2's pre-review RV9-38 of P09, B1): pytest's default `auto` prints a long + # entry's frame arguments, a helper's raw stream or a statement's password + # among them, in the terminal and in --junitxml. `short` prints none. An + # explicit `--tb` other than `auto` stays as given; `--tb=auto` cannot be + # told from the default, so it becomes short too. `--tb=long`, + # `--fulltrace` (which forces long) and `--showlocals` are not secret-safe. + if config.getoption("tbstyle", "auto") == "auto": + config.option.tbstyle = "short" def pytest_report_header(config): diff --git a/tests/pgcluster.py b/tests/pgcluster.py index 97871b78..4efc76f6 100644 --- a/tests/pgcluster.py +++ b/tests/pgcluster.py @@ -35,7 +35,9 @@ * `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. + data and socket directories; `start_again(standby=True)` starts it in + recovery, with `standby.signal`, and fails unless `pg_is_in_recovery()` + is true, and the next plain start removes the file (T229d). 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` @@ -89,18 +91,26 @@ starts it again on the same directories and runs `SELECT 1`. It exits 0 when each named smoke passes, 1 when one fails or there is no engine, and 2 for a name it does not know. + +PYTEST_DONT_REWRITE (T229s): no assert here is rewritten, whatever hook loads +this plugin, so an assert added later reports its own message and no +operand's value, a tool's text among them. """ from __future__ import annotations import os +import queue import re +import select import shutil import signal +import socket import stat import subprocess import sys import tempfile +import threading import time from pathlib import Path from typing import Dict, List, Optional, Tuple @@ -201,22 +211,32 @@ def required(environ=os.environ) -> bool: # ------------------------------------------------------------ the binaries -def check_bindir(bindir: Path) -> Optional[str]: - """None where `bindir` holds the four tools at major 16, else why not.""" +def check_bindir(bindir: Path, shown: Optional[str] = None) -> Optional[str]: + """None where `bindir` holds the four tools at major 16, else why not. + The reason shows no text a tool printed (T229o; lane 3's ruling + 6949488277 on lane 2's pre-review RV9-38 of P09, B2): a `--version` + that does not say major 16 is shown by its exit and counts, and + `shown` names the directory in place of its path where that path is a + tool's output, `pg_config --bindir`'s.""" + where = str(bindir) if shown is None else shown if not bindir.is_dir(): - return f"{bindir} is not a directory" + return f"{where} is not a directory" missing = [t for t in TOOLS if not os.access(str(bindir / t), os.X_OK) or (bindir / t).is_dir()] if missing: - return f"{bindir} has no {', '.join(missing)}" + return f"{where} has no {', '.join(missing)}" for tool in TOOLS: + label = str(bindir / tool) if shown is None else f"{shown}'s {tool}" try: - said = subprocess.run([str(bindir / tool), "--version"], stdin=DEVNULL, capture_output=True, - text=True, timeout=20, check=False).stdout.strip() + ran = subprocess.run([str(bindir / tool), "--version"], stdin=DEVNULL, capture_output=True, + text=True, timeout=20, check=False) except (OSError, subprocess.SubprocessError) as exc: - said = f"<{exc}>" - m = re.search(r"\(PostgreSQL\) (\d+)", said) + return f"{label} --version did not run: {type(exc).__name__}" + version = ran.stdout or "" + m = re.search(r"\(PostgreSQL\) (\d+)", version) if not m or int(m.group(1)) != MAJOR: - return f"{bindir / tool} is not PostgreSQL {MAJOR}: it says {said!r}" + return (f"{label} is not PostgreSQL {MAJOR}: its --version exited {ran.returncode} " + f"and names {'another major' if m else 'no PostgreSQL major'}; " + f"{len(version.splitlines())} line(s), none shown") return None @@ -231,14 +251,15 @@ def find_bindir(environ=os.environ) -> Tuple[Optional[Path], str]: pg_config = shutil.which("pg_config", path=environ.get("PATH", os.defpath)) if pg_config: try: - out = subprocess.run([pg_config, "--bindir"], stdin=DEVNULL, capture_output=True, - text=True, timeout=20, check=False).stdout.strip() - except (OSError, subprocess.SubprocessError): - out = "" - why = check_bindir(Path(out)) if out else "it printed nothing" + ran = subprocess.run([pg_config, "--bindir"], stdin=DEVNULL, capture_output=True, + text=True, timeout=20, check=False) + out, how = (ran.stdout or "").strip(), f"exited {ran.returncode}" + except (OSError, subprocess.SubprocessError) as exc: + out, how = "", f"did not run ({type(exc).__name__})" + why = check_bindir(Path(out), shown="the directory it printed") if out else "it printed nothing" if why is None: return Path(out), f"`{pg_config} --bindir`" - tried.append(f"`{pg_config} --bindir` says {out or '-'}, and {why}") + tried.append(f"`{pg_config} --bindir` {how}, and {why}") else: tried.append("no pg_config on PATH") why = check_bindir(DEBIAN_BIN) @@ -402,7 +423,15 @@ def sweep_stale() -> List[str]: class ClusterError(Exception): - pass + """A cluster's failure. Its text shows exits and counts, never a line of + a tool's output or of the server's log (T229k; T229l). `could_not_bind` + is True where a start failed and the server log's last five lines name + `bind` (T229l): what `TLSCluster.launch` read in the text before, kept as + a flag, not as text.""" + + def __init__(self, *args, could_not_bind: bool = False) -> None: + super().__init__(*args) + self.could_not_bind = could_not_bind class Bootstrap: @@ -423,16 +452,71 @@ def _masked(text: str) -> str: 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: +def _counted(proc) -> str: + """What a failure message here shows of a tool's run (T229m; lane 3's + ruling 6949488277 on lane 2's pre-review RV9-38 of P09, B2): its exit + and each stream's count of lines. No line of either is shown: initdb's, + git's, openssl's, psql's and lanes-index's own text can echo a + statement, a password-file line, a path or a server's message.""" + parts = [f"exit {proc.returncode}"] + for name in ("stdout", "stderr"): + said = getattr(proc, name, None) + if isinstance(said, bytes): + said = said.decode("utf-8", "replace") + parts.append(f"{name}: {len(said.splitlines()) if isinstance(said, str) else 0} line(s)") + return "; ".join(parts) + "; no line of either is shown" + + +#: An error line of psql's stderr, after psql's own `psql::1: ` where +#: it is there, and its SQLSTATE where psql prints one (`ERROR: 42P01: ...`, +#: at `VERBOSITY` verbose; at the default, psql prints none). The SQLSTATE is +#: taken only from that form on one line (T229p; lane 2's pre-review RV9-38 of +#: P09, N1): `ERROR:`, spaces or tabs, never a newline, then five of +#: `[0-9A-Z]` with a digit among them, as every SQLSTATE of PostgreSQL's and +#: of the product's has, then `:`. So no five-capital word, such as `SYNTH:`, +#: nor the head of a line after an `ERROR:` that ends its own, is shown as one +#: (T229w). Its limit (T229r): at psql's default verbosity, a message +#: whose first word is five of `[0-9A-Z]` with a digit and a colon would be +#: shown as a SQLSTATE. PostgreSQL's primary messages begin in lower case, and +#: psql's echo of a statement is a `LINE n:` line, which never matches. +_PSQL_ERROR = re.compile(r"^(?:psql:\S*: )?(?:ERROR|FATAL|PANIC):", re.M) +_SQLSTATE = re.compile(r"^(?:psql:\S*: )?(?:ERROR|FATAL|PANIC):[ \t]+(?=[A-Z]{0,4}[0-9])([0-9A-Z]{5}):", + re.M) +#: A line of the server's log at ERROR, FATAL or PANIC (T229l; anchored by +#: T229v, lane 2's pre-review RV9-41 of P09, N3): at the line's start, after +#: one of the fixture's own `log_line_prefix` forms where it is there, the +#: severity as the server writes it, then `:` and two spaces. The forms are +#: the default, `%m [%p] ` (its time's three words and the pid in +#: brackets), and `%p ` (the pid and a space), which managed sets on its +#: clusters (T229x; lane 2's targeted check RV9-43 of P09 at `94a40564`, NIT +#: C). So a logged statement whose text holds `ERROR:` is not counted; a +#: continuation line of a logged statement that itself begins `ERROR: ` +#: would be. It is a count only: no line is shown. +_LOG_SEVERE = re.compile(r"^(?:\S+ \S+ \S+ \[\d+\] |\d+ )?(?:ERROR|FATAL|PANIC): ") + + +def _psql_failed(user: str, dbname: str, proc: subprocess.CompletedProcess) -> str: + """What `Cluster.psql`'s `ClusterError` says when psql fails (T229k; + lane 3's ruling 6947252648 on lane 2's pre-review RV9-37 of P09 at + `d9a1f2bf`, S4): psql's exit, the SQLSTATE where its text has one, and + its stderr's counts. No line of psql's text is shown, since psql echoes + a failed statement (`LINE 1: ...`), and a role's statement can hold its + password. Nothing of the text is kept on the exception: no caller needs + it (CX-36's scan of every caller on `main` and at P09's head).""" + text = proc.stderr if isinstance(proc.stderr, str) else "" + lines = text.splitlines() + states = sorted(set(_SQLSTATE.findall(text))) + errors = len(_PSQL_ERROR.findall(text)) + return (f"psql as {user} on {dbname} exited {proc.returncode}: " + f"{'SQLSTATE ' + ', '.join(states) if states else 'no SQLSTATE in its text'}; " + f"stderr: {len(lines)} line(s), {errors} of them ERROR, FATAL or PANIC lines; " + f"no line of it is shown") + + +def _client_env(host: Path, user: str, dbname: str, appname: str, bindir: Path, + port: int = PORT) -> dict: env = _without_pg() - env.update(PGHOST=str(host), PGPORT=str(PORT), PGUSER=user, PGDATABASE=dbname, + env.update(PGHOST=str(host), PGPORT=str(port), PGUSER=user, PGDATABASE=dbname, PGAPPNAME=appname, PGCONNECT_TIMEOUT="10", LC_ALL="C", PATH=_engine_first(bindir, env.get("PATH", os.defpath))) return env @@ -459,6 +543,9 @@ def __init__(self, bindir: Path, template_sql="", imported: bool = False) -> Non for an empty `tmpl` (the smokes' default). `imported` builds `tmpl_imported` too.""" self.bindir, self.template_sql, self.imported = bindir, template_sql, imported + #: The port (T229): it names the socket file, and a TLS cluster's TCP + #: listener uses it too. `listen` and `settings` are `prepare()`'s. + self.port, self.listen, self.settings = PORT, "", [] self.root: Optional[Path] = None self.proc: Optional[subprocess.Popen] = None self.count, self.timings = 0, {} @@ -489,17 +576,48 @@ def psql(self, sql: str, dbname: str = "postgres", user: str = SUPERUSER, 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), + self.bindir, self.port), check=False) if check and proc.returncode != 0: - raise ClusterError(f"psql as {user} on {dbname} exited {proc.returncode}: {proc.stderr.strip()}") + # T229q (lane 2's pre-review RV9-38 of P09, N2): the message is + # made, then psql's run is dropped, so no stream of it stays in + # this frame, which the raise's traceback keeps (`--showlocals`). + failed = _psql_failed(user, dbname, proc) + del proc + raise ClusterError(failed) return proc def log_tail(self) -> str: + """What a failure message shows of the server's log (T229l; lane 3's + ruling 6949488277 on lane 2's pre-review RV9-38 of P09, B2): its + count of lines and of ERROR, FATAL or PANIC lines. No line of it is + shown: under `log_statement = 'all'` a role's statement, its + password among it, is a line of it.""" try: - return " | ".join((self.root / "server.log").read_text().splitlines()[-5:]) + lines = (self.root / "server.log").read_text(errors="replace").splitlines() except OSError: - return "" + return "server.log: not read" + severe = sum(1 for line in lines if _LOG_SEVERE.search(line)) + return (f"server.log: {len(lines)} line(s), {severe} of them ERROR, FATAL or PANIC " + f"lines; no line of it is shown") + + def _could_not_bind(self) -> bool: + """Whether the server log's last five lines name `bind`, in any case + (T229l): what `TLSCluster.launch` looked for in a failed start's text + when that text held those lines.""" + try: + last = (self.root / "server.log").read_text(errors="replace").splitlines()[-5:] + except OSError: + return False + return any("bind" in line.lower() for line in last) + + def _start_failed(self, what: str) -> ClusterError: + """A failed start's error: `what`, the log's counts, and whether its + last lines name a bind, as words and as `could_not_bind` (T229l).""" + bind = self._could_not_bind() + return ClusterError(f"{what}: {self.log_tail()}" + f"{'; its last 5 lines name a bind' if bind else ''}", + could_not_bind=bind) def ready(self) -> bool: """The postmaster's own `ready` status, line 8 of postmaster.pid: what pg_ctl -w reads.""" @@ -515,7 +633,7 @@ def start(self) -> None: _SWEPT.extend(sweep_stale()) self.root = Path(tempfile.mkdtemp(prefix=PREFIX, dir=SOCKET_PARENT)) # mode 0700 (self.root / "owner").write_text(f"{os.getpid()} {_ticks(os.getpid())}\n") - sock = self.root / f".s.PGSQL.{PORT}" + sock = self.root / f".s.PGSQL.{self.port}" if len(os.fsencode(str(sock))) > SOCKET_MAX: raise ClusterError(f"the socket path {sock} is over {SOCKET_MAX} bytes") t1 = time.monotonic() @@ -524,8 +642,9 @@ def start(self) -> None: capture_output=True, text=True, env=self.server_env(), timeout=120, check=False) if init.returncode != 0: - raise ClusterError(f"initdb exited {init.returncode}: {init.stderr.strip()}") + raise ClusterError(f"initdb failed: {_counted(init)}") t2 = time.monotonic() + self.prepare() self.launch() t3 = time.monotonic() self.build_template() @@ -570,7 +689,7 @@ def admin_service(self, database: str) -> str: 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" + text += (f"[{name}]\nhost={self.root}\nport={self.port}\nuser={SUPERUSER}\n" f"dbname={database}\n\n") path.write_text(text, encoding="utf-8") path.chmod(0o600) @@ -652,15 +771,23 @@ def make_logins(self, database: str) -> None: ["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:]}") + failed = (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`): stdout: " + f"{len(out.splitlines())} line(s), " + f"{len(PASSWORD_LINE.findall(out))} of them password-file " + f"lines; stderr: {len(err.splitlines())} line(s); no line of " + f"either is shown") + del out, err + raise ClusterError(failed) self.passwords.update(PASSWORD_LINE.findall(out)) + # T229u (RV9-41, N1): `login add`'s output, its password-file lines + # with their clear passwords, stays in no frame a later raise keeps. + del out, err 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)) + missing = [login for login in FX_LOGINS if login not in can or login not in self.passwords] if missing: raise ClusterError(f"after `login add`, these logins cannot log in or printed no " f"password line: {', '.join(missing)}") @@ -689,7 +816,7 @@ def bootstrap(self, database: str, label: str) -> str: 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)}") + f"bootstrap): {_counted(proc)}") return proc.stdout def build_imported(self) -> None: @@ -717,7 +844,7 @@ def build_imported(self) -> None: 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)}") + f"builds it): {_counted(proc)}") else: self.imported_problem = self._imported_check(register.c) except (ClusterError, OSError, subprocess.SubprocessError) as exc: @@ -745,15 +872,23 @@ def _imported_check(self, commit: str) -> Optional[str]: 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}") + got = said.split("|") + differ = [part for i, part in enumerate(("journal", "head", "switch")) + if len(got) != 3 or got[i] != wanted.split("|")[i]] + return (f"`lanes-index import --at {commit}` exited 0, and {IMPORTED}'s " + f"{', '.join(differ)} differ from {wanted!r} (journal|head|switch); none " + f"of what it reads is shown (T229n)") return None + def prepare(self) -> None: + """Between `initdb` and the first start: nothing here; T229's TLS and + counting clusters set their files and settings.""" + 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), - "-c", "listen_addresses=", "-c", f"unix_socket_directories={self.root}"] - for setting in FAST: + argv = [self.tool("postgres"), "-D", str(self.root / "data"), "-p", str(self.port), + "-c", f"listen_addresses={self.listen}", "-c", f"unix_socket_directories={self.root}"] + for setting in [*FAST, *self.settings]: argv += ["-c", setting] with open(self.root / "server.log", "ab") as log: self.proc = subprocess.Popen(argv, stdin=DEVNULL, stdout=log, stderr=subprocess.STDOUT, @@ -761,9 +896,9 @@ def launch(self) -> None: end = time.monotonic() + DEADLINE while not self.ready(): if self.proc.poll() is not None: - raise ClusterError(f"postgres exited {self.proc.returncode} starting: {self.log_tail()}") + raise self._start_failed(f"postgres exited {self.proc.returncode} starting") if time.monotonic() > end: - raise ClusterError(f"postgres was not ready in {DEADLINE:.0f} s: {self.log_tail()}") + raise self._start_failed(f"postgres was not ready in {DEADLINE:.0f} s") time.sleep(POLL) def stop(self) -> None: @@ -777,11 +912,34 @@ def stop(self) -> None: raise ClusterError(f"postgres did not stop in {DEADLINE:.0f} s after SIGINT: " f"{self.log_tail()}") from None - def start_again(self) -> None: - """Start the stopped cluster on the same data and socket directories.""" + def start_again(self, standby: bool = False) -> None: + """Start the stopped cluster on the same data and socket directories. + With `standby` (T229d; TP:5382-5387, check 11's restart in recovery; + lane 3's batch 11 (1), which corrects batch 7's ruling 2), it starts + in recovery: `standby.signal` is written in the data directory, the + start polls `postmaster.pid` for `ready`, as every start does, and + then fails unless `pg_is_in_recovery()` is true. A hot standby writes + `ready`, never `standby`: PostgreSQL 16 writes `standby` only with + `hot_standby` off, where no session connects, and a plain start + writes `ready` too, so only the query proves the recovery. A start + without it removes the file first, so the cluster comes back a + primary. T224 only calls it.""" if self.proc is not None and self.proc.poll() is None: raise ClusterError("the cluster is running, so it cannot be started again") + signal_file = self.root / "data" / "standby.signal" + if standby: + signal_file.write_text("", encoding="utf-8") + elif signal_file.exists(): + signal_file.unlink() self.launch() + if standby: + answer = self.psql("SELECT pg_is_in_recovery();", check=False) + if answer.returncode != 0 or answer.stdout.strip() != "t": + said = (_psql_failed(SUPERUSER, "postgres", answer) if answer.returncode != 0 else + "f" if answer.stdout.strip() == "f" else + f"neither t nor f: {len(answer.stdout.splitlines())} line(s), none shown") + raise ClusterError(f"the start with standby.signal is ready but not in recovery: " + f"pg_is_in_recovery() answered {said}: {self.log_tail()}") def new_database(self, template: str = TEMPLATE) -> str: """`CREATE DATABASE t_ TEMPLATE