interface_linux.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package sandbox
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "regexp"
  7. "sync"
  8. "github.com/docker/libnetwork/types"
  9. "github.com/vishvananda/netlink"
  10. )
  11. // IfaceOption is a function option type to set interface options
  12. type IfaceOption func(i *nwIface)
  13. type nwIface struct {
  14. srcName string
  15. dstName string
  16. master string
  17. dstMaster string
  18. address *net.IPNet
  19. addressIPv6 *net.IPNet
  20. routes []*net.IPNet
  21. bridge bool
  22. ns *networkNamespace
  23. sync.Mutex
  24. }
  25. func (i *nwIface) SrcName() string {
  26. i.Lock()
  27. defer i.Unlock()
  28. return i.srcName
  29. }
  30. func (i *nwIface) DstName() string {
  31. i.Lock()
  32. defer i.Unlock()
  33. return i.dstName
  34. }
  35. func (i *nwIface) DstMaster() string {
  36. i.Lock()
  37. defer i.Unlock()
  38. return i.dstMaster
  39. }
  40. func (i *nwIface) Bridge() bool {
  41. i.Lock()
  42. defer i.Unlock()
  43. return i.bridge
  44. }
  45. func (i *nwIface) Master() string {
  46. i.Lock()
  47. defer i.Unlock()
  48. return i.master
  49. }
  50. func (i *nwIface) Address() *net.IPNet {
  51. i.Lock()
  52. defer i.Unlock()
  53. return types.GetIPNetCopy(i.address)
  54. }
  55. func (i *nwIface) AddressIPv6() *net.IPNet {
  56. i.Lock()
  57. defer i.Unlock()
  58. return types.GetIPNetCopy(i.addressIPv6)
  59. }
  60. func (i *nwIface) Routes() []*net.IPNet {
  61. i.Lock()
  62. defer i.Unlock()
  63. routes := make([]*net.IPNet, len(i.routes))
  64. for index, route := range i.routes {
  65. r := types.GetIPNetCopy(route)
  66. routes[index] = r
  67. }
  68. return routes
  69. }
  70. func (n *networkNamespace) Interfaces() []Interface {
  71. n.Lock()
  72. defer n.Unlock()
  73. ifaces := make([]Interface, len(n.iFaces))
  74. for i, iface := range n.iFaces {
  75. ifaces[i] = iface
  76. }
  77. return ifaces
  78. }
  79. func (i *nwIface) Remove() error {
  80. i.Lock()
  81. n := i.ns
  82. i.Unlock()
  83. n.Lock()
  84. path := n.path
  85. n.Unlock()
  86. return nsInvoke(path, func(nsFD int) error { return nil }, func(callerFD int) error {
  87. // Find the network inteerface identified by the DstName attribute.
  88. iface, err := netlink.LinkByName(i.DstName())
  89. if err != nil {
  90. return err
  91. }
  92. // Down the interface before configuring
  93. if err := netlink.LinkSetDown(iface); err != nil {
  94. return err
  95. }
  96. err = netlink.LinkSetName(iface, i.SrcName())
  97. if err != nil {
  98. fmt.Println("LinkSetName failed: ", err)
  99. return err
  100. }
  101. // if it is a bridge just delete it.
  102. if i.Bridge() {
  103. if err := netlink.LinkDel(iface); err != nil {
  104. return fmt.Errorf("failed deleting bridge %q: %v", i.SrcName(), err)
  105. }
  106. } else {
  107. // Move the network interface to caller namespace.
  108. if err := netlink.LinkSetNsFd(iface, callerFD); err != nil {
  109. fmt.Println("LinkSetNsPid failed: ", err)
  110. return err
  111. }
  112. }
  113. n.Lock()
  114. for index, intf := range n.iFaces {
  115. if intf == i {
  116. n.iFaces = append(n.iFaces[:index], n.iFaces[index+1:]...)
  117. break
  118. }
  119. }
  120. n.Unlock()
  121. return nil
  122. })
  123. }
  124. // Returns the sandbox's side veth interface statistics
  125. func (i *nwIface) Statistics() (*InterfaceStatistics, error) {
  126. i.Lock()
  127. n := i.ns
  128. i.Unlock()
  129. n.Lock()
  130. path := n.path
  131. n.Unlock()
  132. s := &InterfaceStatistics{}
  133. err := nsInvoke(path, func(nsFD int) error { return nil }, func(callerFD int) error {
  134. data, err := ioutil.ReadFile(netStatsFile)
  135. if err != nil {
  136. return fmt.Errorf("failed to open %s: %v", netStatsFile, err)
  137. }
  138. return scanInterfaceStats(string(data), i.DstName(), s)
  139. })
  140. if err != nil {
  141. err = fmt.Errorf("failed to retrieve the statistics for %s in netns %s: %v", i.DstName(), path, err)
  142. }
  143. return s, err
  144. }
  145. func (n *networkNamespace) findDst(srcName string, isBridge bool) string {
  146. n.Lock()
  147. defer n.Unlock()
  148. for _, i := range n.iFaces {
  149. // The master should match the srcname of the interface and the
  150. // master interface should be of type bridge, if searching for a bridge type
  151. if i.SrcName() == srcName && (!isBridge || i.Bridge()) {
  152. return i.DstName()
  153. }
  154. }
  155. return ""
  156. }
  157. func (n *networkNamespace) AddInterface(srcName, dstPrefix string, options ...IfaceOption) error {
  158. i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
  159. i.processInterfaceOptions(options...)
  160. if i.master != "" {
  161. i.dstMaster = n.findDst(i.master, true)
  162. if i.dstMaster == "" {
  163. return fmt.Errorf("could not find an appropriate master %q for %q",
  164. i.master, i.srcName)
  165. }
  166. }
  167. n.Lock()
  168. i.dstName = fmt.Sprintf("%s%d", i.dstName, n.nextIfIndex)
  169. n.nextIfIndex++
  170. path := n.path
  171. n.Unlock()
  172. return nsInvoke(path, func(nsFD int) error {
  173. // If it is a bridge interface we have to create the bridge inside
  174. // the namespace so don't try to lookup the interface using srcName
  175. if i.bridge {
  176. return nil
  177. }
  178. // Find the network interface identified by the SrcName attribute.
  179. iface, err := netlink.LinkByName(i.srcName)
  180. if err != nil {
  181. return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err)
  182. }
  183. // Move the network interface to the destination namespace.
  184. if err := netlink.LinkSetNsFd(iface, nsFD); err != nil {
  185. return fmt.Errorf("failed to set namespace on link %q: %v", i.srcName, err)
  186. }
  187. return nil
  188. }, func(callerFD int) error {
  189. if i.bridge {
  190. link := &netlink.Bridge{
  191. LinkAttrs: netlink.LinkAttrs{
  192. Name: i.srcName,
  193. },
  194. }
  195. if err := netlink.LinkAdd(link); err != nil {
  196. return fmt.Errorf("failed to create bridge %q: %v", i.srcName, err)
  197. }
  198. }
  199. // Find the network interface identified by the SrcName attribute.
  200. iface, err := netlink.LinkByName(i.srcName)
  201. if err != nil {
  202. return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err)
  203. }
  204. // Down the interface before configuring
  205. if err := netlink.LinkSetDown(iface); err != nil {
  206. return fmt.Errorf("failed to set link down: %v", err)
  207. }
  208. // Configure the interface now this is moved in the proper namespace.
  209. if err := configureInterface(iface, i); err != nil {
  210. return err
  211. }
  212. // Up the interface.
  213. if err := netlink.LinkSetUp(iface); err != nil {
  214. return fmt.Errorf("failed to set link up: %v", err)
  215. }
  216. n.Lock()
  217. n.iFaces = append(n.iFaces, i)
  218. n.Unlock()
  219. return nil
  220. })
  221. }
  222. func configureInterface(iface netlink.Link, i *nwIface) error {
  223. ifaceName := iface.Attrs().Name
  224. ifaceConfigurators := []struct {
  225. Fn func(netlink.Link, *nwIface) error
  226. ErrMessage string
  227. }{
  228. {setInterfaceName, fmt.Sprintf("error renaming interface %q to %q", ifaceName, i.DstName())},
  229. {setInterfaceIP, fmt.Sprintf("error setting interface %q IP to %q", ifaceName, i.Address())},
  230. {setInterfaceIPv6, fmt.Sprintf("error setting interface %q IPv6 to %q", ifaceName, i.AddressIPv6())},
  231. {setInterfaceRoutes, fmt.Sprintf("error setting interface %q routes to %q", ifaceName, i.Routes())},
  232. {setInterfaceMaster, fmt.Sprintf("error setting interface %q master to %q", ifaceName, i.DstMaster())},
  233. }
  234. for _, config := range ifaceConfigurators {
  235. if err := config.Fn(iface, i); err != nil {
  236. return fmt.Errorf("%s: %v", config.ErrMessage, err)
  237. }
  238. }
  239. return nil
  240. }
  241. func setInterfaceMaster(iface netlink.Link, i *nwIface) error {
  242. if i.DstMaster() == "" {
  243. return nil
  244. }
  245. return netlink.LinkSetMaster(iface, &netlink.Bridge{
  246. LinkAttrs: netlink.LinkAttrs{Name: i.DstMaster()}})
  247. }
  248. func setInterfaceIP(iface netlink.Link, i *nwIface) error {
  249. if i.Address() == nil {
  250. return nil
  251. }
  252. ipAddr := &netlink.Addr{IPNet: i.Address(), Label: ""}
  253. return netlink.AddrAdd(iface, ipAddr)
  254. }
  255. func setInterfaceIPv6(iface netlink.Link, i *nwIface) error {
  256. if i.AddressIPv6() == nil {
  257. return nil
  258. }
  259. ipAddr := &netlink.Addr{IPNet: i.AddressIPv6(), Label: ""}
  260. return netlink.AddrAdd(iface, ipAddr)
  261. }
  262. func setInterfaceName(iface netlink.Link, i *nwIface) error {
  263. return netlink.LinkSetName(iface, i.DstName())
  264. }
  265. func setInterfaceRoutes(iface netlink.Link, i *nwIface) error {
  266. for _, route := range i.Routes() {
  267. err := netlink.RouteAdd(&netlink.Route{
  268. Scope: netlink.SCOPE_LINK,
  269. LinkIndex: iface.Attrs().Index,
  270. Dst: route,
  271. })
  272. if err != nil {
  273. return err
  274. }
  275. }
  276. return nil
  277. }
  278. // In older kernels (like the one in Centos 6.6 distro) sysctl does not have netns support. Therefore
  279. // we cannot gather the statistics from /sys/class/net/<dev>/statistics/<counter> files. Per-netns stats
  280. // are naturally found in /proc/net/dev in kernels which support netns (ifconfig relyes on that).
  281. const (
  282. netStatsFile = "/proc/net/dev"
  283. base = "[ ]*%s:([ ]+[0-9]+){16}"
  284. )
  285. func scanInterfaceStats(data, ifName string, i *InterfaceStatistics) error {
  286. var (
  287. bktStr string
  288. bkt uint64
  289. )
  290. regex := fmt.Sprintf(base, ifName)
  291. re := regexp.MustCompile(regex)
  292. line := re.FindString(data)
  293. _, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d",
  294. &bktStr, &i.RxBytes, &i.RxPackets, &i.RxErrors, &i.RxDropped, &bkt, &bkt, &bkt,
  295. &bkt, &i.TxBytes, &i.TxPackets, &i.TxErrors, &i.TxDropped, &bkt, &bkt, &bkt, &bkt)
  296. return err
  297. }