60 lines
1.6 KiB
Go
60 lines
1.6 KiB
Go
package qmp
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
// AttachedFiles lists the inserted image and backing files for each block
|
|
// device. QEMU's resolved image names include the real pflash and CD drives.
|
|
func (c *Conn) AttachedFiles(vmDir string) ([]string, error) {
|
|
raw, err := c.Query("query-block", nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
type image struct {
|
|
Filename string `json:"filename"`
|
|
Backing *image `json:"backing-image"`
|
|
}
|
|
var devices []struct {
|
|
Device string `json:"device"`
|
|
Inserted *struct {
|
|
Image *image `json:"image"`
|
|
Backing string `json:"backing_file"`
|
|
} `json:"inserted"`
|
|
}
|
|
if err := json.Unmarshal(raw, &devices); err != nil {
|
|
return nil, fmt.Errorf("decode query-block: %w", err)
|
|
}
|
|
var paths []string
|
|
for _, d := range devices {
|
|
if d.Inserted == nil {
|
|
continue
|
|
}
|
|
if d.Inserted.Image == nil || (d.Inserted.Backing != "" && d.Inserted.Image.Backing == nil) {
|
|
return nil, fmt.Errorf("cannot identify the complete attached disk or backing chain")
|
|
}
|
|
for img := d.Inserted.Image; img != nil; img = img.Backing {
|
|
if img.Filename == "" {
|
|
return nil, fmt.Errorf("block device has no filename")
|
|
}
|
|
name := img.Filename
|
|
if strings.HasPrefix(name, "json:") {
|
|
return nil, fmt.Errorf("block device %s uses a non-persistent or unresolvable image; eject it before suspending", d.Device)
|
|
}
|
|
if !filepath.IsAbs(name) {
|
|
name = filepath.Join(vmDir, name)
|
|
}
|
|
paths = append(paths, filepath.Clean(name))
|
|
}
|
|
}
|
|
if len(paths) == 0 {
|
|
return nil, fmt.Errorf("no attached media reported by QEMU")
|
|
}
|
|
slices.Sort(paths)
|
|
return slices.Compact(paths), nil
|
|
}
|