From d49648604b29e33804aae5c0e78f7f63eab2e0d9 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Thu, 22 Oct 2026 22:51:58 +0200 Subject: [PATCH 1/9] =?UTF-8?q?f-74:=20qemu:=20num=C3=A9ro=20de=20s=C3=A9r?= =?UTF-8?q?ie=20=20sur=20chaque=20disque,=20ligne=20de=20commande=20c?= =?UTF-8?q?onstruite=20hors=20de=20Start=20#74?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- internal/qemu/args.go | 112 +++++++++++++++++++++++++++++++++++ internal/qemu/args_test.go | 75 +++++++++++++++++++++++ internal/qemu/start_linux.go | 105 +------------------------------- 3 files changed, 190 insertions(+), 102 deletions(-) create mode 100644 internal/qemu/args.go create mode 100644 internal/qemu/args_test.go 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), From 096ee1dc0ed716e85ed4dfa23a2a1b488648f46e Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Thu, 22 Oct 2026 22:52:05 +0200 Subject: [PATCH 2/9] =?UTF-8?q?f-74:=20e2e:=2026-multi-disque=20v=C3=A9rif?= =?UTF-8?q?ie=20les=20liens=20by-id=20au=20lieu=20du=20nom=20dans=20l'invi?= =?UTF-8?q?t=C3=A9=20#74?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- test/e2e/suite/26-multi-disque.sh | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) 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' From 9b5b4a6e62e863dc14146339239c36ced68a0443 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Thu, 22 Oct 2026 22:52:12 +0200 Subject: [PATCH 3/9] =?UTF-8?q?f-74:=20doc:=20dev=20d=C3=A9signe=20l'empla?= =?UTF-8?q?cement=20du=20disque,=20nom=20stable=20sous=20/dev/disk/by-id?= =?UTF-8?q?=20#74?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- api/agent.yaml | 7 ++++++- docs/concepts/vpc-subnet-vm.rst | 4 +++- docs/demarrage/premier-vpc.rst | 8 +++++++- docs/developpement/lab.rst | 4 ++-- 4 files changed, 18 insertions(+), 5 deletions(-) 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 3a7b599..a3972bb 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, #73 * - ``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 From 1e9f436648f4f128b7c02c1b0ea498e9dbc30be0 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 23 Oct 2026 00:26:33 +0200 Subject: [PATCH 4/9] =?UTF-8?q?f-74:=20api:=20disques=20additionnels=20xvd?= =?UTF-8?q?X=20sur=20la=20cible=20SCSI=20de=20m=C3=AAme=20rang,=20sdX=20re?= =?UTF-8?q?fus=C3=A9,=20migration=20des=20cl=C3=A9s=20disk/sdX=20#74?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- cmd/agent/main.go | 5 +++ internal/api/agent/vm_test.go | 63 ++++++++++++++++++-------- internal/api/agent/vms.go | 8 ++++ internal/migration/disk.go | 40 +++++++++++++++++ internal/migration/disk_test.go | 80 +++++++++++++++++++++++++++++++++ internal/qemu/args.go | 10 ++--- internal/qemu/args_test.go | 8 ++-- 7 files changed, 187 insertions(+), 27 deletions(-) create mode 100644 internal/migration/disk.go create mode 100644 internal/migration/disk_test.go diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 98b8e3d..548316e 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -68,6 +68,11 @@ func run(confFile string) int { return 1 } + if err := migration.MigrateVMDisks(db, log.With(slog.String("component", "migration"))); err != nil { + log.Error("vm disk migration failed", "error", err) + return 1 + } + if cfg.BGP.Enabled() { if err := applyBGPBase(cfg, frr.NewClient()); err != nil { log.Error("failed to apply the bgp base configuration", "error", err) diff --git a/internal/api/agent/vm_test.go b/internal/api/agent/vm_test.go index 7412d38..e2ff820 100644 --- a/internal/api/agent/vm_test.go +++ b/internal/api/agent/vm_test.go @@ -24,7 +24,7 @@ func TestVmFromDB_SingleDisk(t *testing.T) { "vm/vm-1/metadata_port": "1234", "vm/vm-1/memory": "512", "vm/vm-1/cpus": "1", - "vm/vm-1/disk/sda": "/data/root.qcow2", + "vm/vm-1/disk/xvda": "/data/root.qcow2", } vm, err := vmFromDB("vm-1", entries) if err != nil { @@ -33,7 +33,7 @@ func TestVmFromDB_SingleDisk(t *testing.T) { if len(vm.Storage) != 1 { t.Fatalf("attendu 1 disque, obtenu %d", len(vm.Storage)) } - if vm.Storage[0].Dev != "sda" || vm.Storage[0].Path != "/data/root.qcow2" { + if vm.Storage[0].Dev != "xvda" || vm.Storage[0].Path != "/data/root.qcow2" { t.Errorf("disque inattendu : %+v", vm.Storage[0]) } } @@ -46,8 +46,8 @@ func TestVmFromDB_MultiDisk(t *testing.T) { "vm/vm-2/metadata_port": "1235", "vm/vm-2/memory": "1024", "vm/vm-2/cpus": "2", - "vm/vm-2/disk/sda": "/data/root.qcow2", - "vm/vm-2/disk/sdb": "/data/data.qcow2", + "vm/vm-2/disk/xvda": "/data/root.qcow2", + "vm/vm-2/disk/xvdb": "/data/data.qcow2", } vm, err := vmFromDB("vm-2", entries) if err != nil { @@ -57,13 +57,13 @@ func TestVmFromDB_MultiDisk(t *testing.T) { t.Fatalf("attendu 2 disques, obtenu %d", len(vm.Storage)) } sort.Slice(vm.Storage, func(i, j int) bool { return vm.Storage[i].Dev < vm.Storage[j].Dev }) - if vm.Storage[0].Dev != "sda" || vm.Storage[1].Dev != "sdb" { - t.Errorf("devs attendus [sda sdb], obtenus [%s %s]", vm.Storage[0].Dev, vm.Storage[1].Dev) + if vm.Storage[0].Dev != "xvda" || vm.Storage[1].Dev != "xvdb" { + t.Errorf("devs attendus [xvda xvdb], obtenus [%s %s]", vm.Storage[0].Dev, vm.Storage[1].Dev) } } func TestVmFromDB_SlotGap(t *testing.T) { - // sdb absent — sda et sdc seulement + // xvdb absent — xvda et xvdc seulement entries := map[string]string{ "vm/vm-3/state": "running", "vm/vm-3/subnet": "sn-1", @@ -71,8 +71,8 @@ func TestVmFromDB_SlotGap(t *testing.T) { "vm/vm-3/metadata_port": "1236", "vm/vm-3/memory": "512", "vm/vm-3/cpus": "1", - "vm/vm-3/disk/sda": "/data/root.qcow2", - "vm/vm-3/disk/sdc": "/data/extra.qcow2", + "vm/vm-3/disk/xvda": "/data/root.qcow2", + "vm/vm-3/disk/xvdc": "/data/extra.qcow2", } vm, err := vmFromDB("vm-3", entries) if err != nil { @@ -85,11 +85,11 @@ func TestVmFromDB_SlotGap(t *testing.T) { for _, s := range vm.Storage { devs[s.Dev] = true } - if !devs["sda"] || !devs["sdc"] { - t.Errorf("attendu sda et sdc, obtenus %v", devs) + if !devs["xvda"] || !devs["xvdc"] { + t.Errorf("attendu xvda et xvdc, obtenus %v", devs) } - if devs["sdb"] { - t.Error("sdb ne devrait pas apparaître") + if devs["xvdb"] { + t.Error("xvdb ne devrait pas apparaître") } } @@ -107,8 +107,8 @@ func TestStartVM_MultiDisk(t *testing.T) { {Subnet: "sn-1", IP: "10.0.0.10", MAC: "52:54:00:00:00:05", Primary: true}, }, Storage: []VMStorage{ - {Path: "/data/root.qcow2", Dev: "sda"}, - {Path: "/data/data.qcow2", Dev: "sdb"}, + {Path: "/data/root.qcow2", Dev: "vda"}, + {Path: "/data/data.qcow2", Dev: "xvda"}, }, Memory: 1024, CPUs: 2, @@ -120,7 +120,7 @@ func TestStartVM_MultiDisk(t *testing.T) { t.Fatalf("attendu 202, obtenu %d : %s", w.Code, w.Body.String()) } - for _, dev := range []string{"sda", "sdb"} { + for _, dev := range []string{"vda", "xvda"} { if _, err := kv.GetFromDB(db, "vm/vm-10/disk/"+dev); err != nil { t.Errorf("disk/%s absent en DB après création", dev) } @@ -142,7 +142,7 @@ func TestStartVM_StorageReturnedInResponse(t *testing.T) { {Subnet: "sn-1", IP: "10.0.0.11", MAC: "52:54:00:00:00:05", Primary: true}, }, Storage: []VMStorage{ - {Path: "/data/root.qcow2", Dev: "sda"}, + {Path: "/data/root.qcow2", Dev: "xvda"}, }, }) @@ -157,11 +157,38 @@ func TestStartVM_StorageReturnedInResponse(t *testing.T) { if len(vm.Storage) != 1 { t.Fatalf("attendu 1 disque dans la réponse, obtenu %d", len(vm.Storage)) } - if vm.Storage[0].Dev != "sda" || vm.Storage[0].Path != "/data/root.qcow2" { + if vm.Storage[0].Dev != "xvda" || vm.Storage[0].Path != "/data/root.qcow2" { t.Errorf("disque inattendu dans la réponse : %+v", vm.Storage[0]) } } +func TestStartVM_RejectsInvalidDiskDev(t *testing.T) { + for _, dev := range []string{"sda", "sdb", "vdb", "xvd", "xvdA", "xvdaa", ""} { + s, db := newTestServer(t) + kv.AddInDB(db, "subnet/sn-1/state", "running") + kv.AddInDB(db, "subnet/sn-1/vpc", "vpc-1") + kv.AddInDB(db, "subnet/sn-1/cidr", "10.0.0.0/24") + + body, _ := json.Marshal(VMCreateRequest{ + Name: "vm-12", + Interfaces: []VMInterface{{Subnet: "sn-1", IP: "10.0.0.12", MAC: "52:54:00:00:00:05", Primary: true}}, + Storage: []VMStorage{{Path: "/data/root.qcow2", Dev: "vda"}, {Path: "/data/data.qcow2", Dev: dev}}, + }) + + w := httptest.NewRecorder() + s.VmsHandler(w, httptest.NewRequest(http.MethodPost, "/vms", bytes.NewReader(body))) + if w.Code != http.StatusBadRequest { + t.Errorf("dev %q : attendu 400, obtenu %d", dev, w.Code) + } + if !strings.Contains(w.Body.String(), "storage 1: dev") { + t.Errorf("dev %q : message inattendu %s", dev, w.Body.String()) + } + if _, err := kv.GetFromDB(db, "vm/vm-12/state"); err == nil { + t.Errorf("dev %q : la VM ne doit pas être enregistrée", dev) + } + } +} + // --- POST /vms : objet metadata --- func postVM(t *testing.T, name string, meta VMMetadata) (*httptest.ResponseRecorder, *badger.DB) { diff --git a/internal/api/agent/vms.go b/internal/api/agent/vms.go index d5ca436..03b617f 100644 --- a/internal/api/agent/vms.go +++ b/internal/api/agent/vms.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "net/http" + "regexp" "strings" dispatcher "git.g3e.fr/syonad/two/internal/dispatcher/agent" @@ -12,6 +13,8 @@ import ( "git.g3e.fr/syonad/two/pkg/db/kv" ) +var diskDev = regexp.MustCompile(`^(vda|xvd[a-z])$`) + func (s *Server) VmsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.Method { @@ -88,6 +91,11 @@ func (s *Server) startVM(w http.ResponseWriter, r *http.Request) { disks := make([]dispatcher.VMDisk, len(req.Storage)) for i, s := range req.Storage { + if !diskDev.MatchString(s.Dev) { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{Error: fmt.Sprintf("storage %d: dev %q must be vda (root disk) or xvd[a-z]", i, s.Dev)}) + return + } disks[i] = dispatcher.VMDisk{Path: s.Path, Dev: s.Dev} } diff --git a/internal/migration/disk.go b/internal/migration/disk.go new file mode 100644 index 0000000..a1eb722 --- /dev/null +++ b/internal/migration/disk.go @@ -0,0 +1,40 @@ +package migration + +import ( + "fmt" + "log/slog" + "regexp" + "strings" + + "git.g3e.fr/syonad/two/pkg/db/kv" + + "github.com/dgraph-io/badger/v4" +) + +var legacyDiskKey = regexp.MustCompile(`^vm/([^/]+)/disk/sd([a-z])$`) + +func MigrateVMDisks(db *badger.DB, log *slog.Logger) error { + entries, err := kv.ListByPrefix(db, "vm/") + if err != nil { + return fmt.Errorf("list vm/: %w", err) + } + + for key, path := range entries { + m := legacyDiskKey.FindStringSubmatch(key) + if m == nil { + continue + } + target := strings.TrimSuffix(key, "sd"+m[2]) + "xvd" + m[2] + if existing, ok := entries[target]; ok && existing != path { + return fmt.Errorf("migrate %s: %s already holds %q", key, target, existing) + } + if err := kv.AddInDB(db, target, path); err != nil { + return fmt.Errorf("migrate %s: %w", key, err) + } + if err := kv.DeleteInDB(db, key); err != nil { + return fmt.Errorf("delete legacy %s: %w", key, err) + } + log.Info("vm disk migrated", "resource", "vm/"+m[1], "from", "sd"+m[2], "to", "xvd"+m[2]) + } + return nil +} diff --git a/internal/migration/disk_test.go b/internal/migration/disk_test.go new file mode 100644 index 0000000..6529964 --- /dev/null +++ b/internal/migration/disk_test.go @@ -0,0 +1,80 @@ +package migration + +import ( + "testing" + + "git.g3e.fr/syonad/two/pkg/db/kv" +) + +func TestMigrateVMDisks_RenamesSCSIDisks(t *testing.T) { + db := newNICDB(t) + kv.AddInDB(db, "vm/i-test1/disk/vda", "/v/root.qcow2") + kv.AddInDB(db, "vm/i-test1/disk/sda", "/v/a.qcow2") + kv.AddInDB(db, "vm/i-test1/disk/sdc", "/v/c.qcow2") + kv.AddInDB(db, "vm/i-test2/disk/sdb", "/v/b.qcow2") + + if err := MigrateVMDisks(db, quietLog()); err != nil { + t.Fatalf("MigrateVMDisks : %v", err) + } + + got, err := kv.ListByPrefix(db, "vm/") + if err != nil { + t.Fatalf("ListByPrefix : %v", err) + } + want := map[string]string{ + "vm/i-test1/disk/vda": "/v/root.qcow2", + "vm/i-test1/disk/xvda": "/v/a.qcow2", + "vm/i-test1/disk/xvdc": "/v/c.qcow2", + "vm/i-test2/disk/xvdb": "/v/b.qcow2", + } + if len(got) != len(want) { + t.Errorf("clés après migration : %v, attendu %v", got, want) + } + for key, value := range want { + if got[key] != value { + t.Errorf("%s = %q, attendu %q", key, got[key], value) + } + } +} + +func TestMigrateVMDisks_Idempotent(t *testing.T) { + db := newNICDB(t) + kv.AddInDB(db, "vm/i-test1/disk/sda", "/v/a.qcow2") + + for i := 0; i < 2; i++ { + if err := MigrateVMDisks(db, quietLog()); err != nil { + t.Fatalf("passe %d : %v", i, err) + } + } + if got, _ := kv.GetFromDB(db, "vm/i-test1/disk/xvda"); got != "/v/a.qcow2" { + t.Errorf("xvda = %q après deux passes", got) + } +} + +func TestMigrateVMDisks_LeavesOtherKeys(t *testing.T) { + db := newNICDB(t) + kv.AddInDB(db, "vm/i-test1/nic/0/sda", "x") + kv.AddInDB(db, "vm/i-test1/disk/sdaa", "/v/x.qcow2") + + if err := MigrateVMDisks(db, quietLog()); err != nil { + t.Fatalf("MigrateVMDisks : %v", err) + } + for _, key := range []string{"vm/i-test1/nic/0/sda", "vm/i-test1/disk/sdaa"} { + if _, err := kv.GetFromDB(db, key); err != nil { + t.Errorf("%s ne devait pas être touchée : %v", key, err) + } + } +} + +func TestMigrateVMDisks_RefusesConflict(t *testing.T) { + db := newNICDB(t) + kv.AddInDB(db, "vm/i-test1/disk/sda", "/v/a.qcow2") + kv.AddInDB(db, "vm/i-test1/disk/xvda", "/v/other.qcow2") + + if err := MigrateVMDisks(db, quietLog()); err == nil { + t.Fatal("un conflit sda/xvda doit faire échouer la migration") + } + if got, _ := kv.GetFromDB(db, "vm/i-test1/disk/sda"); got != "/v/a.qcow2" { + t.Errorf("sda ne doit pas être supprimée en cas de conflit : %q", got) + } +} diff --git a/internal/qemu/args.go b/internal/qemu/args.go index 3e12f7a..4aa7327 100644 --- a/internal/qemu/args.go +++ b/internal/qemu/args.go @@ -49,14 +49,14 @@ func buildArgs(cfg Config) ([]string, error) { hasScsi := false virtioBlk := 0 for _, d := range cfg.Disks { - if strings.HasPrefix(d.Dev, "sd") { + if strings.HasPrefix(d.Dev, "xvd") { 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) + return nil, fmt.Errorf("qemu: %d disques virtio-blk (vd*) déclarés, un seul est supporté — utiliser des disques xvd* pour les disques additionnels", virtioBlk) } if hasScsi { args = append(args, "-device", "virtio-scsi-pci,id=scsi0,bus=pci.0,addr=0x1e") @@ -64,7 +64,7 @@ func buildArgs(cfg Config) ([]string, error) { sorted := make([]DiskConfig, len(cfg.Disks)) copy(sorted, cfg.Disks) - // vd* avant sd* : les disques virtio-blk bootent en premier. + // vd* avant xvd* : 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") @@ -77,8 +77,8 @@ func buildArgs(cfg Config) ([]string, error) { for idx, d := range sorted { bootindex := idx + 1 - if strings.HasPrefix(d.Dev, "sd") { - scsiID := int(d.Dev[2] - 'a') + if strings.HasPrefix(d.Dev, "xvd") { + scsiID := int(d.Dev[3] - '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), diff --git a/internal/qemu/args_test.go b/internal/qemu/args_test.go index fe3b072..6864994 100644 --- a/internal/qemu/args_test.go +++ b/internal/qemu/args_test.go @@ -19,9 +19,9 @@ func TestBuildArgs_DiskSerialIsDeclaredDev(t *testing.T) { Name: "vm1", NICs: []NICConfig{{TapID: 1, Mac: "52:54:00:00:00:01"}}, Disks: []DiskConfig{ - {Path: "/v/b.qcow2", Dev: "sdb"}, + {Path: "/v/b.qcow2", Dev: "xvdb"}, {Path: "/v/root.qcow2", Dev: "vda"}, - {Path: "/v/a.qcow2", Dev: "sda"}, + {Path: "/v/a.qcow2", Dev: "xvda"}, }, }) if err != nil { @@ -31,8 +31,8 @@ func TestBuildArgs_DiskSerialIsDeclaredDev(t *testing.T) { 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", + "scsi-hd,drive=xvda,bus=scsi0.0,scsi-id=0,bootindex=2,serial=xvda", + "scsi-hd,drive=xvdb,bus=scsi0.0,scsi-id=1,bootindex=3,serial=xvdb", "virtio-net-pci,netdev=net0,mac=52:54:00:00:00:01,bus=pci.0,addr=0x03", } got := devicesOf(args) From 30197299957938a9360fa86be2c4cf98ddafeb0f Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 23 Oct 2026 00:26:39 +0200 Subject: [PATCH 5/9] f-74: e2e: image du lab avec /dev/xvdX, 26 sur xvdX et ses partitions, 11 refuse sdX #74 Signed-off-by: GnomeZworc --- test/e2e/lib/vm.sh | 4 ++++ test/e2e/run_test.sh | 12 +++++------ test/e2e/suite/11-validation.sh | 5 ++++- test/e2e/suite/26-multi-disque.sh | 33 +++++++++++++++++-------------- 4 files changed, 32 insertions(+), 22 deletions(-) diff --git a/test/e2e/lib/vm.sh b/test/e2e/lib/vm.sh index b72a7e1..4c02d60 100644 --- a/test/e2e/lib/vm.sh +++ b/test/e2e/lib/vm.sh @@ -15,6 +15,10 @@ two_image () { > /mnt/two-image/etc/cloud/cloud.cfg.d/99_metadata.cfg printf '%s\n' '[Match]' 'Name=en*' '' '[Network]' 'DHCP=ipv4' \ > /mnt/two-image/etc/systemd/network/90-all-en.network + printf '%s\n' \ + 'SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", ENV{ID_SERIAL_SHORT}=="xvd[a-z]", SYMLINK+="$env{ID_SERIAL_SHORT}"' \ + 'SUBSYSTEM=="block", ENV{DEVTYPE}=="partition", ENV{ID_SERIAL_SHORT}=="xvd[a-z]", SYMLINK+="$env{ID_SERIAL_SHORT}%n"' \ + > /mnt/two-image/etc/udev/rules.d/90-two-xvd.rules umount /mnt/two-image qemu-nbd -d /dev/nbd0 >/dev/null mv "${work}/${IMAGE_FILE}" "${TWO_IMAGE}" diff --git a/test/e2e/run_test.sh b/test/e2e/run_test.sh index 186424a..9cd27a8 100755 --- a/test/e2e/run_test.sh +++ b/test/e2e/run_test.sh @@ -361,16 +361,16 @@ test_vm_body_builds_the_create_request () { setup "vm_body : requête de création, disque par défaut, métadonnées et dev" [[ $(node 'vm_body t11-a sn-t11a 10.11.1.10') == '{"name":"t11-a","memory":1024,"cpus":1,"metadata":{},"interfaces":[{"subnet":"sn-t11a","ip":"10.11.1.10","mac":"52:54:00:0b:01:0a","primary":true}],"storage":[{"path":"/var/lib/two/volumes/t11-a.qcow2","dev":"vda"}]}' ]] \ || fail "défaut : $(node 'vm_body t11-a sn-t11a 10.11.1.10')" - [[ $(node 'vm_body t11-b sn-t11a 10.11.1.11 /x.qcow2 "{\"user_data\":\"YQ==\"}" sdb | jq -c "[.metadata.user_data, .storage[0].path, .storage[0].dev]"') == '["YQ==","/x.qcow2","sdb"]' ]] \ - || fail "options : $(node 'vm_body t11-b sn-t11a 10.11.1.11 /x.qcow2 "{\"user_data\":\"YQ==\"}" sdb')" + [[ $(node 'vm_body t11-b sn-t11a 10.11.1.11 /x.qcow2 "{\"user_data\":\"YQ==\"}" xvdb | jq -c "[.metadata.user_data, .storage[0].path, .storage[0].dev]"') == '["YQ==","/x.qcow2","xvdb"]' ]] \ + || fail "options : $(node 'vm_body t11-b sn-t11a 10.11.1.11 /x.qcow2 "{\"user_data\":\"YQ==\"}" xvdb')" teardown } test_vm_json_builds_nics_disks_metadata_and_uefi () { setup "vm_json : NIC (la première primaire), disques, métadonnées, uefi" local out - out=$(node 'vm_json t25-m --disk vda=/v/a.qcow2 --nic sn-a=10.0.1.10 --nic sn-b=10.0.2.10 --disk sda=/v/b.qcow2 --sshkey "ssh-ed25519 AAAA x" --password "\$6\$s\$h" --user-data "I2Nsb3Vk" --uefi') - [[ "${out}" == '{"name":"t25-m","memory":1024,"cpus":1,"metadata":{"sshkey":"ssh-ed25519 AAAA x","password":"$6$s$h","user_data":"I2Nsb3Vk"},"interfaces":[{"subnet":"sn-a","ip":"10.0.1.10","mac":"52:54:00:00:01:0a","primary":true},{"subnet":"sn-b","ip":"10.0.2.10","mac":"52:54:00:00:02:0a","primary":false}],"storage":[{"path":"/v/a.qcow2","dev":"vda"},{"path":"/v/b.qcow2","dev":"sda"}],"uefi":true}' ]] \ + out=$(node 'vm_json t25-m --disk vda=/v/a.qcow2 --nic sn-a=10.0.1.10 --nic sn-b=10.0.2.10 --disk xvda=/v/b.qcow2 --sshkey "ssh-ed25519 AAAA x" --password "\$6\$s\$h" --user-data "I2Nsb3Vk" --uefi') + [[ "${out}" == '{"name":"t25-m","memory":1024,"cpus":1,"metadata":{"sshkey":"ssh-ed25519 AAAA x","password":"$6$s$h","user_data":"I2Nsb3Vk"},"interfaces":[{"subnet":"sn-a","ip":"10.0.1.10","mac":"52:54:00:00:01:0a","primary":true},{"subnet":"sn-b","ip":"10.0.2.10","mac":"52:54:00:00:02:0a","primary":false}],"storage":[{"path":"/v/a.qcow2","dev":"vda"},{"path":"/v/b.qcow2","dev":"xvda"}],"uefi":true}' ]] \ || fail "complet : ${out}" out=$(node 'vm_json t21-a --nic sn-a=10.0.1.10') [[ "${out}" == '{"name":"t21-a","memory":1024,"cpus":1,"metadata":{},"interfaces":[{"subnet":"sn-a","ip":"10.0.1.10","mac":"52:54:00:00:01:0a","primary":true}],"storage":[],"uefi":false}' ]] || fail "minimal : ${out}" @@ -384,8 +384,8 @@ test_vm_json_builds_nics_disks_metadata_and_uefi () { test_vm_launch_copies_the_system_disk_first_and_waits () { setup "vm_launch : disque système vda copié en premier, POST, attente de running" local out - out=$(node 'VOLUMES=/v; TWO_IMAGE=/img; api_state () { echo; }; mkdir () { :; }; cp () { echo "CP $*"; }; api_post () { echo "POST $1 $(jq -c "[.storage[].dev, .interfaces[0].ip]" <<<"$2")"; }; wait_state () { echo "WAIT $*"; }; vm_launch t26-d --nic sn=10.0.0.10 --disk sda=/v/s.qcow2') - [[ "${out}" == $'CP /img /v/t26-d.qcow2\nPOST vms ["vda","sda","10.0.0.10"]\nWAIT vms/t26-d running' ]] || fail "${out}" + out=$(node 'VOLUMES=/v; TWO_IMAGE=/img; api_state () { echo; }; mkdir () { :; }; cp () { echo "CP $*"; }; api_post () { echo "POST $1 $(jq -c "[.storage[].dev, .interfaces[0].ip]" <<<"$2")"; }; wait_state () { echo "WAIT $*"; }; vm_launch t26-d --nic sn=10.0.0.10 --disk xvda=/v/s.qcow2') + [[ "${out}" == $'CP /img /v/t26-d.qcow2\nPOST vms ["vda","xvda","10.0.0.10"]\nWAIT vms/t26-d running' ]] || fail "${out}" [[ $(node 'api_state () { echo running; }; cp () { echo CP; }; api_post () { echo POST; }; vm_launch t --nic s=1.2.3.4 && echo OK') == OK ]] || fail "VM en running relancée" [[ $(node 'api_state () { echo; }; cp () { echo CP; }; vm_launch t --bad x || echo NON') == *NON ]] || fail "option invalide : disque copié ou POST envoyé" teardown diff --git a/test/e2e/suite/11-validation.sh b/test/e2e/suite/11-validation.sh index 3b63c60..b8f89ad 100644 --- a/test/e2e/suite/11-validation.sh +++ b/test/e2e/suite/11-validation.sh @@ -1,6 +1,6 @@ # fonctionnalité: validation de l'API — refus synchrones (400, 409, 422) des VPC, subnets et VM, sans trace en base # hôtes: hv1 -# tickets: #41, #57, #33, #62 +# tickets: #41, #57, #33, #62, #74 on hv1 <<'NODE' check "VPC vp-t11a, l3vni 1100 (témoin)" vpc_create vp-t11a 10.11.0.0/16 1100 @@ -40,6 +40,9 @@ done check "VM : subnet inconnu, 422" expect_code 422 api_post_code vms "$(vm_body t11-x sn-t11z 10.11.1.12 "${NONE}")" check "VM : aucune interface primaire, 400" expect_code 400 api_post_code vms "$(vm_body t11-x sn-t11a 10.11.1.12 "${NONE}" | sed 's/"primary":true/"primary":false/')" check "VM : interface sans mac, 400" expect_code 400 api_post_code vms "$(vm_body t11-x sn-t11a 10.11.1.12 "${NONE}" | jq -c 'del(.interfaces[0].mac)')" +for dev in sdb vdb xvdaa; do + check "VM : disque additionnel ${dev}, 400" expect_code 400 api_post_code vms "$(vm_body t11-x sn-t11a 10.11.1.12 "${NONE}" | jq -c --arg d "${dev}" '.storage += [{"path":"/x.qcow2","dev":$d}]')" +done check "VM : user_data en base64 invalide, 400" expect_code 400 api_post_code vms "$(vm_body t11-x sn-t11a 10.11.1.12 "${NONE}" '{"user_data":"pas du base64 !"}')" check "VMs refusées : aucune trace de t11-x" expect_code 404 api_code GET vms/t11-x cp "${TWO_IMAGE}" "${VOLUMES}/t11-ud.qcow2" diff --git a/test/e2e/suite/26-multi-disque.sh b/test/e2e/suite/26-multi-disque.sh index c756764..66902ac 100644 --- a/test/e2e/suite/26-multi-disque.sh +++ b/test/e2e/suite/26-multi-disque.sh @@ -1,29 +1,32 @@ -# 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 +# fonctionnalité: VM à plusieurs disques — racine virtio (vda) et SCSI (xvdX), tailles et bus vus par la VM, liens /dev/xvdX et by-id par numéro de série, démarrage sur vda # hôtes: hv1 # tickets: #32, #74 on hv1 <<'NODE' KEY=$(vm_key) mkdir -p "${VOLUMES}" -check "volume t26-d-sdb 1 Gio" qemu-img create -q -f qcow2 "${VOLUMES}/t26-d-sdb.qcow2" 1G -check "volume t26-d-sda 2 Gio" qemu-img create -q -f qcow2 "${VOLUMES}/t26-d-sda.qcow2" 2G +check "volume t26-d-xvdb 1 Gio" qemu-img create -q -f qcow2 "${VOLUMES}/t26-d-xvdb.qcow2" 1G +check "volume t26-d-xvda 2 Gio" qemu-img create -q -f qcow2 "${VOLUMES}/t26-d-xvda.qcow2" 2G check "VPC vp-t26" vpc_create vp-t26 10.26.0.0/16 check "subnet sn-t26" subnet_create sn-t26 vp-t26 2601 10.26.1.0/24 -check "VM t26-d : vda (système), sdb, sda" vm_launch t26-d --nic sn-t26=10.26.1.10 --sshkey "${KEY}" \ - --disk "sdb=${VOLUMES}/t26-d-sdb.qcow2" --disk "sda=${VOLUMES}/t26-d-sda.qcow2" -check "API : trois disques" test "$(curl -fsS "${API}/vms/t26-d" | jq -r '[.storage[].dev] | sort | join(" ")')" = "sda sdb vda" +check "VM t26-d : vda (racine), xvdb, xvda" vm_launch t26-d --nic sn-t26=10.26.1.10 --sshkey "${KEY}" \ + --disk "xvdb=${VOLUMES}/t26-d-xvdb.qcow2" --disk "xvda=${VOLUMES}/t26-d-xvda.qcow2" +check "API : trois disques" test "$(curl -fsS "${API}/vms/t26-d" | jq -r '[.storage[].dev] | sort | join(" ")')" = "vda xvda xvdb" 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' 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 +check "t26-d : xvda déclaré → cible SCSI 0, 2 Gio" target_size 0 2147483648 +check "t26-d : xvdb déclaré → cible SCSI 1, 1 Gio" target_size 1 1073741824 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' +info "t26-d : noms du noyau : $(vm_ssh vp-t26 10.26.1.10 'lsblk -dn -o NAME,HCTL,SIZE' 2>&1 | tr '\n' ' ')" +link_size () { local v; v=$(vm_ssh vp-t26 10.26.1.10 "lsblk -b -dn -o SIZE \$(readlink -e ${1})" 2>&1 | tr -d ' '); [ "${v}" = "${2}" ] || { echo "lu : ${v}"; return 1; }; } +check "t26-d : /dev/xvda → 2 Gio (règle udev de l'image)" link_size /dev/xvda 2147483648 +check "t26-d : /dev/xvdb → 1 Gio (règle udev de l'image)" link_size /dev/xvdb 1073741824 +check "t26-d : by-id scsi-0QEMU_QEMU_HARDDISK_xvda → 2 Gio" link_size /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_xvda 2147483648 +check "t26-d : by-id scsi-0QEMU_QEMU_HARDDISK_xvdb → 1 Gio" link_size /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_xvdb 1073741824 +check "t26-d : by-id virtio-vda → /dev/vda" test "$(vm_ssh vp-t26 10.26.1.10 'readlink -e /dev/disk/by-id/virtio-vda')" = /dev/vda +check "t26-d : xvda et xvdb en SCSI (virtio-scsi)" vm_ssh vp-t26 10.26.1.10 'for d in xvda xvdb; do k=$(basename $(readlink -e /dev/$d)); test -d /sys/block/$k/device/scsi_device && readlink -f /sys/block/$k | grep -q virtio || exit 1; done' 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' -check "t26-d : écriture sur sdb et sda" vm_ssh vp-t26 10.26.1.10 'sudo dd if=/dev/zero of=/dev/sdb bs=1M count=8 oflag=direct status=none && sudo dd if=/dev/zero of=/dev/sda bs=1M count=8 oflag=direct status=none' +check "t26-d : partition sur xvdb → lien /dev/xvdb1" vm_ssh vp-t26 10.26.1.10 'echo ",,L" | sudo sfdisk -q /dev/xvdb >/dev/null && sudo udevadm settle && test -b "$(readlink -e /dev/xvdb1)"' +check "t26-d : écriture sur xvda et xvdb1" vm_ssh vp-t26 10.26.1.10 'sudo dd if=/dev/zero of=/dev/xvda bs=1M count=8 oflag=direct status=none && sudo dd if=/dev/zero of=/dev/xvdb1 bs=1M count=8 oflag=direct status=none' NODE From d1b50d546c6ecc49eafd840b5baf0dc57925de62 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 23 Oct 2026 00:26:47 +0200 Subject: [PATCH 6/9] =?UTF-8?q?f-74:=20doc:=20vda=20racine,=20xvdX=20addit?= =?UTF-8?q?ionnels=20et=20/dev/xvdX=20par=20r=C3=A8gle=20udev=20d'image,?= =?UTF-8?q?=20migration,=20notes=20de=20version=20#74?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- api/agent.yaml | 14 ++++++++------ docs/architecture/contraintes.rst | 3 ++- docs/architecture/stockage.rst | 8 +++++++- docs/concepts/vpc-subnet-vm.rst | 11 ++++++----- docs/demarrage/premier-vpc.rst | 15 ++++++++------- docs/deploiement/image-qcow2.rst | 15 +++++++++++++++ docs/developpement/lab.rst | 4 ++-- release_notes/0.2.0.md | 17 ++++++++++++++++- 8 files changed, 64 insertions(+), 23 deletions(-) diff --git a/api/agent.yaml b/api/agent.yaml index 26b223e..03aad15 100644 --- a/api/agent.yaml +++ b/api/agent.yaml @@ -567,12 +567,14 @@ components: dev: type: string 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]$' + vda is the virtio-blk root disk, seen as /dev/vda and booted + first. xvdX is an additional disk on SCSI target X (xvda → 0), + seen by the guest kernel as some /dev/sdY in detection order. The + disk serial is set to dev: an image that follows the two image + requirements links it to /dev/xvdX, and udev always exposes it as + /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_xvdX (virtio-vda for the + root disk). Anything else → 400; sdX is no longer accepted. + pattern: '^(vda|xvd[a-z])$' example: vda VM: diff --git a/docs/architecture/contraintes.rst b/docs/architecture/contraintes.rst index c83fec6..42e8de2 100644 --- a/docs/architecture/contraintes.rst +++ b/docs/architecture/contraintes.rst @@ -39,7 +39,8 @@ Réseau QEMU et VM ---------- -* **Un seul disque ``vdX`` par VM** ; les disques additionnels passent par le SCSI (``sdX``). La +* **Un seul disque virtio, ``vda``, le disque racine** ; les disques additionnels passent par le SCSI + (``xvdX``, cible X). La carte PCI en dépend : NIC en ``0x03``, contrôleur SCSI en ``0x1e``, virtio-blk en ``0x1f``. * ``bus=pci.0`` est explicite sur les trois ``-device`` : un passage de la machine en **q35** casserait le démarrage (``Bus 'pci.0' not found``). diff --git a/docs/architecture/stockage.rst b/docs/architecture/stockage.rst index c8c9af4..431b92b 100644 --- a/docs/architecture/stockage.rst +++ b/docs/architecture/stockage.rst @@ -28,7 +28,7 @@ de sérialisation structurée. vm//nic//primary → "true" (exactement une interface ; absent sur les autres) vm//nic//tap_id → (alloué au premier démarrage, puis conservé) vm//metadata_port → - vm//disk/ → (une clé par disque : sda, vda, …) + vm//disk/ → (une clé par disque : vda, xvda, xvdb, …) vm//memory → (Mo) vm//cpus → vm//uefi → "true" (absent si SeaBIOS) @@ -55,6 +55,12 @@ clés. Les VM ``deleted`` sont ignorées. Une interface dont la MAC est introuva démarrage en la nommant, et la table reste en place tant que toutes les interfaces ne sont pas migrées. +**Anciens noms de disques.** Jusqu'en 0.1.0, les disques additionnels s'appelaient ``sdX``. Au +démarrage, l'agent renomme chaque clé ``vm//disk/sdX`` en ``vm//disk/xvdX`` (même +lettre, même cible SCSI). Si ``xvdX`` existe déjà avec un autre chemin, le démarrage échoue en +nommant la clé. Le numéro de série du disque, et donc son lien ``by-id``, prend le nouveau nom au +prochain lancement de la VM. + **Les états passent par ``state``.** Toujours ``state.Set`` / ``state.Get`` : ``Set`` refuse une valeur hors énumération, ``Get`` refuse de retourner une valeur non reconnue. ``error`` n'est écrit que par ``Dispatcher.Dispatch``, via ``cmd.Key()``. diff --git a/docs/concepts/vpc-subnet-vm.rst b/docs/concepts/vpc-subnet-vm.rst index 212225e..ca9ebcc 100644 --- a/docs/concepts/vpc-subnet-vm.rst +++ b/docs/concepts/vpc-subnet-vm.rst @@ -94,11 +94,12 @@ suppression, ces ``/32`` sont retirés **avant** l'arrêt de QEMU. Comme un subn supprimé tant qu'une VM l'utilise, le ``/32`` d'une VM est toujours retiré avant le ``/24`` de son subnet — l'ordre qui évite le trou noir de `#41 `_. -**Stockage.** Un seul disque ``vdX`` (virtio-blk) par VM ; les disques supplémentaires passent -par le contrôleur SCSI (``sdX``). Cette contrainte vient de la carte PCI figée — voir -:doc:`/architecture/contraintes`. ``dev`` fixe l'emplacement du disque (cible SCSI, slot PCI) -et son numéro de série, pas son nom dans le guest : le disque se retrouve par -``/dev/disk/by-id/…``. +**Stockage.** Un seul disque virtio par VM, ``vda``, le disque racine ; les disques +supplémentaires passent par le contrôleur SCSI (``xvdX``, cible X). Cette contrainte vient de la +carte PCI figée — voir :doc:`/architecture/contraintes`. ``dev`` fixe l'emplacement du disque +(cible SCSI, slot PCI) et son numéro de série, pas le nom que lui donne le noyau du guest +(``/dev/sdY``, dans l'ordre de détection) : le disque se retrouve par ``/dev/xvdX`` dans une +image conforme, et toujours par ``/dev/disk/by-id/…``. Ce qui est stocké, et où ------------------------ diff --git a/docs/demarrage/premier-vpc.rst b/docs/demarrage/premier-vpc.rst index 3d3b2de..567b5bc 100644 --- a/docs/demarrage/premier-vpc.rst +++ b/docs/demarrage/premier-vpc.rst @@ -115,15 +115,16 @@ Exactement une interface est ``primary`` slot PCI (``0x03 + index``), donc le nom de l'interface dans le guest. Tous les subnets d'une VM doivent appartenir au même VPC. -Un seul disque ``vdX`` - Les disques supplémentaires passent par ``sdX``. La carte PCI en dépend — voir +``vda`` pour la racine, ``xvdX`` pour les autres disques + ``vda`` est le disque racine, virtio, démarré en premier. Les disques supplémentaires sont des + ``xvdX`` (``xvda`` = cible SCSI 0) ; ``sdX`` est refusé (400). 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``. +``/dev/xvdX`` dans le guest, jamais ``/dev/sdX`` + Le noyau du guest nomme les disques SCSI ``sdX`` dans l'ordre de détection, qui change d'un + démarrage à l'autre. L'agent donne à chaque disque le numéro de série ```` ; une image + conforme (:doc:`/deploiement/image-qcow2`) en fait le lien ``/dev/xvdX``. Sans cette règle, + le nom stable reste ``/dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_xvdX``. 4. Vérifier ----------- diff --git a/docs/deploiement/image-qcow2.rst b/docs/deploiement/image-qcow2.rst index a8e0488..5922a47 100644 --- a/docs/deploiement/image-qcow2.rst +++ b/docs/deploiement/image-qcow2.rst @@ -284,6 +284,21 @@ interface (``10-netplan-*``). Sur une image démarrée avec ``net.ifnames=0``, v l'image Rocky de cette page, n'est pas encore vérifié. Sans lui, une VM à plusieurs interfaces n'a de bail que sur la première. +**Noms stables des disques additionnels** + +.. code-block:: bash + + cat << 'ENDFILE' > /mnt/etc/udev/rules.d/90-two-xvd.rules + SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", ENV{ID_SERIAL_SHORT}=="xvd[a-z]", SYMLINK+="$env{ID_SERIAL_SHORT}" + SUBSYSTEM=="block", ENV{DEVTYPE}=="partition", ENV{ID_SERIAL_SHORT}=="xvd[a-z]", SYMLINK+="$env{ID_SERIAL_SHORT}%n" + ENDFILE + +L'agent donne à chaque disque additionnel le numéro de série ``xvdX`` déclaré dans l'API ; ces +règles en font ``/dev/xvdX`` (et ``/dev/xvdXN`` pour ses partitions). Le noyau, lui, nomme les +disques SCSI ``/dev/sdY`` dans l'ordre de détection, qui change d'un démarrage à l'autre : une +``fstab`` ou un script de la VM doit viser ``/dev/xvdX``, jamais ``/dev/sdY``. Le disque racine +reste ``/dev/vda``. + **Services et durcissement** .. code-block:: bash diff --git a/docs/developpement/lab.rst b/docs/developpement/lab.rst index a3972bb..659ea24 100644 --- a/docs/developpement/lab.rst +++ b/docs/developpement/lab.rst @@ -320,7 +320,7 @@ Générée par ``test/e2e/run.sh --matrice`` à partir des en-têtes ; à régé - hv1 - #33, #62, #73 * - ``26-multi-disque`` - - 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 + - VM à plusieurs disques — racine virtio (vda) et SCSI (xvdX), tailles et bus vus par la VM, liens ``/dev/xvdX`` et ``by-id`` par numéro de série, démarrage sur vda - hv1 - #32, #74 * - ``27-reboot`` @@ -412,7 +412,7 @@ Hypothèses vérifiées en lab, à garder en tête en écrivant un test : * systemd-networkd **ne réécrit pas** un bail renouvelé à l'identique : un renouvellement se vérifie par le DHCPACK dans le journal du serveur (``lease_renewed``), pas par le fichier de bail ; -* l'agent n'accepte **qu'un seul disque virtio** (le disque système) ; les autres sont des ``sdX`` ; +* l'agent n'accepte **qu'un seul disque virtio** (le disque racine, ``vda``) ; les autres sont des ``xvdX`` ; * sur Debian 12, ``ebtables -L`` (nft) garde les zéros de tête des MAC ; * ``interface_ip`` est posée en ``/32`` sur le bridge du netns en mode ``bridge`` ; * depuis le netns d'un hôte, une VM d'un autre hôte ne répond pas : la réponse repart vers la diff --git a/release_notes/0.2.0.md b/release_notes/0.2.0.md index 001f589..77c0798 100644 --- a/release_notes/0.2.0.md +++ b/release_notes/0.2.0.md @@ -87,6 +87,18 @@ L3VNI, avec une configuration BGP pilotée par l'agent ; documentation du projet leurs subnets (VM injoignable), et n'était pas tenable en IPv6 - Migration au démarrage : les VM existantes gardent leur MAC, recopiée sur chaque interface +**Disques : `vda` pour la racine, `xvdX` pour les autres (#74)** + +- `dev` accepte désormais `vda`, le disque racine virtio, et `xvda` à `xvdz` pour les disques + additionnels, sur la cible SCSI de même rang (`xvda` → 0). Toute autre valeur est refusée (400), + `sdX` compris +- Chaque disque reçoit le numéro de série ``. Le noyau de l'invité nomme les disques SCSI + `/dev/sdY` dans l'ordre de détection, qui change d'un démarrage à l'autre (mesuré en lab : `sda` + et `sdb` inversés 4 démarrages sur 6). Le nom stable est `/dev/xvdX`, créé par une règle udev + de l'image (exigence décrite dans la documentation de construction d'image), et toujours + `/dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_xvdX` +- Migration au démarrage : les clés `vm//disk/sdX` deviennent `vm//disk/xvdX` + **Exploitation** - Le watchdog contrôle aussi, avec une section `bgp` : les sessions vers les route reflectors ; @@ -164,7 +176,7 @@ bash ./deploy.sh -t 0.2.0 ``` Sans `dhcp.backend` ni `bgp` dans `/etc/two/agent.yml`, le comportement est celui de la 0.1.0, à -trois exceptions près, qui touchent les appelants de l'API : +quatre exceptions près, qui touchent les appelants de l'API : - **`interface_ip` ne se fournit plus pour un subnet `vxlan`** : il est refusé (400), l'agent le calcule. Le retirer des appels de création, et ne plus placer de VM sur les deux dernières @@ -172,6 +184,9 @@ trois exceptions près, qui touchent les appelants de l'API : - **un subnet encore utilisé par une VM ne se supprime plus** : supprimer les VM d'abord - **chaque interface d'une VM doit porter sa `mac`** (400 sinon) : l'appelant la choisit et en garantit l'unicité. Les VM existantes gardent la leur, recopiée au premier démarrage de l'agent +- **les disques additionnels s'appellent `xvdX`** : `sdX` est refusé (400). Les VM existantes sont + migrées ; leurs disques prennent le numéro de série `xvdX` au prochain lancement, et une image + qui les montait par `/dev/sdY` doit passer à `/dev/xvdX` Les subnets `vxlan` existants gardent leur adressage et le modèle précédent (gateway sur le bridge) jusqu'à leur recréation. From 8cb5117cb2b4af941ac3d890d93ad3d369b465f4 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 23 Oct 2026 12:10:01 +0200 Subject: [PATCH 7/9] =?UTF-8?q?f-56:=20agent:=20MTU=20unique=20network.mtu?= =?UTF-8?q?=5Fvm,=20underlay=20=C3=A0=209000=20contr=C3=B4l=C3=A9=20=C3=A0?= =?UTF-8?q?=20la=20cr=C3=A9ation,=20option=20DHCP=2026=20et=20host=5Fmtu?= =?UTF-8?q?=20#56?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- conf/agent/config.exemple.yml | 12 +++ internal/api/agent/helpers_test.go | 4 + internal/api/dhcp/convert.go | 3 +- internal/api/dhcp/digest.go | 2 +- internal/api/dhcp/models.go | 2 + internal/api/dhcp/mtu_test.go | 44 +++++++++ internal/api/dhcp/server.go | 3 + internal/config/agent/network.go | 52 +++++++++++ internal/config/agent/network_test.go | 98 ++++++++++++++++++++ internal/config/agent/struct.go | 7 ++ internal/dhcp/generate.go | 8 ++ internal/dhcp/mtu_test.go | 20 ++++ internal/dhcp/struct.go | 1 + internal/dhcpbackend/backend.go | 1 + internal/dhcpbackend/dnsmasq.go | 1 + internal/dhcpbackend/dnsmasq_test.go | 6 ++ internal/dhcpbackend/two.go | 1 + internal/dhcpbackend/two_test.go | 12 +++ internal/dhcpd/dhcpd.go | 8 ++ internal/dhcpd/mtu_test.go | 68 ++++++++++++++ internal/dhcpd/reply.go | 1 + internal/dhcpd/store.go | 4 +- internal/dispatcher/agent/helpers_test.go | 4 + internal/dispatcher/agent/mtu_test.go | 88 ++++++++++++++++++ internal/dispatcher/agent/subnet_commands.go | 10 ++ internal/dispatcher/agent/vpc_commands.go | 22 +++++ internal/l3vni/l3.go | 9 +- internal/l3vni/l3_test.go | 10 +- internal/netif/link.go | 8 ++ internal/netif/tap_linux.go | 4 +- internal/netif/tap_other.go | 2 +- internal/qemu/args.go | 6 +- internal/qemu/args_test.go | 5 +- internal/qemu/config.go | 1 + internal/subnet/create.go | 10 +- internal/subnet/data.go | 1 + internal/vm/create.go | 4 +- 37 files changed, 518 insertions(+), 24 deletions(-) create mode 100644 internal/api/dhcp/mtu_test.go create mode 100644 internal/config/agent/network.go create mode 100644 internal/config/agent/network_test.go create mode 100644 internal/dhcp/mtu_test.go create mode 100644 internal/dhcpd/mtu_test.go create mode 100644 internal/dispatcher/agent/mtu_test.go diff --git a/conf/agent/config.exemple.yml b/conf/agent/config.exemple.yml index a31a58d..19a09f9 100644 --- a/conf/agent/config.exemple.yml +++ b/conf/agent/config.exemple.yml @@ -35,6 +35,18 @@ interfaces: internet: br-000000 admin: br-000000 +# MTU, identical on every hypervisor. +# mtu_vm: MTU of the VMs and of every bridge, veth, tap and VXLAN the agent creates, +# announced by DHCP option 26 and QEMU host_mtu. 1500 at most; below 1500 only with +# allow_mtu_vm_below_1500, never below 1280. +# allow_mtu_underlay_below_9000: a vxlan subnet (or a VPC with l3vni) is refused when +# its underlay is not at exactly 9000, unless this is true. The underlay must always +# carry mtu_vm plus 50 bytes of VXLAN header. +network: + mtu_vm: 1500 + allow_mtu_vm_below_1500: false + allow_mtu_underlay_below_9000: false + # BGP control plane of the hypervisor (optional). # Absent: the agent leaves FRR alone. Present: at every start, before serving its # API, the agent applies the base BGP configuration through vtysh (router-id = the diff --git a/internal/api/agent/helpers_test.go b/internal/api/agent/helpers_test.go index 69adfb2..d3808ce 100644 --- a/internal/api/agent/helpers_test.go +++ b/internal/api/agent/helpers_test.go @@ -29,3 +29,7 @@ func newTestServerWith(t *testing.T, cfg *configuration.Config) (*Server, *badge d := dispatcher.New(q, db, cfg, logger) return New(d, db, logger, "127.0.0.1:0"), db } + +func init() { + dispatcher.LinkMTU = func(string) (int, error) { return 9000, nil } +} diff --git a/internal/api/dhcp/convert.go b/internal/api/dhcp/convert.go index 77dd7c4..88d3c2f 100644 --- a/internal/api/dhcp/convert.go +++ b/internal/api/dhcp/convert.go @@ -17,7 +17,7 @@ func (s Subnet) toConfig() (dhcpd.SubnetConfig, error) { return dhcpd.SubnetConfig{}, fmt.Errorf("invalid interface ip %q", s.InterfaceIP) } - c := dhcpd.SubnetConfig{Network: network, InterfaceIP: interfaceIP} + c := dhcpd.SubnetConfig{Network: network, InterfaceIP: interfaceIP, MTU: s.MTU} if s.VPCRoute != "" { if _, c.VPCRoute, err = net.ParseCIDR(s.VPCRoute); err != nil { @@ -48,6 +48,7 @@ func subnetFromConfig(c dhcpd.SubnetConfig) Subnet { s := Subnet{ Network: c.Network.String(), InterfaceIP: c.InterfaceIP.String(), + MTU: c.MTU, } if c.VPCRoute != nil { s.VPCRoute = c.VPCRoute.String() diff --git a/internal/api/dhcp/digest.go b/internal/api/dhcp/digest.go index f311b22..4cc0c25 100644 --- a/internal/api/dhcp/digest.go +++ b/internal/api/dhcp/digest.go @@ -47,7 +47,7 @@ func CanonicalSubnet(s Subnet) (Subnet, error) { return Subnet{}, err } - out := Subnet{Network: network, InterfaceIP: interfaceIP} + out := Subnet{Network: network, InterfaceIP: interfaceIP, MTU: s.MTU} if s.VPCRoute != "" { if out.VPCRoute, err = canonicalCIDR(s.VPCRoute); err != nil { diff --git a/internal/api/dhcp/models.go b/internal/api/dhcp/models.go index d454194..7fc3933 100644 --- a/internal/api/dhcp/models.go +++ b/internal/api/dhcp/models.go @@ -17,6 +17,7 @@ type Subnet struct { InterfaceIP string `json:"interface_ip"` VPCRoute string `json:"vpc_route,omitempty"` DefaultGateway string `json:"default_gateway,omitempty"` + MTU int `json:"mtu,omitempty"` } type Host struct { @@ -38,6 +39,7 @@ type Lease struct { Router string `json:"router,omitempty"` DNS []string `json:"dns"` Routes []string `json:"routes"` + MTU uint16 `json:"mtu,omitempty"` LeaseSeconds uint32 `json:"lease_seconds"` } diff --git a/internal/api/dhcp/mtu_test.go b/internal/api/dhcp/mtu_test.go new file mode 100644 index 0000000..5131f08 --- /dev/null +++ b/internal/api/dhcp/mtu_test.go @@ -0,0 +1,44 @@ +package dhcpapi + +import ( + "net" + "testing" + + "git.g3e.fr/syonad/two/internal/dhcpd" + "github.com/insomniacslk/dhcp/dhcpv4" +) + +func TestSubnet_MTUSurvivesTheConversions(t *testing.T) { + c, err := Subnet{Network: "10.0.5.0/24", InterfaceIP: "10.0.5.1", MTU: 1450}.toConfig() + if err != nil { + t.Fatalf("toConfig : %v", err) + } + if c.MTU != 1450 { + t.Errorf("toConfig : mtu %d", c.MTU) + } + if got := subnetFromConfig(c).MTU; got != 1450 { + t.Errorf("subnetFromConfig : mtu %d", got) + } + canonical, err := CanonicalSubnet(Subnet{Network: "10.0.5.0/24", InterfaceIP: "10.0.5.1", MTU: 1450}) + if err != nil || canonical.MTU != 1450 { + t.Errorf("CanonicalSubnet : %+v, %v", canonical, err) + } +} + +func TestLeaseFromReply_ShowsTheMTU(t *testing.T) { + _, network, _ := net.ParseCIDR("10.0.5.0/24") + mac, _ := net.ParseMAC("00:22:33:00:00:0a") + c := dhcpd.SubnetConfig{Network: network, InterfaceIP: net.ParseIP("10.0.5.1"), MTU: 1450} + h := dhcpd.Host{MAC: mac, IP: net.ParseIP("10.0.5.10")} + req, err := dhcpv4.New(dhcpv4.WithMessageType(dhcpv4.MessageTypeRequest), dhcpv4.WithHwAddr(mac)) + if err != nil { + t.Fatal(err) + } + reply, err := dhcpd.BuildReply(c, h, req) + if err != nil { + t.Fatalf("BuildReply : %v", err) + } + if got := leaseFromReply(mac, reply).MTU; got != 1450 { + t.Errorf("lease.MTU = %d, attendu 1450", got) + } +} diff --git a/internal/api/dhcp/server.go b/internal/api/dhcp/server.go index 879ac58..7ec50d4 100644 --- a/internal/api/dhcp/server.go +++ b/internal/api/dhcp/server.go @@ -186,5 +186,8 @@ func leaseFromReply(mac net.HardwareAddr, reply *dhcpv4.DHCPv4) *Lease { for _, route := range reply.ClasslessStaticRoute() { lease.Routes = append(lease.Routes, route.Dest.String()+" via "+route.Router.String()) } + if mtu, err := dhcpv4.GetUint16(dhcpv4.OptionInterfaceMTU, reply.Options); err == nil { + lease.MTU = mtu + } return lease } diff --git a/internal/config/agent/network.go b/internal/config/agent/network.go new file mode 100644 index 0000000..7ee02e0 --- /dev/null +++ b/internal/config/agent/network.go @@ -0,0 +1,52 @@ +package configuration + +import "fmt" + +const ( + MTUVM = 1500 + MinMTUVM = 1280 + MTUUnderlay = 9000 + VXLANOverhead = 50 +) + +type Network struct { + MTUVM int `mapstructure:"mtu_vm"` + AllowMTUVMBelow1500 bool `mapstructure:"allow_mtu_vm_below_1500"` + AllowMTUUnderlayBelow9000 bool `mapstructure:"allow_mtu_underlay_below_9000"` +} + +func (n Network) VM() int { + if n.MTUVM == 0 { + return MTUVM + } + return n.MTUVM +} + +func (n Network) Validate() error { + switch { + case n.MTUVM > MTUVM: + return fmt.Errorf("network.mtu_vm %d is above %d", n.MTUVM, MTUVM) + case n.MTUVM < MinMTUVM: + return fmt.Errorf("network.mtu_vm %d is below the minimum %d", n.MTUVM, MinMTUVM) + case n.MTUVM < MTUVM && !n.AllowMTUVMBelow1500: + return fmt.Errorf("network.mtu_vm %d is below %d: set network.allow_mtu_vm_below_1500 to allow it", n.MTUVM, MTUVM) + } + return nil +} + +func (n Network) CheckUnderlay(iface string, mtu int) error { + if mtu != MTUUnderlay && !n.AllowMTUUnderlayBelow9000 { + return fmt.Errorf("underlay %s has mtu %d, %d expected: set network.allow_mtu_underlay_below_9000 to allow another value", iface, mtu, MTUUnderlay) + } + if mtu < n.VM()+VXLANOverhead { + return fmt.Errorf("underlay %s has mtu %d, below network.mtu_vm %d plus %d bytes of vxlan header", iface, mtu, n.VM(), VXLANOverhead) + } + return nil +} + +func (n Network) CheckBridge(iface string, mtu int) error { + if mtu < n.VM() { + return fmt.Errorf("bridge %s has mtu %d, below network.mtu_vm %d", iface, mtu, n.VM()) + } + return nil +} diff --git a/internal/config/agent/network_test.go b/internal/config/agent/network_test.go new file mode 100644 index 0000000..6c475dd --- /dev/null +++ b/internal/config/agent/network_test.go @@ -0,0 +1,98 @@ +package configuration + +import ( + "strings" + "testing" +) + +func TestLoadConfig_NetworkDefauts(t *testing.T) { + cfg, err := LoadConfig(writeYAML(t, "")) + if err != nil { + t.Fatalf("LoadConfig a échoué : %v", err) + } + if cfg.Network.MTUVM != 1500 || cfg.Network.AllowMTUVMBelow1500 || cfg.Network.AllowMTUUnderlayBelow9000 { + t.Errorf("network par défaut : %+v", cfg.Network) + } +} + +func TestLoadConfig_MTUVMRefuseSansOption(t *testing.T) { + if _, err := LoadConfig(writeYAML(t, "network:\n mtu_vm: 1450\n")); err == nil || !strings.Contains(err.Error(), "allow_mtu_vm_below_1500") { + t.Errorf("mtu_vm 1450 sans option : %v", err) + } + cfg, err := LoadConfig(writeYAML(t, "network:\n mtu_vm: 1450\n allow_mtu_vm_below_1500: true\n")) + if err != nil || cfg.Network.MTUVM != 1450 { + t.Errorf("mtu_vm 1450 avec option : %v, %+v", err, cfg) + } +} + +func TestNetworkValidate(t *testing.T) { + cases := []struct { + n Network + ok bool + }{ + {Network{MTUVM: 1500}, true}, + {Network{MTUVM: 1501}, false}, + {Network{MTUVM: 9000, AllowMTUVMBelow1500: true}, false}, + {Network{MTUVM: 1499}, false}, + {Network{MTUVM: 1499, AllowMTUVMBelow1500: true}, true}, + {Network{MTUVM: 1280, AllowMTUVMBelow1500: true}, true}, + {Network{MTUVM: 1279, AllowMTUVMBelow1500: true}, false}, + {Network{MTUVM: 0, AllowMTUVMBelow1500: true}, false}, + } + for _, c := range cases { + if err := c.n.Validate(); (err == nil) != c.ok { + t.Errorf("Validate(%+v) = %v", c.n, err) + } + } +} + +func TestNetworkCheckUnderlay(t *testing.T) { + n := Network{MTUVM: 1500} + if err := n.CheckUnderlay("br-000000", 9000); err != nil { + t.Errorf("9000 : %v", err) + } + for _, m := range []int{9216, 8999, 1550} { + if err := n.CheckUnderlay("br-000000", m); err == nil || !strings.Contains(err.Error(), "allow_mtu_underlay_below_9000") { + t.Errorf("%d sans option : %v", m, err) + } + } + n.AllowMTUUnderlayBelow9000 = true + if err := n.CheckUnderlay("br-000000", 1550); err != nil { + t.Errorf("1550 avec option : %v", err) + } + if err := n.CheckUnderlay("br-000000", 1549); err == nil || !strings.Contains(err.Error(), "vxlan header") { + t.Errorf("1549 avec option, mtu_vm 1500 : %v", err) + } + n.MTUVM = 1400 + if err := n.CheckUnderlay("br-000000", 1450); err != nil { + t.Errorf("1450 pour mtu_vm 1400 : %v", err) + } + if err := (Network{MTUVM: 8960}).CheckUnderlay("br-000000", 9000); err == nil { + t.Error("mtu_vm 8960 + 50 dépasse 9000") + } +} + +func TestNetworkVMIs1500WhenUnset(t *testing.T) { + if got := (Network{}).VM(); got != 1500 { + t.Errorf("VM() d'une section vide = %d", got) + } + if got := (Network{MTUVM: 1400}).VM(); got != 1400 { + t.Errorf("VM() = %d, attendu 1400", got) + } + if err := (Network{}).CheckUnderlay("br-000000", 1549); err == nil { + t.Error("section vide : 1549 doit être refusé (mtu_vm 1500 + 50)") + } +} + +func TestNetworkCheckBridge(t *testing.T) { + n := Network{MTUVM: 1500} + if err := n.CheckBridge("br-lan", 1500); err != nil { + t.Errorf("1500 : %v", err) + } + if err := n.CheckBridge("br-000000", 9000); err != nil { + t.Errorf("9000 : %v", err) + } + if err := n.CheckBridge("br-lan", 1499); err == nil || !strings.Contains(err.Error(), "br-lan") { + t.Errorf("1499 : %v", err) + } +} diff --git a/internal/config/agent/struct.go b/internal/config/agent/struct.go index 17ddd43..86a6fd7 100644 --- a/internal/config/agent/struct.go +++ b/internal/config/agent/struct.go @@ -55,6 +55,7 @@ type Config struct { Enabled bool `mapstructure:"enabled"` IntervalSeconds int `mapstructure:"interval_seconds"` } `mapstructure:"watchdog"` + Network Network `mapstructure:"network"` BGP BGP `mapstructure:"bgp"` DefaultInterface string `mapstructure:"default_interface"` Interfaces map[string]string `mapstructure:"interfaces"` @@ -90,6 +91,9 @@ func LoadConfig(path string) (*Config, error) { v.SetDefault("default_interface", "br-000000") v.SetDefault("logger.level", "info") v.SetDefault("logger.debug", false) + v.SetDefault("network.mtu_vm", MTUVM) + v.SetDefault("network.allow_mtu_vm_below_1500", false) + v.SetDefault("network.allow_mtu_underlay_below_9000", false) if err := v.ReadInConfig(); err != nil && !errors.Is(err, os.ErrNotExist) { return nil, fmt.Errorf("read %s: %w", path, err) @@ -99,6 +103,9 @@ func LoadConfig(path string) (*Config, error) { if err := v.Unmarshal(&cfg); err != nil { return nil, err } + if err := cfg.Network.Validate(); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } return &cfg, nil } diff --git a/internal/dhcp/generate.go b/internal/dhcp/generate.go index 6724b62..ccd39b3 100644 --- a/internal/dhcp/generate.go +++ b/internal/dhcp/generate.go @@ -31,6 +31,7 @@ func GenerateConfig(c Config) (string, error) { fmt.Fprintf(&sb, "dhcp-option=3\n") } fmt.Fprintf(&sb, "dhcp-option=6,1.1.1.1,8.8.8.8\n") + fmt.Fprintf(&sb, "dhcp-option=26,%d\n", c.interfaceMTU()) fmt.Fprintf(&sb, "dhcp-hostsdir=%s\n", HostsDir(c.ConfDir, c.Name)) fmt.Fprintf(&sb, "dhcp-optsdir=%s\n", OptsDir(c.ConfDir, c.Name)) @@ -44,6 +45,13 @@ func GenerateConfig(c Config) (string, error) { return outPath, os.WriteFile(outPath, []byte(sb.String()), 0644) } +func (c Config) interfaceMTU() int { + if c.MTU == 0 { + return 1500 + } + return c.MTU +} + func classlessRoutes(c Config) []string { nextHop := c.InterfaceIP.String() diff --git a/internal/dhcp/mtu_test.go b/internal/dhcp/mtu_test.go new file mode 100644 index 0000000..e4ea54f --- /dev/null +++ b/internal/dhcp/mtu_test.go @@ -0,0 +1,20 @@ +package dhcp + +import ( + "strings" + "testing" +) + +func TestGenerateConfig_CarriesTheInterfaceMTU(t *testing.T) { + c := newConf(t, "192.168.1.0/29") + c.MTU = 1450 + if content := confLines(t, c); !strings.Contains(content, "dhcp-option=26,1450\n") { + t.Errorf("option 26 absente :\n%s", content) + } +} + +func TestGenerateConfig_InterfaceMTUIs1500WhenUnset(t *testing.T) { + if content := confLines(t, newConf(t, "192.168.1.0/29")); !strings.Contains(content, "dhcp-option=26,1500\n") { + t.Errorf("option 26 absente :\n%s", content) + } +} diff --git a/internal/dhcp/struct.go b/internal/dhcp/struct.go index 44d51a7..1d8ca11 100644 --- a/internal/dhcp/struct.go +++ b/internal/dhcp/struct.go @@ -15,4 +15,5 @@ type Config struct { ConfDir string Listen string Except string + MTU int } diff --git a/internal/dhcpbackend/backend.go b/internal/dhcpbackend/backend.go index 9d61510..cfdf47c 100644 --- a/internal/dhcpbackend/backend.go +++ b/internal/dhcpbackend/backend.go @@ -16,6 +16,7 @@ type Subnet struct { InterfaceIP net.IP VPCRoute *net.IPNet DefaultGateway net.IP + MTU int } func (s Subnet) Instance() string { diff --git a/internal/dhcpbackend/dnsmasq.go b/internal/dhcpbackend/dnsmasq.go index e6ac72b..c21df2e 100644 --- a/internal/dhcpbackend/dnsmasq.go +++ b/internal/dhcpbackend/dnsmasq.go @@ -35,6 +35,7 @@ func (b Dnsmasq) config(s Subnet) dhcp.Config { InterfaceIP: s.InterfaceIP, VPCRoute: s.VPCRoute, DefaultGateway: s.DefaultGateway, + MTU: s.MTU, } if s.Listen != "" && s.Listen != s.Bridge { c.Listen = s.Listen diff --git a/internal/dhcpbackend/dnsmasq_test.go b/internal/dhcpbackend/dnsmasq_test.go index 4f2a69a..d83a506 100644 --- a/internal/dhcpbackend/dnsmasq_test.go +++ b/internal/dhcpbackend/dnsmasq_test.go @@ -112,6 +112,12 @@ func TestDnsmasqSetVM_RejectsAVMWithoutReservation(t *testing.T) { } } +func TestDnsmasqConfig_CarriesTheMTU(t *testing.T) { + if c := (Dnsmasq{}).config(Subnet{VPC: "vp-s9", Bridge: "br-s9r1", MTU: 1450}); c.MTU != 1450 { + t.Errorf("mtu = %d, want 1450", c.MTU) + } +} + func TestDnsmasqConfig_ListenOnGatewayExcludesTheBridge(t *testing.T) { c := Dnsmasq{}.config(Subnet{VPC: "vp-s9", Bridge: "br-s9r1", Listen: "gw-s9r1"}) if c.Listen != "gw-s9r1" || c.Except != "br-s9r1" { diff --git a/internal/dhcpbackend/two.go b/internal/dhcpbackend/two.go index ec501e2..6c780cd 100644 --- a/internal/dhcpbackend/two.go +++ b/internal/dhcpbackend/two.go @@ -79,6 +79,7 @@ func (b Two) pushSubnet(s Subnet) error { subnet := dhcpapi.Subnet{ Network: s.Network.String(), InterfaceIP: s.InterfaceIP.String(), + MTU: s.MTU, } if s.VPCRoute != nil { subnet.VPCRoute = s.VPCRoute.String() diff --git a/internal/dhcpbackend/two_test.go b/internal/dhcpbackend/two_test.go index a63521c..21df32d 100644 --- a/internal/dhcpbackend/two_test.go +++ b/internal/dhcpbackend/two_test.go @@ -93,6 +93,18 @@ func TestTwoPushSubnet_ReachesTheStore(t *testing.T) { } } +func TestTwoPushSubnet_CarriesTheMTU(t *testing.T) { + b, s, store := twoBackend(t) + s.MTU = 1450 + + if err := b.pushSubnet(s); err != nil { + t.Fatalf("pushSubnet: %v", err) + } + if got, _ := store.Subnet(); got.MTU != 1450 { + t.Errorf("mtu = %d, want 1450", got.MTU) + } +} + func TestTwoPushSubnet_OmitsAnAbsentVPCRouteAndGateway(t *testing.T) { b, s, store := twoBackend(t) s.VPCRoute = nil diff --git a/internal/dhcpd/dhcpd.go b/internal/dhcpd/dhcpd.go index 3d1f95b..c2db3dd 100644 --- a/internal/dhcpd/dhcpd.go +++ b/internal/dhcpd/dhcpd.go @@ -19,6 +19,14 @@ type SubnetConfig struct { InterfaceIP net.IP VPCRoute *net.IPNet DefaultGateway net.IP + MTU int +} + +func (c SubnetConfig) InterfaceMTU() int { + if c.MTU == 0 { + return 1500 + } + return c.MTU } type Host struct { diff --git a/internal/dhcpd/mtu_test.go b/internal/dhcpd/mtu_test.go new file mode 100644 index 0000000..4691191 --- /dev/null +++ b/internal/dhcpd/mtu_test.go @@ -0,0 +1,68 @@ +package dhcpd + +import ( + "os" + "testing" + + "github.com/insomniacslk/dhcp/dhcpv4" +) + +func replyMTU(t *testing.T, c SubnetConfig) uint16 { + t.Helper() + h := testHost(t) + reply, err := BuildReply(c, h, request(t, dhcpv4.MessageTypeRequest, h.MAC)) + if err != nil { + t.Fatalf("BuildReply: %v", err) + } + m, err := dhcpv4.GetUint16(dhcpv4.OptionInterfaceMTU, reply.Options) + if err != nil { + t.Fatalf("option 26 absente : %v", err) + } + return m +} + +func TestBuildReply_CarriesTheInterfaceMTU(t *testing.T) { + c := testConfig(t) + c.MTU = 1450 + if got := replyMTU(t, c); got != 1450 { + t.Errorf("option 26 = %d, attendu 1450", got) + } +} + +func TestBuildReply_InterfaceMTUIs1500WhenUnset(t *testing.T) { + if got := replyMTU(t, testConfig(t)); got != 1500 { + t.Errorf("option 26 = %d, attendu 1500", got) + } +} + +func TestStore_MTUIsPersisted(t *testing.T) { + s, path := loadedStore(t) + c := fullConfig(t) + c.MTU = 1450 + if err := s.SetSubnet(c); err != nil { + t.Fatalf("SetSubnet: %v", err) + } + reloaded := NewStore(path) + if err := reloaded.Load(); err != nil { + t.Fatalf("Load: %v", err) + } + if got, _ := reloaded.Subnet(); got.MTU != 1450 { + t.Errorf("mtu relu = %d, attendu 1450", got.MTU) + } +} + +func TestStore_StateWithoutMTUIsServedAt1500(t *testing.T) { + path := statePath(t) + legacy := `{"subnet":{"network":"10.0.5.0/24","interface_ip":"10.0.5.1"},"hosts":[]}` + if err := os.WriteFile(path, []byte(legacy), 0600); err != nil { + t.Fatal(err) + } + s := NewStore(path) + if err := s.Load(); err != nil { + t.Fatalf("Load: %v", err) + } + c, _ := s.Subnet() + if got := replyMTU(t, c); got != 1500 { + t.Errorf("ancien état sans mtu : option 26 = %d, attendu 1500", got) + } +} diff --git a/internal/dhcpd/reply.go b/internal/dhcpd/reply.go index a603b41..cc340e1 100644 --- a/internal/dhcpd/reply.go +++ b/internal/dhcpd/reply.go @@ -88,6 +88,7 @@ func BuildReply(c SubnetConfig, h Host, req *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, err dhcpv4.WithOption(dhcpv4.OptServerIdentifier(c.InterfaceIP)), dhcpv4.WithOption(dhcpv4.OptDNS(DNSServers()...)), dhcpv4.WithOption(dhcpv4.OptClasslessStaticRoute(routes...)), + dhcpv4.WithOption(dhcpv4.OptGeneric(dhcpv4.OptionInterfaceMTU, dhcpv4.Uint16(c.InterfaceMTU()).ToBytes())), } if h.DefaultRoute && c.DefaultGateway != nil { mods = append(mods, dhcpv4.WithOption(dhcpv4.OptRouter(c.DefaultGateway))) diff --git a/internal/dhcpd/store.go b/internal/dhcpd/store.go index 86b756d..d8d84e0 100644 --- a/internal/dhcpd/store.go +++ b/internal/dhcpd/store.go @@ -20,6 +20,7 @@ type diskSubnet struct { InterfaceIP string `json:"interface_ip"` VPCRoute string `json:"vpc_route,omitempty"` DefaultGateway string `json:"default_gateway,omitempty"` + MTU int `json:"mtu,omitempty"` } type diskHost struct { @@ -98,7 +99,7 @@ func subnetFromDisk(d diskSubnet) (SubnetConfig, error) { return SubnetConfig{}, ErrNoInterfaceIP } - c := SubnetConfig{Network: network, InterfaceIP: interfaceIP} + c := SubnetConfig{Network: network, InterfaceIP: interfaceIP, MTU: d.MTU} if d.VPCRoute != "" { if _, c.VPCRoute, err = net.ParseCIDR(d.VPCRoute); err != nil { @@ -232,6 +233,7 @@ func (s *Store) persist() error { sub := diskSubnet{ Network: s.subnet.Network.String(), InterfaceIP: s.subnet.InterfaceIP.String(), + MTU: s.subnet.MTU, } if s.subnet.VPCRoute != nil { sub.VPCRoute = s.subnet.VPCRoute.String() diff --git a/internal/dispatcher/agent/helpers_test.go b/internal/dispatcher/agent/helpers_test.go index 2e6cbcc..d404d99 100644 --- a/internal/dispatcher/agent/helpers_test.go +++ b/internal/dispatcher/agent/helpers_test.go @@ -45,3 +45,7 @@ func (m mockCmd) Prepare(db *badger.DB, cfg *configuration.Config) error { func (m mockCmd) Execute(db *badger.DB, cfg *configuration.Config) error { return m.executeFn(db, cfg) } + +func init() { + LinkMTU = func(string) (int, error) { return 9000, nil } +} diff --git a/internal/dispatcher/agent/mtu_test.go b/internal/dispatcher/agent/mtu_test.go new file mode 100644 index 0000000..2313284 --- /dev/null +++ b/internal/dispatcher/agent/mtu_test.go @@ -0,0 +1,88 @@ +package dispatcher + +import ( + "strings" + "testing" + + "git.g3e.fr/syonad/two/pkg/db/kv" +) + +func withLinkMTU(t *testing.T, mtus map[string]int) { + t.Helper() + previous := LinkMTU + LinkMTU = func(name string) (int, error) { return mtus[name], nil } + t.Cleanup(func() { LinkMTU = previous }) +} + +func TestCreateSubnetCommand_Prepare_VxlanRefusesAnUnderlayOtherThan9000(t *testing.T) { + withLinkMTU(t, map[string]int{"br-vms": 1500, "br-default": 9000}) + _, db := newTestDispatcher(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + + cmd := CreateSubnetCommand{Name: "sn-1", VPC: "vpc-1", VxlanID: 100, IfaceType: "vms", CIDR: "10.0.0.0/24"} + err := cmd.Prepare(db, testCfg()) + if err == nil || !strings.Contains(err.Error(), "underlay br-vms has mtu 1500") { + t.Fatalf("underlay br-vms à 1500 : %v", err) + } + if _, err := kv.GetFromDB(db, "subnet/sn-1/state"); err == nil { + t.Error("aucune clé ne doit être écrite après un refus") + } + + cmd.IfaceType = "" + if err := cmd.Prepare(db, testCfg()); err != nil { + t.Errorf("default_interface à 9000 : %v", err) + } +} + +func TestCreateSubnetCommand_Prepare_VxlanUnderlayBelow9000WithTheOption(t *testing.T) { + withLinkMTU(t, map[string]int{"br-vms": 1549}) + cfg := testCfg() + cfg.Network.AllowMTUUnderlayBelow9000 = true + _, db := newTestDispatcher(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + + cmd := CreateSubnetCommand{Name: "sn-1", VPC: "vpc-1", VxlanID: 100, IfaceType: "vms", CIDR: "10.0.0.0/24"} + if err := cmd.Prepare(db, cfg); err == nil || !strings.Contains(err.Error(), "vxlan header") { + t.Fatalf("1549 pour mtu_vm 1500 : %v", err) + } + cfg.Network.MTUVM = 1499 + if err := cmd.Prepare(db, cfg); err != nil { + t.Errorf("1549 pour mtu_vm 1499 : %v", err) + } +} + +func TestCreateSubnetCommand_Prepare_BridgeChecksTheBridgeWithoutVxlanHeader(t *testing.T) { + withLinkMTU(t, map[string]int{"br-vms": 1500, "br-default": 1499}) + _, db := newTestDispatcher(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + + ok := CreateSubnetCommand{Name: "sn-1", VPC: "vpc-1", Mode: "bridge", IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24"} + if err := ok.Prepare(db, testCfg()); err != nil { + t.Errorf("bridge br-vms à 1500 : %v", err) + } + small := CreateSubnetCommand{Name: "sn-2", VPC: "vpc-1", Mode: "bridge", InterfaceIP: "10.0.1.1", CIDR: "10.0.1.0/24"} + if err := small.Prepare(db, testCfg()); err == nil || !strings.Contains(err.Error(), "bridge br-default has mtu 1499") { + t.Errorf("bridge br-default à 1499 : %v", err) + } + if _, err := kv.GetFromDB(db, "subnet/sn-2/state"); err == nil { + t.Error("aucune clé ne doit être écrite après un refus") + } +} + +func TestCreateVPCCommand_Prepare_L3VNIChecksTheUnderlay(t *testing.T) { + cfg := bgpConfig() + cfg.DefaultInterface = "br-000000" + withLinkMTU(t, map[string]int{"br-000000": 1500}) + _, db := newTestDispatcher(t) + + err := (CreateVPCCommand{Name: "vpc-1", CIDR: "10.0.0.0/16", L3VNI: 4001}).Prepare(db, cfg) + if err == nil || !strings.Contains(err.Error(), "underlay br-000000") { + t.Fatalf("underlay br-000000 à 1500 : %v", err) + } + if _, err := kv.GetFromDB(db, "vpc/vpc-1/state"); err == nil { + t.Error("aucune clé ne doit être écrite après un refus") + } + if err := (CreateVPCCommand{Name: "vpc-2", CIDR: "10.0.0.0/16"}).Prepare(db, cfg); err != nil { + t.Errorf("un VPC sans l3vni ne contrôle pas l'underlay : %v", err) + } +} diff --git a/internal/dispatcher/agent/subnet_commands.go b/internal/dispatcher/agent/subnet_commands.go index e5807ba..d97de05 100644 --- a/internal/dispatcher/agent/subnet_commands.go +++ b/internal/dispatcher/agent/subnet_commands.go @@ -63,6 +63,16 @@ func (c CreateSubnetCommand) Prepare(db *badger.DB, cfg *configuration.Config) e if !ok { localIface = cfg.DefaultInterface } + switch c.Mode { + case subnet.ModeVxlan: + if err := checkUnderlay(cfg, localIface); err != nil { + return err + } + case subnet.ModeBridge: + if err := checkBridge(cfg, localIface); err != nil { + return err + } + } state.Set(db, c.Key(), state.Creating) kv.AddInDB(db, "subnet/"+c.Name+"/vpc", c.VPC) kv.AddInDB(db, "subnet/"+c.Name+"/mode", c.Mode) diff --git a/internal/dispatcher/agent/vpc_commands.go b/internal/dispatcher/agent/vpc_commands.go index 7404342..df87004 100644 --- a/internal/dispatcher/agent/vpc_commands.go +++ b/internal/dispatcher/agent/vpc_commands.go @@ -9,6 +9,7 @@ import ( configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/l3vni" + "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/state" "git.g3e.fr/syonad/two/internal/vpc" "git.g3e.fr/syonad/two/pkg/db/kv" @@ -34,6 +35,9 @@ func (c CreateVPCCommand) Prepare(db *badger.DB, cfg *configuration.Config) erro if err := c.checkL3VNI(db, cfg); err != nil { return err } + if err := checkUnderlay(cfg, cfg.DefaultInterface); err != nil { + return err + } } if err := kv.AddInDB(db, "vpc/"+c.Name+"/cidr", c.CIDR); err != nil { return err @@ -46,6 +50,24 @@ func (c CreateVPCCommand) Prepare(db *badger.DB, cfg *configuration.Config) erro return state.Set(db, c.Key(), state.Creating) } +var LinkMTU = netif.LinkMTU + +func checkUnderlay(cfg *configuration.Config, iface string) error { + m, err := LinkMTU(iface) + if err != nil { + return fmt.Errorf("read mtu of underlay %s: %w", iface, err) + } + return cfg.Network.CheckUnderlay(iface, m) +} + +func checkBridge(cfg *configuration.Config, iface string) error { + m, err := LinkMTU(iface) + if err != nil { + return fmt.Errorf("read mtu of bridge %s: %w", iface, err) + } + return cfg.Network.CheckBridge(iface, m) +} + func (c CreateVPCCommand) checkL3VNI(db *badger.DB, cfg *configuration.Config) error { if err := l3vni.Valid(c.L3VNI); err != nil { return err diff --git a/internal/l3vni/l3.go b/internal/l3vni/l3.go index 3558274..65bd453 100644 --- a/internal/l3vni/l3.go +++ b/internal/l3vni/l3.go @@ -14,8 +14,6 @@ import ( "github.com/dgraph-io/badger/v4" ) -const l3MTU = 1500 - var ( transitHost = &net.IPNet{IP: net.IPv4(169, 254, 0, 1).To4(), Mask: net.CIDRMask(30, 32)} transitNetns = &net.IPNet{IP: net.IPv4(169, 254, 0, 2).To4(), Mask: net.CIDRMask(30, 32)} @@ -76,6 +74,7 @@ func createL3(h host, cfg *configuration.Config, v l3VPC) error { if err != nil { return fmt.Errorf("vtep: %w", err) } + mtu := cfg.Network.VM() rmac, err := RouterMAC(vtep) if err != nil { return err @@ -85,12 +84,12 @@ func createL3(h host, cfg *configuration.Config, v l3VPC) error { run func() error }{ {"create " + v.vrf(), func() error { return h.CreateVRF(v.vrf(), v.vni) }}, - {"create " + v.bridge(), func() error { return h.CreateBridge(v.bridge(), l3MTU, rmac) }}, + {"create " + v.bridge(), func() error { return h.CreateBridge(v.bridge(), mtu, rmac) }}, {"attach " + v.bridge(), func() error { return h.SetMaster(v.bridge(), v.vrf()) }}, - {"create " + v.vxlan(), func() error { return h.CreateVxlan(v.vxlan(), int(v.vni), cfg.DefaultInterface, l3MTU) }}, + {"create " + v.vxlan(), func() error { return h.CreateVxlan(v.vxlan(), int(v.vni), cfg.DefaultInterface, mtu) }}, {"attach " + v.vxlan(), func() error { return h.SetMaster(v.vxlan(), v.bridge()) }}, {"set up " + v.vxlan(), func() error { return h.LinkUp("", v.vxlan()) }}, - {"create " + v.vethHost(), func() error { return h.CreateVeth(v.vethHost(), v.vethNetns(), v.netns, l3MTU) }}, + {"create " + v.vethHost(), func() error { return h.CreateVeth(v.vethHost(), v.vethNetns(), v.netns, mtu) }}, {"attach " + v.vethHost(), func() error { return h.SetMaster(v.vethHost(), v.vrf()) }}, {"address " + v.vethHost(), func() error { return h.AddrAdd("", v.vethHost(), transitHost) }}, {"set up " + v.vethHost(), func() error { return h.LinkUp("", v.vethHost()) }}, diff --git a/internal/l3vni/l3_test.go b/internal/l3vni/l3_test.go index ee3f9bc..17e0c8c 100644 --- a/internal/l3vni/l3_test.go +++ b/internal/l3vni/l3_test.go @@ -113,18 +113,20 @@ func labL3(t *testing.T) l3VPC { func TestCreateL3FollowsTheLabRecipe(t *testing.T) { f := &fakeHost{} - if err := createL3(f, bgpConfig(), labL3(t)); err != nil { + cfg := bgpConfig() + cfg.Network.MTUVM = 1450 + if err := createL3(f, cfg, labL3(t)); err != nil { t.Fatal(err) } want := []string{ "vtep br-000000", "vrf vrf-s7 table 2700", - "bridge brl3-s7 mtu 1500 mac 02:02:c0:a8:0e:0b", + "bridge brl3-s7 mtu 1450 mac 02:02:c0:a8:0e:0b", "master brl3-s7 vrf-s7", - "vxlan vxl3-s7 id 2700 dev br-000000 mtu 1500", + "vxlan vxl3-s7 id 2700 dev br-000000 mtu 1450", "master vxl3-s7 brl3-s7", "up [] vxl3-s7", - "veth l3-s7-o peer l3-s7-i netns vp-s7 mtu 1500", + "veth l3-s7-o peer l3-s7-i netns vp-s7 mtu 1450", "master l3-s7-o vrf-s7", "addr [] l3-s7-o 169.254.0.1/30", "up [] l3-s7-o", diff --git a/internal/netif/link.go b/internal/netif/link.go index ff76352..56fdb87 100644 --- a/internal/netif/link.go +++ b/internal/netif/link.go @@ -38,3 +38,11 @@ func LinkIPv4(name string) ([]net.IP, error) { } return ips, nil } + +func LinkMTU(name string) (int, error) { + link, err := netlink.LinkByName(name) + if err != nil { + return 0, err + } + return link.Attrs().MTU, nil +} diff --git a/internal/netif/tap_linux.go b/internal/netif/tap_linux.go index 15313af..e9f7a8c 100644 --- a/internal/netif/tap_linux.go +++ b/internal/netif/tap_linux.go @@ -9,12 +9,12 @@ import ( "github.com/vishvananda/netlink" ) -func CreateTap(tapID int, bridgeName, vpcName string) error { +func CreateTap(tapID int, bridgeName, vpcName string, mtu int) error { name := fmt.Sprintf("tap%d", tapID) return netns.Call(vpcName, func() error { tap := &netlink.Tuntap{ - LinkAttrs: netlink.LinkAttrs{Name: name}, + LinkAttrs: netlink.LinkAttrs{Name: name, MTU: mtu}, Mode: netlink.TUNTAP_MODE_TAP, } if err := netlink.LinkAdd(tap); err != nil { diff --git a/internal/netif/tap_other.go b/internal/netif/tap_other.go index 18afcbe..7257f22 100644 --- a/internal/netif/tap_other.go +++ b/internal/netif/tap_other.go @@ -4,7 +4,7 @@ package netif import "errors" -func CreateTap(_ int, _, _ string) error { +func CreateTap(_ int, _, _ string, _ int) error { return errors.New("netif: tap not supported on this platform") } diff --git a/internal/qemu/args.go b/internal/qemu/args.go index 4aa7327..f97a265 100644 --- a/internal/qemu/args.go +++ b/internal/qemu/args.go @@ -102,9 +102,13 @@ func buildArgs(cfg Config) ([]string, error) { 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 { + device := fmt.Sprintf("virtio-net-pci,netdev=net%d,mac=%s,bus=pci.0,addr=0x%02x", i, n.Mac, firstNICSlot+i) + if n.MTU > 0 { + device += fmt.Sprintf(",host_mtu=%d", n.MTU) + } 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), + "-device", device, ) } diff --git a/internal/qemu/args_test.go b/internal/qemu/args_test.go index 6864994..58a91ee 100644 --- a/internal/qemu/args_test.go +++ b/internal/qemu/args_test.go @@ -17,7 +17,7 @@ func devicesOf(args []string) []string { func TestBuildArgs_DiskSerialIsDeclaredDev(t *testing.T) { args, err := buildArgs(Config{ Name: "vm1", - NICs: []NICConfig{{TapID: 1, Mac: "52:54:00:00:00:01"}}, + NICs: []NICConfig{{TapID: 1, Mac: "52:54:00:00:00:01", MTU: 1450}, {TapID: 2, Mac: "52:54:00:00:00:02"}}, Disks: []DiskConfig{ {Path: "/v/b.qcow2", Dev: "xvdb"}, {Path: "/v/root.qcow2", Dev: "vda"}, @@ -33,7 +33,8 @@ func TestBuildArgs_DiskSerialIsDeclaredDev(t *testing.T) { "virtio-blk-pci,drive=vda,bus=pci.0,addr=0x1f,bootindex=1,serial=vda", "scsi-hd,drive=xvda,bus=scsi0.0,scsi-id=0,bootindex=2,serial=xvda", "scsi-hd,drive=xvdb,bus=scsi0.0,scsi-id=1,bootindex=3,serial=xvdb", - "virtio-net-pci,netdev=net0,mac=52:54:00:00:00:01,bus=pci.0,addr=0x03", + "virtio-net-pci,netdev=net0,mac=52:54:00:00:00:01,bus=pci.0,addr=0x03,host_mtu=1450", + "virtio-net-pci,netdev=net1,mac=52:54:00:00:00:02,bus=pci.0,addr=0x04", } got := devicesOf(args) if len(got) != len(want) { diff --git a/internal/qemu/config.go b/internal/qemu/config.go index ed4f445..684223e 100644 --- a/internal/qemu/config.go +++ b/internal/qemu/config.go @@ -14,6 +14,7 @@ type DiskConfig struct { type NICConfig struct { TapID int Mac string + MTU int } type Config struct { diff --git a/internal/subnet/create.go b/internal/subnet/create.go index 3ac6f31..2a5a777 100644 --- a/internal/subnet/create.go +++ b/internal/subnet/create.go @@ -28,6 +28,7 @@ func CreateSubnet(db *badger.DB, subnetName string, cfg *configuration.Config) e if err != nil { return err } + d.mtu = cfg.Network.VM() backend, err := dhcpbackend.New(cfg) if err != nil { @@ -51,7 +52,7 @@ func createSubnet(db *badger.DB, subnetName string, d subnetData, backend dhcpba vethE := "v-" + d.subnetID + "-e" vethI := "v-" + d.subnetID + "-i" - if err := netif.CreateVethToNetns(vethE, vethI, "/var/run/netns/"+d.vpc, 1500); err != nil { + if err := netif.CreateVethToNetns(vethE, vethI, "/var/run/netns/"+d.vpc, d.mtu); err != nil { return fmt.Errorf("create veth: %w", err) } @@ -85,7 +86,7 @@ func createSubnet(db *badger.DB, subnetName string, d subnetData, backend dhcpba } if err := netns.Call(d.vpc, func() error { - if err := netif.CreateBridge(d.bridge, 1500, gatewayMAC); err != nil { + if err := netif.CreateBridge(d.bridge, d.mtu, gatewayMAC); err != nil { return fmt.Errorf("create bridge: %w", err) } return netif.BridgeSetMaster(vethI, d.bridge) @@ -144,10 +145,10 @@ func createSubnet(db *badger.DB, subnetName string, d subnetData, backend dhcpba func setupVxlanHost(d subnetData, vethE string) error { vxlanIface := fmt.Sprintf("vxlan-%d", d.vxlanID) - if err := netif.CreateBridge(d.bridge, 1500, nil); err != nil { + if err := netif.CreateBridge(d.bridge, d.mtu, nil); err != nil { return fmt.Errorf("create bridge: %w", err) } - if err := netif.CreateVxlan(vxlanIface, d.vxlanID, d.localIface, 1500); err != nil { + if err := netif.CreateVxlan(vxlanIface, d.vxlanID, d.localIface, d.mtu); err != nil { return fmt.Errorf("create vxlan: %w", err) } if err := netif.BridgeSetMaster(vethE, d.bridge); err != nil { @@ -183,5 +184,6 @@ func startDHCP(subnetName string, d subnetData, backend dhcpbackend.Backend) err InterfaceIP: d.interfaceIP, VPCRoute: vpcRoute, DefaultGateway: defaultGateway, + MTU: d.mtu, }) } diff --git a/internal/subnet/data.go b/internal/subnet/data.go index 43a5cf0..d5caaaa 100644 --- a/internal/subnet/data.go +++ b/internal/subnet/data.go @@ -23,6 +23,7 @@ type subnetData struct { vpcCIDR *net.IPNet defaultRoute bool gateway net.IP + mtu int } func loadSubnet(db *badger.DB, name string) (subnetData, error) { diff --git a/internal/vm/create.go b/internal/vm/create.go index fc2bf0c..17c709d 100644 --- a/internal/vm/create.go +++ b/internal/vm/create.go @@ -42,7 +42,7 @@ func StartVM(db *badger.DB, name string, cfg *configuration.Config) error { } for _, n := range d.nics { - if err := netif.CreateTap(n.tapID, n.bridge, n.vpcName); err != nil { + if err := netif.CreateTap(n.tapID, n.bridge, n.vpcName, cfg.Network.VM()); err != nil { return fmt.Errorf("create tap of interface %d: %w", n.index, err) } } @@ -85,7 +85,7 @@ func StartVM(db *badger.DB, name string, cfg *configuration.Config) error { qNICs := make([]qemu.NICConfig, len(d.nics)) for i, n := range d.nics { - qNICs[i] = qemu.NICConfig{TapID: n.tapID, Mac: n.mac} + qNICs[i] = qemu.NICConfig{TapID: n.tapID, Mac: n.mac, MTU: cfg.Network.VM()} } qcfg := qemu.Config{ From 43ba8ce139b28cf4fb0d0b49f4bfda279b840391 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 23 Oct 2026 12:10:08 +0200 Subject: [PATCH 8/9] =?UTF-8?q?f-56:=20e2e:=2028-mtu,=20MTU=20des=20VM=20p?= =?UTF-8?q?ar=20DHCP=20et=20QEMU=20sur=20les=20deux=20backends,=20refus=20?= =?UTF-8?q?d'un=20underlay=20qui=20n'est=20pas=20=C3=A0=209000=20#56?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- test/e2e/suite/28-mtu.sh | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 test/e2e/suite/28-mtu.sh diff --git a/test/e2e/suite/28-mtu.sh b/test/e2e/suite/28-mtu.sh new file mode 100644 index 0000000..f8e307c --- /dev/null +++ b/test/e2e/suite/28-mtu.sh @@ -0,0 +1,40 @@ +# fonctionnalité: MTU des VM (network.mtu_vm, 1500 par défaut) — annoncé par le DHCP (option 26, serveur intégré sur hv1, dnsmasq sur hv2) et par QEMU (host_mtu), porté par le tap, le bridge, le veth et le VXLAN du subnet ; subnet vxlan refusé sur un underlay qui n'est pas à 9000 +# hôtes: hv1 hv2 +# tickets: #56 + +on hv1 <<'NODE' +KEY=$(vm_key) +link_mtu () { cat "/sys/class/net/${1}/mtu"; } +check "prérequis : underlay br-000000 à 9000" test "$(link_mtu br-000000)" -eq 9000 +check "prérequis : br-lan à 1500" test "$(link_mtu br-lan)" -eq 1500 +check "VPC vp-t28" vpc_create vp-t28 10.28.0.0/16 +check "subnet vxlan sur br-lan (1500, pas 9000) refusé, 422" expect_code 422 api_post_code subnets '{"name":"sn-t28x","vpc":"vp-t28","mode":"vxlan","vxlan_id":2809,"iface_type":"lan","cidr":"10.28.9.0/24"}' +check "subnet refusé : aucune trace de sn-t28x" expect_code 404 api_code GET subnets/sn-t28x +check "subnet sn-t28 sur br-000000" subnet_create sn-t28 vp-t28 2801 10.28.1.0/24 +for iface in v-t28-e br-t28 vxlan-2801; do + check "hôte : ${iface} à 1500" test "$(link_mtu "${iface}")" -eq 1500 +done +for iface in v-t28-i br-t28 gw-t28; do + check "netns vp-t28 : ${iface} à 1500" test "$(ip netns exec vp-t28 cat "/sys/class/net/${iface}/mtu")" -eq 1500 +done +check "VM t28-m" vm_launch t28-m --nic sn-t28=10.28.1.10 --sshkey "${KEY}" +check "t28-m joignable" vm_wait vp-t28 10.28.1.10 +info "t28-m : taps du netns : $(ip -n vp-t28 -o link show | awk -F': ' '/: tap/ {print $2}' | tr '\n' ' ')" +check "netns vp-t28 : tap de t28-m à 1500" sh -c "ip -n vp-t28 -o link show | grep ': tap' | grep -q ' mtu 1500 '" +check "QEMU : host_mtu=1500 sur virtio-net-pci" sh -c "ps -eo args | grep '[q]emu.*t28-m' | grep -q 'virtio-net-pci,[^ ]*host_mtu=1500'" +check "t28-m : bail DHCP avec MTU=1500 (option 26)" test "$(vm_lease vp-t28 10.28.1.10 MTU)" = 1500 +check "t28-m : ens3 à 1500" vm_grep vp-t28 10.28.1.10 'cat /sys/class/net/ens3/mtu' '^1500$' +check "t28-m : ping de 1472 octets sans fragmentation vers la gateway" vm_ssh vp-t28 10.28.1.10 'ping -n -c 2 -W 2 -M do -s 1472 10.28.1.254' +check "t28-m : 1473 octets sans fragmentation refusés par la VM elle-même (témoin)" vm_grep vp-t28 10.28.1.10 'ping -n -c 1 -W 2 -M do -s 1473 10.28.1.254' 'too long' +NODE + +on hv2 <<'NODE' +KEY=$(vm_key) +check "hv2 : VPC vp-t28" vpc_create vp-t28 10.28.0.0/16 +check "hv2 : subnet sn-t28" subnet_create sn-t28 vp-t28 2801 10.28.1.0/24 +check "hv2 : dnsmasq annonce l'option 26" sh -c "grep -rqx 'dhcp-option=26,1500' /etc/dnsmasq.d/" +check "hv2 : VM t28-d" vm_launch t28-d --nic sn-t28=10.28.1.20 --sshkey "${KEY}" +check "t28-d joignable" vm_wait vp-t28 10.28.1.20 +check "t28-d : bail DHCP (dnsmasq) avec MTU=1500 (option 26)" test "$(vm_lease vp-t28 10.28.1.20 MTU)" = 1500 +check "t28-d : ens3 à 1500" vm_grep vp-t28 10.28.1.20 'cat /sys/class/net/ens3/mtu' '^1500$' +NODE From d9d0ab3489cc03f5c116cd5209fb5729846f40ec Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 23 Oct 2026 12:10:15 +0200 Subject: [PATCH 9/9] =?UTF-8?q?f-56:=20doc:=20MTU=20unique=20du=20cluster,?= =?UTF-8?q?=20underlay=20=C3=A0=209000,=20section=20network,=20notes=20de?= =?UTF-8?q?=20version=20#56?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: GnomeZworc --- docs/deploiement/architecture-cluster.rst | 31 ++++++++++++++++++----- docs/deploiement/routeurs.rst | 7 ++--- docs/developpement/lab.rst | 4 +++ docs/exploitation/configuration.rst | 26 +++++++++++++++++++ release_notes/0.2.0.md | 24 +++++++++++++++--- 5 files changed, 80 insertions(+), 12 deletions(-) diff --git a/docs/deploiement/architecture-cluster.rst b/docs/deploiement/architecture-cluster.rst index 841dda3..b0957b8 100644 --- a/docs/deploiement/architecture-cluster.rst +++ b/docs/deploiement/architecture-cluster.rst @@ -117,14 +117,33 @@ les fait converger. MTU --- -.. warning:: +Le MTU est une valeur **unique pour tout le cluster** : toutes les VM, et tous les bridges, veth, +taps et interfaces VXLAN que l'agent crée, sont au MTU des VM, ``network.mtu_vm`` (1500 par +défaut, cf. :doc:`/exploitation/configuration`). Il doit être identique sur tous les +hyperviseurs : un subnet est un seul domaine L2 qui s'étend sur plusieurs hôtes, et un élément à +un MTU plus petit que les autres jette les trames en silence — un bridge ne fragmente pas et +n'émet aucun ICMP. Le symptôme est trompeur : le ping passe, les petites requêtes passent, les +transferts volumineux et les poignées de main TLS échouent. - L'agent crée bridges, veth et interfaces VXLAN avec un **MTU figé à 1500**. VXLAN ajoute 50 - octets d'encapsulation : le réseau qui relie les hyperviseurs doit donc accepter au moins - **1550 octets** de MTU, sinon les paquets pleine taille des VM sont perdus. +L'underlay, le réseau qui relie les hyperviseurs et porte le VXLAN, est attendu à **exactement +9000**. VXLAN ajoute 50 octets d'encapsulation ; 9000 laisse donc toute la marge à des VM à 1500. +L'agent refuse de créer un subnet ``vxlan`` (ou un VPC avec ``l3vni``) dont l'interface n'est +pas à 9000, sauf si ``network.allow_mtu_underlay_below_9000`` l'y autorise ; même alors, +l'underlay doit faire au moins ``network.mtu_vm`` + 50. Un underlay à 1500 impose donc des VM à +1450 au plus, et l'option ``network.allow_mtu_vm_below_1500``. - Le symptôme est trompeur : le ping passe, les petites requêtes passent, les transferts - volumineux et les poignées de main TLS échouent. +Le MTU est annoncé aux VM par deux voies : l'option DHCP 26 et ``host_mtu`` sur leur interface +virtio. Une image dont le client DHCP ignore l'option 26 s'aligne quand même. + +.. note:: + + **VM en mode bridge sur un bridge à 9000.** Un subnet ``bridge`` rattaché à ``br-000000`` + met ses VM, à 1500, sur un segment L2 à 9000 avec l'hôte et tout ce qui s'y trouve. Le + routage vers les autres subnets reste correct — un routeur renvoie un « fragmentation + needed » plutôt que de perdre en silence —, mais l'interface du routeur qui sert de gateway + à ce segment doit être à 1500 : sinon elle peut envoyer à la VM des trames plus grandes + qu'elle n'accepte. En TCP, le MSS annoncé par la VM protège l'échange ; en UDP ou en ICMP, + les gros paquets venant d'un équipement à 9000 du même segment sont perdus. Hyperviseurs sans état ---------------------- diff --git a/docs/deploiement/routeurs.rst b/docs/deploiement/routeurs.rst index fd2668a..78337ea 100644 --- a/docs/deploiement/routeurs.rst +++ b/docs/deploiement/routeurs.rst @@ -88,9 +88,10 @@ Indépendamment des choix d'équipement, deux contraintes viennent de ce que fai .. warning:: - **MTU** — l'agent crée bridges, veth et interfaces VXLAN avec un MTU figé à 1500, et VXLAN - ajoute 50 octets d'encapsulation. Les liens entre hyperviseurs doivent donc accepter au moins - **1550 octets**. Cf. :doc:`architecture-cluster`. + **MTU** — l'underlay est attendu à **9000** : l'agent refuse un subnet ``vxlan`` sur une + interface à un autre MTU, sauf option, et les VM sont à 1500 plus 50 octets d'encapsulation. + L'interface d'un routeur qui sert de gateway à un segment de VM doit être au MTU des VM + (1500). Cf. :doc:`architecture-cluster`. .. warning:: diff --git a/docs/developpement/lab.rst b/docs/developpement/lab.rst index 659ea24..95b7bae 100644 --- a/docs/developpement/lab.rst +++ b/docs/developpement/lab.rst @@ -327,6 +327,10 @@ Générée par ``test/e2e/run.sh --matrice`` à partir des en-têtes ; à régé - redémarrage d'une VM depuis l'invité — même processus QEMU, même adresse, nouveau bail, user_data non rejoué - hv1 - #46 + * - ``28-mtu`` + - MTU des VM (``network.mtu_vm``, 1500) — option DHCP 26 (serveur intégré et dnsmasq), ``host_mtu`` de QEMU, tap, bridge, veth et VXLAN du subnet ; subnet vxlan refusé sur un underlay qui n'est pas à 9000 + - hv1 hv2 + - #56 * - ``31-gateway`` - gateway d'un subnet vxlan — gateway anycast et adresse d'émission calculées, default_route et gateway explicite, routes DHCP, macvlan gw-, FDB locale, sysctls ARP, règles de confinement, suppression et recréation - hv1 diff --git a/docs/exploitation/configuration.rst b/docs/exploitation/configuration.rst index d4bf8eb..4d67e98 100644 --- a/docs/exploitation/configuration.rst +++ b/docs/exploitation/configuration.rst @@ -104,6 +104,32 @@ Traduit les clés logiques ``iface_type`` de l'API vers les bridges physiques de inconnue ou omise retombe silencieusement sur ``default_interface`` — ce n'est pas une erreur, mais c'est une source de subnets branchés au mauvais endroit sans le dire. +MTU +--- + +.. code-block:: yaml + + network: + mtu_vm: 1500 + allow_mtu_vm_below_1500: false + allow_mtu_underlay_below_9000: false + +* ``mtu_vm`` — le MTU de toutes les VM, et de tous les bridges, veth, taps et interfaces VXLAN + que l'agent crée. Il est annoncé aux VM par l'option DHCP 26 et par ``host_mtu``. **Il doit + être identique sur tous les hyperviseurs.** 1500 au plus ; en dessous, seulement avec + ``allow_mtu_vm_below_1500``, et jamais sous 1280. Une valeur hors de ces bornes fait échouer + le démarrage de l'agent. +* ``allow_mtu_underlay_below_9000`` — l'underlay est attendu à exactement 9000. Sans cette + option, un subnet ``vxlan`` dont l'interface (celle de ``iface_type``, ou + ``default_interface``) n'est pas à 9000 est refusé (422), comme un VPC avec ``l3vni`` si + ``default_interface`` ne l'est pas (409). Dans tous les cas, l'underlay doit faire au moins + ``mtu_vm`` + 50 (en-tête VXLAN). + +Un subnet ``bridge`` est refusé (422) si son bridge est sous ``mtu_vm`` ; il n'y a pas +d'encapsulation, donc pas de marge à prévoir. Les interfaces sont créées au MTU en vigueur à la +création du subnet : changer ``mtu_vm`` ne modifie pas les subnets existants, il faut les +recréer. + Plan de contrôle BGP -------------------- diff --git a/release_notes/0.2.0.md b/release_notes/0.2.0.md index 77c0798..4003d31 100644 --- a/release_notes/0.2.0.md +++ b/release_notes/0.2.0.md @@ -99,6 +99,20 @@ L3VNI, avec une configuration BGP pilotée par l'agent ; documentation du projet `/dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_xvdX` - Migration au démarrage : les clés `vm//disk/sdX` deviennent `vm//disk/xvdX` +**MTU unique du cluster (#56)** + +- Nouvelle section `network` de la configuration de l'agent. `mtu_vm` (1500 par défaut, 1500 au + plus) fixe le MTU de toutes les VM et de tous les bridges, veth, taps et interfaces VXLAN que + l'agent crée, jusque-là figé à 1500. Il doit être identique sur tous les hyperviseurs. Sous + 1500, il faut `allow_mtu_vm_below_1500`, et jamais sous 1280 ; une valeur hors bornes fait + échouer le démarrage +- Le MTU est annoncé aux VM par l'option DHCP 26 (serveur intégré et dnsmasq) et par `host_mtu` + sur leur interface virtio. `probe` l'affiche +- L'underlay est attendu à exactement 9000 : un subnet `vxlan` dont l'interface n'y est pas est + refusé (422), comme un VPC avec `l3vni` si `default_interface` n'y est pas (409), sauf avec + `allow_mtu_underlay_below_9000`. Dans tous les cas l'underlay doit porter `mtu_vm` + 50 octets + d'en-tête VXLAN. Un subnet `bridge` est refusé si son bridge est sous `mtu_vm` + **Exploitation** - Le watchdog contrôle aussi, avec une section `bgp` : les sessions vers les route reflectors ; @@ -149,8 +163,7 @@ L3VNI, avec une configuration BGP pilotée par l'agent ; documentation du projet Celles de la 0.1.0 restent valables, sauf mention contraire ci-dessus. S'y ajoutent : -- **L3VNI** : pas de migration à chaud ; la gateway anycast (#57) la prépare côté réseau. MTU - 1500 de bout en bout (#56). Le transit `169.254.0.0/30` étant identique sur tous les hôtes, les ICMP des sauts distants sont +- **L3VNI** : pas de migration à chaud ; la gateway anycast (#57) la prépare côté réseau. Le transit `169.254.0.0/30` étant identique sur tous les hôtes, les ICMP des sauts distants sont rejetés comme « martiens » (traceroute partiel) - Avec une section `bgp`, l'agent ne démarre pas sans FRR et `agent.service` ne le relance pas : au démarrage, l'ordre est migration réseau, puis FRR, puis l'agent (#52) @@ -176,7 +189,7 @@ bash ./deploy.sh -t 0.2.0 ``` Sans `dhcp.backend` ni `bgp` dans `/etc/two/agent.yml`, le comportement est celui de la 0.1.0, à -quatre exceptions près, qui touchent les appelants de l'API : +cinq exceptions près ; les quatre premières touchent les appelants de l'API : - **`interface_ip` ne se fournit plus pour un subnet `vxlan`** : il est refusé (400), l'agent le calcule. Le retirer des appels de création, et ne plus placer de VM sur les deux dernières @@ -187,6 +200,11 @@ quatre exceptions près, qui touchent les appelants de l'API : - **les disques additionnels s'appellent `xvdX`** : `sdX` est refusé (400). Les VM existantes sont migrées ; leurs disques prennent le numéro de série `xvdX` au prochain lancement, et une image qui les montait par `/dev/sdY` doit passer à `/dev/xvdX` +- **l'underlay doit être à 9000** : sur un hyperviseur dont `default_interface` (ou l'interface + d'un `iface_type`) est à un autre MTU, la création d'un subnet `vxlan` est refusée. Passer + l'underlay à 9000, ou poser `network.allow_mtu_underlay_below_9000: true` — sous 1550, il faut + aussi abaisser `network.mtu_vm` avec `allow_mtu_vm_below_1500`. Les subnets existants gardent + leurs interfaces à 1500 jusqu'à leur recréation Les subnets `vxlan` existants gardent leur adressage et le modèle précédent (gateway sur le bridge) jusqu'à leur recréation.