container_unix.go 33 KB

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