From 1fd3169564abccd94f0e2786160ab294832a498b Mon Sep 17 00:00:00 2001 From: Eugene Yakubovich Date: Thu, 19 Feb 2015 15:29:56 -0800 Subject: [PATCH] Added ability to specify net ns at link creation Creating a link in one namespace and then moving can be problematic since there could be a iface name conflict. However, it is not always possible to switch into the target namespace either -- e.g. creating a macvlan interface must be done in the namespace of the parent interface. --- link.go | 10 ++++++++-- link_linux.go | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/link.go b/link.go index 276c2f8..a424639 100644 --- a/link.go +++ b/link.go @@ -10,6 +10,11 @@ type Link interface { Type() string } +type ( + NsPid int + NsFd int +) + // LinkAttrs represents data shared by most link types type LinkAttrs struct { Index int @@ -18,8 +23,9 @@ type LinkAttrs struct { Name string HardwareAddr net.HardwareAddr Flags net.Flags - ParentIndex int // index of the parent link device - MasterIndex int // must be the index of a bridge + ParentIndex int // index of the parent link device + MasterIndex int // must be the index of a bridge + Namespace interface{} // nil | NsPid | NsFd } // Device links cannot be created via netlink. These links diff --git a/link_linux.go b/link_linux.go index aedea16..5897af6 100644 --- a/link_linux.go +++ b/link_linux.go @@ -312,6 +312,20 @@ func LinkAdd(link Link) error { req.AddData(mtu) } + if base.Namespace != nil { + var attr *nl.RtAttr + switch base.Namespace.(type) { + case NsPid: + val := nl.Uint32Attr(uint32(base.Namespace.(NsPid))) + attr = nl.NewRtAttr(syscall.IFLA_NET_NS_PID, val) + case NsFd: + val := nl.Uint32Attr(uint32(base.Namespace.(NsFd))) + attr = nl.NewRtAttr(nl.IFLA_NET_NS_FD, val) + } + + req.AddData(attr) + } + linkInfo := nl.NewRtAttr(syscall.IFLA_LINKINFO, nil) nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type()))