Skip to content

Commit 6edc1c0

Browse files
committed
disk: Round up disk size to 512 bytes
Apple virtualization framework rejects disks if the disk size is not aligned to 512 bytes. QEMU block layer round the size up when creating or resizing disks. Let's do the same to ensure that we don't create or resize disk to unusable size. I added only trivial tests fro the RoundUp helper since this kind of code is easy to get wrong. We need to add more tests for creating and resizing disk images. Fixes #3390 Signed-off-by: Nir Soffer <[email protected]>
1 parent 377c1f7 commit 6edc1c0

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

pkg/nativeimgutil/nativeimgutil.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,17 @@ import (
2323
"github.com/sirupsen/logrus"
2424
)
2525

26+
// Disk image size must be aigned to sector size. Qemu block layer is rounding
27+
// up the size to 512 bytes. Apple virtualization framework reject disks not
28+
// aligned to 512 bytes.
29+
const sectorSize = 512
30+
31+
// RoundUp rounds size up to sectorSize.
32+
func RoundUp(size int) int {
33+
sectors := (size + sectorSize - 1) / sectorSize
34+
return sectors * sectorSize
35+
}
36+
2637
// CreateRawDataDisk creates an empty raw data disk.
2738
func CreateRawDataDisk(dir string, size int) error {
2839
dataDisk := filepath.Join(dir, filenames.DataDisk)
@@ -34,13 +45,15 @@ func CreateRawDataDisk(dir string, size int) error {
3445
return err
3546
}
3647
defer f.Close()
37-
return f.Truncate(int64(size))
48+
roundedSize := RoundUp(size)
49+
return f.Truncate(int64(roundedSize))
3850
}
3951

4052
// ResizeRawDataDisk resizes a raw data disk.
4153
func ResizeRawDataDisk(dir string, size int) error {
4254
dataDisk := filepath.Join(dir, filenames.DataDisk)
43-
return os.Truncate(dataDisk, int64(size))
55+
roundedSize := RoundUp(size)
56+
return os.Truncate(dataDisk, int64(roundedSize))
4457
}
4558

4659
// ConvertToRaw converts a source disk into a raw disk.

pkg/nativeimgutil/nativeimgutil_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,24 @@ import (
1313
"gotest.tools/v3/assert"
1414
)
1515

16+
func TestRoundUp(t *testing.T) {
17+
tests := []struct {
18+
Size int
19+
Rounded int
20+
}{
21+
{0, 0},
22+
{1, 512},
23+
{511, 512},
24+
{512, 512},
25+
{123456789, 123457024},
26+
}
27+
for _, tc := range tests {
28+
if RoundUp(tc.Size) != tc.Rounded {
29+
t.Errorf("expected %d, got %d", tc.Rounded, tc.Size)
30+
}
31+
}
32+
}
33+
1634
func createImg(name, format, size string) error {
1735
return exec.Command("qemu-img", "create", name, "-f", format, size).Run()
1836
}

0 commit comments

Comments
 (0)