From 94c2f82867582a20c5d543eb85563737f0284647 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 6 Oct 2026 14:13:08 +0200 Subject: [PATCH] f-41: frr, sysctl, netif: primitives du L3VNI #41 Signed-off-by: GnomeZworc --- internal/frr/client.go | 107 +++++++++++++++++++ internal/frr/client_test.go | 184 +++++++++++++++++++++++++++++++++ internal/frr/config.go | 129 +++++++++++++++++++++++ internal/frr/config_test.go | 142 +++++++++++++++++++++++++ internal/frr/teardown.go | 84 +++++++++++++++ internal/frr/teardown_test.go | 142 +++++++++++++++++++++++++ internal/netif/addr.go | 8 ++ internal/netif/route.go | 27 +++++ internal/netif/vrf.go | 16 +++ internal/sysctl/sysctl.go | 23 +++++ internal/sysctl/sysctl_test.go | 48 +++++++++ 11 files changed, 910 insertions(+) create mode 100644 internal/frr/client.go create mode 100644 internal/frr/client_test.go create mode 100644 internal/frr/config.go create mode 100644 internal/frr/config_test.go create mode 100644 internal/frr/teardown.go create mode 100644 internal/frr/teardown_test.go create mode 100644 internal/netif/route.go create mode 100644 internal/netif/vrf.go create mode 100644 internal/sysctl/sysctl.go create mode 100644 internal/sysctl/sysctl_test.go diff --git a/internal/frr/client.go b/internal/frr/client.go new file mode 100644 index 0000000..1f76d4e --- /dev/null +++ b/internal/frr/client.go @@ -0,0 +1,107 @@ +package frr + +import ( + "fmt" + "os/exec" + "strings" +) + +type runner func(args ...string) ([]byte, error) + +type Client struct { + run runner +} + +func NewClient() *Client { + return &Client{run: func(args ...string) ([]byte, error) { + return exec.Command("vtysh", args...).CombinedOutput() + }} +} + +func (c *Client) ApplyBase(b Base) error { + if err := b.validate(); err != nil { + return err + } + if err := c.configure(b.commands()...); err != nil { + return err + } + return c.save() +} + +func (c *Client) ApplyVRF(v VRF) error { + if err := v.validate(); err != nil { + return err + } + if err := c.configure(v.commands()...); err != nil { + return err + } + return c.save() +} + +func (c *Client) WithdrawVRF(v VRF) error { + return c.teardown(v, routingTeardown) +} + +func (c *Client) RemoveVRF(v VRF) error { + if err := c.teardown(v, vrfTeardown); err != nil { + return err + } + running, err := c.runningConfig() + if err != nil { + return err + } + return remaining(routingTeardown(v, running)) +} + +func (c *Client) teardown(v VRF, plan func(VRF, string) []step) error { + if err := v.validateName(); err != nil { + return err + } + running, err := c.runningConfig() + if err != nil { + return err + } + for _, s := range plan(v, running) { + if err := c.configure(s...); err != nil { + return err + } + } + if err := c.save(); err != nil { + return err + } + if running, err = c.runningConfig(); err != nil { + return err + } + return remaining(plan(v, running)) +} + +func (c *Client) runningConfig() (string, error) { + return c.exec("show running-config") +} + +func (c *Client) configure(cmds ...string) error { + _, err := c.exec(append([]string{"configure terminal"}, cmds...)...) + return err +} + +func (c *Client) save() error { + _, err := c.exec("write memory") + return err +} + +func (c *Client) exec(cmds ...string) (string, error) { + args := make([]string, 0, 2*len(cmds)) + for _, cmd := range cmds { + args = append(args, "-c", cmd) + } + out, err := c.run(args...) + if err != nil { + return "", fmt.Errorf("vtysh %q: %w: %s", cmds, err, strings.TrimSpace(string(out))) + } + for _, l := range strings.Split(string(out), "\n") { + if strings.HasPrefix(strings.TrimSpace(l), "%") { + return "", fmt.Errorf("vtysh %q: %s", cmds, strings.TrimSpace(l)) + } + } + return string(out), nil +} diff --git a/internal/frr/client_test.go b/internal/frr/client_test.go new file mode 100644 index 0000000..d48ba4d --- /dev/null +++ b/internal/frr/client_test.go @@ -0,0 +1,184 @@ +package frr + +import ( + "errors" + "net" + "reflect" + "strings" + "testing" +) + +type fakeVtysh struct { + calls [][]string + running []string + fail map[string]string + status map[string]error +} + +func (f *fakeVtysh) run(args ...string) ([]byte, error) { + var cmds []string + for i := 1; i < len(args); i += 2 { + cmds = append(cmds, args[i]) + } + f.calls = append(f.calls, cmds) + last := cmds[len(cmds)-1] + if last == "show running-config" { + if len(f.running) == 0 { + return nil, errors.New("show running-config inattendu") + } + out := f.running[0] + f.running = f.running[1:] + return []byte(out), nil + } + for _, c := range cmds { + if out, ok := f.fail[c]; ok { + return []byte(out), f.status[c] + } + } + return nil, nil +} + +func (f *fakeVtysh) client() *Client { + return &Client{run: f.run} +} + +func (f *fakeVtysh) sent(cmd string) bool { + for _, c := range f.calls { + for _, x := range c { + if x == cmd { + return true + } + } + } + return false +} + +func TestApplyVRFConfiguresThenSaves(t *testing.T) { + f := &fakeVtysh{} + if err := f.client().ApplyVRF(labVRF(t)); err != nil { + t.Fatal(err) + } + want := [][]string{ + append([]string{"configure terminal"}, labVRF(t).commands()...), + {"write memory"}, + } + if !reflect.DeepEqual(f.calls, want) { + t.Errorf("appels :\n%q\nattendu :\n%q", f.calls, want) + } +} + +func TestApplyVRFRefusesAnInvalidVRFWithoutCallingVtysh(t *testing.T) { + f := &fakeVtysh{} + v := labVRF(t) + v.L3VNI = 0 + if err := f.client().ApplyVRF(v); err == nil || !strings.Contains(err.Error(), "l3vni 0") { + t.Errorf("erreur %v", err) + } + if len(f.calls) != 0 { + t.Errorf("vtysh appelé : %q", f.calls) + } +} + +func TestApplyBaseConfiguresThenSaves(t *testing.T) { + f := &fakeVtysh{} + b := Base{ASN: 64600, RouterID: labVRF(t).VTEP, RouteReflectors: []net.IP{net.ParseIP("10.255.255.1")}} + if err := f.client().ApplyBase(b); err != nil { + t.Fatal(err) + } + if len(f.calls) != 2 || f.calls[0][0] != "configure terminal" || f.calls[0][1] != "router bgp 64600" || f.calls[1][0] != "write memory" { + t.Errorf("appels : %q", f.calls) + } +} + +func TestExecReportsAnErrorPrintedByVtysh(t *testing.T) { + f := &fakeVtysh{fail: map[string]string{"vni 4001": "% Please unconfigure l3vni 4001\n"}} + err := f.client().ApplyVRF(labVRF(t)) + if err == nil || !strings.Contains(err.Error(), "% Please unconfigure l3vni 4001") { + t.Errorf("erreur %v", err) + } + if f.sent("write memory") { + t.Error("configuration sauvegardée malgré l'erreur") + } +} + +func TestExecReportsANonZeroExit(t *testing.T) { + f := &fakeVtysh{ + fail: map[string]string{"write memory": "Building Configuration...\n"}, + status: map[string]error{"write memory": errors.New("exit status 1")}, + } + err := f.client().ApplyVRF(labVRF(t)) + if err == nil || !strings.Contains(err.Error(), "exit status 1") || !strings.Contains(err.Error(), "Building Configuration...") { + t.Errorf("erreur %v", err) + } +} + +func TestWithdrawVRFRunsEachStepInOrderThenSaves(t *testing.T) { + f := &fakeVtysh{running: []string{fullRunning, otherOnlyRunning}} + if err := f.client().WithdrawVRF(labVRF(t)); err != nil { + t.Fatal(err) + } + want := [][]string{ + {"show running-config"}, + {"configure terminal", "router bgp 64600 vrf vrf-a1b2", "address-family ipv4 unicast", "no redistribute kernel"}, + {"configure terminal", "vrf vrf-a1b2", "no vni 4001"}, + {"configure terminal", "no router bgp 64600 vrf vrf-a1b2"}, + {"configure terminal", "no route-map EXPORT-a1b2"}, + {"configure terminal", "no ip prefix-list PL-a1b2"}, + {"write memory"}, + {"show running-config"}, + } + if !reflect.DeepEqual(f.calls, want) { + t.Errorf("appels :\n%q\nattendu :\n%q", f.calls, want) + } +} + +func TestWithdrawVRFStopsAtTheFirstRefusedStep(t *testing.T) { + f := &fakeVtysh{ + running: []string{fullRunning}, + fail: map[string]string{"no vni 4001": "% Please unconfigure l3vni 4001\n"}, + } + if err := f.client().WithdrawVRF(labVRF(t)); err == nil || !strings.Contains(err.Error(), "Please unconfigure") { + t.Errorf("erreur %v", err) + } + if f.sent("no router bgp 64600 vrf vrf-a1b2") { + t.Error("instance BGP supprimée après un refus de l'étape précédente") + } +} + +func TestWithdrawVRFFailsWhenFRRKeptTheConfiguration(t *testing.T) { + f := &fakeVtysh{running: []string{fullRunning, fullRunning}} + err := f.client().WithdrawVRF(labVRF(t)) + if err == nil || !strings.Contains(err.Error(), "configuration still present after teardown") || !strings.Contains(err.Error(), "no router bgp 64600 vrf vrf-a1b2") { + t.Errorf("erreur %v", err) + } +} + +func TestRemoveVRFDeletesTheVRFAndChecksNothingIsLeft(t *testing.T) { + gone := "vrf vrf-a1b2c\n vni 4002\nexit-vrf\n" + f := &fakeVtysh{running: []string{otherOnlyRunning, gone, gone}} + if err := f.client().RemoveVRF(labVRF(t)); err != nil { + t.Fatal(err) + } + if !f.sent("no vrf vrf-a1b2") { + t.Errorf("appels : %q", f.calls) + } +} + +func TestRemoveVRFFailsWhenRoutingConfigurationIsStillThere(t *testing.T) { + f := &fakeVtysh{running: []string{otherOnlyRunning, "", fullRunning}} + err := f.client().RemoveVRF(labVRF(t)) + if err == nil || !strings.Contains(err.Error(), "configuration still present after teardown") { + t.Errorf("erreur %v", err) + } +} + +func TestTeardownNeedsOnlyTheASNAndTheID(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) + } + f = &fakeVtysh{} + if err := f.client().WithdrawVRF(VRF{ASN: 64600}); err == nil || len(f.calls) != 0 { + t.Errorf("démontage sans id : erreur %v, appels %q", err, f.calls) + } +} diff --git a/internal/frr/config.go b/internal/frr/config.go new file mode 100644 index 0000000..10cdd4d --- /dev/null +++ b/internal/frr/config.go @@ -0,0 +1,129 @@ +package frr + +import ( + "fmt" + "net" +) + +const maxVNI = 1<<24 - 1 + +type Base struct { + ASN uint32 + RouterID net.IP + RouteReflectors []net.IP +} + +type VRF struct { + ASN uint32 + ID string + L3VNI uint32 + VTEP net.IP + Supernet *net.IPNet +} + +func (b Base) validate() error { + if b.ASN == 0 { + return fmt.Errorf("frr: asn must not be 0") + } + if b.RouterID.To4() == nil { + return fmt.Errorf("frr: router-id %v is not an IPv4 address", b.RouterID) + } + if len(b.RouteReflectors) == 0 { + return fmt.Errorf("frr: at least one route reflector is required") + } + for _, rr := range b.RouteReflectors { + if rr.To4() == nil { + return fmt.Errorf("frr: route reflector %v is not an IPv4 address", rr) + } + } + return nil +} + +func (b Base) commands() []string { + cmds := []string{ + fmt.Sprintf("router bgp %d", b.ASN), + fmt.Sprintf("bgp router-id %s", b.RouterID), + "no bgp default ipv4-unicast", + "neighbor fabric peer-group", + fmt.Sprintf("neighbor fabric remote-as %d", b.ASN), + "neighbor fabric capability extended-nexthop", + } + for _, rr := range b.RouteReflectors { + cmds = append(cmds, fmt.Sprintf("neighbor %s peer-group fabric", rr)) + } + return append(cmds, + "address-family l2vpn evpn", + "neighbor fabric activate", + "advertise-all-vni", + "exit-address-family", + "exit", + ) +} + +func (v VRF) Name() string { + return "vrf-" + v.ID +} + +func (v VRF) prefixList() string { + return "PL-" + v.ID +} + +func (v VRF) routeMap() string { + return "EXPORT-" + v.ID +} + +func (v VRF) bgpInstance() string { + return fmt.Sprintf("router bgp %d vrf %s", v.ASN, v.Name()) +} + +func (v VRF) validateName() error { + if v.ASN == 0 { + return fmt.Errorf("frr: asn must not be 0") + } + if v.ID == "" { + return fmt.Errorf("frr: vrf id must not be empty") + } + return nil +} + +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.VTEP.To4() == nil { + return fmt.Errorf("frr: vtep %v is not an IPv4 address", v.VTEP) + } + if v.Supernet == nil || v.Supernet.IP.To4() == nil { + return fmt.Errorf("frr: supernet %v is not an IPv4 prefix", v.Supernet) + } + return nil +} + +func (v VRF) commands() []string { + return []string{ + fmt.Sprintf("ip prefix-list %s seq 10 permit %s le 32", v.prefixList(), v.Supernet), + fmt.Sprintf("route-map %s permit 10", v.routeMap()), + fmt.Sprintf("match ip address prefix-list %s", v.prefixList()), + "exit", + fmt.Sprintf("route-map %s deny 20", v.routeMap()), + "exit", + fmt.Sprintf("vrf %s", v.Name()), + fmt.Sprintf("vni %d", v.L3VNI), + "exit-vrf", + v.bgpInstance(), + fmt.Sprintf("bgp router-id %s", v.VTEP), + "no bgp default ipv4-unicast", + "address-family ipv4 unicast", + fmt.Sprintf("redistribute kernel route-map %s", v.routeMap()), + "exit-address-family", + "address-family l2vpn evpn", + fmt.Sprintf("rd %s:%d", v.VTEP, v.L3VNI), + fmt.Sprintf("route-target both %d:%d", v.ASN, v.L3VNI), + "advertise ipv4 unicast", + "exit-address-family", + "exit", + } +} diff --git a/internal/frr/config_test.go b/internal/frr/config_test.go new file mode 100644 index 0000000..ac30a87 --- /dev/null +++ b/internal/frr/config_test.go @@ -0,0 +1,142 @@ +package frr + +import ( + "net" + "reflect" + "strings" + "testing" +) + +func mustCIDR(t *testing.T, s string) *net.IPNet { + t.Helper() + _, n, err := net.ParseCIDR(s) + if err != nil { + t.Fatal(err) + } + return n +} + +func labVRF(t *testing.T) VRF { + return VRF{ + ASN: 64600, + ID: "a1b2", + L3VNI: 4001, + VTEP: net.ParseIP("192.168.14.11"), + Supernet: mustCIDR(t, "10.10.0.0/16"), + } +} + +func TestBaseCommands(t *testing.T) { + b := Base{ + ASN: 64600, + RouterID: net.ParseIP("192.168.14.13"), + RouteReflectors: []net.IP{net.ParseIP("10.255.255.1"), net.ParseIP("10.255.255.2")}, + } + want := []string{ + "router bgp 64600", + "bgp router-id 192.168.14.13", + "no bgp default ipv4-unicast", + "neighbor fabric peer-group", + "neighbor fabric remote-as 64600", + "neighbor fabric capability extended-nexthop", + "neighbor 10.255.255.1 peer-group fabric", + "neighbor 10.255.255.2 peer-group fabric", + "address-family l2vpn evpn", + "neighbor fabric activate", + "advertise-all-vni", + "exit-address-family", + "exit", + } + if got := b.commands(); !reflect.DeepEqual(got, want) { + t.Errorf("commandes de base :\n%s\nattendu :\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} + +func TestVRFCommands(t *testing.T) { + want := []string{ + "ip prefix-list PL-a1b2 seq 10 permit 10.10.0.0/16 le 32", + "route-map EXPORT-a1b2 permit 10", + "match ip address prefix-list PL-a1b2", + "exit", + "route-map EXPORT-a1b2 deny 20", + "exit", + "vrf vrf-a1b2", + "vni 4001", + "exit-vrf", + "router bgp 64600 vrf vrf-a1b2", + "bgp router-id 192.168.14.11", + "no bgp default ipv4-unicast", + "address-family ipv4 unicast", + "redistribute kernel route-map EXPORT-a1b2", + "exit-address-family", + "address-family l2vpn evpn", + "rd 192.168.14.11:4001", + "route-target both 64600:4001", + "advertise ipv4 unicast", + "exit-address-family", + "exit", + } + if got := labVRF(t).commands(); !reflect.DeepEqual(got, want) { + t.Errorf("commandes de VRF :\n%s\nattendu :\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} + +func TestBaseValidateRejects(t *testing.T) { + valid := func() Base { + return Base{ASN: 64600, RouterID: net.ParseIP("192.168.14.13"), RouteReflectors: []net.IP{net.ParseIP("10.255.255.1")}} + } + if err := valid().validate(); err != nil { + t.Fatalf("base valide refusée : %v", err) + } + cases := map[string]struct { + mutate func(*Base) + msg string + }{ + "asn nul": {func(b *Base) { b.ASN = 0 }, "asn must not be 0"}, + "router-id absent": {func(b *Base) { b.RouterID = nil }, "router-id is not an IPv4 address"}, + "router-id IPv6": {func(b *Base) { b.RouterID = net.ParseIP("fd00::1") }, "router-id fd00::1 is not an IPv4 address"}, + "aucun RR": {func(b *Base) { b.RouteReflectors = nil }, "at least one route reflector is required"}, + "RR IPv6": {func(b *Base) { b.RouteReflectors = append(b.RouteReflectors, net.ParseIP("fd00::2")) }, "route reflector fd00::2 is not an IPv4 address"}, + } + for name, c := range cases { + b := valid() + c.mutate(&b) + if err := b.validate(); err == nil || !strings.Contains(err.Error(), c.msg) { + t.Errorf("%s : erreur %v, « %s » attendu", name, err, c.msg) + } + } +} + +func TestVRFValidateRejects(t *testing.T) { + if err := labVRF(t).validate(); err != nil { + t.Fatalf("VRF valide refusée : %v", err) + } + cases := map[string]struct { + mutate func(*VRF) + msg string + }{ + "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"}, + "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"}, + "supernet IPv6": {func(v *VRF) { v.Supernet = mustCIDR(t, "fd00::/48") }, "supernet fd00::/48 is not an IPv4 prefix"}, + } + for name, c := range cases { + v := labVRF(t) + c.mutate(&v) + if err := v.validate(); err == nil || !strings.Contains(err.Error(), c.msg) { + t.Errorf("%s : erreur %v, « %s » attendu", name, err, c.msg) + } + } +} + +func TestVRFAcceptsTheLargest24BitVNI(t *testing.T) { + v := labVRF(t) + v.L3VNI = 16777215 + if err := v.validate(); err != nil { + t.Errorf("l3vni 16777215 refusée : %v", err) + } +} diff --git a/internal/frr/teardown.go b/internal/frr/teardown.go new file mode 100644 index 0000000..bcdd18d --- /dev/null +++ b/internal/frr/teardown.go @@ -0,0 +1,84 @@ +package frr + +import ( + "fmt" + "strings" +) + +type step []string + +func routingTeardown(v VRF, running string) []step { + lines := strings.Split(running, "\n") + bgp := hasLine(lines, v.bgpInstance()) + var steps []step + if bgp { + steps = append(steps, step{v.bgpInstance(), "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()}) + } + if hasPrefix(lines, "route-map "+v.routeMap()+" ") { + steps = append(steps, step{"no route-map " + v.routeMap()}) + } + if hasPrefix(lines, "ip prefix-list "+v.prefixList()+" ") { + steps = append(steps, step{"no ip prefix-list " + v.prefixList()}) + } + return steps +} + +func vrfTeardown(v VRF, running string) []step { + if hasLine(strings.Split(running, "\n"), "vrf "+v.Name()) { + return []step{{"no vrf " + v.Name()}} + } + return nil +} + +func hasLine(lines []string, want string) bool { + for _, l := range lines { + if strings.TrimRight(l, " \r") == want { + return true + } + } + return false +} + +func hasPrefix(lines []string, prefix string) bool { + for _, l := range lines { + if strings.HasPrefix(l, prefix) { + return true + } + } + return false +} + +func vrfVNI(lines []string, name string) string { + in := false + for _, l := range lines { + l = strings.TrimRight(l, " \r") + switch { + case l == "vrf "+name: + in = true + case in && l == "exit-vrf": + return "" + case in: + if f := strings.Fields(l); len(f) >= 2 && f[0] == "vni" { + return f[1] + } + } + } + return "" +} + +func remaining(steps []step) error { + if len(steps) == 0 { + return nil + } + var parts []string + for _, s := range steps { + parts = append(parts, strings.Join(s, " / ")) + } + return fmt.Errorf("configuration still present after teardown: %s", strings.Join(parts, "; ")) +} diff --git a/internal/frr/teardown_test.go b/internal/frr/teardown_test.go new file mode 100644 index 0000000..cd27049 --- /dev/null +++ b/internal/frr/teardown_test.go @@ -0,0 +1,142 @@ +package frr + +import ( + "reflect" + "testing" +) + +const fullRunning = `frr version 10.7.1 +frr defaults traditional +hostname hv1 +! +vrf vrf-a1b2 + vni 4001 +exit-vrf +! +vrf vrf-a1b2c + vni 4002 +exit-vrf +! +router bgp 64600 + bgp router-id 192.168.14.11 + no bgp default ipv4-unicast + neighbor fabric peer-group + neighbor fabric remote-as 64600 + neighbor 10.255.255.1 peer-group fabric + ! + address-family l2vpn evpn + neighbor fabric activate + advertise-all-vni + exit-address-family +exit +! +router bgp 64600 vrf vrf-a1b2 + bgp router-id 192.168.14.11 + no bgp default ipv4-unicast + ! + address-family ipv4 unicast + redistribute kernel route-map EXPORT-a1b2 + exit-address-family + ! + address-family l2vpn evpn + advertise ipv4 unicast + rd 192.168.14.11:4001 + route-target import 64600:4001 + route-target export 64600:4001 + exit-address-family +exit +! +router bgp 64600 vrf vrf-a1b2c + bgp router-id 192.168.14.11 +exit +! +ip prefix-list PL-a1b2 seq 10 permit 10.10.0.0/16 le 32 +ip prefix-list PL-a1b2c seq 10 permit 10.20.0.0/16 le 32 +! +route-map EXPORT-a1b2 permit 10 + match ip address prefix-list PL-a1b2 +exit +! +route-map EXPORT-a1b2 deny 20 +exit +! +route-map EXPORT-a1b2c permit 10 +exit +! +end +` + +const otherOnlyRunning = `vrf vrf-a1b2 +exit-vrf +! +vrf vrf-a1b2c + vni 4002 +exit-vrf +! +router bgp 64600 vrf vrf-a1b2c +exit +! +ip prefix-list PL-a1b2c seq 10 permit 10.20.0.0/16 le 32 +! +route-map EXPORT-a1b2c permit 10 +exit +! +end +` + +func TestRoutingTeardownFollowsTheOrderFRRRequires(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"}, + } + if got := routingTeardown(labVRF(t), fullRunning); !reflect.DeepEqual(got, want) { + t.Errorf("démontage :\n%q\nattendu :\n%q", got, want) + } +} + +func TestRoutingTeardownIgnoresAVRFWhoseNameExtendsOurs(t *testing.T) { + if got := routingTeardown(labVRF(t), otherOnlyRunning); got != nil { + t.Errorf("étapes visant vrf-a1b2c : %q", got) + } +} + +func TestRoutingTeardownUsesTheVNIFoundInFRR(t *testing.T) { + v := labVRF(t) + v.L3VNI = 9999 + running := "vrf vrf-a1b2\n vni 4001\nexit-vrf\n" + want := []step{{"vrf vrf-a1b2", "no vni 4001"}} + if got := routingTeardown(v, running); !reflect.DeepEqual(got, want) { + t.Errorf("démontage : %q, %q attendu", got, want) + } +} + +func TestRoutingTeardownSkipsWhatIsAbsent(t *testing.T) { + running := "vrf vrf-a1b2\n vni 4001\nexit-vrf\n!\nip prefix-list PL-a1b2 seq 10 permit 10.10.0.0/16 le 32\n" + want := []step{ + {"vrf vrf-a1b2", "no vni 4001"}, + {"no ip prefix-list PL-a1b2"}, + } + if got := routingTeardown(labVRF(t), running); !reflect.DeepEqual(got, want) { + t.Errorf("démontage :\n%q\nattendu :\n%q", got, want) + } +} + +func TestRoutingTeardownDoesNotReadAVNIOutsideTheVRFBlock(t *testing.T) { + running := "vrf vrf-a1b2\nexit-vrf\n!\nvrf vrf-a1b2c\n vni 4002\nexit-vrf\n" + if got := routingTeardown(labVRF(t), running); got != nil { + t.Errorf("étapes : %q", got) + } +} + +func TestVRFTeardown(t *testing.T) { + want := []step{{"no vrf vrf-a1b2"}} + if got := vrfTeardown(labVRF(t), otherOnlyRunning); !reflect.DeepEqual(got, want) { + t.Errorf("démontage : %q, %q attendu", got, want) + } + if got := vrfTeardown(labVRF(t), "vrf vrf-a1b2c\nexit-vrf\n"); got != nil { + t.Errorf("étapes visant vrf-a1b2c : %q", got) + } +} diff --git a/internal/netif/addr.go b/internal/netif/addr.go index b45b6aa..cd5dd74 100644 --- a/internal/netif/addr.go +++ b/internal/netif/addr.go @@ -19,3 +19,11 @@ func AddrAdd(iface string, ip net.IP) error { } return netlink.AddrAdd(link, addr) } + +func AddrAddPrefix(iface string, prefix *net.IPNet) error { + link, err := netlink.LinkByName(iface) + if err != nil { + return err + } + return netlink.AddrAdd(link, &netlink.Addr{IPNet: prefix}) +} diff --git a/internal/netif/route.go b/internal/netif/route.go new file mode 100644 index 0000000..f10b159 --- /dev/null +++ b/internal/netif/route.go @@ -0,0 +1,27 @@ +package netif + +import ( + "net" + + "github.com/vishvananda/netlink" +) + +func RouteReplaceVia(table int, dst *net.IPNet, gw net.IP, iface string) error { + link, err := netlink.LinkByName(iface) + if err != nil { + return err + } + return netlink.RouteReplace(&netlink.Route{ + LinkIndex: link.Attrs().Index, + Dst: dst, + Gw: gw, + Table: table, + }) +} + +func RouteDel(table int, dst *net.IPNet) error { + return netlink.RouteDel(&netlink.Route{ + Dst: dst, + Table: table, + }) +} diff --git a/internal/netif/vrf.go b/internal/netif/vrf.go new file mode 100644 index 0000000..8d8e47e --- /dev/null +++ b/internal/netif/vrf.go @@ -0,0 +1,16 @@ +package netif + +import ( + "github.com/vishvananda/netlink" +) + +func CreateVRF(name string, table uint32) error { + vrf := &netlink.Vrf{ + LinkAttrs: netlink.LinkAttrs{Name: name}, + Table: table, + } + if err := netlink.LinkAdd(vrf); err != nil { + return err + } + return netlink.LinkSetUp(vrf) +} diff --git a/internal/sysctl/sysctl.go b/internal/sysctl/sysctl.go new file mode 100644 index 0000000..50f0a1a --- /dev/null +++ b/internal/sysctl/sysctl.go @@ -0,0 +1,23 @@ +package sysctl + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +var root = "/proc/sys" + +func Set(key, value string) error { + path := filepath.Join(root, strings.ReplaceAll(key, ".", "/")) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0) + if err != nil { + return fmt.Errorf("sysctl %s: %w", key, err) + } + if _, err := f.WriteString(value); err != nil { + f.Close() + return fmt.Errorf("sysctl %s=%s: %w", key, value, err) + } + return f.Close() +} diff --git a/internal/sysctl/sysctl_test.go b/internal/sysctl/sysctl_test.go new file mode 100644 index 0000000..e07674f --- /dev/null +++ b/internal/sysctl/sysctl_test.go @@ -0,0 +1,48 @@ +package sysctl + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func fakeRoot(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "net", "ipv4"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "net", "ipv4", "ip_forward"), []byte("0\n"), 0o644); err != nil { + t.Fatal(err) + } + old := root + root = dir + t.Cleanup(func() { root = old }) + return dir +} + +func TestSetWritesTheValueAtTheKeyPath(t *testing.T) { + dir := fakeRoot(t) + if err := Set("net.ipv4.ip_forward", "1"); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(dir, "net", "ipv4", "ip_forward")) + if err != nil { + t.Fatal(err) + } + if string(got) != "1" { + t.Errorf("contenu %q, \"1\" attendu", got) + } +} + +func TestSetRefusesAnUnknownKeyWithoutCreatingIt(t *testing.T) { + dir := fakeRoot(t) + err := Set("net.ipv4.ip_forwarding", "1") + if err == nil || !strings.Contains(err.Error(), "sysctl net.ipv4.ip_forwarding") { + t.Errorf("erreur %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "net", "ipv4", "ip_forwarding")); !os.IsNotExist(err) { + t.Errorf("clé inconnue créée : %v", err) + } +}