/
vm.go
271 lines (210 loc) · 6.59 KB
/
vm.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
package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
lxdShared "github.com/canonical/lxd/shared"
"golang.org/x/sys/unix"
"github.com/canonical/lxd-imagebuilder/shared"
)
type vm struct {
imageFile string
loopDevice string
rootFS string
rootfsDir string
size uint64
ctx context.Context
}
func newVM(ctx context.Context, imageFile, rootfsDir, fs string, size uint64) (*vm, error) {
if fs == "" {
fs = "ext4"
}
if !slices.Contains([]string{"btrfs", "ext4"}, fs) {
return nil, fmt.Errorf("Unsupported fs: %s", fs)
}
if size == 0 {
size = 4294967296
}
return &vm{ctx: ctx, imageFile: imageFile, rootfsDir: rootfsDir, rootFS: fs, size: size}, nil
}
func (v *vm) getLoopDev() string {
return v.loopDevice
}
func (v *vm) getRootfsDevFile() string {
if v.loopDevice == "" {
return ""
}
return fmt.Sprintf("%sp2", v.loopDevice)
}
func (v *vm) getUEFIDevFile() string {
if v.loopDevice == "" {
return ""
}
return fmt.Sprintf("%sp1", v.loopDevice)
}
func (v *vm) createEmptyDiskImage() error {
f, err := os.Create(v.imageFile)
if err != nil {
return fmt.Errorf("Failed to open %s: %w", v.imageFile, err)
}
defer f.Close()
err = f.Chmod(0600)
if err != nil {
return fmt.Errorf("Failed to chmod %s: %w", v.imageFile, err)
}
err = f.Truncate(int64(v.size))
if err != nil {
return fmt.Errorf("Failed to create sparse file %s: %w", v.imageFile, err)
}
return nil
}
func (v *vm) createPartitions() error {
args := [][]string{
{"--zap-all"},
{"--new=1::+100M", "-t 1:EF00"},
{"--new=2::", "-t 2:8300"},
}
for _, cmd := range args {
err := shared.RunCommand(v.ctx, nil, nil, "sgdisk", append([]string{v.imageFile}, cmd...)...)
if err != nil {
return fmt.Errorf("Failed to create partitions: %w", err)
}
}
return nil
}
func (v *vm) mountImage() error {
// If loopDevice is set, it probably is already mounted.
if v.loopDevice != "" {
return nil
}
var out strings.Builder
err := shared.RunCommand(v.ctx, nil, &out, "losetup", "-P", "-f", "--show", v.imageFile)
if err != nil {
return fmt.Errorf("Failed to setup loop device: %w", err)
}
v.loopDevice = strings.TrimSpace(out.String())
out.Reset()
// Ensure the partitions are accessible. This part is usually only needed
// if building inside of a container.
err = shared.RunCommand(v.ctx, nil, &out, "lsblk", "--raw", "--output", "MAJ:MIN", "--noheadings", v.loopDevice)
if err != nil {
return fmt.Errorf("Failed to list block devices: %w", err)
}
deviceNumbers := strings.Split(out.String(), "\n")
if !lxdShared.PathExists(v.getUEFIDevFile()) {
fields := strings.Split(deviceNumbers[1], ":")
major, err := strconv.Atoi(fields[0])
if err != nil {
return fmt.Errorf("Failed to parse %q: %w", fields[0], err)
}
minor, err := strconv.Atoi(fields[1])
if err != nil {
return fmt.Errorf("Failed to parse %q: %w", fields[1], err)
}
dev := unix.Mkdev(uint32(major), uint32(minor))
err = unix.Mknod(v.getUEFIDevFile(), unix.S_IFBLK|0644, int(dev))
if err != nil {
return fmt.Errorf("Failed to create block device %q: %w", v.getUEFIDevFile(), err)
}
}
if !lxdShared.PathExists(v.getRootfsDevFile()) {
fields := strings.Split(deviceNumbers[2], ":")
major, err := strconv.Atoi(fields[0])
if err != nil {
return fmt.Errorf("Failed to parse %q: %w", fields[0], err)
}
minor, err := strconv.Atoi(fields[1])
if err != nil {
return fmt.Errorf("Failed to parse %q: %w", fields[1], err)
}
dev := unix.Mkdev(uint32(major), uint32(minor))
err = unix.Mknod(v.getRootfsDevFile(), unix.S_IFBLK|0644, int(dev))
if err != nil {
return fmt.Errorf("Failed to create block device %q: %w", v.getRootfsDevFile(), err)
}
}
return nil
}
func (v *vm) umountImage() error {
// If loopDevice is empty, the image probably isn't mounted.
if v.loopDevice == "" || !lxdShared.PathExists(v.loopDevice) {
return nil
}
err := shared.RunCommand(v.ctx, nil, nil, "losetup", "-d", v.loopDevice)
if err != nil {
return fmt.Errorf("Failed to detach loop device: %w", err)
}
// Make sure that p1 and p2 are also removed.
if lxdShared.PathExists(v.getUEFIDevFile()) {
err := os.Remove(v.getUEFIDevFile())
if err != nil {
return fmt.Errorf("Failed to remove file %q: %w", v.getUEFIDevFile(), err)
}
}
if lxdShared.PathExists(v.getRootfsDevFile()) {
err := os.Remove(v.getRootfsDevFile())
if err != nil {
return fmt.Errorf("Failed to remove file %q: %w", v.getRootfsDevFile(), err)
}
}
v.loopDevice = ""
return nil
}
func (v *vm) createRootFS() error {
if v.loopDevice == "" {
return errors.New("Disk image not mounted")
}
switch v.rootFS {
case "btrfs":
err := shared.RunCommand(v.ctx, nil, nil, "mkfs.btrfs", "-f", "-L", "rootfs", v.getRootfsDevFile())
if err != nil {
return fmt.Errorf("Failed to create btrfs filesystem: %w", err)
}
// Create the root subvolume as well
err = shared.RunCommand(v.ctx, nil, nil, "mount", "-t", v.rootFS, v.getRootfsDevFile(), v.rootfsDir)
if err != nil {
return fmt.Errorf("Failed to mount %q at %q: %w", v.getRootfsDevFile(), v.rootfsDir, err)
}
defer func() {
_ = shared.RunCommand(v.ctx, nil, nil, "umount", v.rootfsDir)
}()
return shared.RunCommand(v.ctx, nil, nil, "btrfs", "subvolume", "create", fmt.Sprintf("%s/@", v.rootfsDir))
case "ext4":
return shared.RunCommand(v.ctx, nil, nil, "mkfs.ext4", "-F", "-b", "4096", "-i 8192", "-m", "0", "-L", "rootfs", "-E", "resize=536870912", v.getRootfsDevFile())
}
return nil
}
func (v *vm) createUEFIFS() error {
if v.loopDevice == "" {
return errors.New("Disk image not mounted")
}
return shared.RunCommand(v.ctx, nil, nil, "mkfs.vfat", "-F", "32", "-n", "UEFI", v.getUEFIDevFile())
}
func (v *vm) mountRootPartition() error {
if v.loopDevice == "" {
return errors.New("Disk image not mounted")
}
switch v.rootFS {
case "btrfs":
return shared.RunCommand(v.ctx, nil, nil, "mount", v.getRootfsDevFile(), v.rootfsDir, "-t", v.rootFS, "-o", "defaults,discard,nobarrier,commit=300,noatime,subvol=/@")
case "ext4":
return shared.RunCommand(v.ctx, nil, nil, "mount", v.getRootfsDevFile(), v.rootfsDir, "-t", v.rootFS, "-o", "discard,nobarrier,commit=300,noatime,data=writeback")
}
return nil
}
func (v *vm) mountUEFIPartition() error {
if v.loopDevice == "" {
return errors.New("Disk image not mounted")
}
mountpoint := filepath.Join(v.rootfsDir, "boot", "efi")
err := os.MkdirAll(mountpoint, 0755)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", mountpoint, err)
}
return shared.RunCommand(v.ctx, nil, nil, "mount", "-t", "vfat", v.getUEFIDevFile(), mountpoint, "-o", "discard")
}