1
0
mirror of https://github.com/pgbackrest/pgbackrest.git synced 2026-10-23 21:28:56 +03:00
Files
pgbackrest/test/lib/common/exec.py
David Steele 59bd2cd96c Migrate the build and documentation code from C to Python.
The build tool in src/build becomes build/build.py with its library in build/lib, and the C part of the documentation tool in doc/src becomes doc/doc.py with its library in doc/lib. They migrate together because doc/src was built on src/build, linking its config and help parsing along with its extensions to the core types. doc.pl runs doc.py rather than building and running a C binary, and meson runs build.py for the code it generates as it builds.

The three libraries form the hierarchy the C include path did: build/lib is the base, doc/lib sits on it, and test/lib sits on both. They are implicit namespace packages so a package spans them, and a module lives in exactly one library and holds the union of what the tools need from it, since Python resolves a module name to a single file and cannot extend one the way the C included a core module and added to it. define.yaml declares which libraries each tool may import and the test runner puts only those on the path, so a test of the build library cannot reach the doc or test library any more than the build tool can.

The declarations move with the code. config.yaml, error.yaml, and postgres.yaml are now at the root of build, and help.xml becomes doc/xml/reference.xml since it is documentation that the help happens to be generated from, so the generator is told where it is rather than knowing. dist.sh moves to build as well. The documentation tool's own option declarations are gone because they existed only to generate the option parser for the C binary and doc.py parses its command line directly.

Three modules in src/build/common were never build tool code. exec, regExp, and string extend the core types for the test harness and the unit tests, which were their only users, so they move to test/src/harness. The json and xml extensions had no users outside the two tools and are removed with them, and the tests for both are trimmed to the core functions that remain.

The help unit test built its fixture by calling the generator's C functions directly, which was the last thing outside the tools that depended on them. It now runs build.py help-data to write the packed help and loads that, so it still runs against the current declarations without needing the generated C, which may not have been written when the test runs.

The manual page wrapping is a port of the wrapper the binary uses for its own help, so the manual page and pgbackrest help break lines the same way, including where a word longer than a line is left unbroken.

libyaml is no longer needed to build pgBackRest since the only thing that read yaml was the C generator. It is dropped from the development container and from every CI platform, and meson no longer looks for it. Code generation needs nothing compiled first either, so a test run no longer builds a generator before it can select the tests.

The common source list is merged into the pgbackrest source list since it existed only so the generator could be built from the same files, and the entries that were out of alphabetical order are put in order while the list is being rewritten anyway.

Every file the generator writes is byte identical to what the C wrote, for the project declarations and for the documentation's own. The documentation is checked the same way: the HTML rendered on this branch is byte identical to the HTML rendered on integration, every file of it, which exercises the whole pipeline on the real content rather than only the four files the tool writes.

Every module in both libraries is declared in define.yaml and has full line and branch coverage. The coverage list is keyed by file rather than by module name, since the same name in two languages is two files and one of them would have silently lost its requirement while both existed.

TestError becomes ToolError, since it is the error type for three tools now rather than for the harness alone.
2026-07-30 19:37:43 +07:00

135 lines
5.3 KiB
Python

"""Execute Process.
Exec runs a command in the background so several can run at once, which is how the test driver keeps every vm busy. It keeps stdout
and stderr apart because a test that writes anything to stderr has failed whatever its exit status, e.g. a valgrind error.
exec_one() runs a command and waits for it, with stderr folded into the output as execOneExpectP() in test/src/harness/exec.c does.
The combined output is returned on success and carried in the error on failure, since a failed meson or ninja run says what went
wrong there rather than in its exit status."""
####################################################################################################################################
import os
import select
import subprocess
import sys
from common.error import ToolError
####################################################################################################################################
class Exec:
"""Run a command in the background and collect its output."""
def __init__(self, command, show_output=False, merge_error=False):
self.command = command
self.show_output = show_output # Write output as it arrives rather than only keeping it?
self.merge_error = merge_error # Fold stderr into the output rather than keeping it apart?
self.output = ""
self.error = ""
self._process = None
self._fd_out = None
self._fd_list = []
self._show_idx = 0 # How much of the output has been written when show_output is set
################################################################################################################################
def begin(self):
"""Start the command."""
self._process = subprocess.Popen(
["sh", "-c", self.command],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT if self.merge_error else subprocess.PIPE,
)
self._fd_out = self._process.stdout.fileno()
self._fd_list = [self._fd_out] + ([] if self.merge_error else [self._process.stderr.fileno()])
################################################################################################################################
def _show(self):
"""Write the complete lines that have arrived since the last call, indented the way the log indents output."""
idx = self.output.rfind("\n") + 1
if idx > self._show_idx:
for line in self.output[self._show_idx : idx].splitlines():
sys.stdout.write(" %s\n" % line)
sys.stdout.flush()
self._show_idx = idx
################################################################################################################################
def _drain(self, timeout):
"""Read whatever is available on stdout and stderr, dropping a stream when it reaches end of file.
A timeout of zero returns immediately and None waits for data, which is only safe once the command has exited."""
for fd in select.select(self._fd_list, [], [], timeout)[0]:
data = os.read(fd, 65536)
# No data on a ready stream means end of file
if not data:
self._fd_list.remove(fd)
continue
if fd == self._fd_out:
self.output += data.decode(errors="replace")
if self.show_output:
self._show()
else:
self.error += data.decode(errors="replace")
################################################################################################################################
def end(self, wait=True):
"""Return the exit status, or None when the command is still running and wait is not set.
Output is drained while the command runs so a full pipe buffer cannot block it."""
while self._process.poll() is None:
self._drain(0.05 if wait else 0)
if not wait:
return None
# The command is done so read what is left. Waiting for data is safe here since the only writer has exited.
while self._fd_list:
self._drain(None)
self._process.stdout.close()
if not self.merge_error:
self._process.stderr.close()
return self._process.returncode
####################################################################################################################################
def exec_one(command, result_expect=0, show_output=False):
"""Run a command through the shell and return its combined output.
Raise ToolError when the exit status is not the expected one."""
process = Exec(command, show_output=show_output, merge_error=True)
process.begin()
status = process.end()
if status != result_expect:
output = process.output.strip()
raise ToolError("%s terminated unexpectedly [%d]%s%s" % (command, status, ": " if output else "", output))
return process.output
####################################################################################################################################
def exec_status(command):
"""Run a command through the shell and return its exit status, discarding the output.
Used where a command is expected to fail, e.g. pulling an image that is not in the cache."""
process = Exec(command)
process.begin()
return process.end()