driver.go 20 KB

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