container_operations_unix.go 33 KB

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