2024-01-01 09:55:49 +00:00
|
|
|
//go:build linux
|
|
|
|
|
2023-12-29 23:37:59 +00:00
|
|
|
package main
|
|
|
|
|
2024-01-01 09:55:49 +00:00
|
|
|
import (
|
2024-01-01 22:49:26 +00:00
|
|
|
"antoine-roux.tk/projects/go/firecracker-netns/internal/netlink"
|
2024-01-01 09:55:49 +00:00
|
|
|
"antoine-roux.tk/projects/go/firecracker-netns/internal/netns"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"runtime"
|
|
|
|
)
|
2023-12-29 23:37:59 +00:00
|
|
|
|
2024-01-01 22:49:26 +00:00
|
|
|
func setupEnv() int {
|
|
|
|
newNs, err := netns.New()
|
2024-01-01 09:55:49 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Println("new ns error", err)
|
2024-01-01 22:49:26 +00:00
|
|
|
return 1
|
2024-01-01 09:55:49 +00:00
|
|
|
}
|
|
|
|
|
2024-01-01 22:49:26 +00:00
|
|
|
defer func(handle netns.NsHandle) {
|
2024-01-01 09:55:49 +00:00
|
|
|
err := handle.Close()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("close ns error", err)
|
|
|
|
}
|
2024-01-01 22:49:26 +00:00
|
|
|
}(newNs)
|
|
|
|
|
|
|
|
defer func(ns netns.NsHandle) {
|
|
|
|
err := netns.Delete(ns)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("delete ns error", err)
|
|
|
|
}
|
|
|
|
}(newNs)
|
|
|
|
|
2024-01-02 17:39:09 +00:00
|
|
|
vethPair, err := netlink.NewVirtualPairing(newNs, "wlp3s0")
|
2024-01-01 22:49:26 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Println("new Veth error", err)
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func(veth *netlink.PairLink) {
|
2024-01-02 17:39:09 +00:00
|
|
|
err = veth.DeleteVirtualPairing()
|
2024-01-01 22:49:26 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Println("delete vethPair error", err)
|
|
|
|
}
|
|
|
|
}(vethPair)
|
2024-01-01 09:55:49 +00:00
|
|
|
|
2024-01-01 22:49:26 +00:00
|
|
|
err = netns.Set(newNs)
|
2024-01-01 09:55:49 +00:00
|
|
|
if err != nil {
|
2024-01-01 22:49:26 +00:00
|
|
|
return 1
|
2024-01-01 09:55:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Do something with the network namespace
|
|
|
|
interfaces, _ := net.Interfaces()
|
|
|
|
fmt.Printf("Interfaces: %v\n", interfaces)
|
|
|
|
|
|
|
|
cmd := exec.Command("/bin/sh")
|
|
|
|
|
|
|
|
cmd.Stdin = os.Stdin
|
|
|
|
cmd.Stdout = os.Stdout
|
|
|
|
cmd.Stderr = os.Stderr
|
|
|
|
|
|
|
|
cmd.Env = []string{"PS1=-[ns-process]- # "}
|
|
|
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
fmt.Printf("Error running the /bin/sh command - %s\n", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
2024-01-01 22:49:26 +00:00
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// Lock the OS Thread, so we don't accidentally switch namespaces
|
|
|
|
runtime.LockOSThread()
|
|
|
|
defer runtime.UnlockOSThread()
|
|
|
|
|
|
|
|
os.Exit(setupEnv())
|
2023-12-29 23:37:59 +00:00
|
|
|
}
|