driver.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. package bridge
  2. import (
  3. "encoding/hex"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "github.com/Sirupsen/logrus"
  14. "github.com/docker/docker/daemon/network"
  15. "github.com/docker/docker/daemon/networkdriver"
  16. "github.com/docker/docker/daemon/networkdriver/ipallocator"
  17. "github.com/docker/docker/daemon/networkdriver/portmapper"
  18. "github.com/docker/docker/nat"
  19. "github.com/docker/docker/pkg/iptables"
  20. "github.com/docker/docker/pkg/parsers/kernel"
  21. "github.com/docker/docker/pkg/resolvconf"
  22. "github.com/docker/libcontainer/netlink"
  23. )
  24. const (
  25. DefaultNetworkBridge = "docker0"
  26. MaxAllocatedPortAttempts = 10
  27. )
  28. // Network interface represents the networking stack of a container
  29. type networkInterface struct {
  30. IP net.IP
  31. IPv6 net.IP
  32. PortMappings []net.Addr // There are mappings to the host interfaces
  33. }
  34. type ifaces struct {
  35. c map[string]*networkInterface
  36. sync.Mutex
  37. }
  38. func (i *ifaces) Set(key string, n *networkInterface) {
  39. i.Lock()
  40. i.c[key] = n
  41. i.Unlock()
  42. }
  43. func (i *ifaces) Get(key string) *networkInterface {
  44. i.Lock()
  45. res := i.c[key]
  46. i.Unlock()
  47. return res
  48. }
  49. var (
  50. addrs = []string{
  51. // Here we don't follow the convention of using the 1st IP of the range for the gateway.
  52. // This is to use the same gateway IPs as the /24 ranges, which predate the /16 ranges.
  53. // In theory this shouldn't matter - in practice there's bound to be a few scripts relying
  54. // on the internal addressing or other things like that.
  55. // They shouldn't, but hey, let's not break them unless we really have to.
  56. "172.17.42.1/16", // Don't use 172.16.0.0/16, it conflicts with EC2 DNS 172.16.0.23
  57. "10.0.42.1/16", // Don't even try using the entire /8, that's too intrusive
  58. "10.1.42.1/16",
  59. "10.42.42.1/16",
  60. "172.16.42.1/24",
  61. "172.16.43.1/24",
  62. "172.16.44.1/24",
  63. "10.0.42.1/24",
  64. "10.0.43.1/24",
  65. "192.168.42.1/24",
  66. "192.168.43.1/24",
  67. "192.168.44.1/24",
  68. }
  69. bridgeIface string
  70. bridgeIPv4Network *net.IPNet
  71. bridgeIPv6Addr net.IP
  72. globalIPv6Network *net.IPNet
  73. portMapper *portmapper.PortMapper
  74. once sync.Once
  75. defaultBindingIP = net.ParseIP("0.0.0.0")
  76. currentInterfaces = ifaces{c: make(map[string]*networkInterface)}
  77. ipAllocator = ipallocator.New()
  78. )
  79. func initPortMapper() {
  80. once.Do(func() {
  81. portMapper = portmapper.New()
  82. })
  83. }
  84. type Config struct {
  85. EnableIPv6 bool
  86. EnableIptables bool
  87. EnableIpForward bool
  88. EnableIpMasq bool
  89. DefaultIp net.IP
  90. Iface string
  91. IP string
  92. FixedCIDR string
  93. FixedCIDRv6 string
  94. InterContainerCommunication bool
  95. }
  96. func InitDriver(config *Config) error {
  97. var (
  98. networkv4 *net.IPNet
  99. networkv6 *net.IPNet
  100. addrv4 net.Addr
  101. addrsv6 []net.Addr
  102. bridgeIPv6 = "fe80::1/64"
  103. )
  104. // try to modprobe bridge first
  105. // see gh#12177
  106. if out, err := exec.Command("modprobe", "-va", "bridge", "nf_nat").Output(); err != nil {
  107. logrus.Warnf("Running modprobe bridge nf_nat failed with message: %s, error: %v", out, err)
  108. }
  109. initPortMapper()
  110. if config.DefaultIp != nil {
  111. defaultBindingIP = config.DefaultIp
  112. }
  113. bridgeIface = config.Iface
  114. usingDefaultBridge := false
  115. if bridgeIface == "" {
  116. usingDefaultBridge = true
  117. bridgeIface = DefaultNetworkBridge
  118. }
  119. addrv4, addrsv6, err := networkdriver.GetIfaceAddr(bridgeIface)
  120. if err != nil {
  121. // No Bridge existent, create one
  122. // If we're not using the default bridge, fail without trying to create it
  123. if !usingDefaultBridge {
  124. return err
  125. }
  126. logrus.Info("Bridge interface not found, trying to create it")
  127. // If the iface is not found, try to create it
  128. if err := configureBridge(config.IP, bridgeIPv6, config.EnableIPv6); err != nil {
  129. logrus.Errorf("Could not configure Bridge: %s", err)
  130. return err
  131. }
  132. addrv4, addrsv6, err = networkdriver.GetIfaceAddr(bridgeIface)
  133. if err != nil {
  134. return err
  135. }
  136. if config.FixedCIDRv6 != "" {
  137. // Setting route to global IPv6 subnet
  138. logrus.Infof("Adding route to IPv6 network %q via device %q", config.FixedCIDRv6, bridgeIface)
  139. if err := netlink.AddRoute(config.FixedCIDRv6, "", "", bridgeIface); err != nil {
  140. logrus.Fatalf("Could not add route to IPv6 network %q via device %q", config.FixedCIDRv6, bridgeIface)
  141. }
  142. }
  143. } else {
  144. // Bridge exists already, getting info...
  145. // Validate that the bridge ip matches the ip specified by BridgeIP
  146. if config.IP != "" {
  147. networkv4 = addrv4.(*net.IPNet)
  148. bip, _, err := net.ParseCIDR(config.IP)
  149. if err != nil {
  150. return err
  151. }
  152. if !networkv4.IP.Equal(bip) {
  153. return fmt.Errorf("Bridge ip (%s) does not match existing bridge configuration %s", networkv4.IP, bip)
  154. }
  155. }
  156. // A bridge might exist but not have any IPv6 addr associated with it yet
  157. // (for example, an existing Docker installation that has only been used
  158. // with IPv4 and docker0 already is set up) In that case, we can perform
  159. // the bridge init for IPv6 here, else we will error out below if --ipv6=true
  160. if len(addrsv6) == 0 && config.EnableIPv6 {
  161. if err := setupIPv6Bridge(bridgeIPv6); err != nil {
  162. return err
  163. }
  164. // Recheck addresses now that IPv6 is setup on the bridge
  165. addrv4, addrsv6, err = networkdriver.GetIfaceAddr(bridgeIface)
  166. if err != nil {
  167. return err
  168. }
  169. }
  170. // TODO: Check if route to config.FixedCIDRv6 is set
  171. }
  172. if config.EnableIPv6 {
  173. bip6, _, err := net.ParseCIDR(bridgeIPv6)
  174. if err != nil {
  175. return err
  176. }
  177. found := false
  178. for _, addrv6 := range addrsv6 {
  179. networkv6 = addrv6.(*net.IPNet)
  180. if networkv6.IP.Equal(bip6) {
  181. found = true
  182. break
  183. }
  184. }
  185. if !found {
  186. return fmt.Errorf("Bridge IPv6 does not match existing bridge configuration %s", bip6)
  187. }
  188. }
  189. networkv4 = addrv4.(*net.IPNet)
  190. if config.EnableIPv6 {
  191. if len(addrsv6) == 0 {
  192. return errors.New("IPv6 enabled but no IPv6 detected")
  193. }
  194. bridgeIPv6Addr = networkv6.IP
  195. }
  196. // Configure iptables for link support
  197. if config.EnableIptables {
  198. if err := setupIPTables(addrv4, config.InterContainerCommunication, config.EnableIpMasq); err != nil {
  199. logrus.Errorf("Error configuing iptables: %s", err)
  200. return err
  201. }
  202. }
  203. if config.EnableIpForward {
  204. // Enable IPv4 forwarding
  205. if err := ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte{'1', '\n'}, 0644); err != nil {
  206. logrus.Warnf("WARNING: unable to enable IPv4 forwarding: %s\n", err)
  207. }
  208. if config.FixedCIDRv6 != "" {
  209. // Enable IPv6 forwarding
  210. if err := ioutil.WriteFile("/proc/sys/net/ipv6/conf/default/forwarding", []byte{'1', '\n'}, 0644); err != nil {
  211. logrus.Warnf("WARNING: unable to enable IPv6 default forwarding: %s\n", err)
  212. }
  213. if err := ioutil.WriteFile("/proc/sys/net/ipv6/conf/all/forwarding", []byte{'1', '\n'}, 0644); err != nil {
  214. logrus.Warnf("WARNING: unable to enable IPv6 all forwarding: %s\n", err)
  215. }
  216. }
  217. }
  218. // We can always try removing the iptables
  219. if err := iptables.RemoveExistingChain("DOCKER", iptables.Nat); err != nil {
  220. return err
  221. }
  222. if config.EnableIptables {
  223. _, err := iptables.NewChain("DOCKER", bridgeIface, iptables.Nat)
  224. if err != nil {
  225. return err
  226. }
  227. chain, err := iptables.NewChain("DOCKER", bridgeIface, iptables.Filter)
  228. if err != nil {
  229. return err
  230. }
  231. portMapper.SetIptablesChain(chain)
  232. }
  233. bridgeIPv4Network = networkv4
  234. if config.FixedCIDR != "" {
  235. _, subnet, err := net.ParseCIDR(config.FixedCIDR)
  236. if err != nil {
  237. return err
  238. }
  239. logrus.Debugf("Subnet: %v", subnet)
  240. if err := ipAllocator.RegisterSubnet(bridgeIPv4Network, subnet); err != nil {
  241. logrus.Errorf("Error registering subnet for IPv4 bridge network: %s", err)
  242. return err
  243. }
  244. }
  245. if config.FixedCIDRv6 != "" {
  246. _, subnet, err := net.ParseCIDR(config.FixedCIDRv6)
  247. if err != nil {
  248. return err
  249. }
  250. logrus.Debugf("Subnet: %v", subnet)
  251. if err := ipAllocator.RegisterSubnet(subnet, subnet); err != nil {
  252. logrus.Errorf("Error registering subnet for IPv6 bridge network: %s", err)
  253. return err
  254. }
  255. globalIPv6Network = subnet
  256. }
  257. // Block BridgeIP in IP allocator
  258. ipAllocator.RequestIP(bridgeIPv4Network, bridgeIPv4Network.IP)
  259. return nil
  260. }
  261. func setupIPTables(addr net.Addr, icc, ipmasq bool) error {
  262. // Enable NAT
  263. if ipmasq {
  264. natArgs := []string{"-s", addr.String(), "!", "-o", bridgeIface, "-j", "MASQUERADE"}
  265. if !iptables.Exists(iptables.Nat, "POSTROUTING", natArgs...) {
  266. if output, err := iptables.Raw(append([]string{
  267. "-t", string(iptables.Nat), "-I", "POSTROUTING"}, natArgs...)...); err != nil {
  268. return fmt.Errorf("Unable to enable network bridge NAT: %s", err)
  269. } else if len(output) != 0 {
  270. return iptables.ChainError{Chain: "POSTROUTING", Output: output}
  271. }
  272. }
  273. }
  274. var (
  275. args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
  276. acceptArgs = append(args, "ACCEPT")
  277. dropArgs = append(args, "DROP")
  278. )
  279. if !icc {
  280. iptables.Raw(append([]string{"-D", "FORWARD"}, acceptArgs...)...)
  281. if !iptables.Exists(iptables.Filter, "FORWARD", dropArgs...) {
  282. logrus.Debugf("Disable inter-container communication")
  283. if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, dropArgs...)...); err != nil {
  284. return fmt.Errorf("Unable to prevent intercontainer communication: %s", err)
  285. } else if len(output) != 0 {
  286. return fmt.Errorf("Error disabling intercontainer communication: %s", output)
  287. }
  288. }
  289. } else {
  290. iptables.Raw(append([]string{"-D", "FORWARD"}, dropArgs...)...)
  291. if !iptables.Exists(iptables.Filter, "FORWARD", acceptArgs...) {
  292. logrus.Debugf("Enable inter-container communication")
  293. if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, acceptArgs...)...); err != nil {
  294. return fmt.Errorf("Unable to allow intercontainer communication: %s", err)
  295. } else if len(output) != 0 {
  296. return fmt.Errorf("Error enabling intercontainer communication: %s", output)
  297. }
  298. }
  299. }
  300. // Accept all non-intercontainer outgoing packets
  301. outgoingArgs := []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}
  302. if !iptables.Exists(iptables.Filter, "FORWARD", outgoingArgs...) {
  303. if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, outgoingArgs...)...); err != nil {
  304. return fmt.Errorf("Unable to allow outgoing packets: %s", err)
  305. } else if len(output) != 0 {
  306. return iptables.ChainError{Chain: "FORWARD outgoing", Output: output}
  307. }
  308. }
  309. // Accept incoming packets for existing connections
  310. existingArgs := []string{"-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}
  311. if !iptables.Exists(iptables.Filter, "FORWARD", existingArgs...) {
  312. if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, existingArgs...)...); err != nil {
  313. return fmt.Errorf("Unable to allow incoming packets: %s", err)
  314. } else if len(output) != 0 {
  315. return iptables.ChainError{Chain: "FORWARD incoming", Output: output}
  316. }
  317. }
  318. return nil
  319. }
  320. func RequestPort(ip net.IP, proto string, port int) (int, error) {
  321. initPortMapper()
  322. return portMapper.Allocator.RequestPort(ip, proto, port)
  323. }
  324. // configureBridge attempts to create and configure a network bridge interface named `bridgeIface` on the host
  325. // If bridgeIP is empty, it will try to find a non-conflicting IP from the Docker-specified private ranges
  326. // If the bridge `bridgeIface` already exists, it will only perform the IP address association with the existing
  327. // bridge (fixes issue #8444)
  328. // If an address which doesn't conflict with existing interfaces can't be found, an error is returned.
  329. func configureBridge(bridgeIP string, bridgeIPv6 string, enableIPv6 bool) error {
  330. nameservers := []string{}
  331. resolvConf, _ := resolvconf.Get()
  332. // We don't check for an error here, because we don't really care
  333. // if we can't read /etc/resolv.conf. So instead we skip the append
  334. // if resolvConf is nil. It either doesn't exist, or we can't read it
  335. // for some reason.
  336. if resolvConf != nil {
  337. nameservers = append(nameservers, resolvconf.GetNameserversAsCIDR(resolvConf)...)
  338. }
  339. var ifaceAddr string
  340. if len(bridgeIP) != 0 {
  341. _, _, err := net.ParseCIDR(bridgeIP)
  342. if err != nil {
  343. return err
  344. }
  345. ifaceAddr = bridgeIP
  346. } else {
  347. for _, addr := range addrs {
  348. _, dockerNetwork, err := net.ParseCIDR(addr)
  349. if err != nil {
  350. return err
  351. }
  352. if err := networkdriver.CheckNameserverOverlaps(nameservers, dockerNetwork); err == nil {
  353. if err := networkdriver.CheckRouteOverlaps(dockerNetwork); err == nil {
  354. ifaceAddr = addr
  355. break
  356. } else {
  357. logrus.Debugf("%s %s", addr, err)
  358. }
  359. }
  360. }
  361. }
  362. if ifaceAddr == "" {
  363. return fmt.Errorf("Could not find a free IP address range for interface '%s'. Please configure its address manually and run 'docker -b %s'", bridgeIface, bridgeIface)
  364. }
  365. logrus.Debugf("Creating bridge %s with network %s", bridgeIface, ifaceAddr)
  366. if err := createBridgeIface(bridgeIface); err != nil {
  367. // The bridge may already exist, therefore we can ignore an "exists" error
  368. if !os.IsExist(err) {
  369. return err
  370. }
  371. }
  372. iface, err := net.InterfaceByName(bridgeIface)
  373. if err != nil {
  374. return err
  375. }
  376. ipAddr, ipNet, err := net.ParseCIDR(ifaceAddr)
  377. if err != nil {
  378. return err
  379. }
  380. if err := netlink.NetworkLinkAddIp(iface, ipAddr, ipNet); err != nil {
  381. return fmt.Errorf("Unable to add private network: %s", err)
  382. }
  383. if enableIPv6 {
  384. if err := setupIPv6Bridge(bridgeIPv6); err != nil {
  385. return err
  386. }
  387. }
  388. if err := netlink.NetworkLinkUp(iface); err != nil {
  389. return fmt.Errorf("Unable to start network bridge: %s", err)
  390. }
  391. return nil
  392. }
  393. func setupIPv6Bridge(bridgeIPv6 string) error {
  394. iface, err := net.InterfaceByName(bridgeIface)
  395. if err != nil {
  396. return err
  397. }
  398. // Enable IPv6 on the bridge
  399. procFile := "/proc/sys/net/ipv6/conf/" + iface.Name + "/disable_ipv6"
  400. if err := ioutil.WriteFile(procFile, []byte{'0', '\n'}, 0644); err != nil {
  401. return fmt.Errorf("Unable to enable IPv6 addresses on bridge: %v", err)
  402. }
  403. ipAddr6, ipNet6, err := net.ParseCIDR(bridgeIPv6)
  404. if err != nil {
  405. return fmt.Errorf("Unable to parse bridge IPv6 address: %q, error: %v", bridgeIPv6, err)
  406. }
  407. if err := netlink.NetworkLinkAddIp(iface, ipAddr6, ipNet6); err != nil {
  408. return fmt.Errorf("Unable to add private IPv6 network: %v", err)
  409. }
  410. return nil
  411. }
  412. func createBridgeIface(name string) error {
  413. kv, err := kernel.GetKernelVersion()
  414. // Only set the bridge's mac address if the kernel version is > 3.3
  415. // before that it was not supported
  416. setBridgeMacAddr := err == nil && (kv.Kernel >= 3 && kv.Major >= 3)
  417. logrus.Debugf("setting bridge mac address = %v", setBridgeMacAddr)
  418. return netlink.CreateBridge(name, setBridgeMacAddr)
  419. }
  420. // Generate a IEEE802 compliant MAC address from the given IP address.
  421. //
  422. // The generator is guaranteed to be consistent: the same IP will always yield the same
  423. // MAC address. This is to avoid ARP cache issues.
  424. func generateMacAddr(ip net.IP) net.HardwareAddr {
  425. hw := make(net.HardwareAddr, 6)
  426. // The first byte of the MAC address has to comply with these rules:
  427. // 1. Unicast: Set the least-significant bit to 0.
  428. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  429. // 3. As "small" as possible: The veth address has to be "smaller" than the bridge address.
  430. hw[0] = 0x02
  431. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  432. // Since this address is locally administered, we can do whatever we want as long as
  433. // it doesn't conflict with other addresses.
  434. hw[1] = 0x42
  435. // Insert the IP address into the last 32 bits of the MAC address.
  436. // This is a simple way to guarantee the address will be consistent and unique.
  437. copy(hw[2:], ip.To4())
  438. return hw
  439. }
  440. func linkLocalIPv6FromMac(mac string) (string, error) {
  441. hx := strings.Replace(mac, ":", "", -1)
  442. hw, err := hex.DecodeString(hx)
  443. if err != nil {
  444. return "", errors.New("Could not parse MAC address " + mac)
  445. }
  446. hw[0] ^= 0x2
  447. return fmt.Sprintf("fe80::%x%x:%xff:fe%x:%x%x/64", hw[0], hw[1], hw[2], hw[3], hw[4], hw[5]), nil
  448. }
  449. // Allocate a network interface
  450. func Allocate(id, requestedMac, requestedIP, requestedIPv6 string) (*network.Settings, error) {
  451. var (
  452. ip net.IP
  453. mac net.HardwareAddr
  454. err error
  455. globalIPv6 net.IP
  456. )
  457. ip, err = ipAllocator.RequestIP(bridgeIPv4Network, net.ParseIP(requestedIP))
  458. if err != nil {
  459. return nil, err
  460. }
  461. // If no explicit mac address was given, generate a random one.
  462. if mac, err = net.ParseMAC(requestedMac); err != nil {
  463. mac = generateMacAddr(ip)
  464. }
  465. if globalIPv6Network != nil {
  466. // If globalIPv6Network Size is at least a /80 subnet generate IPv6 address from MAC address
  467. netmaskOnes, _ := globalIPv6Network.Mask.Size()
  468. ipv6 := net.ParseIP(requestedIPv6)
  469. if ipv6 == nil && netmaskOnes <= 80 {
  470. ipv6 = make(net.IP, len(globalIPv6Network.IP))
  471. copy(ipv6, globalIPv6Network.IP)
  472. for i, h := range mac {
  473. ipv6[i+10] = h
  474. }
  475. }
  476. globalIPv6, err = ipAllocator.RequestIP(globalIPv6Network, ipv6)
  477. if err != nil {
  478. logrus.Errorf("Allocator: RequestIP v6: %v", err)
  479. return nil, err
  480. }
  481. logrus.Infof("Allocated IPv6 %s", globalIPv6)
  482. }
  483. maskSize, _ := bridgeIPv4Network.Mask.Size()
  484. // If linklocal IPv6
  485. localIPv6Net, err := linkLocalIPv6FromMac(mac.String())
  486. if err != nil {
  487. return nil, err
  488. }
  489. localIPv6, _, _ := net.ParseCIDR(localIPv6Net)
  490. networkSettings := &network.Settings{
  491. IPAddress: ip.String(),
  492. Gateway: bridgeIPv4Network.IP.String(),
  493. MacAddress: mac.String(),
  494. Bridge: bridgeIface,
  495. IPPrefixLen: maskSize,
  496. LinkLocalIPv6Address: localIPv6.String(),
  497. }
  498. if globalIPv6Network != nil {
  499. networkSettings.GlobalIPv6Address = globalIPv6.String()
  500. maskV6Size, _ := globalIPv6Network.Mask.Size()
  501. networkSettings.GlobalIPv6PrefixLen = maskV6Size
  502. networkSettings.IPv6Gateway = bridgeIPv6Addr.String()
  503. }
  504. currentInterfaces.Set(id, &networkInterface{
  505. IP: ip,
  506. IPv6: globalIPv6,
  507. })
  508. return networkSettings, nil
  509. }
  510. // Release an interface for a select ip
  511. func Release(id string) {
  512. var containerInterface = currentInterfaces.Get(id)
  513. if containerInterface == nil {
  514. logrus.Warnf("No network information to release for %s", id)
  515. return
  516. }
  517. for _, nat := range containerInterface.PortMappings {
  518. if err := portMapper.Unmap(nat); err != nil {
  519. logrus.Infof("Unable to unmap port %s: %s", nat, err)
  520. }
  521. }
  522. if err := ipAllocator.ReleaseIP(bridgeIPv4Network, containerInterface.IP); err != nil {
  523. logrus.Infof("Unable to release IPv4 %s", err)
  524. }
  525. if globalIPv6Network != nil {
  526. if err := ipAllocator.ReleaseIP(globalIPv6Network, containerInterface.IPv6); err != nil {
  527. logrus.Infof("Unable to release IPv6 %s", err)
  528. }
  529. }
  530. }
  531. // Allocate an external port and map it to the interface
  532. func AllocatePort(id string, port nat.Port, binding nat.PortBinding) (nat.PortBinding, error) {
  533. var (
  534. ip = defaultBindingIP
  535. proto = port.Proto()
  536. containerPort = port.Int()
  537. network = currentInterfaces.Get(id)
  538. )
  539. if binding.HostIp != "" {
  540. ip = net.ParseIP(binding.HostIp)
  541. if ip == nil {
  542. return nat.PortBinding{}, fmt.Errorf("Bad parameter: invalid host ip %s", binding.HostIp)
  543. }
  544. }
  545. // host ip, proto, and host port
  546. var container net.Addr
  547. switch proto {
  548. case "tcp":
  549. container = &net.TCPAddr{IP: network.IP, Port: containerPort}
  550. case "udp":
  551. container = &net.UDPAddr{IP: network.IP, Port: containerPort}
  552. default:
  553. return nat.PortBinding{}, fmt.Errorf("unsupported address type %s", proto)
  554. }
  555. //
  556. // Try up to 10 times to get a port that's not already allocated.
  557. //
  558. // In the event of failure to bind, return the error that portmapper.Map
  559. // yields.
  560. //
  561. var (
  562. host net.Addr
  563. err error
  564. )
  565. hostPort, err := nat.ParsePort(binding.HostPort)
  566. if err != nil {
  567. return nat.PortBinding{}, err
  568. }
  569. for i := 0; i < MaxAllocatedPortAttempts; i++ {
  570. if host, err = portMapper.Map(container, ip, hostPort); err == nil {
  571. break
  572. }
  573. // There is no point in immediately retrying to map an explicitly
  574. // chosen port.
  575. if hostPort != 0 {
  576. logrus.Warnf("Failed to allocate and map port %d: %s", hostPort, err)
  577. break
  578. }
  579. logrus.Warnf("Failed to allocate and map port: %s, retry: %d", err, i+1)
  580. }
  581. if err != nil {
  582. return nat.PortBinding{}, err
  583. }
  584. network.PortMappings = append(network.PortMappings, host)
  585. switch netAddr := host.(type) {
  586. case *net.TCPAddr:
  587. return nat.PortBinding{HostIp: netAddr.IP.String(), HostPort: strconv.Itoa(netAddr.Port)}, nil
  588. case *net.UDPAddr:
  589. return nat.PortBinding{HostIp: netAddr.IP.String(), HostPort: strconv.Itoa(netAddr.Port)}, nil
  590. default:
  591. return nat.PortBinding{}, fmt.Errorf("unsupported address type %T", netAddr)
  592. }
  593. }
  594. //TODO: should it return something more than just an error?
  595. func LinkContainers(action, parentIP, childIP string, ports []nat.Port, ignoreErrors bool) error {
  596. var nfAction iptables.Action
  597. switch action {
  598. case "-A":
  599. nfAction = iptables.Append
  600. case "-I":
  601. nfAction = iptables.Insert
  602. case "-D":
  603. nfAction = iptables.Delete
  604. default:
  605. return fmt.Errorf("Invalid action '%s' specified", action)
  606. }
  607. ip1 := net.ParseIP(parentIP)
  608. if ip1 == nil {
  609. return fmt.Errorf("Parent IP '%s' is invalid", parentIP)
  610. }
  611. ip2 := net.ParseIP(childIP)
  612. if ip2 == nil {
  613. return fmt.Errorf("Child IP '%s' is invalid", childIP)
  614. }
  615. chain := iptables.Chain{Name: "DOCKER", Bridge: bridgeIface}
  616. for _, port := range ports {
  617. if err := chain.Link(nfAction, ip1, ip2, port.Int(), port.Proto()); !ignoreErrors && err != nil {
  618. return err
  619. }
  620. }
  621. return nil
  622. }