]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
Make Register= a feature
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Wed, 22 Jan 2025 09:54:55 +0000 (10:54 +0100)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Wed, 22 Jan 2025 10:38:56 +0000 (11:38 +0100)
By default, we want to register if machined is available and not
otherwise so let's make Register= a feature that defaults to "auto".

mkosi/__init__.py
mkosi/config.py
mkosi/qemu.py
mkosi/resources/man/mkosi.1.md
mkosi/vmspawn.py
tests/test_json.py

index 31f5b10a8537c4c1daeba72d70408ad3d6dd9b64..51d0ca617270de110757982a2dc121f6385f6545 100644 (file)
@@ -91,6 +91,7 @@ from mkosi.qemu import (
     copy_ephemeral,
     finalize_credentials,
     finalize_kernel_command_line_extra,
+    finalize_register,
     join_initrds,
     run_qemu,
     run_ssh,
@@ -3910,7 +3911,7 @@ def run_shell(args: Args, config: Config) -> None:
     for k, v in finalize_credentials(config).items():
         cmdline += [f"--set-credential={k}:{v}"]
 
-    cmdline += ["--register", yes_no(config.register)]
+    cmdline += ["--register", yes_no(finalize_register(config))]
 
     with contextlib.ExitStack() as stack:
         # Make sure the latest nspawn settings are always used.
index f2c6530def32f44abc614fe58279df60f32b791f..f77c34b2bc1c56fdd9296f40af2e1df574f40301 100644 (file)
@@ -1911,7 +1911,7 @@ class Config:
     ephemeral: bool
     credentials: dict[str, str]
     kernel_command_line_extra: list[str]
-    register: bool
+    register: ConfigFeature
     runtime_trees: list[ConfigTree]
     runtime_size: Optional[int]
     runtime_scratch: ConfigFeature
@@ -3735,8 +3735,8 @@ SETTINGS: list[ConfigSetting[Any]] = [
         dest="register",
         metavar="BOOL",
         section="Runtime",
-        parse=config_parse_boolean,
-        default=True,
+        parse=config_parse_feature,
+        default=ConfigFeature.auto,
         help="Register booted vm/container with systemd-machined",
     ),
 ]
@@ -4969,7 +4969,7 @@ def summary(config: Config) -> str:
                     SSH Certificate: {none_to_none(config.ssh_certificate)}
                             Machine: {config.machine_or_name()}
                     Forward Journal: {none_to_none(config.forward_journal)}
-       Register guest with machined: {yes_no(config.register)}
+       Register guest with machined: {config.register}
 
             Virtual Machine Monitor: {config.vmm}
                             Console: {config.console}
index 84bfad8184212076858a6cfb9b9a0b5305776f5a..5427fbbe08820fe0d0320a83071c894e49c82760 100644 (file)
@@ -961,8 +961,47 @@ def scope_cmd(
     ]  # fmt: skip
 
 
+def machine1_is_available(config: Config) -> bool:
+    if "DBUS_SYSTEM_ADDRESS" not in os.environ and not Path("/run/dbus/system_bus_socket").is_socket():
+        return False
+
+    services = json.loads(
+        run(
+            ["busctl", "list", "--json=pretty"],
+            foreground=False,
+            env=os.environ | config.environment,
+            sandbox=config.sandbox(relaxed=True),
+            stdout=subprocess.PIPE,
+            stderr=sys.stderr,
+        ).stdout.strip()
+    )
+
+    return any(service.name == "org.freedesktop.machine1" for service in services)
+
+
+def finalize_register(config: Config) -> bool:
+    if config.register == ConfigFeature.disabled:
+        return False
+
+    if os.getuid() == 0 and (
+        Path("/run/systemd/machine/io.systemd.Machine").is_socket() or machine1_is_available(config)
+    ):
+        return True
+
+    if config.register == ConfigFeature.enabled:
+        if os.getuid() != 0:
+            die("Container registration requires root privileges")
+        else:
+            die(
+                "Container registration was requested but systemd-machined is not available",
+                hint="Is the systemd-container package installed?",
+            )
+
+    return False
+
+
 def register_machine(config: Config, pid: int, fname: Path, cid: Optional[int]) -> None:
-    if not config.register or os.getuid() != 0:
+    if not finalize_register(config):
         return
 
     if (p := Path("/run/systemd/machine/io.systemd.Machine")).is_socket():
@@ -992,7 +1031,7 @@ def register_machine(config: Config, pid: int, fname: Path, cid: Optional[int])
             stdout=subprocess.DEVNULL,
             stderr=sys.stderr,
         )
-    elif "DBUS_SYSTEM_ADDRESS" in os.environ or Path("/run/dbus/system_bus_socket").is_socket():
+    else:
         run(
             [
                 "busctl",
index 58598cdf6d433f9c6426d60c29872bfb4364459d..e255c884c7c124260d5e15233b1ec72921cd512c 100644 (file)
@@ -1798,8 +1798,12 @@ boolean argument: either `1`, `yes`, or `true` to enable, or `0`, `no`,
     of the same image.
 
 `Register=`, `--register=`
-:   Takes a boolean value. Enabled by default. Specifies whether to register
-    the vm/container with systemd-machined.
+:   Takes a boolean value or `auto`. Specifies whether to register the
+    vm/container with systemd-machined. If enabled, mkosi will fail if
+    it can't register the vm/container with systemd-machined. If
+    disabled, mkosi will not register the vm/container with
+    systemd-machined. If `auto`, mkosi will register the vm/container
+    with systemd-machined if it is available. Defaults to `auto`.
 
 `ForwardJournal=`, `--forward-journal=`
 :   Specify the path to which journal logs from containers and virtual
index 9a3a4c129afb9fd15ff74d11c957f119ef5cae74..60a21b11d30fbfb5a4659a1d3cfcbaaa165598a2 100644 (file)
@@ -20,6 +20,7 @@ from mkosi.qemu import (
     finalize_credentials,
     finalize_firmware,
     finalize_kernel_command_line_extra,
+    finalize_register,
 )
 from mkosi.run import run
 from mkosi.types import PathString
@@ -58,7 +59,7 @@ def run_vmspawn(args: Args, config: Config) -> None:
         "--vsock", config.vsock.to_tristate(),
         "--tpm", config.tpm.to_tristate(),
         "--secure-boot", yes_no(config.secure_boot),
-        "--register", yes_no(config.register),
+        "--register", yes_no(finalize_register(config)),
         "--console", str(config.console),
     ]  # fmt: skip
 
index b107467af1a1146b39313db00bb3dc7d1eda2713..3d164f53ab77290faac56e9b1b4ee38ffd9e89fa 100644 (file)
@@ -260,7 +260,7 @@ def test_config() -> None:
             "ProxyUrl": "https://my/proxy",
             "QemuArgs": [],
             "RAM": 123,
-            "Register": true,
+            "Register": "enabled",
             "Release": "53",
             "Removable": false,
             "RemoveFiles": [],
@@ -507,7 +507,7 @@ def test_config() -> None:
         proxy_url="https://my/proxy",
         qemu_args=[],
         ram=123,
-        register=True,
+        register=ConfigFeature.enabled,
         release="53",
         removable=False,
         remove_files=[],