interface_linux.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package osl
  2. import (
  3. "fmt"
  4. "net"
  5. "sync"
  6. "syscall"
  7. "time"
  8. "github.com/docker/docker/libnetwork/ns"
  9. "github.com/docker/docker/libnetwork/types"
  10. "github.com/sirupsen/logrus"
  11. "github.com/vishvananda/netlink"
  12. "github.com/vishvananda/netns"
  13. )
  14. // IfaceOption is a function option type to set interface options
  15. type IfaceOption func(i *nwIface)
  16. type nwIface struct {
  17. srcName string
  18. dstName string
  19. master string
  20. dstMaster string
  21. mac net.HardwareAddr
  22. address *net.IPNet
  23. addressIPv6 *net.IPNet
  24. llAddrs []*net.IPNet
  25. routes []*net.IPNet
  26. bridge bool
  27. ns *networkNamespace
  28. sync.Mutex
  29. }
  30. func (i *nwIface) SrcName() string {
  31. i.Lock()
  32. defer i.Unlock()
  33. return i.srcName
  34. }
  35. func (i *nwIface) DstName() string {
  36. i.Lock()
  37. defer i.Unlock()
  38. return i.dstName
  39. }
  40. func (i *nwIface) DstMaster() string {
  41. i.Lock()
  42. defer i.Unlock()
  43. return i.dstMaster
  44. }
  45. func (i *nwIface) Bridge() bool {
  46. i.Lock()
  47. defer i.Unlock()
  48. return i.bridge
  49. }
  50. func (i *nwIface) Master() string {
  51. i.Lock()
  52. defer i.Unlock()
  53. return i.master
  54. }
  55. func (i *nwIface) MacAddress() net.HardwareAddr {
  56. i.Lock()
  57. defer i.Unlock()
  58. return types.GetMacCopy(i.mac)
  59. }
  60. func (i *nwIface) Address() *net.IPNet {
  61. i.Lock()
  62. defer i.Unlock()
  63. return types.GetIPNetCopy(i.address)
  64. }
  65. func (i *nwIface) AddressIPv6() *net.IPNet {
  66. i.Lock()
  67. defer i.Unlock()
  68. return types.GetIPNetCopy(i.addressIPv6)
  69. }
  70. func (i *nwIface) LinkLocalAddresses() []*net.IPNet {
  71. i.Lock()
  72. defer i.Unlock()
  73. return i.llAddrs
  74. }
  75. func (i *nwIface) Routes() []*net.IPNet {
  76. i.Lock()
  77. defer i.Unlock()
  78. routes := make([]*net.IPNet, len(i.routes))
  79. for index, route := range i.routes {
  80. r := types.GetIPNetCopy(route)
  81. routes[index] = r
  82. }
  83. return routes
  84. }
  85. func (n *networkNamespace) Interfaces() []Interface {
  86. n.Lock()
  87. defer n.Unlock()
  88. ifaces := make([]Interface, len(n.iFaces))
  89. for i, iface := range n.iFaces {
  90. ifaces[i] = iface
  91. }
  92. return ifaces
  93. }
  94. func (i *nwIface) Remove() error {
  95. i.Lock()
  96. n := i.ns
  97. i.Unlock()
  98. n.Lock()
  99. isDefault := n.isDefault
  100. nlh := n.nlHandle
  101. n.Unlock()
  102. // Find the network interface identified by the DstName attribute.
  103. iface, err := nlh.LinkByName(i.DstName())
  104. if err != nil {
  105. return err
  106. }
  107. // Down the interface before configuring
  108. if err := nlh.LinkSetDown(iface); err != nil {
  109. return err
  110. }
  111. err = nlh.LinkSetName(iface, i.SrcName())
  112. if err != nil {
  113. logrus.Debugf("LinkSetName failed for interface %s: %v", i.SrcName(), err)
  114. return err
  115. }
  116. // if it is a bridge just delete it.
  117. if i.Bridge() {
  118. if err := nlh.LinkDel(iface); err != nil {
  119. return fmt.Errorf("failed deleting bridge %q: %v", i.SrcName(), err)
  120. }
  121. } else if !isDefault {
  122. // Move the network interface to caller namespace.
  123. if err := nlh.LinkSetNsFd(iface, ns.ParseHandlerInt()); err != nil {
  124. logrus.Debugf("LinkSetNsPid failed for interface %s: %v", i.SrcName(), err)
  125. return err
  126. }
  127. }
  128. n.Lock()
  129. for index, intf := range n.iFaces {
  130. if intf == i {
  131. n.iFaces = append(n.iFaces[:index], n.iFaces[index+1:]...)
  132. break
  133. }
  134. }
  135. n.Unlock()
  136. n.checkLoV6()
  137. return nil
  138. }
  139. // Returns the sandbox's side veth interface statistics
  140. func (i *nwIface) Statistics() (*types.InterfaceStatistics, error) {
  141. i.Lock()
  142. n := i.ns
  143. i.Unlock()
  144. l, err := n.nlHandle.LinkByName(i.DstName())
  145. if err != nil {
  146. return nil, fmt.Errorf("failed to retrieve the statistics for %s in netns %s: %v", i.DstName(), n.path, err)
  147. }
  148. stats := l.Attrs().Statistics
  149. if stats == nil {
  150. return nil, fmt.Errorf("no statistics were returned")
  151. }
  152. return &types.InterfaceStatistics{
  153. RxBytes: stats.RxBytes,
  154. TxBytes: stats.TxBytes,
  155. RxPackets: stats.RxPackets,
  156. TxPackets: stats.TxPackets,
  157. RxDropped: stats.RxDropped,
  158. TxDropped: stats.TxDropped,
  159. }, nil
  160. }
  161. func (n *networkNamespace) findDst(srcName string, isBridge bool) string {
  162. n.Lock()
  163. defer n.Unlock()
  164. for _, i := range n.iFaces {
  165. // The master should match the srcname of the interface and the
  166. // master interface should be of type bridge, if searching for a bridge type
  167. if i.SrcName() == srcName && (!isBridge || i.Bridge()) {
  168. return i.DstName()
  169. }
  170. }
  171. return ""
  172. }
  173. func (n *networkNamespace) AddInterface(srcName, dstPrefix string, options ...IfaceOption) error {
  174. i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
  175. i.processInterfaceOptions(options...)
  176. if i.master != "" {
  177. i.dstMaster = n.findDst(i.master, true)
  178. if i.dstMaster == "" {
  179. return fmt.Errorf("could not find an appropriate master %q for %q",
  180. i.master, i.srcName)
  181. }
  182. }
  183. n.Lock()
  184. if n.isDefault {
  185. i.dstName = i.srcName
  186. } else {
  187. i.dstName = fmt.Sprintf("%s%d", dstPrefix, n.nextIfIndex[dstPrefix])
  188. n.nextIfIndex[dstPrefix]++
  189. }
  190. path := n.path
  191. isDefault := n.isDefault
  192. nlh := n.nlHandle
  193. nlhHost := ns.NlHandle()
  194. n.Unlock()
  195. // If it is a bridge interface we have to create the bridge inside
  196. // the namespace so don't try to lookup the interface using srcName
  197. if i.bridge {
  198. link := &netlink.Bridge{
  199. LinkAttrs: netlink.LinkAttrs{
  200. Name: i.srcName,
  201. },
  202. }
  203. if err := nlh.LinkAdd(link); err != nil {
  204. return fmt.Errorf("failed to create bridge %q: %v", i.srcName, err)
  205. }
  206. } else {
  207. // Find the network interface identified by the SrcName attribute.
  208. iface, err := nlhHost.LinkByName(i.srcName)
  209. if err != nil {
  210. return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err)
  211. }
  212. // Move the network interface to the destination
  213. // namespace only if the namespace is not a default
  214. // type
  215. if !isDefault {
  216. newNs, err := netns.GetFromPath(path)
  217. if err != nil {
  218. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  219. }
  220. defer newNs.Close()
  221. if err := nlhHost.LinkSetNsFd(iface, int(newNs)); err != nil {
  222. return fmt.Errorf("failed to set namespace on link %q: %v", i.srcName, err)
  223. }
  224. }
  225. }
  226. // Find the network interface identified by the SrcName attribute.
  227. iface, err := nlh.LinkByName(i.srcName)
  228. if err != nil {
  229. return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err)
  230. }
  231. // Down the interface before configuring
  232. if err := nlh.LinkSetDown(iface); err != nil {
  233. return fmt.Errorf("failed to set link down: %v", err)
  234. }
  235. // Configure the interface now this is moved in the proper namespace.
  236. if err := configureInterface(nlh, iface, i); err != nil {
  237. // If configuring the device fails move it back to the host namespace
  238. // and change the name back to the source name. This allows the caller
  239. // to properly cleanup the interface. Its important especially for
  240. // interfaces with global attributes, ex: vni id for vxlan interfaces.
  241. if nerr := nlh.LinkSetName(iface, i.SrcName()); nerr != nil {
  242. logrus.Errorf("renaming interface (%s->%s) failed, %v after config error %v", i.DstName(), i.SrcName(), nerr, err)
  243. }
  244. if nerr := nlh.LinkSetNsFd(iface, ns.ParseHandlerInt()); nerr != nil {
  245. logrus.Errorf("moving interface %s to host ns failed, %v, after config error %v", i.SrcName(), nerr, err)
  246. }
  247. return err
  248. }
  249. // Up the interface.
  250. cnt := 0
  251. for err = nlh.LinkSetUp(iface); err != nil && cnt < 3; cnt++ {
  252. logrus.Debugf("retrying link setup because of: %v", err)
  253. time.Sleep(10 * time.Millisecond)
  254. err = nlh.LinkSetUp(iface)
  255. }
  256. if err != nil {
  257. return fmt.Errorf("failed to set link up: %v", err)
  258. }
  259. // Set the routes on the interface. This can only be done when the interface is up.
  260. if err := setInterfaceRoutes(nlh, iface, i); err != nil {
  261. return fmt.Errorf("error setting interface %q routes to %q: %v", iface.Attrs().Name, i.Routes(), err)
  262. }
  263. n.Lock()
  264. n.iFaces = append(n.iFaces, i)
  265. n.Unlock()
  266. n.checkLoV6()
  267. return nil
  268. }
  269. func configureInterface(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  270. ifaceName := iface.Attrs().Name
  271. ifaceConfigurators := []struct {
  272. Fn func(*netlink.Handle, netlink.Link, *nwIface) error
  273. ErrMessage string
  274. }{
  275. {setInterfaceName, fmt.Sprintf("error renaming interface %q to %q", ifaceName, i.DstName())},
  276. {setInterfaceMAC, fmt.Sprintf("error setting interface %q MAC to %q", ifaceName, i.MacAddress())},
  277. {setInterfaceIP, fmt.Sprintf("error setting interface %q IP to %v", ifaceName, i.Address())},
  278. {setInterfaceIPv6, fmt.Sprintf("error setting interface %q IPv6 to %v", ifaceName, i.AddressIPv6())},
  279. {setInterfaceMaster, fmt.Sprintf("error setting interface %q master to %q", ifaceName, i.DstMaster())},
  280. {setInterfaceLinkLocalIPs, fmt.Sprintf("error setting interface %q link local IPs to %v", ifaceName, i.LinkLocalAddresses())},
  281. }
  282. for _, config := range ifaceConfigurators {
  283. if err := config.Fn(nlh, iface, i); err != nil {
  284. return fmt.Errorf("%s: %v", config.ErrMessage, err)
  285. }
  286. }
  287. return nil
  288. }
  289. func setInterfaceMaster(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  290. if i.DstMaster() == "" {
  291. return nil
  292. }
  293. return nlh.LinkSetMaster(iface, &netlink.Bridge{
  294. LinkAttrs: netlink.LinkAttrs{Name: i.DstMaster()}})
  295. }
  296. func setInterfaceMAC(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  297. if i.MacAddress() == nil {
  298. return nil
  299. }
  300. return nlh.LinkSetHardwareAddr(iface, i.MacAddress())
  301. }
  302. func setInterfaceIP(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  303. if i.Address() == nil {
  304. return nil
  305. }
  306. if err := checkRouteConflict(nlh, i.Address(), netlink.FAMILY_V4); err != nil {
  307. return err
  308. }
  309. ipAddr := &netlink.Addr{IPNet: i.Address(), Label: ""}
  310. return nlh.AddrAdd(iface, ipAddr)
  311. }
  312. func setInterfaceIPv6(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  313. if i.AddressIPv6() == nil {
  314. return nil
  315. }
  316. if err := checkRouteConflict(nlh, i.AddressIPv6(), netlink.FAMILY_V6); err != nil {
  317. return err
  318. }
  319. if err := setIPv6(i.ns.path, i.DstName(), true); err != nil {
  320. return fmt.Errorf("failed to enable ipv6: %v", err)
  321. }
  322. ipAddr := &netlink.Addr{IPNet: i.AddressIPv6(), Label: "", Flags: syscall.IFA_F_NODAD}
  323. return nlh.AddrAdd(iface, ipAddr)
  324. }
  325. func setInterfaceLinkLocalIPs(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  326. for _, llIP := range i.LinkLocalAddresses() {
  327. ipAddr := &netlink.Addr{IPNet: llIP}
  328. if err := nlh.AddrAdd(iface, ipAddr); err != nil {
  329. return err
  330. }
  331. }
  332. return nil
  333. }
  334. func setInterfaceName(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  335. return nlh.LinkSetName(iface, i.DstName())
  336. }
  337. func setInterfaceRoutes(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
  338. for _, route := range i.Routes() {
  339. err := nlh.RouteAdd(&netlink.Route{
  340. Scope: netlink.SCOPE_LINK,
  341. LinkIndex: iface.Attrs().Index,
  342. Dst: route,
  343. })
  344. if err != nil {
  345. return err
  346. }
  347. }
  348. return nil
  349. }
  350. func checkRouteConflict(nlh *netlink.Handle, address *net.IPNet, family int) error {
  351. routes, err := nlh.RouteList(nil, family)
  352. if err != nil {
  353. return err
  354. }
  355. for _, route := range routes {
  356. if route.Dst != nil {
  357. if route.Dst.Contains(address.IP) || address.Contains(route.Dst.IP) {
  358. return fmt.Errorf("cannot program address %v in sandbox interface because it conflicts with existing route %s",
  359. address, route)
  360. }
  361. }
  362. }
  363. return nil
  364. }