container_unix.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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) buildJoinOptions() ([]libnetwork.EndpointOption, error) {
  340. var (
  341. joinOptions []libnetwork.EndpointOption
  342. err error
  343. dns []string
  344. dnsSearch []string
  345. )
  346. joinOptions = append(joinOptions, libnetwork.JoinOptionHostname(container.Config.Hostname),
  347. libnetwork.JoinOptionDomainname(container.Config.Domainname))
  348. if container.hostConfig.NetworkMode.IsHost() {
  349. joinOptions = append(joinOptions, libnetwork.JoinOptionUseDefaultSandbox())
  350. }
  351. container.HostsPath, err = container.getRootResourcePath("hosts")
  352. if err != nil {
  353. return nil, err
  354. }
  355. joinOptions = append(joinOptions, libnetwork.JoinOptionHostsPath(container.HostsPath))
  356. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  357. if err != nil {
  358. return nil, err
  359. }
  360. joinOptions = append(joinOptions, libnetwork.JoinOptionResolvConfPath(container.ResolvConfPath))
  361. if len(container.hostConfig.DNS) > 0 {
  362. dns = container.hostConfig.DNS
  363. } else if len(container.daemon.configStore.DNS) > 0 {
  364. dns = container.daemon.configStore.DNS
  365. }
  366. for _, d := range dns {
  367. joinOptions = append(joinOptions, libnetwork.JoinOptionDNS(d))
  368. }
  369. if len(container.hostConfig.DNSSearch) > 0 {
  370. dnsSearch = container.hostConfig.DNSSearch
  371. } else if len(container.daemon.configStore.DNSSearch) > 0 {
  372. dnsSearch = container.daemon.configStore.DNSSearch
  373. }
  374. for _, ds := range dnsSearch {
  375. joinOptions = append(joinOptions, libnetwork.JoinOptionDNSSearch(ds))
  376. }
  377. if container.NetworkSettings.SecondaryIPAddresses != nil {
  378. name := container.Config.Hostname
  379. if container.Config.Domainname != "" {
  380. name = name + "." + container.Config.Domainname
  381. }
  382. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  383. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(name, a.Addr))
  384. }
  385. }
  386. var childEndpoints, parentEndpoints []string
  387. children, err := container.daemon.children(container.Name)
  388. if err != nil {
  389. return nil, err
  390. }
  391. for linkAlias, child := range children {
  392. _, alias := path.Split(linkAlias)
  393. // allow access to the linked container via the alias, real name, and container hostname
  394. aliasList := alias + " " + child.Config.Hostname
  395. // only add the name if alias isn't equal to the name
  396. if alias != child.Name[1:] {
  397. aliasList = aliasList + " " + child.Name[1:]
  398. }
  399. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  400. if child.NetworkSettings.EndpointID != "" {
  401. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  402. }
  403. }
  404. for _, extraHost := range container.hostConfig.ExtraHosts {
  405. // allow IPv6 addresses in extra hosts; only split on first ":"
  406. parts := strings.SplitN(extraHost, ":", 2)
  407. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(parts[0], parts[1]))
  408. }
  409. refs := container.daemon.containerGraph().RefPaths(container.ID)
  410. for _, ref := range refs {
  411. if ref.ParentID == "0" {
  412. continue
  413. }
  414. c, err := container.daemon.Get(ref.ParentID)
  415. if err != nil {
  416. logrus.Error(err)
  417. }
  418. if c != nil && !container.daemon.configStore.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  419. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  420. joinOptions = append(joinOptions, libnetwork.JoinOptionParentUpdate(c.NetworkSettings.EndpointID, ref.Name, container.NetworkSettings.IPAddress))
  421. if c.NetworkSettings.EndpointID != "" {
  422. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  423. }
  424. }
  425. }
  426. linkOptions := options.Generic{
  427. netlabel.GenericData: options.Generic{
  428. "ParentEndpoints": parentEndpoints,
  429. "ChildEndpoints": childEndpoints,
  430. },
  431. }
  432. joinOptions = append(joinOptions, libnetwork.JoinOptionGeneric(linkOptions))
  433. return joinOptions, nil
  434. }
  435. func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  436. if ep == nil {
  437. return nil, fmt.Errorf("invalid endpoint while building port map info")
  438. }
  439. if networkSettings == nil {
  440. return nil, fmt.Errorf("invalid networksettings while building port map info")
  441. }
  442. driverInfo, err := ep.DriverInfo()
  443. if err != nil {
  444. return nil, err
  445. }
  446. if driverInfo == nil {
  447. // It is not an error for epInfo to be nil
  448. return networkSettings, nil
  449. }
  450. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  451. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  452. }
  453. networkSettings.Ports = nat.PortMap{}
  454. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  455. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  456. for _, tp := range exposedPorts {
  457. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  458. if err != nil {
  459. return nil, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err)
  460. }
  461. networkSettings.Ports[natPort] = nil
  462. }
  463. }
  464. }
  465. mapData, ok := driverInfo[netlabel.PortMap]
  466. if !ok {
  467. return networkSettings, nil
  468. }
  469. if portMapping, ok := mapData.([]types.PortBinding); ok {
  470. for _, pp := range portMapping {
  471. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  472. if err != nil {
  473. return nil, err
  474. }
  475. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  476. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  477. }
  478. }
  479. return networkSettings, nil
  480. }
  481. func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  482. if ep == nil {
  483. return nil, fmt.Errorf("invalid endpoint while building port map info")
  484. }
  485. if networkSettings == nil {
  486. return nil, fmt.Errorf("invalid networksettings while building port map info")
  487. }
  488. epInfo := ep.Info()
  489. if epInfo == nil {
  490. // It is not an error to get an empty endpoint info
  491. return networkSettings, nil
  492. }
  493. ifaceList := epInfo.InterfaceList()
  494. if len(ifaceList) == 0 {
  495. return networkSettings, nil
  496. }
  497. iface := ifaceList[0]
  498. ones, _ := iface.Address().Mask.Size()
  499. networkSettings.IPAddress = iface.Address().IP.String()
  500. networkSettings.IPPrefixLen = ones
  501. if iface.AddressIPv6().IP.To16() != nil {
  502. onesv6, _ := iface.AddressIPv6().Mask.Size()
  503. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  504. networkSettings.GlobalIPv6PrefixLen = onesv6
  505. }
  506. if len(ifaceList) == 1 {
  507. return networkSettings, nil
  508. }
  509. networkSettings.SecondaryIPAddresses = make([]network.Address, 0, len(ifaceList)-1)
  510. networkSettings.SecondaryIPv6Addresses = make([]network.Address, 0, len(ifaceList)-1)
  511. for _, iface := range ifaceList[1:] {
  512. ones, _ := iface.Address().Mask.Size()
  513. addr := network.Address{Addr: iface.Address().IP.String(), PrefixLen: ones}
  514. networkSettings.SecondaryIPAddresses = append(networkSettings.SecondaryIPAddresses, addr)
  515. if iface.AddressIPv6().IP.To16() != nil {
  516. onesv6, _ := iface.AddressIPv6().Mask.Size()
  517. addrv6 := network.Address{Addr: iface.AddressIPv6().IP.String(), PrefixLen: onesv6}
  518. networkSettings.SecondaryIPv6Addresses = append(networkSettings.SecondaryIPv6Addresses, addrv6)
  519. }
  520. }
  521. return networkSettings, nil
  522. }
  523. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  524. epInfo := ep.Info()
  525. if epInfo == nil {
  526. // It is not an error to get an empty endpoint info
  527. return nil
  528. }
  529. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  530. if epInfo.GatewayIPv6().To16() != nil {
  531. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  532. }
  533. container.NetworkSettings.SandboxKey = epInfo.SandboxKey()
  534. return nil
  535. }
  536. func (container *Container) updateNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  537. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  538. networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings)
  539. if err != nil {
  540. return err
  541. }
  542. networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
  543. if err != nil {
  544. return err
  545. }
  546. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  547. networkSettings.Bridge = container.daemon.configStore.Bridge.Iface
  548. }
  549. container.NetworkSettings = networkSettings
  550. return nil
  551. }
  552. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  553. // get removed/unlinked).
  554. func (container *Container) updateNetwork() error {
  555. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  556. if err != nil {
  557. return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  558. }
  559. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  560. if err != nil {
  561. return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  562. }
  563. if err := ep.Leave(container.ID); err != nil {
  564. return fmt.Errorf("endpoint leave failed: %v", err)
  565. }
  566. joinOptions, err := container.buildJoinOptions()
  567. if err != nil {
  568. return fmt.Errorf("Update network failed: %v", err)
  569. }
  570. if err := ep.Join(container.ID, joinOptions...); err != nil {
  571. return fmt.Errorf("endpoint join failed: %v", err)
  572. }
  573. if err := container.updateJoinInfo(ep); err != nil {
  574. return fmt.Errorf("Updating join info failed: %v", err)
  575. }
  576. return nil
  577. }
  578. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  579. var (
  580. portSpecs = make(nat.PortSet)
  581. bindings = make(nat.PortMap)
  582. pbList []types.PortBinding
  583. exposeList []types.TransportPort
  584. createOptions []libnetwork.EndpointOption
  585. )
  586. if container.Config.ExposedPorts != nil {
  587. portSpecs = container.Config.ExposedPorts
  588. }
  589. if container.hostConfig.PortBindings != nil {
  590. for p, b := range container.hostConfig.PortBindings {
  591. bindings[p] = []nat.PortBinding{}
  592. for _, bb := range b {
  593. bindings[p] = append(bindings[p], nat.PortBinding{
  594. HostIP: bb.HostIP,
  595. HostPort: bb.HostPort,
  596. })
  597. }
  598. }
  599. }
  600. ports := make([]nat.Port, len(portSpecs))
  601. var i int
  602. for p := range portSpecs {
  603. ports[i] = p
  604. i++
  605. }
  606. nat.SortPortMap(ports, bindings)
  607. for _, port := range ports {
  608. expose := types.TransportPort{}
  609. expose.Proto = types.ParseProtocol(port.Proto())
  610. expose.Port = uint16(port.Int())
  611. exposeList = append(exposeList, expose)
  612. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  613. binding := bindings[port]
  614. for i := 0; i < len(binding); i++ {
  615. pbCopy := pb.GetCopy()
  616. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  617. var portStart, portEnd int
  618. if err == nil {
  619. portStart, portEnd, err = newP.Range()
  620. }
  621. if err != nil {
  622. return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
  623. }
  624. pbCopy.HostPort = uint16(portStart)
  625. pbCopy.HostPortEnd = uint16(portEnd)
  626. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  627. pbList = append(pbList, pbCopy)
  628. }
  629. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  630. pbList = append(pbList, pb)
  631. }
  632. }
  633. createOptions = append(createOptions,
  634. libnetwork.CreateOptionPortMapping(pbList),
  635. libnetwork.CreateOptionExposedPorts(exposeList))
  636. if container.Config.MacAddress != "" {
  637. mac, err := net.ParseMAC(container.Config.MacAddress)
  638. if err != nil {
  639. return nil, err
  640. }
  641. genericOption := options.Generic{
  642. netlabel.MacAddress: mac,
  643. }
  644. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  645. }
  646. return createOptions, nil
  647. }
  648. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  649. dn := controller.Config().Daemon.DefaultNetwork
  650. dd := controller.Config().Daemon.DefaultDriver
  651. snd := strings.Split(service, ".")
  652. if len(snd) > 2 {
  653. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  654. }
  655. if len(snd) > 1 {
  656. return snd[0], snd[1], dd
  657. }
  658. return snd[0], dn, dd
  659. }
  660. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  661. createOptions := []libnetwork.NetworkOption{}
  662. genericOption := options.Generic{}
  663. // Bridge driver is special due to legacy reasons
  664. if runconfig.NetworkMode(driver).IsBridge() {
  665. genericOption[netlabel.GenericData] = map[string]interface{}{
  666. "BridgeName": dnet,
  667. "AllowNonDefaultBridge": "true",
  668. }
  669. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  670. createOptions = append(createOptions, networkOption)
  671. }
  672. return controller.NewNetwork(driver, dnet, createOptions...)
  673. }
  674. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  675. switch primaryNetworkType {
  676. case "bridge", "none", "host", "container":
  677. return false
  678. }
  679. if container.daemon.configStore.DisableBridge {
  680. return false
  681. }
  682. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  683. return true
  684. }
  685. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  686. return true
  687. }
  688. return false
  689. }
  690. func (container *Container) allocateNetwork() error {
  691. mode := container.hostConfig.NetworkMode
  692. controller := container.daemon.netController
  693. if container.Config.NetworkDisabled || mode.IsContainer() {
  694. return nil
  695. }
  696. networkDriver := string(mode)
  697. service := container.Config.PublishService
  698. networkName := mode.NetworkName()
  699. if mode.IsDefault() {
  700. if service != "" {
  701. service, networkName, networkDriver = parseService(controller, service)
  702. } else {
  703. networkName = controller.Config().Daemon.DefaultNetwork
  704. networkDriver = controller.Config().Daemon.DefaultDriver
  705. }
  706. } else if service != "" {
  707. return fmt.Errorf("conflicting options: publishing a service and network mode")
  708. }
  709. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.configStore.DisableBridge {
  710. container.Config.NetworkDisabled = true
  711. return nil
  712. }
  713. if service == "" {
  714. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  715. // For backward compatibility, replacing "." with "-", instead of failing
  716. service = strings.Replace(container.Name, ".", "-", -1)
  717. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  718. service = strings.Replace(service, "/", "", -1)
  719. }
  720. if container.secondaryNetworkRequired(networkDriver) {
  721. // Configure Bridge as secondary network for port binding purposes
  722. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  723. return err
  724. }
  725. }
  726. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  727. return err
  728. }
  729. return container.writeHostConfig()
  730. }
  731. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  732. controller := container.daemon.netController
  733. n, err := controller.NetworkByName(networkName)
  734. if err != nil {
  735. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  736. return err
  737. }
  738. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  739. return err
  740. }
  741. }
  742. ep, err := n.EndpointByName(service)
  743. if err != nil {
  744. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  745. return err
  746. }
  747. createOptions, err := container.buildCreateEndpointOptions()
  748. if err != nil {
  749. return err
  750. }
  751. ep, err = n.CreateEndpoint(service, createOptions...)
  752. if err != nil {
  753. return err
  754. }
  755. }
  756. if err := container.updateNetworkSettings(n, ep); err != nil {
  757. return err
  758. }
  759. joinOptions, err := container.buildJoinOptions()
  760. if err != nil {
  761. return err
  762. }
  763. if err := ep.Join(container.ID, joinOptions...); err != nil {
  764. return err
  765. }
  766. if err := container.updateJoinInfo(ep); err != nil {
  767. return fmt.Errorf("Updating join info failed: %v", err)
  768. }
  769. return nil
  770. }
  771. func (container *Container) initializeNetworking() error {
  772. var err error
  773. if container.hostConfig.NetworkMode.IsContainer() {
  774. // we need to get the hosts files from the container to join
  775. nc, err := container.getNetworkedContainer()
  776. if err != nil {
  777. return err
  778. }
  779. container.HostnamePath = nc.HostnamePath
  780. container.HostsPath = nc.HostsPath
  781. container.ResolvConfPath = nc.ResolvConfPath
  782. container.Config.Hostname = nc.Config.Hostname
  783. container.Config.Domainname = nc.Config.Domainname
  784. return nil
  785. }
  786. if container.hostConfig.NetworkMode.IsHost() {
  787. container.Config.Hostname, err = os.Hostname()
  788. if err != nil {
  789. return err
  790. }
  791. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  792. if len(parts) > 1 {
  793. container.Config.Hostname = parts[0]
  794. container.Config.Domainname = parts[1]
  795. }
  796. }
  797. if err := container.allocateNetwork(); err != nil {
  798. return err
  799. }
  800. return container.buildHostnameFile()
  801. }
  802. func (container *Container) getIpcContainer() (*Container, error) {
  803. containerID := container.hostConfig.IpcMode.Container()
  804. c, err := container.daemon.Get(containerID)
  805. if err != nil {
  806. return nil, err
  807. }
  808. if !c.IsRunning() {
  809. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  810. }
  811. return c, nil
  812. }
  813. func (container *Container) setupWorkingDirectory() error {
  814. if container.Config.WorkingDir != "" {
  815. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  816. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  817. if err != nil {
  818. return err
  819. }
  820. pthInfo, err := os.Stat(pth)
  821. if err != nil {
  822. if !os.IsNotExist(err) {
  823. return err
  824. }
  825. if err := system.MkdirAll(pth, 0755); err != nil {
  826. return err
  827. }
  828. }
  829. if pthInfo != nil && !pthInfo.IsDir() {
  830. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  831. }
  832. }
  833. return nil
  834. }
  835. func (container *Container) getNetworkedContainer() (*Container, error) {
  836. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  837. switch parts[0] {
  838. case "container":
  839. if len(parts) != 2 {
  840. return nil, fmt.Errorf("no container specified to join network")
  841. }
  842. nc, err := container.daemon.Get(parts[1])
  843. if err != nil {
  844. return nil, err
  845. }
  846. if container == nc {
  847. return nil, fmt.Errorf("cannot join own network")
  848. }
  849. if !nc.IsRunning() {
  850. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  851. }
  852. return nc, nil
  853. default:
  854. return nil, fmt.Errorf("network mode not set to container")
  855. }
  856. }
  857. func (container *Container) releaseNetwork() {
  858. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  859. return
  860. }
  861. eid := container.NetworkSettings.EndpointID
  862. nid := container.NetworkSettings.NetworkID
  863. container.NetworkSettings = &network.Settings{}
  864. if nid == "" || eid == "" {
  865. return
  866. }
  867. n, err := container.daemon.netController.NetworkByID(nid)
  868. if err != nil {
  869. logrus.Errorf("error locating network id %s: %v", nid, err)
  870. return
  871. }
  872. ep, err := n.EndpointByID(eid)
  873. if err != nil {
  874. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  875. return
  876. }
  877. switch {
  878. case container.hostConfig.NetworkMode.IsHost():
  879. if err := ep.Leave(container.ID); err != nil {
  880. logrus.Errorf("Error leaving endpoint id %s for container %s: %v", eid, container.ID, err)
  881. return
  882. }
  883. default:
  884. if err := container.daemon.netController.LeaveAll(container.ID); err != nil {
  885. logrus.Errorf("Leave all failed for %s: %v", container.ID, err)
  886. return
  887. }
  888. }
  889. // In addition to leaving all endpoints, delete implicitly created endpoint
  890. if container.Config.PublishService == "" {
  891. if err := ep.Delete(); err != nil {
  892. logrus.Errorf("deleting endpoint failed: %v", err)
  893. }
  894. }
  895. }
  896. func (container *Container) unmountVolumes(forceSyscall bool) error {
  897. var volumeMounts []mountPoint
  898. for _, mntPoint := range container.MountPoints {
  899. dest, err := container.GetResourcePath(mntPoint.Destination)
  900. if err != nil {
  901. return err
  902. }
  903. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  904. }
  905. for _, mnt := range container.networkMounts() {
  906. dest, err := container.GetResourcePath(mnt.Destination)
  907. if err != nil {
  908. return err
  909. }
  910. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  911. }
  912. for _, volumeMount := range volumeMounts {
  913. if forceSyscall {
  914. syscall.Unmount(volumeMount.Destination, 0)
  915. }
  916. if volumeMount.Volume != nil {
  917. if err := volumeMount.Volume.Unmount(); err != nil {
  918. return err
  919. }
  920. }
  921. }
  922. return nil
  923. }
  924. func (container *Container) networkMounts() []execdriver.Mount {
  925. var mounts []execdriver.Mount
  926. mode := "Z"
  927. if container.hostConfig.NetworkMode.IsContainer() {
  928. mode = "z"
  929. }
  930. if container.ResolvConfPath != "" {
  931. label.Relabel(container.ResolvConfPath, container.MountLabel, mode)
  932. writable := !container.hostConfig.ReadonlyRootfs
  933. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  934. writable = m.RW
  935. }
  936. mounts = append(mounts, execdriver.Mount{
  937. Source: container.ResolvConfPath,
  938. Destination: "/etc/resolv.conf",
  939. Writable: writable,
  940. Private: true,
  941. })
  942. }
  943. if container.HostnamePath != "" {
  944. label.Relabel(container.HostnamePath, container.MountLabel, mode)
  945. writable := !container.hostConfig.ReadonlyRootfs
  946. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  947. writable = m.RW
  948. }
  949. mounts = append(mounts, execdriver.Mount{
  950. Source: container.HostnamePath,
  951. Destination: "/etc/hostname",
  952. Writable: writable,
  953. Private: true,
  954. })
  955. }
  956. if container.HostsPath != "" {
  957. label.Relabel(container.HostsPath, container.MountLabel, mode)
  958. writable := !container.hostConfig.ReadonlyRootfs
  959. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  960. writable = m.RW
  961. }
  962. mounts = append(mounts, execdriver.Mount{
  963. Source: container.HostsPath,
  964. Destination: "/etc/hosts",
  965. Writable: writable,
  966. Private: true,
  967. })
  968. }
  969. return mounts
  970. }
  971. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  972. container.MountPoints[destination] = &mountPoint{
  973. Name: name,
  974. Source: source,
  975. Destination: destination,
  976. RW: rw,
  977. }
  978. }
  979. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  980. container.MountPoints[destination] = &mountPoint{
  981. Name: name,
  982. Driver: volume.DefaultDriverName,
  983. Destination: destination,
  984. RW: rw,
  985. }
  986. }
  987. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  988. container.MountPoints[destination] = &mountPoint{
  989. Name: vol.Name(),
  990. Driver: vol.DriverName(),
  991. Destination: destination,
  992. RW: rw,
  993. Volume: vol,
  994. }
  995. }
  996. func (container *Container) isDestinationMounted(destination string) bool {
  997. return container.MountPoints[destination] != nil
  998. }
  999. func (container *Container) prepareMountPoints() error {
  1000. for _, config := range container.MountPoints {
  1001. if len(config.Driver) > 0 {
  1002. v, err := container.daemon.createVolume(config.Name, config.Driver, nil)
  1003. if err != nil {
  1004. return err
  1005. }
  1006. config.Volume = v
  1007. }
  1008. }
  1009. return nil
  1010. }
  1011. func (container *Container) removeMountPoints(rm bool) error {
  1012. var rmErrors []string
  1013. for _, m := range container.MountPoints {
  1014. if m.Volume == nil {
  1015. continue
  1016. }
  1017. container.daemon.volumes.Decrement(m.Volume)
  1018. if rm {
  1019. if err := container.daemon.volumes.Remove(m.Volume); err != nil {
  1020. rmErrors = append(rmErrors, fmt.Sprintf("%v\n", err))
  1021. continue
  1022. }
  1023. }
  1024. }
  1025. if len(rmErrors) > 0 {
  1026. return fmt.Errorf("Error removing volumes:\n%v", rmErrors)
  1027. }
  1028. return nil
  1029. }