f-41: frr, sysctl, netif: primitives du L3VNI #41

Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
GnomeZworc 2026-10-06 14:13:08 +02:00
commit 94c2f82867
Signed by: nicolas.boufideline
GPG key ID: 4406BBBF8845D632
11 changed files with 910 additions and 0 deletions

23
internal/sysctl/sysctl.go Normal file
View file

@ -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()
}

View file

@ -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)
}
}