Skip to content

Commit 95717e1

Browse files
authored
Merge pull request #3391 from nirs/round-up-disk-size
disk: Round up disk size to 512 bytes
2 parents 60f6e0b + 6edc1c0 commit 95717e1

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

pkg/nativeimgutil/nativeimgutil.go

+15-2
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

+18
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)