|
| 1 | +""" |
| 2 | + Usage: |
| 3 | + [pytest] |
| 4 | + log_cli = true |
| 5 | + log_cli_level = 25 |
| 6 | +
|
| 7 | + or, without touching pytest config at all, by pointing the |
| 8 | + ``PG_PROBACKUP_CMD_LOG`` environment variable at a file -- every executed |
| 9 | + command is then appended there as a bare, copy-paste-into-a-shell line. |
| 10 | +""" |
| 11 | + |
| 12 | +import functools |
| 13 | +import logging |
| 14 | +import os |
| 15 | + |
| 16 | +# Dedicated level for command echoing. Sits between INFO (20) and WARNING (30): |
| 17 | +# more prominent than ordinary INFO chatter, but it is not a warning. |
| 18 | +COMMAND = 25 |
| 19 | +COMMAND_LEVEL_NAME = 'COMMAND' |
| 20 | +logging.addLevelName(COMMAND, COMMAND_LEVEL_NAME) |
| 21 | + |
| 22 | +cmd_logger = logging.getLogger('pg_probackup2.commands') |
| 23 | + |
| 24 | + |
| 25 | +def _command(self, message, *args, **kwargs): |
| 26 | + if self.isEnabledFor(COMMAND): |
| 27 | + self._log(COMMAND, message, args, **kwargs) |
| 28 | + |
| 29 | + |
| 30 | +# Convenience method: ``logging.getLogger(...).command("...")``. |
| 31 | +logging.Logger.command = _command |
| 32 | + |
| 33 | +_FILE_HANDLER_INSTALLED = False |
| 34 | +_TESTGRES_PATCHED = False |
| 35 | + |
| 36 | + |
| 37 | +def _maybe_add_file_handler(): |
| 38 | + """Attach a file handler to the command logger if PG_PROBACKUP_CMD_LOG is set.""" |
| 39 | + global _FILE_HANDLER_INSTALLED |
| 40 | + if _FILE_HANDLER_INSTALLED: |
| 41 | + return |
| 42 | + _FILE_HANDLER_INSTALLED = True |
| 43 | + |
| 44 | + path = os.environ.get('PG_PROBACKUP_CMD_LOG') |
| 45 | + if not path: |
| 46 | + return |
| 47 | + handler = logging.FileHandler(path) |
| 48 | + handler.setLevel(COMMAND) |
| 49 | + # bare command line, one per row -- ready to paste into a shell script |
| 50 | + handler.setFormatter(logging.Formatter('%(message)s')) |
| 51 | + cmd_logger.addHandler(handler) |
| 52 | + # make sure the dedicated logger lets COMMAND records reach the handler even |
| 53 | + # if the root logger is configured at a higher level |
| 54 | + if cmd_logger.level == logging.NOTSET or cmd_logger.level > COMMAND: |
| 55 | + cmd_logger.setLevel(COMMAND) |
| 56 | + |
| 57 | + |
| 58 | +def log_command(cmd, to_stdout=True): |
| 59 | + """Echo a command that is about to be (or has just been) executed. |
| 60 | +
|
| 61 | + Args: |
| 62 | + cmd: the command, either a list/tuple of arguments or an already |
| 63 | + assembled string. |
| 64 | + to_stdout: also ``print()`` to stdout (default True) so the command is |
| 65 | + visible in pytest's "Captured stdout call" section on failure. |
| 66 | + """ |
| 67 | + _maybe_add_file_handler() |
| 68 | + |
| 69 | + if isinstance(cmd, (list, tuple)): |
| 70 | + line = ' '.join(map(str, cmd)) |
| 71 | + else: |
| 72 | + line = str(cmd) |
| 73 | + |
| 74 | + if to_stdout: |
| 75 | + # historical 2.5.11 format: a single-element list, e.g. ['pg_probackup ...'] |
| 76 | + print([line]) |
| 77 | + |
| 78 | + # bare line for handlers/files (grep- and copy-paste-friendly) |
| 79 | + cmd_logger.command('%s', line) |
| 80 | + |
| 81 | + |
| 82 | +def patch_testgres_command_logging(): |
| 83 | + """Echo testgres utility invocations (pg_ctl, initdb, pg_basebackup, ...) too. |
| 84 | +
|
| 85 | + testgres routes every external utility through ``utils.execute_utility2``. |
| 86 | + Several submodules (``node``, ``cache``, ``backup``, ...) grab their own |
| 87 | + reference at import time via ``from .utils import execute_utility2``, so it |
| 88 | + is not enough to replace the function in ``utils``. We therefore: |
| 89 | +
|
| 90 | + 1. replace it in ``testgres.utils`` (so any *later* ``from .utils import`` |
| 91 | + picks up the wrapper), and |
| 92 | + 2. sweep every already-loaded ``testgres.*`` module and replace its |
| 93 | + ``execute_utility2`` attribute when it still points at the original. |
| 94 | +
|
| 95 | + The wrapper only adds an echo and otherwise delegates unchanged, so it is |
| 96 | + safe across testgres versions; any failure to patch is non-fatal. |
| 97 | + """ |
| 98 | + global _TESTGRES_PATCHED |
| 99 | + if _TESTGRES_PATCHED: |
| 100 | + return |
| 101 | + _TESTGRES_PATCHED = True |
| 102 | + |
| 103 | + try: |
| 104 | + import sys |
| 105 | + import testgres.utils as tg_utils |
| 106 | + except Exception as e: # testgres missing/broken -- nothing to patch |
| 107 | + logging.getLogger(__name__).debug( |
| 108 | + "Could not patch testgres for command logging: %s", e) |
| 109 | + return |
| 110 | + |
| 111 | + original = getattr(tg_utils, 'execute_utility2', None) |
| 112 | + if original is None or getattr(original, '_pb2_logging_wrapper', False): |
| 113 | + return |
| 114 | + |
| 115 | + @functools.wraps(original) |
| 116 | + def wrapper(os_ops, args, *a, **kw): |
| 117 | + try: |
| 118 | + log_command(args) |
| 119 | + except Exception: |
| 120 | + # echoing must never break the actual command execution |
| 121 | + pass |
| 122 | + return original(os_ops, args, *a, **kw) |
| 123 | + |
| 124 | + wrapper._pb2_logging_wrapper = True |
| 125 | + |
| 126 | + # 1) the source module (covers future ``from .utils import execute_utility2``) |
| 127 | + tg_utils.execute_utility2 = wrapper |
| 128 | + |
| 129 | + # 2) every already-imported testgres submodule that copied the reference |
| 130 | + for name, module in list(sys.modules.items()): |
| 131 | + if module is None or not name.startswith('testgres'): |
| 132 | + continue |
| 133 | + try: |
| 134 | + if getattr(module, 'execute_utility2', None) is original: |
| 135 | + module.execute_utility2 = wrapper |
| 136 | + except Exception: |
| 137 | + pass |
0 commit comments