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