container_unix.go 31 KB

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