container_operations_unix.go 33 KB

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