diff --git a/api/agent.yaml b/api/agent.yaml index 04502fd..26b223e 100644 --- a/api/agent.yaml +++ b/api/agent.yaml @@ -566,7 +566,12 @@ components: example: /var/lib/two/volumes/abc.qcow2 dev: type: string - description: Device name inside the VM + description: >- + Disk slot: vda is the virtio-blk system disk (one at most), sdX + is SCSI target X (a → 0). Not a guaranteed name inside the VM: + the guest kernel names SCSI disks in detection order. The disk + serial is set to dev, so the guest finds it under + /dev/disk/by-id/ (virtio-, scsi-0QEMU_QEMU_HARDDISK_). pattern: '^[sv]d[a-z]$' example: vda diff --git a/docs/concepts/vpc-subnet-vm.rst b/docs/concepts/vpc-subnet-vm.rst index 8dcf2b7..212225e 100644 --- a/docs/concepts/vpc-subnet-vm.rst +++ b/docs/concepts/vpc-subnet-vm.rst @@ -96,7 +96,9 @@ subnet — l'ordre qui évite le trou noir de `#41 ``. Ce qui est stocké, et où ------------------------ diff --git a/docs/demarrage/premier-vpc.rst b/docs/demarrage/premier-vpc.rst index 562978f..3d3b2de 100644 --- a/docs/demarrage/premier-vpc.rst +++ b/docs/demarrage/premier-vpc.rst @@ -96,7 +96,7 @@ Là encore, attendez ``running`` : "interfaces": [{"subnet": "sn-000001", "ip": "10.1.1.2", "mac": "52:54:00:01:01:02", "primary": true}], "storage": [{"path": "/var/lib/two/volumes/i-web.qcow2", "dev": "vda"}]}' -Quatre points qui coûtent du temps quand on les découvre en production : +Six points qui coûtent du temps quand on les découvre en production : ``user_data`` est **encodé en base64** Un base64 invalide est rejeté en 400 plutôt que servi vide. L'agent n'interprète jamais ce @@ -119,6 +119,12 @@ Un seul disque ``vdX`` Les disques supplémentaires passent par ``sdX``. La carte PCI en dépend — voir :doc:`/architecture/contraintes`. +``dev`` désigne un emplacement, pas un nom dans le guest + ``sdb`` est la cible SCSI 1, mais le noyau du guest nomme les disques SCSI dans l'ordre de + détection : ``/dev/sdb`` peut être un autre disque. L'agent donne à chaque disque le numéro + de série ```` ; le nom stable est sous ``/dev/disk/by-id/`` : + ``scsi-0QEMU_QEMU_HARDDISK_sdb``, ``virtio-vda``. + 4. Vérifier ----------- diff --git a/docs/developpement/lab.rst b/docs/developpement/lab.rst index a0ffd74..22288c1 100644 --- a/docs/developpement/lab.rst +++ b/docs/developpement/lab.rst @@ -320,9 +320,9 @@ Générée par ``test/e2e/run.sh --matrice`` à partir des en-têtes ; à régé - hv1 - #33, #62 * - ``26-multi-disque`` - - VM à plusieurs disques — virtio (vdX) et SCSI (sdX), tailles et bus vus par la VM, démarrage sur vda + - VM à plusieurs disques — virtio (vdX) et SCSI (sdX), tailles et bus vus par la VM, liens ``by-id`` par numéro de série, démarrage sur vda - hv1 - - #32 + - #32, #74 * - ``27-reboot`` - redémarrage d'une VM depuis l'invité — même processus QEMU, même adresse, nouveau bail, user_data non rejoué - hv1 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), diff --git a/test/e2e/suite/26-multi-disque.sh b/test/e2e/suite/26-multi-disque.sh index 4e563f7..c756764 100644 --- a/test/e2e/suite/26-multi-disque.sh +++ b/test/e2e/suite/26-multi-disque.sh @@ -1,6 +1,6 @@ -# fonctionnalité: VM à plusieurs disques — virtio (vdX) et SCSI (sdX), tailles et bus vus par la VM, démarrage sur vda +# fonctionnalité: VM à plusieurs disques — virtio (vdX) et SCSI (sdX), tailles et bus vus par la VM, liens by-id par numéro de série, démarrage sur vda # hôtes: hv1 -# tickets: #32 +# tickets: #32, #74 on hv1 <<'NODE' KEY=$(vm_key) @@ -14,12 +14,14 @@ check "VM t26-d : vda (système), sdb, sda" vm_launch t26-d --nic sn-t26=10.26.1 check "API : trois disques" test "$(curl -fsS "${API}/vms/t26-d" | jq -r '[.storage[].dev] | sort | join(" ")')" = "sda sdb vda" check "t26-d joignable (démarrée sur vda)" vm_wait vp-t26 10.26.1.10 check "t26-d : racine sur vda" vm_grep vp-t26 10.26.1.10 'findmnt -n -o SOURCE /' '^/dev/vda' -size_is () { local v; v=$(vm_ssh vp-t26 10.26.1.10 "lsblk -b -dn -o SIZE /dev/${1}" 2>&1 | tr -d ' '); [ "${v}" = "${2}" ] || { echo "lu : ${v}"; return 1; }; } target_size () { local v; v=$(vm_ssh vp-t26 10.26.1.10 "lsblk -b -dn -o HCTL,SIZE" 2>&1 | awk -v t="${1}" '{split($1, h, ":")} h[3] == t {print $2}'); [ "${v}" = "${2}" ] || { echo "lu : ${v:-aucun disque sur la cible ${1}}"; return 1; }; } check "t26-d : sda déclaré → cible SCSI 0, 2 Gio" target_size 0 2147483648 check "t26-d : sdb déclaré → cible SCSI 1, 1 Gio" target_size 1 1073741824 -known_flaky "#74" "t26-d : nom dans l'invité = dev déclaré, sdb de 1 Gio" size_is sdb 1073741824 -known_flaky "#74" "t26-d : nom dans l'invité = dev déclaré, sda de 2 Gio" size_is sda 2147483648 +info "t26-d : /dev/disk/by-id : $(vm_ssh vp-t26 10.26.1.10 'ls /dev/disk/by-id' 2>&1 | tr '\n' ' ')" +by_id_size () { local v; v=$(vm_ssh vp-t26 10.26.1.10 "lsblk -b -dn -o SIZE \$(readlink -e /dev/disk/by-id/${1})" 2>&1 | tr -d ' '); [ "${v}" = "${2}" ] || { echo "lu : ${v}"; return 1; }; } +check "t26-d : sdb déclaré → by-id scsi-0QEMU_QEMU_HARDDISK_sdb, 1 Gio" by_id_size scsi-0QEMU_QEMU_HARDDISK_sdb 1073741824 +check "t26-d : sda déclaré → by-id scsi-0QEMU_QEMU_HARDDISK_sda, 2 Gio" by_id_size scsi-0QEMU_QEMU_HARDDISK_sda 2147483648 +check "t26-d : vda déclaré → by-id virtio-vda, disque système" test "$(vm_ssh vp-t26 10.26.1.10 'readlink -e /dev/disk/by-id/virtio-vda')" = /dev/vda check "t26-d : sdb en SCSI" vm_grep vp-t26 10.26.1.10 'readlink -f /sys/block/sdb/device/driver' 'sd$' check "t26-d : sda en SCSI (virtio-scsi)" vm_ssh vp-t26 10.26.1.10 'test -d /sys/block/sda/device/scsi_device && readlink -f /sys/block/sda | grep -q virtio' check "t26-d : vda n'est pas en SCSI (témoin)" vm_fails vp-t26 10.26.1.10 'test -d /sys/block/vda/device/scsi_device'