forked from systemd/mkosi
/
mkosi
executable file
·2536 lines (1989 loc) · 91 KB
/
mkosi
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
#!/usr/bin/python3
import argparse
import configparser
import contextlib
import ctypes, ctypes.util
import crypt
import getpass
import hashlib
import os
import platform
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import urllib.request
import uuid
from enum import Enum
__version__ = '1'
# TODO
# - volatile images
# - make debian/ubuntu images bootable
# - work on device nodes
# - allow passing env vars
def die(message, status=1):
assert status >= 1 and status < 128
sys.stderr.write(message + "\n")
sys.exit(status)
class OutputFormat(Enum):
raw_gpt = 1
raw_btrfs = 2
raw_squashfs = 3
directory = 4
subvolume = 5
tar = 6
class Distribution(Enum):
fedora = 1
debian = 2
ubuntu = 3
arch = 4
opensuse = 5
GPT_ROOT_X86 = uuid.UUID("44479540f29741b29af7d131d5f0458a")
GPT_ROOT_X86_64 = uuid.UUID("4f68bce3e8cd4db196e7fbcaf984b709")
GPT_ROOT_ARM = uuid.UUID("69dad7102ce44e3cb16c21a1d49abed3")
GPT_ROOT_ARM_64 = uuid.UUID("b921b0451df041c3af444c6f280d3fae")
GPT_ROOT_IA64 = uuid.UUID("993d8d3df80e4225855a9daf8ed7ea97")
GPT_ESP = uuid.UUID("c12a7328f81f11d2ba4b00a0c93ec93b")
GPT_SWAP = uuid.UUID("0657fd6da4ab43c484e50933c84b4f4f")
GPT_HOME = uuid.UUID("933ac7e12eb44f13b8440e14e2aef915")
GPT_SRV = uuid.UUID("3b8f842520e04f3b907f1a25a76f98e8")
GPT_ROOT_X86_VERITY = uuid.UUID("d13c5d3bb5d1422ab29f9454fdc89d76")
GPT_ROOT_X86_64_VERITY = uuid.UUID("2c7357edebd246d9aec123d437ec2bf5")
GPT_ROOT_ARM_VERITY = uuid.UUID("7386cdf2203c47a9a498f2ecce45a2d6")
GPT_ROOT_ARM_64_VERITY = uuid.UUID("df3300ced69f4c92978c9bfb0f38d820")
GPT_ROOT_IA64_VERITY = uuid.UUID("86ed10d5b60745bb8957d350f23d0571")
if platform.machine() == "x86_64":
GPT_ROOT_NATIVE = GPT_ROOT_X86_64
GPT_ROOT_NATIVE_VERITY = GPT_ROOT_X86_64_VERITY
elif platform.machine() == "aarch64":
GPT_ROOT_NATIVE = GPT_ROOT_ARM_64
GPT_ROOT_NATIVE_VERITY = GPT_ROOT_ARM_64_VERITY
else:
die("Don't know the %s architecture." % platform.machine())
CLONE_NEWNS = 0x00020000
FEDORA_KEYS_MAP = {
"23": "34EC9CBA",
"24": "81B46521",
"25": "FDB19C98",
"26": "64DAB85D",
}
# 1 MB at the beginning of the disk for the GPT disk label, and
# another MB at the end (this is actually more than needed.)
GPT_HEADER_SIZE = 1024*1024
GPT_FOOTER_SIZE = 1024*1024
def unshare(flags):
libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
if libc.unshare(ctypes.c_int(flags)) != 0:
e = ctypes.get_errno()
raise OSError(e, os.strerror(e))
def format_bytes(bytes):
if bytes >= 1024*1024*1024:
return "{:0.1f}G".format(bytes / 1024**3)
if bytes >= 1024*1024:
return "{:0.1f}M".format(bytes / 1024**2)
if bytes >= 1024:
return "{:0.1f}K".format(bytes / 1024)
return "{}B".format(bytes)
def roundup512(x):
return (x + 511) & ~511
def print_step(text):
sys.stderr.write("‣ \033[0;1;39m" + text + "\033[0m\n")
@contextlib.contextmanager
def complete_step(text, text2=None):
print_step(text + '...')
args = []
yield args
if text2 is None:
text2 = text + ' complete'
print_step(text2.format(*args) + '.')
@complete_step('Detaching namespace')
def init_namespace(args):
args.original_umask = os.umask(0o000)
unshare(CLONE_NEWNS)
subprocess.run(["mount", "--make-rslave", "/"], check=True)
def setup_workspace(args):
print_step("Setting up temporary workspace.")
if args.output_format in (OutputFormat.directory, OutputFormat.subvolume):
d = tempfile.TemporaryDirectory(dir=os.path.dirname(args.output), prefix='.mkosi-')
else:
d = tempfile.TemporaryDirectory(dir='/var/tmp', prefix='mkosi-')
print_step("Temporary workspace in " + d.name + " is now set up.")
return d
def btrfs_subvol_create(path, mode=0o755):
m = os.umask(~mode & 0o7777)
subprocess.run(["btrfs", "subvol", "create", path], check=True)
os.umask(m)
def btrfs_subvol_delete(path):
subprocess.run(["btrfs", "subvol", "delete", path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
def btrfs_subvol_make_ro(path, b=True):
subprocess.run(["btrfs", "property", "set", path, "ro", "true" if b else "false"], check=True)
def image_size(args):
size = GPT_HEADER_SIZE + GPT_FOOTER_SIZE
if args.root_size is not None:
size += args.root_size
if args.home_size is not None:
size += args.home_size
if args.srv_size is not None:
size += args.srv_size
if args.bootable:
size += args.esp_size
if args.swap_size is not None:
size += args.swap_size
if args.verity_size is not None:
size += args.verity_size
return size
def create_image(args, workspace):
if not args.output_format in (OutputFormat.raw_gpt, OutputFormat.raw_btrfs, OutputFormat.raw_squashfs):
return None
with complete_step('Creating partition table',
'Created partition table as {.name}') as output:
f = tempfile.NamedTemporaryFile(dir = os.path.dirname(args.output), prefix='.mkosi-')
output.append(f)
# disable copy-on-write if applicable on filesystem
subprocess.run(["chattr", "+C", f.name],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
f.truncate(image_size(args))
pn = 1
table = "label: gpt\n"
run_sfdisk = False
if args.bootable:
table += 'size={}, type={}, name="ESP System Partition"\n'.format(args.esp_size // 512, GPT_ESP)
args.esp_partno = pn
pn += 1
run_sfdisk = True
else:
args.esp_partno = None
if args.swap_size is not None:
table += 'size={}, type={}, name="Swap Partition"\n'.format(args.swap_size // 512, GPT_SWAP)
args.swap_partno = pn
pn += 1
run_sfdisk = True
else:
args.swap_partno = None
args.home_partno = None
args.srv_partno = None
if args.output_format != OutputFormat.raw_btrfs:
if args.home_size is not None:
table += 'size={}, type={}, name="Home Partition"\n'.format(args.home_size // 512, GPT_HOME)
args.home_partno = pn
pn += 1
run_sfdisk = True
if args.srv_size is not None:
table += 'size={}, type={}, name="Server Data Partition"\n'.format(args.srv_size // 512, GPT_SRV)
args.srv_partno = pn
pn += 1
run_sfdisk = True
if args.output_format != OutputFormat.raw_squashfs:
table += 'type={}, attrs={}, name="Root Partition"\n'.format(GPT_ROOT_NATIVE, "GUID:60" if args.read_only and args.output_format != OutputFormat.raw_btrfs else "")
run_sfdisk = True
args.root_partno = pn
pn += 1
if args.verity:
args.verity_partno = pn
pn += 1
else:
args.verity_partno = None
if run_sfdisk:
subprocess.run(["sfdisk", "--color=never", f.name], input=table.encode("utf-8"), check=True)
subprocess.run(["sync"])
args.ran_sfdisk = run_sfdisk
return f
@contextlib.contextmanager
def attach_image_loopback(args, raw):
if raw is None:
yield None
return
with complete_step('Attaching image file',
'Attached image file as {}') as output:
c = subprocess.run(["losetup", "--find", "--show", "--partscan", raw.name],
stdout=subprocess.PIPE, check=True)
loopdev = c.stdout.decode("utf-8").strip()
output.append(loopdev)
try:
yield loopdev
finally:
with complete_step('Detaching image file'):
subprocess.run(["losetup", "--detach", loopdev], check=True)
def partition(loopdev, partno):
if partno is None:
return None
return loopdev + "p" + str(partno)
def prepare_swap(args, loopdev):
if loopdev is None:
return
if args.swap_partno is None:
return
with complete_step('Formatting swap partition'):
subprocess.run(["mkswap", "-Lswap", partition(loopdev, args.swap_partno)],
check=True)
def prepare_esp(args, loopdev):
if loopdev is None:
return
if args.esp_partno is None:
return
with complete_step('Formatting ESP partition'):
subprocess.run(["mkfs.fat", "-nEFI", "-F32", partition(loopdev, args.esp_partno)],
check=True)
def mkfs_ext4(label, mount, dev):
subprocess.run(["mkfs.ext4", "-L", label, "-M", mount, dev], check=True)
def mkfs_btrfs(label, dev):
subprocess.run(["mkfs.btrfs", "-L", label, dev], check=True)
def luks_format(dev, passphrase):
if passphrase['type'] == 'stdin':
passphrase = (passphrase['content'] + "\n").encode("utf-8")
subprocess.run(["cryptsetup", "luksFormat", "--batch-mode", dev], input=passphrase, check=True)
else:
assert passphrase['type'] == 'file'
subprocess.run(["cryptsetup", "luksFormat", "--batch-mode", dev, passphrase['content']], check=True)
def luks_open(dev, passphrase):
name = str(uuid.uuid4())
if passphrase['type'] == 'stdin':
passphrase = (passphrase['content'] + "\n").encode("utf-8")
subprocess.run(["cryptsetup", "open", "--type", "luks", dev, name], input=passphrase, check=True)
else:
assert passphrase['type'] == 'file'
subprocess.run(["cryptsetup", "--key-file", passphrase['content'], "open", "--type", "luks", dev, name], check=True)
return os.path.join("/dev/mapper", name)
def luks_close(dev, text):
if dev is None:
return
with complete_step(text):
subprocess.run(["cryptsetup", "close", dev], check=True)
def luks_format_root(args, loopdev, run_build_script, inserting_squashfs=False):
if args.encrypt != "all":
return
if args.root_partno is None:
return
if args.output_format == OutputFormat.raw_squashfs and not inserting_squashfs:
return
if run_build_script:
return
with complete_step("LUKS formatting root partition"):
luks_format(partition(loopdev, args.root_partno), args.passphrase)
def luks_format_home(args, loopdev, run_build_script):
if args.encrypt is None:
return
if args.home_partno is None:
return
if run_build_script:
return
with complete_step("LUKS formatting home partition"):
luks_format(partition(loopdev, args.home_partno), args.passphrase)
def luks_format_srv(args, loopdev, run_build_script):
if args.encrypt is None:
return
if args.srv_partno is None:
return
if run_build_script:
return
with complete_step("LUKS formatting server data partition"):
luks_format(partition(loopdev, args.srv_partno), args.passphrase)
def luks_setup_root(args, loopdev, run_build_script, inserting_squashfs=False):
if args.encrypt != "all":
return None
if args.root_partno is None:
return None
if args.output_format == OutputFormat.raw_squashfs and not inserting_squashfs:
return
if run_build_script:
return None
with complete_step("Opening LUKS root partition"):
return luks_open(partition(loopdev, args.root_partno), args.passphrase)
def luks_setup_home(args, loopdev, run_build_script):
if args.encrypt is None:
return None
if args.home_partno is None:
return None
if run_build_script:
return None
with complete_step("Opening LUKS home partition"):
return luks_open(partition(loopdev, args.home_partno), args.passphrase)
def luks_setup_srv(args, loopdev, run_build_script):
if args.encrypt is None:
return None
if args.srv_partno is None:
return None
if run_build_script:
return None
with complete_step("Opening LUKS server data partition"):
return luks_open(partition(loopdev, args.srv_partno), args.passphrase)
@contextlib.contextmanager
def luks_setup_all(args, loopdev, run_build_script):
if args.output_format in (OutputFormat.directory, OutputFormat.subvolume, OutputFormat.tar):
yield (None, None, None)
return
try:
root = luks_setup_root(args, loopdev, run_build_script)
try:
home = luks_setup_home(args, loopdev, run_build_script)
try:
srv = luks_setup_srv(args, loopdev, run_build_script)
yield (partition(loopdev, args.root_partno) if root is None else root, \
partition(loopdev, args.home_partno) if home is None else home, \
partition(loopdev, args.srv_partno) if srv is None else srv)
finally:
luks_close(srv, "Closing LUKS server data partition")
finally:
luks_close(home, "Closing LUKS home partition")
finally:
luks_close(root, "Closing LUKS root partition")
def prepare_root(args, dev):
if dev is None:
return
if args.output_format == OutputFormat.raw_squashfs:
return
with complete_step('Formatting root partition'):
if args.output_format == OutputFormat.raw_btrfs:
mkfs_btrfs("root", dev)
else:
mkfs_ext4("root", "/", dev)
def prepare_home(args, dev):
if dev is None:
return
with complete_step('Formatting home partition'):
mkfs_ext4("home", "/home", dev)
def prepare_srv(args, dev):
if dev is None:
return
with complete_step('Formatting server data partition'):
mkfs_ext4("srv", "/srv", dev)
def mount_loop(args, dev, where, read_only=False):
os.makedirs(where, 0o755, True)
options = "-odiscard"
if args.compress and args.output_format == OutputFormat.raw_btrfs:
options += ",compress"
if read_only:
options += ",ro"
subprocess.run(["mount", "-n", dev, where, options], check=True)
def mount_bind(what, where):
os.makedirs(where, 0o755, True)
subprocess.run(["mount", "--bind", what, where], check=True)
def mount_tmpfs(where):
os.makedirs(where, 0o755, True)
subprocess.run(["mount", "tmpfs", "-t", "tmpfs", where], check=True)
@contextlib.contextmanager
def mount_image(args, workspace, loopdev, root_dev, home_dev, srv_dev, root_read_only=False):
if loopdev is None:
yield None
return
with complete_step('Mounting image'):
root = os.path.join(workspace, "root")
if args.output_format != OutputFormat.raw_squashfs:
mount_loop(args, root_dev, root, root_read_only)
if home_dev is not None:
mount_loop(args, home_dev, os.path.join(root, "home"))
if srv_dev is not None:
mount_loop(args, srv_dev, os.path.join(root, "srv"))
if args.esp_partno is not None:
mount_loop(args, partition(loopdev, args.esp_partno), os.path.join(root, "efi"))
# Make sure /tmp and /run are not part of the image
mount_tmpfs(os.path.join(root, "run"))
mount_tmpfs(os.path.join(root, "tmp"))
try:
yield
finally:
with complete_step('Unmounting image'):
for d in ("home", "srv", "efi", "var/cache/dnf", "var/cache/apt/archives", "var/cache/zypp/packages", "run", "tmp"):
umount(os.path.join(root, d))
umount(root)
@contextlib.contextmanager
def mount_api_vfs(args, workspace):
paths = ('/proc', '/dev', '/sys')
root = os.path.join(workspace, "root")
with complete_step('Mounting API VFS'):
for d in paths:
mount_bind(d, root + d)
try:
yield
finally:
with complete_step('Unmounting API VFS'):
for d in paths:
umount(root + d)
@contextlib.contextmanager
def mount_cache(args, workspace):
if args.cache_path is None:
yield
return
# We can't do this in mount_image() yet, as /var itself might have to be created as a subvolume first
with complete_step('Mounting Package Cache'):
if args.distribution == Distribution.fedora:
mount_bind(args.cache_path, os.path.join(workspace, "root", "var/cache/dnf"))
elif args.distribution in (Distribution.debian, Distribution.ubuntu):
mount_bind(args.cache_path, os.path.join(workspace, "root", "var/cache/apt/archives"))
elif args.distribution == Distribution.opensuse:
mount_bind(args.cache_path, os.path.join(workspace, "root", "var/cache/zypp/packages"))
try:
yield
finally:
with complete_step('Unmounting Package Cache'):
for d in ("var/cache/dnf", "var/cache/apt/archives", "var/cache/zypp/packages"):
umount(os.path.join(workspace, "root", d))
def umount(where):
# Ignore failures and error messages
subprocess.run(["umount", "-n", where], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
@complete_step('Setting up basic OS tree')
def prepare_tree(args, workspace, run_build_script):
if args.output_format == OutputFormat.subvolume:
btrfs_subvol_create(os.path.join(workspace, "root"))
else:
try:
os.mkdir(os.path.join(workspace, "root"))
except FileExistsError:
pass
if args.output_format in (OutputFormat.subvolume, OutputFormat.raw_btrfs):
btrfs_subvol_create(os.path.join(workspace, "root", "home"))
btrfs_subvol_create(os.path.join(workspace, "root", "srv"))
btrfs_subvol_create(os.path.join(workspace, "root", "var"))
btrfs_subvol_create(os.path.join(workspace, "root", "var/tmp"), 0o1777)
os.mkdir(os.path.join(workspace, "root", "var/lib"))
btrfs_subvol_create(os.path.join(workspace, "root", "var/lib/machines"), 0o700)
if args.bootable:
# We need an initialized machine ID for the boot logic to work
os.mkdir(os.path.join(workspace, "root", "etc"), 0o755)
open(os.path.join(workspace, "root", "etc/machine-id"), "w").write(args.machine_id + "\n")
os.mkdir(os.path.join(workspace, "root", "efi/EFI"), 0o700)
os.mkdir(os.path.join(workspace, "root", "efi/EFI/BOOT"), 0o700)
os.mkdir(os.path.join(workspace, "root", "efi/EFI/Linux"), 0o700)
os.mkdir(os.path.join(workspace, "root", "efi/EFI/systemd"), 0o700)
os.mkdir(os.path.join(workspace, "root", "efi/loader"), 0o700)
os.mkdir(os.path.join(workspace, "root", "efi/loader/entries"), 0o700)
os.mkdir(os.path.join(workspace, "root", "efi", args.machine_id), 0o700)
os.mkdir(os.path.join(workspace, "root", "boot"), 0o700)
os.symlink("../efi", os.path.join(workspace, "root", "boot/efi"))
os.symlink("efi/loader", os.path.join(workspace, "root", "boot/loader"))
os.symlink("efi/" + args.machine_id, os.path.join(workspace, "root", "boot", args.machine_id))
os.mkdir(os.path.join(workspace, "root", "etc/kernel"), 0o755)
with open(os.path.join(workspace, "root", "etc/kernel/cmdline"), "w") as cmdline:
cmdline.write(args.kernel_commandline)
cmdline.write("\n")
if run_build_script:
os.mkdir(os.path.join(workspace, "root", "root"), 0o750)
os.mkdir(os.path.join(workspace, "root", "root/dest"), 0o755)
def patch_file(filepath, line_rewriter):
temp_new_filepath = filepath + ".tmp.new"
with open(filepath, "r") as old:
with open(temp_new_filepath, "w") as new:
for line in old:
new.write(line_rewriter(line))
shutil.copystat(filepath, temp_new_filepath)
os.remove(filepath)
shutil.move(temp_new_filepath, filepath)
def enable_networkd(workspace):
subprocess.run(["systemctl",
"--root", os.path.join(workspace, "root"),
"enable", "systemd-networkd", "systemd-resolved"],
check=True)
os.remove(os.path.join(workspace, "root", "etc/resolv.conf"))
os.symlink("../usr/lib/systemd/resolv.conf", os.path.join(workspace, "root", "etc/resolv.conf"))
patch_file(os.path.join(workspace, "root", "etc/nsswitch.conf"),
lambda line: " ".join(["resolve" if w == "dns" else w for w in line.split(" ")]) if line.startswith("hosts:") else line)
with open(os.path.join(workspace, "root", "etc/systemd/network/all-ethernet.network"), "w") as f:
f.write("""\
[Match]
Type=ether
[Network]
DHCP=yes
""")
def run_workspace_command(args, workspace, *cmd, network=False, env={}):
cmdline = ["systemd-nspawn",
'--quiet',
"--directory=" + os.path.join(workspace, "root"),
"--uuid=" + args.machine_id,
"--as-pid2",
"--register=no",
"--bind=" + var_tmp(workspace) + ":/var/tmp" ]
if not network:
cmdline += ["--private-network"]
cmdline += [ "--setenv={}={}".format(k,v) for k,v in env.items() ]
cmdline += ['--', *cmd]
subprocess.run(cmdline, check=True)
def check_if_url_exists(url):
req = urllib.request.Request(url, method="HEAD")
try:
if urllib.request.urlopen(req):
return True
except:
return False
def disable_kernel_install(args, workspace):
# Let's disable the automatic kernel installation done by the
# kernel RPMs. After all, we want to built our own unified kernels
# that include the root hash in the kernel command line and can be
# signed as a single EFI executable. Since the root hash is only
# known when the root file system is finalized we turn off any
# kernel installation beforehand.
if not args.bootable:
return
for d in ("etc", "etc/kernel", "etc/kernel/install.d"):
try:
os.mkdir(os.path.join(workspace, "root", d), 0o755)
except FileExistsError:
pass
for f in ("50-dracut.install", "51-dracut-rescue.install", "90-loaderentry.install"):
os.symlink("/dev/null", os.path.join(workspace, "root", "etc/kernel/install.d", f))
@complete_step('Installing Fedora')
def install_fedora(args, workspace, run_build_script):
disable_kernel_install(args, workspace)
gpg_key = "/etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-%s-x86_64" % args.release
if os.path.exists(gpg_key):
gpg_key = "file://%s" % gpg_key
else:
gpg_key = "https://getfedora.org/static/%s.txt" % FEDORA_KEYS_MAP[args.release]
if args.mirror:
baseurl = "{args.mirror}/releases/{args.release}/Everything/x86_64/os/".format(args=args)
if not check_if_url_exists("%s/media.repo" % baseurl):
baseurl = "{args.mirror}/development/{args.release}/Everything/x86_64/os/".format(args=args)
release_url = "baseurl=%s" % baseurl
updates_url = "baseurl={args.mirror}/updates/{args.release}/x86_64/".format(args=args)
else:
release_url = ("metalink=https://mirrors.fedoraproject.org/metalink?" +
"repo=fedora-{args.release}&arch=x86_64".format(args=args))
updates_url = ("metalink=https://mirrors.fedoraproject.org/metalink?" +
"repo=updates-released-f{args.release}&arch=x86_64".format(args=args))
with open(os.path.join(workspace, "dnf.conf"), "w") as f:
f.write("""\
[main]
gpgcheck=1
[fedora]
name=Fedora {args.release} - base
{release_url}
gpgkey={gpg_key}
[updates]
name=Fedora {args.release} - updates
{updates_url}
gpgkey={gpg_key}
""".format(args=args,
gpg_key=gpg_key,
release_url=release_url,
updates_url=updates_url))
if args.repositories:
repos = ["--enablerepo=" + repo for repo in args.repositories]
else:
repos = ["--enablerepo=fedora", "--enablerepo=updates"]
root = os.path.join(workspace, "root")
cmdline = ["dnf",
"-y",
"--config=" + os.path.join(workspace, "dnf.conf"),
"--best",
"--allowerasing",
"--releasever=" + args.release,
"--installroot=" + root,
"--disablerepo=*",
*repos,
"--setopt=keepcache=1",
"--setopt=install_weak_deps=0"]
# Turn off docs, but not during the development build, as dnf currently has problems with that
if not args.with_docs and not run_build_script:
cmdline.append("--setopt=tsflags=nodocs")
cmdline.extend([
"install",
"systemd",
"fedora-release",
"passwd"])
if args.packages is not None:
cmdline.extend(args.packages)
if run_build_script and args.build_packages is not None:
cmdline.extend(args.build_packages)
if args.bootable:
cmdline.extend(["kernel", "systemd-udev", "binutils"])
# Temporary hack: dracut only adds crypto support to the initrd, if the cryptsetup binary is installed
if args.encrypt or args.verity:
cmdline.append("cryptsetup")
if args.output_format == OutputFormat.raw_gpt:
cmdline.append("e2fsprogs")
if args.output_format == OutputFormat.raw_btrfs:
cmdline.append("btrfs-progs")
with mount_api_vfs(args, workspace):
subprocess.run(cmdline, check=True)
def install_debian_or_ubuntu(args, workspace, run_build_script, mirror):
if args.repositories:
components = ','.join(args.repositories)
else:
components = 'main'
cmdline = ["debootstrap",
"--verbose",
"--merged-usr",
"--variant=minbase",
"--include=systemd-sysv",
"--exclude=sysv-rc,initscripts,startpar,lsb-base,insserv",
"--components=" + components,
args.release,
workspace + "/root",
mirror]
if args.bootable and args.output_format == OutputFormat.raw_btrfs:
cmdline[3] += ",btrfs-tools"
subprocess.run(cmdline, check=True)
# Debootstrap is not smart enough to deal correctly with alternative dependencies
# Installing libpam-systemd via debootstrap results in systemd-shim being installed
# Therefore, prefer to install via apt from inside the container
extra_packages = [ 'dbus', 'libpam-systemd']
# Also install extra packages via the secondary APT run, because it is smarter and
# can deal better with any conflicts
if args.packages is not None:
extra_packages += args.packages
if run_build_script and args.build_packages is not None:
extra_packages += args.build_packages
# Work around debian bug #835628
os.makedirs(os.path.join(workspace, "root/etc/dracut.conf.d"), exist_ok=True)
with open(os.path.join(workspace, "root/etc/dracut.conf.d/99-generic.conf"), "w") as f:
f.write("hostonly=no")
if args.bootable:
extra_packages += ["linux-image-amd64", "dracut"]
if extra_packages:
# Debian policy is to start daemons by default.
# The policy-rc.d script can be used choose which ones to start
# Let's install one that denies all daemon startups
# See https://people.debian.org/~hmh/invokerc.d-policyrc.d-specification.txt
# Note: despite writing in /usr/sbin, this file is not shipped by the OS
# and instead should be managed by the admin.
policyrcd = os.path.join(workspace, "root/usr/sbin/policy-rc.d")
with open(policyrcd, "w") as f:
f.write("#!/bin/sh\n")
f.write("exit 101")
os.chmod(policyrcd, 0o755)
if not args.with_docs:
# Create dpkg.cfg to ingore documentation
dpkg_conf = os.path.join(workspace, "root/etc/dpkg/dpkg.cfg.d/01_nodoc")
with open(dpkg_conf, "w") as f:
f.writelines([
'path-exclude /usr/share/locale/*\n',
'path-exclude /usr/share/doc/*\n',
'path-exclude /usr/share/man/*\n',
'path-exclude /usr/share/groff/*\n',
'path-exclude /usr/share/info/*\n',
'path-exclude /usr/share/lintian/*\n',
'path-exclude /usr/share/linda/*\n',
])
cmdline = ["/usr/bin/apt-get", "--assume-yes", "--no-install-recommends", "install"] + extra_packages
run_workspace_command(args, workspace, network=True, env={'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true'}, *cmdline)
os.unlink(policyrcd)
@complete_step('Installing Debian')
def install_debian(args, workspace, run_build_script):
install_debian_or_ubuntu(args, workspace, run_build_script, args.mirror)
@complete_step('Installing Ubuntu')
def install_ubuntu(args, workspace, run_build_script):
install_debian_or_ubuntu(args, workspace, run_build_script, args.mirror)
@complete_step('Installing Arch Linux')
def install_arch(args, workspace, run_build_script):
if args.release is not None:
sys.stderr.write("Distribution release specification is not supported for Arch Linux, ignoring.\n")
keyring = "archlinux"
if platform.machine() == "aarch64":
keyring += "arm"
subprocess.run(["pacman-key", "--nocolor", "--init"], check=True)
subprocess.run(["pacman-key", "--nocolor", "--populate", keyring], check=True)
if platform.machine() == "aarch64":
server = "Server = {}/$arch/$repo".format(args.mirror)
else:
server = "Server = {}/$repo/os/$arch".format(args.mirror)
with open(os.path.join(workspace, "pacman.conf"), "w") as f:
f.write("""\
[options]
HookDir = /no_hook/
HoldPkg = pacman glibc
Architecture = auto
CheckSpace
SigLevel = Required DatabaseOptional
[core]
{server}
[extra]
{server}
[community]
{server}
""".format(args=args, server=server))
subprocess.run(["pacman", "--color", "never", "--config", os.path.join(workspace, "pacman.conf"), "-Sy"], check=True)
c = subprocess.run(["pacman", "--color", "never", "--config", os.path.join(workspace, "pacman.conf"), "-Sg", "base"], stdout=subprocess.PIPE, universal_newlines=True, check=True)
packages = set(c.stdout.split())
packages.remove("base")
packages -= {"cryptsetup",
"device-mapper",
"dhcpcd",
"e2fsprogs",
"jfsutils",
"lvm2",
"mdadm",
"netctl",
"pcmciautils",
"reiserfsprogs",
"xfsprogs"}
if args.bootable:
if args.output_format == OutputFormat.raw_gpt:
packages.add("e2fsprogs")
elif args.output_format == OutputFormat.raw_btrfs:
packages.add("btrfs-progs")
else:
if "linux" in packages:
packages.remove("linux")
if args.packages is not None:
packages |= set(args.packages)
if run_build_script and args.build_packages is not None:
packages |= set(args.build_packages)
cmdline = ["pacstrap",
"-C", os.path.join(workspace, "pacman.conf"),
"-c",
"-d",
workspace + "/root"] + \
list(packages)
subprocess.run(cmdline, check=True)
enable_networkd(workspace)
@complete_step('Installing openSUSE')
def install_opensuse(args, workspace, run_build_script):
root = os.path.join(workspace, "root")
release = args.release.strip('"')
#
# If the release looks like a timestamp, it's Tumbleweed.
# 13.x is legacy (14.x won't ever appear). For anything else,
# let's default to Leap.
#
if release.isdigit() or release == "tumbleweed":
release_url = "{}/tumbleweed/repo/oss/".format(args.mirror)
updates_url = "{}/update/tumbleweed/".format(args.mirror)
elif release.startswith("13."):
release_url = "{}/distribution/{}/repo/oss/".format(args.mirror, release)
updates_url = "{}/update/{}/".format(args.mirror, release)
else:
release_url = "{}/distribution/leap/{}/repo/oss/".format(args.mirror, release)
updates_url = "{}/update/leap/{}/oss/".format(args.mirror, release)
#
# Configure the repositories: we need to enable packages caching
# here to make sure that the package cache stays populated after
# "zypper install".
#
subprocess.run(["zypper", "--root", root, "addrepo", "-ck", release_url, "Main"], check=True)
subprocess.run(["zypper", "--root", root, "addrepo", "-ck", updates_url, "Updates"], check=True)
if not args.with_docs:
with open(os.path.join(root, "etc/zypp/zypp.conf"), "w") as f:
f.write("rpm.install.excludedocs = yes\n")
# The common part of the install comand.
cmdline = ["zypper", "--root", root, "--gpg-auto-import-keys",
"install", "-y", "--no-recommends"]
#
# Install the "minimal" package set.
#
subprocess.run(cmdline + ["-t", "pattern", "minimal_base"], check=True)
#
# Now install the additional packages if necessary.
#
extra_packages = []
if args.bootable:
extra_packages += ["kernel-default"]
if args.encrypt:
extra_packages += ["device-mapper"]
if args.output_format in (OutputFormat.subvolume, OutputFormat.raw_btrfs):
extra_packages += ["btrfsprogs"]
if args.packages:
extra_packages += args.packages
if run_build_script and args.build_packages is not None:
extra_packages += args.build_packages
if extra_packages:
subprocess.run(cmdline + extra_packages, check=True)
#
# Disable packages caching in the image that was enabled
# previously to populate the package cache.
#
subprocess.run(["zypper", "--root", root, "modifyrepo", "-K", "Main"], check=True)
subprocess.run(["zypper", "--root", root, "modifyrepo", "-K", "Updates"], check=True)
#
# Tune dracut confs: openSUSE uses an old version of dracut that's
# probably explain why we need to do those hacks.
#
if args.bootable:
os.makedirs(os.path.join(root, "etc/dracut.conf.d"), exist_ok=True)
with open(os.path.join(root, "etc/dracut.conf.d/99-mkosi.conf"), "w") as f:
f.write("hostonly=no\n")
# dracut from openSUSE is missing upstream commit 016613c774baf.