diff --git a/README.md b/README.md index 20627f4..9382e13 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ curl -X POST http://127.0.0.1:8080/vpcs \ # Un subnet en VXLAN dans ce VPC curl -X POST http://127.0.0.1:8080/subnets \ -d '{"name": "sn-000001", "vpc": "vp-admin", "mode": "vxlan", "vxlan_id": 1, - "iface_type": "vms", "interface_ip": "10.1.1.1", "cidr": "10.1.0.0/23"}' + "iface_type": "vms", "cidr": "10.1.0.0/23"}' # Une VM, avec une clé SSH et un user-data cloud-init en base64 curl -X POST http://127.0.0.1:8080/vms \ diff --git a/docs/architecture/stockage.rst b/docs/architecture/stockage.rst index 6da14d4..fcea89b 100644 --- a/docs/architecture/stockage.rst +++ b/docs/architecture/stockage.rst @@ -15,7 +15,8 @@ de sérialisation structurée. subnet//mode → vxlan | bridge | public_ip subnet//vxlan_id → (mode vxlan uniquement) subnet//cidr → - subnet//interface_ip → (gateway, portée par br-) + subnet//interface_ip → (gateway ; calculée en vxlan : broadcast-1) + subnet//relay_ip → (mode vxlan, calculée : broadcast-2) subnet//local_iface → subnet//default_route → "true" | "false" subnet//gateway → (optionnel) diff --git a/docs/demarrage/premier-vpc.rst b/docs/demarrage/premier-vpc.rst index e5e67dc..2a1f96d 100644 --- a/docs/demarrage/premier-vpc.rst +++ b/docs/demarrage/premier-vpc.rst @@ -14,7 +14,7 @@ Ce que l'on construit graph LR subgraph netns vp-admin - BR["br-sn000001
10.1.1.1"] + BR["br-sn000001
10.1.1.254"] MD["metadata@i-web
169.254.169.254"] end VM["VM i-web
10.1.1.2"] --- BR @@ -58,13 +58,18 @@ prêt est refusé en **422**. Le modèle d'attente est décrit dans :doc:`/explo "mode": "vxlan", "vxlan_id": 1, "iface_type": "vms", - "interface_ip": "10.1.1.1", "cidr": "10.1.0.0/23"}' ``iface_type`` est une clé **logique** résolue dans la configuration de l'agent (section ``interfaces``) vers un bridge physique de l'host ; une clé inconnue retombe sur -``default_interface``. ``interface_ip`` est la gateway du subnet, portée par le bridge créé dans -le netns. +``default_interface``. + +En mode ``vxlan``, les adresses de la gateway sont **calculées** et ne se fournissent pas (un +``interface_ip`` est refusé) : la gateway vue par les VM est l'avant-dernière adresse du CIDR +(``interface_ip`` = ``10.1.1.254`` ici), l'adresse d'émission propre au netns la précédente +(``relay_ip`` = ``10.1.1.253``) ; le CIDR doit valoir au plus ``/29``. Aucune VM ne peut prendre +ces deux adresses, ni celles du réseau et du broadcast. En mode ``bridge``, ``interface_ip`` reste +obligatoire. Les modes disponibles et leurs conséquences sur le routage sont détaillés dans :doc:`/concepts/modes-reseau`. diff --git a/internal/api/agent/models.go b/internal/api/agent/models.go index de01684..045e8fd 100644 --- a/internal/api/agent/models.go +++ b/internal/api/agent/models.go @@ -33,6 +33,7 @@ type Subnet struct { VxlanID int `json:"vxlan_id"` LocalIface string `json:"local_iface"` InterfaceIP string `json:"interface_ip"` + RelayIP string `json:"relay_ip,omitempty"` CIDR string `json:"cidr"` DefaultRoute bool `json:"default_route"` Gateway string `json:"gateway"` diff --git a/internal/api/agent/subnet.go b/internal/api/agent/subnet.go index 4473489..99e4137 100644 --- a/internal/api/agent/subnet.go +++ b/internal/api/agent/subnet.go @@ -55,6 +55,8 @@ func (s *Server) getSubnet(w http.ResponseWriter, _ *http.Request, name string) sub.LocalIface = value case "interface_ip": sub.InterfaceIP = value + case "relay_ip": + sub.RelayIP = value case "cidr": sub.CIDR = value case "default_route": diff --git a/internal/api/agent/subnet_test.go b/internal/api/agent/subnet_test.go index 6cf4176..bf24986 100644 --- a/internal/api/agent/subnet_test.go +++ b/internal/api/agent/subnet_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "strings" "testing" "git.g3e.fr/syonad/two/pkg/db/kv" @@ -57,11 +58,10 @@ func TestPostSubnet_Created(t *testing.T) { s, db := newTestServer(t) kv.AddInDB(db, "vpc/vpc-1/state", "running") req := SubnetCreateRequest{ - Name: "sn-new", - VPC: "vpc-1", - IfaceType: "vms", - InterfaceIP: "10.0.0.1", - CIDR: "10.0.0.0/24", + Name: "sn-new", + VPC: "vpc-1", + IfaceType: "vms", + CIDR: "10.0.0.0/24", } body, _ := json.Marshal(req) w := httptest.NewRecorder() @@ -93,10 +93,9 @@ func TestPostSubnet_IfaceTypeOptional(t *testing.T) { s, db := newTestServer(t) kv.AddInDB(db, "vpc/vpc-1/state", "running") req := SubnetCreateRequest{ - Name: "sn-opt", - VPC: "vpc-1", - InterfaceIP: "10.0.0.1", - CIDR: "10.0.0.0/24", + Name: "sn-opt", + VPC: "vpc-1", + CIDR: "10.0.0.0/24", // IfaceType omis — doit utiliser default_interface } body, _ := json.Marshal(req) @@ -110,11 +109,10 @@ func TestPostSubnet_IfaceTypeOptional(t *testing.T) { func TestPostSubnet_VPCNotFound(t *testing.T) { s, _ := newTestServer(t) req := SubnetCreateRequest{ - Name: "sn-1", - VPC: "vpc-inexistant", - IfaceType: "vms", - InterfaceIP: "10.0.0.1", - CIDR: "10.0.0.0/24", + Name: "sn-1", + VPC: "vpc-inexistant", + IfaceType: "vms", + CIDR: "10.0.0.0/24", } body, _ := json.Marshal(req) w := httptest.NewRecorder() @@ -129,11 +127,10 @@ func TestPostSubnet_Duplicate(t *testing.T) { kv.AddInDB(db, "vpc/vpc-1/state", "running") kv.AddInDB(db, "subnet/sn-exist/state", "running") req := SubnetCreateRequest{ - Name: "sn-exist", - VPC: "vpc-1", - IfaceType: "vms", - InterfaceIP: "10.0.0.1", - CIDR: "10.0.0.0/24", + Name: "sn-exist", + VPC: "vpc-1", + IfaceType: "vms", + CIDR: "10.0.0.0/24", } body, _ := json.Marshal(req) w := httptest.NewRecorder() @@ -147,11 +144,10 @@ func TestPostSubnet_VPCDeleting(t *testing.T) { s, db := newTestServer(t) kv.AddInDB(db, "vpc/vpc-dying/state", "deleting") req := SubnetCreateRequest{ - Name: "sn-1", - VPC: "vpc-dying", - IfaceType: "vms", - InterfaceIP: "10.0.0.1", - CIDR: "10.0.0.0/24", + Name: "sn-1", + VPC: "vpc-dying", + IfaceType: "vms", + CIDR: "10.0.0.0/24", } body, _ := json.Marshal(req) w := httptest.NewRecorder() @@ -206,6 +202,17 @@ func TestPostSubnet_UnknownMode(t *testing.T) { } } +func TestPostSubnet_UnknownModeWithoutInterfaceIP(t *testing.T) { + s, db := newTestServer(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + body, _ := json.Marshal(SubnetCreateRequest{Name: "sn-1", VPC: "vpc-1", Mode: "vlan", CIDR: "10.0.0.0/24"}) + w := httptest.NewRecorder() + s.SubnetsHandler(w, httptest.NewRequest(http.MethodPost, "/subnets", bytes.NewReader(body))) + if w.Code != http.StatusUnprocessableEntity || !strings.Contains(w.Body.String(), "unknown subnet mode") { + t.Errorf("attendu 422 mode inconnu, obtenu %d : %s", w.Code, w.Body.String()) + } +} + func TestPostSubnet_InvalidBody(t *testing.T) { s, _ := newTestServer(t) w := httptest.NewRecorder() @@ -337,3 +344,99 @@ func TestCreateSubnet_GatewayRoundTrip(t *testing.T) { t.Errorf("gateway absente de la réponse GET : %+v", got) } } + +func postSubnetRequest(t *testing.T, s *Server, req SubnetCreateRequest) *httptest.ResponseRecorder { + t.Helper() + body, _ := json.Marshal(req) + w := httptest.NewRecorder() + s.SubnetsHandler(w, httptest.NewRequest(http.MethodPost, "/subnets", bytes.NewReader(body))) + return w +} + +func TestPostSubnet_VxlanRejectsInterfaceIP(t *testing.T) { + for _, mode := range []string{"", "vxlan"} { + s, db := newTestServer(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + w := postSubnetRequest(t, s, SubnetCreateRequest{ + Name: "sn-1", VPC: "vpc-1", Mode: mode, + InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + }) + if w.Code != http.StatusBadRequest { + t.Errorf("mode %q : attendu 400, obtenu %d : %s", mode, w.Code, w.Body.String()) + } + if _, err := kv.GetFromDB(db, "subnet/sn-1/state"); err == nil { + t.Errorf("mode %q : aucun subnet ne doit être créé", mode) + } + } +} + +func TestPostSubnet_BridgeRequiresInterfaceIP(t *testing.T) { + s, db := newTestServer(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + w := postSubnetRequest(t, s, SubnetCreateRequest{ + Name: "sn-br", VPC: "vpc-1", Mode: "bridge", CIDR: "10.0.0.0/24", + }) + if w.Code != http.StatusBadRequest { + t.Errorf("attendu 400, obtenu %d : %s", w.Code, w.Body.String()) + } +} + +func TestPostSubnet_VxlanReturnsComputedAddresses(t *testing.T) { + s, db := newTestServer(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + w := postSubnetRequest(t, s, SubnetCreateRequest{ + Name: "sn-vx", VPC: "vpc-1", Mode: "vxlan", CIDR: "10.0.0.0/24", + }) + if w.Code != http.StatusAccepted { + t.Fatalf("attendu 202, obtenu %d : %s", w.Code, w.Body.String()) + } + var got Subnet + json.NewDecoder(w.Body).Decode(&got) + if got.InterfaceIP != "10.0.0.254" { + t.Errorf("interface_ip attendue 10.0.0.254, obtenu %q", got.InterfaceIP) + } + if got.RelayIP != "10.0.0.253" { + t.Errorf("relay_ip attendu 10.0.0.253, obtenu %q", got.RelayIP) + } +} + +func TestGetSubnet_RelayIPOnlyForVxlan(t *testing.T) { + s, db := newTestServer(t) + kv.AddInDB(db, "vpc/vpc-1/state", "running") + if w := postSubnetRequest(t, s, SubnetCreateRequest{ + Name: "sn-vx", VPC: "vpc-1", CIDR: "10.0.0.0/24", + }); w.Code != http.StatusAccepted { + t.Fatalf("vxlan : attendu 202, obtenu %d : %s", w.Code, w.Body.String()) + } + if w := postSubnetRequest(t, s, SubnetCreateRequest{ + Name: "sn-br", VPC: "vpc-1", Mode: "bridge", InterfaceIP: "10.1.0.1", CIDR: "10.1.0.0/24", + }); w.Code != http.StatusAccepted { + t.Fatalf("bridge : attendu 202, obtenu %d : %s", w.Code, w.Body.String()) + } + + w := httptest.NewRecorder() + s.SubnetByNameHandler(w, httptest.NewRequest(http.MethodGet, "/subnets/sn-vx", nil)) + var vx Subnet + json.NewDecoder(w.Body).Decode(&vx) + if vx.RelayIP != "10.0.0.253" { + t.Errorf("relay_ip attendu 10.0.0.253, obtenu %q", vx.RelayIP) + } + + w = httptest.NewRecorder() + s.SubnetByNameHandler(w, httptest.NewRequest(http.MethodGet, "/subnets/sn-br", nil)) + if strings.Contains(w.Body.String(), "relay_ip") { + t.Errorf("relay_ip ne doit pas apparaître pour un subnet bridge : %s", w.Body.String()) + } + + w = httptest.NewRecorder() + s.SubnetsHandler(w, httptest.NewRequest(http.MethodGet, "/subnets", nil)) + var list []Subnet + json.NewDecoder(w.Body).Decode(&list) + relays := map[string]string{} + for _, sub := range list { + relays[sub.Name] = sub.RelayIP + } + if relays["sn-vx"] != "10.0.0.253" || relays["sn-br"] != "" { + t.Errorf("relay_ip inattendus dans la liste : %v", relays) + } +} diff --git a/internal/api/agent/subnets.go b/internal/api/agent/subnets.go index efa480b..00bfb7b 100644 --- a/internal/api/agent/subnets.go +++ b/internal/api/agent/subnets.go @@ -7,6 +7,7 @@ import ( "strings" dispatcher "git.g3e.fr/syonad/two/internal/dispatcher/agent" + "git.g3e.fr/syonad/two/internal/subnet" "git.g3e.fr/syonad/two/pkg/db/kv" ) @@ -52,6 +53,8 @@ func (s *Server) listSubnets(w http.ResponseWriter, _ *http.Request) { subnets[name].LocalIface = value case "interface_ip": subnets[name].InterfaceIP = value + case "relay_ip": + subnets[name].RelayIP = value case "cidr": subnets[name].CIDR = value case "default_route": @@ -73,9 +76,25 @@ func (s *Server) postSubnet(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(ErrorResponse{Error: "invalid request body"}) return } - if req.Name == "" || req.VPC == "" || req.InterfaceIP == "" || req.CIDR == "" { + if req.Name == "" || req.VPC == "" || req.CIDR == "" { w.WriteHeader(http.StatusBadRequest) - json.NewEncoder(w).Encode(ErrorResponse{Error: "name, vpc, interface_ip and cidr are required"}) + json.NewEncoder(w).Encode(ErrorResponse{Error: "name, vpc and cidr are required"}) + return + } + if req.Mode != "" && !subnet.ValidMode(req.Mode) { + w.WriteHeader(http.StatusUnprocessableEntity) + json.NewEncoder(w).Encode(ErrorResponse{Error: "unknown subnet mode " + strconv.Quote(req.Mode)}) + return + } + vxlan := req.Mode == "" || req.Mode == subnet.ModeVxlan + if !vxlan && req.InterfaceIP == "" { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{Error: "interface_ip is required for " + req.Mode + " subnets"}) + return + } + if vxlan && req.InterfaceIP != "" { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{Error: "interface_ip is computed for vxlan subnets, do not set it"}) return } cmd := dispatcher.CreateSubnetCommand{ @@ -124,6 +143,8 @@ func (s *Server) postSubnet(w http.ResponseWriter, r *http.Request) { sub.LocalIface = value case "interface_ip": sub.InterfaceIP = value + case "relay_ip": + sub.RelayIP = value case "cidr": sub.CIDR = value case "default_route": diff --git a/internal/api/agent/vm_test.go b/internal/api/agent/vm_test.go index e4892f2..66b43d9 100644 --- a/internal/api/agent/vm_test.go +++ b/internal/api/agent/vm_test.go @@ -99,6 +99,7 @@ func TestStartVM_MultiDisk(t *testing.T) { 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-10", @@ -133,6 +134,7 @@ func TestStartVM_StorageReturnedInResponse(t *testing.T) { 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-11", @@ -167,6 +169,7 @@ func postVM(t *testing.T, name string, meta VMMetadata) (*httptest.ResponseRecor 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: name, @@ -291,9 +294,10 @@ func TestVmFromDB_MultipleInterfacesSortedByIndex(t *testing.T) { func TestStartVM_StoresAllInterfaces(t *testing.T) { s, db := newTestServer(t) - for _, sn := range []string{"sn-1", "sn-2"} { + for sn, cidr := range map[string]string{"sn-1": "10.1.0.0/24", "sn-2": "10.2.0.0/24"} { kv.AddInDB(db, "subnet/"+sn+"/state", "running") kv.AddInDB(db, "subnet/"+sn+"/vpc", "vpc-1") + kv.AddInDB(db, "subnet/"+sn+"/cidr", cidr) } body, _ := json.Marshal(VMCreateRequest{ @@ -332,9 +336,10 @@ func TestStartVM_RejectsZeroOrTwoPrimaries(t *testing.T) { } for label, ifaces := range cases { s, db := newTestServer(t) - for _, sn := range []string{"sn-1", "sn-2"} { + for sn, cidr := range map[string]string{"sn-1": "10.1.0.0/24", "sn-2": "10.2.0.0/24"} { kv.AddInDB(db, "subnet/"+sn+"/state", "running") kv.AddInDB(db, "subnet/"+sn+"/vpc", "vpc-1") + kv.AddInDB(db, "subnet/"+sn+"/cidr", cidr) } body, _ := json.Marshal(VMCreateRequest{ Name: "vm-bad", @@ -348,3 +353,71 @@ func TestStartVM_RejectsZeroOrTwoPrimaries(t *testing.T) { } } } + +func TestStartVM_RejectsReservedOrForeignAddresses(t *testing.T) { + cases := map[string]string{ + "passerelle anycast": "10.0.0.254", + "relais": "10.0.0.253", + "adresse réseau": "10.0.0.0", + "broadcast": "10.0.0.255", + "hors cidr": "10.0.1.5", + "gateway explicite": "10.0.0.1", + } + for label, ip := range cases { + 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") + kv.AddInDB(db, "subnet/sn-1/interface_ip", "10.0.0.254") + kv.AddInDB(db, "subnet/sn-1/relay_ip", "10.0.0.253") + kv.AddInDB(db, "subnet/sn-1/gateway", "10.0.0.1") + body, _ := json.Marshal(VMCreateRequest{ + Name: "vm-ip", + Interfaces: []VMInterface{{Subnet: "sn-1", IP: ip, Primary: true}}, + Storage: []VMStorage{{Path: "/data/root.qcow2", Dev: "vda"}}, + }) + w := httptest.NewRecorder() + s.VmsHandler(w, httptest.NewRequest(http.MethodPost, "/vms", bytes.NewReader(body))) + if w.Code != http.StatusUnprocessableEntity { + t.Errorf("%s : attendu 422, obtenu %d — %s", label, w.Code, w.Body.String()) + } + if _, err := kv.GetFromDB(db, "vm/vm-ip/state"); err == nil { + t.Errorf("%s : la VM ne doit pas être créée", label) + } + } +} + +func TestStartVM_AcceptsHostAddressBesideReservedOnes(t *testing.T) { + 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") + kv.AddInDB(db, "subnet/sn-1/interface_ip", "10.0.0.254") + kv.AddInDB(db, "subnet/sn-1/relay_ip", "10.0.0.253") + body, _ := json.Marshal(VMCreateRequest{ + Name: "vm-ip", + Interfaces: []VMInterface{{Subnet: "sn-1", IP: "10.0.0.252", Primary: true}}, + Storage: []VMStorage{{Path: "/data/root.qcow2", Dev: "vda"}}, + }) + w := httptest.NewRecorder() + s.VmsHandler(w, httptest.NewRequest(http.MethodPost, "/vms", bytes.NewReader(body))) + if w.Code != http.StatusAccepted { + t.Fatalf("attendu 202, obtenu %d : %s", w.Code, w.Body.String()) + } +} + +func TestStartVM_RejectsSubnetWithoutCIDR(t *testing.T) { + s, db := newTestServer(t) + kv.AddInDB(db, "subnet/sn-1/state", "running") + kv.AddInDB(db, "subnet/sn-1/vpc", "vpc-1") + body, _ := json.Marshal(VMCreateRequest{ + Name: "vm-ip", + Interfaces: []VMInterface{{Subnet: "sn-1", IP: "10.0.0.5", Primary: true}}, + Storage: []VMStorage{{Path: "/data/root.qcow2", Dev: "vda"}}, + }) + w := httptest.NewRecorder() + s.VmsHandler(w, httptest.NewRequest(http.MethodPost, "/vms", bytes.NewReader(body))) + if w.Code != http.StatusUnprocessableEntity || !strings.Contains(w.Body.String(), "has no cidr") { + t.Errorf("attendu 422 « has no cidr », obtenu %d : %s", w.Code, w.Body.String()) + } +} diff --git a/internal/dispatcher/agent/subnet_commands.go b/internal/dispatcher/agent/subnet_commands.go index f6e7f2d..e5807ba 100644 --- a/internal/dispatcher/agent/subnet_commands.go +++ b/internal/dispatcher/agent/subnet_commands.go @@ -38,6 +38,20 @@ func (c CreateSubnetCommand) Prepare(db *badger.DB, cfg *configuration.Config) e if _, err := kv.GetFromDB(db, "subnet/"+c.Name+"/state"); err == nil { return fmt.Errorf("subnet %q already exists", c.Name) } + relayIP := "" + if c.Mode == subnet.ModeVxlan { + if c.InterfaceIP != "" { + return fmt.Errorf("interface_ip is computed for vxlan subnets, do not set it") + } + addrs, err := subnet.AnycastAddresses(c.CIDR) + if err != nil { + return err + } + c.InterfaceIP = addrs.Gateway.String() + relayIP = addrs.Relay.String() + } else if c.InterfaceIP == "" { + return fmt.Errorf("interface_ip is required for %s subnets", c.Mode) + } vpcState, err := state.Get(db, "vpc/"+c.VPC) if err != nil { return fmt.Errorf("vpc %q not found", c.VPC) @@ -58,6 +72,7 @@ func (c CreateSubnetCommand) Prepare(db *badger.DB, cfg *configuration.Config) e kv.AddInDB(db, "subnet/"+c.Name+"/default_route", strconv.FormatBool(c.DefaultRoute)) if c.Mode == subnet.ModeVxlan { kv.AddInDB(db, "subnet/"+c.Name+"/vxlan_id", strconv.Itoa(c.VxlanID)) + kv.AddInDB(db, "subnet/"+c.Name+"/relay_ip", relayIP) } if c.Gateway != "" { if err := kv.AddInDB(db, "subnet/"+c.Name+"/gateway", c.Gateway); err != nil { diff --git a/internal/dispatcher/agent/subnet_commands_test.go b/internal/dispatcher/agent/subnet_commands_test.go index 3474df1..d9095f2 100644 --- a/internal/dispatcher/agent/subnet_commands_test.go +++ b/internal/dispatcher/agent/subnet_commands_test.go @@ -22,7 +22,7 @@ func TestCreateSubnetCommand_Prepare_Success(t *testing.T) { kv.AddInDB(db, "vpc/vpc-1/state", "running") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-1", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } if err := cmd.Prepare(db, testCfg()); err != nil { t.Fatalf("Prepare a échoué : %v", err) @@ -35,6 +35,10 @@ func TestCreateSubnetCommand_Prepare_Success(t *testing.T) { if vpc != "vpc-1" { t.Errorf("vpc attendu vpc-1, obtenu %q", vpc) } + ip, _ := kv.GetFromDB(db, "subnet/sn-1/interface_ip") + if ip != "10.0.0.254" { + t.Errorf("interface_ip attendue 10.0.0.254, obtenu %q", ip) + } } func TestCreateSubnetCommand_Prepare_UsesIfaceTypeMapping(t *testing.T) { @@ -42,7 +46,7 @@ func TestCreateSubnetCommand_Prepare_UsesIfaceTypeMapping(t *testing.T) { kv.AddInDB(db, "vpc/vpc-1/state", "running") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-1", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } cmd.Prepare(db, testCfg()) iface, _ := kv.GetFromDB(db, "subnet/sn-1/local_iface") @@ -56,7 +60,7 @@ func TestCreateSubnetCommand_Prepare_UsesDefaultIfaceWhenTypeUnknown(t *testing. kv.AddInDB(db, "vpc/vpc-1/state", "running") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-1", VxlanID: 100, - IfaceType: "inconnu", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "inconnu", CIDR: "10.0.0.0/24", } cmd.Prepare(db, testCfg()) iface, _ := kv.GetFromDB(db, "subnet/sn-1/local_iface") @@ -71,7 +75,7 @@ func TestCreateSubnetCommand_Prepare_Duplicate(t *testing.T) { kv.AddInDB(db, "subnet/sn-exist/state", "running") cmd := CreateSubnetCommand{ Name: "sn-exist", VPC: "vpc-1", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } if err := cmd.Prepare(db, testCfg()); err == nil { t.Error("Prepare devrait échouer sur un subnet déjà existant") @@ -82,7 +86,7 @@ func TestCreateSubnetCommand_Prepare_VPCNotFound(t *testing.T) { _, db := newTestDispatcher(t) cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-inexistant", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } if err := cmd.Prepare(db, testCfg()); err == nil { t.Error("Prepare devrait échouer si le VPC n'existe pas") @@ -94,7 +98,7 @@ func TestCreateSubnetCommand_Prepare_VPCDeleting(t *testing.T) { kv.AddInDB(db, "vpc/vpc-dying/state", "deleting") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-dying", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } if err := cmd.Prepare(db, testCfg()); err == nil { t.Error("Prepare devrait échouer si le VPC est en cours de suppression") @@ -106,7 +110,7 @@ func TestCreateSubnetCommand_Prepare_VPCDeleted(t *testing.T) { kv.AddInDB(db, "vpc/vpc-gone/state", "deleted") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-gone", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } if err := cmd.Prepare(db, testCfg()); err == nil { t.Error("Prepare devrait échouer si le VPC est supprimé") @@ -118,7 +122,7 @@ func TestCreateSubnetCommand_Prepare_DefaultsToVxlanMode(t *testing.T) { kv.AddInDB(db, "vpc/vpc-1/state", "running") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-1", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } cmd.Prepare(db, testCfg()) mode, _ := kv.GetFromDB(db, "subnet/sn-1/mode") @@ -180,7 +184,7 @@ func TestCreateSubnetCommand_Prepare_DefaultRouteStored(t *testing.T) { kv.AddInDB(db, "vpc/vpc-1/state", "running") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-1", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", DefaultRoute: true, } if err := cmd.Prepare(db, testCfg()); err != nil { @@ -200,7 +204,7 @@ func TestCreateSubnetCommand_Prepare_DefaultRouteFalseByDefault(t *testing.T) { kv.AddInDB(db, "vpc/vpc-1/state", "running") cmd := CreateSubnetCommand{ Name: "sn-1", VPC: "vpc-1", VxlanID: 100, - IfaceType: "vms", InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + IfaceType: "vms", CIDR: "10.0.0.0/24", } cmd.Prepare(db, testCfg()) val, _ := kv.GetFromDB(db, "subnet/sn-1/default_route") @@ -209,6 +213,76 @@ func TestCreateSubnetCommand_Prepare_DefaultRouteFalseByDefault(t *testing.T) { } } +func TestCreateSubnetCommand_Prepare_VxlanComputesAnycastAddresses(t *testing.T) { + db, err := prepareSubnet(t, CreateSubnetCommand{ + Name: "sn-any", VxlanID: 100, IfaceType: "vms", CIDR: "10.1.0.0/16", + }) + if err != nil { + t.Fatalf("Prepare a échoué : %v", err) + } + if ip, _ := kv.GetFromDB(db, "subnet/sn-any/interface_ip"); ip != "10.1.255.254" { + t.Errorf("interface_ip attendue 10.1.255.254, obtenu %q", ip) + } + if relay, _ := kv.GetFromDB(db, "subnet/sn-any/relay_ip"); relay != "10.1.255.253" { + t.Errorf("relay_ip attendu 10.1.255.253, obtenu %q", relay) + } +} + +func TestCreateSubnetCommand_Prepare_VxlanRefusesInterfaceIP(t *testing.T) { + for _, mode := range []string{"", "vxlan"} { + db, err := prepareSubnet(t, CreateSubnetCommand{ + Name: "sn-ip", Mode: mode, VxlanID: 100, IfaceType: "vms", + InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + }) + if err == nil || !strings.Contains(err.Error(), "interface_ip is computed") { + t.Errorf("mode %q : une interface_ip fournie doit être refusée, obtenu %v", mode, err) + } + if _, err := kv.GetFromDB(db, "subnet/sn-ip/state"); err == nil { + t.Errorf("mode %q : rien ne doit être écrit après un refus", mode) + } + } +} + +func TestCreateSubnetCommand_Prepare_VxlanRefusesSlash30(t *testing.T) { + db, err := prepareSubnet(t, CreateSubnetCommand{ + Name: "sn-small", VxlanID: 100, IfaceType: "vms", CIDR: "10.0.0.0/30", + }) + if err == nil { + t.Fatal("un /30 doit être refusé en mode vxlan") + } + if _, err := kv.GetFromDB(db, "subnet/sn-small/state"); err == nil { + t.Error("rien ne doit être écrit après un refus") + } +} + +func TestCreateSubnetCommand_Prepare_BridgeRequiresInterfaceIP(t *testing.T) { + db, err := prepareSubnet(t, CreateSubnetCommand{ + Name: "sn-br", Mode: "bridge", IfaceType: "vms", CIDR: "10.0.0.0/24", + }) + if err == nil || !strings.Contains(err.Error(), "interface_ip is required") { + t.Errorf("une interface_ip absente doit être refusée en mode bridge, obtenu %v", err) + } + if _, err := kv.GetFromDB(db, "subnet/sn-br/state"); err == nil { + t.Error("rien ne doit être écrit après un refus") + } +} + +func TestCreateSubnetCommand_Prepare_BridgeStoresGivenInterfaceIPWithoutRelay(t *testing.T) { + db, err := prepareSubnet(t, CreateSubnetCommand{ + Name: "sn-br", Mode: "bridge", IfaceType: "vms", + InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + }) + if err != nil { + t.Fatalf("Prepare a échoué : %v", err) + } + if ip, _ := kv.GetFromDB(db, "subnet/sn-br/interface_ip"); ip != "10.0.0.1" { + t.Errorf("interface_ip attendue 10.0.0.1, obtenu %q", ip) + } + if _, err := kv.GetFromDB(db, "subnet/sn-br/relay_ip"); err == nil { + t.Error("relay_ip ne doit être écrit qu'en mode vxlan") + } +} + // --- DeleteSubnetCommand.Prepare --- func TestDeleteSubnetCommand_Prepare_Success(t *testing.T) { @@ -273,7 +347,7 @@ func prepareSubnet(t *testing.T, cmd CreateSubnetCommand) (*badger.DB, error) { func TestCreateSubnetCommand_Prepare_StoresGateway(t *testing.T) { db, err := prepareSubnet(t, CreateSubnetCommand{ Name: "sn-gw", VxlanID: 100, IfaceType: "vms", - InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + CIDR: "10.0.0.0/24", DefaultRoute: true, Gateway: "10.0.0.254", }) if err != nil { @@ -291,7 +365,7 @@ func TestCreateSubnetCommand_Prepare_StoresGateway(t *testing.T) { func TestCreateSubnetCommand_Prepare_NoGatewayWritesNoKey(t *testing.T) { db, err := prepareSubnet(t, CreateSubnetCommand{ Name: "sn-nogw", VxlanID: 100, IfaceType: "vms", - InterfaceIP: "10.0.0.1", CIDR: "10.0.0.0/24", + CIDR: "10.0.0.0/24", }) if err != nil { t.Fatalf("Prepare a échoué : %v", err) diff --git a/internal/dispatcher/agent/vm_commands.go b/internal/dispatcher/agent/vm_commands.go index d634d5d..9f72113 100644 --- a/internal/dispatcher/agent/vm_commands.go +++ b/internal/dispatcher/agent/vm_commands.go @@ -9,6 +9,7 @@ import ( configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/state" + "git.g3e.fr/syonad/two/internal/subnet" "git.g3e.fr/syonad/two/internal/vm" "git.g3e.fr/syonad/two/pkg/db/kv" "github.com/dgraph-io/badger/v4" @@ -106,6 +107,16 @@ func (c StartVMCommand) validateNICs(db *badger.DB) error { if subnetState != state.Creating && subnetState != state.Running { return fmt.Errorf("subnet %q is %s", n.Subnet, subnetState) } + cidr, err := kv.GetFromDB(db, "subnet/"+n.Subnet+"/cidr") + if err != nil { + return fmt.Errorf("subnet %q has no cidr", n.Subnet) + } + interfaceIP, _ := kv.GetFromDB(db, "subnet/"+n.Subnet+"/interface_ip") + relayIP, _ := kv.GetFromDB(db, "subnet/"+n.Subnet+"/relay_ip") + gateway, _ := kv.GetFromDB(db, "subnet/"+n.Subnet+"/gateway") + if err := subnet.CheckHostAddress(cidr, n.IP, interfaceIP, relayIP, gateway); err != nil { + return fmt.Errorf("vm %q on subnet %q: %w", c.Name, n.Subnet, err) + } } if primaries != 1 { return fmt.Errorf("vm %q has %d primary interfaces, expected exactly one", c.Name, primaries) diff --git a/internal/dispatcher/agent/vm_commands_test.go b/internal/dispatcher/agent/vm_commands_test.go index 1a773fc..29b3f69 100644 --- a/internal/dispatcher/agent/vm_commands_test.go +++ b/internal/dispatcher/agent/vm_commands_test.go @@ -13,6 +13,7 @@ func TestStartVMCommand_Prepare_SingleDisk(t *testing.T) { _, db := newTestDispatcher(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") cmd := StartVMCommand{ Name: "vm-1", @@ -36,6 +37,7 @@ func TestStartVMCommand_Prepare_MultiDisk(t *testing.T) { _, db := newTestDispatcher(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") cmd := StartVMCommand{ Name: "vm-2", @@ -67,6 +69,7 @@ func TestStartVMCommand_Prepare_SlotGap(t *testing.T) { _, db := newTestDispatcher(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") // sdb absent au boot — slot réservé pour hotplug cmd := StartVMCommand{ @@ -96,6 +99,7 @@ func TestStartVMCommand_Prepare_NoVolumePath(t *testing.T) { _, db := newTestDispatcher(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") cmd := StartVMCommand{ Name: "vm-4", @@ -177,6 +181,7 @@ func prepareWithDocuments(t *testing.T, docs map[string]string) *badger.DB { _, db := newTestDispatcher(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") cmd := StartVMCommand{ Name: "vm-doc", diff --git a/internal/subnet/addressing.go b/internal/subnet/addressing.go new file mode 100644 index 0000000..03fe64e --- /dev/null +++ b/internal/subnet/addressing.go @@ -0,0 +1,88 @@ +package subnet + +import ( + "fmt" + "net/netip" +) + +const MaxAnycastPrefix = 29 + +type Addresses struct { + Prefix netip.Prefix + Network netip.Addr + Broadcast netip.Addr + Gateway netip.Addr + Relay netip.Addr +} + +func ParsePrefix(cidr string) (netip.Prefix, error) { + prefix, err := netip.ParsePrefix(cidr) + if err != nil { + return netip.Prefix{}, fmt.Errorf("invalid cidr %q", cidr) + } + if !prefix.Addr().Is4() { + return netip.Prefix{}, fmt.Errorf("cidr %q is not ipv4", cidr) + } + if prefix.Masked() != prefix { + return netip.Prefix{}, fmt.Errorf("cidr %q has host bits set, expected %s", cidr, prefix.Masked()) + } + return prefix, nil +} + +func broadcastOf(prefix netip.Prefix) netip.Addr { + b := prefix.Addr().As4() + host := uint32(1)<<(32-prefix.Bits()) - 1 + v := uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]) | host + return netip.AddrFrom4([4]byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)}) +} + +func AnycastAddresses(cidr string) (Addresses, error) { + prefix, err := ParsePrefix(cidr) + if err != nil { + return Addresses{}, err + } + if prefix.Bits() > MaxAnycastPrefix { + return Addresses{}, fmt.Errorf("cidr %q is too small for a vxlan subnet, at most /%d", cidr, MaxAnycastPrefix) + } + broadcast := broadcastOf(prefix) + gateway := broadcast.Prev() + return Addresses{ + Prefix: prefix, + Network: prefix.Addr(), + Broadcast: broadcast, + Gateway: gateway, + Relay: gateway.Prev(), + }, nil +} + +func CheckHostAddress(cidr, ip string, reserved ...string) error { + prefix, err := netip.ParsePrefix(cidr) + if err != nil || !prefix.Addr().Is4() { + return fmt.Errorf("invalid ipv4 cidr %q", cidr) + } + prefix = prefix.Masked() + addr, err := netip.ParseAddr(ip) + if err != nil { + return fmt.Errorf("invalid ip %q", ip) + } + if !prefix.Contains(addr) { + return fmt.Errorf("ip %s is outside %s", addr, prefix) + } + if prefix.Bits() < 31 { + if addr == prefix.Addr() { + return fmt.Errorf("ip %s is the network address of %s", addr, prefix) + } + if addr == broadcastOf(prefix) { + return fmt.Errorf("ip %s is the broadcast address of %s", addr, prefix) + } + } + for _, r := range reserved { + if r == "" { + continue + } + if other, err := netip.ParseAddr(r); err == nil && other == addr { + return fmt.Errorf("ip %s is reserved by the subnet", addr) + } + } + return nil +} diff --git a/internal/subnet/addressing_test.go b/internal/subnet/addressing_test.go new file mode 100644 index 0000000..0762d78 --- /dev/null +++ b/internal/subnet/addressing_test.go @@ -0,0 +1,146 @@ +package subnet + +import ( + "strings" + "testing" +) + +func TestAnycastAddresses_Slash24(t *testing.T) { + a, err := AnycastAddresses("10.0.0.0/24") + if err != nil { + t.Fatalf("AnycastAddresses a échoué : %v", err) + } + for label, c := range map[string][2]string{ + "network": {"10.0.0.0", a.Network.String()}, + "broadcast": {"10.0.0.255", a.Broadcast.String()}, + "gateway": {"10.0.0.254", a.Gateway.String()}, + "relay": {"10.0.0.253", a.Relay.String()}, + } { + if c[0] != c[1] { + t.Errorf("%s attendu %s, obtenu %s", label, c[0], c[1]) + } + } + if a.Prefix.String() != "10.0.0.0/24" { + t.Errorf("prefix attendu 10.0.0.0/24, obtenu %s", a.Prefix) + } +} + +func TestAnycastAddresses_Slash16(t *testing.T) { + a, err := AnycastAddresses("172.16.0.0/16") + if err != nil { + t.Fatalf("AnycastAddresses a échoué : %v", err) + } + if a.Broadcast.String() != "172.16.255.255" { + t.Errorf("broadcast attendu 172.16.255.255, obtenu %s", a.Broadcast) + } + if a.Gateway.String() != "172.16.255.254" { + t.Errorf("gateway attendue 172.16.255.254, obtenu %s", a.Gateway) + } + if a.Relay.String() != "172.16.255.253" { + t.Errorf("relay attendu 172.16.255.253, obtenu %s", a.Relay) + } +} + +func TestAnycastAddresses_Slash29IsTheSmallestAccepted(t *testing.T) { + a, err := AnycastAddresses("192.168.1.8/29") + if err != nil { + t.Fatalf("un /29 doit être accepté : %v", err) + } + if a.Gateway.String() != "192.168.1.14" { + t.Errorf("gateway attendue 192.168.1.14, obtenu %s", a.Gateway) + } + if a.Relay.String() != "192.168.1.13" { + t.Errorf("relay attendu 192.168.1.13, obtenu %s", a.Relay) + } +} + +func TestAnycastAddresses_Refused(t *testing.T) { + cases := map[string]struct { + cidr string + want string + }{ + "/30 trop petit": {"10.0.0.0/30", "too small"}, + "bits d'hôte": {"10.0.0.1/24", "host bits"}, + "ipv6": {"fd00::/64", "not ipv4"}, + "cidr illisible": {"pas-un-cidr", "invalid cidr"}, + "adresse sans prefix": {"10.0.0.0", "invalid cidr"}, + } + for label, c := range cases { + _, err := AnycastAddresses(c.cidr) + if err == nil { + t.Errorf("%s : %q devrait être refusé", label, c.cidr) + continue + } + if !strings.Contains(err.Error(), c.want) { + t.Errorf("%s : erreur attendue contenant %q, obtenu %v", label, c.want, err) + } + } +} + +func TestCheckHostAddress_ValidHost(t *testing.T) { + if err := CheckHostAddress("10.0.0.0/24", "10.0.0.5", "10.0.0.254", "10.0.0.253"); err != nil { + t.Errorf("10.0.0.5 devrait être accepté : %v", err) + } +} + +func TestCheckHostAddress_Refused(t *testing.T) { + cases := map[string]struct { + ip string + want string + }{ + "hors cidr": {"10.0.1.5", "outside"}, + "adresse réseau": {"10.0.0.0", "network address"}, + "adresse broadcast": {"10.0.0.255", "broadcast address"}, + "passerelle réservée": {"10.0.0.254", "reserved"}, + "relais réservé": {"10.0.0.253", "reserved"}, + "ip illisible": {"10.0.0", "invalid ip"}, + "ipv6": {"fd00::5", "outside"}, + } + for label, c := range cases { + err := CheckHostAddress("10.0.0.0/24", c.ip, "10.0.0.254", "10.0.0.253") + if err == nil { + t.Errorf("%s : %s devrait être refusé", label, c.ip) + continue + } + if !strings.Contains(err.Error(), c.want) { + t.Errorf("%s : erreur attendue contenant %q, obtenu %v", label, c.want, err) + } + } +} + +func TestCheckHostAddress_EmptyReservedIgnored(t *testing.T) { + if err := CheckHostAddress("10.0.0.0/24", "10.0.0.5", "", ""); err != nil { + t.Errorf("des réservations vides ne doivent rien bloquer : %v", err) + } +} + +func TestCheckHostAddress_LenientCIDRWithHostBits(t *testing.T) { + if err := CheckHostAddress("10.0.0.1/24", "10.0.0.5"); err != nil { + t.Errorf("un cidr avec bits d'hôte doit être normalisé : %v", err) + } + if err := CheckHostAddress("10.0.0.1/24", "10.0.0.0"); err == nil { + t.Error("l'adresse réseau du cidr normalisé doit rester refusée") + } +} + +func TestCheckHostAddress_Slash31And32HaveNoNetworkOrBroadcast(t *testing.T) { + for _, ip := range []string{"10.0.0.0", "10.0.0.1"} { + if err := CheckHostAddress("10.0.0.0/31", ip); err != nil { + t.Errorf("/31 : %s devrait être accepté : %v", ip, err) + } + } + if err := CheckHostAddress("10.0.0.7/32", "10.0.0.7"); err != nil { + t.Errorf("/32 : 10.0.0.7 devrait être accepté : %v", err) + } + if err := CheckHostAddress("10.0.0.7/32", "10.0.0.8"); err == nil { + t.Error("/32 : 10.0.0.8 est hors du cidr et devrait être refusé") + } +} + +func TestCheckHostAddress_InvalidCIDR(t *testing.T) { + for _, cidr := range []string{"", "pas-un-cidr", "fd00::/64"} { + if err := CheckHostAddress(cidr, "10.0.0.5"); err == nil { + t.Errorf("cidr %q devrait être refusé", cidr) + } + } +}