File: __init__.py

package info (click to toggle)
mkosi 26-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,564 kB
  • sloc: python: 20,615; sh: 640; makefile: 12
file content (192 lines) | stat: -rw-r--r-- 5,591 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# SPDX-License-Identifier: LGPL-2.1-or-later

import contextlib
import dataclasses
import os
import subprocess
import sys
import uuid
from collections.abc import Iterator, Mapping, Sequence
from pathlib import Path
from types import TracebackType
from typing import Any, Optional

import pytest

from mkosi.distribution import Distribution
from mkosi.run import CompletedProcess, fork_and_wait, run
from mkosi.sandbox import acquire_privileges
from mkosi.tree import rmtree
from mkosi.user import INVOKING_USER
from mkosi.util import _FILE, PathString


@dataclasses.dataclass(frozen=True)
class ImageConfig:
    distribution: Distribution
    release: str
    debug_shell: bool


class Image:
    def __init__(self, config: ImageConfig) -> None:
        self.config = config

    def __enter__(self) -> "Image":
        if (cache := INVOKING_USER.cache_dir() / "mkosi") and os.access(cache, os.W_OK):
            tmpdir = cache
        else:
            tmpdir = Path("/var/tmp")

        self.output_dir = Path(os.getenv("TMPDIR", tmpdir)) / uuid.uuid4().hex[:16]

        return self

    def __exit__(
        self,
        type: Optional[type[BaseException]],
        value: Optional[BaseException],
        traceback: Optional[TracebackType],
    ) -> None:
        def clean() -> None:
            acquire_privileges()
            rmtree(self.output_dir)

        fork_and_wait(clean)

    def mkosi(
        self,
        verb: str,
        options: Sequence[PathString] = (),
        args: Sequence[str] = (),
        stdin: _FILE = None,
        check: bool = True,
        env: Mapping[str, str] = {},
    ) -> CompletedProcess:
        return run(
            [
                "python3", "-m", "mkosi",
                "--debug",
                *options,
                verb,
                *args,
            ],
            check=check,
            stdin=stdin,
            stdout=sys.stdout,
            env=os.environ | env,
        )  # fmt: skip

    def build(
        self,
        options: Sequence[PathString] = (),
        args: Sequence[str] = (),
        env: Mapping[str, str] = {},
    ) -> CompletedProcess:
        kcl = [
            "loglevel=6",
            "systemd.log_level=debug",
            "udev.log_level=info",
            "systemd.show_status=false",
            "systemd.journald.forward_to_console",
            "systemd.journald.max_level_console=info",
            "systemd.firstboot=no",
            "systemd.unit=mkosi-check-and-shutdown.service",
        ]

        opt: list[PathString] = [
            "--distribution", str(self.config.distribution),
            "--release", self.config.release,
            *(f"--kernel-command-line={i}" for i in kcl),
            "--force",
            "--incremental=strict",
            "--output-directory", self.output_dir,
            *(["--debug-shell"] if self.config.debug_shell else []),
            *options,
        ]  # fmt: skip

        self.mkosi("summary", opt, env=env)

        return self.mkosi(
            "build",
            opt,
            args,
            stdin=sys.stdin if sys.stdin.isatty() else None,
            env=env,
        )

    def boot(self, options: Sequence[str] = (), args: Sequence[str] = ()) -> CompletedProcess:
        result = self.mkosi(
            "boot",
            [
                "--runtime-build-sources=no",
                "--ephemeral=yes",
                "--register=no",
                *options,
            ],
            args,
            stdin=sys.stdin if sys.stdin.isatty() else None,
            check=False,
        )

        if result.returncode != 123:
            raise subprocess.CalledProcessError(result.returncode, result.args, result.stdout, result.stderr)

        return result

    def vm(self, options: Sequence[str] = (), args: Sequence[str] = ()) -> CompletedProcess:
        need_hyperv_workaround = os.uname().machine == "x86_64"

        result = self.mkosi(
            "vm",
            [
                "--runtime-build-sources=no",
                "--vsock=yes",
                # TODO: Drop once both Hyper-V bugs are fixed in Github Actions.
                *(["--qemu-args=-cpu max,pcid=off"] if need_hyperv_workaround else []),
                "--ram=2G",
                "--ephemeral=yes",
                "--register=no",
                *options,
            ],
            args,
            stdin=sys.stdin if sys.stdin.isatty() else None,
            check=False,
        )

        if result.returncode != 123:
            raise subprocess.CalledProcessError(result.returncode, result.args, result.stdout, result.stderr)

        return result


@pytest.fixture(scope="session", autouse=True)
def suspend_capture_stdin(pytestconfig: Any) -> Iterator[None]:
    """
    When --capture=no (or -s) is specified, pytest will still intercept
    stdin. Let's explicitly make it not capture stdin when --capture=no is
    specified so we can debug image boot failures by logging into the emergency
    shell.
    """

    capmanager: Any = pytestconfig.pluginmanager.getplugin("capturemanager")

    if pytestconfig.getoption("capture") == "no":
        capmanager.suspend_global_capture(in_=True)

    yield

    if pytestconfig.getoption("capture") == "no":
        capmanager.resume_global_capture()


@contextlib.contextmanager
def ci_group(s: str) -> Iterator[None]:
    github_actions = os.getenv("GITHUB_ACTIONS")
    if github_actions:
        print(f"\n::group::{s}", flush=True)
    try:
        yield
    finally:
        if github_actions:
            print("\n::endgroup::", flush=True)