container_operations_unix.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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. UIDMapping: uidMap,
  221. UTS: uts,
  222. }
  223. return nil
  224. }
  225. // getSize returns the real size & virtual size of the container.
  226. func (daemon *Daemon) getSize(container *container.Container) (int64, int64) {
  227. var (
  228. sizeRw, sizeRootfs int64
  229. err error
  230. )
  231. if err := daemon.Mount(container); err != nil {
  232. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  233. return sizeRw, sizeRootfs
  234. }
  235. defer daemon.Unmount(container)
  236. sizeRw, err = container.RWLayer.Size()
  237. if err != nil {
  238. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", daemon.driver, container.ID, err)
  239. // FIXME: GetSize should return an error. Not changing it now in case
  240. // there is a side-effect.
  241. sizeRw = -1
  242. }
  243. if parent := container.RWLayer.Parent(); parent != nil {
  244. sizeRootfs, err = parent.Size()
  245. if err != nil {
  246. sizeRootfs = -1
  247. } else if sizeRw != -1 {
  248. sizeRootfs += sizeRw
  249. }
  250. }
  251. return sizeRw, sizeRootfs
  252. }
  253. func (daemon *Daemon) buildSandboxOptions(container *container.Container, n libnetwork.Network) ([]libnetwork.SandboxOption, error) {
  254. var (
  255. sboxOptions []libnetwork.SandboxOption
  256. err error
  257. dns []string
  258. dnsSearch []string
  259. dnsOptions []string
  260. )
  261. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  262. libnetwork.OptionDomainname(container.Config.Domainname))
  263. if container.HostConfig.NetworkMode.IsHost() {
  264. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  265. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  266. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  267. } else if daemon.execDriver.SupportsHooks() {
  268. // OptionUseExternalKey is mandatory for userns support.
  269. // But optional for non-userns support
  270. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  271. }
  272. container.HostsPath, err = container.GetRootResourcePath("hosts")
  273. if err != nil {
  274. return nil, err
  275. }
  276. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  277. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  278. if err != nil {
  279. return nil, err
  280. }
  281. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  282. if len(container.HostConfig.DNS) > 0 {
  283. dns = container.HostConfig.DNS
  284. } else if len(daemon.configStore.DNS) > 0 {
  285. dns = daemon.configStore.DNS
  286. }
  287. for _, d := range dns {
  288. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  289. }
  290. if len(container.HostConfig.DNSSearch) > 0 {
  291. dnsSearch = container.HostConfig.DNSSearch
  292. } else if len(daemon.configStore.DNSSearch) > 0 {
  293. dnsSearch = daemon.configStore.DNSSearch
  294. }
  295. for _, ds := range dnsSearch {
  296. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  297. }
  298. if len(container.HostConfig.DNSOptions) > 0 {
  299. dnsOptions = container.HostConfig.DNSOptions
  300. } else if len(daemon.configStore.DNSOptions) > 0 {
  301. dnsOptions = daemon.configStore.DNSOptions
  302. }
  303. for _, ds := range dnsOptions {
  304. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  305. }
  306. if container.NetworkSettings.SecondaryIPAddresses != nil {
  307. name := container.Config.Hostname
  308. if container.Config.Domainname != "" {
  309. name = name + "." + container.Config.Domainname
  310. }
  311. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  312. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  313. }
  314. }
  315. for _, extraHost := range container.HostConfig.ExtraHosts {
  316. // allow IPv6 addresses in extra hosts; only split on first ":"
  317. parts := strings.SplitN(extraHost, ":", 2)
  318. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  319. }
  320. // Link feature is supported only for the default bridge network.
  321. // return if this call to build join options is not for default bridge network
  322. if n.Name() != "bridge" {
  323. return sboxOptions, nil
  324. }
  325. ep, _ := container.GetEndpointInNetwork(n)
  326. if ep == nil {
  327. return sboxOptions, nil
  328. }
  329. var childEndpoints, parentEndpoints []string
  330. children, err := daemon.children(container.Name)
  331. if err != nil {
  332. return nil, err
  333. }
  334. for linkAlias, child := range children {
  335. if !isLinkable(child) {
  336. return nil, fmt.Errorf("Cannot link to %s, as it does not belong to the default network", child.Name)
  337. }
  338. _, alias := path.Split(linkAlias)
  339. // allow access to the linked container via the alias, real name, and container hostname
  340. aliasList := alias + " " + child.Config.Hostname
  341. // only add the name if alias isn't equal to the name
  342. if alias != child.Name[1:] {
  343. aliasList = aliasList + " " + child.Name[1:]
  344. }
  345. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.Networks["bridge"].IPAddress))
  346. cEndpoint, _ := child.GetEndpointInNetwork(n)
  347. if cEndpoint != nil && cEndpoint.ID() != "" {
  348. childEndpoints = append(childEndpoints, cEndpoint.ID())
  349. }
  350. }
  351. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  352. refs := daemon.containerGraph().RefPaths(container.ID)
  353. for _, ref := range refs {
  354. if ref.ParentID == "0" {
  355. continue
  356. }
  357. c, err := daemon.Get(ref.ParentID)
  358. if err != nil {
  359. logrus.Error(err)
  360. }
  361. if c != nil && !daemon.configStore.DisableBridge && container.HostConfig.NetworkMode.IsPrivate() {
  362. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, bridgeSettings.IPAddress)
  363. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, bridgeSettings.IPAddress))
  364. if ep.ID() != "" {
  365. parentEndpoints = append(parentEndpoints, ep.ID())
  366. }
  367. }
  368. }
  369. linkOptions := options.Generic{
  370. netlabel.GenericData: options.Generic{
  371. "ParentEndpoints": parentEndpoints,
  372. "ChildEndpoints": childEndpoints,
  373. },
  374. }
  375. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  376. return sboxOptions, nil
  377. }
  378. func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network) error {
  379. if container.NetworkSettings == nil {
  380. container.NetworkSettings = &network.Settings{Networks: make(map[string]*network.EndpointSettings)}
  381. }
  382. if !container.HostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  383. return runconfig.ErrConflictHostNetwork
  384. }
  385. for s := range container.NetworkSettings.Networks {
  386. sn, err := daemon.FindNetwork(s)
  387. if err != nil {
  388. continue
  389. }
  390. if sn.Name() == n.Name() {
  391. // Avoid duplicate config
  392. return nil
  393. }
  394. if !runconfig.NetworkMode(sn.Type()).IsPrivate() ||
  395. !runconfig.NetworkMode(n.Type()).IsPrivate() {
  396. return runconfig.ErrConflictSharedNetwork
  397. }
  398. if runconfig.NetworkMode(sn.Name()).IsNone() ||
  399. runconfig.NetworkMode(n.Name()).IsNone() {
  400. return runconfig.ErrConflictNoNetwork
  401. }
  402. }
  403. container.NetworkSettings.Networks[n.Name()] = new(network.EndpointSettings)
  404. return nil
  405. }
  406. func (daemon *Daemon) updateEndpointNetworkSettings(container *container.Container, n libnetwork.Network, ep libnetwork.Endpoint) error {
  407. if err := container.BuildEndpointInfo(n, ep); err != nil {
  408. return err
  409. }
  410. if container.HostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  411. container.NetworkSettings.Bridge = daemon.configStore.Bridge.Iface
  412. }
  413. return nil
  414. }
  415. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  416. // get removed/unlinked).
  417. func (daemon *Daemon) updateNetwork(container *container.Container) error {
  418. ctrl := daemon.netController
  419. sid := container.NetworkSettings.SandboxID
  420. sb, err := ctrl.SandboxByID(sid)
  421. if err != nil {
  422. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  423. }
  424. // Find if container is connected to the default bridge network
  425. var n libnetwork.Network
  426. for name := range container.NetworkSettings.Networks {
  427. sn, err := daemon.FindNetwork(name)
  428. if err != nil {
  429. continue
  430. }
  431. if sn.Name() == "bridge" {
  432. n = sn
  433. break
  434. }
  435. }
  436. if n == nil {
  437. // Not connected to the default bridge network; Nothing to do
  438. return nil
  439. }
  440. options, err := daemon.buildSandboxOptions(container, n)
  441. if err != nil {
  442. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  443. }
  444. if err := sb.Refresh(options...); err != nil {
  445. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  446. }
  447. return nil
  448. }
  449. func (daemon *Daemon) allocateNetwork(container *container.Container) error {
  450. controller := daemon.netController
  451. // Cleanup any stale sandbox left over due to ungraceful daemon shutdown
  452. if err := controller.SandboxDestroy(container.ID); err != nil {
  453. logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
  454. }
  455. updateSettings := false
  456. if len(container.NetworkSettings.Networks) == 0 {
  457. mode := container.HostConfig.NetworkMode
  458. if container.Config.NetworkDisabled || mode.IsContainer() {
  459. return nil
  460. }
  461. networkName := mode.NetworkName()
  462. if mode.IsDefault() {
  463. networkName = controller.Config().Daemon.DefaultNetwork
  464. }
  465. if mode.IsUserDefined() {
  466. n, err := daemon.FindNetwork(networkName)
  467. if err != nil {
  468. return err
  469. }
  470. networkName = n.Name()
  471. }
  472. container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings)
  473. container.NetworkSettings.Networks[networkName] = new(network.EndpointSettings)
  474. updateSettings = true
  475. }
  476. for n := range container.NetworkSettings.Networks {
  477. if err := daemon.connectToNetwork(container, n, updateSettings); err != nil {
  478. return err
  479. }
  480. }
  481. return container.WriteHostConfig()
  482. }
  483. func (daemon *Daemon) getNetworkSandbox(container *container.Container) libnetwork.Sandbox {
  484. var sb libnetwork.Sandbox
  485. daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  486. if s.ContainerID() == container.ID {
  487. sb = s
  488. return true
  489. }
  490. return false
  491. })
  492. return sb
  493. }
  494. // ConnectToNetwork connects a container to a network
  495. func (daemon *Daemon) ConnectToNetwork(container *container.Container, idOrName string) error {
  496. if !container.Running {
  497. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  498. }
  499. if err := daemon.connectToNetwork(container, idOrName, true); err != nil {
  500. return err
  501. }
  502. if err := container.ToDiskLocking(); err != nil {
  503. return fmt.Errorf("Error saving container to disk: %v", err)
  504. }
  505. return nil
  506. }
  507. func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, updateSettings bool) (err error) {
  508. if container.HostConfig.NetworkMode.IsContainer() {
  509. return runconfig.ErrConflictSharedNetwork
  510. }
  511. if runconfig.NetworkMode(idOrName).IsBridge() &&
  512. daemon.configStore.DisableBridge {
  513. container.Config.NetworkDisabled = true
  514. return nil
  515. }
  516. controller := daemon.netController
  517. n, err := daemon.FindNetwork(idOrName)
  518. if err != nil {
  519. return err
  520. }
  521. if updateSettings {
  522. if err := daemon.updateNetworkSettings(container, n); err != nil {
  523. return err
  524. }
  525. }
  526. ep, err := container.GetEndpointInNetwork(n)
  527. if err == nil {
  528. return fmt.Errorf("container already connected to network %s", idOrName)
  529. }
  530. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  531. return err
  532. }
  533. createOptions, err := container.BuildCreateEndpointOptions(n)
  534. if err != nil {
  535. return err
  536. }
  537. endpointName := strings.TrimPrefix(container.Name, "/")
  538. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  539. if err != nil {
  540. return err
  541. }
  542. defer func() {
  543. if err != nil {
  544. if e := ep.Delete(); e != nil {
  545. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  546. }
  547. }
  548. }()
  549. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  550. return err
  551. }
  552. sb := daemon.getNetworkSandbox(container)
  553. if sb == nil {
  554. options, err := daemon.buildSandboxOptions(container, n)
  555. if err != nil {
  556. return err
  557. }
  558. sb, err = controller.NewSandbox(container.ID, options...)
  559. if err != nil {
  560. return err
  561. }
  562. container.UpdateSandboxNetworkSettings(sb)
  563. }
  564. if err := ep.Join(sb); err != nil {
  565. return err
  566. }
  567. if err := container.UpdateJoinInfo(n, ep); err != nil {
  568. return derr.ErrorCodeJoinInfo.WithArgs(err)
  569. }
  570. return nil
  571. }
  572. // DisconnectFromNetwork disconnects container from network n.
  573. func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  574. if !container.Running {
  575. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  576. }
  577. if container.HostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  578. return runconfig.ErrConflictHostNetwork
  579. }
  580. return disconnectFromNetwork(container, n)
  581. }
  582. func disconnectFromNetwork(container *container.Container, n libnetwork.Network) error {
  583. if err := container.ToDiskLocking(); err != nil {
  584. return fmt.Errorf("Error saving container to disk: %v", err)
  585. }
  586. var (
  587. ep libnetwork.Endpoint
  588. sbox libnetwork.Sandbox
  589. )
  590. s := func(current libnetwork.Endpoint) bool {
  591. epInfo := current.Info()
  592. if epInfo == nil {
  593. return false
  594. }
  595. if sb := epInfo.Sandbox(); sb != nil {
  596. if sb.ContainerID() == container.ID {
  597. ep = current
  598. sbox = sb
  599. return true
  600. }
  601. }
  602. return false
  603. }
  604. n.WalkEndpoints(s)
  605. if ep == nil {
  606. return fmt.Errorf("container %s is not connected to the network", container.ID)
  607. }
  608. if err := ep.Leave(sbox); err != nil {
  609. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  610. }
  611. if err := ep.Delete(); err != nil {
  612. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  613. }
  614. delete(container.NetworkSettings.Networks, n.Name())
  615. return nil
  616. }
  617. func (daemon *Daemon) initializeNetworking(container *container.Container) error {
  618. var err error
  619. if container.HostConfig.NetworkMode.IsContainer() {
  620. // we need to get the hosts files from the container to join
  621. nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
  622. if err != nil {
  623. return err
  624. }
  625. container.HostnamePath = nc.HostnamePath
  626. container.HostsPath = nc.HostsPath
  627. container.ResolvConfPath = nc.ResolvConfPath
  628. container.Config.Hostname = nc.Config.Hostname
  629. container.Config.Domainname = nc.Config.Domainname
  630. return nil
  631. }
  632. if container.HostConfig.NetworkMode.IsHost() {
  633. container.Config.Hostname, err = os.Hostname()
  634. if err != nil {
  635. return err
  636. }
  637. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  638. if len(parts) > 1 {
  639. container.Config.Hostname = parts[0]
  640. container.Config.Domainname = parts[1]
  641. }
  642. }
  643. if err := daemon.allocateNetwork(container); err != nil {
  644. return err
  645. }
  646. return container.BuildHostnameFile()
  647. }
  648. // called from the libcontainer pre-start hook to set the network
  649. // namespace configuration linkage to the libnetwork "sandbox" entity
  650. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  651. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  652. var sandbox libnetwork.Sandbox
  653. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  654. daemon.netController.WalkSandboxes(search)
  655. if sandbox == nil {
  656. return derr.ErrorCodeNoSandbox.WithArgs(containerID, "no sandbox found")
  657. }
  658. return sandbox.SetKey(path)
  659. }
  660. func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) {
  661. containerID := container.HostConfig.IpcMode.Container()
  662. c, err := daemon.Get(containerID)
  663. if err != nil {
  664. return nil, err
  665. }
  666. if !c.IsRunning() {
  667. return nil, derr.ErrorCodeIPCRunning
  668. }
  669. return c, nil
  670. }
  671. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
  672. nc, err := daemon.Get(connectedContainerID)
  673. if err != nil {
  674. return nil, err
  675. }
  676. if containerID == nc.ID {
  677. return nil, derr.ErrorCodeJoinSelf
  678. }
  679. if !nc.IsRunning() {
  680. return nil, derr.ErrorCodeJoinRunning.WithArgs(connectedContainerID)
  681. }
  682. return nc, nil
  683. }
  684. func (daemon *Daemon) releaseNetwork(container *container.Container) {
  685. if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  686. return
  687. }
  688. sid := container.NetworkSettings.SandboxID
  689. networks := container.NetworkSettings.Networks
  690. for n := range networks {
  691. networks[n] = &network.EndpointSettings{}
  692. }
  693. container.NetworkSettings = &network.Settings{Networks: networks}
  694. if sid == "" || len(networks) == 0 {
  695. return
  696. }
  697. sb, err := daemon.netController.SandboxByID(sid)
  698. if err != nil {
  699. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  700. return
  701. }
  702. if err := sb.Delete(); err != nil {
  703. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  704. }
  705. }
  706. func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
  707. rootUID, rootGID := daemon.GetRemappedUIDGID()
  708. if !c.HasMountFor("/dev/shm") {
  709. shmPath, err := c.ShmResourcePath()
  710. if err != nil {
  711. return err
  712. }
  713. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  714. return err
  715. }
  716. shmSize := container.DefaultSHMSize
  717. if c.HostConfig.ShmSize != nil {
  718. shmSize = *c.HostConfig.ShmSize
  719. }
  720. shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
  721. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
  722. return fmt.Errorf("mounting shm tmpfs: %s", err)
  723. }
  724. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  725. return err
  726. }
  727. }
  728. if !c.HasMountFor("/dev/mqueue") {
  729. mqueuePath, err := c.MqueueResourcePath()
  730. if err != nil {
  731. return err
  732. }
  733. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  734. return err
  735. }
  736. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  737. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  738. }
  739. if err := os.Chown(mqueuePath, rootUID, rootGID); err != nil {
  740. return err
  741. }
  742. }
  743. return nil
  744. }
  745. func (daemon *Daemon) mountVolumes(container *container.Container) error {
  746. mounts, err := daemon.setupMounts(container)
  747. if err != nil {
  748. return err
  749. }
  750. for _, m := range mounts {
  751. dest, err := container.GetResourcePath(m.Destination)
  752. if err != nil {
  753. return err
  754. }
  755. var stat os.FileInfo
  756. stat, err = os.Stat(m.Source)
  757. if err != nil {
  758. return err
  759. }
  760. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  761. return err
  762. }
  763. opts := "rbind,ro"
  764. if m.Writable {
  765. opts = "rbind,rw"
  766. }
  767. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  768. return err
  769. }
  770. }
  771. return nil
  772. }
  773. func killProcessDirectly(container *container.Container) error {
  774. if _, err := container.WaitStop(10 * time.Second); err != nil {
  775. // Ensure that we don't kill ourselves
  776. if pid := container.GetPID(); pid != 0 {
  777. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  778. if err := syscall.Kill(pid, 9); err != nil {
  779. if err != syscall.ESRCH {
  780. return err
  781. }
  782. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  783. }
  784. }
  785. }
  786. return nil
  787. }
  788. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  789. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  790. // if there was no error, return the device
  791. if err == nil {
  792. device.Path = deviceMapping.PathInContainer
  793. return append(devs, device), nil
  794. }
  795. // if the device is not a device node
  796. // try to see if it's a directory holding many devices
  797. if err == devices.ErrNotADevice {
  798. // check if it is a directory
  799. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  800. // mount the internal devices recursively
  801. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  802. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  803. if e != nil {
  804. // ignore the device
  805. return nil
  806. }
  807. // add the device to userSpecified devices
  808. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  809. devs = append(devs, childDevice)
  810. return nil
  811. })
  812. }
  813. }
  814. if len(devs) > 0 {
  815. return devs, nil
  816. }
  817. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  818. }
  819. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  820. if len(userDevices) == 0 {
  821. return defaultDevices
  822. }
  823. paths := map[string]*configs.Device{}
  824. for _, d := range userDevices {
  825. paths[d.Path] = d
  826. }
  827. var devs []*configs.Device
  828. for _, d := range defaultDevices {
  829. if _, defined := paths[d.Path]; !defined {
  830. devs = append(devs, d)
  831. }
  832. }
  833. return append(devs, userDevices...)
  834. }
  835. func detachMounted(path string) error {
  836. return syscall.Unmount(path, syscall.MNT_DETACH)
  837. }
  838. func isLinkable(child *container.Container) bool {
  839. // A container is linkable only if it belongs to the default network
  840. _, ok := child.NetworkSettings.Networks["bridge"]
  841. return ok
  842. }