container_unix.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. derr "github.com/docker/docker/api/errors"
  16. "github.com/docker/docker/daemon/execdriver"
  17. "github.com/docker/docker/daemon/links"
  18. "github.com/docker/docker/daemon/network"
  19. "github.com/docker/docker/pkg/directory"
  20. "github.com/docker/docker/pkg/nat"
  21. "github.com/docker/docker/pkg/stringid"
  22. "github.com/docker/docker/pkg/system"
  23. "github.com/docker/docker/pkg/ulimit"
  24. "github.com/docker/docker/runconfig"
  25. "github.com/docker/docker/utils"
  26. "github.com/docker/docker/volume"
  27. "github.com/docker/libnetwork"
  28. "github.com/docker/libnetwork/netlabel"
  29. "github.com/docker/libnetwork/options"
  30. "github.com/docker/libnetwork/types"
  31. "github.com/opencontainers/runc/libcontainer/configs"
  32. "github.com/opencontainers/runc/libcontainer/devices"
  33. "github.com/opencontainers/runc/libcontainer/label"
  34. )
  35. // DefaultPathEnv is unix style list of directories to search for
  36. // executables. Each directory is separated from the next by a colon
  37. // ':' character .
  38. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  39. // Container holds the fields specific to unixen implementations. See
  40. // CommonContainer for standard fields common to all containers.
  41. type Container struct {
  42. CommonContainer
  43. // Fields below here are platform specific.
  44. activeLinks map[string]*links.Link
  45. AppArmorProfile string
  46. HostnamePath string
  47. HostsPath string
  48. MountPoints map[string]*mountPoint
  49. ResolvConfPath string
  50. Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility
  51. VolumesRW map[string]bool // Deprecated since 1.7, kept for backwards compatibility
  52. }
  53. func killProcessDirectly(container *Container) error {
  54. if _, err := container.WaitStop(10 * time.Second); err != nil {
  55. // Ensure that we don't kill ourselves
  56. if pid := container.getPID(); pid != 0 {
  57. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  58. if err := syscall.Kill(pid, 9); err != nil {
  59. if err != syscall.ESRCH {
  60. return err
  61. }
  62. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  63. }
  64. }
  65. }
  66. return nil
  67. }
  68. func (container *Container) setupLinkedContainers() ([]string, error) {
  69. var (
  70. env []string
  71. daemon = container.daemon
  72. )
  73. children, err := daemon.children(container.Name)
  74. if err != nil {
  75. return nil, err
  76. }
  77. if len(children) > 0 {
  78. for linkAlias, child := range children {
  79. if !child.IsRunning() {
  80. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  81. }
  82. link := links.NewLink(
  83. container.NetworkSettings.IPAddress,
  84. child.NetworkSettings.IPAddress,
  85. linkAlias,
  86. child.Config.Env,
  87. child.Config.ExposedPorts,
  88. )
  89. for _, envVar := range link.ToEnv() {
  90. env = append(env, envVar)
  91. }
  92. }
  93. }
  94. return env, nil
  95. }
  96. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  97. // if a domain name was specified, append it to the hostname (see #7851)
  98. fullHostname := container.Config.Hostname
  99. if container.Config.Domainname != "" {
  100. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  101. }
  102. // Setup environment
  103. env := []string{
  104. "PATH=" + DefaultPathEnv,
  105. "HOSTNAME=" + fullHostname,
  106. // Note: we don't set HOME here because it'll get autoset intelligently
  107. // based on the value of USER inside dockerinit, but only if it isn't
  108. // set already (ie, that can be overridden by setting HOME via -e or ENV
  109. // in a Dockerfile).
  110. }
  111. if container.Config.Tty {
  112. env = append(env, "TERM=xterm")
  113. }
  114. env = append(env, linkedEnv...)
  115. // because the env on the container can override certain default values
  116. // we need to replace the 'env' keys where they match and append anything
  117. // else.
  118. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  119. return env
  120. }
  121. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  122. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  123. // if there was no error, return the device
  124. if err == nil {
  125. device.Path = deviceMapping.PathInContainer
  126. return append(devs, device), nil
  127. }
  128. // if the device is not a device node
  129. // try to see if it's a directory holding many devices
  130. if err == devices.ErrNotADevice {
  131. // check if it is a directory
  132. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  133. // mount the internal devices recursively
  134. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  135. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  136. if e != nil {
  137. // ignore the device
  138. return nil
  139. }
  140. // add the device to userSpecified devices
  141. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  142. devs = append(devs, childDevice)
  143. return nil
  144. })
  145. }
  146. }
  147. if len(devs) > 0 {
  148. return devs, nil
  149. }
  150. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  151. }
  152. func populateCommand(c *Container, env []string) error {
  153. var en *execdriver.Network
  154. if !c.Config.NetworkDisabled {
  155. en = &execdriver.Network{
  156. NamespacePath: c.NetworkSettings.SandboxKey,
  157. }
  158. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  159. if parts[0] == "container" {
  160. nc, err := c.getNetworkedContainer()
  161. if err != nil {
  162. return err
  163. }
  164. en.ContainerID = nc.ID
  165. }
  166. }
  167. ipc := &execdriver.Ipc{}
  168. if c.hostConfig.IpcMode.IsContainer() {
  169. ic, err := c.getIpcContainer()
  170. if err != nil {
  171. return err
  172. }
  173. ipc.ContainerID = ic.ID
  174. } else {
  175. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  176. }
  177. pid := &execdriver.Pid{}
  178. pid.HostPid = c.hostConfig.PidMode.IsHost()
  179. uts := &execdriver.UTS{
  180. HostUTS: c.hostConfig.UTSMode.IsHost(),
  181. }
  182. // Build lists of devices allowed and created within the container.
  183. var userSpecifiedDevices []*configs.Device
  184. for _, deviceMapping := range c.hostConfig.Devices {
  185. devs, err := getDevicesFromPath(deviceMapping)
  186. if err != nil {
  187. return err
  188. }
  189. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  190. }
  191. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  192. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  193. // TODO: this can be removed after lxc-conf is fully deprecated
  194. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  195. if err != nil {
  196. return err
  197. }
  198. var rlimits []*ulimit.Rlimit
  199. ulimits := c.hostConfig.Ulimits
  200. // Merge ulimits with daemon defaults
  201. ulIdx := make(map[string]*ulimit.Ulimit)
  202. for _, ul := range ulimits {
  203. ulIdx[ul.Name] = ul
  204. }
  205. for name, ul := range c.daemon.configStore.Ulimits {
  206. if _, exists := ulIdx[name]; !exists {
  207. ulimits = append(ulimits, ul)
  208. }
  209. }
  210. for _, limit := range ulimits {
  211. rl, err := limit.GetRlimit()
  212. if err != nil {
  213. return err
  214. }
  215. rlimits = append(rlimits, rl)
  216. }
  217. resources := &execdriver.Resources{
  218. Memory: c.hostConfig.Memory,
  219. MemorySwap: c.hostConfig.MemorySwap,
  220. KernelMemory: c.hostConfig.KernelMemory,
  221. CPUShares: c.hostConfig.CPUShares,
  222. CpusetCpus: c.hostConfig.CpusetCpus,
  223. CpusetMems: c.hostConfig.CpusetMems,
  224. CPUPeriod: c.hostConfig.CPUPeriod,
  225. CPUQuota: c.hostConfig.CPUQuota,
  226. BlkioWeight: c.hostConfig.BlkioWeight,
  227. Rlimits: rlimits,
  228. OomKillDisable: c.hostConfig.OomKillDisable,
  229. MemorySwappiness: -1,
  230. }
  231. if c.hostConfig.MemorySwappiness != nil {
  232. resources.MemorySwappiness = *c.hostConfig.MemorySwappiness
  233. }
  234. processConfig := execdriver.ProcessConfig{
  235. Privileged: c.hostConfig.Privileged,
  236. Entrypoint: c.Path,
  237. Arguments: c.Args,
  238. Tty: c.Config.Tty,
  239. User: c.Config.User,
  240. }
  241. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  242. processConfig.Env = env
  243. c.command = &execdriver.Command{
  244. ID: c.ID,
  245. Rootfs: c.rootfsPath(),
  246. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  247. InitPath: "/.dockerinit",
  248. WorkingDir: c.Config.WorkingDir,
  249. Network: en,
  250. Ipc: ipc,
  251. Pid: pid,
  252. UTS: uts,
  253. Resources: resources,
  254. AllowedDevices: allowedDevices,
  255. AutoCreatedDevices: autoCreatedDevices,
  256. CapAdd: c.hostConfig.CapAdd.Slice(),
  257. CapDrop: c.hostConfig.CapDrop.Slice(),
  258. GroupAdd: c.hostConfig.GroupAdd,
  259. ProcessConfig: processConfig,
  260. ProcessLabel: c.getProcessLabel(),
  261. MountLabel: c.getMountLabel(),
  262. LxcConfig: lxcConfig,
  263. AppArmorProfile: c.AppArmorProfile,
  264. CgroupParent: c.hostConfig.CgroupParent,
  265. }
  266. return nil
  267. }
  268. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  269. if len(userDevices) == 0 {
  270. return defaultDevices
  271. }
  272. paths := map[string]*configs.Device{}
  273. for _, d := range userDevices {
  274. paths[d.Path] = d
  275. }
  276. var devs []*configs.Device
  277. for _, d := range defaultDevices {
  278. if _, defined := paths[d.Path]; !defined {
  279. devs = append(devs, d)
  280. }
  281. }
  282. return append(devs, userDevices...)
  283. }
  284. // GetSize returns the real size & virtual size of the container.
  285. func (container *Container) getSize() (int64, int64) {
  286. var (
  287. sizeRw, sizeRootfs int64
  288. err error
  289. driver = container.daemon.driver
  290. )
  291. if err := container.Mount(); err != nil {
  292. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  293. return sizeRw, sizeRootfs
  294. }
  295. defer container.Unmount()
  296. initID := fmt.Sprintf("%s-init", container.ID)
  297. sizeRw, err = driver.DiffSize(container.ID, initID)
  298. if err != nil {
  299. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  300. // FIXME: GetSize should return an error. Not changing it now in case
  301. // there is a side-effect.
  302. sizeRw = -1
  303. }
  304. if _, err = os.Stat(container.basefs); err == nil {
  305. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  306. sizeRootfs = -1
  307. }
  308. }
  309. return sizeRw, sizeRootfs
  310. }
  311. // Attempt to set the network mounts given a provided destination and
  312. // the path to use for it; return true if the given destination was a
  313. // network mount file
  314. func (container *Container) trySetNetworkMount(destination string, path string) bool {
  315. if destination == "/etc/resolv.conf" {
  316. container.ResolvConfPath = path
  317. return true
  318. }
  319. if destination == "/etc/hostname" {
  320. container.HostnamePath = path
  321. return true
  322. }
  323. if destination == "/etc/hosts" {
  324. container.HostsPath = path
  325. return true
  326. }
  327. return false
  328. }
  329. func (container *Container) buildHostnameFile() error {
  330. hostnamePath, err := container.getRootResourcePath("hostname")
  331. if err != nil {
  332. return err
  333. }
  334. container.HostnamePath = hostnamePath
  335. if container.Config.Domainname != "" {
  336. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  337. }
  338. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  339. }
  340. func (container *Container) buildSandboxOptions() ([]libnetwork.SandboxOption, error) {
  341. var (
  342. sboxOptions []libnetwork.SandboxOption
  343. err error
  344. dns []string
  345. dnsSearch []string
  346. )
  347. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  348. libnetwork.OptionDomainname(container.Config.Domainname))
  349. if container.hostConfig.NetworkMode.IsHost() {
  350. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  351. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  352. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  353. }
  354. container.HostsPath, err = container.getRootResourcePath("hosts")
  355. if err != nil {
  356. return nil, err
  357. }
  358. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  359. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  360. if err != nil {
  361. return nil, err
  362. }
  363. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  364. if len(container.hostConfig.DNS) > 0 {
  365. dns = container.hostConfig.DNS
  366. } else if len(container.daemon.configStore.DNS) > 0 {
  367. dns = container.daemon.configStore.DNS
  368. }
  369. for _, d := range dns {
  370. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  371. }
  372. if len(container.hostConfig.DNSSearch) > 0 {
  373. dnsSearch = container.hostConfig.DNSSearch
  374. } else if len(container.daemon.configStore.DNSSearch) > 0 {
  375. dnsSearch = container.daemon.configStore.DNSSearch
  376. }
  377. for _, ds := range dnsSearch {
  378. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  379. }
  380. if container.NetworkSettings.SecondaryIPAddresses != nil {
  381. name := container.Config.Hostname
  382. if container.Config.Domainname != "" {
  383. name = name + "." + container.Config.Domainname
  384. }
  385. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  386. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  387. }
  388. }
  389. var childEndpoints, parentEndpoints []string
  390. children, err := container.daemon.children(container.Name)
  391. if err != nil {
  392. return nil, err
  393. }
  394. for linkAlias, child := range children {
  395. _, alias := path.Split(linkAlias)
  396. // allow access to the linked container via the alias, real name, and container hostname
  397. aliasList := alias + " " + child.Config.Hostname
  398. // only add the name if alias isn't equal to the name
  399. if alias != child.Name[1:] {
  400. aliasList = aliasList + " " + child.Name[1:]
  401. }
  402. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  403. if child.NetworkSettings.EndpointID != "" {
  404. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  405. }
  406. }
  407. for _, extraHost := range container.hostConfig.ExtraHosts {
  408. // allow IPv6 addresses in extra hosts; only split on first ":"
  409. parts := strings.SplitN(extraHost, ":", 2)
  410. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  411. }
  412. refs := container.daemon.containerGraph().RefPaths(container.ID)
  413. for _, ref := range refs {
  414. if ref.ParentID == "0" {
  415. continue
  416. }
  417. c, err := container.daemon.Get(ref.ParentID)
  418. if err != nil {
  419. logrus.Error(err)
  420. }
  421. if c != nil && !container.daemon.configStore.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  422. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  423. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, container.NetworkSettings.IPAddress))
  424. if c.NetworkSettings.EndpointID != "" {
  425. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  426. }
  427. }
  428. }
  429. linkOptions := options.Generic{
  430. netlabel.GenericData: options.Generic{
  431. "ParentEndpoints": parentEndpoints,
  432. "ChildEndpoints": childEndpoints,
  433. },
  434. }
  435. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  436. return sboxOptions, nil
  437. }
  438. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  439. if ep == nil {
  440. return nil, derr.ErrorCodeEmptyEndpoint
  441. }
  442. if networkSettings == nil {
  443. return nil, derr.ErrorCodeEmptyNetwork
  444. }
  445. driverInfo, err := ep.DriverInfo()
  446. if err != nil {
  447. return nil, err
  448. }
  449. if driverInfo == nil {
  450. // It is not an error for epInfo to be nil
  451. return networkSettings, nil
  452. }
  453. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  454. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  455. }
  456. networkSettings.Ports = nat.PortMap{}
  457. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  458. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  459. for _, tp := range exposedPorts {
  460. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  461. if err != nil {
  462. return nil, derr.ErrorCodeParsingPort.WithArgs(tp.Port, err)
  463. }
  464. networkSettings.Ports[natPort] = nil
  465. }
  466. }
  467. }
  468. mapData, ok := driverInfo[netlabel.PortMap]
  469. if !ok {
  470. return networkSettings, nil
  471. }
  472. if portMapping, ok := mapData.([]types.PortBinding); ok {
  473. for _, pp := range portMapping {
  474. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  475. if err != nil {
  476. return nil, err
  477. }
  478. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  479. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  480. }
  481. }
  482. return networkSettings, nil
  483. }
  484. func (container *Container) buildEndpointInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  485. if ep == nil {
  486. return nil, derr.ErrorCodeEmptyEndpoint
  487. }
  488. if networkSettings == nil {
  489. return nil, derr.ErrorCodeEmptyNetwork
  490. }
  491. epInfo := ep.Info()
  492. if epInfo == nil {
  493. // It is not an error to get an empty endpoint info
  494. return networkSettings, nil
  495. }
  496. iface := epInfo.Iface()
  497. if iface == nil {
  498. return networkSettings, nil
  499. }
  500. ones, _ := iface.Address().Mask.Size()
  501. networkSettings.IPAddress = iface.Address().IP.String()
  502. networkSettings.IPPrefixLen = ones
  503. if iface.AddressIPv6().IP.To16() != nil {
  504. onesv6, _ := iface.AddressIPv6().Mask.Size()
  505. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  506. networkSettings.GlobalIPv6PrefixLen = onesv6
  507. }
  508. return networkSettings, nil
  509. }
  510. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  511. epInfo := ep.Info()
  512. if epInfo == nil {
  513. // It is not an error to get an empty endpoint info
  514. return nil
  515. }
  516. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  517. if epInfo.GatewayIPv6().To16() != nil {
  518. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  519. }
  520. return nil
  521. }
  522. func (container *Container) updateEndpointNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  523. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  524. networkSettings, err := container.buildPortMapInfo(ep, networkSettings)
  525. if err != nil {
  526. return err
  527. }
  528. networkSettings, err = container.buildEndpointInfo(ep, networkSettings)
  529. if err != nil {
  530. return err
  531. }
  532. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  533. networkSettings.Bridge = container.daemon.configStore.Bridge.Iface
  534. }
  535. container.NetworkSettings = networkSettings
  536. return nil
  537. }
  538. func (container *Container) updateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  539. container.NetworkSettings.SandboxID = sb.ID()
  540. container.NetworkSettings.SandboxKey = sb.Key()
  541. return nil
  542. }
  543. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  544. // get removed/unlinked).
  545. func (container *Container) updateNetwork() error {
  546. ctrl := container.daemon.netController
  547. sid := container.NetworkSettings.SandboxID
  548. sb, err := ctrl.SandboxByID(sid)
  549. if err != nil {
  550. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  551. }
  552. options, err := container.buildSandboxOptions()
  553. if err != nil {
  554. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  555. }
  556. if err := sb.Refresh(options...); err != nil {
  557. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  558. }
  559. return nil
  560. }
  561. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  562. var (
  563. portSpecs = make(nat.PortSet)
  564. bindings = make(nat.PortMap)
  565. pbList []types.PortBinding
  566. exposeList []types.TransportPort
  567. createOptions []libnetwork.EndpointOption
  568. )
  569. if container.Config.ExposedPorts != nil {
  570. portSpecs = container.Config.ExposedPorts
  571. }
  572. if container.hostConfig.PortBindings != nil {
  573. for p, b := range container.hostConfig.PortBindings {
  574. bindings[p] = []nat.PortBinding{}
  575. for _, bb := range b {
  576. bindings[p] = append(bindings[p], nat.PortBinding{
  577. HostIP: bb.HostIP,
  578. HostPort: bb.HostPort,
  579. })
  580. }
  581. }
  582. }
  583. ports := make([]nat.Port, len(portSpecs))
  584. var i int
  585. for p := range portSpecs {
  586. ports[i] = p
  587. i++
  588. }
  589. nat.SortPortMap(ports, bindings)
  590. for _, port := range ports {
  591. expose := types.TransportPort{}
  592. expose.Proto = types.ParseProtocol(port.Proto())
  593. expose.Port = uint16(port.Int())
  594. exposeList = append(exposeList, expose)
  595. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  596. binding := bindings[port]
  597. for i := 0; i < len(binding); i++ {
  598. pbCopy := pb.GetCopy()
  599. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  600. var portStart, portEnd int
  601. if err == nil {
  602. portStart, portEnd, err = newP.Range()
  603. }
  604. if err != nil {
  605. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  606. }
  607. pbCopy.HostPort = uint16(portStart)
  608. pbCopy.HostPortEnd = uint16(portEnd)
  609. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  610. pbList = append(pbList, pbCopy)
  611. }
  612. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  613. pbList = append(pbList, pb)
  614. }
  615. }
  616. createOptions = append(createOptions,
  617. libnetwork.CreateOptionPortMapping(pbList),
  618. libnetwork.CreateOptionExposedPorts(exposeList))
  619. if container.Config.MacAddress != "" {
  620. mac, err := net.ParseMAC(container.Config.MacAddress)
  621. if err != nil {
  622. return nil, err
  623. }
  624. genericOption := options.Generic{
  625. netlabel.MacAddress: mac,
  626. }
  627. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  628. }
  629. return createOptions, nil
  630. }
  631. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  632. dn := controller.Config().Daemon.DefaultNetwork
  633. dd := controller.Config().Daemon.DefaultDriver
  634. snd := strings.Split(service, ".")
  635. if len(snd) > 2 {
  636. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  637. }
  638. if len(snd) > 1 {
  639. return snd[0], snd[1], dd
  640. }
  641. return snd[0], dn, dd
  642. }
  643. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  644. createOptions := []libnetwork.NetworkOption{}
  645. genericOption := options.Generic{}
  646. // Bridge driver is special due to legacy reasons
  647. if runconfig.NetworkMode(driver).IsBridge() {
  648. genericOption[netlabel.GenericData] = map[string]interface{}{
  649. "BridgeName": dnet,
  650. "AllowNonDefaultBridge": "true",
  651. }
  652. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  653. createOptions = append(createOptions, networkOption)
  654. }
  655. return controller.NewNetwork(driver, dnet, createOptions...)
  656. }
  657. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  658. switch primaryNetworkType {
  659. case "bridge", "none", "host", "container":
  660. return false
  661. }
  662. if container.daemon.configStore.DisableBridge {
  663. return false
  664. }
  665. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  666. return true
  667. }
  668. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  669. return true
  670. }
  671. return false
  672. }
  673. func (container *Container) allocateNetwork() error {
  674. mode := container.hostConfig.NetworkMode
  675. controller := container.daemon.netController
  676. if container.Config.NetworkDisabled || mode.IsContainer() {
  677. return nil
  678. }
  679. networkDriver := string(mode)
  680. service := container.Config.PublishService
  681. networkName := mode.NetworkName()
  682. if mode.IsDefault() {
  683. if service != "" {
  684. service, networkName, networkDriver = parseService(controller, service)
  685. } else {
  686. networkName = controller.Config().Daemon.DefaultNetwork
  687. networkDriver = controller.Config().Daemon.DefaultDriver
  688. }
  689. } else if service != "" {
  690. return derr.ErrorCodeNetworkConflict
  691. }
  692. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.configStore.DisableBridge {
  693. container.Config.NetworkDisabled = true
  694. return nil
  695. }
  696. if service == "" {
  697. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  698. // For backward compatibility, replacing "." with "-", instead of failing
  699. service = strings.Replace(container.Name, ".", "-", -1)
  700. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  701. service = strings.Replace(service, "/", "", -1)
  702. }
  703. if container.secondaryNetworkRequired(networkDriver) {
  704. // Configure Bridge as secondary network for port binding purposes
  705. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  706. return err
  707. }
  708. }
  709. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  710. return err
  711. }
  712. return container.writeHostConfig()
  713. }
  714. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  715. controller := container.daemon.netController
  716. n, err := controller.NetworkByName(networkName)
  717. if err != nil {
  718. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  719. return err
  720. }
  721. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  722. return err
  723. }
  724. }
  725. ep, err := n.EndpointByName(service)
  726. if err != nil {
  727. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  728. return err
  729. }
  730. createOptions, err := container.buildCreateEndpointOptions()
  731. if err != nil {
  732. return err
  733. }
  734. ep, err = n.CreateEndpoint(service, createOptions...)
  735. if err != nil {
  736. return err
  737. }
  738. }
  739. if err := container.updateEndpointNetworkSettings(n, ep); err != nil {
  740. return err
  741. }
  742. var sb libnetwork.Sandbox
  743. controller.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  744. if s.ContainerID() == container.ID {
  745. sb = s
  746. return true
  747. }
  748. return false
  749. })
  750. if sb == nil {
  751. options, err := container.buildSandboxOptions()
  752. if err != nil {
  753. return err
  754. }
  755. sb, err = controller.NewSandbox(container.ID, options...)
  756. if err != nil {
  757. return err
  758. }
  759. }
  760. container.updateSandboxNetworkSettings(sb)
  761. if err := ep.Join(sb); err != nil {
  762. return err
  763. }
  764. if err := container.updateJoinInfo(ep); err != nil {
  765. return derr.ErrorCodeJoinInfo.WithArgs(err)
  766. }
  767. return nil
  768. }
  769. func (container *Container) initializeNetworking() error {
  770. var err error
  771. if container.hostConfig.NetworkMode.IsContainer() {
  772. // we need to get the hosts files from the container to join
  773. nc, err := container.getNetworkedContainer()
  774. if err != nil {
  775. return err
  776. }
  777. container.HostnamePath = nc.HostnamePath
  778. container.HostsPath = nc.HostsPath
  779. container.ResolvConfPath = nc.ResolvConfPath
  780. container.Config.Hostname = nc.Config.Hostname
  781. container.Config.Domainname = nc.Config.Domainname
  782. return nil
  783. }
  784. if container.hostConfig.NetworkMode.IsHost() {
  785. container.Config.Hostname, err = os.Hostname()
  786. if err != nil {
  787. return err
  788. }
  789. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  790. if len(parts) > 1 {
  791. container.Config.Hostname = parts[0]
  792. container.Config.Domainname = parts[1]
  793. }
  794. }
  795. if err := container.allocateNetwork(); err != nil {
  796. return err
  797. }
  798. return container.buildHostnameFile()
  799. }
  800. func (container *Container) getIpcContainer() (*Container, error) {
  801. containerID := container.hostConfig.IpcMode.Container()
  802. c, err := container.daemon.Get(containerID)
  803. if err != nil {
  804. return nil, err
  805. }
  806. if !c.IsRunning() {
  807. return nil, derr.ErrorCodeIPCRunning
  808. }
  809. return c, nil
  810. }
  811. func (container *Container) setupWorkingDirectory() error {
  812. if container.Config.WorkingDir != "" {
  813. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  814. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  815. if err != nil {
  816. return err
  817. }
  818. pthInfo, err := os.Stat(pth)
  819. if err != nil {
  820. if !os.IsNotExist(err) {
  821. return err
  822. }
  823. if err := system.MkdirAll(pth, 0755); err != nil {
  824. return err
  825. }
  826. }
  827. if pthInfo != nil && !pthInfo.IsDir() {
  828. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  829. }
  830. }
  831. return nil
  832. }
  833. func (container *Container) getNetworkedContainer() (*Container, error) {
  834. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  835. switch parts[0] {
  836. case "container":
  837. if len(parts) != 2 {
  838. return nil, derr.ErrorCodeParseContainer
  839. }
  840. nc, err := container.daemon.Get(parts[1])
  841. if err != nil {
  842. return nil, err
  843. }
  844. if container == nc {
  845. return nil, derr.ErrorCodeJoinSelf
  846. }
  847. if !nc.IsRunning() {
  848. return nil, derr.ErrorCodeJoinRunning.WithArgs(parts[1])
  849. }
  850. return nc, nil
  851. default:
  852. return nil, derr.ErrorCodeModeNotContainer
  853. }
  854. }
  855. func (container *Container) releaseNetwork() {
  856. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  857. return
  858. }
  859. sid := container.NetworkSettings.SandboxID
  860. eid := container.NetworkSettings.EndpointID
  861. nid := container.NetworkSettings.NetworkID
  862. container.NetworkSettings = &network.Settings{}
  863. if sid == "" || nid == "" || eid == "" {
  864. return
  865. }
  866. sb, err := container.daemon.netController.SandboxByID(sid)
  867. if err != nil {
  868. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  869. return
  870. }
  871. n, err := container.daemon.netController.NetworkByID(nid)
  872. if err != nil {
  873. logrus.Errorf("error locating network id %s: %v", nid, err)
  874. return
  875. }
  876. ep, err := n.EndpointByID(eid)
  877. if err != nil {
  878. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  879. return
  880. }
  881. if err := sb.Delete(); err != nil {
  882. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  883. return
  884. }
  885. // In addition to leaving all endpoints, delete implicitly created endpoint
  886. if container.Config.PublishService == "" {
  887. if err := ep.Delete(); err != nil {
  888. logrus.Errorf("deleting endpoint failed: %v", err)
  889. }
  890. }
  891. }
  892. func (container *Container) unmountVolumes(forceSyscall bool) error {
  893. var volumeMounts []mountPoint
  894. for _, mntPoint := range container.MountPoints {
  895. dest, err := container.GetResourcePath(mntPoint.Destination)
  896. if err != nil {
  897. return err
  898. }
  899. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  900. }
  901. for _, mnt := range container.networkMounts() {
  902. dest, err := container.GetResourcePath(mnt.Destination)
  903. if err != nil {
  904. return err
  905. }
  906. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  907. }
  908. for _, volumeMount := range volumeMounts {
  909. if forceSyscall {
  910. syscall.Unmount(volumeMount.Destination, 0)
  911. }
  912. if volumeMount.Volume != nil {
  913. if err := volumeMount.Volume.Unmount(); err != nil {
  914. return err
  915. }
  916. }
  917. }
  918. return nil
  919. }
  920. func (container *Container) networkMounts() []execdriver.Mount {
  921. var mounts []execdriver.Mount
  922. shared := container.hostConfig.NetworkMode.IsContainer()
  923. if container.ResolvConfPath != "" {
  924. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  925. writable := !container.hostConfig.ReadonlyRootfs
  926. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  927. writable = m.RW
  928. }
  929. mounts = append(mounts, execdriver.Mount{
  930. Source: container.ResolvConfPath,
  931. Destination: "/etc/resolv.conf",
  932. Writable: writable,
  933. Private: true,
  934. })
  935. }
  936. if container.HostnamePath != "" {
  937. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  938. writable := !container.hostConfig.ReadonlyRootfs
  939. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  940. writable = m.RW
  941. }
  942. mounts = append(mounts, execdriver.Mount{
  943. Source: container.HostnamePath,
  944. Destination: "/etc/hostname",
  945. Writable: writable,
  946. Private: true,
  947. })
  948. }
  949. if container.HostsPath != "" {
  950. label.Relabel(container.HostsPath, container.MountLabel, shared)
  951. writable := !container.hostConfig.ReadonlyRootfs
  952. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  953. writable = m.RW
  954. }
  955. mounts = append(mounts, execdriver.Mount{
  956. Source: container.HostsPath,
  957. Destination: "/etc/hosts",
  958. Writable: writable,
  959. Private: true,
  960. })
  961. }
  962. return mounts
  963. }
  964. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  965. container.MountPoints[destination] = &mountPoint{
  966. Name: name,
  967. Source: source,
  968. Destination: destination,
  969. RW: rw,
  970. }
  971. }
  972. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  973. container.MountPoints[destination] = &mountPoint{
  974. Name: name,
  975. Driver: volume.DefaultDriverName,
  976. Destination: destination,
  977. RW: rw,
  978. }
  979. }
  980. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  981. container.MountPoints[destination] = &mountPoint{
  982. Name: vol.Name(),
  983. Driver: vol.DriverName(),
  984. Destination: destination,
  985. RW: rw,
  986. Volume: vol,
  987. }
  988. }
  989. func (container *Container) isDestinationMounted(destination string) bool {
  990. return container.MountPoints[destination] != nil
  991. }
  992. func (container *Container) prepareMountPoints() error {
  993. for _, config := range container.MountPoints {
  994. if len(config.Driver) > 0 {
  995. v, err := container.daemon.createVolume(config.Name, config.Driver, nil)
  996. if err != nil {
  997. return err
  998. }
  999. config.Volume = v
  1000. }
  1001. }
  1002. return nil
  1003. }
  1004. func (container *Container) removeMountPoints(rm bool) error {
  1005. var rmErrors []string
  1006. for _, m := range container.MountPoints {
  1007. if m.Volume == nil {
  1008. continue
  1009. }
  1010. container.daemon.volumes.Decrement(m.Volume)
  1011. if rm {
  1012. err := container.daemon.volumes.Remove(m.Volume)
  1013. // ErrVolumeInUse is ignored because having this
  1014. // volume being referenced by othe container is
  1015. // not an error, but an implementation detail.
  1016. // This prevents docker from logging "ERROR: Volume in use"
  1017. // where there is another container using the volume.
  1018. if err != nil && err != ErrVolumeInUse {
  1019. rmErrors = append(rmErrors, err.Error())
  1020. }
  1021. }
  1022. }
  1023. if len(rmErrors) > 0 {
  1024. return derr.ErrorCodeRemovingVolume.WithArgs(strings.Join(rmErrors, "\n"))
  1025. }
  1026. return nil
  1027. }