// execute f() in tgtNS func withNetNS(curNS, tgtNS *os.File, f func() error) error { if err := ns.SetNS(tgtNS, syscall.CLONE_NEWNET); err != nil { return err } if err := f(); err != nil { // Attempt to revert the net ns in a known state if err := ns.SetNS(curNS, syscall.CLONE_NEWNET); err != nil { log.Printf("Cannot revert the net namespace: %v", err) } return err } return ns.SetNS(curNS, syscall.CLONE_NEWNET) }
func newNetNS() (hostNS, childNS *os.File, err error) { defer func() { if err != nil { if hostNS != nil { hostNS.Close() } if childNS != nil { childNS.Close() } } }() hostNS, err = os.Open(selfNetNS) if err != nil { return } if err = syscall.Unshare(syscall.CLONE_NEWNET); err != nil { return } childNS, err = os.Open(selfNetNS) if err != nil { ns.SetNS(hostNS, syscall.CLONE_NEWNET) return } return }
// enterHostNS moves into the host's network namespace. func (n *Networking) enterHostNS() error { return ns.SetNS(n.hostNS, syscall.CLONE_NEWNET) }