container_operations_unix.go 33 KB

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