container_operations_unix.go 34 KB

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