forked from archlinux/archinstall
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice.py
More file actions
1608 lines (1261 loc) · 41.8 KB
/
device.py
File metadata and controls
1608 lines (1261 loc) · 41.8 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 builtins
import math
import uuid
from dataclasses import dataclass, field
from enum import Enum, StrEnum, auto
from pathlib import Path
from typing import NotRequired, Self, TypedDict, override
from uuid import UUID
import parted
from parted import Disk, Geometry, Partition
from pydantic import BaseModel, Field, ValidationInfo, field_serializer, field_validator
from archinstall.lib.hardware import SysInfo
from archinstall.lib.models.users import Password
from archinstall.lib.output import debug
from archinstall.lib.translationhandler import tr
ENC_IDENTIFIER = 'ainst'
DEFAULT_ITER_TIME = 10000
class DiskLayoutType(Enum):
Default = 'default_layout'
Manual = 'manual_partitioning'
Pre_mount = 'pre_mounted_config'
def display_msg(self) -> str:
match self:
case DiskLayoutType.Default:
return tr('Use a best-effort default partition layout')
case DiskLayoutType.Manual:
return tr('Manual Partitioning')
case DiskLayoutType.Pre_mount:
return tr('Pre-mounted configuration')
class _DiskLayoutConfigurationSerialization(TypedDict):
config_type: str
device_modifications: NotRequired[list[_DeviceModificationSerialization]]
lvm_config: NotRequired[_LvmConfigurationSerialization]
mountpoint: NotRequired[str]
btrfs_options: NotRequired[_BtrfsOptionsSerialization]
disk_encryption: NotRequired[_DiskEncryptionSerialization]
@dataclass
class DiskLayoutConfiguration:
config_type: DiskLayoutType
device_modifications: list[DeviceModification] = field(default_factory=list)
lvm_config: LvmConfiguration | None = None
disk_encryption: DiskEncryption | None = None
btrfs_options: BtrfsOptions | None = None
# used for pre-mounted config
mountpoint: Path | None = None
def json(self) -> _DiskLayoutConfigurationSerialization:
if self.config_type == DiskLayoutType.Pre_mount:
return {
'config_type': self.config_type.value,
'mountpoint': str(self.mountpoint),
}
else:
config: _DiskLayoutConfigurationSerialization = {
'config_type': self.config_type.value,
'device_modifications': [mod.json() for mod in self.device_modifications],
}
if self.lvm_config:
config['lvm_config'] = self.lvm_config.json()
if self.disk_encryption:
config['disk_encryption'] = self.disk_encryption.json()
if self.btrfs_options:
config['btrfs_options'] = self.btrfs_options.json()
return config
@classmethod
def parse_arg(
cls,
disk_config: _DiskLayoutConfigurationSerialization,
enc_password: Password | None = None,
) -> Self | None:
from archinstall.lib.disk.device_handler import device_handler
device_modifications: list[DeviceModification] = []
config_type = disk_config.get('config_type', None)
if not config_type:
raise ValueError('Missing disk layout configuration: config_type')
config = cls(
config_type=DiskLayoutType(config_type),
device_modifications=device_modifications,
)
if config_type == DiskLayoutType.Pre_mount.value:
if not (mountpoint := disk_config.get('mountpoint')):
raise ValueError('Must set a mountpoint when layout type is pre-mount')
path = Path(str(mountpoint))
mods = device_handler.detect_pre_mounted_mods(path)
device_modifications.extend(mods)
config.mountpoint = path
return config
for entry in disk_config.get('device_modifications', []):
device_path = Path(entry['device']) if entry.get('device', None) else None
if not device_path:
continue
device = device_handler.get_device(device_path)
if not device:
continue
device_modification = DeviceModification(
wipe=entry.get('wipe', False),
device=device,
)
device_partitions: list[PartitionModification] = []
for partition in entry.get('partitions', []):
flags = [flag for f in partition.get('flags', []) if (flag := PartitionFlag.from_string(f))]
if fs_type := partition.get('fs_type'):
fs_type = FilesystemType(fs_type)
else:
fs_type = None
device_partition = PartitionModification(
status=ModificationStatus(partition['status']),
fs_type=fs_type,
start=Size.parse_args(partition['start']),
length=Size.parse_args(partition['size']),
mount_options=partition['mount_options'],
mountpoint=Path(partition['mountpoint']) if partition['mountpoint'] else None,
dev_path=Path(partition['dev_path']) if partition['dev_path'] else None,
type=PartitionType(partition['type']),
flags=flags,
btrfs_subvols=SubvolumeModification.parse_args(partition.get('btrfs', [])),
)
# special 'invisible' attr to internally identify the part mod
device_partition._obj_id = partition['obj_id']
device_partitions.append(device_partition)
device_modification.partitions = device_partitions
device_modifications.append(device_modification)
for dev_mod in device_modifications:
dev_mod.partitions.sort(key=lambda p: (not p.is_delete(), p.start))
non_delete_partitions = [part_mod for part_mod in dev_mod.partitions if not part_mod.is_delete()]
if not non_delete_partitions:
continue
first = non_delete_partitions[0]
if first.status == ModificationStatus.CREATE and not first.start.is_valid_start():
raise ValueError('First partition must start at no less than 1 MiB')
for i, current_partition in enumerate(non_delete_partitions[1:], start=1):
previous_partition = non_delete_partitions[i - 1]
if current_partition.status == ModificationStatus.CREATE and current_partition.start < previous_partition.end:
raise ValueError('Partitions overlap')
create_partitions = [part_mod for part_mod in non_delete_partitions if part_mod.status == ModificationStatus.CREATE]
if not create_partitions:
continue
for part in create_partitions:
if part.start != part.start.align() or part.length != part.length.align():
raise ValueError('Partition is misaligned')
last = create_partitions[-1]
total_size = dev_mod.device.device_info.total_size
if dev_mod.using_gpt(device_handler.partition_table):
if last.end > total_size.gpt_end():
raise ValueError('Partition overlaps backup GPT header')
elif last.end > total_size.align():
raise ValueError('Partition too large for device')
# Parse LVM configuration from settings
if (lvm_arg := disk_config.get('lvm_config', None)) is not None:
config.lvm_config = LvmConfiguration.parse_arg(lvm_arg, config)
if (enc_config := disk_config.get('disk_encryption', None)) is not None:
config.disk_encryption = DiskEncryption.parse_arg(config, enc_config, enc_password)
if config.has_default_btrfs_vols():
if (btrfs_arg := disk_config.get('btrfs_options', None)) is not None:
config.btrfs_options = BtrfsOptions.parse_arg(btrfs_arg)
return config
def has_default_btrfs_vols(self) -> bool:
for mod in self.device_modifications:
for part in mod.partitions:
if not (part.is_create_or_modify() and part.fs_type == FilesystemType.BTRFS):
continue
if any(subvol.is_default_root() for subvol in part.btrfs_subvols):
return True
return False
class PartitionTable(Enum):
GPT = 'gpt'
MBR = 'msdos'
def is_gpt(self) -> bool:
return self == PartitionTable.GPT
def is_mbr(self) -> bool:
return self == PartitionTable.MBR
@classmethod
def default(cls) -> Self:
return cls.GPT if SysInfo.has_uefi() else cls.MBR
class Units(Enum):
BINARY = 'binary'
DECIMAL = 'decimal'
class Unit(Enum):
B = 1 # byte
kB = 1000**1 # kilobyte
MB = 1000**2 # megabyte
GB = 1000**3 # gigabyte
TB = 1000**4 # terabyte
PB = 1000**5 # petabyte
EB = 1000**6 # exabyte
ZB = 1000**7 # zettabyte
YB = 1000**8 # yottabyte
KiB = 1024**1 # kibibyte
MiB = 1024**2 # mebibyte
GiB = 1024**3 # gibibyte
TiB = 1024**4 # tebibyte
PiB = 1024**5 # pebibyte
EiB = 1024**6 # exbibyte
ZiB = 1024**7 # zebibyte
YiB = 1024**8 # yobibyte
sectors = 'sectors' # size in sector
@classmethod
def get_all_units(cls) -> list[str]:
return [u.name for u in cls]
@classmethod
def get_si_units(cls) -> list[Self]:
return [u for u in cls if 'i' not in u.name and u.name != 'sectors']
@classmethod
def get_binary_units(cls) -> list[Self]:
return [u for u in cls if 'i' in u.name or u.name == 'B']
class _SectorSizeSerialization(TypedDict):
value: int
unit: str
@dataclass
class SectorSize:
value: int
unit: Unit
def __post_init__(self) -> None:
match self.unit:
case Unit.sectors:
raise ValueError('Unit type sector not allowed for SectorSize')
@classmethod
def default(cls) -> Self:
return cls(512, Unit.B)
def json(self) -> _SectorSizeSerialization:
return {
'value': self.value,
'unit': self.unit.name,
}
@classmethod
def parse_args(cls, arg: _SectorSizeSerialization) -> Self:
return cls(
arg['value'],
Unit[arg['unit']],
)
def normalize(self) -> int:
"""
will normalize the value of the unit to Byte
"""
return int(self.value * self.unit.value)
class _SizeSerialization(TypedDict):
value: int
unit: str
sector_size: _SectorSizeSerialization
@dataclass
class Size:
value: int
unit: Unit
sector_size: SectorSize
def json(self) -> _SizeSerialization:
return {
'value': self.value,
'unit': self.unit.name,
'sector_size': self.sector_size.json(),
}
@classmethod
def parse_args(cls, size_arg: _SizeSerialization) -> Self:
sector_size = size_arg['sector_size']
return cls(
size_arg['value'],
Unit[size_arg['unit']],
SectorSize.parse_args(sector_size),
)
def convert(
self,
target_unit: Unit,
sector_size: SectorSize | None = None,
) -> Size:
if target_unit == Unit.sectors and sector_size is None:
raise ValueError('If target has unit sector, a sector size must be provided')
if self.unit == target_unit:
return self
elif self.unit == Unit.sectors:
norm = self._normalize()
return Size(norm, Unit.B, self.sector_size).convert(target_unit, sector_size)
else:
if target_unit == Unit.sectors and sector_size is not None:
norm = self._normalize()
sectors = math.ceil(norm / sector_size.value)
return Size(sectors, Unit.sectors, sector_size)
else:
value = int(self._normalize() / target_unit.value)
return Size(value, target_unit, self.sector_size)
def as_text(self) -> str:
return self.format_size(
self.unit,
self.sector_size,
)
def format_size(
self,
target_unit: Unit,
sector_size: SectorSize | None = None,
include_unit: bool = True,
) -> str:
target_size = self.convert(target_unit, sector_size)
if include_unit:
return f'{target_size.value} {target_unit.name}'
return f'{target_size.value}'
def binary_unit_highest(self, include_unit: bool = True) -> str:
binary_units = Unit.get_binary_units()
size = float(self._normalize())
unit = Unit.KiB
base_value = unit.value
for binary_unit in binary_units:
unit = binary_unit
if size < base_value:
break
size /= base_value
formatted_size = f'{size:.1f}'
if formatted_size.endswith('.0'):
formatted_size = formatted_size[:-2]
if not include_unit:
return formatted_size
return f'{formatted_size} {unit.name}'
def si_unit_highest(self, include_unit: bool = True) -> str:
si_units = Unit.get_si_units()
all_si_values = [self.convert(si) for si in si_units]
filtered = filter(lambda x: x.value >= 1, all_si_values)
# we have to get the max by the unit value as we're interested
# in getting the value in the highest possible unit without floats
si_value = max(filtered, key=lambda x: x.unit.value)
if include_unit:
return f'{si_value.value} {si_value.unit.name}'
return f'{si_value.value}'
def format_highest(self, include_unit: bool = True, units: Units = Units.BINARY) -> str:
if units == Units.BINARY:
return self.binary_unit_highest(include_unit)
else:
return self.si_unit_highest(include_unit)
def is_valid_start(self) -> bool:
return self >= Size(1, Unit.MiB, self.sector_size)
def align(self) -> Size:
align_norm = Size(1, Unit.MiB, self.sector_size)._normalize()
src_norm = self._normalize()
return self - Size(abs(src_norm % align_norm), Unit.B, self.sector_size)
def gpt_end(self) -> Size:
return self - Size(1, Unit.MiB, self.sector_size)
def _normalize(self) -> int:
"""
will normalize the value of the unit to Byte
"""
if self.unit == Unit.sectors and self.sector_size is not None:
return self.value * self.sector_size.normalize()
return int(self.value * self.unit.value)
def __sub__(self, other: Self) -> Size:
src_norm = self._normalize()
dest_norm = other._normalize()
return Size(abs(src_norm - dest_norm), Unit.B, self.sector_size)
def __add__(self, other: Self) -> Size:
src_norm = self._normalize()
dest_norm = other._normalize()
return Size(abs(src_norm + dest_norm), Unit.B, self.sector_size)
def __lt__(self, other: Self) -> bool:
return self._normalize() < other._normalize()
def __le__(self, other: Self) -> bool:
return self._normalize() <= other._normalize()
@override
def __eq__(self, other: object) -> bool:
if not isinstance(other, Size):
return NotImplemented
return self._normalize() == other._normalize()
@override
def __ne__(self, other: object) -> bool:
if not isinstance(other, Size):
return NotImplemented
return self._normalize() != other._normalize()
def __gt__(self, other: Self) -> bool:
return self._normalize() > other._normalize()
def __ge__(self, other: Self) -> bool:
return self._normalize() >= other._normalize()
class BtrfsMountOption(Enum):
compress = 'compress=zstd'
nodatacow = 'nodatacow'
@dataclass
class _BtrfsSubvolumeInfo:
name: Path
mountpoint: Path | None
@dataclass
class _PartitionInfo:
partition: Partition
name: str
type: PartitionType
fs_type: FilesystemType | None
path: Path
start: Size
length: Size
flags: list[PartitionFlag]
partn: int | None
partuuid: str | None
uuid: str | None
disk: Disk
mountpoints: list[Path]
btrfs_subvol_infos: list[_BtrfsSubvolumeInfo] = field(default_factory=list)
@property
def sector_size(self) -> SectorSize:
sector_size = self.partition.geometry.device.sectorSize
return SectorSize(sector_size, Unit.B)
def table_data(self) -> dict[str, str]:
end = self.start + self.length
part_info = {
'Name': self.name,
'Type': self.type.value,
'Filesystem': self.fs_type.value if self.fs_type else tr('Unknown'),
'Path': str(self.path),
'Start': self.start.format_size(Unit.sectors, self.sector_size, include_unit=False),
'End': end.format_size(Unit.sectors, self.sector_size, include_unit=False),
'Size': self.length.format_highest(),
'Flags': ', '.join(f.description for f in self.flags),
}
if self.btrfs_subvol_infos:
part_info['Btrfs vol.'] = f'{len(self.btrfs_subvol_infos)} subvolumes'
return part_info
@classmethod
def from_partition(
cls,
partition: Partition,
lsblk_info: LsblkInfo,
fs_type: FilesystemType | None,
btrfs_subvol_infos: list[_BtrfsSubvolumeInfo] = [],
) -> Self:
partition_type = PartitionType.get_type_from_code(partition.type)
flags = [f for f in PartitionFlag if partition.getFlag(f.flag_id)]
start = Size(
partition.geometry.start,
Unit.sectors,
SectorSize(partition.disk.device.sectorSize, Unit.B),
)
length = Size(
int(partition.getLength(unit='B')),
Unit.B,
SectorSize(partition.disk.device.sectorSize, Unit.B),
)
return cls(
partition=partition,
name=partition.get_name(),
type=partition_type,
fs_type=fs_type,
path=Path(partition.path),
start=start,
length=length,
flags=flags,
partn=lsblk_info.partn,
partuuid=lsblk_info.partuuid,
uuid=lsblk_info.uuid,
disk=partition.disk,
mountpoints=lsblk_info.mountpoints,
btrfs_subvol_infos=btrfs_subvol_infos,
)
@dataclass
class _DeviceInfo:
model: str
path: Path
type: str
total_size: Size
free_space_regions: list[DeviceGeometry]
sector_size: SectorSize
read_only: bool
dirty: bool
@override
def __hash__(self) -> int:
return hash(self.path)
def table_data(self) -> dict[str, str | int | bool]:
total_free_space = sum([region.get_length(unit=Unit.MiB) for region in self.free_space_regions])
return {
'Model': self.model,
'Path': str(self.path),
'Type': self.type,
'Size': self.total_size.format_highest(),
'Free space': int(total_free_space),
'Sector size': self.sector_size.value,
'Read only': self.read_only,
}
@classmethod
def from_disk(cls, disk: Disk) -> Self:
device = disk.device
if device.type == 18:
device_type = 'loop'
elif device.type in parted.devices:
device_type = parted.devices[device.type]
else:
debug(f'Device code unknown: {device.type}')
device_type = parted.devices[parted.DEVICE_UNKNOWN]
sector_size = SectorSize(device.sectorSize, Unit.B)
free_space = [DeviceGeometry(g, sector_size) for g in disk.getFreeSpaceRegions()]
return cls(
model=device.model.strip(),
path=Path(device.path),
type=device_type,
sector_size=sector_size,
total_size=Size(int(device.getLength(unit='B')), Unit.B, sector_size),
free_space_regions=free_space,
read_only=device.readOnly,
dirty=device.dirty,
)
class _SubvolumeModificationSerialization(TypedDict):
name: str
mountpoint: str
@dataclass
class SubvolumeModification:
name: Path | str
mountpoint: Path | None = None
@classmethod
def from_existing_subvol_info(cls, info: _BtrfsSubvolumeInfo) -> Self:
return cls(info.name, mountpoint=info.mountpoint)
@classmethod
def parse_args(cls, subvol_args: list[_SubvolumeModificationSerialization]) -> list[Self]:
mods = []
for entry in subvol_args:
if not entry.get('name', None) or not entry.get('mountpoint', None):
debug(f'Subvolume arg is missing name: {entry}')
continue
mountpoint = Path(entry['mountpoint']) if entry['mountpoint'] else None
mods.append(cls(entry['name'], mountpoint))
return mods
@property
def relative_mountpoint(self) -> Path:
"""
Will return the relative path based on the anchor
e.g. Path('/mnt/test') -> Path('mnt/test')
"""
if self.mountpoint is not None:
return self.mountpoint.relative_to(self.mountpoint.anchor)
raise ValueError('Mountpoint is not specified')
def is_root(self) -> bool:
if self.mountpoint:
return self.mountpoint == Path('/')
return False
def is_default_root(self) -> bool:
return self.name == Path('@') and self.is_root()
def json(self) -> _SubvolumeModificationSerialization:
return {'name': str(self.name), 'mountpoint': str(self.mountpoint)}
def table_data(self) -> _SubvolumeModificationSerialization:
return self.json()
class DeviceGeometry:
def __init__(self, geometry: Geometry, sector_size: SectorSize):
self._geometry = geometry
self._sector_size = sector_size
@property
def start(self) -> int:
return self._geometry.start
@property
def end(self) -> int:
return self._geometry.end
def get_length(self, unit: Unit = Unit.sectors) -> int:
return self._geometry.getLength(unit.name)
def table_data(self) -> dict[str, str | int]:
start = Size(self._geometry.start, Unit.sectors, self._sector_size)
end = Size(self._geometry.end, Unit.sectors, self._sector_size)
length = Size(self._geometry.getLength(), Unit.sectors, self._sector_size)
start_str = f'{self._geometry.start} / {start.format_size(Unit.B, include_unit=False)}'
end_str = f'{self._geometry.end} / {end.format_size(Unit.B, include_unit=False)}'
length_str = f'{self._geometry.getLength()} / {length.format_size(Unit.B, include_unit=False)}'
return {
'Sector size': self._sector_size.value,
'Start (sector/B)': start_str,
'End (sector/B)': end_str,
'Size (sectors/B)': length_str,
}
@dataclass
class BDevice:
disk: Disk
device_info: _DeviceInfo
partition_infos: list[_PartitionInfo]
@override
def __hash__(self) -> int:
return hash(self.disk.device.path)
class PartitionType(StrEnum):
BOOT = auto()
PRIMARY = auto()
_UNKNOWN = 'unknown'
@classmethod
def get_type_from_code(cls, code: int) -> Self:
if code == parted.PARTITION_NORMAL:
return cls.PRIMARY
else:
debug(f'Partition code not supported: {code}')
return cls._UNKNOWN
def get_partition_code(self) -> int | None:
if self == PartitionType.PRIMARY:
return parted.PARTITION_NORMAL
elif self == PartitionType.BOOT:
return parted.PARTITION_BOOT
return None
@dataclass(frozen=True)
class PartitionFlagDataMixin:
flag_id: int
alias: str | None = None
class PartitionFlag(PartitionFlagDataMixin, Enum):
BOOT = parted.PARTITION_BOOT
XBOOTLDR = parted.PARTITION_BLS_BOOT, 'bls_boot'
ESP = parted.PARTITION_ESP
LINUX_HOME = parted.PARTITION_LINUX_HOME, 'linux-home'
SWAP = parted.PARTITION_SWAP
@property
def description(self) -> str:
return self.alias or self.name.lower()
@classmethod
def from_string(cls, s: str) -> Self | None:
s = s.lower()
for partition_flag in cls:
if s in (partition_flag.name.lower(), partition_flag.alias):
return partition_flag
debug(f'Partition flag not supported: {s}')
return None
class PartitionGUID(Enum):
"""
A list of Partition type GUIDs (lsblk -o+PARTTYPE) can be found here: https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
"""
LINUX_ROOT_X86_64 = '4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709'
@property
def bytes(self) -> builtins.bytes:
return uuid.UUID(self.value).bytes
class FilesystemType(StrEnum):
BTRFS = auto()
EXT2 = auto()
EXT3 = auto()
EXT4 = auto()
F2FS = auto()
FAT12 = auto()
FAT16 = auto()
FAT32 = auto()
NTFS = auto()
XFS = auto()
LINUX_SWAP = 'linux-swap'
# this is not a FS known to parted, so be careful
# with the usage from this enum
CRYPTO_LUKS = 'crypto_LUKS'
def is_crypto(self) -> bool:
return self == FilesystemType.CRYPTO_LUKS
@property
def parted_value(self) -> str:
return self.value + '(v1)' if self == FilesystemType.LINUX_SWAP else self.value
@property
def installation_pkg(self) -> str | None:
match self:
case FilesystemType.BTRFS:
return 'btrfs-progs'
case FilesystemType.XFS:
return 'xfsprogs'
case FilesystemType.F2FS:
return 'f2fs-tools'
case _:
return None
class ModificationStatus(StrEnum):
EXIST = 'existing'
MODIFY = auto()
DELETE = auto()
CREATE = auto()
class _PartitionModificationSerialization(TypedDict):
obj_id: str
status: str
type: str
start: _SizeSerialization
size: _SizeSerialization
fs_type: str | None
mountpoint: str | None
mount_options: list[str]
flags: list[str]
btrfs: list[_SubvolumeModificationSerialization]
dev_path: str | None
@dataclass
class PartitionModification:
status: ModificationStatus
type: PartitionType
start: Size
length: Size
fs_type: FilesystemType | None = None
mountpoint: Path | None = None
mount_options: list[str] = field(default_factory=list)
flags: list[PartitionFlag] = field(default_factory=list)
btrfs_subvols: list[SubvolumeModification] = field(default_factory=list)
# only set if the device was created or exists
dev_path: Path | None = None
partn: int | None = None
partuuid: str | None = None
uuid: str | None = None
_obj_id: UUID | str = field(init=False)
def __post_init__(self) -> None:
# needed to use the object as a dictionary key due to hash func
if not hasattr(self, '_obj_id'):
self._obj_id = uuid.uuid4()
if self.is_exists_or_modify() and not self.dev_path:
raise ValueError('If partition marked as existing a path must be set')
if self.fs_type is None and self.status == ModificationStatus.MODIFY:
raise ValueError('FS type must not be empty on modifications with status type modify')
@override
def __hash__(self) -> int:
return hash(self._obj_id)
@property
def end(self) -> Size:
return self.start + self.length
@property
def obj_id(self) -> str:
if hasattr(self, '_obj_id'):
return str(self._obj_id)
return ''
@property
def safe_dev_path(self) -> Path:
if self.dev_path is None:
raise ValueError('Device path was not set')
return self.dev_path
@property
def safe_fs_type(self) -> FilesystemType:
if self.fs_type is None:
raise ValueError('File system type is not set')
return self.fs_type
@classmethod
def from_existing_partition(cls, partition_info: _PartitionInfo) -> Self:
if partition_info.btrfs_subvol_infos:
mountpoint = None
subvol_mods = []
for i in partition_info.btrfs_subvol_infos:
subvol_mods.append(
SubvolumeModification.from_existing_subvol_info(i),
)
else:
mountpoint = partition_info.mountpoints[0] if partition_info.mountpoints else None
subvol_mods = []
return cls(
status=ModificationStatus.EXIST,
type=partition_info.type,
start=partition_info.start,
length=partition_info.length,
fs_type=partition_info.fs_type,
dev_path=partition_info.path,
partn=partition_info.partn,
partuuid=partition_info.partuuid,
uuid=partition_info.uuid,
flags=partition_info.flags,
mountpoint=mountpoint,
btrfs_subvols=subvol_mods,
)
@property
def relative_mountpoint(self) -> Path:
"""
Will return the relative path based on the anchor
e.g. Path('/mnt/test') -> Path('mnt/test')
"""
if self.mountpoint:
return self.mountpoint.relative_to(self.mountpoint.anchor)
raise ValueError('Mountpoint is not specified')
def is_efi(self) -> bool:
return PartitionFlag.ESP in self.flags
def is_boot(self) -> bool:
return PartitionFlag.BOOT in self.flags
def is_root(self) -> bool:
if self.mountpoint is not None:
return self.mountpoint == Path('/')
else:
for subvol in self.btrfs_subvols:
if subvol.is_root():
return True
return False
def is_home(self) -> bool:
if self.mountpoint is not None:
return self.mountpoint == Path('/home')
return False
def is_swap(self) -> bool:
return self.fs_type == FilesystemType.LINUX_SWAP
def is_modify(self) -> bool:
return self.status == ModificationStatus.MODIFY
def is_delete(self) -> bool:
return self.status == ModificationStatus.DELETE
def exists(self) -> bool:
return self.status == ModificationStatus.EXIST
def is_exists_or_modify(self) -> bool:
return self.status in [
ModificationStatus.EXIST,
ModificationStatus.DELETE,
ModificationStatus.MODIFY,
]
def is_create_or_modify(self) -> bool:
return self.status in [ModificationStatus.CREATE, ModificationStatus.MODIFY]
@property
def mapper_name(self) -> str | None:
if self.is_root():
return 'root'
if self.is_home():
return 'home'
if self.dev_path:
return f'{ENC_IDENTIFIER}{self.dev_path.name}'
return None
def set_flag(self, flag: PartitionFlag) -> None:
if flag not in self.flags:
self.flags.append(flag)
def invert_flag(self, flag: PartitionFlag) -> None:
if flag in self.flags:
self.flags = [f for f in self.flags if f != flag]
else:
self.set_flag(flag)