|
| 1 | +""" |
| 2 | +Utility classes to run external tools |
| 3 | +""" |
| 4 | + |
| 5 | +import base64 |
| 6 | +import json |
| 7 | +import logging |
| 8 | +import subprocess |
| 9 | +import tempfile |
| 10 | +from os import PathLike |
| 11 | +from pathlib import Path |
| 12 | +from typing import Mapping, Optional, Sequence, TypeAlias |
| 13 | + |
| 14 | +LOGGER = logging.getLogger("operator-cert") |
| 15 | + |
| 16 | + |
| 17 | +CommandArg: TypeAlias = str | PathLike[str] |
| 18 | + |
| 19 | + |
| 20 | +class Secret(str): |
| 21 | + """ |
| 22 | + A string with sensitive content that should not be logged |
| 23 | + """ |
| 24 | + |
| 25 | + |
| 26 | +def run( |
| 27 | + *cmd: CommandArg, |
| 28 | + cwd: Optional[CommandArg] = None, |
| 29 | + env: Optional[Mapping[str, str]] = None, |
| 30 | +) -> None: |
| 31 | + """ |
| 32 | + Execute an external command |
| 33 | +
|
| 34 | + Args: |
| 35 | + *cmd: The command and its arguments |
| 36 | + cwd: Directory to run the command in, by default current working directory |
| 37 | + env: Environment variables, if None the current environment is used |
| 38 | +
|
| 39 | + Raises: |
| 40 | + subprocess.CalledProcessError when the called process exits with a |
| 41 | + non-zero status; the process' stdout and stderr can be obtained |
| 42 | + from the exception object |
| 43 | + """ |
| 44 | + LOGGER.debug("Running %s from %s", cmd, cwd or Path.cwd()) |
| 45 | + subprocess.run( |
| 46 | + cmd, |
| 47 | + stdout=subprocess.PIPE, |
| 48 | + stderr=subprocess.STDOUT, |
| 49 | + check=True, |
| 50 | + cwd=cwd, |
| 51 | + env=env, |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +class Ansible: |
| 56 | + """ |
| 57 | + Utility class to interact with Ansible |
| 58 | + """ |
| 59 | + |
| 60 | + def __init__(self, path: Optional[Path]) -> None: |
| 61 | + """ |
| 62 | + Initialize the Ansible instance |
| 63 | +
|
| 64 | + Args: |
| 65 | + path: The working directory for the ansible commands; |
| 66 | + It must contain an ansible.cfg file |
| 67 | + """ |
| 68 | + self.path = (path or Path.cwd()).absolute() |
| 69 | + # Simple sanity check to ensure the directory actually contains |
| 70 | + # a copy of the operator-pipelines project |
| 71 | + ansible_cfg_file = self.path / "ansible.cfg" |
| 72 | + if not ansible_cfg_file.exists(): |
| 73 | + raise FileNotFoundError(f"ansible.cfg not found in {self.path}") |
| 74 | + |
| 75 | + def playbook_path(self, playbook_name: str) -> Path: |
| 76 | + """ |
| 77 | + Return the path to the playbook file with the given name; this is specific |
| 78 | + to the operator-pipelines project |
| 79 | + """ |
| 80 | + playbook_dir = self.path / "ansible" / "playbooks" |
| 81 | + for ext in ("yml", "yaml"): |
| 82 | + playbook_path = playbook_dir / f"{playbook_name}.{ext}" |
| 83 | + if playbook_path.exists(): |
| 84 | + return playbook_path |
| 85 | + raise FileNotFoundError(f"Playbook {playbook_name} not found in {playbook_dir}") |
| 86 | + |
| 87 | + def run_playbook( |
| 88 | + self, playbook: str, *extra_args: CommandArg, **extra_vars: str | Secret |
| 89 | + ) -> None: |
| 90 | + """ |
| 91 | + Run an ansible playbook |
| 92 | +
|
| 93 | + Args: |
| 94 | + playbook: The name of the playbook to execute |
| 95 | + *extra_args: Additional arguments for the ansible playbook |
| 96 | + **extra_vars: Extra variables to pass to the playbook |
| 97 | + """ |
| 98 | + command: list[CommandArg] = ["ansible-playbook", self.playbook_path(playbook)] |
| 99 | + command.extend(extra_args) |
| 100 | + secrets = {} |
| 101 | + for k, v in extra_vars.items(): |
| 102 | + if isinstance(v, Secret): |
| 103 | + # Avoid adding secrets to the command line |
| 104 | + secrets[k] = str(v) |
| 105 | + else: |
| 106 | + command.extend(["-e", f"{k}={v}"]) |
| 107 | + with tempfile.NamedTemporaryFile( |
| 108 | + mode="w", |
| 109 | + encoding="utf-8", |
| 110 | + suffix=".json", |
| 111 | + delete=True, |
| 112 | + delete_on_close=False, |
| 113 | + ) as tmp: |
| 114 | + if secrets: |
| 115 | + json.dump(secrets, tmp) |
| 116 | + command.extend(["-e", f"@{tmp.name}"]) |
| 117 | + tmp.close() |
| 118 | + run(*command, cwd=self.path) |
| 119 | + |
| 120 | + |
| 121 | +class Podman: |
| 122 | + """ |
| 123 | + Utility class to interact with Podman. |
| 124 | + """ |
| 125 | + |
| 126 | + def __init__(self, auth: Optional[Mapping[str, tuple[str, str]]] = None): |
| 127 | + """ |
| 128 | + Initialize the Podman instance |
| 129 | +
|
| 130 | + Args: |
| 131 | + auth: The authentication credentials for registries |
| 132 | + """ |
| 133 | + self._auth = { |
| 134 | + "auths": { |
| 135 | + registry: { |
| 136 | + "auth": base64.b64encode( |
| 137 | + f"{username}:{password}".encode("utf-8") |
| 138 | + ).decode("ascii") |
| 139 | + } |
| 140 | + for registry, (username, password) in (auth or {}).items() |
| 141 | + if username and password |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + def _run(self, *args: CommandArg) -> None: |
| 146 | + """ |
| 147 | + Run a podman subcommand |
| 148 | +
|
| 149 | + Args: |
| 150 | + *args: The podman subcommand and its arguments |
| 151 | + """ |
| 152 | + command: list[CommandArg] = ["podman"] |
| 153 | + command.extend(args) |
| 154 | + with tempfile.NamedTemporaryFile( |
| 155 | + mode="w", |
| 156 | + encoding="utf-8", |
| 157 | + suffix=".json", |
| 158 | + delete=True, |
| 159 | + delete_on_close=False, |
| 160 | + ) as tmp: |
| 161 | + json.dump(self._auth, tmp) |
| 162 | + tmp.close() |
| 163 | + LOGGER.debug("Using podman auth file: %s", tmp.name) |
| 164 | + run(*command, env={"REGISTRY_AUTH_FILE": tmp.name}) |
| 165 | + |
| 166 | + def build( |
| 167 | + self, |
| 168 | + context: CommandArg, |
| 169 | + image: str, |
| 170 | + containerfile: Optional[CommandArg] = None, |
| 171 | + extra_args: Optional[Sequence[CommandArg]] = None, |
| 172 | + ) -> None: |
| 173 | + """ |
| 174 | + Build an image |
| 175 | +
|
| 176 | + Args: |
| 177 | + context: Directory to build the image from |
| 178 | + image: The name of the image to build |
| 179 | + containerfile: The path to the container configuration file, |
| 180 | + if not specified it will be inferred by podman |
| 181 | + extra_args: Additional arguments for the podman build command |
| 182 | + """ |
| 183 | + command: list[CommandArg] = ["build", "-t", image, context] |
| 184 | + if containerfile: |
| 185 | + command.extend(["-f", containerfile]) |
| 186 | + if extra_args: |
| 187 | + command.extend(extra_args) |
| 188 | + self._run(*command) |
| 189 | + |
| 190 | + def push(self, image: str) -> None: |
| 191 | + """ |
| 192 | + Push an image to a registry. |
| 193 | +
|
| 194 | + Args: |
| 195 | + image: The name of the image to push. |
| 196 | + """ |
| 197 | + self._run("push", image) |
0 commit comments