container_unix.go 35 KB

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