container_operations_unix.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "time"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/container"
  14. "github.com/docker/docker/daemon/execdriver"
  15. "github.com/docker/docker/daemon/links"
  16. "github.com/docker/docker/daemon/network"
  17. derr "github.com/docker/docker/errors"
  18. "github.com/docker/docker/pkg/fileutils"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/mount"
  21. "github.com/docker/docker/pkg/stringid"
  22. "github.com/docker/docker/pkg/ulimit"
  23. "github.com/docker/docker/runconfig"
  24. "github.com/docker/libnetwork"
  25. "github.com/docker/libnetwork/netlabel"
  26. "github.com/docker/libnetwork/options"
  27. "github.com/opencontainers/runc/libcontainer/configs"
  28. "github.com/opencontainers/runc/libcontainer/devices"
  29. "github.com/opencontainers/runc/libcontainer/label"
  30. )
  31. func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
  32. var env []string
  33. children, err := daemon.children(container.Name)
  34. if err != nil {
  35. return nil, err
  36. }
  37. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  38. if bridgeSettings == nil {
  39. return nil, nil
  40. }
  41. if len(children) > 0 {
  42. for linkAlias, child := range children {
  43. if !child.IsRunning() {
  44. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  45. }
  46. childBridgeSettings := child.NetworkSettings.Networks["bridge"]
  47. if childBridgeSettings == nil {
  48. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  49. }
  50. link := links.NewLink(
  51. bridgeSettings.IPAddress,
  52. childBridgeSettings.IPAddress,
  53. linkAlias,
  54. child.Config.Env,
  55. child.Config.ExposedPorts,
  56. )
  57. for _, envVar := range link.ToEnv() {
  58. env = append(env, envVar)
  59. }
  60. }
  61. }
  62. return env, nil
  63. }
  64. func (daemon *Daemon) populateCommand(c *container.Container, env []string) error {
  65. var en *execdriver.Network
  66. if !c.Config.NetworkDisabled {
  67. en = &execdriver.Network{}
  68. if !daemon.execDriver.SupportsHooks() || c.HostConfig.NetworkMode.IsHost() {
  69. en.NamespacePath = c.NetworkSettings.SandboxKey
  70. }
  71. if c.HostConfig.NetworkMode.IsContainer() {
  72. nc, err := daemon.getNetworkedContainer(c.ID, c.HostConfig.NetworkMode.ConnectedContainer())
  73. if err != nil {
  74. return err
  75. }
  76. en.ContainerID = nc.ID
  77. }
  78. }
  79. ipc := &execdriver.Ipc{}
  80. var err error
  81. c.ShmPath, err = c.ShmResourcePath()
  82. if err != nil {
  83. return err
  84. }
  85. c.MqueuePath, err = c.MqueueResourcePath()
  86. if err != nil {
  87. return err
  88. }
  89. if c.HostConfig.IpcMode.IsContainer() {
  90. ic, err := daemon.getIpcContainer(c)
  91. if err != nil {
  92. return err
  93. }
  94. ipc.ContainerID = ic.ID
  95. c.ShmPath = ic.ShmPath
  96. c.MqueuePath = ic.MqueuePath
  97. } else {
  98. ipc.HostIpc = c.HostConfig.IpcMode.IsHost()
  99. if ipc.HostIpc {
  100. if _, err := os.Stat("/dev/shm"); err != nil {
  101. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  102. }
  103. if _, err := os.Stat("/dev/mqueue"); err != nil {
  104. return fmt.Errorf("/dev/mqueue is not mounted, but must be for --ipc=host")
  105. }
  106. c.ShmPath = "/dev/shm"
  107. c.MqueuePath = "/dev/mqueue"
  108. }
  109. }
  110. pid := &execdriver.Pid{}
  111. pid.HostPid = c.HostConfig.PidMode.IsHost()
  112. uts := &execdriver.UTS{
  113. HostUTS: c.HostConfig.UTSMode.IsHost(),
  114. }
  115. // Build lists of devices allowed and created within the container.
  116. var userSpecifiedDevices []*configs.Device
  117. for _, deviceMapping := range c.HostConfig.Devices {
  118. devs, err := getDevicesFromPath(deviceMapping)
  119. if err != nil {
  120. return err
  121. }
  122. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  123. }
  124. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  125. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  126. var rlimits []*ulimit.Rlimit
  127. ulimits := c.HostConfig.Ulimits
  128. // Merge ulimits with daemon defaults
  129. ulIdx := make(map[string]*ulimit.Ulimit)
  130. for _, ul := range ulimits {
  131. ulIdx[ul.Name] = ul
  132. }
  133. for name, ul := range daemon.configStore.Ulimits {
  134. if _, exists := ulIdx[name]; !exists {
  135. ulimits = append(ulimits, ul)
  136. }
  137. }
  138. weightDevices, err := getBlkioWeightDevices(c.HostConfig)
  139. if err != nil {
  140. return err
  141. }
  142. readBpsDevice, err := getBlkioReadBpsDevices(c.HostConfig)
  143. if err != nil {
  144. return err
  145. }
  146. writeBpsDevice, err := getBlkioWriteBpsDevices(c.HostConfig)
  147. if err != nil {
  148. return err
  149. }
  150. for _, limit := range ulimits {
  151. rl, err := limit.GetRlimit()
  152. if err != nil {
  153. return err
  154. }
  155. rlimits = append(rlimits, rl)
  156. }
  157. resources := &execdriver.Resources{
  158. CommonResources: execdriver.CommonResources{
  159. Memory: c.HostConfig.Memory,
  160. MemoryReservation: c.HostConfig.MemoryReservation,
  161. CPUShares: c.HostConfig.CPUShares,
  162. BlkioWeight: c.HostConfig.BlkioWeight,
  163. },
  164. MemorySwap: c.HostConfig.MemorySwap,
  165. KernelMemory: c.HostConfig.KernelMemory,
  166. CpusetCpus: c.HostConfig.CpusetCpus,
  167. CpusetMems: c.HostConfig.CpusetMems,
  168. CPUPeriod: c.HostConfig.CPUPeriod,
  169. CPUQuota: c.HostConfig.CPUQuota,
  170. Rlimits: rlimits,
  171. BlkioWeightDevice: weightDevices,
  172. BlkioThrottleReadBpsDevice: readBpsDevice,
  173. BlkioThrottleWriteBpsDevice: writeBpsDevice,
  174. OomKillDisable: c.HostConfig.OomKillDisable,
  175. MemorySwappiness: *c.HostConfig.MemorySwappiness,
  176. }
  177. processConfig := execdriver.ProcessConfig{
  178. CommonProcessConfig: execdriver.CommonProcessConfig{
  179. Entrypoint: c.Path,
  180. Arguments: c.Args,
  181. Tty: c.Config.Tty,
  182. },
  183. Privileged: c.HostConfig.Privileged,
  184. User: c.Config.User,
  185. }
  186. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  187. processConfig.Env = env
  188. remappedRoot := &execdriver.User{}
  189. rootUID, rootGID := daemon.GetRemappedUIDGID()
  190. if rootUID != 0 {
  191. remappedRoot.UID = rootUID
  192. remappedRoot.GID = rootGID
  193. }
  194. uidMap, gidMap := daemon.GetUIDGIDMaps()
  195. c.Command = &execdriver.Command{
  196. CommonCommand: execdriver.CommonCommand{
  197. ID: c.ID,
  198. InitPath: "/.dockerinit",
  199. MountLabel: c.GetMountLabel(),
  200. Network: en,
  201. ProcessConfig: processConfig,
  202. ProcessLabel: c.GetProcessLabel(),
  203. Rootfs: c.BaseFS,
  204. Resources: resources,
  205. WorkingDir: c.Config.WorkingDir,
  206. },
  207. AllowedDevices: allowedDevices,
  208. AppArmorProfile: c.AppArmorProfile,
  209. AutoCreatedDevices: autoCreatedDevices,
  210. CapAdd: c.HostConfig.CapAdd.Slice(),
  211. CapDrop: c.HostConfig.CapDrop.Slice(),
  212. CgroupParent: c.HostConfig.CgroupParent,
  213. GIDMapping: gidMap,
  214. GroupAdd: c.HostConfig.GroupAdd,
  215. Ipc: ipc,
  216. OomScoreAdj: c.HostConfig.OomScoreAdj,
  217. Pid: pid,
  218. ReadonlyRootfs: c.HostConfig.ReadonlyRootfs,
  219. RemappedRoot: remappedRoot,
  220. SeccompProfile: c.SeccompProfile,
  221. UIDMapping: uidMap,
  222. UTS: uts,
  223. }
  224. return nil
  225. }
  226. // getSize returns the real size & virtual size of the container.
  227. func (daemon *Daemon) getSize(container *container.Container) (int64, int64) {
  228. var (
  229. sizeRw, sizeRootfs int64
  230. err error
  231. )
  232. if err := daemon.Mount(container); err != nil {
  233. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  234. return sizeRw, sizeRootfs
  235. }
  236. defer daemon.Unmount(container)
  237. sizeRw, err = container.RWLayer.Size()
  238. if err != nil {
  239. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", daemon.driver, container.ID, err)
  240. // FIXME: GetSize should return an error. Not changing it now in case
  241. // there is a side-effect.
  242. sizeRw = -1
  243. }
  244. if parent := container.RWLayer.Parent(); parent != nil {
  245. sizeRootfs, err = parent.Size()
  246. if err != nil {
  247. sizeRootfs = -1
  248. } else if sizeRw != -1 {
  249. sizeRootfs += sizeRw
  250. }
  251. }
  252. return sizeRw, sizeRootfs
  253. }
  254. func (daemon *Daemon) buildSandboxOptions(container *container.Container, n libnetwork.Network) ([]libnetwork.SandboxOption, error) {
  255. var (
  256. sboxOptions []libnetwork.SandboxOption
  257. err error
  258. dns []string
  259. dnsSearch []string
  260. dnsOptions []string
  261. )
  262. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  263. libnetwork.OptionDomainname(container.Config.Domainname))
  264. if container.HostConfig.NetworkMode.IsHost() {
  265. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  266. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  267. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  268. } else if daemon.execDriver.SupportsHooks() {
  269. // OptionUseExternalKey is mandatory for userns support.
  270. // But optional for non-userns support
  271. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  272. }
  273. container.HostsPath, err = container.GetRootResourcePath("hosts")
  274. if err != nil {
  275. return nil, err
  276. }
  277. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  278. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  279. if err != nil {
  280. return nil, err
  281. }
  282. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  283. if len(container.HostConfig.DNS) > 0 {
  284. dns = container.HostConfig.DNS
  285. } else if len(daemon.configStore.DNS) > 0 {
  286. dns = daemon.configStore.DNS
  287. }
  288. for _, d := range dns {
  289. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  290. }
  291. if len(container.HostConfig.DNSSearch) > 0 {
  292. dnsSearch = container.HostConfig.DNSSearch
  293. } else if len(daemon.configStore.DNSSearch) > 0 {
  294. dnsSearch = daemon.configStore.DNSSearch
  295. }
  296. for _, ds := range dnsSearch {
  297. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  298. }
  299. if len(container.HostConfig.DNSOptions) > 0 {
  300. dnsOptions = container.HostConfig.DNSOptions
  301. } else if len(daemon.configStore.DNSOptions) > 0 {
  302. dnsOptions = daemon.configStore.DNSOptions
  303. }
  304. for _, ds := range dnsOptions {
  305. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  306. }
  307. if container.NetworkSettings.SecondaryIPAddresses != nil {
  308. name := container.Config.Hostname
  309. if container.Config.Domainname != "" {
  310. name = name + "." + container.Config.Domainname
  311. }
  312. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  313. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  314. }
  315. }
  316. for _, extraHost := range container.HostConfig.ExtraHosts {
  317. // allow IPv6 addresses in extra hosts; only split on first ":"
  318. parts := strings.SplitN(extraHost, ":", 2)
  319. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  320. }
  321. // Link feature is supported only for the default bridge network.
  322. // return if this call to build join options is not for default bridge network
  323. if n.Name() != "bridge" {
  324. return sboxOptions, nil
  325. }
  326. ep, _ := container.GetEndpointInNetwork(n)
  327. if ep == nil {
  328. return sboxOptions, nil
  329. }
  330. var childEndpoints, parentEndpoints []string
  331. children, err := daemon.children(container.Name)
  332. if err != nil {
  333. return nil, err
  334. }
  335. for linkAlias, child := range children {
  336. if !isLinkable(child) {
  337. return nil, fmt.Errorf("Cannot link to %s, as it does not belong to the default network", child.Name)
  338. }
  339. _, alias := path.Split(linkAlias)
  340. // allow access to the linked container via the alias, real name, and container hostname
  341. aliasList := alias + " " + child.Config.Hostname
  342. // only add the name if alias isn't equal to the name
  343. if alias != child.Name[1:] {
  344. aliasList = aliasList + " " + child.Name[1:]
  345. }
  346. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.Networks["bridge"].IPAddress))
  347. cEndpoint, _ := child.GetEndpointInNetwork(n)
  348. if cEndpoint != nil && cEndpoint.ID() != "" {
  349. childEndpoints = append(childEndpoints, cEndpoint.ID())
  350. }
  351. }
  352. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  353. refs := daemon.containerGraph().RefPaths(container.ID)
  354. for _, ref := range refs {
  355. if ref.ParentID == "0" {
  356. continue
  357. }
  358. c, err := daemon.Get(ref.ParentID)
  359. if err != nil {
  360. logrus.Error(err)
  361. }
  362. if c != nil && !daemon.configStore.DisableBridge && container.HostConfig.NetworkMode.IsPrivate() {
  363. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, bridgeSettings.IPAddress)
  364. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, bridgeSettings.IPAddress))
  365. if ep.ID() != "" {
  366. parentEndpoints = append(parentEndpoints, ep.ID())
  367. }
  368. }
  369. }
  370. linkOptions := options.Generic{
  371. netlabel.GenericData: options.Generic{
  372. "ParentEndpoints": parentEndpoints,
  373. "ChildEndpoints": childEndpoints,
  374. },
  375. }
  376. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  377. return sboxOptions, nil
  378. }
  379. func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network) error {
  380. if container.NetworkSettings == nil {
  381. container.NetworkSettings = &network.Settings{Networks: make(map[string]*network.EndpointSettings)}
  382. }
  383. if !container.HostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  384. return runconfig.ErrConflictHostNetwork
  385. }
  386. for s := range container.NetworkSettings.Networks {
  387. sn, err := daemon.FindNetwork(s)
  388. if err != nil {
  389. continue
  390. }
  391. if sn.Name() == n.Name() {
  392. // Avoid duplicate config
  393. return nil
  394. }
  395. if !runconfig.NetworkMode(sn.Type()).IsPrivate() ||
  396. !runconfig.NetworkMode(n.Type()).IsPrivate() {
  397. return runconfig.ErrConflictSharedNetwork
  398. }
  399. if runconfig.NetworkMode(sn.Name()).IsNone() ||
  400. runconfig.NetworkMode(n.Name()).IsNone() {
  401. return runconfig.ErrConflictNoNetwork
  402. }
  403. }
  404. container.NetworkSettings.Networks[n.Name()] = new(network.EndpointSettings)
  405. return nil
  406. }
  407. func (daemon *Daemon) updateEndpointNetworkSettings(container *container.Container, n libnetwork.Network, ep libnetwork.Endpoint) error {
  408. if err := container.BuildEndpointInfo(n, ep); err != nil {
  409. return err
  410. }
  411. if container.HostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  412. container.NetworkSettings.Bridge = daemon.configStore.Bridge.Iface
  413. }
  414. return nil
  415. }
  416. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  417. // get removed/unlinked).
  418. func (daemon *Daemon) updateNetwork(container *container.Container) error {
  419. ctrl := daemon.netController
  420. sid := container.NetworkSettings.SandboxID
  421. sb, err := ctrl.SandboxByID(sid)
  422. if err != nil {
  423. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  424. }
  425. // Find if container is connected to the default bridge network
  426. var n libnetwork.Network
  427. for name := range container.NetworkSettings.Networks {
  428. sn, err := daemon.FindNetwork(name)
  429. if err != nil {
  430. continue
  431. }
  432. if sn.Name() == "bridge" {
  433. n = sn
  434. break
  435. }
  436. }
  437. if n == nil {
  438. // Not connected to the default bridge network; Nothing to do
  439. return nil
  440. }
  441. options, err := daemon.buildSandboxOptions(container, n)
  442. if err != nil {
  443. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  444. }
  445. if err := sb.Refresh(options...); err != nil {
  446. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  447. }
  448. return nil
  449. }
  450. func (daemon *Daemon) allocateNetwork(container *container.Container) error {
  451. controller := daemon.netController
  452. // Cleanup any stale sandbox left over due to ungraceful daemon shutdown
  453. if err := controller.SandboxDestroy(container.ID); err != nil {
  454. logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
  455. }
  456. updateSettings := false
  457. if len(container.NetworkSettings.Networks) == 0 {
  458. mode := container.HostConfig.NetworkMode
  459. if container.Config.NetworkDisabled || mode.IsContainer() {
  460. return nil
  461. }
  462. networkName := mode.NetworkName()
  463. if mode.IsDefault() {
  464. networkName = controller.Config().Daemon.DefaultNetwork
  465. }
  466. if mode.IsUserDefined() {
  467. n, err := daemon.FindNetwork(networkName)
  468. if err != nil {
  469. return err
  470. }
  471. networkName = n.Name()
  472. }
  473. container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings)
  474. container.NetworkSettings.Networks[networkName] = new(network.EndpointSettings)
  475. updateSettings = true
  476. }
  477. for n := range container.NetworkSettings.Networks {
  478. if err := daemon.connectToNetwork(container, n, updateSettings); err != nil {
  479. return err
  480. }
  481. }
  482. return container.WriteHostConfig()
  483. }
  484. func (daemon *Daemon) getNetworkSandbox(container *container.Container) libnetwork.Sandbox {
  485. var sb libnetwork.Sandbox
  486. daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  487. if s.ContainerID() == container.ID {
  488. sb = s
  489. return true
  490. }
  491. return false
  492. })
  493. return sb
  494. }
  495. // ConnectToNetwork connects a container to a network
  496. func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string) error {
  497. if !container.Running {
  498. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  499. }
  500. if err := daemon.connectToNetwork(container, idOrName, true); err != nil {
  501. return err
  502. }
  503. if err := container.ToDiskLocking(); err != nil {
  504. return fmt.Errorf("Error saving container to disk: %v", err)
  505. }
  506. return nil
  507. }
  508. func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, updateSettings bool) (err error) {
  509. if container.HostConfig.NetworkMode.IsContainer() {
  510. return runconfig.ErrConflictSharedNetwork
  511. }
  512. if runconfig.NetworkMode(idOrName).IsBridge() &&
  513. daemon.configStore.DisableBridge {
  514. container.Config.NetworkDisabled = true
  515. return nil
  516. }
  517. controller := daemon.netController
  518. n, err := daemon.FindNetwork(idOrName)
  519. if err != nil {
  520. return err
  521. }
  522. if updateSettings {
  523. if err := daemon.updateNetworkSettings(container, n); err != nil {
  524. return err
  525. }
  526. }
  527. ep, err := container.GetEndpointInNetwork(n)
  528. if err == nil {
  529. return fmt.Errorf("Conflict. A container with name %q is already connected to network %s.", strings.TrimPrefix(container.Name, "/"), idOrName)
  530. }
  531. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  532. return err
  533. }
  534. createOptions, err := container.BuildCreateEndpointOptions(n)
  535. if err != nil {
  536. return err
  537. }
  538. endpointName := strings.TrimPrefix(container.Name, "/")
  539. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  540. if err != nil {
  541. return err
  542. }
  543. defer func() {
  544. if err != nil {
  545. if e := ep.Delete(); e != nil {
  546. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  547. }
  548. }
  549. }()
  550. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  551. return err
  552. }
  553. sb := daemon.getNetworkSandbox(container)
  554. if sb == nil {
  555. options, err := daemon.buildSandboxOptions(container, n)
  556. if err != nil {
  557. return err
  558. }
  559. sb, err = controller.NewSandbox(container.ID, options...)
  560. if err != nil {
  561. return err
  562. }
  563. container.UpdateSandboxNetworkSettings(sb)
  564. }
  565. if err := ep.Join(sb); err != nil {
  566. return err
  567. }
  568. if err := container.UpdateJoinInfo(n, ep); err != nil {
  569. return derr.ErrorCodeJoinInfo.WithArgs(err)
  570. }
  571. return nil
  572. }
  573. // DisconnectFromNetwork disconnects container from network n.
  574. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  575. if !container.Running {
  576. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  577. }
  578. if container.HostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  579. return runconfig.ErrConflictHostNetwork
  580. }
  581. return disconnectFromNetwork(container, n)
  582. }
  583. func disconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  584. if err := container.ToDiskLocking(); err != nil {
  585. return fmt.Errorf("Error saving container to disk: %v", err)
  586. }
  587. var (
  588. ep libnetwork.Endpoint
  589. sbox libnetwork.Sandbox
  590. )
  591. s := func(current libnetwork.Endpoint) bool {
  592. epInfo := current.Info()
  593. if epInfo == nil {
  594. return false
  595. }
  596. if sb := epInfo.Sandbox(); sb != nil {
  597. if sb.ContainerID() == container.ID {
  598. ep = current
  599. sbox = sb
  600. return true
  601. }
  602. }
  603. return false
  604. }
  605. n.WalkEndpoints(s)
  606. if ep == nil {
  607. return fmt.Errorf("container %s is not connected to the network", container.ID)
  608. }
  609. if err := ep.Leave(sbox); err != nil {
  610. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  611. }
  612. if err := ep.Delete(); err != nil {
  613. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  614. }
  615. delete(container.NetworkSettings.Networks, n.Name())
  616. return nil
  617. }
  618. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  619. var err error
  620. if container.HostConfig.NetworkMode.IsContainer() {
  621. // we need to get the hosts files from the container to join
  622. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  623. if err != nil {
  624. return err
  625. }
  626. container.HostnamePath = nc.HostnamePath
  627. container.HostsPath = nc.HostsPath
  628. container.ResolvConfPath = nc.ResolvConfPath
  629. container.Config.Hostname = nc.Config.Hostname
  630. container.Config.Domainname = nc.Config.Domainname
  631. return nil
  632. }
  633. if container.HostConfig.NetworkMode.IsHost() {
  634. container.Config.Hostname, err = os.Hostname()
  635. if err != nil {
  636. return err
  637. }
  638. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  639. if len(parts) > 1 {
  640. container.Config.Hostname = parts[0]
  641. container.Config.Domainname = parts[1]
  642. }
  643. }
  644. if err := daemon.allocateNetwork(container); err != nil {
  645. return err
  646. }
  647. return container.BuildHostnameFile()
  648. }
  649. // called from the libcontainer pre-start hook to set the network
  650. // namespace configuration linkage to the libnetwork "sandbox" entity
  651. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  652. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  653. var sandbox libnetwork.Sandbox
  654. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  655. daemon.netController.WalkSandboxes(search)
  656. if sandbox == nil {
  657. return derr.ErrorCodeNoSandbox.WithArgs(containerID, "no sandbox found")
  658. }
  659. return sandbox.SetKey(path)
  660. }
  661. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  662. containerID := container.HostConfig.IpcMode.Container()
  663. c, err := daemon.Get(containerID)
  664. if err != nil {
  665. return nil, err
  666. }
  667. if !c.IsRunning() {
  668. return nil, derr.ErrorCodeIPCRunning
  669. }
  670. return c, nil
  671. }
  672. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  673. nc, err := daemon.Get(connectedContainerID)
  674. if err != nil {
  675. return nil, err
  676. }
  677. if containerID == nc.ID {
  678. return nil, derr.ErrorCodeJoinSelf
  679. }
  680. if !nc.IsRunning() {
  681. return nil, derr.ErrorCodeJoinRunning.WithArgs(connectedContainerID)
  682. }
  683. return nc, nil
  684. }
  685. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  686. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  687. return
  688. }
  689. sid := container.NetworkSettings.SandboxID
  690. networks := container.NetworkSettings.Networks
  691. for n := range networks {
  692. networks[n] = &network.EndpointSettings{}
  693. }
  694. container.NetworkSettings = &network.Settings{Networks: networks}
  695. if sid == "" || len(networks) == 0 {
  696. return
  697. }
  698. sb, err := daemon.netController.SandboxByID(sid)
  699. if err != nil {
  700. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  701. return
  702. }
  703. if err := sb.Delete(); err != nil {
  704. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  705. }
  706. }
  707. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  708. rootUID, rootGID := daemon.GetRemappedUIDGID()
  709. if !c.HasMountFor("/dev/shm") {
  710. shmPath, err := c.ShmResourcePath()
  711. if err != nil {
  712. return err
  713. }
  714. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  715. return err
  716. }
  717. shmSize := container.DefaultSHMSize
  718. if c.HostConfig.ShmSize != nil {
  719. shmSize = *c.HostConfig.ShmSize
  720. }
  721. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  722. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  723. return fmt.Errorf("mounting shm tmpfs: %s", err)
  724. }
  725. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  726. return err
  727. }
  728. }
  729. if !c.HasMountFor("/dev/mqueue") {
  730. mqueuePath, err := c.MqueueResourcePath()
  731. if err != nil {
  732. return err
  733. }
  734. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  735. return err
  736. }
  737. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  738. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  739. }
  740. if err := os.Chown(mqueuePath, rootUID, rootGID); err != nil {
  741. return err
  742. }
  743. }
  744. return nil
  745. }
  746. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  747. mounts, err := daemon.setupMounts(container)
  748. if err != nil {
  749. return err
  750. }
  751. for _, m := range mounts {
  752. dest, err := container.GetResourcePath(m.Destination)
  753. if err != nil {
  754. return err
  755. }
  756. var stat os.FileInfo
  757. stat, err = os.Stat(m.Source)
  758. if err != nil {
  759. return err
  760. }
  761. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  762. return err
  763. }
  764. opts := "rbind,ro"
  765. if m.Writable {
  766. opts = "rbind,rw"
  767. }
  768. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  769. return err
  770. }
  771. }
  772. return nil
  773. }
  774. func killProcessDirectly(container *container.Container) error {
  775. if _, err := container.WaitStop(10 * time.Second); err != nil {
  776. // Ensure that we don't kill ourselves
  777. if pid := container.GetPID(); pid != 0 {
  778. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  779. if err := syscall.Kill(pid, 9); err != nil {
  780. if err != syscall.ESRCH {
  781. return err
  782. }
  783. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  784. }
  785. }
  786. }
  787. return nil
  788. }
  789. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  790. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  791. // if there was no error, return the device
  792. if err == nil {
  793. device.Path = deviceMapping.PathInContainer
  794. return append(devs, device), nil
  795. }
  796. // if the device is not a device node
  797. // try to see if it's a directory holding many devices
  798. if err == devices.ErrNotADevice {
  799. // check if it is a directory
  800. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  801. // mount the internal devices recursively
  802. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  803. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  804. if e != nil {
  805. // ignore the device
  806. return nil
  807. }
  808. // add the device to userSpecified devices
  809. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  810. devs = append(devs, childDevice)
  811. return nil
  812. })
  813. }
  814. }
  815. if len(devs) > 0 {
  816. return devs, nil
  817. }
  818. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  819. }
  820. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  821. if len(userDevices) == 0 {
  822. return defaultDevices
  823. }
  824. paths := map[string]*configs.Device{}
  825. for _, d := range userDevices {
  826. paths[d.Path] = d
  827. }
  828. var devs []*configs.Device
  829. for _, d := range defaultDevices {
  830. if _, defined := paths[d.Path]; !defined {
  831. devs = append(devs, d)
  832. }
  833. }
  834. return append(devs, userDevices...)
  835. }
  836. func detachMounted(path string) error {
  837. return syscall.Unmount(path, syscall.MNT_DETACH)
  838. }
  839. func isLinkable(child *container.Container) bool {
  840. // A container is linkable only if it belongs to the default network
  841. _, ok := child.NetworkSettings.Networks["bridge"]
  842. return ok
  843. }