container_operations_unix.go 33 KB

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