driver.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package bridge
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "net"
  7. "strings"
  8. "github.com/dotcloud/docker/daemon/networkdriver"
  9. "github.com/dotcloud/docker/daemon/networkdriver/ipallocator"
  10. "github.com/dotcloud/docker/daemon/networkdriver/portallocator"
  11. "github.com/dotcloud/docker/daemon/networkdriver/portmapper"
  12. "github.com/dotcloud/docker/engine"
  13. "github.com/dotcloud/docker/pkg/iptables"
  14. "github.com/dotcloud/docker/pkg/netlink"
  15. "github.com/dotcloud/docker/pkg/networkfs/resolvconf"
  16. "github.com/dotcloud/docker/utils"
  17. )
  18. const (
  19. DefaultNetworkBridge = "docker0"
  20. )
  21. // Network interface represents the networking stack of a container
  22. type networkInterface struct {
  23. IP net.IP
  24. PortMappings []net.Addr // there are mappings to the host interfaces
  25. }
  26. var (
  27. addrs = []string{
  28. // Here we don't follow the convention of using the 1st IP of the range for the gateway.
  29. // This is to use the same gateway IPs as the /24 ranges, which predate the /16 ranges.
  30. // In theory this shouldn't matter - in practice there's bound to be a few scripts relying
  31. // on the internal addressing or other stupid things like that.
  32. // They shouldn't, but hey, let's not break them unless we really have to.
  33. "172.17.42.1/16", // Don't use 172.16.0.0/16, it conflicts with EC2 DNS 172.16.0.23
  34. "10.0.42.1/16", // Don't even try using the entire /8, that's too intrusive
  35. "10.1.42.1/16",
  36. "10.42.42.1/16",
  37. "172.16.42.1/24",
  38. "172.16.43.1/24",
  39. "172.16.44.1/24",
  40. "10.0.42.1/24",
  41. "10.0.43.1/24",
  42. "192.168.42.1/24",
  43. "192.168.43.1/24",
  44. "192.168.44.1/24",
  45. }
  46. bridgeIface string
  47. bridgeNetwork *net.IPNet
  48. defaultBindingIP = net.ParseIP("0.0.0.0")
  49. currentInterfaces = make(map[string]*networkInterface)
  50. )
  51. func InitDriver(job *engine.Job) engine.Status {
  52. var (
  53. network *net.IPNet
  54. enableIPTables = job.GetenvBool("EnableIptables")
  55. icc = job.GetenvBool("InterContainerCommunication")
  56. ipForward = job.GetenvBool("EnableIpForward")
  57. bridgeIP = job.Getenv("BridgeIP")
  58. )
  59. if defaultIP := job.Getenv("DefaultBindingIP"); defaultIP != "" {
  60. defaultBindingIP = net.ParseIP(defaultIP)
  61. }
  62. bridgeIface = job.Getenv("BridgeIface")
  63. usingDefaultBridge := false
  64. if bridgeIface == "" {
  65. usingDefaultBridge = true
  66. bridgeIface = DefaultNetworkBridge
  67. }
  68. addr, err := networkdriver.GetIfaceAddr(bridgeIface)
  69. if err != nil {
  70. // If we're not using the default bridge, fail without trying to create it
  71. if !usingDefaultBridge {
  72. job.Logf("bridge not found: %s", bridgeIface)
  73. return job.Error(err)
  74. }
  75. // If the iface is not found, try to create it
  76. job.Logf("creating new bridge for %s", bridgeIface)
  77. if err := createBridge(bridgeIP); err != nil {
  78. return job.Error(err)
  79. }
  80. job.Logf("getting iface addr")
  81. addr, err = networkdriver.GetIfaceAddr(bridgeIface)
  82. if err != nil {
  83. return job.Error(err)
  84. }
  85. network = addr.(*net.IPNet)
  86. } else {
  87. network = addr.(*net.IPNet)
  88. // validate that the bridge ip matches the ip specified by BridgeIP
  89. if bridgeIP != "" {
  90. bip, _, err := net.ParseCIDR(bridgeIP)
  91. if err != nil {
  92. return job.Error(err)
  93. }
  94. if !network.IP.Equal(bip) {
  95. return job.Errorf("bridge ip (%s) does not match existing bridge configuration %s", network.IP, bip)
  96. }
  97. }
  98. }
  99. // Configure iptables for link support
  100. if enableIPTables {
  101. if err := setupIPTables(addr, icc); err != nil {
  102. return job.Error(err)
  103. }
  104. }
  105. if ipForward {
  106. // Enable IPv4 forwarding
  107. if err := ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte{'1', '\n'}, 0644); err != nil {
  108. job.Logf("WARNING: unable to enable IPv4 forwarding: %s\n", err)
  109. }
  110. }
  111. // We can always try removing the iptables
  112. if err := iptables.RemoveExistingChain("DOCKER"); err != nil {
  113. return job.Error(err)
  114. }
  115. if enableIPTables {
  116. chain, err := iptables.NewChain("DOCKER", bridgeIface)
  117. if err != nil {
  118. return job.Error(err)
  119. }
  120. portmapper.SetIptablesChain(chain)
  121. }
  122. bridgeNetwork = network
  123. // https://github.com/dotcloud/docker/issues/2768
  124. job.Eng.Hack_SetGlobalVar("httpapi.bridgeIP", bridgeNetwork.IP)
  125. for name, f := range map[string]engine.Handler{
  126. "allocate_interface": Allocate,
  127. "release_interface": Release,
  128. "allocate_port": AllocatePort,
  129. "link": LinkContainers,
  130. } {
  131. if err := job.Eng.Register(name, f); err != nil {
  132. return job.Error(err)
  133. }
  134. }
  135. return engine.StatusOK
  136. }
  137. func setupIPTables(addr net.Addr, icc bool) error {
  138. // Enable NAT
  139. natArgs := []string{"POSTROUTING", "-t", "nat", "-s", addr.String(), "!", "-d", addr.String(), "-j", "MASQUERADE"}
  140. if !iptables.Exists(natArgs...) {
  141. if output, err := iptables.Raw(append([]string{"-I"}, natArgs...)...); err != nil {
  142. return fmt.Errorf("Unable to enable network bridge NAT: %s", err)
  143. } else if len(output) != 0 {
  144. return fmt.Errorf("Error iptables postrouting: %s", output)
  145. }
  146. }
  147. var (
  148. args = []string{"FORWARD", "-i", bridgeIface, "-o", bridgeIface, "-j"}
  149. acceptArgs = append(args, "ACCEPT")
  150. dropArgs = append(args, "DROP")
  151. )
  152. if !icc {
  153. iptables.Raw(append([]string{"-D"}, acceptArgs...)...)
  154. if !iptables.Exists(dropArgs...) {
  155. utils.Debugf("Disable inter-container communication")
  156. if output, err := iptables.Raw(append([]string{"-I"}, dropArgs...)...); err != nil {
  157. return fmt.Errorf("Unable to prevent intercontainer communication: %s", err)
  158. } else if len(output) != 0 {
  159. return fmt.Errorf("Error disabling intercontainer communication: %s", output)
  160. }
  161. }
  162. } else {
  163. iptables.Raw(append([]string{"-D"}, dropArgs...)...)
  164. if !iptables.Exists(acceptArgs...) {
  165. utils.Debugf("Enable inter-container communication")
  166. if output, err := iptables.Raw(append([]string{"-I"}, acceptArgs...)...); err != nil {
  167. return fmt.Errorf("Unable to allow intercontainer communication: %s", err)
  168. } else if len(output) != 0 {
  169. return fmt.Errorf("Error enabling intercontainer communication: %s", output)
  170. }
  171. }
  172. }
  173. // Accept all non-intercontainer outgoing packets
  174. outgoingArgs := []string{"FORWARD", "-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}
  175. if !iptables.Exists(outgoingArgs...) {
  176. if output, err := iptables.Raw(append([]string{"-I"}, outgoingArgs...)...); err != nil {
  177. return fmt.Errorf("Unable to allow outgoing packets: %s", err)
  178. } else if len(output) != 0 {
  179. return fmt.Errorf("Error iptables allow outgoing: %s", output)
  180. }
  181. }
  182. // Accept incoming packets for existing connections
  183. existingArgs := []string{"FORWARD", "-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}
  184. if !iptables.Exists(existingArgs...) {
  185. if output, err := iptables.Raw(append([]string{"-I"}, existingArgs...)...); err != nil {
  186. return fmt.Errorf("Unable to allow incoming packets: %s", err)
  187. } else if len(output) != 0 {
  188. return fmt.Errorf("Error iptables allow incoming: %s", output)
  189. }
  190. }
  191. return nil
  192. }
  193. // CreateBridgeIface creates a network bridge interface on the host system with the name `ifaceName`,
  194. // and attempts to configure it with an address which doesn't conflict with any other interface on the host.
  195. // If it can't find an address which doesn't conflict, it will return an error.
  196. func createBridge(bridgeIP string) error {
  197. nameservers := []string{}
  198. resolvConf, _ := resolvconf.Get()
  199. // we don't check for an error here, because we don't really care
  200. // if we can't read /etc/resolv.conf. So instead we skip the append
  201. // if resolvConf is nil. It either doesn't exist, or we can't read it
  202. // for some reason.
  203. if resolvConf != nil {
  204. nameservers = append(nameservers, resolvconf.GetNameserversAsCIDR(resolvConf)...)
  205. }
  206. var ifaceAddr string
  207. if len(bridgeIP) != 0 {
  208. _, _, err := net.ParseCIDR(bridgeIP)
  209. if err != nil {
  210. return err
  211. }
  212. ifaceAddr = bridgeIP
  213. } else {
  214. for _, addr := range addrs {
  215. _, dockerNetwork, err := net.ParseCIDR(addr)
  216. if err != nil {
  217. return err
  218. }
  219. if err := networkdriver.CheckNameserverOverlaps(nameservers, dockerNetwork); err == nil {
  220. if err := networkdriver.CheckRouteOverlaps(dockerNetwork); err == nil {
  221. ifaceAddr = addr
  222. break
  223. } else {
  224. utils.Debugf("%s %s", addr, err)
  225. }
  226. }
  227. }
  228. }
  229. if ifaceAddr == "" {
  230. 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)
  231. }
  232. utils.Debugf("Creating bridge %s with network %s", bridgeIface, ifaceAddr)
  233. if err := createBridgeIface(bridgeIface); err != nil {
  234. return err
  235. }
  236. iface, err := net.InterfaceByName(bridgeIface)
  237. if err != nil {
  238. return err
  239. }
  240. ipAddr, ipNet, err := net.ParseCIDR(ifaceAddr)
  241. if err != nil {
  242. return err
  243. }
  244. if netlink.NetworkLinkAddIp(iface, ipAddr, ipNet); err != nil {
  245. return fmt.Errorf("Unable to add private network: %s", err)
  246. }
  247. if err := netlink.NetworkLinkUp(iface); err != nil {
  248. return fmt.Errorf("Unable to start network bridge: %s", err)
  249. }
  250. return nil
  251. }
  252. func createBridgeIface(name string) error {
  253. kv, err := utils.GetKernelVersion()
  254. // only set the bridge's mac address if the kernel version is > 3.3
  255. // before that it was not supported
  256. setBridgeMacAddr := err == nil && (kv.Kernel >= 3 && kv.Major >= 3)
  257. utils.Debugf("setting bridge mac address = %v", setBridgeMacAddr)
  258. return netlink.CreateBridge(name, setBridgeMacAddr)
  259. }
  260. // Allocate a network interface
  261. func Allocate(job *engine.Job) engine.Status {
  262. var (
  263. ip *net.IP
  264. err error
  265. id = job.Args[0]
  266. requestedIP = net.ParseIP(job.Getenv("RequestedIP"))
  267. )
  268. if requestedIP != nil {
  269. ip, err = ipallocator.RequestIP(bridgeNetwork, &requestedIP)
  270. } else {
  271. ip, err = ipallocator.RequestIP(bridgeNetwork, nil)
  272. }
  273. if err != nil {
  274. return job.Error(err)
  275. }
  276. out := engine.Env{}
  277. out.Set("IP", ip.String())
  278. out.Set("Mask", bridgeNetwork.Mask.String())
  279. out.Set("Gateway", bridgeNetwork.IP.String())
  280. out.Set("Bridge", bridgeIface)
  281. size, _ := bridgeNetwork.Mask.Size()
  282. out.SetInt("IPPrefixLen", size)
  283. currentInterfaces[id] = &networkInterface{
  284. IP: *ip,
  285. }
  286. out.WriteTo(job.Stdout)
  287. return engine.StatusOK
  288. }
  289. // release an interface for a select ip
  290. func Release(job *engine.Job) engine.Status {
  291. var (
  292. id = job.Args[0]
  293. containerInterface = currentInterfaces[id]
  294. ip net.IP
  295. port int
  296. proto string
  297. )
  298. if containerInterface == nil {
  299. return job.Errorf("No network information to release for %s", id)
  300. }
  301. for _, nat := range containerInterface.PortMappings {
  302. if err := portmapper.Unmap(nat); err != nil {
  303. log.Printf("Unable to unmap port %s: %s", nat, err)
  304. }
  305. // this is host mappings
  306. switch a := nat.(type) {
  307. case *net.TCPAddr:
  308. proto = "tcp"
  309. ip = a.IP
  310. port = a.Port
  311. case *net.UDPAddr:
  312. proto = "udp"
  313. ip = a.IP
  314. port = a.Port
  315. }
  316. if err := portallocator.ReleasePort(ip, proto, port); err != nil {
  317. log.Printf("Unable to release port %s", nat)
  318. }
  319. }
  320. if err := ipallocator.ReleaseIP(bridgeNetwork, &containerInterface.IP); err != nil {
  321. log.Printf("Unable to release ip %s\n", err)
  322. }
  323. return engine.StatusOK
  324. }
  325. // Allocate an external port and map it to the interface
  326. func AllocatePort(job *engine.Job) engine.Status {
  327. var (
  328. err error
  329. ip = defaultBindingIP
  330. id = job.Args[0]
  331. hostIP = job.Getenv("HostIP")
  332. hostPort = job.GetenvInt("HostPort")
  333. containerPort = job.GetenvInt("ContainerPort")
  334. proto = job.Getenv("Proto")
  335. network = currentInterfaces[id]
  336. )
  337. if hostIP != "" {
  338. ip = net.ParseIP(hostIP)
  339. }
  340. // host ip, proto, and host port
  341. hostPort, err = portallocator.RequestPort(ip, proto, hostPort)
  342. if err != nil {
  343. return job.Error(err)
  344. }
  345. var (
  346. container net.Addr
  347. host net.Addr
  348. )
  349. if proto == "tcp" {
  350. host = &net.TCPAddr{IP: ip, Port: hostPort}
  351. container = &net.TCPAddr{IP: network.IP, Port: containerPort}
  352. } else {
  353. host = &net.UDPAddr{IP: ip, Port: hostPort}
  354. container = &net.UDPAddr{IP: network.IP, Port: containerPort}
  355. }
  356. if err := portmapper.Map(container, ip, hostPort); err != nil {
  357. portallocator.ReleasePort(ip, proto, hostPort)
  358. return job.Error(err)
  359. }
  360. network.PortMappings = append(network.PortMappings, host)
  361. out := engine.Env{}
  362. out.Set("HostIP", ip.String())
  363. out.SetInt("HostPort", hostPort)
  364. if _, err := out.WriteTo(job.Stdout); err != nil {
  365. return job.Error(err)
  366. }
  367. return engine.StatusOK
  368. }
  369. func LinkContainers(job *engine.Job) engine.Status {
  370. var (
  371. action = job.Args[0]
  372. childIP = job.Getenv("ChildIP")
  373. parentIP = job.Getenv("ParentIP")
  374. ignoreErrors = job.GetenvBool("IgnoreErrors")
  375. ports = job.GetenvList("Ports")
  376. )
  377. split := func(p string) (string, string) {
  378. parts := strings.Split(p, "/")
  379. return parts[0], parts[1]
  380. }
  381. for _, p := range ports {
  382. port, proto := split(p)
  383. if output, err := iptables.Raw(action, "FORWARD",
  384. "-i", bridgeIface, "-o", bridgeIface,
  385. "-p", proto,
  386. "-s", parentIP,
  387. "--dport", port,
  388. "-d", childIP,
  389. "-j", "ACCEPT"); !ignoreErrors && err != nil {
  390. return job.Error(err)
  391. } else if len(output) != 0 {
  392. return job.Errorf("Error toggle iptables forward: %s", output)
  393. }
  394. if output, err := iptables.Raw(action, "FORWARD",
  395. "-i", bridgeIface, "-o", bridgeIface,
  396. "-p", proto,
  397. "-s", childIP,
  398. "--sport", port,
  399. "-d", parentIP,
  400. "-j", "ACCEPT"); !ignoreErrors && err != nil {
  401. return job.Error(err)
  402. } else if len(output) != 0 {
  403. return job.Errorf("Error toggle iptables forward: %s", output)
  404. }
  405. }
  406. return engine.StatusOK
  407. }