interface_linux.go 11 KB

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