container_unix.go 34 KB

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