-
Notifications
You must be signed in to change notification settings - Fork 0
/
mkosi
executable file
·3690 lines (2925 loc) · 129 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
# PYTHON_ARGCOMPLETE_OK
# SPDX-License-Identifier: LGPL-2.1+
import argparse
import configparser
import contextlib
import collections
import crypt
import ctypes, ctypes.util
import errno
import fcntl
import getpass
import glob
import hashlib
import os
import platform
import re
import shutil
import stat
import string
import sys
import tempfile
import urllib.request
import uuid
try:
import argcomplete
except ImportError:
pass
from enum import Enum
from subprocess import run, DEVNULL, PIPE
__version__ = '4'
if sys.version_info < (3, 5):
sys.exit("Sorry, we need at least Python 3.5.")
# TODO
# - volatile images
# - make 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)
def warn(message, *args, **kwargs):
sys.stderr.write('WARNING: ' + message.format(*args, **kwargs) + '\n')
class OutputFormat(Enum):
raw_ext4 = 1
raw_gpt = 1 # Kept for backwards compatibility
raw_btrfs = 2
raw_squashfs = 3
directory = 4
subvolume = 5
tar = 6
raw_xfs = 7
RAW_RW_FS_FORMATS = (
OutputFormat.raw_ext4,
OutputFormat.raw_btrfs,
OutputFormat.raw_xfs
)
RAW_FORMATS = (*RAW_RW_FS_FORMATS, OutputFormat.raw_squashfs)
class Distribution(Enum):
fedora = 1
debian = 2
ubuntu = 3
arch = 4
opensuse = 5
mageia = 6
centos = 7
clear = 8
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")
CLONE_NEWNS = 0x00020000
FEDORA_KEYS_MAP = {
'23': '34EC9CBA',
'24': '81B46521',
'25': 'FDB19C98',
'26': '64DAB85D',
'27': 'F5282EE4',
'28': '9DB62FB1',
}
# 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
GPTRootTypePair = collections.namedtuple('GPTRootTypePair', 'root verity')
def gpt_root_native():
"""The tag for the native GPT root partition
Returns a tuple of two tags: for the root partition and for the
matching verity partition.
"""
if platform.machine() == "x86_64":
return GPTRootTypePair(GPT_ROOT_X86_64, GPT_ROOT_X86_64_VERITY)
elif platform.machine() == "aarch64":
return GPTRootTypePair(GPT_ROOT_ARM_64, GPT_ROOT_ARM_64_VERITY)
else:
die("Unknown architecture {}.".format(platform.machine()))
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")
def mkdir_last(path, mode=0o777):
"""Create directory path
Only the final component will be created, so this is different than mkdirs().
"""
try:
os.mkdir(path, mode)
except FileExistsError:
if not os.path.isdir(path):
raise
return path
_IOC_NRBITS = 8
_IOC_TYPEBITS = 8
_IOC_SIZEBITS = 14
_IOC_DIRBITS = 2
_IOC_NRSHIFT = 0
_IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS
_IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS
_IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS
_IOC_NONE = 0
_IOC_WRITE = 1
_IOC_READ = 2
def _IOC(dir, type, nr, argtype):
size = {'int':4, 'size_t':8}[argtype]
return dir<<_IOC_DIRSHIFT | type<<_IOC_TYPESHIFT | nr<<_IOC_NRSHIFT | size<<_IOC_SIZESHIFT
def _IOW(type, nr, size):
return _IOC(_IOC_WRITE, type, nr, size)
FICLONE = _IOW(0x94, 9, 'int')
@contextlib.contextmanager
def open_close(path, flags, mode=0o664):
fd = os.open(path, flags | os.O_CLOEXEC, mode)
try:
yield fd
finally:
os.close(fd)
def _reflink(oldfd, newfd):
fcntl.ioctl(newfd, FICLONE, oldfd)
def copy_fd(oldfd, newfd):
try:
_reflink(oldfd, newfd)
except OSError as e:
if e.errno not in {errno.EXDEV, errno.EOPNOTSUPP}:
raise
shutil.copyfileobj(open(oldfd, 'rb', closefd=False),
open(newfd, 'wb', closefd=False))
def copy_file_object(oldobject, newobject):
try:
_reflink(oldobject.fileno(), newobject.fileno())
except OSError as e:
if e.errno not in {errno.EXDEV, errno.EOPNOTSUPP}:
raise
shutil.copyfileobj(oldobject, newobject)
def copy_symlink(oldpath, newpath):
src = os.readlink(oldpath)
os.symlink(src, newpath)
def copy_file(oldpath, newpath):
if os.path.islink(oldpath):
copy_symlink(oldpath, newpath)
return
with open_close(oldpath, os.O_RDONLY) as oldfd:
st = os.stat(oldfd)
try:
with open_close(newpath, os.O_WRONLY|os.O_CREAT|os.O_EXCL, st.st_mode) as newfd:
copy_fd(oldfd, newfd)
except FileExistsError:
os.unlink(newpath)
with open_close(newpath, os.O_WRONLY|os.O_CREAT, st.st_mode) as newfd:
copy_fd(oldfd, newfd)
shutil.copystat(oldpath, newpath, follow_symlinks=False)
def symlink_f(target, path):
try:
os.symlink(target, path)
except FileExistsError:
os.unlink(path)
os.symlink(target, path)
def copy(oldpath, newpath):
try:
mkdir_last(newpath)
except FileExistsError:
# something that is not a directory already exists
os.unlink(newpath)
mkdir_last(newpath)
for entry in os.scandir(oldpath):
newentry = os.path.join(newpath, entry.name)
if entry.is_dir(follow_symlinks=False):
copy(entry.path, newentry)
elif entry.is_symlink():
target = os.readlink(entry.path)
symlink_f(target, newentry)
shutil.copystat(entry.path, newentry, follow_symlinks=False)
else:
st = entry.stat(follow_symlinks=False)
if stat.S_ISREG(st.st_mode):
copy_file(entry.path, newentry)
else:
print('Ignoring', entry.path)
continue
shutil.copystat(oldpath, newpath, follow_symlinks=True)
@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)
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)
run(["btrfs", "subvol", "create", path], check=True)
os.umask(m)
def btrfs_subvol_delete(path):
# Extract the path of the subvolume relative to the filesystem
c = run(["btrfs", "subvol", "show", path],
stdout=PIPE, stderr=DEVNULL, universal_newlines=True, check=True)
subvol_path = c.stdout.splitlines()[0]
# Make the subvolume RW again if it was set RO by btrfs_subvol_delete
run(["btrfs", "property", "set", path, "ro", "false"], check=True)
# Recursively delete the direct children of the subvolume
c = run(["btrfs", "subvol", "list", "-o", path],
stdout=PIPE, stderr=DEVNULL, universal_newlines=True, check=True)
for line in c.stdout.splitlines():
if not line:
continue
child_subvol_path = line.split(" ", 8)[-1]
child_path = os.path.normpath(os.path.join(
path,
os.path.relpath(child_subvol_path, subvol_path)
))
btrfs_subvol_delete(child_path)
# Delete the subvolume now that all its descendants have been deleted
run(["btrfs", "subvol", "delete", path], stdout=DEVNULL, stderr=DEVNULL, check=True)
def btrfs_subvol_make_ro(path, b=True):
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 disable_cow(path):
"""Disable copy-on-write if applicable on filesystem"""
run(["chattr", "+C", path], stdout=DEVNULL, stderr=DEVNULL, check=False)
def determine_partition_table(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().root,
"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
return table, run_sfdisk
def create_image(args, workspace, for_cache):
if args.output_format not in RAW_FORMATS:
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-', delete=not for_cache)
output.append(f)
disable_cow(f.name)
f.truncate(image_size(args))
table, run_sfdisk = determine_partition_table(args)
if run_sfdisk:
run(["sfdisk", "--color=never", f.name], input=table.encode("utf-8"), check=True)
run(["sync"])
args.ran_sfdisk = run_sfdisk
return f
def reuse_cache_image(args, workspace, run_build_script, for_cache):
if not args.incremental:
return None, False
if args.output_format not in RAW_RW_FS_FORMATS:
return None, False
fname = args.cache_pre_dev if run_build_script else args.cache_pre_inst
if for_cache:
if fname and os.path.exists(fname):
# Cache already generated, skip generation, note that manually removing the exising cache images is
# necessary if Packages or BuildPackages change
return None, True
else:
return None, False
if fname is None:
return None, False
with complete_step('Basing off cached image ' + fname,
'Copied cached image as {.name}') as output:
try:
source = open(fname, 'rb')
except FileNotFoundError:
return None, False
with source:
f = tempfile.NamedTemporaryFile(dir = os.path.dirname(args.output), prefix='.mkosi-')
output.append(f)
# So on one hand we want CoW off, since this stuff will
# have a lot of random write accesses. On the other we
# want the copy to be snappy, hence we do want CoW. Let's
# ask for both, and let the kernel figure things out:
# let's turn off CoW on the file, but start with a CoW
# copy. On btrfs that works: the initial copy is made as
# CoW but later changes do not result in CoW anymore.
disable_cow(f.name)
copy_file_object(source, f)
table, run_sfdisk = determine_partition_table(args)
args.ran_sfdisk = run_sfdisk
return f, True
@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 = run(["losetup", "--find", "--show", "--partscan", raw.name],
stdout=PIPE, check=True)
loopdev = c.stdout.decode("utf-8").strip()
output.append(loopdev)
try:
yield loopdev
finally:
with complete_step('Detaching image file'):
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, cached):
if loopdev is None:
return
if cached:
return
if args.swap_partno is None:
return
with complete_step('Formatting swap partition'):
run(["mkswap", "-Lswap", partition(loopdev, args.swap_partno)], check=True)
def prepare_esp(args, loopdev, cached):
if loopdev is None:
return
if cached:
return
if args.esp_partno is None:
return
with complete_step('Formatting ESP partition'):
run(["mkfs.fat", "-nEFI", "-F32", partition(loopdev, args.esp_partno)], check=True)
def mkfs_ext4(label, mount, dev):
run(["mkfs.ext4", "-L", label, "-M", mount, dev], check=True)
def mkfs_btrfs(label, dev):
run(["mkfs.btrfs", "-L", label, "-d", "single", "-m", "single", dev], check=True)
def mkfs_xfs(label, dev):
run(["mkfs.xfs", "-n", "ftype=1", "-L", label, dev], check=True)
def luks_format(dev, passphrase):
if passphrase['type'] == 'stdin':
passphrase = (passphrase['content'] + "\n").encode("utf-8")
run(["cryptsetup", "luksFormat", "--batch-mode", dev], input=passphrase, check=True)
else:
assert passphrase['type'] == 'file'
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")
run(["cryptsetup", "open", "--type", "luks", dev, name], input=passphrase, check=True)
else:
assert passphrase['type'] == 'file'
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):
run(["cryptsetup", "close", dev], check=True)
def luks_format_root(args, loopdev, run_build_script, cached, 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
if cached:
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, cached):
if args.encrypt is None:
return
if args.home_partno is None:
return
if run_build_script:
return
if cached:
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, cached):
if args.encrypt is None:
return
if args.srv_partno is None:
return
if run_build_script:
return
if cached:
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 None
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, cached):
if dev is None:
return
if args.output_format == OutputFormat.raw_squashfs:
return
if cached:
return
with complete_step('Formatting root partition'):
if args.output_format == OutputFormat.raw_btrfs:
mkfs_btrfs("root", dev)
elif args.output_format == OutputFormat.raw_xfs:
mkfs_xfs("root", dev)
else:
mkfs_ext4("root", "/", dev)
def prepare_home(args, dev, cached):
if dev is None:
return
if cached:
return
with complete_step('Formatting home partition'):
mkfs_ext4("home", "/home", dev)
def prepare_srv(args, dev, cached):
if dev is None:
return
if cached:
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"
run(["mount", "-n", dev, where, options], check=True)
def mount_bind(what, where):
os.makedirs(what, 0o755, True)
os.makedirs(where, 0o755, True)
run(["mount", "--bind", what, where], check=True)
def mount_tmpfs(where):
os.makedirs(where, 0o755, True)
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", "run", "tmp"):
umount(os.path.join(root, d))
umount(root)
@complete_step("Assigning hostname")
def install_etc_hostname(args, workspace):
etc_hostname = os.path.join(workspace, "root", "etc/hostname")
# Always unlink first, so that we don't get in trouble due to a
# symlink or suchlike. Also if no hostname is configured we really
# don't want the file to exist, so that systemd's implicit
# hostname logic can take effect.
try:
os.unlink(etc_hostname)
except FileNotFoundError:
pass
if args.hostname:
open(etc_hostname, "w").write(args.hostname + "\n")
@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 in (Distribution.fedora, Distribution.mageia):
mount_bind(args.cache_path, os.path.join(workspace, "root", "var/cache/dnf"))
elif args.distribution == Distribution.centos:
# We mount both the YUM and the DNF cache in this case, as YUM might just be redirected to DNF even if we invoke the former
mount_bind(os.path.join(args.cache_path, "yum"), os.path.join(workspace, "root", "var/cache/yum"))
mount_bind(os.path.join(args.cache_path, "dnf"), 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.arch:
mount_bind(args.cache_path, os.path.join(workspace, "root", "var/cache/pacman/pkg"))
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/yum", "var/cache/apt/archives", "var/cache/pacman/pkg", "var/cache/zypp/packages"):
umount(os.path.join(workspace, "root", d))
def umount(where):
# Ignore failures and error messages
run(["umount", "-n", where], stdout=DEVNULL, stderr=DEVNULL)
@complete_step('Setting up basic OS tree')
def prepare_tree(args, workspace, run_build_script, cached):
if args.output_format == OutputFormat.subvolume:
btrfs_subvol_create(os.path.join(workspace, "root"))
else:
mkdir_last(os.path.join(workspace, "root"))
if args.output_format in (OutputFormat.subvolume, OutputFormat.raw_btrfs):
if cached and args.output_format is OutputFormat.raw_btrfs:
return
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 cached:
return
if args.bootable:
# We need an initialized machine ID for the boot logic to work
os.mkdir(os.path.join(workspace, "root", "etc"), 0o755)
with open(os.path.join(workspace, "root", "etc/machine-id"), "w") as f:
f.write(args.machine_id)
f.write("\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)
if args.build_dir is not None:
os.mkdir(os.path.join(workspace, "root", "root/build"), 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):
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("../run/systemd/resolve/stub-resolv.conf", os.path.join(workspace, "root", "etc/resolv.conf"))
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 enable_networkmanager(workspace):
run(["systemctl",
"--root", os.path.join(workspace, "root"),
"enable", "NetworkManager"],
check=True)
def run_workspace_command(args, workspace, *cmd, network=False, env={}, nspawn_params=[]):
cmdline = ["systemd-nspawn",
'--quiet',
"--directory=" + os.path.join(workspace, "root"),
"--uuid=" + args.machine_id,
"--machine=mkosi-" + uuid.uuid4().hex,
"--as-pid2",
"--register=no",
"--bind=" + var_tmp(workspace) + ":/var/tmp" ]
if network:
# If we're using the host network namespace, use the same resolver
cmdline += ["--bind-ro=/etc/resolv.conf"]
else:
cmdline += ["--private-network"]
cmdline += [ "--setenv={}={}".format(k,v) for k,v in env.items() ]
if nspawn_params:
cmdline += nspawn_params
cmdline += ['--', *cmd]
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"):
mkdir_last(os.path.join(workspace, "root", d), 0o755)
masked = []
for f in ("50-dracut.install", "51-dracut-rescue.install", "90-loaderentry.install"):
path = os.path.join(workspace, "root", "etc/kernel/install.d", f)
os.symlink("/dev/null", path)
masked += [path]
return masked
def reenable_kernel_install(args, workspace, masked):
# Undo disable_kernel_install() so the final image can be used
# with scripts installing a kernel following the Bootloader Spec
if not args.bootable:
return
for f in masked:
os.unlink(f)
def invoke_dnf(args, workspace, repositories, base_packages, boot_packages, config_file):
repos = ["--enablerepo=" + repo for repo in repositories]
root = os.path.join(workspace, "root")
cmdline = ["dnf",
"-y",
"--config=" + config_file,
"--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",
*base_packages
])
cmdline.extend(args.packages)
if run_build_script: