diff --git a/internal/qemu/args.go b/internal/qemu/args.go new file mode 100644 index 0000000..3e12f7a --- /dev/null +++ b/internal/qemu/args.go @@ -0,0 +1,112 @@ +package qemu + +import ( + "fmt" + "path/filepath" + "sort" + "strings" +) + +const ( + firstNICSlot = 0x03 + lastNICSlot = 0x1d + maxNICs = lastNICSlot - firstNICSlot + 1 +) + +func buildArgs(cfg Config) ([]string, error) { + memory := cfg.Memory + if memory == 0 { + memory = 512 + } + + cpus := cfg.CPUs + if cpus == 0 { + cpus = 1 + } + + serialSock := filepath.Join(cfg.SerialDir, cfg.Name+".sock") + monitorSock := filepath.Join(cfg.MonitorDir, cfg.Name+".sock") + qmpSock := filepath.Join(cfg.QMPDir, cfg.Name+".sock") + + args := []string{ + "-enable-kvm", + "-cpu", "host", + "-m", fmt.Sprintf("%d", memory), + "-smp", fmt.Sprintf("%d", cpus), + "-serial", fmt.Sprintf("unix:%s,server,nowait", serialSock), + "-monitor", fmt.Sprintf("unix:%s,server,nowait", monitorSock), + "-qmp", fmt.Sprintf("unix:%s,server,nowait", qmpSock), + "-display", "none", + } + + if cfg.UEFICodePath != "" && cfg.UEFIVarsPath != "" { + args = append(args, + "-drive", fmt.Sprintf("if=pflash,format=raw,readonly=on,file=%s", cfg.UEFICodePath), + "-drive", fmt.Sprintf("if=pflash,format=raw,file=%s", cfg.UEFIVarsPath), + ) + } + + hasScsi := false + virtioBlk := 0 + for _, d := range cfg.Disks { + if strings.HasPrefix(d.Dev, "sd") { + hasScsi = true + } else { + virtioBlk++ + } + } + if virtioBlk > 1 { + return nil, fmt.Errorf("qemu: %d disques virtio-blk (vd*) déclarés, un seul est supporté — utiliser des disques sd* pour les disques additionnels", virtioBlk) + } + if hasScsi { + args = append(args, "-device", "virtio-scsi-pci,id=scsi0,bus=pci.0,addr=0x1e") + } + + sorted := make([]DiskConfig, len(cfg.Disks)) + copy(sorted, cfg.Disks) + // vd* avant sd* : les disques virtio-blk bootent en premier. + // À lettre égale de type, ordre alphabétique. + sort.Slice(sorted, func(i, j int) bool { + iVirtio := strings.HasPrefix(sorted[i].Dev, "vd") + jVirtio := strings.HasPrefix(sorted[j].Dev, "vd") + if iVirtio != jVirtio { + return iVirtio + } + return sorted[i].Dev < sorted[j].Dev + }) + + for idx, d := range sorted { + bootindex := idx + 1 + if strings.HasPrefix(d.Dev, "sd") { + scsiID := int(d.Dev[2] - 'a') + args = append(args, + "-drive", fmt.Sprintf("file=%s,if=none,id=%s", d.Path, d.Dev), + "-device", fmt.Sprintf("scsi-hd,drive=%s,bus=scsi0.0,scsi-id=%d,bootindex=%d,serial=%s", d.Dev, scsiID, bootindex, d.Dev), + ) + } else { + args = append(args, + "-drive", fmt.Sprintf("file=%s,if=none,id=%s", d.Path, d.Dev), + "-device", fmt.Sprintf("virtio-blk-pci,drive=%s,bus=pci.0,addr=0x1f,bootindex=%d,serial=%s", d.Dev, bootindex, d.Dev), + ) + } + } + + // Slots 0x03 à 0x1d réservés au réseau par la carte PCI (#36). Le slot est + // dérivé de l'index et non laissé à QEMU : c'est lui qui fixe le nom de + // l'interface dans le guest, et un slot flottant la renomme d'un démarrage + // à l'autre. + if len(cfg.NICs) == 0 { + return nil, fmt.Errorf("vm %s has no network interface", cfg.Name) + } + if len(cfg.NICs) > maxNICs { + return nil, fmt.Errorf("vm %s has %d interfaces, the pci map holds %d", cfg.Name, len(cfg.NICs), maxNICs) + } + for i, n := range cfg.NICs { + args = append(args, + "-netdev", fmt.Sprintf("tap,id=net%d,ifname=tap%d,script=no,downscript=no", i, n.TapID), + "-device", fmt.Sprintf("virtio-net-pci,netdev=net%d,mac=%s,bus=pci.0,addr=0x%02x", i, n.Mac, firstNICSlot+i), + ) + } + + return append(args, "-daemonize"), nil +} diff --git a/internal/qemu/args_test.go b/internal/qemu/args_test.go new file mode 100644 index 0000000..fe3b072 --- /dev/null +++ b/internal/qemu/args_test.go @@ -0,0 +1,75 @@ +package qemu + +import ( + "testing" +) + +func devicesOf(args []string) []string { + var devices []string + for i := 0; i+1 < len(args); i++ { + if args[i] == "-device" { + devices = append(devices, args[i+1]) + } + } + return devices +} + +func TestBuildArgs_DiskSerialIsDeclaredDev(t *testing.T) { + args, err := buildArgs(Config{ + Name: "vm1", + NICs: []NICConfig{{TapID: 1, Mac: "52:54:00:00:00:01"}}, + Disks: []DiskConfig{ + {Path: "/v/b.qcow2", Dev: "sdb"}, + {Path: "/v/root.qcow2", Dev: "vda"}, + {Path: "/v/a.qcow2", Dev: "sda"}, + }, + }) + if err != nil { + t.Fatalf("buildArgs a échoué : %v", err) + } + + want := []string{ + "virtio-scsi-pci,id=scsi0,bus=pci.0,addr=0x1e", + "virtio-blk-pci,drive=vda,bus=pci.0,addr=0x1f,bootindex=1,serial=vda", + "scsi-hd,drive=sda,bus=scsi0.0,scsi-id=0,bootindex=2,serial=sda", + "scsi-hd,drive=sdb,bus=scsi0.0,scsi-id=1,bootindex=3,serial=sdb", + "virtio-net-pci,netdev=net0,mac=52:54:00:00:00:01,bus=pci.0,addr=0x03", + } + got := devicesOf(args) + if len(got) != len(want) { + t.Fatalf("devices = %q, attendu %q", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("device %d = %q, attendu %q", i, got[i], want[i]) + } + } +} + +func TestBuildArgs_EndsWithDaemonize(t *testing.T) { + args, err := buildArgs(Config{Name: "vm1", NICs: []NICConfig{{TapID: 1, Mac: "52:54:00:00:00:01"}}}) + if err != nil { + t.Fatalf("buildArgs a échoué : %v", err) + } + if args[len(args)-1] != "-daemonize" { + t.Errorf("dernier argument = %q, attendu -daemonize", args[len(args)-1]) + } +} + +func TestBuildArgs_RejectsSecondVirtioDisk(t *testing.T) { + _, err := buildArgs(Config{ + Name: "vm1", + NICs: []NICConfig{{TapID: 1, Mac: "52:54:00:00:00:01"}}, + Disks: []DiskConfig{{Path: "/v/a", Dev: "vda"}, {Path: "/v/b", Dev: "vdb"}}, + }) + if err == nil { + t.Fatal("buildArgs a accepté deux disques virtio") + } +} + +func TestBuildArgs_RejectsNoNIC(t *testing.T) { + _, err := buildArgs(Config{Name: "vm1"}) + if err == nil { + t.Fatal("buildArgs a accepté une VM sans interface") + } +} diff --git a/internal/qemu/start_linux.go b/internal/qemu/start_linux.go index 1a8f918..4316180 100644 --- a/internal/qemu/start_linux.go +++ b/internal/qemu/start_linux.go @@ -6,28 +6,10 @@ import ( "fmt" "os" "os/exec" - "path/filepath" - "sort" "strings" ) -const ( - firstNICSlot = 0x03 - lastNICSlot = 0x1d - maxNICs = lastNICSlot - firstNICSlot + 1 -) - func Start(cfg Config) error { - memory := cfg.Memory - if memory == 0 { - memory = 512 - } - - cpus := cfg.CPUs - if cpus == 0 { - cpus = 1 - } - for _, dir := range []string{cfg.SerialDir, cfg.MonitorDir, cfg.QMPDir} { if dir != "" { if err := os.MkdirAll(dir, 0755); err != nil { @@ -36,92 +18,11 @@ func Start(cfg Config) error { } } - serialSock := filepath.Join(cfg.SerialDir, cfg.Name+".sock") - monitorSock := filepath.Join(cfg.MonitorDir, cfg.Name+".sock") - qmpSock := filepath.Join(cfg.QMPDir, cfg.Name+".sock") - - args := []string{ - "-enable-kvm", - "-cpu", "host", - "-m", fmt.Sprintf("%d", memory), - "-smp", fmt.Sprintf("%d", cpus), - "-serial", fmt.Sprintf("unix:%s,server,nowait", serialSock), - "-monitor", fmt.Sprintf("unix:%s,server,nowait", monitorSock), - "-qmp", fmt.Sprintf("unix:%s,server,nowait", qmpSock), - "-display", "none", + args, err := buildArgs(cfg) + if err != nil { + return err } - if cfg.UEFICodePath != "" && cfg.UEFIVarsPath != "" { - args = append(args, - "-drive", fmt.Sprintf("if=pflash,format=raw,readonly=on,file=%s", cfg.UEFICodePath), - "-drive", fmt.Sprintf("if=pflash,format=raw,file=%s", cfg.UEFIVarsPath), - ) - } - - hasScsi := false - virtioBlk := 0 - for _, d := range cfg.Disks { - if strings.HasPrefix(d.Dev, "sd") { - hasScsi = true - } else { - virtioBlk++ - } - } - if virtioBlk > 1 { - return fmt.Errorf("qemu: %d disques virtio-blk (vd*) déclarés, un seul est supporté — utiliser des disques sd* pour les disques additionnels", virtioBlk) - } - if hasScsi { - args = append(args, "-device", "virtio-scsi-pci,id=scsi0,bus=pci.0,addr=0x1e") - } - - sorted := make([]DiskConfig, len(cfg.Disks)) - copy(sorted, cfg.Disks) - // vd* avant sd* : les disques virtio-blk bootent en premier. - // À lettre égale de type, ordre alphabétique. - sort.Slice(sorted, func(i, j int) bool { - iVirtio := strings.HasPrefix(sorted[i].Dev, "vd") - jVirtio := strings.HasPrefix(sorted[j].Dev, "vd") - if iVirtio != jVirtio { - return iVirtio - } - return sorted[i].Dev < sorted[j].Dev - }) - - for idx, d := range sorted { - bootindex := idx + 1 - if strings.HasPrefix(d.Dev, "sd") { - scsiID := int(d.Dev[2] - 'a') - args = append(args, - "-drive", fmt.Sprintf("file=%s,if=none,id=%s", d.Path, d.Dev), - "-device", fmt.Sprintf("scsi-hd,drive=%s,bus=scsi0.0,scsi-id=%d,bootindex=%d", d.Dev, scsiID, bootindex), - ) - } else { - args = append(args, - "-drive", fmt.Sprintf("file=%s,if=none,id=%s", d.Path, d.Dev), - "-device", fmt.Sprintf("virtio-blk-pci,drive=%s,bus=pci.0,addr=0x1f,bootindex=%d", d.Dev, bootindex), - ) - } - } - - // Slots 0x03 à 0x1d réservés au réseau par la carte PCI (#36). Le slot est - // dérivé de l'index et non laissé à QEMU : c'est lui qui fixe le nom de - // l'interface dans le guest, et un slot flottant la renomme d'un démarrage - // à l'autre. - if len(cfg.NICs) == 0 { - return fmt.Errorf("vm %s has no network interface", cfg.Name) - } - if len(cfg.NICs) > maxNICs { - return fmt.Errorf("vm %s has %d interfaces, the pci map holds %d", cfg.Name, len(cfg.NICs), maxNICs) - } - for i, n := range cfg.NICs { - args = append(args, - "-netdev", fmt.Sprintf("tap,id=net%d,ifname=tap%d,script=no,downscript=no", i, n.TapID), - "-device", fmt.Sprintf("virtio-net-pci,netdev=net%d,mac=%s,bus=pci.0,addr=0x%02x", i, n.Mac, firstNICSlot+i), - ) - } - - args = append(args, "-daemonize") - scopeArgs := append([]string{ "--scope", "--unit=" + ScopeName(cfg.Name),