|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +""" |
| 4 | +OCI podman context |
| 5 | +""" |
| 6 | + |
| 7 | +import logging |
| 8 | +from contextlib import ExitStack |
| 9 | +from functools import wraps |
| 10 | +from os import rmdir |
| 11 | +from pathlib import Path |
| 12 | +from subprocess import PIPE, Popen, STDOUT |
| 13 | +from tempfile import mkdtemp |
| 14 | +from time import sleep |
| 15 | +from typing import Optional |
| 16 | + |
| 17 | +from podman.client import PodmanClient |
| 18 | + |
| 19 | +from ..constants import PODMAN_CONNECTION_MAX_DURATION |
| 20 | +from ..logger import LoggerSetup |
| 21 | + |
| 22 | + |
| 23 | +class PodmanContext(ExitStack): |
| 24 | + """ |
| 25 | + OCI podman context provides a context manager to be used to interact with |
| 26 | + the podman API from Python. |
| 27 | +
|
| 28 | + :author: Garden Linux Maintainers |
| 29 | + :copyright: Copyright 2024 SAP SE |
| 30 | + :package: gardenlinux |
| 31 | + :subpackage: oci |
| 32 | + :since: 0.11.0 |
| 33 | + :license: https://www.apache.org/licenses/LICENSE-2.0 |
| 34 | + Apache License, Version 2.0 |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, logger: Optional[logging.Logger] = None): |
| 38 | + """ |
| 39 | + Constructor __init__(PodmanContext) |
| 40 | +
|
| 41 | + :since: 0.11.0 |
| 42 | + """ |
| 43 | + |
| 44 | + ExitStack.__init__(self) |
| 45 | + |
| 46 | + if logger is None or not logger.hasHandlers(): |
| 47 | + logger = LoggerSetup.get_logger("gardenlinux.oci") |
| 48 | + |
| 49 | + self._logger = logger |
| 50 | + self._podman = None |
| 51 | + self._podman_daemon = None |
| 52 | + self._tmpdir = None |
| 53 | + |
| 54 | + def __enter__(self): |
| 55 | + """ |
| 56 | + python.org: Enter the runtime context related to this object. |
| 57 | +
|
| 58 | + :return: (object) Podman context instance |
| 59 | + :since: 0.11.0 |
| 60 | + """ |
| 61 | + |
| 62 | + self._tmpdir = mkdtemp() |
| 63 | + |
| 64 | + podman_sock = str(Path(self._tmpdir, "podman.sock")) |
| 65 | + |
| 66 | + self._podman = PodmanClient(base_url=f"unix://{podman_sock}") |
| 67 | + self._podman_daemon = Popen( |
| 68 | + args=[ |
| 69 | + "py-podman", |
| 70 | + "system", |
| 71 | + "service", |
| 72 | + f"--time={PODMAN_CONNECTION_MAX_DURATION}", |
| 73 | + f"unix://{podman_sock}", |
| 74 | + ], |
| 75 | + executable="podman", |
| 76 | + stdout=PIPE, |
| 77 | + stderr=STDOUT, |
| 78 | + ) |
| 79 | + |
| 80 | + self.enter_context(self._podman_daemon) |
| 81 | + self._wait_for_socket(podman_sock) |
| 82 | + self.enter_context(self._podman) |
| 83 | + |
| 84 | + return self |
| 85 | + |
| 86 | + def __exit__(self, exc_type, exc_value, traceback): |
| 87 | + """ |
| 88 | + python.org: Exit the runtime context related to this object. |
| 89 | +
|
| 90 | + :return: (bool) True to suppress exceptions |
| 91 | + :since: 0.11.0 |
| 92 | + """ |
| 93 | + |
| 94 | + try: |
| 95 | + self._podman_daemon.terminate() |
| 96 | + self._podman_daemon.wait(PODMAN_CONNECTION_MAX_DURATION) |
| 97 | + |
| 98 | + if exc_type is not None: |
| 99 | + stdout = self._podman_daemon.stdout.read() |
| 100 | + self._logger.error( |
| 101 | + f"Podman context encountered an error. Process output: {stdout}" |
| 102 | + ) |
| 103 | + finally: |
| 104 | + self._podman_daemon = None |
| 105 | + |
| 106 | + rmdir(self._tmpdir) |
| 107 | + self._tmpdir = None |
| 108 | + |
| 109 | + return False |
| 110 | + |
| 111 | + def __getattr__(self, name: str): |
| 112 | + """ |
| 113 | + python.org: Called when an attribute lookup has not found the attribute in |
| 114 | + the usual places (i.e. it is not an instance attribute nor is it found in the |
| 115 | + class tree for self). |
| 116 | +
|
| 117 | + :param name: Attribute name |
| 118 | +
|
| 119 | + :return: (mixed) Attribute |
| 120 | + :since: 0.11.0 |
| 121 | + """ |
| 122 | + |
| 123 | + if self._podman_daemon is None: |
| 124 | + raise RuntimeError("Podman context not ready") |
| 125 | + |
| 126 | + return getattr(self._podman, name) |
| 127 | + |
| 128 | + def _wait_for_socket(self, sock: str): |
| 129 | + """ |
| 130 | + Waits for the socket file to be created. |
| 131 | +
|
| 132 | + :since: 0.11.0 |
| 133 | + """ |
| 134 | + |
| 135 | + sock_path = Path(sock) |
| 136 | + |
| 137 | + for _ in range(0, 5 * PODMAN_CONNECTION_MAX_DURATION): |
| 138 | + if sock_path.exists(): |
| 139 | + break |
| 140 | + |
| 141 | + sleep(0.2) |
| 142 | + |
| 143 | + if not sock_path.exists(): |
| 144 | + raise TimeoutError() |
| 145 | + |
| 146 | + @staticmethod |
| 147 | + def wrap(f): |
| 148 | + """ |
| 149 | + Wraps the given function to provide access to a podman client. |
| 150 | +
|
| 151 | + :since: 0.11.0 |
| 152 | + """ |
| 153 | + |
| 154 | + @wraps(f) |
| 155 | + def decorator(*args, **kwargs): |
| 156 | + """ |
| 157 | + Decorator for wrapping a function or method with a call context. |
| 158 | + """ |
| 159 | + |
| 160 | + if "podman" in kwargs: |
| 161 | + raise ValueError( |
| 162 | + "Podman context wrapped functions can not be called with `kwargs['podman']`" |
| 163 | + ) |
| 164 | + |
| 165 | + with PodmanContext() as podman: |
| 166 | + kwargs["podman"] = podman |
| 167 | + return f(*args, **kwargs) |
| 168 | + |
| 169 | + return decorator |
0 commit comments