f-10: code: add function to call a function in a netns #10
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
parent
454005d6ac
commit
a650a34fc3
3 changed files with 56 additions and 0 deletions
5
internal/netns/call.go
Normal file
5
internal/netns/call.go
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
package netns
|
||||
|
||||
func Call(name string, fn func() error) error {
|
||||
return call(name, fn)
|
||||
}
|
||||
44
internal/netns/call_linux.go
Normal file
44
internal/netns/call_linux.go
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
//go:build linux
|
||||
|
||||
package netns
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func call(name string, fn func() error) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
// sauvegarde du netns courant
|
||||
orig, err := os.Open("/proc/self/ns/net")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer orig.Close()
|
||||
|
||||
// entrer dans le netns cible
|
||||
f, err := os.Open(fmt.Sprintf("/var/run/netns/%s", name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if err := unix.Setns(int(f.Fd()), unix.CLONE_NEWNET); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// exécuter la fonction dans le netns
|
||||
err = fn()
|
||||
|
||||
// toujours revenir au netns d'origine
|
||||
if restoreErr := unix.Setns(int(orig.Fd()), unix.CLONE_NEWNET); restoreErr != nil {
|
||||
return restoreErr
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
7
internal/netns/call_other.go
Normal file
7
internal/netns/call_other.go
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
//go:build !linux
|
||||
|
||||
package netns
|
||||
|
||||
func call(name string, fn func() error) error {
|
||||
return fn()
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue