forked from clearlinux/clr-installer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ops.go
1846 lines (1542 loc) · 48.9 KB
/
ops.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
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: GPL-3.0-only
package storage
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/clearlinux/clr-installer/cmd"
"github.com/clearlinux/clr-installer/errors"
"github.com/clearlinux/clr-installer/log"
"github.com/clearlinux/clr-installer/progress"
"github.com/clearlinux/clr-installer/utils"
)
type blockDeviceOps struct {
makeFsCommand func(bd *BlockDevice, args []string) ([]string, error)
makeFsArgs []string
makePartCommand func(bd *BlockDevice) (string, error)
}
var (
bdOps = map[string]*blockDeviceOps{
"ext2": {commonMakeFsCommand, []string{"-v", "-F"}, commonMakePartCommand},
"ext3": {commonMakeFsCommand, []string{"-v", "-F"}, commonMakePartCommand},
"ext4": {commonMakeFsCommand, []string{"-v", "-F", "-b", "4096"}, commonMakePartCommand},
"btrfs": {commonMakeFsCommand, []string{"-f"}, commonMakePartCommand},
"xfs": {commonMakeFsCommand, []string{"-f"}, commonMakePartCommand},
"swap": {swapMakeFsCommand, []string{}, swapMakePartCommand},
"vfat": {commonMakeFsCommand, []string{"-F32"}, vfatMakePartCommand},
}
guidMap = map[string]string{
"/": "4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709",
"/home": "933AC7E1-2EB4-4F13-B844-0E14E2AEF915",
"/srv": "3B8F8425-20E0-4F3B-907F-1A25A76F98E8",
"swap": "0657FD6D-A4AB-43C4-84E5-0933C84B4F4F",
"efi": "C12A7328-F81F-11D2-BA4B-00A0C93EC93B",
}
mountedPoints []string
mountedEncrypts []string
)
// MakeFs runs mkfs.* commands for a BlockDevice definition
func (bd *BlockDevice) MakeFs() error {
if bd.Type == BlockDeviceTypeDisk {
return errors.Errorf("Trying to run MakeFs() against a disk, partition required")
}
if op, ok := bdOps[bd.FsType]; ok {
if cmd, err := op.makeFsCommand(bd, op.makeFsArgs); err == nil {
return makeFs(bd, cmd)
}
}
return errors.Errorf("MakeFs() not implemented for filesystem: %s", bd.FsType)
}
func makeFs(bd *BlockDevice, args []string) error {
if bd.Options != "" {
args = append(args, strings.Split(bd.Options, " ")...)
}
args = append(args, bd.GetMappedDeviceFile())
err := cmd.RunAndLog(args...)
if err != nil {
return errors.Wrap(err)
}
// Updated the UUID and LABEL now that we made the fs
err = bd.updatePartitionInfo()
if err != nil {
return errors.Wrap(err)
}
return nil
}
func (bd *BlockDevice) updatePartitionInfo() error {
if bd.Type == BlockDeviceTypeDisk {
return errors.Errorf("Trying to run updatePartitionInfo() against a disk, partition required")
}
var err error
blkid := bytes.NewBuffer(nil)
devFile := bd.GetDeviceFile()
// Read the partition blkid info
err = cmd.Run(blkid,
"blkid",
"--probe",
devFile,
"--output",
"export",
)
if err != nil {
log.Warning("updatePartitionInfo() had an error reading blkid %q",
fmt.Sprintf("%s", blkid.String()))
return err
}
for _, line := range strings.Split(blkid.String(), "\n") {
fields := strings.Split(line, "=")
if len(fields) == 2 {
if fields[0] == "LABEL" {
bd.Label = fields[1]
log.Debug("updatePartitionInfo: Updated %d LABEL: %s", devFile, bd.Label)
} else if fields[0] == "UUID" {
bd.UUID = fields[1]
log.Debug("updatePartitionInfo: Updated %d UUID: %s", devFile, bd.UUID)
}
} else {
log.Debug("updatePartitionInfo: Ignoring unknown line: %s", line)
}
}
return err
}
// getGUID determines the partition type guid either based on:
// + mount point
// + file system type (i.e swap)
// + or if it's the "special" efi case
func (bd *BlockDevice) getGUID() (string, error) {
if guid, ok := guidMap[bd.MountPoint]; ok {
return guid, nil
}
if guid, ok := guidMap[bd.FsType]; ok {
return guid, nil
}
if bd.FsType == "vfat" && bd.MountPoint == "/boot" {
return guidMap["efi"], nil
}
return "none", errors.Errorf("Could not determine the guid for: %s", bd.Name)
}
func (bd *BlockDevice) isStandardMount() bool {
standard := false
for mnt := range guidMap {
if bd.MountPoint == mnt {
standard = true
}
}
if bd.MountPoint == "/boot" {
standard = true
}
return standard
}
// Mount will mount a block devices bd considering its mount point and the
// root directory
func (bd *BlockDevice) Mount(root string) error {
if bd.Type == BlockDeviceTypeDisk {
return errors.Errorf("Trying to run mountFs() against a disk, partition required")
}
targetPath := filepath.Join(root, bd.MountPoint)
return mountFs(bd.GetMappedDeviceFile(), targetPath, bd.FsType, syscall.MS_RELATIME)
}
// UmountAll unmounts all previously mounted devices
func UmountAll() error {
var mountError error
fails := make([]string, 0)
// Ensure the top level mount point is unmounted last
sort.Sort(sort.Reverse(sort.StringSlice(mountedPoints)))
for _, point := range mountedPoints {
if err := syscall.Unmount(point, syscall.MNT_FORCE|syscall.MNT_DETACH); err != nil {
err = fmt.Errorf("umount %s: %v", point, err)
log.ErrorError(err)
fails = append(fails, point)
} else {
log.Debug("Unmounted ok: %s", point)
}
}
for _, point := range mountedEncrypts {
if err := unMapEncrypted(point); err != nil {
err = fmt.Errorf("unmap encrypted %s: %v", point, err)
log.ErrorError(err)
fails = append(fails, "e-"+point)
} else {
log.Debug("Encrypted partition %q unmapped", point)
}
}
if len(fails) > 0 {
mountError = errors.Errorf("Failed to unmount: %v", fails)
}
return mountError
}
// When you specify a start (or end) position to the parted mkpart command,
// it internally generates a range of acceptable values centered on the value
// you specify, and extends equally on both sides by half the unit size you
// used but ONLY when you use K or M (or G); using B or any of the XiB will
// not auto align.
// We choose M to provide a 1M wide window for a possible optimal value.
func getStartEndMB(start uint64, end uint64) string {
startMB := (start / (1000 * 1000))
endMB := (end / (1000 * 1000))
strStart := fmt.Sprintf("%dM", startMB)
if start < 1 {
strStart = "0%"
}
strEnd := fmt.Sprintf("%dM", endMB)
if end < 1 {
strEnd = "-1"
}
return strStart + " " + strEnd
}
// WritePartitionLabel make a device a 'gpt' partition type
// Only call when we are wiping and reusing the entire disk
func (bd *BlockDevice) WritePartitionLabel() error {
if bd.Type != BlockDeviceTypeDisk && bd.Type != BlockDeviceTypeLoop {
return errors.Errorf("Type is partition, disk required")
}
mesg := utils.Locale.Get("Writing partition table to: %s", bd.Name)
prg := progress.NewLoop(mesg)
log.Info(mesg)
args := []string{
"parted",
"-s",
bd.GetDeviceFile(),
"mklabel",
"gpt",
}
err := cmd.RunAndLog(args...)
if err != nil {
return errors.Wrap(err)
}
prg.Success()
return nil
}
// WritePartitionTable writes the defined partitions to the actual block device
func (bd *BlockDevice) WritePartitionTable(legacyBios bool, wholeDisk bool, dryRun *[]string) error {
if bd.Type != BlockDeviceTypeDisk && bd.Type != BlockDeviceTypeLoop {
return errors.Errorf("Type is partition, disk required")
}
var prg progress.Progress
//write the partition label
if dryRun != nil {
if wholeDisk {
*dryRun = append(*dryRun, bd.Name+": "+utils.Locale.Get(PartitioningWarning))
}
} else {
if wholeDisk {
if err := bd.WritePartitionLabel(); err != nil {
return err
}
} else {
log.Debug("WritePartitionTable: partial disk, skipping mklabel for %s", bd.Name)
}
mesg := utils.Locale.Get("Updating partition table for: %s", bd.Name)
prg = progress.NewLoop(mesg)
log.Info(mesg)
}
var err error
var start uint64
maxFound := false
// First remove any user removed partitions
if len(bd.removedParts) > 0 {
rmArgs := []string{
"parted",
"-a",
"optimal",
bd.GetDeviceFile(),
"unit", "MB",
"--script",
"--",
}
for _, curr := range bd.removedParts {
if dryRun == nil {
rmArgs = append(rmArgs, fmt.Sprintf("rm %d", curr))
} else {
*dryRun = append(*dryRun, fmt.Sprintf("%s: %s",
bd.GetNewPartitionName(curr),
utils.Locale.Get(RemoveParitionWarning)))
}
}
if dryRun == nil {
log.Debug("WritePartitionTable: remove partitions : %v", bd.removedParts)
err = cmd.RunAndLog(rmArgs...)
if err != nil {
log.Warning("Failed to remove existing partition: %v (%s)", bd.removedParts, err)
}
}
}
// Initialize the partition list before we add new ones
currentPartitions := bd.getPartitionList()
// Sort the partitions by name before writing the partition table
log.Debug("Partitions before sorting:")
for _, part := range bd.Children {
part.logDetails()
}
sort.Sort(ByBDName(bd.Children))
log.Debug("Partitions after sorting:")
for _, part := range bd.Children {
part.logDetails()
// Make sure each partition has a number set
part.SetPartitionNumber(part.GetPartitionNumber())
}
// Make the needed new partitions
for _, curr := range bd.Children {
if dryRun != nil {
if curr.MakePartition {
size, _ := HumanReadableSizeWithPrecision(curr.Size, 1)
*dryRun = append(*dryRun, fmt.Sprintf("%s: %s [%s]",
bd.Name, utils.Locale.Get(AddPartitionInfo), size))
}
continue
}
log.Debug("WritePartitionTable: processing child: %v", curr)
baseArgs := []string{
"parted",
"-a",
"optimal",
bd.GetDeviceFile(),
"unit", "MB",
"--script",
"--",
}
if !curr.MakePartition {
log.Debug("WritePartitionTable: skipping partition %s", curr.Name)
continue
}
var mkPart string
op, found := bdOps[curr.FsType]
if !found {
return errors.Errorf("No makePartCommand() implementation for: %s",
curr.FsType)
}
mkPart, err = op.makePartCommand(curr)
if err != nil {
return err
}
size := uint64(curr.Size)
end := start + size
if !wholeDisk {
start, end = bd.getPartitionStartEnd(curr.partition)
} else {
log.Debug("WritePartitionTable: WholeDisk mode")
}
log.Debug("WritePartitionTable: start: %d, end: %d", start, end)
if size < 1 {
if maxFound {
return errors.Errorf("Found more than one partition with size 0 for %s!", bd.Name)
}
maxFound = true
end = 0
}
retries := 3
for {
mkPartCmd := mkPart + " " + getStartEndMB(start, end)
log.Debug("WritePartitionTable: mkPartCmd: %s", mkPartCmd)
args := append(baseArgs, mkPartCmd)
err = cmd.RunAndLog(args...)
if err == nil || retries == 0 {
break
}
// Move the start position ahead one MB in an attempt
// to find a working optimal partition entry
start = start + (1000 * 1000)
retries--
}
if err != nil {
return errors.Wrap(err)
}
// Get the new list of partitions
newPartitions := bd.getPartitionList()
// The current partition is new one added
curr.SetPartitionNumber(findNewPartition(currentPartitions, newPartitions).Number)
start = end
currentPartitions = newPartitions
}
if dryRun == nil {
var bootPartition uint64
bootStyle := "boot"
guids := map[int]string{}
// Now that all new partitions are created,
// and we know their assigned numbers ...
for _, curr := range bd.Children {
// First, check if we have the standard /boot partition
// We have a /boot partition, use this
if curr.MountPoint == "/boot" {
bootPartition = curr.partition
if legacyBios {
bootStyle = "legacy_boot"
}
}
var guid string
guid, err = curr.getGUID()
if err != nil {
log.Warning("%s", err)
}
if curr.FsType != "swap" || curr.Type != BlockDeviceTypeCrypt {
guids[int(curr.partition)] = guid
}
}
prg.Success()
msg := utils.Locale.Get("Adjusting filesystem configurations")
prg = progress.MultiStep(len(guids), msg)
log.Info(msg)
cnt := 1
for idx, guid := range guids {
if guid == "none" {
continue
}
args := []string{
"sgdisk",
bd.GetDeviceFile(),
fmt.Sprintf("--typecode=%d:%s", idx, guid),
}
err = cmd.RunAndLog(args...)
if err != nil {
return errors.Wrap(err)
}
prg.Partial(cnt)
cnt = cnt + 1
}
// In case we didn't have a /boot partition, we
// need to set / as boot
for _, curr := range bd.Children {
// Only check for / in new partitions
if !curr.MakePartition {
continue
}
if curr.MountPoint == "/" {
// If legacyBios mode and we do not have a boot, use root
if legacyBios && bootPartition == 0 {
bootPartition = curr.partition
bootStyle = "legacy_boot"
}
}
}
if bootPartition != 0 {
args := []string{
"parted",
bd.GetDeviceFile(),
fmt.Sprintf("set %d %s on", bootPartition, bootStyle),
}
err = cmd.RunAndLog(args...)
if err != nil {
return errors.Wrap(err)
}
}
if err = bd.PartProbe(); err != nil {
prg.Failure()
return err
}
time.Sleep(time.Duration(4) * time.Second)
prg.Success()
}
return nil
}
func (bd *BlockDevice) getPartitionList() []*PartedPartition {
var partitionList []*PartedPartition
var err error
partTable := bytes.NewBuffer(nil)
devFile := bd.GetDeviceFile()
if !utils.IntSliceContains([]int{BlockDeviceTypeDisk, BlockDeviceTypeLoop}, int(bd.Type)) {
log.Warning("getPartitionList() called on non-disk %q", devFile)
return partitionList
}
// Read the partition table for the device
err = cmd.Run(partTable,
"parted",
"--machine",
"--script",
"--",
devFile,
"unit",
"B",
"print",
)
if err != nil {
log.Warning("getPartitionList() had an error reading partition table %q",
fmt.Sprintf("%s", partTable.String()))
return partitionList
}
for _, line := range strings.Split(partTable.String(), ";\n") {
partition := &PartedPartition{}
fields := strings.Split(line, ":")
if len(fields) == 7 {
partition.Number, err = strconv.ParseUint(fields[0], 10, 64)
if err != nil {
log.Warning("getPartitionList: Failed to parse partition number from: %s", line)
}
partition.Start, err = strconv.ParseUint(strings.TrimRight(fields[1], "B"), 10, 64)
if err != nil {
log.Warning("getPartitionList: Failed to parse start position from: %s", line)
}
partition.End, err = strconv.ParseUint(strings.TrimRight(fields[2], "B"), 10, 64)
if err != nil {
log.Warning("getPartitionList: Failed to parse end position from: %s", line)
}
partition.Size, err = strconv.ParseUint(strings.TrimRight(fields[3], "B"), 10, 64)
if err != nil {
log.Warning("getPartitionList: Failed to parse partition size from: %s", line)
}
partition.FileSystem = fields[4]
partition.Name = fields[5]
partition.Flags = fields[6]
partitionList = append(partitionList, partition)
}
}
return partitionList
}
func findNewPartition(currentPartitions, newPartitions []*PartedPartition) *PartedPartition {
newPartition := &PartedPartition{}
if len(newPartitions) <= len(currentPartitions) {
log.Warning("findNewPartition: number of new partitions is not greater than the current")
return newPartition
}
if len(newPartitions)-len(currentPartitions) != 1 {
log.Warning("findNewPartition: number of new partition is more than 1")
return newPartition
}
for _, newPart := range newPartitions {
found := true
for _, curPart := range currentPartitions {
if curPart.Number == newPart.Number {
found = false
continue
}
}
if found {
newPartition = newPart
continue
}
}
return newPartition
}
func (bd *BlockDevice) getPartitionTable() *bytes.Buffer {
partTable := bytes.NewBuffer(nil)
devFile := bd.GetDeviceFile()
if !utils.IntSliceContains([]int{BlockDeviceTypeDisk, BlockDeviceTypeLoop}, int(bd.Type)) {
log.Warning("getPartitionTable() called on non-disk %q", devFile)
return partTable
}
// Read the partition table for the device
err := cmd.Run(partTable,
"parted",
"--machine",
"--script",
"--",
devFile,
"unit",
"B",
"print",
"free",
)
if err != nil {
log.Warning("getPartitionTable() had an error reading partition table %q",
fmt.Sprintf("%s", partTable.String()))
empty := bytes.NewBuffer(nil)
return empty
}
return partTable
}
func (bd *BlockDevice) getPartitionStartEnd(partNumber uint64) (uint64, uint64) {
var start, end uint64
devFile := bd.GetDeviceFile()
if !utils.IntSliceContains([]int{BlockDeviceTypeDisk, BlockDeviceTypeLoop}, int(bd.Type)) {
log.Warning("getPartitionStartEnd() called on non-disk %q", devFile)
return start, end
}
for _, part := range bd.PartTable {
if part.Number == partNumber {
return part.Start, part.End
}
}
log.Warning("getPartitionStartEnd() did not find partition %s for disk %q", partNumber, devFile)
return start, end
}
// LargestContiguousFreeSpace returns the largest, contiguous block of free
// space in the partition table for the block device.
// If none found, returns {0, 0}
func (bd *BlockDevice) LargestContiguousFreeSpace(minSize uint64) (uint64, uint64) {
var start, end, size uint64
devFile := bd.GetDeviceFile()
if !utils.IntSliceContains([]int{BlockDeviceTypeDisk, BlockDeviceTypeLoop}, int(bd.Type)) {
log.Warning("LargestContiguousFreeSpace() called on non-disk %q", devFile)
return start, end
}
size = minSize - 1
for _, part := range bd.PartTable {
if part.Number == 0 && part.FileSystem == "free" {
if part.Size > size {
start = part.Start
end = part.End
}
}
}
return start, end
}
// AddFromFreePartition reduces the free partition by the size given
// User when adding a new partition to a disk from free space
func (bd *BlockDevice) AddFromFreePartition(parted *PartedPartition, child *BlockDevice) {
var next uint64
var partitionList []*PartedPartition
devFile := bd.GetDeviceFile()
if !utils.IntSliceContains([]int{BlockDeviceTypeDisk, BlockDeviceTypeLoop}, int(bd.Type)) {
log.Warning("AddFromFreePartition() called on non-disk %q", devFile)
return
}
const (
maxPartitions = 127
)
found := false
next = 1
for !found && next < maxPartitions {
present := false
for _, partition := range bd.PartTable {
if partition.Number == next {
present = true
break
}
}
if present {
next = next + 1
} else {
found = true
}
}
if next >= maxPartitions {
log.Warning("AddFromFreePartition() could not add new partition: %v", child)
return
}
for _, partition := range bd.PartTable {
// Find the partition to update/remove
if partition.Number == parted.Number &&
partition.Start == parted.Start {
log.Debug("Found the free partition to update: %v", partition)
addPart := partition.Clone()
addPart.Number = next
addPart.End = addPart.Start + (child.Size - 1)
addPart.Size = child.Size
addPart.FileSystem = ""
log.Debug("Adding the new partition: %v", addPart)
partitionList = append(partitionList, addPart)
child.SetPartitionNumber(addPart.Number)
bd.AddChild(child)
log.Debug("Added new child partition: %v", child)
newSize := partition.Size - addPart.Size
newStart := addPart.End + 1
log.Debug("Free partition newStart: %d, newSize: %d", newStart, newSize)
if (int(partition.End) - int(newStart)) <= 0 {
log.Debug("No Free space left: %v", partition)
continue
}
if newSize > (10 * 1024 * 1024) {
newPart := partition.Clone()
newPart.Start = newStart
newPart.Size = newSize
log.Debug("Found enough free to add back: %v", newPart)
partitionList = append(partitionList, newPart)
}
continue
}
log.Debug("Not the right partition, adding back: %v", partition)
partitionList = append(partitionList, partition)
}
bd.PartTable = partitionList
// Consolidate neighboring free partitions
bd.consolidateFree()
}
func (bd *BlockDevice) consolidateFree() {
last := &PartedPartition{}
var newPartTable []*PartedPartition
for _, part := range bd.PartTable {
// Found a free partition
if part.Number == 0 && part.FileSystem == "free" {
// And the last partition was also free, then consolidate
if last.Number == 0 && last.FileSystem == "free" {
last.End = part.End
last.Size = last.Size + part.Size
continue
}
}
newPart := part.Clone()
newPartTable = append(newPartTable, newPart)
last = newPart
}
bd.PartTable = newPartTable
}
// RemovePartition remove a child from the disk and updates
// frees the space in the partition table
func (bd *BlockDevice) RemovePartition(child *BlockDevice) *PartedPartition {
var removedPartition *PartedPartition
devFile := bd.GetDeviceFile()
if !utils.IntSliceContains([]int{BlockDeviceTypeDisk, BlockDeviceTypeLoop}, int(bd.Type)) {
log.Warning("RemovePartition() called on non-disk %q", devFile)
return removedPartition
}
deleteIndex := -1
for idx, curr := range bd.Children {
if curr.Name == child.Name {
child.Parent = nil
deleteIndex = idx
break
}
}
if deleteIndex < 0 {
log.Warning("RemovePartition() fail to find (and remove) child: %v", child)
return removedPartition
}
log.Debug("RemovePartition() found child partition index to delete %d", deleteIndex)
// keep a reference to the child
delelteChild := bd.Children[deleteIndex].Clone()
// Remove the child for the block devices
bd.Children = append(bd.Children[:deleteIndex], bd.Children[deleteIndex+1:]...)
partString := devNameSuffixExp.FindString(delelteChild.Name)
partNumber, err := strconv.ParseUint(partString, 10, 64)
if err != nil {
log.Warning("RemovePartition() fail to find child partition number: %v", child)
return removedPartition
}
log.Debug("RemovePartition() Need to add partition %d to the remove list", partNumber)
for _, partition := range bd.PartTable {
// Find the partition to free/remove
if partition.Number == partNumber {
log.Debug("Found the partition to free partition: %v", partition)
partition.Number = 0
partition.FileSystem = "free"
partition.Name = ""
partition.Flags = ""
removedPartition = partition.Clone()
break
}
}
// Consolidate neighboring free partitions
bd.consolidateFree()
if !delelteChild.MakePartition {
bd.addRemovePartition(partNumber)
log.Debug("RemovePartition() Add partition to be removed %d", partNumber)
}
return removedPartition
}
// Populate the current partition table for a disk device
func (bd *BlockDevice) setPartitionTable(partTable *bytes.Buffer) {
var partitionList []*PartedPartition
devFile := bd.GetDeviceFile()
if !utils.IntSliceContains([]int{BlockDeviceTypeDisk, BlockDeviceTypeLoop}, int(bd.Type)) {
log.Warning("setPartitionTable() called on non-disk %q", devFile)
return
}
var err error
for _, line := range strings.Split(partTable.String(), ";\n") {
partition := &PartedPartition{}
log.Debug("setPartitionTable() line is %q", line)
fields := strings.Split(line, ":")
if len(fields) == 7 {
partition.Number, err = strconv.ParseUint(fields[0], 10, 64)
if err != nil {
log.Warning("setPartitionTable: Failed to parse partition number from: %s", line)
}
partition.Start, err = strconv.ParseUint(strings.TrimRight(fields[1], "B"), 10, 64)
if err != nil {
log.Warning("setPartitionTable: Failed to parse start position from: %s", line)
}
partition.End, err = strconv.ParseUint(strings.TrimRight(fields[2], "B"), 10, 64)
if err != nil {
log.Warning("setPartitionTable: Failed to parse end position from: %s", line)
}
partition.Size, err = strconv.ParseUint(strings.TrimRight(fields[3], "B"), 10, 64)
if err != nil {
log.Warning("setPartitionTable: Failed to parse partition size from: %s", line)
}
partition.FileSystem = fields[4]
partition.Name = fields[5]
partition.Flags = fields[6]
partitionList = append(partitionList, partition)
continue
}
if len(fields) == 5 && fields[4] == "free" {
partition.Number = 0 // We use 0 to special case as a free partition
partition.Start, err = strconv.ParseUint(strings.TrimRight(fields[1], "B"), 10, 64)
if err != nil {
log.Warning("setPartitionTable: Failed to parse start position from: %s", line)
}
partition.End, err = strconv.ParseUint(strings.TrimRight(fields[2], "B"), 10, 64)
if err != nil {
log.Warning("setPartitionTable: Failed to parse end position from: %s", line)
}
partition.Size, err = strconv.ParseUint(strings.TrimRight(fields[3], "B"), 10, 64)
if err != nil {
log.Warning("setPartitionTable: Failed to parse partition size from: %s", line)
}
partition.FileSystem = fields[4]
partitionList = append(partitionList, partition)
}
}
bd.PartTable = partitionList
}
// MountMetaFs mounts proc, sysfs and devfs in the target installation directory
func MountMetaFs(rootDir string) error {
err := mountProcFs(rootDir)
if err != nil {
return err
}
err = mountSysFs(rootDir)
if err != nil {
return err
}
err = mountDevFs(rootDir)
if err != nil {
return err
}
return nil
}
func mountFs(device string, mPointPath string, fsType string, flags uintptr) error {
var err error
if _, err = os.Stat(mPointPath); os.IsNotExist(err) {
if err = os.MkdirAll(mPointPath, 0777); err != nil {
return errors.Errorf("mkdir %s: %v", mPointPath, err)
}
}
if err = syscall.Mount(device, mPointPath, fsType, flags, ""); err != nil {
return errors.Errorf("mount %s %s %s: %v", device, mPointPath, fsType, err)
}
log.Debug("Mounted ok: %s", mPointPath)
// Store the mount point for later unmounting
mountedPoints = append(mountedPoints, mPointPath)
return err
}
func mountDevFs(rootDir string) error {
mPointPath := filepath.Join(rootDir, "dev")
return mountFs("/dev", mPointPath, "devtmpfs", syscall.MS_BIND)
}
func mountSysFs(rootDir string) error {
mPointPath := filepath.Join(rootDir, "sys")
return mountFs("/sys", mPointPath, "sysfs", syscall.MS_BIND)
}
func mountProcFs(rootDir string) error {
mPointPath := filepath.Join(rootDir, "proc")
return mountFs("/proc", mPointPath, "proc", syscall.MS_BIND)
}
func getMakeFsLabel(bd *BlockDevice) []string {
label := []string{}
labelArg := "-L"
if bd.Label != "" {
maxLen := MaxLabelLength(bd.FsType)
if bd.FsType == "vfat" {
labelArg = "-n"