f-91: netns: retour au netns du thread courant, thread détruit sinon #91

Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
GnomeZworc 2026-10-26 14:08:07 +01:00
commit 7b6b454b60
Signed by: nicolas.boufideline
GPG key ID: 4406BBBF8845D632
4 changed files with 250 additions and 59 deletions

View file

@ -5,15 +5,11 @@ package netns
import (
"fmt"
"os"
"runtime"
"golang.org/x/sys/unix"
)
func create(name string) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
base := "/var/run/netns"
path := base + "/" + name
@ -34,36 +30,20 @@ func create(name string) error {
}
f.Close()
// sauvegarde du netns courant
orig, err := os.Open("/proc/self/ns/net")
if err != nil {
return err
}
defer orig.Close()
// nouveau netns
if err := unix.Unshare(unix.CLONE_NEWNET); err != nil {
return err
}
// bind mount du netns du thread courant vers /var/run/netns/<name>
// /proc/self/ns/net pointe vers le ns du processus (thread principal),
// pas du thread courant — il faut utiliser le tid explicitement
threadNsPath := fmt.Sprintf("/proc/self/task/%d/ns/net", unix.Gettid())
if err := unix.Mount(
threadNsPath,
path,
"",
unix.MS_BIND,
"",
); err != nil {
return err
}
// revenir au netns original
if err := unix.Setns(int(orig.Fd()), unix.CLONE_NEWNET); err != nil {
return err
}
return nil
return onThread(func() error {
return unix.Unshare(unix.CLONE_NEWNET)
}, func() error {
// bind mount du netns du thread courant vers /var/run/netns/<name>
// /proc/self/ns/net pointe vers le ns du processus (thread principal),
// pas du thread courant — il faut utiliser le tid explicitement
threadNsPath := fmt.Sprintf("/proc/self/task/%d/ns/net", unix.Gettid())
return unix.Mount(
threadNsPath,
path,
"",
unix.MS_BIND,
"",
)
})
}