-
Notifications
You must be signed in to change notification settings - Fork 54
/
partition_table.go
1403 lines (1219 loc) · 39.6 KB
/
partition_table.go
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
package disk
import (
"fmt"
"math/rand"
"path/filepath"
"github.com/google/uuid"
"github.com/osbuild/images/pkg/blueprint"
"github.com/osbuild/images/pkg/datasizes"
"github.com/osbuild/images/pkg/platform"
)
type PartitionTable struct {
Size uint64 // Size of the disk (in bytes).
UUID string // Unique identifier of the partition table (GPT only).
Type PartitionTableType // Partition table type, e.g. dos, gpt.
Partitions []Partition
SectorSize uint64 // Sector size in bytes
ExtraPadding uint64 // Extra space at the end of the partition table (sectors)
StartOffset uint64 // Starting offset of the first partition in the table (Mb)
}
type PartitioningMode string
const (
// AutoLVMPartitioningMode creates a LVM layout if the filesystem
// contains a mountpoint that's not defined in the base partition table
// of the specified image type. In the other case, a raw layout is used.
AutoLVMPartitioningMode PartitioningMode = "auto-lvm"
// LVMPartitioningMode always creates an LVM layout.
LVMPartitioningMode PartitioningMode = "lvm"
// RawPartitioningMode always creates a raw layout.
RawPartitioningMode PartitioningMode = "raw"
// BtrfsPartitioningMode creates a btrfs layout.
BtrfsPartitioningMode PartitioningMode = "btrfs"
// DefaultPartitioningMode is AutoLVMPartitioningMode and is the empty state
DefaultPartitioningMode PartitioningMode = ""
)
// NewPartitionTable takes an existing base partition table and some parameters
// and returns a new version of the base table modified to satisfy the
// parameters.
//
// Mountpoints: New filesystems and minimum partition sizes are defined in
// mountpoints. By default, if new mountpoints are created, a partition table is
// automatically converted to LVM (see Partitioning modes below).
//
// Image size: The minimum size of the partition table, which in turn will be
// the size of the disk image. The final size of the image will either be the
// value of the imageSize argument or the sum of all partitions and their
// associated metadata, whichever is larger.
//
// Partitioning modes: The mode controls how the partition table is modified.
//
// - Raw will not convert any partition to LVM or Btrfs.
// - LVM will convert the partition that contains the root mountpoint '/' to an
//
// LVM Volume Group and create a root Logical Volume. Any extra mountpoints,
// except /boot, will be added to the Volume Group as new Logical Volumes.
//
// - Btrfs will convert the partition that contains the root mountpoint '/' to
// a Btrfs volume and create a root subvolume. Any extra mountpoints, except
// /boot, will be added to the Btrfs volume as new Btrfs subvolumes.
// - AutoLVM is the default mode and will convert a raw partition table to an
// LVM-based one if and only if new mountpoints are added.
//
// Directory sizes: The requiredSizes argument defines a map of minimum sizes
// for specific directories. These indirectly control the minimum sizes of
// partitions. A directory with a required size will set the minimum size of
// the partition with the mountpoint that contains the directory. Additional
// directory requirements are additive, meaning the minimum size for a
// mountpoint's partition is the sum of all the required directory sizes it
// will contain. By default, if no requiredSizes are provided, the new
// partition table will require at least 1 GiB for '/' and 2 GiB for '/usr'. In
// most cases, this translates to a requirement of 3 GiB for the root
// partition, Logical Volume, or Btrfs subvolume.
//
// # General principles:
//
// Desired sizes for partitions, partition tables, volumes, directories, etc,
// are always treated as minimum sizes. This means that very often the full
// disk image size is larger than the size of the sum of the partitions due to
// metadata. The function considers that the size of volumes have higher
// priority than the size of the disk.
//
// The partition or volume container that contains '/' is always last in the
// partition table layout.
//
// In the case of raw partitioning (no LVM and no Btrfs), the partition
// containing the root filesystem is grown to fill any left over space on the
// partition table. Logical Volumes are not grown to fill the space in the
// Volume Group since they are trivial to grow on a live system.
func NewPartitionTable(basePT *PartitionTable, mountpoints []blueprint.FilesystemCustomization, imageSize uint64, mode PartitioningMode, requiredSizes map[string]uint64, rng *rand.Rand) (*PartitionTable, error) {
newPT := basePT.Clone().(*PartitionTable)
if basePT.features().LVM && (mode == RawPartitioningMode || mode == BtrfsPartitioningMode) {
return nil, fmt.Errorf("%s partitioning mode set for a base partition table with LVM, this is unsupported", mode)
}
// first pass: enlarge existing mountpoints and collect new ones
newMountpoints, _ := newPT.applyCustomization(mountpoints, false)
var ensureLVM, ensureBtrfs bool
switch mode {
case LVMPartitioningMode:
ensureLVM = true
case RawPartitioningMode:
ensureLVM = false
case DefaultPartitioningMode, AutoLVMPartitioningMode:
ensureLVM = len(newMountpoints) > 0
case BtrfsPartitioningMode:
ensureBtrfs = true
default:
return nil, fmt.Errorf("unsupported partitioning mode %q", mode)
}
if ensureLVM {
err := newPT.ensureLVM()
if err != nil {
return nil, err
}
} else if ensureBtrfs {
err := newPT.ensureBtrfs()
if err != nil {
return nil, err
}
}
// second pass: deal with new mountpoints and newly created ones, after switching to
// the LVM layout, if requested, which might introduce new mount points, i.e. `/boot`
_, err := newPT.applyCustomization(newMountpoints, true)
if err != nil {
return nil, err
}
// If no separate requiredSizes are given then we use our defaults
if requiredSizes == nil {
requiredSizes = map[string]uint64{
"/": 1073741824,
"/usr": 2147483648,
}
}
if len(requiredSizes) != 0 {
newPT.EnsureDirectorySizes(requiredSizes)
}
// Calculate partition table offsets and sizes
newPT.relayout(imageSize)
// Generate new UUIDs for filesystems and partitions
newPT.GenerateUUIDs(rng)
return newPT, nil
}
func (pt *PartitionTable) Clone() Entity {
if pt == nil {
return nil
}
clone := &PartitionTable{
Size: pt.Size,
UUID: pt.UUID,
Type: pt.Type,
Partitions: make([]Partition, len(pt.Partitions)),
SectorSize: pt.SectorSize,
ExtraPadding: pt.ExtraPadding,
StartOffset: pt.StartOffset,
}
for idx, partition := range pt.Partitions {
ent := partition.Clone()
// partition.Clone() will return nil only if the partition is nil
if ent == nil {
panic(fmt.Sprintf("partition %d in a Partition Table is nil; this is a programming error", idx))
}
part, cloneOk := ent.(*Partition)
if !cloneOk {
panic("PartitionTable.Clone() returned an Entity that cannot be converted to *PartitionTable; this is a programming error")
}
clone.Partitions[idx] = *part
}
return clone
}
// AlignUp will round up the given size value to the default grain if not
// already aligned.
func (pt *PartitionTable) AlignUp(size uint64) uint64 {
grain := DefaultGrainBytes
if size%grain == 0 {
// already aligned: return unchanged
return size
}
return ((size + grain) / grain) * grain
}
// Convert the given bytes to the number of sectors.
func (pt *PartitionTable) BytesToSectors(size uint64) uint64 {
sectorSize := pt.SectorSize
if sectorSize == 0 {
sectorSize = DefaultSectorSize
}
return size / sectorSize
}
// Convert the given number of sectors to bytes.
func (pt *PartitionTable) SectorsToBytes(size uint64) uint64 {
sectorSize := pt.SectorSize
if sectorSize == 0 {
sectorSize = DefaultSectorSize
}
return size * sectorSize
}
// Returns if the partition table contains a filesystem with the given
// mount point.
func (pt *PartitionTable) ContainsMountpoint(mountpoint string) bool {
return len(entityPath(pt, mountpoint)) > 0
}
// Generate all needed UUIDs for all the partiton and filesystems
//
// Will not overwrite existing UUIDs and only generate UUIDs for
// partitions if the layout is GPT.
func (pt *PartitionTable) GenerateUUIDs(rng *rand.Rand) {
setuuid := func(ent Entity, path []Entity) error {
if ui, ok := ent.(UniqueEntity); ok {
ui.GenUUID(rng)
}
return nil
}
_ = pt.ForEachEntity(setuuid)
// if this is a MBR partition table, there is no need to generate
// uuids for the partitions themselves
if pt.Type != PT_GPT {
return
}
for idx, part := range pt.Partitions {
if part.UUID == "" {
pt.Partitions[idx].UUID = uuid.Must(newRandomUUIDFromReader(rng)).String()
}
}
}
func (pt *PartitionTable) GetItemCount() uint {
return uint(len(pt.Partitions))
}
func (pt *PartitionTable) GetChild(n uint) Entity {
return &pt.Partitions[n]
}
func (pt *PartitionTable) GetSize() uint64 {
return pt.Size
}
func (pt *PartitionTable) EnsureSize(s uint64) bool {
if s > pt.Size {
pt.Size = s
return true
}
return false
}
func (pt *PartitionTable) findDirectoryEntityPath(dir string) []Entity {
if path := entityPath(pt, dir); path != nil {
return path
}
parent := filepath.Dir(dir)
if dir == parent {
// invalid dir or pt has no root
return nil
}
// move up the directory path and check again
return pt.findDirectoryEntityPath(parent)
}
// EnsureDirectorySizes takes a mapping of directory paths to sizes (in bytes)
// and resizes the appropriate partitions such that they are at least the size
// of the sum of their subdirectories plus their own sizes.
// The function will panic if any of the directory paths are invalid.
func (pt *PartitionTable) EnsureDirectorySizes(dirSizeMap map[string]uint64) {
type mntSize struct {
entPath []Entity
newSize uint64
}
// add up the required size for each directory grouped by their mountpoints
mntSizeMap := make(map[string]*mntSize)
for dir, size := range dirSizeMap {
entPath := pt.findDirectoryEntityPath(dir)
if entPath == nil {
panic(fmt.Sprintf("EnsureDirectorySizes: invalid dir path %q", dir))
}
mnt := entPath[0].(Mountable)
mountpoint := mnt.GetMountpoint()
if _, ok := mntSizeMap[mountpoint]; !ok {
mntSizeMap[mountpoint] = &mntSize{entPath, 0}
}
es := mntSizeMap[mountpoint]
es.newSize += size
}
// resize all the entities in the map
for _, es := range mntSizeMap {
resizeEntityBranch(es.entPath, es.newSize)
}
}
func (pt *PartitionTable) CreateMountpoint(mountpoint string, size uint64) (Entity, error) {
filesystem := Filesystem{
Type: "xfs",
Mountpoint: mountpoint,
FSTabOptions: "defaults",
FSTabFreq: 0,
FSTabPassNo: 0,
}
partition := Partition{
Size: size,
Payload: &filesystem,
}
n := len(pt.Partitions)
var maxNo int
if pt.Type == PT_GPT {
switch mountpoint {
case "/boot":
partition.Type = XBootLDRPartitionGUID
default:
partition.Type = FilesystemDataGUID
}
maxNo = 128
} else {
maxNo = 4
}
if n == maxNo {
return nil, fmt.Errorf("maximum number of partitions reached (%d)", maxNo)
}
pt.Partitions = append(pt.Partitions, partition)
return &pt.Partitions[len(pt.Partitions)-1], nil
}
type EntityCallback func(e Entity, path []Entity) error
func forEachEntity(e Entity, path []Entity, cb EntityCallback) error {
childPath := append(path, e)
err := cb(e, childPath)
if err != nil {
return err
}
c, ok := e.(Container)
if !ok {
return nil
}
for idx := uint(0); idx < c.GetItemCount(); idx++ {
child := c.GetChild(idx)
err = forEachEntity(child, childPath, cb)
if err != nil {
return err
}
}
return nil
}
// ForEachEntity runs the provided callback function on each entity in
// the PartitionTable.
func (pt *PartitionTable) ForEachEntity(cb EntityCallback) error {
return forEachEntity(pt, []Entity{}, cb)
}
func (pt *PartitionTable) HeaderSize() uint64 {
// always reserve one extra sector for the GPT header
// this also ensure we have enough space for the MBR
header := pt.SectorsToBytes(1)
if pt.Type == PT_DOS {
return header
}
// calculate the space we need for
parts := uint64(len(pt.Partitions))
// reserve a minimum of 128 partition entires
if parts < 128 {
parts = 128
}
// Assume that each partition entry is 128 bytes
// which might not be the case if the partition
// name exceeds 72 bytes
header += parts * 128
return header
}
// Apply filesystem customization to the partition table. If create is false,
// the function will only apply customizations to existing partitions and
// return a list of left-over mountpoints (i.e. mountpoints in the input that
// were not created). An error can only occur if create is set.
// Does not relayout the table, i.e. a call to relayout might be needed.
func (pt *PartitionTable) applyCustomization(mountpoints []blueprint.FilesystemCustomization, create bool) ([]blueprint.FilesystemCustomization, error) {
newMountpoints := []blueprint.FilesystemCustomization{}
for _, mnt := range mountpoints {
size := clampFSSize(mnt.Mountpoint, mnt.MinSize)
if path := entityPath(pt, mnt.Mountpoint); len(path) != 0 {
size = alignEntityBranch(path, size)
resizeEntityBranch(path, size)
} else {
if !create {
newMountpoints = append(newMountpoints, mnt)
} else if err := pt.createFilesystem(mnt.Mountpoint, size); err != nil {
return nil, err
}
}
}
return newMountpoints, nil
}
// Dynamically calculate and update the start point for each of the existing
// partitions. Adjusts the overall size of image to either the supplied value
// in `size` or to the sum of all partitions if that is larger. Will grow the
// root partition if there is any empty space. Returns the updated start point.
func (pt *PartitionTable) relayout(size uint64) uint64 {
// always reserve one extra sector for the GPT header
header := pt.HeaderSize()
footer := uint64(0)
// The GPT header is also at the end of the partition table
if pt.Type == PT_GPT {
footer = header
}
start := pt.AlignUp(header)
start += pt.StartOffset
size = pt.AlignUp(size)
var rootIdx = -1
for idx := range pt.Partitions {
partition := &pt.Partitions[idx]
if len(entityPath(partition, "/")) != 0 {
// keep the root partition index to handle after all the other
// partitions have been moved and resized
rootIdx = idx
continue
}
partition.Start = start
partition.fitTo(partition.Size)
partition.Size = pt.AlignUp(partition.Size)
start += partition.Size
}
if rootIdx < 0 {
panic("no root filesystem found; this is a programming error")
}
root := &pt.Partitions[rootIdx]
root.Start = start
root.fitTo(root.Size)
// add the extra padding specified in the partition table
footer += pt.ExtraPadding
// If the sum of all partitions is bigger then the specified size,
// we use that instead. Grow the partition table size if needed.
end := pt.AlignUp(root.Start + footer + root.Size)
if end > size {
size = end
}
if size > pt.Size {
pt.Size = size
}
// If there is space left in the partition table, grow root
root.Size = pt.Size - root.Start
// Finally we shrink the last partition, i.e. the root partition,
// to leave space for the footer, e.g. the secondary GPT header.
root.Size -= footer
return start
}
func (pt *PartitionTable) createFilesystem(mountpoint string, size uint64) error {
rootPath := entityPath(pt, "/")
if rootPath == nil {
panic("no root mountpoint for PartitionTable")
}
var vc MountpointCreator
var entity Entity
var idx int
for idx, entity = range rootPath {
var ok bool
if vc, ok = entity.(MountpointCreator); ok {
break
}
}
if vc == nil {
panic("could not find root volume container")
}
newVol, err := vc.CreateMountpoint(mountpoint, 0)
if err != nil {
return fmt.Errorf("failed creating volume: %w", err)
}
vcPath := append([]Entity{newVol}, rootPath[idx:]...)
size = alignEntityBranch(vcPath, size)
resizeEntityBranch(vcPath, size)
return nil
}
// entityPath stats at ent and searches for an Entity with a Mountpoint equal
// to the target. Returns a slice of all the Entities leading to the Mountable
// in reverse order. If no Entity has the target as a Mountpoint, returns nil.
// If a slice is returned, the last element is always the starting Entity ent
// and the first element is always a Mountable with a Mountpoint equal to the
// target.
func entityPath(ent Entity, target string) []Entity {
switch e := ent.(type) {
case Mountable:
if target == e.GetMountpoint() {
return []Entity{ent}
}
case Container:
for idx := uint(0); idx < e.GetItemCount(); idx++ {
child := e.GetChild(idx)
path := entityPath(child, target)
if path != nil {
path = append(path, e)
return path
}
}
}
return nil
}
type MountableCallback func(mnt Mountable, path []Entity) error
func forEachMountable(c Container, path []Entity, cb MountableCallback) error {
for idx := uint(0); idx < c.GetItemCount(); idx++ {
child := c.GetChild(idx)
childPath := append(path, child)
var err error
switch ent := child.(type) {
case Mountable:
err = cb(ent, childPath)
case Container:
err = forEachMountable(ent, childPath, cb)
}
if err != nil {
return err
}
}
return nil
}
// ForEachMountable runs the provided callback function on each Mountable in
// the PartitionTable.
func (pt *PartitionTable) ForEachMountable(cb MountableCallback) error {
return forEachMountable(pt, []Entity{pt}, cb)
}
// FindMountable returns the Mountable entity with the given mountpoint in the
// PartitionTable. Returns nil if no Entity has the target as a Mountpoint.
func (pt *PartitionTable) FindMountable(mountpoint string) Mountable {
path := entityPath(pt, mountpoint)
if len(path) == 0 {
return nil
}
// first path element is guaranteed to be Mountable
return path[0].(Mountable)
}
func clampFSSize(mountpoint string, size uint64) uint64 {
// set a minimum size of 1GB for all mountpoints
// with the exception for '/boot' (= 500 MB)
var minSize uint64 = 1073741824
if mountpoint == "/boot" {
minSize = 524288000
}
if minSize > size {
return minSize
}
return size
}
func alignEntityBranch(path []Entity, size uint64) uint64 {
if len(path) == 0 {
return size
}
element := path[0]
if c, ok := element.(MountpointCreator); ok {
size = c.AlignUp(size)
}
return alignEntityBranch(path[1:], size)
}
// resizeEntityBranch resizes the first entity in the specified path to be at
// least the specified size and then grows every entity up the path to the
// PartitionTable accordingly.
func resizeEntityBranch(path []Entity, size uint64) {
if len(path) == 0 {
return
}
element := path[0]
if c, ok := element.(Container); ok {
containerSize := uint64(0)
for idx := uint(0); idx < c.GetItemCount(); idx++ {
if s, ok := c.GetChild(idx).(Sizeable); ok {
containerSize += s.GetSize()
} else {
break
}
}
// If containerSize is 0, it means it doesn't have any direct sizeable
// children (e.g., a LUKS container with a VG child). In that case,
// set the containerSize to the desired size for the branch before
// adding any metadata.
if containerSize == 0 {
containerSize = size
}
if vc, ok := element.(VolumeContainer); ok {
containerSize += vc.MetadataSize()
}
if containerSize > size {
size = containerSize
}
}
if sz, ok := element.(Sizeable); ok {
if !sz.EnsureSize(size) {
return
}
}
resizeEntityBranch(path[1:], size)
}
// GenUUID generates and sets UUIDs for all Partitions in the PartitionTable if
// the layout is GPT.
func (pt *PartitionTable) GenUUID(rng *rand.Rand) {
if pt.UUID == "" {
pt.UUID = uuid.Must(newRandomUUIDFromReader(rng)).String()
}
}
// ensureLVM will ensure that the root partition is on an LVM volume, i.e. if
// it currently is not, it will wrap it in one
func (pt *PartitionTable) ensureLVM() error {
rootPath := entityPath(pt, "/")
if rootPath == nil {
panic("no root mountpoint for PartitionTable")
}
// we need a /boot partition to boot LVM, ensure one exists
bootPath := entityPath(pt, "/boot")
if bootPath == nil {
_, err := pt.CreateMountpoint("/boot", 512*datasizes.MiB)
if err != nil {
return err
}
rootPath = entityPath(pt, "/")
}
parent := rootPath[1] // NB: entityPath has reversed order
if _, ok := parent.(*LVMLogicalVolume); ok {
return nil
} else if part, ok := parent.(*Partition); ok {
filesystem := part.Payload
vg := &LVMVolumeGroup{
Name: "rootvg",
Description: "created via lvm2 and osbuild",
}
// create root logical volume on the new volume group with the same
// size and filesystem as the previous root partition
_, err := vg.CreateLogicalVolume("rootlv", part.Size, filesystem)
if err != nil {
panic(fmt.Sprintf("Could not create LV: %v", err))
}
// replace the top-level partition payload with the new volume group
part.Payload = vg
// reset the vg partition size - it will be grown later
part.Size = 0
if pt.Type == PT_GPT {
part.Type = LVMPartitionGUID
} else {
part.Type = "8e"
}
} else {
return fmt.Errorf("Unsupported parent for LVM")
}
return nil
}
// ensureBtrfs will ensure that the root partition is on a btrfs subvolume, i.e. if
// it currently is not, it will wrap it in one
func (pt *PartitionTable) ensureBtrfs() error {
rootPath := entityPath(pt, "/")
if rootPath == nil {
return fmt.Errorf("no root mountpoint for a partition table: %#v", pt)
}
// we need a /boot partition to boot btrfs, ensure one exists
bootPath := entityPath(pt, "/boot")
if bootPath == nil {
_, err := pt.CreateMountpoint("/boot", 512*datasizes.MiB)
if err != nil {
return fmt.Errorf("failed to create /boot partition when ensuring btrfs: %w", err)
}
rootPath = entityPath(pt, "/")
}
parent := rootPath[1] // NB: entityPath has reversed order
if _, ok := parent.(*Btrfs); ok {
return nil
} else if part, ok := parent.(*Partition); ok {
rootMountable, ok := rootPath[0].(Mountable)
if !ok {
return fmt.Errorf("root entity is not mountable: %T, this is a violation of entityPath() contract", rootPath[0])
}
opts, err := rootMountable.GetFSTabOptions()
if err != nil {
return err
}
btrfs := &Btrfs{
Label: "root",
Subvolumes: []BtrfsSubvolume{
{
Name: "root",
Mountpoint: "/",
Compress: DefaultBtrfsCompression,
ReadOnly: opts.ReadOnly(),
Size: part.Size,
},
},
}
// replace the top-level partition payload with a new btrfs filesystem
part.Payload = btrfs
// reset the btrfs partition size - it will be grown later
part.Size = 0
part.Type, err = getPartitionTypeIDfor(pt.Type, "data")
if err != nil {
return fmt.Errorf("error converting partition table to btrfs: %w", err)
}
} else {
return fmt.Errorf("unsupported parent for btrfs: %T", parent)
}
return nil
}
type partitionTableFeatures struct {
LVM bool
Btrfs bool
XFS bool
FAT bool
EXT4 bool
LUKS bool
}
// features examines all of the PartitionTable entities
// and returns a struct with flags set for each feature used
func (pt *PartitionTable) features() partitionTableFeatures {
var ptFeatures partitionTableFeatures
introspectPT := func(e Entity, path []Entity) error {
switch ent := e.(type) {
case *LVMLogicalVolume:
ptFeatures.LVM = true
case *Btrfs:
ptFeatures.Btrfs = true
case *Filesystem:
switch ent.GetFSType() {
case "vfat":
ptFeatures.FAT = true
case "btrfs":
ptFeatures.Btrfs = true
case "xfs":
ptFeatures.XFS = true
case "ext4":
ptFeatures.EXT4 = true
}
case *LUKSContainer:
ptFeatures.LUKS = true
}
return nil
}
_ = pt.ForEachEntity(introspectPT)
return ptFeatures
}
// GetBuildPackages returns an array of packages needed to support the features used in the PartitionTable.
func (pt *PartitionTable) GetBuildPackages() []string {
packages := []string{}
features := pt.features()
if features.LVM {
packages = append(packages, "lvm2")
}
if features.Btrfs {
packages = append(packages, "btrfs-progs")
}
if features.XFS {
packages = append(packages, "xfsprogs")
}
if features.FAT {
packages = append(packages, "dosfstools")
}
if features.EXT4 {
packages = append(packages, "e2fsprogs")
}
if features.LUKS {
packages = append(packages,
"clevis",
"clevis-luks",
"cryptsetup",
)
}
return packages
}
// GetMountpointSize takes a mountpoint and returns the size of the entity this
// mountpoint belongs to.
func (pt *PartitionTable) GetMountpointSize(mountpoint string) (uint64, error) {
path := entityPath(pt, mountpoint)
if path == nil {
return 0, fmt.Errorf("cannot find mountpoint %s", mountpoint)
}
for _, ent := range path {
if sizeable, ok := ent.(Sizeable); ok {
return sizeable.GetSize(), nil
}
}
panic(fmt.Sprintf("no sizeable of the entity path for mountpoint %s, this is a programming error", mountpoint))
}
// EnsureRootFilesystem adds a root filesystem if the partition table doesn't
// already have one.
//
// When adding the root filesystem, add it to:
//
// - The first LVM Volume Group if one exists, otherwise
// - The first Btrfs volume if one exists, otherwise
// - At the end of the plain partitions.
//
// For LVM and Plain, the fsType argument must be a valid filesystem type.
func EnsureRootFilesystem(pt *PartitionTable, defaultFsType FSType) error {
// collect all labels and subvolume names to avoid conflicts
subvolNames := make(map[string]bool)
labels := make(map[string]bool)
var foundRoot bool
_ = pt.ForEachMountable(func(mnt Mountable, path []Entity) error {
if mnt.GetMountpoint() == "/" {
foundRoot = true
return nil
}
labels[mnt.GetFSSpec().Label] = true
switch mountable := mnt.(type) {
case *BtrfsSubvolume:
subvolNames[mountable.Name] = true
}
return nil
})
if foundRoot {
// nothing to do
return nil
}
for _, part := range pt.Partitions {
switch payload := part.Payload.(type) {
case *LVMVolumeGroup:
if defaultFsType == FS_NONE {
return fmt.Errorf("error creating root logical volume: no default filesystem type")
}
rootLabel, err := genUniqueString("root", labels)
if err != nil {
return fmt.Errorf("error creating root logical volume: %w", err)
}
rootfs := &Filesystem{
Type: defaultFsType.String(),
Label: rootLabel,
Mountpoint: "/",
FSTabOptions: "defaults",
}
// Let the function autogenerate the name to avoid conflicts
// with LV names from customizations.
// Set the size to 0 and it will be adjusted by
// EnsureDirectorySizes() and relayout().
if _, err := payload.CreateLogicalVolume("", 0, rootfs); err != nil {
return fmt.Errorf("error creating root logical volume: %w", err)
}
return nil
case *Btrfs:
rootName, err := genUniqueString("root", subvolNames)
if err != nil {
return fmt.Errorf("error creating root subvolume: %w", err)
}
rootsubvol := BtrfsSubvolume{
Name: rootName,
Mountpoint: "/",
}
payload.Subvolumes = append(payload.Subvolumes, rootsubvol)
return nil
}
}
// We're going to create a root partition, so we have to ensure the default type is set.
if defaultFsType == FS_NONE {
return fmt.Errorf("error creating root partition: no default filesystem type")
}
// add a plain root partition at the end of the partition table
rootLabel, err := genUniqueString("root", labels)
if err != nil {
return fmt.Errorf("error creating root partition: %w", err)
}
partType, err := getPartitionTypeIDfor(pt.Type, "data")
if err != nil {
return fmt.Errorf("error creating root partition: %w", err)
}
rootpart := Partition{
Type: partType,
Size: 0, // Set the size to 0 and it will be adjusted by EnsureDirectorySizes() and relayout()
Payload: &Filesystem{
Type: defaultFsType.String(),
Label: rootLabel,
Mountpoint: "/",
FSTabOptions: "defaults",
},
}
pt.Partitions = append(pt.Partitions, rootpart)
return nil
}
// addBootPartition creates a boot partition. The function will append the boot
// partition to the end of the existing partition table therefore it is best to