generated from hashicorp/packer-plugin-scaffolding
-
Notifications
You must be signed in to change notification settings - Fork 17
/
step_disk_file_prepare.go
100 lines (77 loc) · 2.34 KB
/
step_disk_file_prepare.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
package tart
import (
"context"
"errors"
"github.com/diskfs/go-diskfs"
"github.com/diskfs/go-diskfs/partition/gpt"
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
"os"
"path"
)
type stepDiskFilePrepare struct {
vmName string
}
func (s *stepDiskFilePrepare) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
ui := state.Get("ui").(packersdk.Ui)
ui.Say("Inspecting machine disk image...")
homeDir, err := os.UserHomeDir()
if err != nil {
ui.Error(err.Error())
return multistep.ActionHalt
}
diskImagePath := path.Join(homeDir, ".tart", "vms", config.VMName, "disk.img")
if config.DiskSizeGb > 0 {
err = growDisk(config.DiskSizeGb, diskImagePath)
if err != nil {
ui.Error(err.Error())
return multistep.ActionHalt
}
state.Put("disk-changed", true)
}
disk, err := diskfs.Open(diskImagePath)
if err != nil {
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say("Getting partition table...")
partitionTable, err := disk.GetPartitionTable()
if err != nil {
ui.Error(err.Error())
return multistep.ActionHalt
}
gptTable := partitionTable.(*gpt.Table)
for i, partition := range gptTable.Partitions {
if partition.Name != "RecoveryOSContainer" {
continue
}
ui.Say("Found recovery partition. Let's remove it to save space...")
// there are max 128 partitions and we probably on the third one
// the rest are just empty structs so let's reuse them
gptTable.Partitions[i] = gptTable.Partitions[len(gptTable.Partitions)-1]
err = disk.Partition(gptTable)
if err != nil {
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say("Successfully updated partitions...")
state.Put("disk-changed", true)
break
}
return multistep.ActionContinue
}
func growDisk(diskSizeGb uint16, diskImagePath string) error {
desiredSizeInBytes := int64(diskSizeGb) * 1_000_000_000
diskImageStat, err := os.Stat(diskImagePath)
if err != nil {
return err
}
if diskImageStat.Size() > desiredSizeInBytes {
return errors.New("Image disk is larger then desired! Only disk size increasing is supported! Can't shrink the disk ATM. :-(")
}
return os.Truncate(diskImagePath, desiredSizeInBytes)
}
// Cleanup stops the VM.
func (s *stepDiskFilePrepare) Cleanup(state multistep.StateBag) {
}