container_operations_unix.go 33 KB

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