forked from archlinux/archinstall
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstaller.py
More file actions
2096 lines (1689 loc) · 68.9 KB
/
installer.py
File metadata and controls
2096 lines (1689 loc) · 68.9 KB
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
import os
import platform
import re
import shlex
import subprocess
import textwrap
import time
from collections.abc import Callable
from pathlib import Path
from subprocess import CalledProcessError
from types import TracebackType
from typing import Any, Self
from archinstall.lib.boot import Boot
from archinstall.lib.command import SysCommand, run
from archinstall.lib.disk.fido import Fido2
from archinstall.lib.disk.luks import Luks2, unlock_luks2_dev
from archinstall.lib.disk.lvm import lvm_import_vg, lvm_pvseg_info, lvm_vol_change
from archinstall.lib.disk.utils import (
get_lsblk_by_mountpoint,
get_lsblk_info,
get_parent_device_path,
get_unique_path_for_device,
mount,
swapon,
)
from archinstall.lib.exceptions import DiskError, HardwareIncompatibilityError, RequirementError, ServiceException, SysCallError
from archinstall.lib.hardware import SysInfo
from archinstall.lib.linux_path import LPath
from archinstall.lib.locale.utils import verify_keyboard_layout, verify_x11_keyboard_layout
from archinstall.lib.mirror.mirror_handler import MirrorListHandler
from archinstall.lib.models.application import ZramAlgorithm
from archinstall.lib.models.bootloader import Bootloader
from archinstall.lib.models.device import (
DiskEncryption,
DiskLayoutConfiguration,
EncryptionType,
FilesystemType,
LvmVolume,
PartitionModification,
SectorSize,
Size,
SnapshotType,
SubvolumeModification,
Unit,
)
from archinstall.lib.models.locale import LocaleConfiguration
from archinstall.lib.models.mirrors import MirrorConfiguration
from archinstall.lib.models.network import Nic
from archinstall.lib.models.packages import Repository
from archinstall.lib.models.pacman import PacmanConfiguration
from archinstall.lib.models.users import User
from archinstall.lib.output import debug, error, info, log, logger, warn
from archinstall.lib.packages.packages import installed_package
from archinstall.lib.pacman.config import PacmanConfig
from archinstall.lib.pacman.pacman import Pacman
from archinstall.lib.pathnames import MIRRORLIST, PACMAN_CONF
from archinstall.lib.plugins import plugins
from archinstall.lib.translationhandler import tr
# Any package that the Installer() is responsible for (optional and the default ones)
__packages__ = ['base', 'sudo', 'linux-firmware', 'linux', 'linux-lts', 'linux-zen', 'linux-hardened']
# Additional packages that are installed if the user is running the Live ISO with accessibility tools enabled
__accessibility_packages__ = ['brltty', 'espeakup', 'alsa-utils']
class Installer:
def __init__(
self,
target: Path,
disk_config: DiskLayoutConfiguration,
base_packages: list[str] = [],
kernels: list[str] | None = None,
silent: bool = False,
):
"""
`Installer()` is the wrapper for most basic installation steps.
It also wraps :py:func:`~archinstall.Installer.pacstrap` among other things.
"""
self._base_packages = base_packages or __packages__[:3]
self.kernels = kernels or ['linux']
self._disk_config = disk_config
self._disk_encryption = disk_config.disk_encryption or DiskEncryption(EncryptionType.NO_ENCRYPTION)
self.target: Path = target
self.init_time = time.strftime('%Y-%m-%d_%H-%M-%S')
self._helper_flags: dict[str, str | bool | None] = {
'base': False,
'bootloader': None,
}
for kernel in self.kernels:
self._base_packages.append(kernel)
# If using accessibility tools in the live environment, append those to the packages list
if accessibility_tools_in_use():
self._base_packages.extend(__accessibility_packages__)
self.post_base_install: list[Callable] = [] # type: ignore[type-arg]
self._modules: list[str] = []
self._binaries: list[str] = []
self._files: list[str] = []
# systemd, sd-vconsole and sd-encrypt will be replaced by udev, keymap and encrypt
# if HSM is not used to encrypt the root volume. Check mkinitcpio() function for that override.
self._hooks: list[str] = [
'base',
'systemd',
'autodetect',
'microcode',
'modconf',
'kms',
'keyboard',
'sd-vconsole',
'block',
'filesystems',
'fsck',
]
self._kernel_params: list[str] = []
self._fstab_entries: list[str] = []
self._zram_enabled = False
self._disable_fstrim = False
self.pacman = Pacman(self.target, silent)
def __enter__(self) -> Self:
return self
def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> bool | None:
if exc_type is not None:
error(str(exc_value))
self.sync_log_to_install_medium()
# We avoid printing /mnt/<log path> because that might confuse people if they note it down
# and then reboot, and an identical log file will be found in the ISO medium anyway.
print(tr('[!] A log file has been created here: {}').format(logger.path))
print(tr('Please submit this issue (and file) to https://github.com/archlinux/archinstall/issues'))
# Return None to propagate the exception
return None
info(tr('Syncing the system...'))
os.sync()
if not (missing_steps := self.post_install_check()):
msg = f'Installation completed without any errors.\nLog files temporarily available at {logger.directory}.\nYou may reboot when ready.\n'
log(msg, fg='green')
self.sync_log_to_install_medium()
return True
else:
warn('Some required steps were not successfully installed/configured before leaving the installer:')
for step in missing_steps:
warn(f' - {step}')
warn(f'Detailed error logs can be found at: {logger.directory}')
warn('Submit this zip file as an issue to https://github.com/archlinux/archinstall/issues')
self.sync_log_to_install_medium()
return False
def remove_mod(self, mod: str) -> None:
if mod in self._modules:
self._modules.remove(mod)
def append_mod(self, mod: str) -> None:
if mod not in self._modules:
self._modules.append(mod)
def _verify_service_stop(self, offline: bool, skip_ntp: bool, skip_wkd: bool) -> None:
"""
Certain services might be running that affects the system during installation.
One such service is "reflector.service" which updates /etc/pacman.d/mirrorlist
We need to wait for it before we continue since we opted in to use a custom mirror/region.
"""
if not skip_ntp:
info(tr('Waiting for time sync (timedatectl show) to complete.'))
started_wait = time.time()
notified = False
while True:
if not notified and time.time() - started_wait > 5:
notified = True
warn(tr('Time synchronization not completing, while you wait - check the docs for workarounds: https://archinstall.readthedocs.io/'))
time_val = SysCommand('timedatectl show --property=NTPSynchronized --value').decode()
if time_val and time_val.strip() == 'yes':
break
time.sleep(1)
else:
info(tr('Skipping waiting for automatic time sync (this can cause issues if time is out of sync during installation)'))
if not offline:
info('Waiting for automatic mirror selection (reflector) to complete.')
for _ in range(60):
if self._service_state('reflector') in ('dead', 'failed', 'exited'):
break
time.sleep(1)
else:
warn('Reflector did not complete within 60 seconds, continuing anyway...')
else:
info('Skipped reflector...')
# info('Waiting for pacman-init.service to complete.')
# while self._service_state('pacman-init') not in ('dead', 'failed', 'exited'):
# time.sleep(1)
if not skip_wkd:
info(tr('Waiting for Arch Linux keyring sync (archlinux-keyring-wkd-sync) to complete.'))
# Wait for the timer to kick in
while self._service_started('archlinux-keyring-wkd-sync.timer') is None:
time.sleep(1)
# Wait for the service to enter a finished state
while self._service_state('archlinux-keyring-wkd-sync.service') not in ('dead', 'failed', 'exited'):
time.sleep(1)
def _verify_boot_part(self) -> None:
"""
Check that mounted /boot device has at minimum size for installation
The reason this check is here is to catch pre-mounted device configuration and potentially
configured one that has not gone through any previous checks (e.g. --silence mode)
NOTE: this function should be run AFTER running the mount_ordered_layout function
"""
boot_mount = self.target / 'boot'
lsblk_info = get_lsblk_by_mountpoint(boot_mount)
if len(lsblk_info) > 0:
if lsblk_info[0].size < Size(200, Unit.MiB, SectorSize.default()):
raise DiskError(
f'The boot partition mounted at {boot_mount} is not large enough to install a boot loader. '
f'Please resize it to at least 200MiB and re-run the installation.',
)
def sanity_check(
self,
offline: bool = False,
skip_ntp: bool = False,
skip_wkd: bool = False,
) -> None:
# self._verify_boot_part()
self._verify_service_stop(offline, skip_ntp, skip_wkd)
def mount_ordered_layout(self) -> None:
debug('Mounting ordered layout')
luks_handlers: dict[Any, Luks2] = {}
match self._disk_encryption.encryption_type:
case EncryptionType.NO_ENCRYPTION:
self._import_lvm()
self._mount_lvm_layout()
case EncryptionType.LUKS:
luks_handlers = self._prepare_luks_partitions(self._disk_encryption.partitions)
case EncryptionType.LVM_ON_LUKS:
luks_handlers = self._prepare_luks_partitions(self._disk_encryption.partitions)
self._import_lvm()
self._mount_lvm_layout(luks_handlers)
case EncryptionType.LUKS_ON_LVM:
self._import_lvm()
luks_handlers = self._prepare_luks_lvm(self._disk_encryption.lvm_volumes)
self._mount_lvm_layout(luks_handlers)
# mount all regular partitions
self._mount_partition_layout(luks_handlers)
def _mount_partition_layout(self, luks_handlers: dict[Any, Luks2]) -> None:
debug('Mounting partition layout')
# do not mount any PVs part of the LVM configuration
pvs = []
if self._disk_config.lvm_config:
pvs = self._disk_config.lvm_config.get_all_pvs()
sorted_device_mods = self._disk_config.device_modifications.copy()
# move the device with the root partition to the beginning of the list
for mod in self._disk_config.device_modifications:
if any(partition.is_root() for partition in mod.partitions):
sorted_device_mods.remove(mod)
sorted_device_mods.insert(0, mod)
break
for mod in sorted_device_mods:
not_pv_part_mods = [p for p in mod.partitions if p not in pvs]
# partitions have to mounted in the right order on btrfs the mountpoint will
# be empty as the actual subvolumes are getting mounted instead so we'll use
# '/' just for sorting
sorted_part_mods = sorted(not_pv_part_mods, key=lambda x: x.mountpoint or Path('/'))
for part_mod in sorted_part_mods:
if luks_handler := luks_handlers.get(part_mod):
self._mount_luks_partition(part_mod, luks_handler)
else:
self._mount_partition(part_mod)
def _mount_lvm_layout(self, luks_handlers: dict[Any, Luks2] = {}) -> None:
lvm_config = self._disk_config.lvm_config
if not lvm_config:
debug('No lvm config defined to be mounted')
return
debug('Mounting LVM layout')
for vg in lvm_config.vol_groups:
sorted_vol = sorted(vg.volumes, key=lambda x: x.mountpoint or Path('/'))
for vol in sorted_vol:
if luks_handler := luks_handlers.get(vol):
self._mount_luks_volume(vol, luks_handler)
else:
self._mount_lvm_vol(vol)
def _prepare_luks_partitions(
self,
partitions: list[PartitionModification],
) -> dict[PartitionModification, Luks2]:
return {
part_mod: unlock_luks2_dev(
part_mod.dev_path,
part_mod.mapper_name,
self._disk_encryption.encryption_password,
)
for part_mod in partitions
if part_mod.mapper_name and part_mod.dev_path
}
def _import_lvm(self) -> None:
lvm_config = self._disk_config.lvm_config
if not lvm_config:
debug('No lvm config defined to be imported')
return
for vg in lvm_config.vol_groups:
lvm_import_vg(vg)
for vol in vg.volumes:
lvm_vol_change(vol, True)
def _prepare_luks_lvm(
self,
lvm_volumes: list[LvmVolume],
) -> dict[LvmVolume, Luks2]:
return {
vol: unlock_luks2_dev(
vol.dev_path,
vol.mapper_name,
self._disk_encryption.encryption_password,
)
for vol in lvm_volumes
if vol.mapper_name and vol.dev_path
}
def _mount_partition(self, part_mod: PartitionModification) -> None:
if not part_mod.dev_path:
return
# it would be none if it's btrfs as the subvolumes will have the mountpoints defined
if part_mod.mountpoint:
target = self.target / part_mod.relative_mountpoint
mount(part_mod.dev_path, target, options=part_mod.mount_options)
elif part_mod.fs_type == FilesystemType.BTRFS:
# Only mount BTRFS subvolumes that have mountpoints specified
subvols_with_mountpoints = [sv for sv in part_mod.btrfs_subvols if sv.mountpoint is not None]
if subvols_with_mountpoints:
self._mount_btrfs_subvol(
part_mod.dev_path,
part_mod.btrfs_subvols,
part_mod.mount_options,
)
elif part_mod.is_swap():
swapon(part_mod.dev_path)
def _mount_lvm_vol(self, volume: LvmVolume) -> None:
if volume.fs_type != FilesystemType.BTRFS:
if volume.mountpoint and volume.dev_path:
target = self.target / volume.relative_mountpoint
mount(volume.dev_path, target, options=volume.mount_options)
if volume.fs_type == FilesystemType.BTRFS and volume.dev_path:
# Only mount BTRFS subvolumes that have mountpoints specified
subvols_with_mountpoints = [sv for sv in volume.btrfs_subvols if sv.mountpoint is not None]
if subvols_with_mountpoints:
self._mount_btrfs_subvol(volume.dev_path, volume.btrfs_subvols, volume.mount_options)
def _mount_luks_partition(self, part_mod: PartitionModification, luks_handler: Luks2) -> None:
if not luks_handler.mapper_dev:
return None
if part_mod.fs_type == FilesystemType.BTRFS and part_mod.btrfs_subvols:
# Only mount BTRFS subvolumes that have mountpoints specified
subvols_with_mountpoints = [sv for sv in part_mod.btrfs_subvols if sv.mountpoint is not None]
if subvols_with_mountpoints:
self._mount_btrfs_subvol(luks_handler.mapper_dev, part_mod.btrfs_subvols, part_mod.mount_options)
elif part_mod.mountpoint:
target = self.target / part_mod.relative_mountpoint
mount(luks_handler.mapper_dev, target, options=part_mod.mount_options)
def _mount_luks_volume(self, volume: LvmVolume, luks_handler: Luks2) -> None:
if volume.fs_type != FilesystemType.BTRFS:
if volume.mountpoint and luks_handler.mapper_dev:
target = self.target / volume.relative_mountpoint
mount(luks_handler.mapper_dev, target, options=volume.mount_options)
if volume.fs_type == FilesystemType.BTRFS and luks_handler.mapper_dev:
# Only mount BTRFS subvolumes that have mountpoints specified
subvols_with_mountpoints = [sv for sv in volume.btrfs_subvols if sv.mountpoint is not None]
if subvols_with_mountpoints:
self._mount_btrfs_subvol(luks_handler.mapper_dev, volume.btrfs_subvols, volume.mount_options)
def _mount_btrfs_subvol(
self,
dev_path: Path,
subvolumes: list[SubvolumeModification],
mount_options: list[str] = [],
) -> None:
# Filter out subvolumes without mountpoints to avoid errors when sorting
subvols_with_mountpoints = [sv for sv in subvolumes if sv.mountpoint is not None]
for subvol in sorted(subvols_with_mountpoints, key=lambda x: x.relative_mountpoint):
mountpoint = self.target / subvol.relative_mountpoint
options = mount_options + [f'subvol={subvol.name}']
mount(dev_path, mountpoint, options=options)
def generate_key_files(self) -> None:
match self._disk_encryption.encryption_type:
case EncryptionType.LUKS:
self._generate_key_files_partitions()
case EncryptionType.LUKS_ON_LVM:
self._generate_key_file_lvm_volumes()
case EncryptionType.LVM_ON_LUKS:
# currently LvmOnLuks only supports a single
# partitioning layout (boot + partition)
# so we won't need any keyfile generation atm
pass
def _generate_key_files_partitions(self) -> None:
root_is_encrypted = any(p.is_root() for p in self._disk_encryption.partitions)
for part_mod in self._disk_encryption.partitions:
gen_enc_file = self._disk_encryption.should_generate_encryption_file(part_mod)
luks_handler = Luks2(
part_mod.safe_dev_path,
mapper_name=part_mod.mapper_name,
password=self._disk_encryption.encryption_password,
)
if gen_enc_file and not part_mod.is_root():
if root_is_encrypted:
debug(f'Creating key-file: {part_mod.dev_path}')
luks_handler.create_keyfile(self.target)
else:
debug(f'Adding passphrase-based crypttab entry for {part_mod.dev_path}')
luks_handler.create_crypttab_entry(self.target)
if part_mod.is_root() and not gen_enc_file:
if self._disk_encryption.hsm_device:
if self._disk_encryption.encryption_password:
Fido2.fido2_enroll(
self._disk_encryption.hsm_device,
part_mod.safe_dev_path,
self._disk_encryption.encryption_password,
)
def _generate_key_file_lvm_volumes(self) -> None:
root_is_encrypted = any(v.is_root() for v in self._disk_encryption.lvm_volumes)
for vol in self._disk_encryption.lvm_volumes:
gen_enc_file = self._disk_encryption.should_generate_encryption_file(vol)
luks_handler = Luks2(
vol.safe_dev_path,
mapper_name=vol.mapper_name,
password=self._disk_encryption.encryption_password,
)
if gen_enc_file and not vol.is_root():
if root_is_encrypted:
info(f'Creating key-file: {vol.dev_path}')
luks_handler.create_keyfile(self.target)
else:
info(f'Adding passphrase-based crypttab entry for {vol.dev_path}')
luks_handler.create_crypttab_entry(self.target)
if vol.is_root() and not gen_enc_file:
if self._disk_encryption.hsm_device:
if self._disk_encryption.encryption_password:
Fido2.fido2_enroll(
self._disk_encryption.hsm_device,
vol.safe_dev_path,
self._disk_encryption.encryption_password,
)
def sync_log_to_install_medium(self) -> bool:
# Copy over the install log (if there is one) to the install medium if
# at least the base has been strapped in, otherwise we won't have a filesystem/structure to copy to.
if self._helper_flags.get('base-strapped', False) is True:
absolute_logfile = logger.path
logfile_target = self.target / absolute_logfile
logfile_target.parent.mkdir(parents=True, exist_ok=True)
absolute_logfile.copy(logfile_target, preserve_metadata=True)
return True
def add_swapfile(self, size: str = '4G', enable_resume: bool = True, file: str = '/swapfile') -> None:
if file[:1] != '/':
file = f'/{file}'
if len(file.strip()) <= 0 or file == '/':
raise ValueError(f'The filename for the swap file has to be a valid path, not: {self.target}{file}')
SysCommand(f'dd if=/dev/zero of={self.target}{file} bs={size} count=1')
SysCommand(f'chmod 0600 {self.target}{file}')
SysCommand(f'mkswap {self.target}{file}')
self._fstab_entries.append(f'{file} none swap defaults 0 0')
if enable_resume:
resume_uuid = SysCommand(f'findmnt -no UUID -T {self.target}{file}').decode()
resume_offset = (
SysCommand(
f'filefrag -v {self.target}{file}',
)
.decode()
.split('0:', 1)[1]
.split(':', 1)[1]
.split('..', 1)[0]
.strip()
)
self._hooks.append('resume')
self._kernel_params.append(f'resume=UUID={resume_uuid}')
self._kernel_params.append(f'resume_offset={resume_offset}')
def post_install_check(self, *args: str, **kwargs: str) -> list[str]:
return [step for step, flag in self._helper_flags.items() if flag is False]
def set_mirrors(
self,
mirror_list_handler: MirrorListHandler,
mirror_config: MirrorConfiguration,
on_target: bool = False,
) -> None:
"""
Set the mirror configuration for the installation.
:param mirror_config: The mirror configuration to use.
:type mirror_config: MirrorConfiguration
:on_target: Whether to set the mirrors on the target system or the live system.
:param on_target: bool
"""
debug('Setting mirrors on ' + ('target' if on_target else 'live system'))
for plugin in plugins.values():
if hasattr(plugin, 'on_mirrors'):
if result := plugin.on_mirrors(mirror_config):
mirror_config = result
if on_target:
mirrorlist_config = self.target / MIRRORLIST.relative_to_root()
pacman_config = self.target / PACMAN_CONF.relative_to_root()
else:
mirrorlist_config = MIRRORLIST
pacman_config = PACMAN_CONF
repositories_config = mirror_config.repositories_config()
if repositories_config:
debug(f'Pacman config: {repositories_config}')
with open(pacman_config, 'a') as fp:
fp.write(repositories_config)
regions_config = mirror_config.regions_config(mirror_list_handler, speed_sort=True)
if regions_config:
debug(f'Mirrorlist:\n{regions_config}')
mirrorlist_config.write_text(regions_config)
custom_servers = mirror_config.custom_servers_config()
if custom_servers:
debug(f'Custom servers:\n{custom_servers}')
content = mirrorlist_config.read_text()
mirrorlist_config.write_text(f'{custom_servers}\n\n{content}')
def genfstab(self, flags: str = '-pU') -> None:
fstab_path = self.target / 'etc' / 'fstab'
info(f'Updating {fstab_path}')
try:
gen_fstab = SysCommand(f'genfstab {flags} -f {self.target} {self.target}').output()
except SysCallError as err:
raise RequirementError(f'Could not generate fstab, strapping in packages most likely failed (disk out of space?)\n Error: {err}')
with open(fstab_path, 'ab') as fp:
fp.write(gen_fstab)
if not fstab_path.is_file():
raise RequirementError('Could not create fstab file')
for plugin in plugins.values():
if hasattr(plugin, 'on_genfstab'):
if plugin.on_genfstab(self) is True:
break
with open(fstab_path, 'a') as fp:
for entry in self._fstab_entries:
fp.write(f'{entry}\n')
def set_hostname(self, hostname: str) -> None:
(self.target / 'etc/hostname').write_text(hostname + '\n')
def set_locale(self, locale_config: LocaleConfiguration) -> bool:
modifier = ''
lang = locale_config.sys_lang
encoding = locale_config.sys_enc
# This is a temporary patch to fix #1200
if '.' in locale_config.sys_lang:
lang, potential_encoding = locale_config.sys_lang.split('.', 1)
# Override encoding if encoding is set to the default parameter
# and the "found" encoding differs.
if locale_config.sys_enc == 'UTF-8' and locale_config.sys_enc != potential_encoding:
encoding = potential_encoding
# Make sure we extract the modifier, that way we can put it in if needed.
if '@' in locale_config.sys_lang:
lang, modifier = locale_config.sys_lang.split('@', 1)
modifier = f'@{modifier}'
# - End patch
locale_gen = self.target / 'etc/locale.gen'
locale_gen_lines = locale_gen.read_text().splitlines(True)
# A locale entry in /etc/locale.gen may or may not contain the encoding
# in the first column of the entry; check for both cases.
entry_re = re.compile(rf'#{lang}(\.{encoding})?{modifier} {encoding}')
lang_value = None
for index, line in enumerate(locale_gen_lines):
if entry_re.match(line):
uncommented_line = line.removeprefix('#')
locale_gen_lines[index] = uncommented_line
locale_gen.write_text(''.join(locale_gen_lines))
lang_value = uncommented_line.split()[0]
break
if lang_value is None:
error(f"Invalid locale: language '{locale_config.sys_lang}', encoding '{locale_config.sys_enc}'")
return False
try:
self.arch_chroot('locale-gen')
except SysCallError as e:
error(f'Failed to run locale-gen on target: {e}')
return False
(self.target / 'etc/locale.conf').write_text(f'LANG={lang_value}\n')
return True
def set_timezone(self, zone: str) -> bool:
if not zone:
return True
if not len(zone):
return True # Redundant
for plugin in plugins.values():
if hasattr(plugin, 'on_timezone'):
if result := plugin.on_timezone(zone):
zone = result
if (Path('/usr') / 'share' / 'zoneinfo' / zone).exists():
(Path(self.target) / 'etc' / 'localtime').unlink(missing_ok=True)
self.arch_chroot(f'ln -s /usr/share/zoneinfo/{zone} /etc/localtime')
return True
else:
warn(f'Time zone {zone} does not exist, continuing with system default')
return False
def activate_time_synchronization(self) -> None:
info('Activating systemd-timesyncd for time synchronization using Arch Linux and ntp.org NTP servers')
self.enable_service('systemd-timesyncd')
def enable_espeakup(self) -> None:
info('Enabling espeakup.service for speech synthesis (accessibility)')
self.enable_service('espeakup')
def enable_periodic_trim(self) -> None:
info('Enabling periodic TRIM')
# fstrim is owned by util-linux, a dependency of both base and systemd.
self.enable_service('fstrim.timer')
def enable_service(self, services: str | list[str]) -> None:
if isinstance(services, str):
services = [services]
for service in services:
info(f'Enabling service {service}')
try:
SysCommand(f'systemctl --root={self.target} enable {service}')
except SysCallError as err:
raise ServiceException(f'Unable to start service {service}: {err}')
for plugin in plugins.values():
if hasattr(plugin, 'on_service'):
plugin.on_service(service)
def disable_service(self, services_disable: str | list[str]) -> None:
if isinstance(services_disable, str):
services_disable = [services_disable]
for service in services_disable:
info(f'Disabling service {service}')
try:
SysCommand(f'systemctl --root={self.target} disable {service}')
except SysCallError as err:
raise ServiceException(f'Unable to disable service {service}: {err}')
def run_command(self, cmd: str, peek_output: bool = False) -> SysCommand:
return SysCommand(f'arch-chroot -S {self.target} {cmd}', peek_output=peek_output)
def arch_chroot(self, cmd: str, run_as: str | None = None, peek_output: bool = False) -> SysCommand:
if run_as:
cmd = f'su - {run_as} -c {shlex.quote(cmd)}'
return self.run_command(cmd, peek_output=peek_output)
def drop_to_shell(self) -> None:
subprocess.check_call(f'arch-chroot {self.target}', shell=True)
def configure_nic(self, nic: Nic) -> None:
conf = nic.as_systemd_config()
for plugin in plugins.values():
if hasattr(plugin, 'on_configure_nic'):
conf = (
plugin.on_configure_nic(
nic.iface,
nic.dhcp,
nic.ip,
nic.gateway,
nic.dns,
)
or conf
)
with open(f'{self.target}/etc/systemd/network/10-{nic.iface}.network', 'a') as netconf:
netconf.write(str(conf))
def copy_iso_network_config(self, enable_services: bool = False) -> bool:
# Copy (if any) iwd password and config files
iwd_dir = LPath('/var/lib/iwd')
if psk_files := list(iwd_dir.glob('*.psk')):
iwd_target = self.target / iwd_dir.relative_to_root()
iwd_target.mkdir(parents=True, exist_ok=True)
for psk in psk_files:
psk.copy(iwd_target / psk.name, preserve_metadata=True)
if enable_services:
# If we haven't installed the base yet (function called pre-maturely)
if self._helper_flags.get('base', False) is False:
self._base_packages.append('iwd')
# This function will be called after minimal_installation()
# as a hook for post-installs. This hook is only needed if
# base is not installed yet.
def post_install_enable_iwd_service(*args: str, **kwargs: str) -> None:
self.enable_service('iwd')
self.post_base_install.append(post_install_enable_iwd_service)
# Otherwise, we can go ahead and add the required package
# and enable it's service:
else:
self.pacman.strap('iwd')
self.enable_service('iwd')
# Enable systemd-resolved by (forcefully) setting a symlink
# For further details see https://wiki.archlinux.org/title/Systemd-resolved#DNS
resolv_config_path = self.target / 'etc/resolv.conf'
resolv_config_path.unlink(missing_ok=True)
resolv_config_path.symlink_to('/run/systemd/resolve/stub-resolv.conf')
# Copy (if any) systemd-networkd config files
network_dir = LPath('/etc/systemd/network')
if netconfigurations := list(network_dir.glob('*')):
network_target = self.target / network_dir.relative_to_root()
network_target.mkdir(parents=True, exist_ok=True)
for netconf_file in netconfigurations:
netconf_file.copy(network_target / netconf_file.name, preserve_metadata=True)
if enable_services:
# If we haven't installed the base yet (function called pre-maturely)
if self._helper_flags.get('base', False) is False:
def post_install_enable_networkd_resolved(*args: str, **kwargs: str) -> None:
self.enable_service(['systemd-networkd', 'systemd-resolved'])
self.post_base_install.append(post_install_enable_networkd_resolved)
# Otherwise, we can go ahead and enable the services
else:
self.enable_service(['systemd-networkd', 'systemd-resolved'])
return True
def mkinitcpio(self, flags: list[str]) -> bool:
for plugin in plugins.values():
if hasattr(plugin, 'on_mkinitcpio'):
# Allow plugins to override the usage of mkinitcpio altogether.
if plugin.on_mkinitcpio(self):
return True
with open(f'{self.target}/etc/mkinitcpio.conf', 'r+') as mkinit:
content = mkinit.read()
content = re.sub('\nMODULES=(.*)', f'\nMODULES=({" ".join(self._modules)})', content)
content = re.sub('\nBINARIES=(.*)', f'\nBINARIES=({" ".join(self._binaries)})', content)
content = re.sub('\nFILES=(.*)', f'\nFILES=({" ".join(self._files)})', content)
if not self._disk_encryption.hsm_device:
# For now, if we don't use HSM we revert to the old
# way of setting up encryption hooks for mkinitcpio.
# This is purely for stability reasons, we're going away from this.
# * systemd -> udev
# * sd-vconsole -> keymap
self._hooks = [hook.replace('systemd', 'udev').replace('sd-vconsole', 'keymap consolefont') for hook in self._hooks]
content = re.sub('\nHOOKS=(.*)', f'\nHOOKS=({" ".join(self._hooks)})', content)
mkinit.seek(0)
mkinit.truncate()
mkinit.write(content)
try:
self.arch_chroot(f'mkinitcpio {" ".join(flags)}', peek_output=True)
return True
except SysCallError as e:
if e.worker_log:
log(e.worker_log.decode())
return False
def _get_microcode(self) -> Path | None:
if not SysInfo.is_vm():
if vendor := SysInfo.cpu_vendor():
return vendor.get_ucode()
return None
def _prepare_fs_type(
self,
fs_type: FilesystemType,
mountpoint: Path | None,
) -> None:
if (pkg := fs_type.installation_pkg) is not None:
self._base_packages.append(pkg)
# https://github.com/archlinux/archinstall/issues/1837
if fs_type == FilesystemType.BTRFS:
self._disable_fstrim = True
def _prepare_encrypt(self, before: str = 'filesystems') -> None:
if self._disk_encryption.hsm_device:
# Required by mkinitcpio to add support for fido2-device options
self.pacman.strap('libfido2')
if 'sd-encrypt' not in self._hooks:
self._hooks.insert(self._hooks.index(before), 'sd-encrypt')
else:
if 'encrypt' not in self._hooks:
self._hooks.insert(self._hooks.index(before), 'encrypt')
def minimal_installation(
self,
optional_repositories: list[Repository] = [],
mkinitcpio: bool = True,
hostname: str | None = None,
locale_config: LocaleConfiguration | None = LocaleConfiguration.default(),
pacman_config: PacmanConfiguration | None = None,
) -> None:
if self._disk_config.lvm_config:
lvm = 'lvm2'
self.add_additional_packages(lvm)
self._hooks.insert(self._hooks.index('filesystems') - 1, lvm)
for vg in self._disk_config.lvm_config.vol_groups:
for vol in vg.volumes:
if vol.fs_type is not None:
self._prepare_fs_type(vol.fs_type, vol.mountpoint)
types = (EncryptionType.LVM_ON_LUKS, EncryptionType.LUKS_ON_LVM)
if self._disk_encryption.encryption_type in types:
self._prepare_encrypt(lvm)
else:
for mod in self._disk_config.device_modifications:
for part in mod.partitions:
if part.fs_type is None:
continue
self._prepare_fs_type(part.fs_type, part.mountpoint)
if part in self._disk_encryption.partitions:
self._prepare_encrypt()
if ucode := self._get_microcode():
(self.target / 'boot' / ucode).unlink(missing_ok=True)
self._base_packages.append(ucode.stem)
else:
debug('Archinstall will not install any ucode.')
debug(f'Optional repositories: {optional_repositories}')
# This action takes place on the host system as pacstrap copies over package repository lists.
pacman_conf = PacmanConfig(self.target)
pacman_conf.enable(optional_repositories)
pacman_conf.apply()
if locale_config:
self.set_vconsole(locale_config)
self.pacman.strap(self._base_packages)
self._helper_flags['base-strapped'] = True
pacman_conf.persist()
if pacman_config:
pacman_conf.configure(pacman_config)
# Periodic TRIM may improve the performance and longevity of SSDs whilst
# having no adverse effect on other devices. Most distributions enable
# periodic TRIM by default.
#
# https://github.com/archlinux/archinstall/issues/880
# https://github.com/archlinux/archinstall/issues/1837
# https://github.com/archlinux/archinstall/issues/1841
if not self._disable_fstrim:
self.enable_periodic_trim()
# TODO: Support locale and timezone
# os.remove(f'{self.target}/etc/localtime')
# sys_command(f'arch-chroot {self.target} ln -s /usr/share/zoneinfo/{localtime} /etc/localtime')
# sys_command('arch-chroot /mnt hwclock --hctosys --localtime')
if hostname:
self.set_hostname(hostname)
if locale_config:
self.set_locale(locale_config)
self.set_keyboard_language(locale_config.kb_layout)
if mkinitcpio and not self.mkinitcpio(['-P']):
error('Error generating initramfs (continuing anyway)')
self._helper_flags['base'] = True
# Run registered post-install hooks
for function in self.post_base_install:
info(f'Running post-installation hook: {function}')
function(self)
for plugin in plugins.values():
if hasattr(plugin, 'on_install'):
plugin.on_install(self)
def setup_btrfs_snapshot(
self,
snapshot_type: SnapshotType,
bootloader: Bootloader | None = None,
) -> None:
if snapshot_type == SnapshotType.Snapper:
debug('Setting up Btrfs snapper')
self.pacman.strap('snapper')
snapper: dict[str, str] = {
'root': '/',
'home': '/home',
}
for config_name, mountpoint in snapper.items():
command = [
'arch-chroot',
'-S',
str(self.target),
'snapper',
'--no-dbus',
'-c',
config_name,
'create-config',
mountpoint,
]