| 1 | |
| 2 | |
| 3 | |
| 4 | package qemuimgutil |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io/fs" |
| 13 | "os" |
| 14 | "os/exec" |
| 15 | "strconv" |
| 16 | |
| 17 | "github.com/lima-vm/go-qcow2reader/image" |
| 18 | "github.com/lima-vm/go-qcow2reader/image/raw" |
| 19 | "github.com/sirupsen/logrus" |
| 20 | ) |
| 21 | |
| 22 | const QemuImgFormat = "qcow2" |
| 23 | |
| 24 | |
| 25 | type QemuImageUtil struct { |
| 26 | DefaultFormat string |
| 27 | } |
| 28 | |
| 29 | |
| 30 | type Info struct { |
| 31 | Filename string `json:"filename,omitempty"` |
| 32 | Format string `json:"format,omitempty"` |
| 33 | VSize int64 `json:"virtual-size,omitempty"` |
| 34 | ActualSize int64 `json:"actual-size,omitempty"` |
| 35 | DirtyFlag bool `json:"dirty-flag,omitempty"` |
| 36 | ClusterSize int `json:"cluster-size,omitempty"` |
| 37 | BackingFilename string `json:"backing-filename,omitempty"` |
| 38 | FullBackingFilename string `json:"full-backing-filename,omitempty"` |
| 39 | BackingFilenameFormat string `json:"backing-filename-format,omitempty"` |
| 40 | FormatSpecific *InfoFormatSpecific `json:"format-specific,omitempty"` |
| 41 | Children []InfoChild `json:"children,omitempty"` |
| 42 | } |
| 43 | |
| 44 | type InfoChild struct { |
| 45 | Name string `json:"name,omitempty"` |
| 46 | Info Info `json:"info,omitempty"` |
| 47 | } |
| 48 | |
| 49 | type InfoFormatSpecific struct { |
| 50 | Type string `json:"type,omitempty"` |
| 51 | Data json.RawMessage `json:"data,omitempty"` |
| 52 | } |
| 53 | |
| 54 | func resizeDisk(ctx context.Context, disk, format string, size int64) error { |
| 55 | args := []string{"resize", "-f", format, disk, strconv.FormatInt(size, 10)} |
| 56 | cmd := exec.CommandContext(ctx, "qemu-img", args...) |
| 57 | if out, err := cmd.CombinedOutput(); err != nil { |
| 58 | return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err) |
| 59 | } |
| 60 | return nil |
| 61 | } |
| 62 | |
| 63 | func (sp *InfoFormatSpecific) Qcow2() *InfoFormatSpecificDataQcow2 { |
| 64 | if sp.Type != "qcow2" { |
| 65 | return nil |
| 66 | } |
| 67 | var x InfoFormatSpecificDataQcow2 |
| 68 | if err := json.Unmarshal(sp.Data, &x); err != nil { |
| 69 | panic(err) |
| 70 | } |
| 71 | return &x |
| 72 | } |
| 73 | |
| 74 | func (sp *InfoFormatSpecific) Vmdk() *InfoFormatSpecificDataVmdk { |
| 75 | if sp.Type != "vmdk" { |
| 76 | return nil |
| 77 | } |
| 78 | var x InfoFormatSpecificDataVmdk |
| 79 | if err := json.Unmarshal(sp.Data, &x); err != nil { |
| 80 | panic(err) |
| 81 | } |
| 82 | return &x |
| 83 | } |
| 84 | |
| 85 | type InfoFormatSpecificDataQcow2 struct { |
| 86 | Compat string `json:"compat,omitempty"` |
| 87 | DataFile string `json:"data-file,omitempty"` |
| 88 | LazyRefcounts bool `json:"lazy-refcounts,omitempty"` |
| 89 | Corrupt bool `json:"corrupt,omitempty"` |
| 90 | RefcountBits int `json:"refcount-bits,omitempty"` |
| 91 | CompressionType string `json:"compression-type,omitempty"` |
| 92 | ExtendedL2 bool `json:"extended-l2,omitempty"` |
| 93 | } |
| 94 | |
| 95 | type InfoFormatSpecificDataVmdk struct { |
| 96 | CreateType string `json:"create-type,omitempty"` |
| 97 | CID int `json:"cid,omitempty"` |
| 98 | ParentCID int `json:"parent-cid,omitempty"` |
| 99 | Extents []InfoFormatSpecificDataVmdkExtent `json:"extents,omitempty"` |
| 100 | } |
| 101 | |
| 102 | type InfoFormatSpecificDataVmdkExtent struct { |
| 103 | Filename string `json:"filename,omitempty"` |
| 104 | Format string `json:"format,omitempty"` |
| 105 | VSize int64 `json:"virtual-size,omitempty"` |
| 106 | ClusterSize int `json:"cluster-size,omitempty"` |
| 107 | } |
| 108 | |
| 109 | func convertToRaw(ctx context.Context, source, dest string) error { |
| 110 | if source != dest { |
| 111 | return execQemuImgConvert(ctx, source, dest) |
| 112 | } |
| 113 | |
| 114 | |
| 115 | |
| 116 | info, err := getInfo(ctx, source) |
| 117 | if err != nil { |
| 118 | return fmt.Errorf("failed to get info for source disk %#q: %w", source, err) |
| 119 | } |
| 120 | if info.Format == "raw" { |
| 121 | return nil |
| 122 | } |
| 123 | |
| 124 | tempFile := dest + ".lima-qemu-convert.tmp" |
| 125 | defer os.Remove(tempFile) |
| 126 | |
| 127 | if err := execQemuImgConvert(ctx, source, tempFile); err != nil { |
| 128 | return err |
| 129 | } |
| 130 | |
| 131 | return os.Rename(tempFile, dest) |
| 132 | } |
| 133 | |
| 134 | func execQemuImgConvert(ctx context.Context, source, dest string) error { |
| 135 | var stdout, stderr bytes.Buffer |
| 136 | cmd := exec.CommandContext(ctx, "qemu-img", "convert", "-O", "raw", source, dest) |
| 137 | cmd.Stdout = &stdout |
| 138 | cmd.Stderr = &stderr |
| 139 | if err := cmd.Run(); err != nil { |
| 140 | return fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w", |
| 141 | cmd.Args, stdout.String(), stderr.String(), err) |
| 142 | } |
| 143 | return nil |
| 144 | } |
| 145 | |
| 146 | func parseInfo(b []byte) (*Info, error) { |
| 147 | var imgInfo Info |
| 148 | if err := json.Unmarshal(b, &imgInfo); err != nil { |
| 149 | return nil, err |
| 150 | } |
| 151 | return &imgInfo, nil |
| 152 | } |
| 153 | |
| 154 | func getInfo(ctx context.Context, f string) (*Info, error) { |
| 155 | var stdout, stderr bytes.Buffer |
| 156 | cmd := exec.CommandContext(ctx, "qemu-img", "info", "--output=json", "--force-share", f) |
| 157 | cmd.Stdout = &stdout |
| 158 | cmd.Stderr = &stderr |
| 159 | if err := cmd.Run(); err != nil { |
| 160 | return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w", |
| 161 | cmd.Args, stdout.String(), stderr.String(), err) |
| 162 | } |
| 163 | return parseInfo(stdout.Bytes()) |
| 164 | } |
| 165 | |
| 166 | |
| 167 | func (q *QemuImageUtil) CreateDisk(ctx context.Context, disk string, size int64) error { |
| 168 | if _, err := os.Stat(disk); err == nil || !errors.Is(err, fs.ErrNotExist) { |
| 169 | |
| 170 | return err |
| 171 | } |
| 172 | |
| 173 | args := []string{"create", "-f", q.DefaultFormat, disk, strconv.FormatInt(size, 10)} |
| 174 | cmd := exec.CommandContext(ctx, "qemu-img", args...) |
| 175 | if out, err := cmd.CombinedOutput(); err != nil { |
| 176 | return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err) |
| 177 | } |
| 178 | return nil |
| 179 | } |
| 180 | |
| 181 | |
| 182 | func (q *QemuImageUtil) ResizeDisk(ctx context.Context, disk string, size int64) error { |
| 183 | info, err := getInfo(ctx, disk) |
| 184 | if err != nil { |
| 185 | return fmt.Errorf("failed to get info for disk %#q: %w", disk, err) |
| 186 | } |
| 187 | return resizeDisk(ctx, disk, info.Format, size) |
| 188 | } |
| 189 | |
| 190 | |
| 191 | func (q *QemuImageUtil) MakeSparse(_ context.Context, _ *os.File, _ int64) error { |
| 192 | return nil |
| 193 | } |
| 194 | |
| 195 | |
| 196 | func GetInfo(ctx context.Context, path string) (*Info, error) { |
| 197 | qemuInfo, err := getInfo(ctx, path) |
| 198 | if err != nil { |
| 199 | return nil, err |
| 200 | } |
| 201 | |
| 202 | return qemuInfo, nil |
| 203 | } |
| 204 | |
| 205 | |
| 206 | |
| 207 | func (q *QemuImageUtil) Convert(ctx context.Context, imageType image.Type, source, dest string, size *int64, allowSourceWithBackingFile bool) error { |
| 208 | if imageType != raw.Type { |
| 209 | return fmt.Errorf("QemuImageUtil.Convert only supports raw.Type, got %#q", imageType) |
| 210 | } |
| 211 | if !allowSourceWithBackingFile { |
| 212 | info, err := getInfo(ctx, source) |
| 213 | if err != nil { |
| 214 | return fmt.Errorf("failed to get info for source disk %#q: %w", source, err) |
| 215 | } |
| 216 | if err := rejectExternalFileReferences(info); err != nil { |
| 217 | return err |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | if err := convertToRaw(ctx, source, dest); err != nil { |
| 222 | return err |
| 223 | } |
| 224 | |
| 225 | if size != nil { |
| 226 | destInfo, err := getInfo(ctx, dest) |
| 227 | if err != nil { |
| 228 | return fmt.Errorf("failed to get info for converted disk %#q: %w", dest, err) |
| 229 | } |
| 230 | |
| 231 | if *size > destInfo.VSize { |
| 232 | return resizeDisk(ctx, dest, "raw", *size) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | return nil |
| 237 | } |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | func rejectExternalFileReferences(info *Info) error { |
| 247 | if info.BackingFilename != "" { |
| 248 | return fmt.Errorf("image (%#q) must not have a backing file (%#q)", info.Filename, info.BackingFilename) |
| 249 | } |
| 250 | if info.FullBackingFilename != "" { |
| 251 | return fmt.Errorf("image (%#q) must not have a backing file (%#q)", info.Filename, info.FullBackingFilename) |
| 252 | } |
| 253 | if info.FormatSpecific != nil { |
| 254 | if qcow2 := info.FormatSpecific.Qcow2(); qcow2 != nil && qcow2.DataFile != "" { |
| 255 | return fmt.Errorf("image (%#q) must not have an external data file (%#q)", info.Filename, qcow2.DataFile) |
| 256 | } |
| 257 | if vmdk := info.FormatSpecific.Vmdk(); vmdk != nil { |
| 258 | for _, e := range vmdk.Extents { |
| 259 | if e.Filename != info.Filename { |
| 260 | return fmt.Errorf("image (%#q) must not have an extent file (%#q)", info.Filename, e.Filename) |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | return nil |
| 266 | } |
| 267 | |
| 268 | |
| 269 | func AcceptableAsBaseDisk(info *Info) error { |
| 270 | switch info.Format { |
| 271 | case "qcow2", "raw": |
| 272 | |
| 273 | default: |
| 274 | logrus.WithField("filename", info.Filename). |
| 275 | Warnf("Unsupported image format %#q. The image may not boot, or may have an extra privilege to access the host filesystem. Use with caution.", info.Format) |
| 276 | } |
| 277 | if err := rejectExternalFileReferences(info); err != nil { |
| 278 | return err |
| 279 | } |
| 280 | |
| 281 | switch len(info.Children) { |
| 282 | case 0: |
| 283 | |
| 284 | case 1: |
| 285 | if info.Filename != info.Children[0].Info.Filename { |
| 286 | return fmt.Errorf("base disk (%#q) child must not have a different filename (%#q)", info.Filename, info.Children[0].Info.Filename) |
| 287 | } |
| 288 | if len(info.Children[0].Info.Children) > 0 { |
| 289 | return fmt.Errorf("base disk (%#q) child must not have children of its own", info.Filename) |
| 290 | } |
| 291 | default: |
| 292 | return fmt.Errorf("base disk (%#q) must not have multiple children: %+v", info.Filename, info.Children) |
| 293 | } |
| 294 | return nil |
| 295 | } |