container_linux.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. // +build linux
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/daemon/network"
  17. "github.com/docker/docker/links"
  18. "github.com/docker/docker/nat"
  19. "github.com/docker/docker/pkg/archive"
  20. "github.com/docker/docker/pkg/directory"
  21. "github.com/docker/docker/pkg/ioutils"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/docker/pkg/ulimit"
  24. "github.com/docker/docker/runconfig"
  25. "github.com/docker/docker/utils"
  26. "github.com/docker/libcontainer/configs"
  27. "github.com/docker/libcontainer/devices"
  28. "github.com/docker/libnetwork"
  29. "github.com/docker/libnetwork/netlabel"
  30. "github.com/docker/libnetwork/options"
  31. "github.com/docker/libnetwork/types"
  32. )
  33. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  34. type Container struct {
  35. CommonContainer
  36. // Fields below here are platform specific.
  37. AppArmorProfile string
  38. activeLinks map[string]*links.Link
  39. }
  40. func killProcessDirectly(container *Container) error {
  41. if _, err := container.WaitStop(10 * time.Second); err != nil {
  42. // Ensure that we don't kill ourselves
  43. if pid := container.GetPid(); pid != 0 {
  44. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  45. if err := syscall.Kill(pid, 9); err != nil {
  46. if err != syscall.ESRCH {
  47. return err
  48. }
  49. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  50. }
  51. }
  52. }
  53. return nil
  54. }
  55. func (container *Container) setupLinkedContainers() ([]string, error) {
  56. var (
  57. env []string
  58. daemon = container.daemon
  59. )
  60. children, err := daemon.Children(container.Name)
  61. if err != nil {
  62. return nil, err
  63. }
  64. if len(children) > 0 {
  65. container.activeLinks = make(map[string]*links.Link, len(children))
  66. // If we encounter an error make sure that we rollback any network
  67. // config and iptables changes
  68. rollback := func() {
  69. for _, link := range container.activeLinks {
  70. link.Disable()
  71. }
  72. container.activeLinks = nil
  73. }
  74. for linkAlias, child := range children {
  75. if !child.IsRunning() {
  76. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  77. }
  78. link, err := links.NewLink(
  79. container.NetworkSettings.IPAddress,
  80. child.NetworkSettings.IPAddress,
  81. linkAlias,
  82. child.Config.Env,
  83. child.Config.ExposedPorts,
  84. )
  85. if err != nil {
  86. rollback()
  87. return nil, err
  88. }
  89. container.activeLinks[link.Alias()] = link
  90. if err := link.Enable(); err != nil {
  91. rollback()
  92. return nil, err
  93. }
  94. for _, envVar := range link.ToEnv() {
  95. env = append(env, envVar)
  96. }
  97. }
  98. }
  99. return env, nil
  100. }
  101. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  102. // if a domain name was specified, append it to the hostname (see #7851)
  103. fullHostname := container.Config.Hostname
  104. if container.Config.Domainname != "" {
  105. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  106. }
  107. // Setup environment
  108. env := []string{
  109. "PATH=" + DefaultPathEnv,
  110. "HOSTNAME=" + fullHostname,
  111. // Note: we don't set HOME here because it'll get autoset intelligently
  112. // based on the value of USER inside dockerinit, but only if it isn't
  113. // set already (ie, that can be overridden by setting HOME via -e or ENV
  114. // in a Dockerfile).
  115. }
  116. if container.Config.Tty {
  117. env = append(env, "TERM=xterm")
  118. }
  119. env = append(env, linkedEnv...)
  120. // because the env on the container can override certain default values
  121. // we need to replace the 'env' keys where they match and append anything
  122. // else.
  123. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  124. return env
  125. }
  126. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  127. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  128. // if there was no error, return the device
  129. if err == nil {
  130. device.Path = deviceMapping.PathInContainer
  131. return append(devs, device), nil
  132. }
  133. // if the device is not a device node
  134. // try to see if it's a directory holding many devices
  135. if err == devices.ErrNotADevice {
  136. // check if it is a directory
  137. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  138. // mount the internal devices recursively
  139. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  140. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  141. if e != nil {
  142. // ignore the device
  143. return nil
  144. }
  145. // add the device to userSpecified devices
  146. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  147. devs = append(devs, childDevice)
  148. return nil
  149. })
  150. }
  151. }
  152. if len(devs) > 0 {
  153. return devs, nil
  154. }
  155. return devs, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  156. }
  157. func populateCommand(c *Container, env []string) error {
  158. en := &execdriver.Network{
  159. NamespacePath: c.NetworkSettings.SandboxKey,
  160. }
  161. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  162. if parts[0] == "container" {
  163. nc, err := c.getNetworkedContainer()
  164. if err != nil {
  165. return err
  166. }
  167. en.ContainerID = nc.ID
  168. }
  169. ipc := &execdriver.Ipc{}
  170. if c.hostConfig.IpcMode.IsContainer() {
  171. ic, err := c.getIpcContainer()
  172. if err != nil {
  173. return err
  174. }
  175. ipc.ContainerID = ic.ID
  176. } else {
  177. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  178. }
  179. pid := &execdriver.Pid{}
  180. pid.HostPid = c.hostConfig.PidMode.IsHost()
  181. uts := &execdriver.UTS{
  182. HostUTS: c.hostConfig.UTSMode.IsHost(),
  183. }
  184. // Build lists of devices allowed and created within the container.
  185. var userSpecifiedDevices []*configs.Device
  186. for _, deviceMapping := range c.hostConfig.Devices {
  187. devs, err := getDevicesFromPath(deviceMapping)
  188. if err != nil {
  189. return err
  190. }
  191. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  192. }
  193. allowedDevices := append(configs.DefaultAllowedDevices, userSpecifiedDevices...)
  194. autoCreatedDevices := append(configs.DefaultAutoCreatedDevices, userSpecifiedDevices...)
  195. // TODO: this can be removed after lxc-conf is fully deprecated
  196. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  197. if err != nil {
  198. return err
  199. }
  200. var rlimits []*ulimit.Rlimit
  201. ulimits := c.hostConfig.Ulimits
  202. // Merge ulimits with daemon defaults
  203. ulIdx := make(map[string]*ulimit.Ulimit)
  204. for _, ul := range ulimits {
  205. ulIdx[ul.Name] = ul
  206. }
  207. for name, ul := range c.daemon.config.Ulimits {
  208. if _, exists := ulIdx[name]; !exists {
  209. ulimits = append(ulimits, ul)
  210. }
  211. }
  212. for _, limit := range ulimits {
  213. rl, err := limit.GetRlimit()
  214. if err != nil {
  215. return err
  216. }
  217. rlimits = append(rlimits, rl)
  218. }
  219. resources := &execdriver.Resources{
  220. Memory: c.hostConfig.Memory,
  221. MemorySwap: c.hostConfig.MemorySwap,
  222. CpuShares: c.hostConfig.CpuShares,
  223. CpusetCpus: c.hostConfig.CpusetCpus,
  224. CpusetMems: c.hostConfig.CpusetMems,
  225. CpuPeriod: c.hostConfig.CpuPeriod,
  226. CpuQuota: c.hostConfig.CpuQuota,
  227. BlkioWeight: c.hostConfig.BlkioWeight,
  228. Rlimits: rlimits,
  229. OomKillDisable: c.hostConfig.OomKillDisable,
  230. }
  231. processConfig := execdriver.ProcessConfig{
  232. Privileged: c.hostConfig.Privileged,
  233. Entrypoint: c.Path,
  234. Arguments: c.Args,
  235. Tty: c.Config.Tty,
  236. User: c.Config.User,
  237. }
  238. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  239. processConfig.Env = env
  240. c.command = &execdriver.Command{
  241. ID: c.ID,
  242. Rootfs: c.RootfsPath(),
  243. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  244. InitPath: "/.dockerinit",
  245. WorkingDir: c.Config.WorkingDir,
  246. Network: en,
  247. Ipc: ipc,
  248. Pid: pid,
  249. UTS: uts,
  250. Resources: resources,
  251. AllowedDevices: allowedDevices,
  252. AutoCreatedDevices: autoCreatedDevices,
  253. CapAdd: c.hostConfig.CapAdd,
  254. CapDrop: c.hostConfig.CapDrop,
  255. ProcessConfig: processConfig,
  256. ProcessLabel: c.GetProcessLabel(),
  257. MountLabel: c.GetMountLabel(),
  258. LxcConfig: lxcConfig,
  259. AppArmorProfile: c.AppArmorProfile,
  260. CgroupParent: c.hostConfig.CgroupParent,
  261. }
  262. return nil
  263. }
  264. // GetSize, return real size, virtual size
  265. func (container *Container) GetSize() (int64, int64) {
  266. var (
  267. sizeRw, sizeRootfs int64
  268. err error
  269. driver = container.daemon.driver
  270. )
  271. if err := container.Mount(); err != nil {
  272. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  273. return sizeRw, sizeRootfs
  274. }
  275. defer container.Unmount()
  276. initID := fmt.Sprintf("%s-init", container.ID)
  277. sizeRw, err = driver.DiffSize(container.ID, initID)
  278. if err != nil {
  279. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  280. // FIXME: GetSize should return an error. Not changing it now in case
  281. // there is a side-effect.
  282. sizeRw = -1
  283. }
  284. if _, err = os.Stat(container.basefs); err == nil {
  285. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  286. sizeRootfs = -1
  287. }
  288. }
  289. return sizeRw, sizeRootfs
  290. }
  291. func (container *Container) buildHostnameFile() error {
  292. hostnamePath, err := container.GetRootResourcePath("hostname")
  293. if err != nil {
  294. return err
  295. }
  296. container.HostnamePath = hostnamePath
  297. if container.Config.Domainname != "" {
  298. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  299. }
  300. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  301. }
  302. func (container *Container) buildJoinOptions() ([]libnetwork.EndpointOption, error) {
  303. var (
  304. joinOptions []libnetwork.EndpointOption
  305. err error
  306. dns []string
  307. dnsSearch []string
  308. )
  309. joinOptions = append(joinOptions, libnetwork.JoinOptionHostname(container.Config.Hostname),
  310. libnetwork.JoinOptionDomainname(container.Config.Domainname))
  311. if container.hostConfig.NetworkMode.IsHost() {
  312. joinOptions = append(joinOptions, libnetwork.JoinOptionUseDefaultSandbox())
  313. }
  314. container.HostsPath, err = container.GetRootResourcePath("hosts")
  315. if err != nil {
  316. return nil, err
  317. }
  318. joinOptions = append(joinOptions, libnetwork.JoinOptionHostsPath(container.HostsPath))
  319. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  320. if err != nil {
  321. return nil, err
  322. }
  323. joinOptions = append(joinOptions, libnetwork.JoinOptionResolvConfPath(container.ResolvConfPath))
  324. if len(container.hostConfig.Dns) > 0 {
  325. dns = container.hostConfig.Dns
  326. } else if len(container.daemon.config.Dns) > 0 {
  327. dns = container.daemon.config.Dns
  328. }
  329. for _, d := range dns {
  330. joinOptions = append(joinOptions, libnetwork.JoinOptionDNS(d))
  331. }
  332. if len(container.hostConfig.DnsSearch) > 0 {
  333. dnsSearch = container.hostConfig.DnsSearch
  334. } else if len(container.daemon.config.DnsSearch) > 0 {
  335. dnsSearch = container.daemon.config.DnsSearch
  336. }
  337. for _, ds := range dnsSearch {
  338. joinOptions = append(joinOptions, libnetwork.JoinOptionDNSSearch(ds))
  339. }
  340. if container.NetworkSettings.SecondaryIPAddresses != nil {
  341. name := container.Config.Hostname
  342. if container.Config.Domainname != "" {
  343. name = name + "." + container.Config.Domainname
  344. }
  345. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  346. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(name, a.Addr))
  347. }
  348. }
  349. var childEndpoints, parentEndpoints []string
  350. children, err := container.daemon.Children(container.Name)
  351. if err != nil {
  352. return nil, err
  353. }
  354. for linkAlias, child := range children {
  355. _, alias := path.Split(linkAlias)
  356. // allow access to the linked container via the alias, real name, and container hostname
  357. aliasList := alias + " " + child.Config.Hostname
  358. // only add the name if alias isn't equal to the name
  359. if alias != child.Name[1:] {
  360. aliasList = aliasList + " " + child.Name[1:]
  361. }
  362. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  363. if child.NetworkSettings.EndpointID != "" {
  364. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  365. }
  366. }
  367. for _, extraHost := range container.hostConfig.ExtraHosts {
  368. // allow IPv6 addresses in extra hosts; only split on first ":"
  369. parts := strings.SplitN(extraHost, ":", 2)
  370. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(parts[0], parts[1]))
  371. }
  372. refs := container.daemon.ContainerGraph().RefPaths(container.ID)
  373. for _, ref := range refs {
  374. if ref.ParentID == "0" {
  375. continue
  376. }
  377. c, err := container.daemon.Get(ref.ParentID)
  378. if err != nil {
  379. logrus.Error(err)
  380. }
  381. if c != nil && !container.daemon.config.DisableNetwork && container.hostConfig.NetworkMode.IsPrivate() {
  382. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  383. joinOptions = append(joinOptions, libnetwork.JoinOptionParentUpdate(c.NetworkSettings.EndpointID, ref.Name, container.NetworkSettings.IPAddress))
  384. if c.NetworkSettings.EndpointID != "" {
  385. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  386. }
  387. }
  388. }
  389. linkOptions := options.Generic{
  390. netlabel.GenericData: options.Generic{
  391. "ParentEndpoints": parentEndpoints,
  392. "ChildEndpoints": childEndpoints,
  393. },
  394. }
  395. joinOptions = append(joinOptions, libnetwork.JoinOptionGeneric(linkOptions))
  396. return joinOptions, nil
  397. }
  398. func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  399. if ep == nil {
  400. return nil, fmt.Errorf("invalid endpoint while building port map info")
  401. }
  402. if networkSettings == nil {
  403. return nil, fmt.Errorf("invalid networksettings while building port map info")
  404. }
  405. driverInfo, err := ep.DriverInfo()
  406. if err != nil {
  407. return nil, err
  408. }
  409. if driverInfo == nil {
  410. // It is not an error for epInfo to be nil
  411. return networkSettings, nil
  412. }
  413. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  414. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  415. }
  416. mapData, ok := driverInfo[netlabel.PortMap]
  417. if !ok {
  418. return networkSettings, nil
  419. }
  420. if portMapping, ok := mapData.([]types.PortBinding); ok {
  421. networkSettings.Ports = nat.PortMap{}
  422. for _, pp := range portMapping {
  423. natPort := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  424. natBndg := nat.PortBinding{HostIp: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  425. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  426. }
  427. }
  428. return networkSettings, nil
  429. }
  430. func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  431. if ep == nil {
  432. return nil, fmt.Errorf("invalid endpoint while building port map info")
  433. }
  434. if networkSettings == nil {
  435. return nil, fmt.Errorf("invalid networksettings while building port map info")
  436. }
  437. epInfo := ep.Info()
  438. if epInfo == nil {
  439. // It is not an error to get an empty endpoint info
  440. return networkSettings, nil
  441. }
  442. ifaceList := epInfo.InterfaceList()
  443. if len(ifaceList) == 0 {
  444. return networkSettings, nil
  445. }
  446. iface := ifaceList[0]
  447. ones, _ := iface.Address().Mask.Size()
  448. networkSettings.IPAddress = iface.Address().IP.String()
  449. networkSettings.IPPrefixLen = ones
  450. if iface.AddressIPv6().IP.To16() != nil {
  451. onesv6, _ := iface.AddressIPv6().Mask.Size()
  452. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  453. networkSettings.GlobalIPv6PrefixLen = onesv6
  454. }
  455. if len(ifaceList) == 1 {
  456. return networkSettings, nil
  457. }
  458. networkSettings.SecondaryIPAddresses = make([]network.Address, 0, len(ifaceList)-1)
  459. networkSettings.SecondaryIPv6Addresses = make([]network.Address, 0, len(ifaceList)-1)
  460. for _, iface := range ifaceList[1:] {
  461. ones, _ := iface.Address().Mask.Size()
  462. addr := network.Address{Addr: iface.Address().IP.String(), PrefixLen: ones}
  463. networkSettings.SecondaryIPAddresses = append(networkSettings.SecondaryIPAddresses, addr)
  464. if iface.AddressIPv6().IP.To16() != nil {
  465. onesv6, _ := iface.AddressIPv6().Mask.Size()
  466. addrv6 := network.Address{Addr: iface.AddressIPv6().IP.String(), PrefixLen: onesv6}
  467. networkSettings.SecondaryIPv6Addresses = append(networkSettings.SecondaryIPv6Addresses, addrv6)
  468. }
  469. }
  470. return networkSettings, nil
  471. }
  472. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  473. epInfo := ep.Info()
  474. if epInfo == nil {
  475. // It is not an error to get an empty endpoint info
  476. return nil
  477. }
  478. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  479. if epInfo.GatewayIPv6().To16() != nil {
  480. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  481. }
  482. container.NetworkSettings.SandboxKey = epInfo.SandboxKey()
  483. return nil
  484. }
  485. func (container *Container) updateNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  486. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  487. networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings)
  488. if err != nil {
  489. return err
  490. }
  491. networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
  492. if err != nil {
  493. return err
  494. }
  495. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  496. networkSettings.Bridge = container.daemon.config.Bridge.Iface
  497. }
  498. container.NetworkSettings = networkSettings
  499. return nil
  500. }
  501. func (container *Container) UpdateNetwork() error {
  502. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  503. if err != nil {
  504. return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  505. }
  506. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  507. if err != nil {
  508. return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  509. }
  510. if err := ep.Leave(container.ID); err != nil {
  511. return fmt.Errorf("endpoint leave failed: %v", err)
  512. }
  513. joinOptions, err := container.buildJoinOptions()
  514. if err != nil {
  515. return fmt.Errorf("Update network failed: %v", err)
  516. }
  517. if _, err := ep.Join(container.ID, joinOptions...); err != nil {
  518. return fmt.Errorf("endpoint join failed: %v", err)
  519. }
  520. if err := container.updateJoinInfo(ep); err != nil {
  521. return fmt.Errorf("Updating join info failed: %v", err)
  522. }
  523. return nil
  524. }
  525. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  526. var (
  527. portSpecs = make(nat.PortSet)
  528. bindings = make(nat.PortMap)
  529. pbList []types.PortBinding
  530. exposeList []types.TransportPort
  531. createOptions []libnetwork.EndpointOption
  532. )
  533. if container.Config.PortSpecs != nil {
  534. if err := migratePortMappings(container.Config, container.hostConfig); err != nil {
  535. return nil, err
  536. }
  537. container.Config.PortSpecs = nil
  538. if err := container.WriteHostConfig(); err != nil {
  539. return nil, err
  540. }
  541. }
  542. if container.Config.ExposedPorts != nil {
  543. portSpecs = container.Config.ExposedPorts
  544. }
  545. if container.hostConfig.PortBindings != nil {
  546. for p, b := range container.hostConfig.PortBindings {
  547. bindings[p] = []nat.PortBinding{}
  548. for _, bb := range b {
  549. bindings[p] = append(bindings[p], nat.PortBinding{
  550. HostIp: bb.HostIp,
  551. HostPort: bb.HostPort,
  552. })
  553. }
  554. }
  555. }
  556. container.NetworkSettings.PortMapping = nil
  557. ports := make([]nat.Port, len(portSpecs))
  558. var i int
  559. for p := range portSpecs {
  560. ports[i] = p
  561. i++
  562. }
  563. nat.SortPortMap(ports, bindings)
  564. for _, port := range ports {
  565. expose := types.TransportPort{}
  566. expose.Proto = types.ParseProtocol(port.Proto())
  567. expose.Port = uint16(port.Int())
  568. exposeList = append(exposeList, expose)
  569. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  570. binding := bindings[port]
  571. for i := 0; i < len(binding); i++ {
  572. pbCopy := pb.GetCopy()
  573. pbCopy.HostPort = uint16(nat.Port(binding[i].HostPort).Int())
  574. pbCopy.HostIP = net.ParseIP(binding[i].HostIp)
  575. pbList = append(pbList, pbCopy)
  576. }
  577. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  578. pbList = append(pbList, pb)
  579. }
  580. }
  581. createOptions = append(createOptions,
  582. libnetwork.CreateOptionPortMapping(pbList),
  583. libnetwork.CreateOptionExposedPorts(exposeList))
  584. if container.Config.MacAddress != "" {
  585. mac, err := net.ParseMAC(container.Config.MacAddress)
  586. if err != nil {
  587. return nil, err
  588. }
  589. genericOption := options.Generic{
  590. netlabel.MacAddress: mac,
  591. }
  592. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  593. }
  594. return createOptions, nil
  595. }
  596. func (container *Container) AllocateNetwork() error {
  597. mode := container.hostConfig.NetworkMode
  598. if container.Config.NetworkDisabled || mode.IsContainer() {
  599. return nil
  600. }
  601. var err error
  602. n, err := container.daemon.netController.NetworkByName(string(mode))
  603. if err != nil {
  604. return fmt.Errorf("error locating network with name %s: %v", string(mode), err)
  605. }
  606. createOptions, err := container.buildCreateEndpointOptions()
  607. if err != nil {
  608. return err
  609. }
  610. ep, err := n.CreateEndpoint(container.Name, createOptions...)
  611. if err != nil {
  612. return err
  613. }
  614. if err := container.updateNetworkSettings(n, ep); err != nil {
  615. return err
  616. }
  617. joinOptions, err := container.buildJoinOptions()
  618. if err != nil {
  619. return err
  620. }
  621. if _, err := ep.Join(container.ID, joinOptions...); err != nil {
  622. return err
  623. }
  624. if err := container.updateJoinInfo(ep); err != nil {
  625. return fmt.Errorf("Updating join info failed: %v", err)
  626. }
  627. if err := container.WriteHostConfig(); err != nil {
  628. return err
  629. }
  630. return nil
  631. }
  632. func (container *Container) initializeNetworking() error {
  633. var err error
  634. // Make sure NetworkMode has an acceptable value before
  635. // initializing networking.
  636. if container.hostConfig.NetworkMode == runconfig.NetworkMode("") {
  637. container.hostConfig.NetworkMode = runconfig.NetworkMode("bridge")
  638. }
  639. if container.hostConfig.NetworkMode.IsContainer() {
  640. // we need to get the hosts files from the container to join
  641. nc, err := container.getNetworkedContainer()
  642. if err != nil {
  643. return err
  644. }
  645. container.HostnamePath = nc.HostnamePath
  646. container.HostsPath = nc.HostsPath
  647. container.ResolvConfPath = nc.ResolvConfPath
  648. container.Config.Hostname = nc.Config.Hostname
  649. container.Config.Domainname = nc.Config.Domainname
  650. return nil
  651. }
  652. if container.daemon.config.DisableNetwork {
  653. container.Config.NetworkDisabled = true
  654. }
  655. if container.hostConfig.NetworkMode.IsHost() {
  656. container.Config.Hostname, err = os.Hostname()
  657. if err != nil {
  658. return err
  659. }
  660. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  661. if len(parts) > 1 {
  662. container.Config.Hostname = parts[0]
  663. container.Config.Domainname = parts[1]
  664. }
  665. }
  666. if err := container.AllocateNetwork(); err != nil {
  667. return err
  668. }
  669. return container.buildHostnameFile()
  670. }
  671. // Make sure the config is compatible with the current kernel
  672. func (container *Container) verifyDaemonSettings() {
  673. if container.hostConfig.Memory > 0 && !container.daemon.sysInfo.MemoryLimit {
  674. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  675. container.hostConfig.Memory = 0
  676. }
  677. if container.hostConfig.Memory > 0 && container.hostConfig.MemorySwap != -1 && !container.daemon.sysInfo.SwapLimit {
  678. logrus.Warnf("Your kernel does not support swap limit capabilities. Limitation discarded.")
  679. container.hostConfig.MemorySwap = -1
  680. }
  681. if container.daemon.sysInfo.IPv4ForwardingDisabled {
  682. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  683. }
  684. }
  685. func (container *Container) ExportRw() (archive.Archive, error) {
  686. if err := container.Mount(); err != nil {
  687. return nil, err
  688. }
  689. if container.daemon == nil {
  690. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  691. }
  692. archive, err := container.daemon.Diff(container)
  693. if err != nil {
  694. container.Unmount()
  695. return nil, err
  696. }
  697. return ioutils.NewReadCloserWrapper(archive, func() error {
  698. err := archive.Close()
  699. container.Unmount()
  700. return err
  701. }),
  702. nil
  703. }
  704. func (container *Container) getIpcContainer() (*Container, error) {
  705. containerID := container.hostConfig.IpcMode.Container()
  706. c, err := container.daemon.Get(containerID)
  707. if err != nil {
  708. return nil, err
  709. }
  710. if !c.IsRunning() {
  711. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  712. }
  713. return c, nil
  714. }
  715. func (container *Container) setupWorkingDirectory() error {
  716. if container.Config.WorkingDir != "" {
  717. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  718. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  719. if err != nil {
  720. return err
  721. }
  722. pthInfo, err := os.Stat(pth)
  723. if err != nil {
  724. if !os.IsNotExist(err) {
  725. return err
  726. }
  727. if err := os.MkdirAll(pth, 0755); err != nil {
  728. return err
  729. }
  730. }
  731. if pthInfo != nil && !pthInfo.IsDir() {
  732. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  733. }
  734. }
  735. return nil
  736. }
  737. func (container *Container) getNetworkedContainer() (*Container, error) {
  738. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  739. switch parts[0] {
  740. case "container":
  741. if len(parts) != 2 {
  742. return nil, fmt.Errorf("no container specified to join network")
  743. }
  744. nc, err := container.daemon.Get(parts[1])
  745. if err != nil {
  746. return nil, err
  747. }
  748. if container == nc {
  749. return nil, fmt.Errorf("cannot join own network")
  750. }
  751. if !nc.IsRunning() {
  752. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  753. }
  754. return nc, nil
  755. default:
  756. return nil, fmt.Errorf("network mode not set to container")
  757. }
  758. }
  759. func (container *Container) ReleaseNetwork() {
  760. if container.hostConfig.NetworkMode.IsContainer() {
  761. return
  762. }
  763. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  764. if err != nil {
  765. logrus.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  766. return
  767. }
  768. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  769. if err != nil {
  770. logrus.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  771. return
  772. }
  773. if err := ep.Leave(container.ID); err != nil {
  774. logrus.Errorf("leaving endpoint failed: %v", err)
  775. }
  776. if err := ep.Delete(); err != nil {
  777. logrus.Errorf("deleting endpoint failed: %v", err)
  778. }
  779. container.NetworkSettings = &network.Settings{}
  780. }
  781. func disableAllActiveLinks(container *Container) {
  782. if container.activeLinks != nil {
  783. for _, link := range container.activeLinks {
  784. link.Disable()
  785. }
  786. }
  787. }
  788. func (container *Container) DisableLink(name string) {
  789. if container.activeLinks != nil {
  790. if link, exists := container.activeLinks[name]; exists {
  791. link.Disable()
  792. delete(container.activeLinks, name)
  793. if err := container.UpdateNetwork(); err != nil {
  794. logrus.Debugf("Could not update network to remove link: %v", err)
  795. }
  796. } else {
  797. logrus.Debugf("Could not find active link for %s", name)
  798. }
  799. }
  800. }
  801. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  802. var volumeMounts []mountPoint
  803. for _, mntPoint := range container.MountPoints {
  804. dest, err := container.GetResourcePath(mntPoint.Destination)
  805. if err != nil {
  806. return err
  807. }
  808. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  809. }
  810. for _, mnt := range container.networkMounts() {
  811. dest, err := container.GetResourcePath(mnt.Destination)
  812. if err != nil {
  813. return err
  814. }
  815. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  816. }
  817. for _, volumeMount := range volumeMounts {
  818. if forceSyscall {
  819. syscall.Unmount(volumeMount.Destination, 0)
  820. }
  821. if volumeMount.Volume != nil {
  822. if err := volumeMount.Volume.Unmount(); err != nil {
  823. return err
  824. }
  825. }
  826. }
  827. return nil
  828. }