diff --git a/api/agent.yaml b/api/agent.yaml index 03aad15..04502fd 100644 --- a/api/agent.yaml +++ b/api/agent.yaml @@ -566,15 +566,8 @@ components: example: /var/lib/two/volumes/abc.qcow2 dev: type: string - description: >- - 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])$' + description: Device name inside the VM + pattern: '^[sv]d[a-z]$' example: vda VM: diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 548316e..98b8e3d 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -68,11 +68,6 @@ 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/conf/agent/config.exemple.yml b/conf/agent/config.exemple.yml index 19a09f9..a31a58d 100644 --- a/conf/agent/config.exemple.yml +++ b/conf/agent/config.exemple.yml @@ -35,18 +35,6 @@ 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/docs/architecture/contraintes.rst b/docs/architecture/contraintes.rst index 42e8de2..c83fec6 100644 --- a/docs/architecture/contraintes.rst +++ b/docs/architecture/contraintes.rst @@ -39,8 +39,7 @@ Réseau QEMU et VM ---------- -* **Un seul disque virtio, ``vda``, le disque racine** ; les disques additionnels passent par le SCSI - (``xvdX``, cible X). La +* **Un seul disque ``vdX`` par VM** ; les disques additionnels passent par le SCSI (``sdX``). 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 431b92b..c8c9af4 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 : vda, xvda, xvdb, …) + vm//disk/ → (une clé par disque : sda, vda, …) vm//memory → (Mo) vm//cpus → vm//uefi → "true" (absent si SeaBIOS) @@ -55,12 +55,6 @@ 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 ca9ebcc..8dcf2b7 100644 --- a/docs/concepts/vpc-subnet-vm.rst +++ b/docs/concepts/vpc-subnet-vm.rst @@ -94,12 +94,9 @@ 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 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/…``. +**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`. Ce qui est stocké, et où ------------------------ diff --git a/docs/demarrage/premier-vpc.rst b/docs/demarrage/premier-vpc.rst index 567b5bc..562978f 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"}]}' -Six points qui coûtent du temps quand on les découvre en production : +Quatre 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 @@ -115,17 +115,10 @@ 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. -``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 +Un seul disque ``vdX`` + Les disques supplémentaires passent par ``sdX``. La carte PCI en dépend — voir :doc:`/architecture/contraintes`. -``/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/architecture-cluster.rst b/docs/deploiement/architecture-cluster.rst index b0957b8..841dda3 100644 --- a/docs/deploiement/architecture-cluster.rst +++ b/docs/deploiement/architecture-cluster.rst @@ -117,33 +117,14 @@ les fait converger. MTU --- -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. +.. warning:: -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``. + 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. -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. + Le symptôme est trompeur : le ping passe, les petites requêtes passent, les transferts + volumineux et les poignées de main TLS échouent. Hyperviseurs sans état ---------------------- diff --git a/docs/deploiement/image-qcow2.rst b/docs/deploiement/image-qcow2.rst index 5922a47..a8e0488 100644 --- a/docs/deploiement/image-qcow2.rst +++ b/docs/deploiement/image-qcow2.rst @@ -284,21 +284,6 @@ 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/deploiement/routeurs.rst b/docs/deploiement/routeurs.rst index 78337ea..fd2668a 100644 --- a/docs/deploiement/routeurs.rst +++ b/docs/deploiement/routeurs.rst @@ -88,10 +88,9 @@ Indépendamment des choix d'équipement, deux contraintes viennent de ce que fai .. warning:: - **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`. + **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`. .. warning:: diff --git a/docs/developpement/lab.rst b/docs/developpement/lab.rst index 95b7bae..3a7b599 100644 --- a/docs/developpement/lab.rst +++ b/docs/developpement/lab.rst @@ -320,17 +320,13 @@ 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 — 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 + - VM à plusieurs disques — virtio (vdX) et SCSI (sdX), tailles et bus vus par la VM, démarrage sur vda - hv1 - - #32, #74 + - #32 * - ``27-reboot`` - 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 @@ -416,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 racine, ``vda``) ; les autres sont des ``xvdX`` ; +* l'agent n'accepte **qu'un seul disque virtio** (le disque système) ; les autres sont des ``sdX`` ; * 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/docs/exploitation/configuration.rst b/docs/exploitation/configuration.rst index 4d67e98..d4bf8eb 100644 --- a/docs/exploitation/configuration.rst +++ b/docs/exploitation/configuration.rst @@ -104,32 +104,6 @@ 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/internal/api/agent/helpers_test.go b/internal/api/agent/helpers_test.go index d3808ce..69adfb2 100644 --- a/internal/api/agent/helpers_test.go +++ b/internal/api/agent/helpers_test.go @@ -29,7 +29,3 @@ 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/agent/vm_test.go b/internal/api/agent/vm_test.go index e2ff820..7412d38 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/xvda": "/data/root.qcow2", + "vm/vm-1/disk/sda": "/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 != "xvda" || vm.Storage[0].Path != "/data/root.qcow2" { + if vm.Storage[0].Dev != "sda" || 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/xvda": "/data/root.qcow2", - "vm/vm-2/disk/xvdb": "/data/data.qcow2", + "vm/vm-2/disk/sda": "/data/root.qcow2", + "vm/vm-2/disk/sdb": "/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 != "xvda" || vm.Storage[1].Dev != "xvdb" { - t.Errorf("devs attendus [xvda xvdb], obtenus [%s %s]", vm.Storage[0].Dev, vm.Storage[1].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) } } func TestVmFromDB_SlotGap(t *testing.T) { - // xvdb absent — xvda et xvdc seulement + // sdb absent — sda et sdc 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/xvda": "/data/root.qcow2", - "vm/vm-3/disk/xvdc": "/data/extra.qcow2", + "vm/vm-3/disk/sda": "/data/root.qcow2", + "vm/vm-3/disk/sdc": "/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["xvda"] || !devs["xvdc"] { - t.Errorf("attendu xvda et xvdc, obtenus %v", devs) + if !devs["sda"] || !devs["sdc"] { + t.Errorf("attendu sda et sdc, obtenus %v", devs) } - if devs["xvdb"] { - t.Error("xvdb ne devrait pas apparaître") + if devs["sdb"] { + t.Error("sdb 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: "vda"}, - {Path: "/data/data.qcow2", Dev: "xvda"}, + {Path: "/data/root.qcow2", Dev: "sda"}, + {Path: "/data/data.qcow2", Dev: "sdb"}, }, 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{"vda", "xvda"} { + for _, dev := range []string{"sda", "sdb"} { 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: "xvda"}, + {Path: "/data/root.qcow2", Dev: "sda"}, }, }) @@ -157,38 +157,11 @@ 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 != "xvda" || vm.Storage[0].Path != "/data/root.qcow2" { + if vm.Storage[0].Dev != "sda" || 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 03b617f..d5ca436 100644 --- a/internal/api/agent/vms.go +++ b/internal/api/agent/vms.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "net/http" - "regexp" "strings" dispatcher "git.g3e.fr/syonad/two/internal/dispatcher/agent" @@ -13,8 +12,6 @@ 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 { @@ -91,11 +88,6 @@ 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/api/dhcp/convert.go b/internal/api/dhcp/convert.go index 88d3c2f..77dd7c4 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, MTU: s.MTU} + c := dhcpd.SubnetConfig{Network: network, InterfaceIP: interfaceIP} if s.VPCRoute != "" { if _, c.VPCRoute, err = net.ParseCIDR(s.VPCRoute); err != nil { @@ -48,7 +48,6 @@ 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 4cc0c25..f311b22 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, MTU: s.MTU} + out := Subnet{Network: network, InterfaceIP: interfaceIP} 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 7fc3933..d454194 100644 --- a/internal/api/dhcp/models.go +++ b/internal/api/dhcp/models.go @@ -17,7 +17,6 @@ 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 { @@ -39,7 +38,6 @@ 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 deleted file mode 100644 index 5131f08..0000000 --- a/internal/api/dhcp/mtu_test.go +++ /dev/null @@ -1,44 +0,0 @@ -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 7ec50d4..879ac58 100644 --- a/internal/api/dhcp/server.go +++ b/internal/api/dhcp/server.go @@ -186,8 +186,5 @@ 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 deleted file mode 100644 index 7ee02e0..0000000 --- a/internal/config/agent/network.go +++ /dev/null @@ -1,52 +0,0 @@ -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 deleted file mode 100644 index 6c475dd..0000000 --- a/internal/config/agent/network_test.go +++ /dev/null @@ -1,98 +0,0 @@ -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 86a6fd7..17ddd43 100644 --- a/internal/config/agent/struct.go +++ b/internal/config/agent/struct.go @@ -55,7 +55,6 @@ 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"` @@ -91,9 +90,6 @@ 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) @@ -103,9 +99,6 @@ 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 ccd39b3..6724b62 100644 --- a/internal/dhcp/generate.go +++ b/internal/dhcp/generate.go @@ -31,7 +31,6 @@ 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)) @@ -45,13 +44,6 @@ 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 deleted file mode 100644 index e4ea54f..0000000 --- a/internal/dhcp/mtu_test.go +++ /dev/null @@ -1,20 +0,0 @@ -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 1d8ca11..44d51a7 100644 --- a/internal/dhcp/struct.go +++ b/internal/dhcp/struct.go @@ -15,5 +15,4 @@ type Config struct { ConfDir string Listen string Except string - MTU int } diff --git a/internal/dhcpbackend/backend.go b/internal/dhcpbackend/backend.go index cfdf47c..9d61510 100644 --- a/internal/dhcpbackend/backend.go +++ b/internal/dhcpbackend/backend.go @@ -16,7 +16,6 @@ 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 c21df2e..e6ac72b 100644 --- a/internal/dhcpbackend/dnsmasq.go +++ b/internal/dhcpbackend/dnsmasq.go @@ -35,7 +35,6 @@ 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 d83a506..4f2a69a 100644 --- a/internal/dhcpbackend/dnsmasq_test.go +++ b/internal/dhcpbackend/dnsmasq_test.go @@ -112,12 +112,6 @@ 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 6c780cd..ec501e2 100644 --- a/internal/dhcpbackend/two.go +++ b/internal/dhcpbackend/two.go @@ -79,7 +79,6 @@ 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 21df32d..a63521c 100644 --- a/internal/dhcpbackend/two_test.go +++ b/internal/dhcpbackend/two_test.go @@ -93,18 +93,6 @@ 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 c2db3dd..3d1f95b 100644 --- a/internal/dhcpd/dhcpd.go +++ b/internal/dhcpd/dhcpd.go @@ -19,14 +19,6 @@ 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 deleted file mode 100644 index 4691191..0000000 --- a/internal/dhcpd/mtu_test.go +++ /dev/null @@ -1,68 +0,0 @@ -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 cc340e1..a603b41 100644 --- a/internal/dhcpd/reply.go +++ b/internal/dhcpd/reply.go @@ -88,7 +88,6 @@ 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 d8d84e0..86b756d 100644 --- a/internal/dhcpd/store.go +++ b/internal/dhcpd/store.go @@ -20,7 +20,6 @@ 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 { @@ -99,7 +98,7 @@ func subnetFromDisk(d diskSubnet) (SubnetConfig, error) { return SubnetConfig{}, ErrNoInterfaceIP } - c := SubnetConfig{Network: network, InterfaceIP: interfaceIP, MTU: d.MTU} + c := SubnetConfig{Network: network, InterfaceIP: interfaceIP} if d.VPCRoute != "" { if _, c.VPCRoute, err = net.ParseCIDR(d.VPCRoute); err != nil { @@ -233,7 +232,6 @@ 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 d404d99..2e6cbcc 100644 --- a/internal/dispatcher/agent/helpers_test.go +++ b/internal/dispatcher/agent/helpers_test.go @@ -45,7 +45,3 @@ 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 deleted file mode 100644 index 2313284..0000000 --- a/internal/dispatcher/agent/mtu_test.go +++ /dev/null @@ -1,88 +0,0 @@ -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 d97de05..e5807ba 100644 --- a/internal/dispatcher/agent/subnet_commands.go +++ b/internal/dispatcher/agent/subnet_commands.go @@ -63,16 +63,6 @@ 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 df87004..7404342 100644 --- a/internal/dispatcher/agent/vpc_commands.go +++ b/internal/dispatcher/agent/vpc_commands.go @@ -9,7 +9,6 @@ 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" @@ -35,9 +34,6 @@ 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 @@ -50,24 +46,6 @@ 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 65bd453..3558274 100644 --- a/internal/l3vni/l3.go +++ b/internal/l3vni/l3.go @@ -14,6 +14,8 @@ 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)} @@ -74,7 +76,6 @@ 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 @@ -84,12 +85,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(), mtu, rmac) }}, + {"create " + v.bridge(), func() error { return h.CreateBridge(v.bridge(), l3MTU, 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, mtu) }}, + {"create " + v.vxlan(), func() error { return h.CreateVxlan(v.vxlan(), int(v.vni), cfg.DefaultInterface, l3MTU) }}, {"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, mtu) }}, + {"create " + v.vethHost(), func() error { return h.CreateVeth(v.vethHost(), v.vethNetns(), v.netns, l3MTU) }}, {"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 17e0c8c..ee3f9bc 100644 --- a/internal/l3vni/l3_test.go +++ b/internal/l3vni/l3_test.go @@ -113,20 +113,18 @@ func labL3(t *testing.T) l3VPC { func TestCreateL3FollowsTheLabRecipe(t *testing.T) { f := &fakeHost{} - cfg := bgpConfig() - cfg.Network.MTUVM = 1450 - if err := createL3(f, cfg, labL3(t)); err != nil { + if err := createL3(f, bgpConfig(), labL3(t)); err != nil { t.Fatal(err) } want := []string{ "vtep br-000000", "vrf vrf-s7 table 2700", - "bridge brl3-s7 mtu 1450 mac 02:02:c0:a8:0e:0b", + "bridge brl3-s7 mtu 1500 mac 02:02:c0:a8:0e:0b", "master brl3-s7 vrf-s7", - "vxlan vxl3-s7 id 2700 dev br-000000 mtu 1450", + "vxlan vxl3-s7 id 2700 dev br-000000 mtu 1500", "master vxl3-s7 brl3-s7", "up [] vxl3-s7", - "veth l3-s7-o peer l3-s7-i netns vp-s7 mtu 1450", + "veth l3-s7-o peer l3-s7-i netns vp-s7 mtu 1500", "master l3-s7-o vrf-s7", "addr [] l3-s7-o 169.254.0.1/30", "up [] l3-s7-o", diff --git a/internal/migration/disk.go b/internal/migration/disk.go deleted file mode 100644 index a1eb722..0000000 --- a/internal/migration/disk.go +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 6529964..0000000 --- a/internal/migration/disk_test.go +++ /dev/null @@ -1,80 +0,0 @@ -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/netif/link.go b/internal/netif/link.go index 56fdb87..ff76352 100644 --- a/internal/netif/link.go +++ b/internal/netif/link.go @@ -38,11 +38,3 @@ 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 e9f7a8c..15313af 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, mtu int) error { +func CreateTap(tapID int, bridgeName, vpcName string) error { name := fmt.Sprintf("tap%d", tapID) return netns.Call(vpcName, func() error { tap := &netlink.Tuntap{ - LinkAttrs: netlink.LinkAttrs{Name: name, MTU: mtu}, + LinkAttrs: netlink.LinkAttrs{Name: name}, 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 7257f22..18afcbe 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, _ int) error { +func CreateTap(_ int, _, _ string) error { return errors.New("netif: tap not supported on this platform") } diff --git a/internal/qemu/args.go b/internal/qemu/args.go deleted file mode 100644 index f97a265..0000000 --- a/internal/qemu/args.go +++ /dev/null @@ -1,116 +0,0 @@ -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, "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 xvd* 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 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") - 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, "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), - ) - } 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 { - 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", device, - ) - } - - return append(args, "-daemonize"), nil -} diff --git a/internal/qemu/args_test.go b/internal/qemu/args_test.go deleted file mode 100644 index 58a91ee..0000000 --- a/internal/qemu/args_test.go +++ /dev/null @@ -1,76 +0,0 @@ -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", 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"}, - {Path: "/v/a.qcow2", Dev: "xvda"}, - }, - }) - 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=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,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) { - 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/config.go b/internal/qemu/config.go index 684223e..ed4f445 100644 --- a/internal/qemu/config.go +++ b/internal/qemu/config.go @@ -14,7 +14,6 @@ type DiskConfig struct { type NICConfig struct { TapID int Mac string - MTU int } type Config struct { diff --git a/internal/qemu/start_linux.go b/internal/qemu/start_linux.go index 4316180..1a8f918 100644 --- a/internal/qemu/start_linux.go +++ b/internal/qemu/start_linux.go @@ -6,10 +6,28 @@ 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 { @@ -18,11 +36,92 @@ func Start(cfg Config) error { } } - args, err := buildArgs(cfg) - if err != nil { - return err + 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 fmt.Errorf("qemu: %d disques virtio-blk (vd*) déclarés, un seul est supporté — utiliser des disques sd* pour les disques additionnels", virtioBlk) + } + if hasScsi { + args = append(args, "-device", "virtio-scsi-pci,id=scsi0,bus=pci.0,addr=0x1e") + } + + sorted := make([]DiskConfig, len(cfg.Disks)) + copy(sorted, cfg.Disks) + // vd* avant sd* : les disques virtio-blk bootent en premier. + // À lettre égale de type, ordre alphabétique. + sort.Slice(sorted, func(i, j int) bool { + iVirtio := strings.HasPrefix(sorted[i].Dev, "vd") + jVirtio := strings.HasPrefix(sorted[j].Dev, "vd") + if iVirtio != jVirtio { + return iVirtio + } + return sorted[i].Dev < sorted[j].Dev + }) + + for idx, d := range sorted { + bootindex := idx + 1 + if strings.HasPrefix(d.Dev, "sd") { + scsiID := int(d.Dev[2] - 'a') + args = append(args, + "-drive", fmt.Sprintf("file=%s,if=none,id=%s", d.Path, d.Dev), + "-device", fmt.Sprintf("scsi-hd,drive=%s,bus=scsi0.0,scsi-id=%d,bootindex=%d", d.Dev, scsiID, bootindex), + ) + } else { + args = append(args, + "-drive", fmt.Sprintf("file=%s,if=none,id=%s", d.Path, d.Dev), + "-device", fmt.Sprintf("virtio-blk-pci,drive=%s,bus=pci.0,addr=0x1f,bootindex=%d", d.Dev, bootindex), + ) + } + } + + // Slots 0x03 à 0x1d réservés au réseau par la carte PCI (#36). Le slot est + // dérivé de l'index et non laissé à QEMU : c'est lui qui fixe le nom de + // l'interface dans le guest, et un slot flottant la renomme d'un démarrage + // à l'autre. + if len(cfg.NICs) == 0 { + return fmt.Errorf("vm %s has no network interface", cfg.Name) + } + if len(cfg.NICs) > maxNICs { + return fmt.Errorf("vm %s has %d interfaces, the pci map holds %d", cfg.Name, len(cfg.NICs), maxNICs) + } + for i, n := range cfg.NICs { + args = append(args, + "-netdev", fmt.Sprintf("tap,id=net%d,ifname=tap%d,script=no,downscript=no", i, n.TapID), + "-device", fmt.Sprintf("virtio-net-pci,netdev=net%d,mac=%s,bus=pci.0,addr=0x%02x", i, n.Mac, firstNICSlot+i), + ) + } + + args = append(args, "-daemonize") + scopeArgs := append([]string{ "--scope", "--unit=" + ScopeName(cfg.Name), diff --git a/internal/subnet/create.go b/internal/subnet/create.go index 2a5a777..3ac6f31 100644 --- a/internal/subnet/create.go +++ b/internal/subnet/create.go @@ -28,7 +28,6 @@ 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 { @@ -52,7 +51,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, d.mtu); err != nil { + if err := netif.CreateVethToNetns(vethE, vethI, "/var/run/netns/"+d.vpc, 1500); err != nil { return fmt.Errorf("create veth: %w", err) } @@ -86,7 +85,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, d.mtu, gatewayMAC); err != nil { + if err := netif.CreateBridge(d.bridge, 1500, gatewayMAC); err != nil { return fmt.Errorf("create bridge: %w", err) } return netif.BridgeSetMaster(vethI, d.bridge) @@ -145,10 +144,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, d.mtu, nil); err != nil { + if err := netif.CreateBridge(d.bridge, 1500, nil); err != nil { return fmt.Errorf("create bridge: %w", err) } - if err := netif.CreateVxlan(vxlanIface, d.vxlanID, d.localIface, d.mtu); err != nil { + if err := netif.CreateVxlan(vxlanIface, d.vxlanID, d.localIface, 1500); err != nil { return fmt.Errorf("create vxlan: %w", err) } if err := netif.BridgeSetMaster(vethE, d.bridge); err != nil { @@ -184,6 +183,5 @@ 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 d5caaaa..43a5cf0 100644 --- a/internal/subnet/data.go +++ b/internal/subnet/data.go @@ -23,7 +23,6 @@ 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 17c709d..fc2bf0c 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, cfg.Network.VM()); err != nil { + if err := netif.CreateTap(n.tapID, n.bridge, n.vpcName); 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, MTU: cfg.Network.VM()} + qNICs[i] = qemu.NICConfig{TapID: n.tapID, Mac: n.mac} } qcfg := qemu.Config{ diff --git a/release_notes/0.2.0.md b/release_notes/0.2.0.md index 4003d31..001f589 100644 --- a/release_notes/0.2.0.md +++ b/release_notes/0.2.0.md @@ -87,32 +87,6 @@ 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` - -**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 ; @@ -163,7 +137,8 @@ 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. 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. 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 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) @@ -189,7 +164,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, à -cinq exceptions près ; les quatre premières touchent les appelants de l'API : +trois 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 @@ -197,14 +172,6 @@ cinq exceptions près ; les quatre premières 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` -- **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. diff --git a/test/e2e/lib/vm.sh b/test/e2e/lib/vm.sh index 4c02d60..b72a7e1 100644 --- a/test/e2e/lib/vm.sh +++ b/test/e2e/lib/vm.sh @@ -15,10 +15,6 @@ 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 9cd27a8..186424a 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==\"}" 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')" + [[ $(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')" 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 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}' ]] \ + 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}' ]] \ || 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 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}" + 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}" [[ $(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 b8f89ad..3b63c60 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, #74 +# tickets: #41, #57, #33, #62 on hv1 <<'NODE' check "VPC vp-t11a, l3vni 1100 (témoin)" vpc_create vp-t11a 10.11.0.0/16 1100 @@ -40,9 +40,6 @@ 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 66902ac..4e563f7 100644 --- a/test/e2e/suite/26-multi-disque.sh +++ b/test/e2e/suite/26-multi-disque.sh @@ -1,32 +1,27 @@ -# 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 +# fonctionnalité: VM à plusieurs disques — virtio (vdX) et SCSI (sdX), tailles et bus vus par la VM, démarrage sur vda # hôtes: hv1 -# tickets: #32, #74 +# tickets: #32 on hv1 <<'NODE' KEY=$(vm_key) mkdir -p "${VOLUMES}" -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 "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 "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 (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 "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 "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 : 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' ' ')" -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 : 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 +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' -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' +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' NODE diff --git a/test/e2e/suite/28-mtu.sh b/test/e2e/suite/28-mtu.sh deleted file mode 100644 index f8e307c..0000000 --- a/test/e2e/suite/28-mtu.sh +++ /dev/null @@ -1,40 +0,0 @@ -# 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