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:
parent
1ea44dfaf9
commit
7c94e6f267
4 changed files with 250 additions and 59 deletions
|
|
@ -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,
|
||||
"",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue