diff --git a/api/agent.yaml b/api/agent.yaml index e8e5b7c..714b8f6 100644 --- a/api/agent.yaml +++ b/api/agent.yaml @@ -321,11 +321,11 @@ components: type: integer format: int32 minimum: 1 - maximum: 16777215 + maximum: 65535 description: >- Optional. L3VNI of the VPC, used for inter-subnet routing between hypervisors (symmetric IRB). Also the id of the routing table of the VPC VRF, so 253-255 are - rejected. Requires the bgp section in the agent configuration, and must not be used + rejected, and the number of the route distinguisher :, which holds 16 bits. Requires the bgp section in the agent configuration, and must not be used by another VPC of the agent. Absent: the VPC has no L3VNI. example: 4001 diff --git a/cmd/agent/main.go b/cmd/agent/main.go index e824dbc..197d1c3 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -31,11 +31,14 @@ const shutdownTimeout = 20 * time.Second func main() { confFile := flag.String("config", "/etc/two/agent.yml", "config file path") flag.Parse() + os.Exit(run(*confFile)) +} - cfg, err := configuration.LoadConfig(*confFile) +func run(confFile string) int { + cfg, err := configuration.LoadConfig(confFile) if err != nil { slog.Error("failed to load config", "error", err) - return + return 1 } log := logger.New(cfg.Logger.Level, cfg.Logger.Debug) @@ -52,18 +55,18 @@ func main() { // d'états, et des ressources transitoires orphelines d'un arrêt précédent. if err := migration.MigrateStates(db, log.With(slog.String("component", "migration"))); err != nil { log.Error("failed to migrate states", "error", err) - return + return 1 } if err := migration.MigrateVMNICs(db, log.With(slog.String("component", "migration"))); err != nil { log.Error("vm nic migration failed", "error", err) - return + 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) - return + return 1 } log.Info("bgp base configuration applied", "asn", cfg.BGP.ASN, "route_reflectors", cfg.BGP.RouteReflectors) } @@ -118,6 +121,7 @@ func main() { servers["admin"] = adminSrv } closeDB = shutdown(log, q, servers, shutdownTimeout) + return 0 } type baseApplier interface { diff --git a/cmd/agent/main_test.go b/cmd/agent/main_test.go index 302d0e7..9f3209c 100644 --- a/cmd/agent/main_test.go +++ b/cmd/agent/main_test.go @@ -5,6 +5,8 @@ import ( "errors" "io" "log/slog" + "os" + "path/filepath" "strings" "sync/atomic" "testing" @@ -117,3 +119,27 @@ func TestApplyBGPBase_RefusesAnInvalidSectionBeforeTouchingFRR(t *testing.T) { t.Error("ApplyBase appelé avec une section bgp invalide") } } + +func TestRunExitsNonZeroWhenTheConfigCannotBeLoaded(t *testing.T) { + conf := filepath.Join(t.TempDir(), "agent.yml") + if err := os.WriteFile(conf, []byte("bgp: [non: valide\n"), 0o600); err != nil { + t.Fatal(err) + } + if code := run(conf); code != 1 { + t.Errorf("code de sortie %d, 1 attendu", code) + } +} + +func TestRunExitsNonZeroWhenTheBGPBaseCannotBeApplied(t *testing.T) { + dir := t.TempDir() + conf := filepath.Join(dir, "agent.yml") + yml := "database:\n path: " + filepath.Join(dir, "db") + "\n" + + "default_interface: two-test-absent0\n" + + "bgp:\n asn: 64600\n route_reflectors: [10.255.255.1]\n" + if err := os.WriteFile(conf, []byte(yml), 0o600); err != nil { + t.Fatal(err) + } + if code := run(conf); code != 1 { + t.Errorf("code de sortie %d, 1 attendu", code) + } +} diff --git a/docs/architecture/vue-densemble.rst b/docs/architecture/vue-densemble.rst index a0f5c3f..e589562 100644 --- a/docs/architecture/vue-densemble.rst +++ b/docs/architecture/vue-densemble.rst @@ -39,6 +39,13 @@ Paquets - migrations idempotentes jouées au démarrage de l'agent * - ``internal/vpc``, ``internal/subnet`` - création et suppression bas niveau (netns + netif) + * - ``internal/l3vni`` + - routage d'une VPC par L3VNI : VRF, L3VNI, transit, configuration FRR, export des routes + ``/24`` et ``/32`` + * - ``internal/frr`` + - génération des commandes FRR, seul point d'appel à ``vtysh`` + * - ``internal/sysctl`` + - écriture sous ``/proc/sys``, dans un netns si besoin * - ``internal/netns`` - network namespaces : create/enter/delete/call * - ``internal/netif`` diff --git a/docs/developpement/lab.rst b/docs/developpement/lab.rst index 638b361..d45aa3d 100644 --- a/docs/developpement/lab.rst +++ b/docs/developpement/lab.rst @@ -149,7 +149,10 @@ livré le 2026-10-11 un E5-2670 de 2012, x86-64-v2, sur lequel Rocky 10 ne déma ``prepare`` refuse donc un serveur sans x86-64-v3 — dans une ``session``, il est aussitôt supprimé. La zone n'est pas imposée : ``plan`` et ``up`` prennent la première zone de ``LAB_ZONES`` (par défaut toutes les zones Elastic Metal) où l'offre est en stock, ``SCW_DEFAULT_ZONE`` -passant en tête ; ``status`` et ``down`` couvrent toutes ces zones. +passant en tête ; ``status`` et ``down`` couvrent toutes ces zones. Une zone dont la liste échoue +est signalée sans masquer les autres : ``status`` affiche ce qui a répondu, ``down`` supprime les +serveurs listés, et tous deux sortent en erreur ; ``up`` refuse de créer tant qu'une zone reste +inconnue. ``session`` est la forme normale d'usage : le serveur est supprimé à la fin, que la commande réussisse, échoue, ou que la session soit interrompue (Ctrl-C, ``TERM``, fermeture du terminal). @@ -245,7 +248,7 @@ Ce que le fichier déclare : * ``frr`` — le chemin d'un ``frr.conf``, relatif au fichier de topologie : FRR est installé au démarrage et la configuration déposée **telle quelle** (voir `Rôles`_). * ``release`` — **obligatoire pour un hyperviseur**, refusé ailleurs : le tag de la release de - two que ``deploy.sh`` installe (``release: 0.2.0rc005``). Sans lui, ``deploy.sh`` prendrait la + two que ``deploy.sh`` installe (``release: 0.2.0rc008``). Sans lui, ``deploy.sh`` prendrait la dernière release, et le lab ne serait plus reproductible. * ``agent`` — pour un hyperviseur seulement : le chemin d'un ``agent.yml``, relatif au fichier de topologie, déposé dans ``/etc/two/agent.yml`` avant ``deploy.sh``. Sans lui, l'agent tourne @@ -302,8 +305,8 @@ Limites : 1000 nœuds, 256 segments, et autant de câbles que la plage UDP le pe name loopback secondary frr release agent sw1 - underlay 169.254.0.1/28 sw1.conf - - rr1 lo1 10.255.255.1/32 underlay 169.254.0.3/28 rr1.conf - - - hv1 - - hv1.conf 0.2.0rc005 two.yml - hv2 - - hv2.conf 0.2.0rc005 bgp.yml + hv1 - - hv1.conf 0.2.0rc008 two.yml + hv2 - - hv2.conf 0.2.0rc008 bgp.yml segment underlay: 192.168.14.0/24, mtu 9000, switch sw1, bridge br-underlay, gateway 192.168.14.1 node interface address mac udp switch port mac udp @@ -758,6 +761,12 @@ sortie vaut 1 si une vérification échoue **ou si aucune n'a été faite**. chaque hôte, sans doublon EVPN ; watchdog : ``/32`` orphelin signalé comme trou noir, ``/32`` manquant signalé - hv1, hv2, hv3, rr1 + * - ``s9-subnets-partages`` + - deux VPC, avec et sans ``l3vni``, chacune avec deux subnets présents sur **les deux** + hyperviseurs et une VM par subnet et par hôte : ping entre toutes les paires (même subnet ou + non, même hôte ou non) ; chaque VM voit la MAC de gateway de son propre hôte ; aucune MAC en + double sur les quatre VNI + - hv2, hv3, rr1 ``s6`` réutilise les VM de ``s4`` : le lancer après. @@ -850,6 +859,21 @@ Trois défauts trouvés et corrigés pendant la campagne : * **L3VNI libérée de façon asynchrone** : juste après ``no vni``, ``no router bgp … vrf`` peut être refusé (« Please unconfigure l3vni ») puis accepté un instant plus tard ; l'agent réessaie. +Le 2026-10-12, release ``0.2.0rc006``, ``evpn-3hv.yml`` : ``s1`` à ``s7`` sans échec, +``s8-l3vni-migration`` **50 réussi(s), 0 échoué(s)** (MAC de gateway propre à chaque hôte, aucun +doublon EVPN), ``s9-subnets-partages`` **75 réussi(s), 1 échoué(s)**. L'échec est une session SSH +coupée (``Broken pipe``), pas un ping perdu : quand un hôte route vers une VM d'un autre hôte, son +netns émet une requête ARP au nom de la gateway, partagée par tous les hôtes ; la VM met son cache à +jour et, pendant ~8 s, envoie à la gateway de l'autre hôte ce qui était destiné à la sienne. +Détails et suite : `#57 `_. + +.. note:: + + Un ``Broken pipe`` (``client_loop: send disconnect``) ou une session SSH figée dans un scénario + n'est **pas forcément un aléa du lab** : c'est la signature de ce problème. Ne pas le classer + comme test instable ni ajouter un nouvel essai qui le masquerait ; regarder d'abord le cache ARP + de la VM (``ip neigh show ``) et l'état de la session côté VM. + Les VM sont accessibles depuis le netns de leur VPC, sur l'hyperviseur, avec l'utilisateur ``syonad`` créé par les métadonnées de two : diff --git a/docs/exploitation/observabilite.rst b/docs/exploitation/observabilite.rst index d0b97e1..6602dfa 100644 --- a/docs/exploitation/observabilite.rst +++ b/docs/exploitation/observabilite.rst @@ -50,7 +50,8 @@ Avec une section ``bgp`` dans la configuration, il contrôle aussi le plan de co le propriétaire n'existe plus — ni ``running``, ni en ``creating``, ``deleting`` ou ``error`` — est signalée comme un **trou noir** : l'annonce attire du trafic que plus rien ne reçoit. -Un VPC routé alors que la section ``bgp`` a disparu de la configuration est signalé lui aussi. +Un VPC routé alors que la section ``bgp`` a disparu de la configuration est signalé lui aussi. Il +reste supprimable : le démontage lit l'AS de son instance dans la configuration courante de FRR. .. note:: diff --git a/internal/api/agent/vpc_test.go b/internal/api/agent/vpc_test.go index 626667a..8578b57 100644 --- a/internal/api/agent/vpc_test.go +++ b/internal/api/agent/vpc_test.go @@ -280,6 +280,7 @@ func TestPostVpc_RejectsAnInvalidL3VNIAsABadRequest(t *testing.T) { for _, body := range []string{ `{"name":"vp-1","cidr":"10.0.0.0/16","l3vni":0}`, `{"name":"vp-1","cidr":"10.0.0.0/16","l3vni":255}`, + `{"name":"vp-1","cidr":"10.0.0.0/16","l3vni":65536}`, `{"name":"vp-1","cidr":"10.0.0.0/16","l3vni":16777216}`, `{"name":"vp-1","cidr":"10.0.0.0/16","l3vni":-1}`, } { diff --git a/internal/api/agent/vpcs.go b/internal/api/agent/vpcs.go index 1e0ed68..17110d2 100644 --- a/internal/api/agent/vpcs.go +++ b/internal/api/agent/vpcs.go @@ -8,7 +8,7 @@ import ( "strings" dispatcher "git.g3e.fr/syonad/two/internal/dispatcher/agent" - "git.g3e.fr/syonad/two/internal/vpc" + "git.g3e.fr/syonad/two/internal/l3vni" "git.g3e.fr/syonad/two/pkg/db/kv" ) @@ -82,7 +82,7 @@ func (s *Server) postVpc(w http.ResponseWriter, r *http.Request) { } cmd := dispatcher.CreateVPCCommand{Name: req.Name, CIDR: req.CIDR} if req.L3VNI != nil { - if err := vpc.ValidL3VNI(*req.L3VNI); err != nil { + if err := l3vni.Valid(*req.L3VNI); err != nil { w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(ErrorResponse{Error: err.Error()}) return diff --git a/internal/dispatcher/agent/vpc_commands.go b/internal/dispatcher/agent/vpc_commands.go index d37c31b..7404342 100644 --- a/internal/dispatcher/agent/vpc_commands.go +++ b/internal/dispatcher/agent/vpc_commands.go @@ -8,6 +8,7 @@ import ( "time" configuration "git.g3e.fr/syonad/two/internal/config/agent" + "git.g3e.fr/syonad/two/internal/l3vni" "git.g3e.fr/syonad/two/internal/state" "git.g3e.fr/syonad/two/internal/vpc" "git.g3e.fr/syonad/two/pkg/db/kv" @@ -46,7 +47,7 @@ func (c CreateVPCCommand) Prepare(db *badger.DB, cfg *configuration.Config) erro } func (c CreateVPCCommand) checkL3VNI(db *badger.DB, cfg *configuration.Config) error { - if err := vpc.ValidL3VNI(c.L3VNI); err != nil { + if err := l3vni.Valid(c.L3VNI); err != nil { return err } if cfg == nil || !cfg.BGP.Enabled() { @@ -132,7 +133,7 @@ func (c DeleteVPCCommand) Execute(db *badger.DB, cfg *configuration.Config) erro case <-time.After(time.Duration(cfg.Dispatcher.PollSeconds) * time.Second): } } - if err := vpc.DeleteVPC(db, c.Name, cfg); err != nil { + if err := vpc.DeleteVPC(db, c.Name); err != nil { return err } current, err := state.Get(db, c.Key()) diff --git a/internal/frr/client.go b/internal/frr/client.go index 3f38204..d380e85 100644 --- a/internal/frr/client.go +++ b/internal/frr/client.go @@ -83,8 +83,8 @@ func (c *Client) RemoveVRF(v VRF) error { } func (c *Client) teardown(v VRF, plan func(VRF, string) []step) error { - if err := v.validateName(); err != nil { - return err + if v.ID == "" { + return fmt.Errorf("frr: vrf id must not be empty") } running, err := c.runningConfig() if err != nil { diff --git a/internal/frr/client_test.go b/internal/frr/client_test.go index ea68e1e..0f9ec9e 100644 --- a/internal/frr/client_test.go +++ b/internal/frr/client_test.go @@ -172,10 +172,10 @@ func TestRemoveVRFFailsWhenRoutingConfigurationIsStillThere(t *testing.T) { } } -func TestTeardownNeedsOnlyTheASNAndTheID(t *testing.T) { +func TestTeardownNeedsOnlyTheID(t *testing.T) { f := &fakeVtysh{running: []string{"", ""}} - if err := f.client().WithdrawVRF(VRF{ASN: 64600, ID: "a1b2"}); err != nil { - t.Errorf("démontage refusé : %v", err) + if err := f.client().WithdrawVRF(VRF{ID: "a1b2"}); err != nil { + t.Errorf("démontage sans asn refusé : %v", err) } f = &fakeVtysh{} if err := f.client().WithdrawVRF(VRF{ASN: 64600}); err == nil || len(f.calls) != 0 { diff --git a/internal/frr/config.go b/internal/frr/config.go index 2ebad5e..34e3210 100644 --- a/internal/frr/config.go +++ b/internal/frr/config.go @@ -6,7 +6,7 @@ import ( "strings" ) -const maxVNI = 1<<24 - 1 +const MaxL3VNI = 1<<16 - 1 type Base struct { ASN uint32 @@ -116,8 +116,8 @@ func (v VRF) validate() error { if err := v.validateName(); err != nil { return err } - if v.L3VNI == 0 || v.L3VNI > maxVNI { - return fmt.Errorf("frr: l3vni %d does not fit in 24 bits", v.L3VNI) + if v.L3VNI == 0 || v.L3VNI > MaxL3VNI { + return fmt.Errorf("frr: l3vni %d out of range 1-%d: the route distinguisher : holds 16 bits", v.L3VNI, MaxL3VNI) } if v.VTEP.To4() == nil { return fmt.Errorf("frr: vtep %v is not an IPv4 address", v.VTEP) diff --git a/internal/frr/config_test.go b/internal/frr/config_test.go index ac30a87..766554a 100644 --- a/internal/frr/config_test.go +++ b/internal/frr/config_test.go @@ -117,8 +117,9 @@ func TestVRFValidateRejects(t *testing.T) { }{ "asn nul": {func(v *VRF) { v.ASN = 0 }, "asn must not be 0"}, "id vide": {func(v *VRF) { v.ID = "" }, "vrf id must not be empty"}, - "l3vni nul": {func(v *VRF) { v.L3VNI = 0 }, "l3vni 0 does not fit in 24 bits"}, - "l3vni sur 25 bits": {func(v *VRF) { v.L3VNI = 16777216 }, "l3vni 16777216 does not fit in 24 bits"}, + "l3vni nul": {func(v *VRF) { v.L3VNI = 0 }, "l3vni 0 out of range 1-65535"}, + "l3vni sur 17 bits": {func(v *VRF) { v.L3VNI = 65536 }, "l3vni 65536 out of range 1-65535"}, + "l3vni sur 24 bits": {func(v *VRF) { v.L3VNI = 16777215 }, "l3vni 16777215 out of range 1-65535"}, "vtep absent": {func(v *VRF) { v.VTEP = nil }, "vtep is not an IPv4 address"}, "vtep IPv6": {func(v *VRF) { v.VTEP = net.ParseIP("fd00::1") }, "vtep fd00::1 is not an IPv4 address"}, "supernet absent": {func(v *VRF) { v.Supernet = nil }, "supernet is not an IPv4 prefix"}, @@ -133,10 +134,10 @@ func TestVRFValidateRejects(t *testing.T) { } } -func TestVRFAcceptsTheLargest24BitVNI(t *testing.T) { +func TestVRFAcceptsTheLargest16BitVNI(t *testing.T) { v := labVRF(t) - v.L3VNI = 16777215 + v.L3VNI = 65535 if err := v.validate(); err != nil { - t.Errorf("l3vni 16777215 refusée : %v", err) + t.Errorf("l3vni 65535 refusée : %v", err) } } diff --git a/internal/frr/teardown.go b/internal/frr/teardown.go index bcdd18d..fcbc407 100644 --- a/internal/frr/teardown.go +++ b/internal/frr/teardown.go @@ -2,6 +2,7 @@ package frr import ( "fmt" + "strconv" "strings" ) @@ -9,16 +10,17 @@ type step []string func routingTeardown(v VRF, running string) []step { lines := strings.Split(running, "\n") - bgp := hasLine(lines, v.bgpInstance()) + instance := vrfInstance(lines, v.Name()) + bgp := instance != "" var steps []step if bgp { - steps = append(steps, step{v.bgpInstance(), "address-family ipv4 unicast", "no redistribute kernel"}) + steps = append(steps, step{instance, "address-family ipv4 unicast", "no redistribute kernel"}) } if vni := vrfVNI(lines, v.Name()); vni != "" { steps = append(steps, step{"vrf " + v.Name(), "no vni " + vni}) } if bgp { - steps = append(steps, step{"no " + v.bgpInstance()}) + steps = append(steps, step{"no " + instance}) } if hasPrefix(lines, "route-map "+v.routeMap()+" ") { steps = append(steps, step{"no route-map " + v.routeMap()}) @@ -36,6 +38,19 @@ func vrfTeardown(v VRF, running string) []step { return nil } +func vrfInstance(lines []string, name string) string { + for _, l := range lines { + f := strings.Fields(l) + if len(f) != 5 || f[0] != "router" || f[1] != "bgp" || f[3] != "vrf" || f[4] != name { + continue + } + if _, err := strconv.ParseUint(f[2], 10, 32); err == nil { + return strings.Join(f, " ") + } + } + return "" +} + func hasLine(lines []string, want string) bool { for _, l := range lines { if strings.TrimRight(l, " \r") == want { diff --git a/internal/frr/teardown_test.go b/internal/frr/teardown_test.go index cd27049..210c943 100644 --- a/internal/frr/teardown_test.go +++ b/internal/frr/teardown_test.go @@ -97,6 +97,23 @@ func TestRoutingTeardownFollowsTheOrderFRRRequires(t *testing.T) { } } +func TestRoutingTeardownTakesTheASNOfTheInstanceFromFRR(t *testing.T) { + want := []step{ + {"router bgp 64600 vrf vrf-a1b2", "address-family ipv4 unicast", "no redistribute kernel"}, + {"vrf vrf-a1b2", "no vni 4001"}, + {"no router bgp 64600 vrf vrf-a1b2"}, + {"no route-map EXPORT-a1b2"}, + {"no ip prefix-list PL-a1b2"}, + } + for _, asn := range []uint32{0, 64601} { + v := labVRF(t) + v.ASN = asn + if got := routingTeardown(v, fullRunning); !reflect.DeepEqual(got, want) { + t.Errorf("asn %d :\n%q\nattendu :\n%q", asn, got, want) + } + } +} + func TestRoutingTeardownIgnoresAVRFWhoseNameExtendsOurs(t *testing.T) { if got := routingTeardown(labVRF(t), otherOnlyRunning); got != nil { t.Errorf("étapes visant vrf-a1b2c : %q", got) diff --git a/internal/vpc/host.go b/internal/l3vni/host.go similarity index 89% rename from internal/vpc/host.go rename to internal/l3vni/host.go index 37a1720..4899d3e 100644 --- a/internal/vpc/host.go +++ b/internal/l3vni/host.go @@ -1,4 +1,4 @@ -package vpc +package l3vni import ( "net" @@ -13,8 +13,7 @@ type host interface { VTEPAddress(iface string) (net.IP, error) Sysctl(ns, key, value string) error CreateVRF(name string, table uint32) error - CreateBridge(name string, mtu int) error - SetHardwareAddr(name string, mac net.HardwareAddr) error + CreateBridge(name string, mtu int, mac net.HardwareAddr) error SetMaster(iface, master string) error CreateVxlan(name string, vni int, iface string, mtu int) error CreateVeth(hostIf, nsIf, ns string, mtu int) error @@ -52,10 +51,8 @@ func (system) Sysctl(ns, key, value string) error { func (system) CreateVRF(name string, table uint32) error { return netif.CreateVRF(name, table) } -func (system) CreateBridge(name string, mtu int) error { return netif.CreateBridge(name, mtu) } - -func (system) SetHardwareAddr(name string, mac net.HardwareAddr) error { - return netif.LinkSetHardwareAddr(name, mac) +func (system) CreateBridge(name string, mtu int, mac net.HardwareAddr) error { + return netif.CreateBridge(name, mtu, mac) } func (system) SetMaster(iface, master string) error { return netif.BridgeSetMaster(iface, master) } diff --git a/internal/vpc/l3.go b/internal/l3vni/l3.go similarity index 87% rename from internal/vpc/l3.go rename to internal/l3vni/l3.go index 79b2088..3558274 100644 --- a/internal/vpc/l3.go +++ b/internal/l3vni/l3.go @@ -1,12 +1,14 @@ -package vpc +package l3vni import ( + "errors" "fmt" "net" "strconv" configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/frr" + "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/pkg/db/kv" "github.com/dgraph-io/badger/v4" @@ -28,14 +30,17 @@ type l3VPC struct { func loadL3(db *badger.DB, name, id string) (l3VPC, bool, error) { raw, err := kv.GetFromDB(db, "vpc/"+name+"/l3vni") - if err != nil { + if errors.Is(err, badger.ErrKeyNotFound) { return l3VPC{}, false, nil } + if err != nil { + return l3VPC{}, false, fmt.Errorf("vpc %q: reading l3vni: %w", name, err) + } vni, err := strconv.ParseUint(raw, 10, 32) if err != nil { return l3VPC{}, false, fmt.Errorf("vpc %q: invalid l3vni %q", name, raw) } - if err := ValidL3VNI(uint32(vni)); err != nil { + if err := Valid(uint32(vni)); err != nil { return l3VPC{}, false, fmt.Errorf("vpc %q: %w", name, err) } cidr, err := kv.GetFromDB(db, "vpc/"+name+"/cidr") @@ -55,14 +60,6 @@ func (v l3VPC) vxlan() string { return "vxl3-" + v.id } func (v l3VPC) vethHost() string { return "l3-" + v.id + "-o" } func (v l3VPC) vethNetns() string { return "l3-" + v.id + "-i" } -func routerMAC(vtep net.IP) (net.HardwareAddr, error) { - ip := vtep.To4() - if ip == nil { - return nil, fmt.Errorf("vtep %v is not an IPv4 address", vtep) - } - return net.HardwareAddr{0x02, 0x02, ip[0], ip[1], ip[2], ip[3]}, nil -} - func bgpASN(cfg *configuration.Config) (uint32, error) { if cfg == nil || !cfg.BGP.Enabled() { return 0, fmt.Errorf("the vpc has an l3vni but the agent configuration has no bgp section") @@ -79,7 +76,7 @@ func createL3(h host, cfg *configuration.Config, v l3VPC) error { if err != nil { return fmt.Errorf("vtep: %w", err) } - rmac, err := routerMAC(vtep) + rmac, err := RouterMAC(vtep) if err != nil { return err } @@ -88,8 +85,7 @@ func createL3(h host, cfg *configuration.Config, v l3VPC) error { run func() error }{ {"create " + v.vrf(), func() error { return h.CreateVRF(v.vrf(), v.vni) }}, - {"create " + v.bridge(), func() error { return h.CreateBridge(v.bridge(), l3MTU) }}, - {"set router mac on " + v.bridge(), func() error { return h.SetHardwareAddr(v.bridge(), 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, l3MTU) }}, {"attach " + v.vxlan(), func() error { return h.SetMaster(v.vxlan(), v.bridge()) }}, @@ -118,12 +114,8 @@ func createL3(h host, cfg *configuration.Config, v l3VPC) error { return nil } -func deleteL3(h host, cfg *configuration.Config, v l3VPC) error { - asn, err := bgpASN(cfg) - if err != nil { - return err - } - frrVRF := frr.VRF{ASN: asn, ID: v.id} +func deleteL3(h host, v l3VPC) error { + frrVRF := frr.VRF{ID: v.id} if err := h.WithdrawVRF(frrVRF); err != nil { return fmt.Errorf("l3vni %d: withdraw frr: %w", v.vni, err) } @@ -138,6 +130,22 @@ func deleteL3(h host, cfg *configuration.Config, v l3VPC) error { return nil } +func Create(db *badger.DB, vpcName string, cfg *configuration.Config) error { + v, ok, err := loadRouted(db, vpcName) + if err != nil || !ok { + return err + } + return createL3(newSystem(), cfg, v) +} + +func Delete(db *badger.DB, vpcName string) error { + v, ok, err := loadRouted(db, vpcName) + if err != nil || !ok { + return err + } + return deleteL3(newSystem(), v) +} + type Routing struct { VNI uint32 Supernet *net.IPNet @@ -165,5 +173,5 @@ func LoadRouting(db *badger.DB, vpcName string) (Routing, bool, error) { } func RouterMAC(vtep net.IP) (net.HardwareAddr, error) { - return routerMAC(vtep) + return netif.HostMAC(netif.RoleRouter, vtep) } diff --git a/internal/vpc/l3_test.go b/internal/l3vni/l3_test.go similarity index 85% rename from internal/vpc/l3_test.go rename to internal/l3vni/l3_test.go index a56fad9..ee3f9bc 100644 --- a/internal/vpc/l3_test.go +++ b/internal/l3vni/l3_test.go @@ -1,4 +1,4 @@ -package vpc +package l3vni import ( "errors" @@ -43,12 +43,8 @@ func (f *fakeHost) CreateVRF(name string, table uint32) error { return f.record(fmt.Sprintf("vrf %s table %d", name, table)) } -func (f *fakeHost) CreateBridge(name string, mtu int) error { - return f.record(fmt.Sprintf("bridge %s mtu %d", name, mtu)) -} - -func (f *fakeHost) SetHardwareAddr(name string, mac net.HardwareAddr) error { - return f.record(fmt.Sprintf("mac %s %s", name, mac)) +func (f *fakeHost) CreateBridge(name string, mtu int, mac net.HardwareAddr) error { + return f.record(fmt.Sprintf("bridge %s mtu %d mac %s", name, mtu, mac)) } func (f *fakeHost) SetMaster(iface, master string) error { @@ -123,8 +119,7 @@ func TestCreateL3FollowsTheLabRecipe(t *testing.T) { want := []string{ "vtep br-000000", "vrf vrf-s7 table 2700", - "bridge brl3-s7 mtu 1500", - "mac brl3-s7 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 1500", "master vxl3-s7 brl3-s7", @@ -173,16 +168,16 @@ func TestCreateL3StopsAtTheFirstFailure(t *testing.T) { func TestDeleteL3WithdrawsFRRThenTheKernelThenTheVRF(t *testing.T) { f := &fakeHost{} - if err := deleteL3(f, bgpConfig(), labL3(t)); err != nil { + if err := deleteL3(f, labL3(t)); err != nil { t.Fatal(err) } want := []string{ - "frr withdraw asn=64600 id=s7 vni=0", + "frr withdraw asn=0 id=s7 vni=0", "del l3-s7-o", "del vxl3-s7", "del brl3-s7", "del vrf-s7", - "frr remove asn=64600 id=s7 vni=0", + "frr remove asn=0 id=s7 vni=0", } if !reflect.DeepEqual(f.calls, want) { t.Errorf("appels :\n%s\nattendu :\n%s", strings.Join(f.calls, "\n"), strings.Join(want, "\n")) @@ -191,7 +186,7 @@ func TestDeleteL3WithdrawsFRRThenTheKernelThenTheVRF(t *testing.T) { func TestDeleteL3KeepsTheKernelWhenFRRRefusesTheWithdrawal(t *testing.T) { f := &fakeHost{fail: map[string]error{"frr withdraw": errors.New("% Please unconfigure l3vni 2700")}} - err := deleteL3(f, bgpConfig(), labL3(t)) + err := deleteL3(f, labL3(t)) if err == nil || !strings.Contains(err.Error(), "withdraw frr") { t.Errorf("erreur %v", err) } @@ -202,7 +197,7 @@ func TestDeleteL3KeepsTheKernelWhenFRRRefusesTheWithdrawal(t *testing.T) { func TestDeleteL3KeepsTheFRRVRFWhenAKernelLinkCannotBeDeleted(t *testing.T) { f := &fakeHost{fail: map[string]error{"del brl3-s7": errors.New("device busy")}} - if err := deleteL3(f, bgpConfig(), labL3(t)); err == nil || !strings.Contains(err.Error(), "delete brl3-s7") { + if err := deleteL3(f, labL3(t)); err == nil || !strings.Contains(err.Error(), "delete brl3-s7") { t.Errorf("erreur %v", err) } for _, c := range f.calls { @@ -212,19 +207,19 @@ func TestDeleteL3KeepsTheFRRVRFWhenAKernelLinkCannotBeDeleted(t *testing.T) { } } -func TestDeleteL3RequiresTheBGPSection(t *testing.T) { +func TestDeleteL3DoesNotDependOnTheAgentBGPSection(t *testing.T) { f := &fakeHost{} - if err := deleteL3(f, &configuration.Config{}, labL3(t)); err == nil || len(f.calls) != 0 { + if err := deleteL3(f, labL3(t)); err != nil || len(f.calls) != 6 { t.Errorf("erreur %v, appels %q", err, f.calls) } } func TestRouterMAC(t *testing.T) { - mac, err := routerMAC(net.ParseIP("192.168.14.11")) + mac, err := RouterMAC(net.ParseIP("192.168.14.11")) if err != nil || mac.String() != "02:02:c0:a8:0e:0b" { - t.Errorf("routerMAC = %v, %v", mac, err) + t.Errorf("RouterMAC = %v, %v", mac, err) } - if _, err := routerMAC(net.ParseIP("fd00::1")); err == nil { + if _, err := RouterMAC(net.ParseIP("fd00::1")); err == nil { t.Error("VTEP IPv6 accepté") } } @@ -252,3 +247,14 @@ func TestLoadL3(t *testing.T) { t.Errorf("VPC sans cidr : %v", err) } } + +func TestLoadL3ReportsAReadErrorInsteadOfAVPCWithoutL3VNI(t *testing.T) { + db := kv.InitDB(kv.Config{Path: t.TempDir()}, false) + kv.AddInDB(db, "vpc/vp-a/cidr", "10.241.0.0/16") + kv.AddInDB(db, "vpc/vp-a/l3vni", "2700") + db.Close() + _, ok, err := loadL3(db, "vp-a", "a") + if ok || err == nil || !strings.Contains(err.Error(), "reading l3vni") { + t.Errorf("base fermée : ok=%v err=%v, erreur de lecture attendue", ok, err) + } +} diff --git a/internal/l3vni/l3vni.go b/internal/l3vni/l3vni.go new file mode 100644 index 0000000..bebfa7b --- /dev/null +++ b/internal/l3vni/l3vni.go @@ -0,0 +1,17 @@ +package l3vni + +import ( + "fmt" + + "git.g3e.fr/syonad/two/internal/frr" +) + +func Valid(id uint32) error { + if id == 0 || id > frr.MaxL3VNI { + return fmt.Errorf("l3vni %d out of range 1-%d: the route distinguisher : holds 16 bits", id, frr.MaxL3VNI) + } + if id >= 253 && id <= 255 { + return fmt.Errorf("l3vni %d is reserved: it is also the routing table id, and tables 253-255 belong to the kernel", id) + } + return nil +} diff --git a/internal/l3vni/l3vni_test.go b/internal/l3vni/l3vni_test.go new file mode 100644 index 0000000..ea18bc3 --- /dev/null +++ b/internal/l3vni/l3vni_test.go @@ -0,0 +1,30 @@ +package l3vni + +import ( + "strings" + "testing" +) + +func TestValid_AcceptsEvery16BitValueOutsideTheKernelTables(t *testing.T) { + for _, id := range []uint32{1, 252, 256, 4001, 65535} { + if err := Valid(id); err != nil { + t.Errorf("Valid(%d) = %v", id, err) + } + } +} + +func TestValid_RejectsOutOfRangeAndReservedTables(t *testing.T) { + cases := map[uint32]string{ + 0: "out of range 1-65535", + 65536: "out of range 1-65535", + 16777215: "out of range 1-65535", + 253: "is reserved", + 254: "is reserved", + 255: "is reserved", + } + for id, want := range cases { + if err := Valid(id); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("Valid(%d) = %v, attendu %q", id, err, want) + } + } +} diff --git a/internal/vpc/route.go b/internal/l3vni/route.go similarity index 98% rename from internal/vpc/route.go rename to internal/l3vni/route.go index 3b5da19..333abf6 100644 --- a/internal/vpc/route.go +++ b/internal/l3vni/route.go @@ -1,4 +1,4 @@ -package vpc +package l3vni import ( "fmt" diff --git a/internal/vpc/route_test.go b/internal/l3vni/route_test.go similarity index 99% rename from internal/vpc/route_test.go rename to internal/l3vni/route_test.go index ded011a..0377f68 100644 --- a/internal/vpc/route_test.go +++ b/internal/l3vni/route_test.go @@ -1,4 +1,4 @@ -package vpc +package l3vni import ( "errors" diff --git a/internal/netif/bridge.go b/internal/netif/bridge.go index a4754a3..1bd5e18 100644 --- a/internal/netif/bridge.go +++ b/internal/netif/bridge.go @@ -1,14 +1,17 @@ package netif import ( + "net" + "github.com/vishvananda/netlink" ) -func CreateBridge(name string, mtu int) error { +func CreateBridge(name string, mtu int, mac net.HardwareAddr) error { br := &netlink.Bridge{ LinkAttrs: netlink.LinkAttrs{ - Name: name, - MTU: mtu, + Name: name, + MTU: mtu, + HardwareAddr: mac, }, } diff --git a/internal/netif/mac.go b/internal/netif/mac.go new file mode 100644 index 0000000..ba8300c --- /dev/null +++ b/internal/netif/mac.go @@ -0,0 +1,21 @@ +package netif + +import ( + "fmt" + "net" +) + +const ( + locallyAdministered byte = 0x02 + + RoleRouter byte = 0x02 + RoleHostGateway byte = 0x03 +) + +func HostMAC(role byte, vtep net.IP) (net.HardwareAddr, error) { + ip := vtep.To4() + if ip == nil { + return nil, fmt.Errorf("vtep %v is not an IPv4 address", vtep) + } + return net.HardwareAddr{locallyAdministered, role, ip[0], ip[1], ip[2], ip[3]}, nil +} diff --git a/internal/netif/mac_test.go b/internal/netif/mac_test.go new file mode 100644 index 0000000..5230513 --- /dev/null +++ b/internal/netif/mac_test.go @@ -0,0 +1,60 @@ +package netif + +import ( + "net" + "testing" +) + +func TestHostMAC(t *testing.T) { + cases := []struct { + role byte + vtep string + want string + }{ + {RoleHostGateway, "192.168.14.11", "02:03:c0:a8:0e:0b"}, + {RoleHostGateway, "192.168.14.12", "02:03:c0:a8:0e:0c"}, + {RoleHostGateway, "10.0.0.1", "02:03:0a:00:00:01"}, + {RoleRouter, "192.168.14.11", "02:02:c0:a8:0e:0b"}, + } + for _, c := range cases { + got, err := HostMAC(c.role, net.ParseIP(c.vtep)) + if err != nil { + t.Fatalf("rôle %#x, VTEP %s : erreur inattendue %v", c.role, c.vtep, err) + } + if got.String() != c.want { + t.Errorf("rôle %#x, VTEP %s : %s, %s attendu", c.role, c.vtep, got, c.want) + } + } +} + +func TestHostMACIsLocalUnicast(t *testing.T) { + for _, role := range []byte{RoleRouter, RoleHostGateway} { + got, err := HostMAC(role, net.ParseIP("192.168.14.11")) + if err != nil { + t.Fatal(err) + } + if got[0]&0x02 == 0 { + t.Errorf("%s : bit « administrée localement » absent", got) + } + if got[0]&0x01 != 0 { + t.Errorf("%s : MAC de groupe (multicast)", got) + } + } +} + +func TestHostMACRolesDifferOnTheSameHost(t *testing.T) { + if RoleRouter == RoleHostGateway { + t.Fatalf("rôles identiques : %#x", RoleRouter) + } + if RoleRouter != 0x02 || RoleHostGateway != 0x03 { + t.Errorf("rôles %#x / %#x, 0x02 / 0x03 attendus (valeurs publiées dans la doc)", RoleRouter, RoleHostGateway) + } +} + +func TestHostMACRejectsANonIPv4VTEP(t *testing.T) { + for _, vtep := range []net.IP{nil, net.ParseIP("fd00::1")} { + if mac, err := HostMAC(RoleHostGateway, vtep); err == nil { + t.Errorf("VTEP %v accepté : %s", vtep, mac) + } + } +} diff --git a/internal/netif/route_other.go b/internal/netif/route_other.go index 71daec7..dcfd025 100644 --- a/internal/netif/route_other.go +++ b/internal/netif/route_other.go @@ -8,7 +8,7 @@ import ( ) func RouteAdd(_ string, _ *net.IPNet) error { - return nil + return errors.New("not supported on this platform") } func TableRoutesVia(_ int, _ string) ([]*net.IPNet, error) { diff --git a/internal/netif/upDown.go b/internal/netif/upDown.go index 4e9cc61..6d27cc2 100644 --- a/internal/netif/upDown.go +++ b/internal/netif/upDown.go @@ -1,8 +1,6 @@ package netif import ( - "net" - "github.com/vishvananda/netlink" ) @@ -21,11 +19,3 @@ func LinkSetDown(name string) error { } return netlink.LinkSetDown(link) } - -func LinkSetHardwareAddr(name string, mac net.HardwareAddr) error { - link, err := netlink.LinkByName(name) - if err != nil { - return err - } - return netlink.LinkSetHardwareAddr(link, mac) -} diff --git a/internal/subnet/create.go b/internal/subnet/create.go index e70fd47..12d345e 100644 --- a/internal/subnet/create.go +++ b/internal/subnet/create.go @@ -8,10 +8,10 @@ import ( "git.g3e.fr/syonad/two/internal/dhcp" "git.g3e.fr/syonad/two/internal/dhcpbackend" "git.g3e.fr/syonad/two/internal/ebtables" + "git.g3e.fr/syonad/two/internal/l3vni" "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/netns" "git.g3e.fr/syonad/two/internal/state" - "git.g3e.fr/syonad/two/internal/vpc" "github.com/dgraph-io/badger/v4" ) @@ -40,7 +40,7 @@ func CreateSubnet(db *badger.DB, subnetName string, cfg *configuration.Config) e } if d.mode == ModeVxlan { - if err := vpc.ExportRoute(db, d.vpc, d.cidr); err != nil { + if err := l3vni.ExportRoute(db, d.vpc, d.cidr); err != nil { return err } } @@ -80,20 +80,15 @@ func createSubnet(db *badger.DB, subnetName string, d subnetData, backend dhcpba if err != nil { return fmt.Errorf("vtep of %s: %w", d.localIface, err) } - if gatewayMAC, err = hostGatewayMAC(vtep); err != nil { + if gatewayMAC, err = netif.HostMAC(netif.RoleHostGateway, vtep); err != nil { return err } } if err := netns.Call(d.vpc, func() error { - if err := netif.CreateBridge(d.bridge, 1500); err != nil { + if err := netif.CreateBridge(d.bridge, 1500, gatewayMAC); err != nil { return fmt.Errorf("create bridge: %w", err) } - if gatewayMAC != nil { - if err := netif.LinkSetHardwareAddr(d.bridge, gatewayMAC); err != nil { - return fmt.Errorf("set gateway mac %s: %w", gatewayMAC, err) - } - } return netif.BridgeSetMaster(vethI, d.bridge) }); err != nil { return fmt.Errorf("setup bridge in netns: %w", err) @@ -146,7 +141,7 @@ func createSubnet(db *badger.DB, subnetName string, d subnetData, backend dhcpba func setupVxlanHost(d subnetData, vethE string) error { vxlanIface := fmt.Sprintf("vxlan-%d", d.vxlanID) - if err := netif.CreateBridge(d.bridge, 1500); 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, 1500); err != nil { diff --git a/internal/subnet/delete.go b/internal/subnet/delete.go index 8ad0b3d..8ee4d78 100644 --- a/internal/subnet/delete.go +++ b/internal/subnet/delete.go @@ -6,10 +6,10 @@ import ( configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/dhcpbackend" "git.g3e.fr/syonad/two/internal/ebtables" + "git.g3e.fr/syonad/two/internal/l3vni" "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/netns" "git.g3e.fr/syonad/two/internal/state" - "git.g3e.fr/syonad/two/internal/vpc" "git.g3e.fr/syonad/two/pkg/db/kv" "github.com/dgraph-io/badger/v4" @@ -35,7 +35,7 @@ func DeleteSubnet(db *badger.DB, subnetName string, cfg *configuration.Config) e } if d.mode == ModeVxlan { - if err := vpc.WithdrawRoute(db, d.vpc, d.cidr); err != nil { + if err := l3vni.WithdrawRoute(db, d.vpc, d.cidr); err != nil { return err } } diff --git a/internal/subnet/gateway.go b/internal/subnet/gateway.go deleted file mode 100644 index 4d3c37a..0000000 --- a/internal/subnet/gateway.go +++ /dev/null @@ -1,19 +0,0 @@ -package subnet - -import ( - "fmt" - "net" -) - -const ( - roleHostGateway = 0x03 - locallyAdministered = 0x02 -) - -func hostGatewayMAC(vtep net.IP) (net.HardwareAddr, error) { - ip := vtep.To4() - if ip == nil { - return nil, fmt.Errorf("vtep %v is not an IPv4 address", vtep) - } - return net.HardwareAddr{locallyAdministered, roleHostGateway, ip[0], ip[1], ip[2], ip[3]}, nil -} diff --git a/internal/subnet/gateway_test.go b/internal/subnet/gateway_test.go deleted file mode 100644 index 55f7c8b..0000000 --- a/internal/subnet/gateway_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package subnet - -import ( - "net" - "testing" -) - -func TestHostGatewayMAC(t *testing.T) { - cases := map[string]string{ - "192.168.14.11": "02:03:c0:a8:0e:0b", - "192.168.14.12": "02:03:c0:a8:0e:0c", - "10.0.0.1": "02:03:0a:00:00:01", - } - for vtep, want := range cases { - got, err := hostGatewayMAC(net.ParseIP(vtep)) - if err != nil { - t.Fatalf("VTEP %s : erreur inattendue %v", vtep, err) - } - if got.String() != want { - t.Errorf("VTEP %s : %s, %s attendu", vtep, got, want) - } - } -} - -func TestHostGatewayMACIsLocalUnicast(t *testing.T) { - got, err := hostGatewayMAC(net.ParseIP("192.168.14.11")) - if err != nil { - t.Fatal(err) - } - if got[0]&0x02 == 0 { - t.Errorf("%s : bit « administrée localement » absent", got) - } - if got[0]&0x01 != 0 { - t.Errorf("%s : MAC de groupe (multicast)", got) - } -} - -func TestHostGatewayMACDiffersFromTheRouterMACOfTheSameHost(t *testing.T) { - got, _ := hostGatewayMAC(net.ParseIP("192.168.14.11")) - if got.String() == "02:02:c0:a8:0e:0b" { - t.Errorf("%s : même MAC que la RMAC du L3VNI de cet hôte", got) - } -} - -func TestHostGatewayMACRejectsANonIPv4VTEP(t *testing.T) { - for _, vtep := range []net.IP{nil, net.ParseIP("fd00::1")} { - if mac, err := hostGatewayMAC(vtep); err == nil { - t.Errorf("VTEP %v accepté : %s", vtep, mac) - } - } -} diff --git a/internal/vm/create.go b/internal/vm/create.go index 1896b81..1318750 100644 --- a/internal/vm/create.go +++ b/internal/vm/create.go @@ -10,12 +10,12 @@ import ( configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/dhcpbackend" "git.g3e.fr/syonad/two/internal/iptables" + "git.g3e.fr/syonad/two/internal/l3vni" "git.g3e.fr/syonad/two/internal/metadata" "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/netns" "git.g3e.fr/syonad/two/internal/qemu" "git.g3e.fr/syonad/two/internal/state" - "git.g3e.fr/syonad/two/internal/vpc" "github.com/dgraph-io/badger/v4" ) @@ -112,7 +112,7 @@ func StartVM(db *badger.DB, name string, cfg *configuration.Config) error { return fmt.Errorf("start qemu: %w", err) } - if err := applyHostRoutes(db, d, vpc.ExportRoute); err != nil { + if err := applyHostRoutes(db, d, l3vni.ExportRoute); err != nil { return err } diff --git a/internal/vm/delete.go b/internal/vm/delete.go index 12651fb..304a75d 100644 --- a/internal/vm/delete.go +++ b/internal/vm/delete.go @@ -9,12 +9,12 @@ import ( configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/dhcpbackend" "git.g3e.fr/syonad/two/internal/iptables" + "git.g3e.fr/syonad/two/internal/l3vni" "git.g3e.fr/syonad/two/internal/metadata" "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/netns" "git.g3e.fr/syonad/two/internal/qmp" "git.g3e.fr/syonad/two/internal/state" - "git.g3e.fr/syonad/two/internal/vpc" "github.com/dgraph-io/badger/v4" ) @@ -39,7 +39,7 @@ func StopVM(db *badger.DB, name string, cfg *configuration.Config) error { return err } - if err := applyHostRoutes(db, d, vpc.WithdrawRoute); err != nil { + if err := applyHostRoutes(db, d, l3vni.WithdrawRoute); err != nil { return err } diff --git a/internal/vpc/create.go b/internal/vpc/create.go index a7f5b24..c0377bf 100644 --- a/internal/vpc/create.go +++ b/internal/vpc/create.go @@ -4,6 +4,7 @@ import ( "strings" 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/netns" "git.g3e.fr/syonad/two/internal/state" @@ -26,7 +27,7 @@ func CreateVPC(db *badger.DB, name string, cfg *configuration.Config) error { } if err := netns.Call(name, func() error { - return netif.CreateBridge("br-public", 1500) + return netif.CreateBridge("br-public", 1500, nil) }); err != nil { return err } @@ -49,15 +50,9 @@ func CreateVPC(db *badger.DB, name string, cfg *configuration.Config) error { }); err != nil { return err } - l3, ok, err := loadL3(db, name, vpcID) - if err != nil { + if err := l3vni.Create(db, name, cfg); err != nil { return err } - if ok { - if err := createL3(newSystem(), cfg, l3); err != nil { - return err - } - } return state.Set(db, "vpc/"+name, state.Running) } return nil diff --git a/internal/vpc/delete.go b/internal/vpc/delete.go index 66d6d7a..d26a052 100644 --- a/internal/vpc/delete.go +++ b/internal/vpc/delete.go @@ -3,7 +3,7 @@ package vpc import ( "strings" - 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/netns" "git.g3e.fr/syonad/two/internal/state" @@ -11,21 +11,15 @@ import ( "github.com/dgraph-io/badger/v4" ) -func DeleteVPC(db *badger.DB, name string, cfg *configuration.Config) error { +func DeleteVPC(db *badger.DB, name string) error { if current, err := state.Get(db, "vpc/"+name); err != nil { return err } else if current == state.Deleting { vpcID := strings.SplitN(name, "-", 2)[1] - l3, ok, err := loadL3(db, name, vpcID) - if err != nil { + if err := l3vni.Delete(db, name); err != nil { return err } - if ok { - if err := deleteL3(newSystem(), cfg, l3); err != nil { - return err - } - } if err := netif.DeleteLink("vp-" + vpcID + "-e"); err != nil { return err diff --git a/internal/vpc/l3vni.go b/internal/vpc/l3vni.go deleted file mode 100644 index eddf26d..0000000 --- a/internal/vpc/l3vni.go +++ /dev/null @@ -1,15 +0,0 @@ -package vpc - -import "fmt" - -const maxL3VNI = 1<<24 - 1 - -func ValidL3VNI(id uint32) error { - if id == 0 || id > maxL3VNI { - return fmt.Errorf("l3vni %d does not fit in 24 bits (1-%d)", id, maxL3VNI) - } - if id >= 253 && id <= 255 { - return fmt.Errorf("l3vni %d is reserved: it is also the routing table id, and tables 253-255 belong to the kernel", id) - } - return nil -} diff --git a/internal/vpc/l3vni_test.go b/internal/vpc/l3vni_test.go deleted file mode 100644 index c93c86c..0000000 --- a/internal/vpc/l3vni_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package vpc - -import ( - "strings" - "testing" -) - -func TestValidL3VNI_AcceptsEvery24BitValueOutsideTheKernelTables(t *testing.T) { - for _, id := range []uint32{1, 252, 256, 4001, 16777215} { - if err := ValidL3VNI(id); err != nil { - t.Errorf("ValidL3VNI(%d) = %v", id, err) - } - } -} - -func TestValidL3VNI_RejectsOutOfRangeAndReservedTables(t *testing.T) { - cases := map[uint32]string{ - 0: "does not fit in 24 bits", - 16777216: "does not fit in 24 bits", - 253: "is reserved", - 254: "is reserved", - 255: "is reserved", - } - for id, want := range cases { - if err := ValidL3VNI(id); err == nil || !strings.Contains(err.Error(), want) { - t.Errorf("ValidL3VNI(%d) = %v, attendu %q", id, err, want) - } - } -} diff --git a/internal/watchdog/check_l3.go b/internal/watchdog/check_l3.go index 537cf29..0fee453 100644 --- a/internal/watchdog/check_l3.go +++ b/internal/watchdog/check_l3.go @@ -8,10 +8,10 @@ import ( configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/frr" + "git.g3e.fr/syonad/two/internal/l3vni" "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/netns" "git.g3e.fr/syonad/two/internal/state" - "git.g3e.fr/syonad/two/internal/vpc" "git.g3e.fr/syonad/two/internal/watchdog/notify" "git.g3e.fr/syonad/two/pkg/db/kv" @@ -91,7 +91,7 @@ func CheckL3VPCs(db *badger.DB, cfg *configuration.Config, p l3Probe, n notify.N if st, err := state.Get(db, prefixVPC+name); err != nil || st != state.Running { continue } - r, ok, err := vpc.LoadRouting(db, name) + r, ok, err := l3vni.LoadRouting(db, name) if err != nil { n.Notify(kindVPC, name, err.Error()) continue @@ -117,7 +117,7 @@ func expectedRouterMAC(cfg *configuration.Config, p l3Probe, n notify.Notifier) n.Notify(kindBGP, "vtep", fmt.Sprintf("vtep address unreadable on %s: %v", cfg.DefaultInterface, err)) return "unknown" } - mac, err := vpc.RouterMAC(vtep) + mac, err := l3vni.RouterMAC(vtep) if err != nil { n.Notify(kindBGP, "vtep", err.Error()) return "unknown" @@ -125,7 +125,7 @@ func expectedRouterMAC(cfg *configuration.Config, p l3Probe, n notify.Notifier) return mac.String() } -func checkL3VPC(db *badger.DB, name string, r vpc.Routing, rmac string, p l3Probe, n notify.Notifier) { +func checkL3VPC(db *badger.DB, name string, r l3vni.Routing, rmac string, p l3Probe, n notify.Notifier) { for _, iface := range []string{r.VRF, r.Bridge, r.Vxlan, r.VethHost} { if problem := p.LinkProblem("", iface); problem != "" { n.Notify(kindVPC, name, problem) diff --git a/release_notes/0.2.0.md b/release_notes/0.2.0.md index a552911..950937e 100644 --- a/release_notes/0.2.0.md +++ b/release_notes/0.2.0.md @@ -34,9 +34,10 @@ L3VNI, avec une configuration BGP pilotée par l'agent ; documentation du projet **Routage inter-subnet entre hyperviseurs : L3VNI (#41)** -- Nouveau champ facultatif `l3vni` sur `POST /vpcs` (1 à 16777215, sauf 253-255 : c'est aussi - l'identifiant de la table de routage). Absent, le VPC se comporte comme avant. Une L3VNI déjà - portée par un VPC de l'agent est refusée (409), comme un `l3vni` demandé sans section `bgp` +- Nouveau champ facultatif `l3vni` sur `POST /vpcs` (1 à 65535, sauf 253-255 : c'est aussi + l'identifiant de la table de routage, et le numéro du RD `:`, sur 16 bits). + Absent, le VPC se comporte comme avant. Une L3VNI déjà portée par un VPC de l'agent est refusée + (409), comme un `l3vni` demandé sans section `bgp` - Pour un VPC routé, l'agent pose sur l'hyperviseur une VRF (table = L3VNI), un bridge à la MAC de routeur `02:02:`, le VXLAN de la L3VNI, un lien de transit `169.254.0.1/30` ↔ `169.254.0.2/30` vers le netns et la route du `cidr` du VPC dans le netns ; FRR reçoit la VRF, diff --git a/scripts/lab-host.sh b/scripts/lab-host.sh index 77ab32d..5072f5f 100755 --- a/scripts/lab-host.sh +++ b/scripts/lab-host.sh @@ -175,14 +175,18 @@ build_request () { } lab_servers () { - local JSON Z ALL="[]" + local JSON Z ALL="[]" RC=0 for Z in ${ZONES}; do - JSON=$(api GET "/baremetal/v1/zones/${Z}/servers?project_id=${PROJECT_ID}&tags=${LAB_TAG}&page_size=100") \ - || return 1 + if ! JSON=$(api GET "/baremetal/v1/zones/${Z}/servers?project_id=${PROJECT_ID}&tags=${LAB_TAG}&page_size=100"); then + warn "zone ${Z} : liste des serveurs de lab indisponible" + RC=1 + continue + fi ALL=$(jq -c --argjson all "${ALL}" --arg p "${PROJECT_ID}" --arg t "${LAB_TAG}" --arg z "${Z}" \ '$all + [.servers[] | select(.project_id == $p and (.tags | index($t))) | . + {zone: $z}]' <<< "${JSON}") done printf '%s\n' "${ALL}" + return "${RC}" } server_ip () { @@ -279,7 +283,8 @@ require_no_lab_server () { report_uncertain_creation () { local FOUND - if FOUND=$(lab_servers) && [[ $(jq 'length' <<< "${FOUND}") -gt 0 ]]; then + FOUND=$(lab_servers) + if [[ $(jq 'length' <<< "${FOUND}") -gt 0 ]]; then warn "un serveur de lab existe bien : $(jq -r '[.[].id] | join(", ")' <<< "${FOUND}")" fi die "création incertaine : le serveur a pu être créé et être facturé ; '${0##*/} status' puis '${0##*/} down'" @@ -312,13 +317,14 @@ cmd_up () { } cmd_status () { - local SERVERS - SERVERS=$(lab_servers) || die "impossible de lister les serveurs de lab" + local SERVERS RC=0 + SERVERS=$(lab_servers) || RC=1 if [[ $(jq 'length' <<< "${SERVERS}") -eq 0 ]]; then - info "aucun serveur de lab dans le projet ${PROJECT_ID} (${ZONES})" - return 0 + [[ "${RC}" -eq 0 ]] && info "aucun serveur de lab dans le projet ${PROJECT_ID} (${ZONES})" + else + jq -r '.[] | "\(.zone) \(.id) \(.name) \(.offer_name) \(.status) installation \(.install.status // "none") \(.created_at) \([.ips[] | select(.version == "IPv4") | .address] | join(","))"' <<< "${SERVERS}" fi - jq -r '.[] | "\(.zone) \(.id) \(.name) \(.offer_name) \(.status) installation \(.install.status // "none") \(.created_at) \([.ips[] | select(.version == "IPv4") | .address] | join(","))"' <<< "${SERVERS}" + [[ "${RC}" -eq 0 ]] || die "liste incomplète : des serveurs de lab peuvent exister dans les zones en erreur" } require_known_server () { @@ -424,24 +430,24 @@ wait_gone () { lab_server_ids () { local DEADLINE=$(( SECONDS + DELETE_TIMEOUT )) - local SERVERS + local SERVERS="[]" while (( SECONDS < DEADLINE )); do if SERVERS=$(lab_servers); then jq -r '.[] | "\(.zone) \(.id)"' <<< "${SERVERS}" return 0 fi - warn "liste des serveurs de lab indisponible, nouvel essai dans ${POLL_INTERVAL}s" + warn "liste des serveurs de lab incomplète, nouvel essai dans ${POLL_INTERVAL}s" sleep "${POLL_INTERVAL}" done + jq -r '.[] | "\(.zone) \(.id)"' <<< "${SERVERS}" return 1 } cmd_down () { local IDS ID FAILED=0 if ! IDS=$(lab_server_ids); then - warn "impossible de lister les serveurs de lab après ${DELETE_TIMEOUT}s" + warn "liste des serveurs de lab incomplète après ${DELETE_TIMEOUT}s : suppression de ceux qui sont listés" FAILED=1 - IDS="" fi IDS=$(printf '%s\n%s\n' "${IDS}" "${CREATED_ID}" | grep -v '^$' | sort -u) while read -r ZONE ID; do diff --git a/scripts/lab-host_test.sh b/scripts/lab-host_test.sh index 12f44f3..8e8d848 100755 --- a/scripts/lab-host_test.sh +++ b/scripts/lab-host_test.sh @@ -73,6 +73,8 @@ if method == "GET" and path == zone + "/os": if method == "GET" and path == "/iam/v1alpha1/ssh-keys": reply(200, {"ssh_keys": st["keys"], "total_count": len(st["keys"])}) if method == "GET" and path == zone + "/servers": + if st.get("zones", {}).get(zname, {}).get("list_fail"): + reply(503, {"message": "service unavailable"}) if st["list_errors"] > 0: st["list_errors"] -= 1 reply(503, {"message": "service unavailable"}) @@ -470,6 +472,33 @@ test_down_fails_loudly_when_listing_never_works () { teardown } +test_down_deletes_what_answering_zones_list_when_one_zone_fails () { + setup "down : une zone en erreur n'empêche pas de supprimer les serveurs des autres" + mutate ".servers[\"srv-lab\"] = ${LAB_SERVER} | .zones = {\"nl-ams-2\": {list_fail: true}}" + LAB_ZONES="fr-par-1 nl-ams-2" LAB_DELETE_TIMEOUT=1 run_lab down && fail "down a réussi malgré une zone en erreur" + [[ $(remaining) == "foreign-1,foreign-2" ]] || fail "restants : $(remaining)" + grep -q "zone nl-ams-2" "${WORK}/out.log" || fail "zone en erreur non signalée" + grep -q "TOUJOURS FACTURÉ" "${WORK}/out.log" || fail "pas d'alerte de facturation" + teardown +} + +test_status_lists_answering_zones_and_fails_when_one_zone_fails () { + setup "status : liste les zones qui répondent, échoue si une zone est en erreur" + mutate ".servers[\"srv-lab\"] = ${LAB_SERVER} | .zones = {\"nl-ams-2\": {list_fail: true}}" + LAB_ZONES="fr-par-1 nl-ams-2" run_lab status && fail "status a réussi malgré une zone en erreur" + grep -q "^fr-par-1 srv-lab " "${WORK}/out.log" || fail "srv-lab non listé" + grep -q "liste incomplète" "${WORK}/out.log" || fail "liste incomplète non signalée" + teardown +} + +test_up_refuses_when_one_zone_cannot_be_listed () { + setup "up : refus si une zone ne peut pas être listée" + mutate '.zones = {"nl-ams-2": {list_fail: true}} | .progress = [["ready","completed"]]' + LAB_ZONES="fr-par-1 nl-ams-2" run_lab up && fail "up a réussi" + grep -q "^POST" "${WORK}/calls.log" && fail "serveur créé sans connaître toutes les zones" + teardown +} + test_session_deletes_created_server_even_if_missing_from_list () { setup "session : supprime le serveur créé même absent de la liste" mutate '.hide_from_list = true | .progress = [["ready","completed"]]' diff --git a/test/e2e/scenarios/s9-subnets-partages.sh b/test/e2e/scenarios/s9-subnets-partages.sh new file mode 100644 index 0000000..f61776c --- /dev/null +++ b/test/e2e/scenarios/s9-subnets-partages.sh @@ -0,0 +1,45 @@ +for host in hv2 hv3; do +on "${host}" "HOST=${host}" <<'NODE' +two_image || { echo "ÉCHOUÉ: image compatible two (${HOST})"; exit 0; } +KEY=$(vm_key) +case "${HOST}" in hv2) n=1 ;; hv3) n=2 ;; esac +check "${HOST} : VPC vp-s9r, l3vni 2900" vpc_create vp-s9r 10.250.0.0/16 2900 +check "${HOST} : subnet sn-s9r1 (VNI 2911)" subnet_create sn-s9r1 vp-s9r 2911 10.250.1.1 10.250.1.0/24 +check "${HOST} : subnet sn-s9r2 (VNI 2912)" subnet_create sn-s9r2 vp-s9r 2912 10.250.2.1 10.250.2.0/24 +check "${HOST} : VM s9-r1-${n} 10.250.1.1${n}" vm_create "s9-r1-${n}" sn-s9r1 "10.250.1.1${n}" "${KEY}" +check "${HOST} : VM s9-r2-${n} 10.250.2.1${n}" vm_create "s9-r2-${n}" sn-s9r2 "10.250.2.1${n}" "${KEY}" +check "${HOST} : VPC vp-s9n, sans l3vni" vpc_create vp-s9n 10.251.0.0/16 +check "${HOST} : subnet sn-s9n1 (VNI 2921)" subnet_create sn-s9n1 vp-s9n 2921 10.251.1.1 10.251.1.0/24 +check "${HOST} : subnet sn-s9n2 (VNI 2922)" subnet_create sn-s9n2 vp-s9n 2922 10.251.2.1 10.251.2.0/24 +check "${HOST} : VM s9-n1-${n} 10.251.1.1${n}" vm_create "s9-n1-${n}" sn-s9n1 "10.251.1.1${n}" "${KEY}" +check "${HOST} : VM s9-n2-${n} 10.251.2.1${n}" vm_create "s9-n2-${n}" sn-s9n2 "10.251.2.1${n}" "${KEY}" +NODE +done + +for host in hv2 hv3; do +on "${host}" "HOST=${host}" <<'NODE' +case "${HOST}" in hv2) n=1; mac=02:03:c0:a8:0e:0c ;; hv3) n=2; mac=02:03:c0:a8:0e:0d ;; esac +for v in r n; do + vpc="vp-s9${v}" + net="10.25$([ "${v}" = r ] && echo 0 || echo 1)" + for s in 1 2; do + src="${net}.${s}.1${n}" + check "${HOST} : ${src} joignable" vm_wait "${vpc}" "${src}" + check "${HOST} : ${src} joint sa gateway ${net}.${s}.1" vm_ssh "${vpc}" "${src}" "ping -n -c 2 -W 2 ${net}.${s}.1" + check "${HOST} : ${src} voit la MAC de gateway de son hôte (${mac})" vm_grep "${vpc}" "${src}" "ip neigh show ${net}.${s}.1" "lladdr ${mac} " + for d in 1 2; do + for m in 1 2; do + dst="${net}.${d}.1${m}" + [ "${dst}" = "${src}" ] && continue + for i in $(seq 1 12); do vm_ssh "${vpc}" "${src}" "ping -n -c 1 -W 2 ${dst}" >/dev/null 2>&1 && break; sleep 5; done + check "${vpc} : ${src} (${HOST}) joint ${dst} ($([ "${d}" = "${s}" ] && echo 'même subnet' || echo 'autre subnet'), $([ "${m}" = "${n}" ] && echo 'même hôte' || echo 'autre hôte'))" \ + vm_ssh "${vpc}" "${src}" "ping -n -c 3 -W 2 ${dst}" + done + done + done +done +for vni in 2911 2912 2921 2922; do + check "${HOST} : aucune MAC en double sur la VNI ${vni}" sh -c "! vtysh -c 'show evpn mac vni ${vni} duplicate' | grep -qiE '([0-9a-f]{2}:){5}[0-9a-f]{2}'" +done +NODE +done diff --git a/test/e2e/topologies/evpn-2hv.yml b/test/e2e/topologies/evpn-2hv.yml index 3faa984..293da21 100644 --- a/test/e2e/topologies/evpn-2hv.yml +++ b/test/e2e/topologies/evpn-2hv.yml @@ -21,9 +21,9 @@ nodes: loopback: 10.255.255.1/32, frr: frr/rr1.conf } hv1: { role: hypervisor, image: debian12, cpus: 4, memory: 16384, segments: [underlay], - addresses: { underlay: 192.168.14.11 }, frr: frr/hv1.conf, release: 0.2.0rc005, + addresses: { underlay: 192.168.14.11 }, frr: frr/hv1.conf, release: 0.2.0rc008, agent: agent/two.yml } hv2: { role: hypervisor, image: debian12, cpus: 4, memory: 16384, segments: [underlay], - addresses: { underlay: 192.168.14.12 }, frr: frr/hv2.conf, release: 0.2.0rc005, + addresses: { underlay: 192.168.14.12 }, frr: frr/hv2.conf, release: 0.2.0rc008, agent: agent/bgp.yml } diff --git a/test/e2e/topologies/evpn-3hv.yml b/test/e2e/topologies/evpn-3hv.yml index b0e794d..7b2893d 100644 --- a/test/e2e/topologies/evpn-3hv.yml +++ b/test/e2e/topologies/evpn-3hv.yml @@ -21,13 +21,13 @@ nodes: loopback: 10.255.255.1/32, frr: frr/rr1.conf } hv1: { role: hypervisor, image: debian12, cpus: 4, memory: 16384, segments: [underlay], - addresses: { underlay: 192.168.14.11 }, frr: frr/hv1.conf, release: 0.2.0rc005, + addresses: { underlay: 192.168.14.11 }, frr: frr/hv1.conf, release: 0.2.0rc008, agent: agent/two.yml } hv2: { role: hypervisor, image: debian12, cpus: 4, memory: 16384, segments: [underlay], - addresses: { underlay: 192.168.14.12 }, frr: frr/hv2.conf, release: 0.2.0rc005, + addresses: { underlay: 192.168.14.12 }, frr: frr/hv2.conf, release: 0.2.0rc008, agent: agent/bgp.yml } hv3: { role: hypervisor, image: debian12, cpus: 4, memory: 16384, segments: [underlay], - addresses: { underlay: 192.168.14.13 }, frr: frr/hv3.conf, release: 0.2.0rc005, + addresses: { underlay: 192.168.14.13 }, frr: frr/hv3.conf, release: 0.2.0rc008, agent: agent/bgp.yml }