container_operations_unix.go 33 KB

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