-
Notifications
You must be signed in to change notification settings - Fork 291
/
__init__.py
2240 lines (1725 loc) · 81.5 KB
/
__init__.py
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: LGPL-2.1+
import contextlib
import datetime
import errno
import hashlib
import http.server
import itertools
import json
import logging
import os
import re
import resource
import shutil
import subprocess
import sys
import tempfile
import uuid
from collections.abc import Iterator, Sequence
from pathlib import Path
from textwrap import dedent
from typing import Callable, ContextManager, Optional, TextIO, Union, cast
from mkosi.btrfs import btrfs_maybe_snapshot_subvolume
from mkosi.config import (
ConfigFeature,
GenericVersion,
MkosiArgs,
MkosiConfig,
MkosiConfigParser,
SecureBootSignTool,
)
from mkosi.install import add_dropin_config_from_resource, copy_path, flock
from mkosi.log import Style, color_error, complete_step, die, log_step
from mkosi.manifest import Manifest
from mkosi.mounts import mount_overlay, scandir_recursive
from mkosi.pager import page
from mkosi.qemu import copy_ephemeral, machine_cid, run_qemu
from mkosi.remove import unlink_try_hard
from mkosi.run import (
become_root,
bwrap,
bwrap_cmd,
fork_and_wait,
run,
run_workspace_command,
spawn,
)
from mkosi.state import MkosiState
from mkosi.types import PathString
from mkosi.util import (
Compression,
InvokingUser,
ManifestFormat,
OutputFormat,
Verb,
flatten,
format_bytes,
format_rlimit,
is_apt_distribution,
is_portage_distribution,
prepend_to_environ_path,
)
MKOSI_COMMANDS_NEED_BUILD = (Verb.build, Verb.shell, Verb.boot, Verb.qemu, Verb.serve)
MKOSI_COMMANDS_SUDO = (Verb.shell, Verb.boot)
@contextlib.contextmanager
def mount_image(state: MkosiState) -> Iterator[None]:
with complete_step("Mounting image…", "Unmounting image…"), contextlib.ExitStack() as stack:
if state.config.base_trees and state.config.overlay:
bases = []
state.workspace.joinpath("bases").mkdir(exist_ok=True)
for path in state.config.base_trees:
d = Path(stack.enter_context(tempfile.TemporaryDirectory(dir=state.workspace / "bases", prefix=path.name)))
d.rmdir() # We need the random name, but we want to create the directory ourselves
if path.is_dir():
bases += [path]
elif path.suffix == ".tar":
shutil.unpack_archive(path, d)
bases += [d]
elif path.suffix == ".raw":
# We want to use bwrap() here but it doesn't propagate mounts so we use run() instead.
run(["systemd-dissect", "-M", path, d])
stack.callback(lambda: run(["systemd-dissect", "-U", d]))
bases += [d]
else:
die(f"Unsupported base tree source {path}")
stack.enter_context(mount_overlay(bases, state.root, state.root, read_only=False))
yield
def clean_paths(
root: Path,
globs: Sequence[str],
tool: str,
always: bool) -> None:
"""Remove globs under root if always or if tool is not found under root."""
toolp = root / tool.lstrip('/')
cond = always or not os.access(toolp, os.F_OK, follow_symlinks=False)
paths = flatten(root.glob(glob.lstrip('/')) for glob in globs)
if not cond or not paths:
return
with complete_step(f"Cleaning {toolp.name} metadata…"):
for path in paths:
unlink_try_hard(path)
def clean_dnf_metadata(root: Path, always: bool) -> None:
"""Remove dnf metadata if /bin/dnf is not present in the image
If dnf is not installed, there doesn't seem to be much use in keeping the
dnf metadata, since it's not usable from within the image anyway.
"""
paths = [
"/var/lib/dnf",
"/var/log/dnf.*",
"/var/log/hawkey.*",
"/var/cache/dnf",
]
clean_paths(root, paths, tool='/bin/dnf', always=always)
def clean_yum_metadata(root: Path, always: bool) -> None:
"""Remove yum metadata if /bin/yum is not present in the image"""
paths = [
"/var/lib/yum",
"/var/log/yum.*",
"/var/cache/yum",
]
clean_paths(root, paths, tool='/bin/yum', always=always)
def clean_rpm_metadata(root: Path, always: bool) -> None:
"""Remove rpm metadata if /bin/rpm is not present in the image"""
paths = [
"/var/lib/rpm",
"/usr/lib/sysimage/rpm",
]
clean_paths(root, paths, tool='/bin/rpm', always=always)
def clean_apt_metadata(root: Path, always: bool) -> None:
"""Remove apt metadata if /usr/bin/apt is not present in the image"""
paths = [
"/var/lib/apt",
"/var/log/apt",
"/var/cache/apt",
]
clean_paths(root, paths, tool='/usr/bin/apt', always=always)
def clean_dpkg_metadata(root: Path, always: bool) -> None:
"""Remove dpkg metadata if /usr/bin/dpkg is not present in the image"""
paths = [
"/var/lib/dpkg",
"/var/log/dpkg.log",
]
clean_paths(root, paths, tool='/usr/bin/dpkg', always=always)
def clean_pacman_metadata(root: Path, always: bool) -> None:
"""Remove pacman metadata if /usr/bin/pacman is not present in the image"""
paths = [
"/var/lib/pacman",
"/var/cache/pacman",
"/var/log/pacman.log"
]
clean_paths(root, paths, tool='/usr/bin/pacman', always=always)
def clean_package_manager_metadata(state: MkosiState) -> None:
"""Remove package manager metadata
Try them all regardless of the distro: metadata is only removed if the
package manager is present in the image.
"""
if state.config.clean_package_metadata == ConfigFeature.disabled:
return
# we try then all: metadata will only be touched if any of them are in the
# final image
always = state.config.clean_package_metadata == ConfigFeature.enabled
clean_dnf_metadata(state.root, always=always)
clean_yum_metadata(state.root, always=always)
clean_rpm_metadata(state.root, always=always)
clean_apt_metadata(state.root, always=always)
clean_dpkg_metadata(state.root, always=always)
clean_pacman_metadata(state.root, always=always)
def remove_files(state: MkosiState) -> None:
"""Remove files based on user-specified patterns"""
if not state.config.remove_files:
return
with complete_step("Removing files…"):
for pattern in state.config.remove_files:
for p in state.root.glob(pattern.lstrip("/")):
unlink_try_hard(p)
def install_distribution(state: MkosiState) -> None:
if state.config.base_trees:
if not state.config.packages:
return
with complete_step(f"Installing extra packages for {str(state.config.distribution).capitalize()}"):
state.installer.install_packages(state, state.config.packages)
else:
with complete_step(f"Installing {str(state.config.distribution).capitalize()}"):
state.installer.install(state)
# Ensure /efi exists so that the ESP is mounted there, as recommended by
# https://0pointer.net/blog/linux-boot-partitions.html. Use the most restrictive access mode we
# can without tripping up mkfs tools since this directory is only meant to be overmounted and
# should not be read from or written to.
state.root.joinpath("efi").mkdir(mode=0o500, exist_ok=True)
if state.config.packages:
state.installer.install_packages(state, state.config.packages)
def install_build_packages(state: MkosiState) -> None:
if not need_build_packages(state.config):
return
with complete_step(f"Installing build packages for {str(state.config.distribution).capitalize()}"), mount_build_overlay(state):
state.installer.install_packages(state, state.config.build_packages)
def remove_packages(state: MkosiState) -> None:
"""Remove packages listed in config.remove_packages"""
if not state.config.remove_packages:
return
with complete_step(f"Removing {len(state.config.packages)} packages…"):
try:
state.installer.remove_packages(state, state.config.remove_packages)
except NotImplementedError:
die(f"Removing packages is not supported for {state.config.distribution}")
def configure_autologin(state: MkosiState) -> None:
if not state.config.autologin:
return
with complete_step("Setting up autologin…"):
add_dropin_config_from_resource(state.root, "console-getty.service", "autologin",
"mkosi.resources", "console_getty_autologin.conf")
add_dropin_config_from_resource(state.root, "serial-getty@ttyS0.service", "autologin",
"mkosi.resources", "serial_getty_autologin.conf")
add_dropin_config_from_resource(state.root, "getty@tty1.service", "autologin",
"mkosi.resources", "getty_autologin.conf")
@contextlib.contextmanager
def mount_cache_overlay(state: MkosiState) -> Iterator[None]:
if not state.config.incremental or not any(state.root.iterdir()):
yield
return
d = state.workspace / "cache-overlay"
d.mkdir(mode=0o755, exist_ok=True)
with mount_overlay([state.root], d, state.root, read_only=False):
yield
def mount_build_overlay(state: MkosiState, read_only: bool = False) -> ContextManager[Path]:
d = state.workspace / "build-overlay"
if not d.is_symlink():
d.mkdir(mode=0o755, exist_ok=True)
return mount_overlay([state.root], state.workspace / "build-overlay", state.root, read_only)
def finalize_sources(config: MkosiConfig) -> list[tuple[Path, Path]]:
sources = [
(src, Path("work/src") / (str(target).lstrip("/") if target else "."))
for src, target
in config.build_sources
]
return sorted(sources, key=lambda s: s[1])
def run_prepare_script(state: MkosiState, build: bool) -> None:
if state.config.prepare_script is None:
return
if build and state.config.build_script is None:
return
bwrap: list[PathString] = [
"--bind", state.config.prepare_script, "/work/prepare",
"--chdir", "/work/src",
]
for src, target in finalize_sources(state.config):
bwrap += ["--bind", src, Path("/") / target]
if build:
with complete_step("Running prepare script in build overlay…"), mount_build_overlay(state):
run_workspace_command(
state.root,
["/work/prepare", "build"],
network=True,
bwrap_params=bwrap,
env=dict(SRCDIR="/work/src") | state.environment,
)
shutil.rmtree(state.root / "work")
else:
with complete_step("Running prepare script…"):
run_workspace_command(
state.root,
["/work/prepare", "final"],
network=True,
bwrap_params=bwrap,
env=dict(SRCDIR="/work/src") | state.environment,
)
shutil.rmtree(state.root / "work")
def run_postinst_script(state: MkosiState) -> None:
if state.config.postinst_script is None:
return
with complete_step("Running postinstall script…"):
bwrap: list[PathString] = [
"--bind", state.config.postinst_script, "/work/postinst",
]
run_workspace_command(state.root, ["/work/postinst", "final"], bwrap_params=bwrap,
network=state.config.with_network, env=state.environment)
shutil.rmtree(state.root / "work")
def run_finalize_script(state: MkosiState) -> None:
if state.config.finalize_script is None:
return
with complete_step("Running finalize script…"):
bwrap([state.config.finalize_script],
root=state.config.tools_tree,
env={**state.environment, "BUILDROOT": str(state.root), "OUTPUTDIR": str(state.staging)})
def certificate_common_name(state: MkosiState, certificate: Path) -> str:
output = bwrap([
"openssl",
"x509",
"-noout",
"-subject",
"-nameopt", "multiline",
"-in", certificate,
], root=state.config.tools_tree, stdout=subprocess.PIPE).stdout
for line in output.splitlines():
if not line.strip().startswith("commonName"):
continue
_, sep, value = line.partition("=")
if not sep:
die("Missing '=' delimiter in openssl output")
return cast(str, value.strip())
die(f"Certificate {certificate} is missing Common Name")
def pesign_prepare(state: MkosiState) -> None:
assert state.config.secure_boot_key
assert state.config.secure_boot_certificate
if (state.workspace / "pesign").exists():
return
(state.workspace / "pesign").mkdir()
# pesign takes a certificate directory and a certificate common name as input arguments, so we have
# to transform our input key and cert into that format. Adapted from
# https://www.mankier.com/1/pesign#Examples-Signing_with_the_certificate_and_private_key_in_individual_files
bwrap(["openssl",
"pkcs12",
"-export",
# Arcane incantation to create a pkcs12 certificate without a password.
"-keypbe", "NONE",
"-certpbe", "NONE",
"-nomaciter",
"-passout", "pass:",
"-out", state.workspace / "secure-boot.p12",
"-inkey", state.config.secure_boot_key,
"-in", state.config.secure_boot_certificate],
root=state.config.tools_tree)
bwrap(["pk12util",
"-K", "",
"-W", "",
"-i", state.workspace / "secure-boot.p12",
"-d", state.workspace / "pesign"],
root=state.config.tools_tree)
def install_boot_loader(state: MkosiState) -> None:
if state.config.bootable == ConfigFeature.disabled:
return
if state.config.output_format == OutputFormat.cpio and state.config.bootable == ConfigFeature.auto:
return
if not any(gen_kernel_images(state)) and state.config.bootable == ConfigFeature.auto:
return
if not shutil.which("bootctl"):
if state.config.bootable == ConfigFeature.enabled:
die("A bootable image was requested but bootctl was not found")
return
directory = state.root / "usr/lib/systemd/boot/efi"
if not directory.exists() or not any(directory.iterdir()):
if state.config.bootable == ConfigFeature.enabled:
die("A bootable image was requested but systemd-boot was not found at "
f"{directory.relative_to(state.root)}")
return
if state.config.secure_boot:
assert state.config.secure_boot_key
assert state.config.secure_boot_certificate
with complete_step("Signing systemd-boot binaries…"):
for input in itertools.chain(directory.glob('*.efi'), directory.glob('*.EFI')):
output = directory / f"{input}.signed"
if (state.config.secure_boot_sign_tool == SecureBootSignTool.sbsign or
state.config.secure_boot_sign_tool == SecureBootSignTool.auto and
shutil.which("sbsign") is not None):
bwrap(["sbsign",
"--key", state.config.secure_boot_key,
"--cert", state.config.secure_boot_certificate,
"--output", output,
input],
root=state.config.tools_tree)
elif (state.config.secure_boot_sign_tool == SecureBootSignTool.pesign or
state.config.secure_boot_sign_tool == SecureBootSignTool.auto and
shutil.which("pesign") is not None):
pesign_prepare(state)
bwrap(["pesign",
"--certdir", state.workspace / "pesign",
"--certificate", certificate_common_name(state, state.config.secure_boot_certificate),
"--sign",
"--force",
"--in", input,
"--out", output],
root=state.config.tools_tree)
else:
die("One of sbsign or pesign is required to use SecureBoot=")
with complete_step("Installing boot loader…"):
bwrap(["bootctl", "install", "--root", state.root, "--all-architectures"],
env={"SYSTEMD_ESP_PATH": "/efi"}, root=state.config.tools_tree)
if state.config.secure_boot:
assert state.config.secure_boot_key
assert state.config.secure_boot_certificate
with complete_step("Setting up secure boot auto-enrollment…"):
keys = state.root / "efi/loader/keys/auto"
keys.mkdir(parents=True, exist_ok=True)
# sbsiglist expects a DER certificate.
bwrap(["openssl",
"x509",
"-outform", "DER",
"-in", state.config.secure_boot_certificate,
"-out", state.workspace / "mkosi.der"],
root=state.config.tools_tree)
bwrap(["sbsiglist",
"--owner", str(uuid.uuid4()),
"--type", "x509",
"--output", state.workspace / "mkosi.esl",
state.workspace / "mkosi.der"],
root=state.config.tools_tree)
# We reuse the key for all secure boot databases to keep things simple.
for db in ["PK", "KEK", "db"]:
bwrap(["sbvarsign",
"--attr",
"NON_VOLATILE,BOOTSERVICE_ACCESS,RUNTIME_ACCESS,TIME_BASED_AUTHENTICATED_WRITE_ACCESS",
"--key", state.config.secure_boot_key,
"--cert", state.config.secure_boot_certificate,
"--output", keys / f"{db}.auth",
db,
state.workspace / "mkosi.esl"],
root=state.config.tools_tree)
def install_base_trees(state: MkosiState) -> None:
if not state.config.base_trees or state.config.overlay:
return
with complete_step("Copying in base trees…"):
for path in state.config.base_trees:
if path.is_dir():
btrfs_maybe_snapshot_subvolume(state.config, path, state.root)
elif path.suffix == ".tar":
shutil.unpack_archive(path, state.root)
elif path.suffix == ".raw":
bwrap(["systemd-dissect", "--copy-from", path, "/", state.root],
root=state.config.tools_tree)
else:
die(f"Unsupported base tree source {path}")
def install_skeleton_trees(state: MkosiState) -> None:
if not state.config.skeleton_trees:
return
with complete_step("Copying in skeleton file trees…"):
for source, target in state.config.skeleton_trees:
t = state.root
if target:
t = state.root / target.relative_to("/")
t.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
if source.is_dir() or target:
copy_path(source, t, preserve_owner=False, root=state.config.tools_tree)
else:
shutil.unpack_archive(source, t)
def install_package_manager_trees(state: MkosiState) -> None:
if not state.config.package_manager_trees:
return
with complete_step("Copying in package maneger file trees…"):
for source, target in state.config.package_manager_trees:
t = state.workspace / "pkgmngr"
if target:
t = state.workspace / "pkgmngr" / target.relative_to("/")
t.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
if source.is_dir() or target:
copy_path(source, t, preserve_owner=False, root=state.config.tools_tree)
else:
shutil.unpack_archive(source, t)
def install_extra_trees(state: MkosiState) -> None:
if not state.config.extra_trees:
return
with complete_step("Copying in extra file trees…"):
for source, target in state.config.extra_trees:
t = state.root
if target:
t = state.root / target.relative_to("/")
t.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
if source.is_dir() or target:
copy_path(source, t, preserve_owner=False, root=state.config.tools_tree)
else:
shutil.unpack_archive(source, t)
def install_build_dest(state: MkosiState) -> None:
if state.config.build_script is None:
return
with complete_step("Copying in build tree…"):
copy_path(state.install_dir, state.root, root=state.config.tools_tree)
def gzip_binary() -> str:
return "pigz" if shutil.which("pigz") else "gzip"
def tar_binary() -> str:
# Some distros (Mandriva) install BSD tar as "tar", hence prefer
# "gtar" if it exists, which should be GNU tar wherever it exists.
# We are interested in exposing same behaviour everywhere hence
# it's preferable to use the same implementation of tar
# everywhere. In particular given the limited/different SELinux
# support in BSD tar and the different command line syntax
# compared to GNU tar.
return "gtar" if shutil.which("gtar") else "tar"
def make_tar(state: MkosiState) -> None:
if state.config.output_format != OutputFormat.tar:
return
cmd: list[PathString] = [
tar_binary(),
"-C", state.root,
"-c", "--xattrs",
"--xattrs-include=*",
"--file", state.staging / state.config.output_with_format,
*(["--xattrs-exclude=security.selinux"] if state.config.tar_strip_selinux_context else []),
".",
]
with complete_step("Creating archive…"):
bwrap(cmd, root=state.config.tools_tree)
def find_files(dir: Path, root: Path) -> Iterator[Path]:
"""Generate a list of all filepaths in directory @dir relative to @root"""
yield from scandir_recursive(dir,
lambda entry: Path(entry.path).relative_to(root))
def make_initrd(state: MkosiState) -> None:
if state.config.output_format != OutputFormat.cpio:
return
make_cpio(state, find_files(state.root, state.root), state.staging / state.config.output_with_format)
def make_cpio(state: MkosiState, files: Iterator[Path], output: Path) -> None:
with complete_step(f"Creating cpio {output}…"), bwrap_cmd(root=state.config.tools_tree) as bwrap:
cmd: list[PathString] = [
*bwrap,
"cpio",
"-o",
"--reproducible",
"--null",
"-H", "newc",
"--quiet",
"-D", state.root,
"-O", output
]
with spawn(cmd, stdin=subprocess.PIPE, text=True) as cpio:
# https://github.com/python/mypy/issues/10583
assert cpio.stdin is not None
for file in files:
cpio.stdin.write(os.fspath(file))
cpio.stdin.write("\0")
cpio.stdin.close()
def make_directory(state: MkosiState) -> None:
if state.config.output_format != OutputFormat.directory:
return
state.root.rename(state.staging / state.config.output_with_format)
def gen_kernel_images(state: MkosiState) -> Iterator[tuple[str, Path]]:
if not state.root.joinpath("usr/lib/modules").exists():
return
for kver in sorted(
(k for k in state.root.joinpath("usr/lib/modules").iterdir() if k.is_dir()),
key=lambda k: GenericVersion(k.name),
reverse=True
):
kimg = Path("usr/lib/modules") / kver.name / "vmlinuz"
if not kimg.exists():
kimg = state.installer.kernel_image(kver.name, state.config.architecture)
yield kver.name, kimg
def filter_kernel_modules(root: Path, kver: str, include: Sequence[str], exclude: Sequence[str]) -> list[Path]:
modulesd = Path("usr/lib/modules") / kver
modules = set(m.relative_to(root) for m in (root / modulesd).glob("**/*.ko*"))
keep = set()
for pattern in include:
regex = re.compile(pattern)
for m in modules:
rel = os.fspath(m.relative_to(modulesd / "kernel"))
if regex.search(rel):
logging.debug(f"Including module {rel}")
keep.add(m)
for pattern in exclude:
regex = re.compile(pattern)
remove = set()
for m in modules:
rel = os.fspath(m.relative_to(modulesd / "kernel"))
if rel not in keep and regex.search(rel):
logging.debug(f"Excluding module {rel}")
remove.add(m)
modules -= remove
return sorted(modules)
def module_path_to_name(path: Path) -> str:
return path.name.partition(".")[0]
def resolve_module_dependencies(state: MkosiState, kver: str, modules: Sequence[str]) -> tuple[set[Path], set[Path]]:
"""
Returns a tuple of lists containing the paths to the module and firmware dependencies of the given list
of module names (including the given module paths themselves). The paths are returned relative to the
root directory.
"""
modulesd = Path("usr/lib/modules") / kver
builtin = set(module_path_to_name(Path(m)) for m in (state.root / modulesd / "modules.builtin").read_text().splitlines())
allmodules = set((state.root / modulesd / "kernel").glob("**/*.ko*"))
nametofile = {module_path_to_name(m): m.relative_to(state.root) for m in allmodules}
# We could run modinfo once for each module but that's slow. Luckily we can pass multiple modules to
# modinfo and it'll process them all in a single go. We get the modinfo for all modules to build two maps
# that map the path of the module to its module dependencies and its firmware dependencies respectively.
info = bwrap(["modinfo", "--basedir", state.root, "--set-version", kver, "--null", *nametofile.keys(), *builtin],
stdout=subprocess.PIPE, root=state.config.tools_tree).stdout
moddep = {}
firmwaredep = {}
depends = []
firmware = []
for line in info.split("\0"):
key, sep, value = line.partition(":")
if not sep:
key, sep, value = line.partition("=")
if key in ("depends", "softdep"):
depends += [d for d in value.strip().split(",") if d]
elif key == "firmware":
firmware += [f.relative_to(state.root) for f in state.root.joinpath("usr/lib/firmware").glob(f"{value.strip()}*")]
elif key == "name":
name = value.strip()
moddep[name] = depends
firmwaredep[name] = firmware
depends = []
firmware = []
todo = [*builtin, *modules]
mods = set()
firmware = set()
while todo:
m = todo.pop()
if m in mods:
continue
depends = moddep.get(m, [])
for d in depends:
if d not in nametofile and d not in builtin:
logging.warning(f"{d} is a dependency of {m} but is not installed, ignoring ")
mods.add(m)
todo += depends
firmware.update(firmwaredep.get(m, []))
return set(nametofile[m] for m in mods if m in nametofile), set(firmware)
def gen_kernel_modules_initrd(state: MkosiState, kver: str) -> Path:
def files() -> Iterator[Path]:
modulesd = Path("usr/lib/modules") / kver
yield modulesd.parent
yield modulesd
yield modulesd / "kernel"
for d in (modulesd, Path("usr/lib/firmware")):
for p in (state.root / d).glob("**/*"):
if p.is_dir():
yield p.relative_to(state.root)
modules = filter_kernel_modules(state.root, kver,
state.config.kernel_modules_initrd_include,
state.config.kernel_modules_initrd_exclude)
names = [module_path_to_name(m) for m in modules]
mods, firmware = resolve_module_dependencies(state, kver, names)
for p in sorted(mods) + sorted(firmware):
yield p
for p in (state.root / modulesd).iterdir():
if not p.name.startswith("modules"):
continue
yield p.relative_to(state.root)
if (state.root / modulesd / "vdso").exists():
yield modulesd / "vdso"
for p in (state.root / modulesd / "vdso").iterdir():
yield p.relative_to(state.root)
kmods = state.workspace / f"initramfs-kernel-modules-{kver}.img"
with complete_step(f"Generating kernel modules initrd for kernel {kver}"):
make_cpio(state, files(), kmods)
# Debian/Ubuntu do not compress their kernel modules, so we compress the initramfs instead. Note that
# this is not ideal since the compressed kernel modules will all be decompressed on boot which
# requires significant memory.
if is_apt_distribution(state.config.distribution):
maybe_compress(state, Compression.zst, kmods, kmods)
return kmods
def install_unified_kernel(state: MkosiState, roothash: Optional[str]) -> None:
# Iterates through all kernel versions included in the image and generates a combined
# kernel+initrd+cmdline+osrelease EFI file from it and places it in the /EFI/Linux directory of the ESP.
# sd-boot iterates through them and shows them in the menu. These "unified" single-file images have the
# benefit that they can be signed like normal EFI binaries, and can encode everything necessary to boot a
# specific root device, including the root hash.
if state.config.bootable == ConfigFeature.disabled:
return
for kver, kimg in gen_kernel_images(state):
shutil.copy(state.root / kimg, state.staging / state.config.output_split_kernel)
break
if state.config.output_format == OutputFormat.cpio and state.config.bootable == ConfigFeature.auto:
return
initrds = []
if state.config.initrds:
initrds = state.config.initrds
elif any(gen_kernel_images(state)):
# Default values are assigned via the parser so we go via the argument parser to construct
# the config for the initrd.
with complete_step("Building initrd"):
password, hashed = state.config.root_password or (None, False)
if password:
rootpwopt = f"hashed:{password}" if hashed else password
else:
rootpwopt = None
args, presets = MkosiConfigParser().parse([
"--directory", "",
"--distribution", str(state.config.distribution),
"--release", state.config.release,
"--architecture", str(state.config.architecture),
*(["--mirror", state.config.mirror] if state.config.mirror else []),
"--repository-key-check", yes_no(state.config.repository_key_check),
"--repositories", ",".join(state.config.repositories),
"--package-manager-tree", ",".join(format_source_target(s, t) for s, t in state.config.package_manager_trees),
*(["--tools-tree", str(state.config.tools_tree)] if state.config.tools_tree else []),
*(["--compress-output", str(state.config.compress_output)] if state.config.compress_output else []),
"--with-network", yes_no(state.config.with_network),
"--cache-only", yes_no(state.config.cache_only),
*(["--output-dir", str(state.config.output_dir)] if state.config.output_dir else []),
*(["--workspace-dir", str(state.config.workspace_dir)] if state.config.workspace_dir else []),
"--cache-dir", str(state.cache_dir.parent),
*(["--local-mirror", str(state.config.local_mirror)] if state.config.local_mirror else []),
"--incremental", yes_no(state.config.incremental),
"--acl", yes_no(state.config.acl),
"--format", "cpio",
"--package", "systemd",
*(["--package", "udev"] if not is_portage_distribution(state.config.distribution) else []),
"--package", "kmod",
*(["--package", "dmsetup"] if is_apt_distribution(state.config.distribution) else []),
"--output", f"{state.config.output}-initrd",
*(["--image-version", state.config.image_version] if state.config.image_version else []),
"--make-initrd", "yes",
"--bootable", "no",
"--manifest-format", "",
*(["--locale", state.config.locale] if state.config.locale else []),
*(["--locale-messages", state.config.locale_messages] if state.config.locale_messages else []),
*(["--keymap", state.config.keymap] if state.config.keymap else []),
*(["--timezone", state.config.timezone] if state.config.timezone else []),
*(["--hostname", state.config.hostname] if state.config.hostname else []),
*(["--root-password", rootpwopt] if rootpwopt else []),
*(["-f"] * state.args.force),
"build",
])
config = presets[0]
unlink_output(args, config)
build_image(args, config, state.uid, state.gid)
initrds = [config.output_dir / config.output]
for kver, kimg in gen_kernel_images(state):
with complete_step(f"Generating unified kernel image for {kimg}"):
image_id = state.config.image_id or f"mkosi-{state.config.distribution}"
# See https://systemd.io/AUTOMATIC_BOOT_ASSESSMENT/#boot-counting
boot_count = ""
if state.root.joinpath("etc/kernel/tries").exists():
boot_count = f'+{state.root.joinpath("etc/kernel/tries").read_text().strip()}'
if state.config.image_version:
boot_binary = state.root / f"efi/EFI/Linux/{image_id}_{state.config.image_version}-{kver}{boot_count}.efi"
elif roothash:
_, _, h = roothash.partition("=")
boot_binary = state.root / f"efi/EFI/Linux/{image_id}-{kver}-{h}{boot_count}.efi"
else:
boot_binary = state.root / f"efi/EFI/Linux/{image_id}-{kver}{boot_count}.efi"
if state.root.joinpath("etc/kernel/cmdline").exists():
cmdline = [state.root.joinpath("etc/kernel/cmdline").read_text().strip()]
elif state.root.joinpath("usr/lib/kernel/cmdline").exists():
cmdline = [state.root.joinpath("usr/lib/kernel/cmdline").read_text().strip()]
else:
cmdline = []
cmdline += state.installer.kernel_command_line(state)
if roothash:
cmdline += [roothash]
cmdline += state.config.kernel_command_line
# Older versions of systemd-stub expect the cmdline section to be null terminated. We can't embed
# nul terminators in argv so let's communicate the cmdline via a file instead.
state.workspace.joinpath("cmdline").write_text(f"{' '.join(cmdline).strip()}\x00")
stub = state.root / f"usr/lib/systemd/boot/efi/linux{state.config.architecture.to_efi()}.efi.stub"
if not stub.exists():
die(f"sd-stub not found at /{stub.relative_to(state.root)} in the image")
cmd: list[PathString] = [
shutil.which("ukify") or "/usr/lib/systemd/ukify",
"--cmdline", f"@{state.workspace / 'cmdline'}",
"--os-release", f"@{state.root / 'usr/lib/os-release'}",
"--stub", stub,
"--output", boot_binary,
"--efi-arch", state.config.architecture.to_efi(),
]
for p in state.config.extra_search_paths:
cmd += ["--tools", p]
uki_config = state.pkgmngr / "etc/kernel/uki.conf"
if uki_config.exists():
cmd += ["--config", uki_config]
if state.config.secure_boot:
assert state.config.secure_boot_key
assert state.config.secure_boot_certificate
cmd += ["--sign-kernel"]
if state.config.secure_boot_sign_tool != SecureBootSignTool.pesign:
cmd += [
"--signtool", "sbsign",
"--secureboot-private-key", state.config.secure_boot_key,
"--secureboot-certificate", state.config.secure_boot_certificate,
]
else:
pesign_prepare(state)
cmd += [
"--signtool", "pesign",
"--secureboot-certificate-dir", state.workspace / "pesign",
"--secureboot-certificate-name", certificate_common_name(state, state.config.secure_boot_certificate),
]
sign_expected_pcr = (state.config.sign_expected_pcr == ConfigFeature.enabled or
(state.config.sign_expected_pcr == ConfigFeature.auto and
shutil.which("systemd-measure") is not None))
if sign_expected_pcr:
cmd += [
"--pcr-private-key", state.config.secure_boot_key,
"--pcr-banks", "sha1,sha256",
]
cmd += [state.root / kimg] + initrds
if state.config.kernel_modules_initrd:
cmd += [gen_kernel_modules_initrd(state, kver)]
bwrap(cmd, root=state.config.tools_tree)
if not state.staging.joinpath(state.config.output_split_uki).exists():
shutil.copy(boot_binary, state.staging / state.config.output_split_uki)