container_operations_unix.go 33 KB

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