container_unix.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/daemon/links"
  17. "github.com/docker/docker/daemon/network"
  18. "github.com/docker/docker/pkg/directory"
  19. "github.com/docker/docker/pkg/nat"
  20. "github.com/docker/docker/pkg/stringid"
  21. "github.com/docker/docker/pkg/system"
  22. "github.com/docker/docker/pkg/ulimit"
  23. "github.com/docker/docker/runconfig"
  24. "github.com/docker/docker/utils"
  25. "github.com/docker/docker/volume"
  26. "github.com/docker/libnetwork"
  27. "github.com/docker/libnetwork/netlabel"
  28. "github.com/docker/libnetwork/options"
  29. "github.com/docker/libnetwork/types"
  30. "github.com/opencontainers/runc/libcontainer/configs"
  31. "github.com/opencontainers/runc/libcontainer/devices"
  32. "github.com/opencontainers/runc/libcontainer/label"
  33. )
  34. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  35. type Container struct {
  36. CommonContainer
  37. // Fields below here are platform specific.
  38. activeLinks map[string]*links.Link
  39. AppArmorProfile string
  40. HostnamePath string
  41. HostsPath string
  42. ShmPath string
  43. MqueuePath 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. 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 := links.NewLink(
  80. container.NetworkSettings.IPAddress,
  81. child.NetworkSettings.IPAddress,
  82. linkAlias,
  83. child.Config.Env,
  84. child.Config.ExposedPorts,
  85. )
  86. for _, envVar := range link.ToEnv() {
  87. env = append(env, envVar)
  88. }
  89. }
  90. }
  91. return env, nil
  92. }
  93. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  94. // if a domain name was specified, append it to the hostname (see #7851)
  95. fullHostname := container.Config.Hostname
  96. if container.Config.Domainname != "" {
  97. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  98. }
  99. // Setup environment
  100. env := []string{
  101. "PATH=" + DefaultPathEnv,
  102. "HOSTNAME=" + fullHostname,
  103. // Note: we don't set HOME here because it'll get autoset intelligently
  104. // based on the value of USER inside dockerinit, but only if it isn't
  105. // set already (ie, that can be overridden by setting HOME via -e or ENV
  106. // in a Dockerfile).
  107. }
  108. if container.Config.Tty {
  109. env = append(env, "TERM=xterm")
  110. }
  111. env = append(env, linkedEnv...)
  112. // because the env on the container can override certain default values
  113. // we need to replace the 'env' keys where they match and append anything
  114. // else.
  115. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  116. return env
  117. }
  118. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  119. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  120. // if there was no error, return the device
  121. if err == nil {
  122. device.Path = deviceMapping.PathInContainer
  123. return append(devs, device), nil
  124. }
  125. // if the device is not a device node
  126. // try to see if it's a directory holding many devices
  127. if err == devices.ErrNotADevice {
  128. // check if it is a directory
  129. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  130. // mount the internal devices recursively
  131. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  132. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  133. if e != nil {
  134. // ignore the device
  135. return nil
  136. }
  137. // add the device to userSpecified devices
  138. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  139. devs = append(devs, childDevice)
  140. return nil
  141. })
  142. }
  143. }
  144. if len(devs) > 0 {
  145. return devs, nil
  146. }
  147. return devs, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  148. }
  149. func populateCommand(c *Container, env []string) error {
  150. var en *execdriver.Network
  151. if !c.Config.NetworkDisabled {
  152. en = &execdriver.Network{
  153. NamespacePath: c.NetworkSettings.SandboxKey,
  154. }
  155. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  156. if parts[0] == "container" {
  157. nc, err := c.getNetworkedContainer()
  158. if err != nil {
  159. return err
  160. }
  161. en.ContainerID = nc.ID
  162. }
  163. }
  164. ipc := &execdriver.Ipc{}
  165. var err error
  166. c.ShmPath, err = c.shmPath()
  167. if err != nil {
  168. return err
  169. }
  170. c.MqueuePath, err = c.mqueuePath()
  171. if err != nil {
  172. return err
  173. }
  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. c.ShmPath = ic.ShmPath
  181. c.MqueuePath = ic.MqueuePath
  182. } else {
  183. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  184. if ipc.HostIpc {
  185. c.ShmPath = "/dev/shm"
  186. c.MqueuePath = "/dev/mqueue"
  187. }
  188. }
  189. pid := &execdriver.Pid{}
  190. pid.HostPid = c.hostConfig.PidMode.IsHost()
  191. uts := &execdriver.UTS{
  192. HostUTS: c.hostConfig.UTSMode.IsHost(),
  193. }
  194. // Build lists of devices allowed and created within the container.
  195. var userSpecifiedDevices []*configs.Device
  196. for _, deviceMapping := range c.hostConfig.Devices {
  197. devs, err := getDevicesFromPath(deviceMapping)
  198. if err != nil {
  199. return err
  200. }
  201. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  202. }
  203. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  204. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  205. // TODO: this can be removed after lxc-conf is fully deprecated
  206. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  207. if err != nil {
  208. return err
  209. }
  210. var rlimits []*ulimit.Rlimit
  211. ulimits := c.hostConfig.Ulimits
  212. // Merge ulimits with daemon defaults
  213. ulIdx := make(map[string]*ulimit.Ulimit)
  214. for _, ul := range ulimits {
  215. ulIdx[ul.Name] = ul
  216. }
  217. for name, ul := range c.daemon.config.Ulimits {
  218. if _, exists := ulIdx[name]; !exists {
  219. ulimits = append(ulimits, ul)
  220. }
  221. }
  222. for _, limit := range ulimits {
  223. rl, err := limit.GetRlimit()
  224. if err != nil {
  225. return err
  226. }
  227. rlimits = append(rlimits, rl)
  228. }
  229. resources := &execdriver.Resources{
  230. Memory: c.hostConfig.Memory,
  231. MemorySwap: c.hostConfig.MemorySwap,
  232. CPUShares: c.hostConfig.CPUShares,
  233. CpusetCpus: c.hostConfig.CpusetCpus,
  234. CpusetMems: c.hostConfig.CpusetMems,
  235. CPUPeriod: c.hostConfig.CPUPeriod,
  236. CPUQuota: c.hostConfig.CPUQuota,
  237. BlkioWeight: c.hostConfig.BlkioWeight,
  238. Rlimits: rlimits,
  239. OomKillDisable: c.hostConfig.OomKillDisable,
  240. MemorySwappiness: -1,
  241. }
  242. if c.hostConfig.MemorySwappiness != nil {
  243. resources.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. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  565. // get removed/unlinked).
  566. func (container *Container) UpdateNetwork() error {
  567. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  568. if err != nil {
  569. return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  570. }
  571. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  572. if err != nil {
  573. return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  574. }
  575. if err := ep.Leave(container.ID); err != nil {
  576. return fmt.Errorf("endpoint leave failed: %v", err)
  577. }
  578. joinOptions, err := container.buildJoinOptions()
  579. if err != nil {
  580. return fmt.Errorf("Update network failed: %v", err)
  581. }
  582. if err := ep.Join(container.ID, joinOptions...); err != nil {
  583. return fmt.Errorf("endpoint join failed: %v", err)
  584. }
  585. if err := container.updateJoinInfo(ep); err != nil {
  586. return fmt.Errorf("Updating join info failed: %v", err)
  587. }
  588. return nil
  589. }
  590. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  591. var (
  592. portSpecs = make(nat.PortSet)
  593. bindings = make(nat.PortMap)
  594. pbList []types.PortBinding
  595. exposeList []types.TransportPort
  596. createOptions []libnetwork.EndpointOption
  597. )
  598. if container.Config.ExposedPorts != nil {
  599. portSpecs = container.Config.ExposedPorts
  600. }
  601. if container.hostConfig.PortBindings != nil {
  602. for p, b := range container.hostConfig.PortBindings {
  603. bindings[p] = []nat.PortBinding{}
  604. for _, bb := range b {
  605. bindings[p] = append(bindings[p], nat.PortBinding{
  606. HostIP: bb.HostIP,
  607. HostPort: bb.HostPort,
  608. })
  609. }
  610. }
  611. }
  612. container.NetworkSettings.PortMapping = nil
  613. ports := make([]nat.Port, len(portSpecs))
  614. var i int
  615. for p := range portSpecs {
  616. ports[i] = p
  617. i++
  618. }
  619. nat.SortPortMap(ports, bindings)
  620. for _, port := range ports {
  621. expose := types.TransportPort{}
  622. expose.Proto = types.ParseProtocol(port.Proto())
  623. expose.Port = uint16(port.Int())
  624. exposeList = append(exposeList, expose)
  625. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  626. binding := bindings[port]
  627. for i := 0; i < len(binding); i++ {
  628. pbCopy := pb.GetCopy()
  629. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  630. if err != nil {
  631. return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
  632. }
  633. pbCopy.HostPort = uint16(newP.Int())
  634. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  635. pbList = append(pbList, pbCopy)
  636. }
  637. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  638. pbList = append(pbList, pb)
  639. }
  640. }
  641. createOptions = append(createOptions,
  642. libnetwork.CreateOptionPortMapping(pbList),
  643. libnetwork.CreateOptionExposedPorts(exposeList))
  644. if container.Config.MacAddress != "" {
  645. mac, err := net.ParseMAC(container.Config.MacAddress)
  646. if err != nil {
  647. return nil, err
  648. }
  649. genericOption := options.Generic{
  650. netlabel.MacAddress: mac,
  651. }
  652. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  653. }
  654. return createOptions, nil
  655. }
  656. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  657. dn := controller.Config().Daemon.DefaultNetwork
  658. dd := controller.Config().Daemon.DefaultDriver
  659. snd := strings.Split(service, ".")
  660. if len(snd) > 2 {
  661. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  662. }
  663. if len(snd) > 1 {
  664. return snd[0], snd[1], dd
  665. }
  666. return snd[0], dn, dd
  667. }
  668. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  669. createOptions := []libnetwork.NetworkOption{}
  670. genericOption := options.Generic{}
  671. // Bridge driver is special due to legacy reasons
  672. if runconfig.NetworkMode(driver).IsBridge() {
  673. genericOption[netlabel.GenericData] = map[string]interface{}{
  674. "BridgeName": dnet,
  675. "AllowNonDefaultBridge": "true",
  676. }
  677. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  678. createOptions = append(createOptions, networkOption)
  679. }
  680. return controller.NewNetwork(driver, dnet, createOptions...)
  681. }
  682. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  683. switch primaryNetworkType {
  684. case "bridge", "none", "host", "container":
  685. return false
  686. }
  687. if container.daemon.config.DisableBridge {
  688. return false
  689. }
  690. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  691. return true
  692. }
  693. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  694. return true
  695. }
  696. return false
  697. }
  698. func (container *Container) AllocateNetwork() error {
  699. mode := container.hostConfig.NetworkMode
  700. controller := container.daemon.netController
  701. if container.Config.NetworkDisabled || mode.IsContainer() {
  702. return nil
  703. }
  704. networkDriver := string(mode)
  705. service := container.Config.PublishService
  706. networkName := mode.NetworkName()
  707. if mode.IsDefault() {
  708. if service != "" {
  709. service, networkName, networkDriver = parseService(controller, service)
  710. } else {
  711. networkName = controller.Config().Daemon.DefaultNetwork
  712. networkDriver = controller.Config().Daemon.DefaultDriver
  713. }
  714. } else if service != "" {
  715. return fmt.Errorf("conflicting options: publishing a service and network mode")
  716. }
  717. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.config.DisableBridge {
  718. container.Config.NetworkDisabled = true
  719. return nil
  720. }
  721. if service == "" {
  722. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  723. // For backward compatibility, replacing "." with "-", instead of failing
  724. service = strings.Replace(container.Name, ".", "-", -1)
  725. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  726. service = strings.Replace(service, "/", "", -1)
  727. }
  728. if container.secondaryNetworkRequired(networkDriver) {
  729. // Configure Bridge as secondary network for port binding purposes
  730. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  731. return err
  732. }
  733. }
  734. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  735. return err
  736. }
  737. return container.WriteHostConfig()
  738. }
  739. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  740. controller := container.daemon.netController
  741. n, err := controller.NetworkByName(networkName)
  742. if err != nil {
  743. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  744. return err
  745. }
  746. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  747. return err
  748. }
  749. }
  750. ep, err := n.EndpointByName(service)
  751. if err != nil {
  752. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  753. return err
  754. }
  755. createOptions, err := container.buildCreateEndpointOptions()
  756. if err != nil {
  757. return err
  758. }
  759. ep, err = n.CreateEndpoint(service, createOptions...)
  760. if err != nil {
  761. return err
  762. }
  763. }
  764. if err := container.updateNetworkSettings(n, ep); err != nil {
  765. return err
  766. }
  767. joinOptions, err := container.buildJoinOptions()
  768. if err != nil {
  769. return err
  770. }
  771. if err := ep.Join(container.ID, joinOptions...); err != nil {
  772. return err
  773. }
  774. if err := container.updateJoinInfo(ep); err != nil {
  775. return fmt.Errorf("Updating join info failed: %v", err)
  776. }
  777. return nil
  778. }
  779. func (container *Container) initializeNetworking() error {
  780. var err error
  781. if container.hostConfig.NetworkMode.IsContainer() {
  782. // we need to get the hosts files from the container to join
  783. nc, err := container.getNetworkedContainer()
  784. if err != nil {
  785. return err
  786. }
  787. container.HostnamePath = nc.HostnamePath
  788. container.HostsPath = nc.HostsPath
  789. container.ResolvConfPath = nc.ResolvConfPath
  790. container.Config.Hostname = nc.Config.Hostname
  791. container.Config.Domainname = nc.Config.Domainname
  792. return nil
  793. }
  794. if container.hostConfig.NetworkMode.IsHost() {
  795. container.Config.Hostname, err = os.Hostname()
  796. if err != nil {
  797. return err
  798. }
  799. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  800. if len(parts) > 1 {
  801. container.Config.Hostname = parts[0]
  802. container.Config.Domainname = parts[1]
  803. }
  804. }
  805. if err := container.AllocateNetwork(); err != nil {
  806. return err
  807. }
  808. return container.buildHostnameFile()
  809. }
  810. func (container *Container) getIpcContainer() (*Container, error) {
  811. containerID := container.hostConfig.IpcMode.Container()
  812. c, err := container.daemon.Get(containerID)
  813. if err != nil {
  814. return nil, err
  815. }
  816. if !c.IsRunning() {
  817. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  818. }
  819. return c, nil
  820. }
  821. func (container *Container) setupWorkingDirectory() error {
  822. if container.Config.WorkingDir != "" {
  823. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  824. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  825. if err != nil {
  826. return err
  827. }
  828. pthInfo, err := os.Stat(pth)
  829. if err != nil {
  830. if !os.IsNotExist(err) {
  831. return err
  832. }
  833. if err := system.MkdirAll(pth, 0755); err != nil {
  834. return err
  835. }
  836. }
  837. if pthInfo != nil && !pthInfo.IsDir() {
  838. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  839. }
  840. }
  841. return nil
  842. }
  843. func (container *Container) getNetworkedContainer() (*Container, error) {
  844. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  845. switch parts[0] {
  846. case "container":
  847. if len(parts) != 2 {
  848. return nil, fmt.Errorf("no container specified to join network")
  849. }
  850. nc, err := container.daemon.Get(parts[1])
  851. if err != nil {
  852. return nil, err
  853. }
  854. if container == nc {
  855. return nil, fmt.Errorf("cannot join own network")
  856. }
  857. if !nc.IsRunning() {
  858. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  859. }
  860. return nc, nil
  861. default:
  862. return nil, fmt.Errorf("network mode not set to container")
  863. }
  864. }
  865. func (container *Container) ReleaseNetwork() {
  866. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  867. return
  868. }
  869. eid := container.NetworkSettings.EndpointID
  870. nid := container.NetworkSettings.NetworkID
  871. container.NetworkSettings = &network.Settings{}
  872. if nid == "" || eid == "" {
  873. return
  874. }
  875. n, err := container.daemon.netController.NetworkByID(nid)
  876. if err != nil {
  877. logrus.Errorf("error locating network id %s: %v", nid, err)
  878. return
  879. }
  880. ep, err := n.EndpointByID(eid)
  881. if err != nil {
  882. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  883. return
  884. }
  885. switch {
  886. case container.hostConfig.NetworkMode.IsHost():
  887. if err := ep.Leave(container.ID); err != nil {
  888. logrus.Errorf("Error leaving endpoint id %s for container %s: %v", eid, container.ID, err)
  889. return
  890. }
  891. default:
  892. if err := container.daemon.netController.LeaveAll(container.ID); err != nil {
  893. logrus.Errorf("Leave all failed for %s: %v", container.ID, err)
  894. return
  895. }
  896. }
  897. // In addition to leaving all endpoints, delete implicitly created endpoint
  898. if container.Config.PublishService == "" {
  899. if err := ep.Delete(); err != nil {
  900. logrus.Errorf("deleting endpoint failed: %v", err)
  901. }
  902. }
  903. }
  904. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  905. var volumeMounts []mountPoint
  906. for _, mntPoint := range container.MountPoints {
  907. dest, err := container.GetResourcePath(mntPoint.Destination)
  908. if err != nil {
  909. return err
  910. }
  911. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  912. }
  913. for _, mnt := range container.networkMounts() {
  914. dest, err := container.GetResourcePath(mnt.Destination)
  915. if err != nil {
  916. return err
  917. }
  918. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  919. }
  920. for _, volumeMount := range volumeMounts {
  921. if forceSyscall {
  922. syscall.Unmount(volumeMount.Destination, 0)
  923. }
  924. if volumeMount.Volume != nil {
  925. if err := volumeMount.Volume.Unmount(); err != nil {
  926. return err
  927. }
  928. }
  929. }
  930. return nil
  931. }
  932. func (container *Container) networkMounts() []execdriver.Mount {
  933. var mounts []execdriver.Mount
  934. mode := "Z"
  935. if container.hostConfig.NetworkMode.IsContainer() {
  936. mode = "z"
  937. }
  938. if container.ResolvConfPath != "" {
  939. label.Relabel(container.ResolvConfPath, container.MountLabel, mode)
  940. writable := !container.hostConfig.ReadonlyRootfs
  941. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  942. writable = m.RW
  943. }
  944. mounts = append(mounts, execdriver.Mount{
  945. Source: container.ResolvConfPath,
  946. Destination: "/etc/resolv.conf",
  947. Writable: writable,
  948. Private: true,
  949. })
  950. }
  951. if container.HostnamePath != "" {
  952. label.Relabel(container.HostnamePath, container.MountLabel, mode)
  953. writable := !container.hostConfig.ReadonlyRootfs
  954. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  955. writable = m.RW
  956. }
  957. mounts = append(mounts, execdriver.Mount{
  958. Source: container.HostnamePath,
  959. Destination: "/etc/hostname",
  960. Writable: writable,
  961. Private: true,
  962. })
  963. }
  964. if container.HostsPath != "" {
  965. label.Relabel(container.HostsPath, container.MountLabel, mode)
  966. writable := !container.hostConfig.ReadonlyRootfs
  967. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  968. writable = m.RW
  969. }
  970. mounts = append(mounts, execdriver.Mount{
  971. Source: container.HostsPath,
  972. Destination: "/etc/hosts",
  973. Writable: writable,
  974. Private: true,
  975. })
  976. }
  977. return mounts
  978. }
  979. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  980. container.MountPoints[destination] = &mountPoint{
  981. Name: name,
  982. Source: source,
  983. Destination: destination,
  984. RW: rw,
  985. }
  986. }
  987. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  988. container.MountPoints[destination] = &mountPoint{
  989. Name: name,
  990. Driver: volume.DefaultDriverName,
  991. Destination: destination,
  992. RW: rw,
  993. }
  994. }
  995. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  996. container.MountPoints[destination] = &mountPoint{
  997. Name: vol.Name(),
  998. Driver: vol.DriverName(),
  999. Destination: destination,
  1000. RW: rw,
  1001. Volume: vol,
  1002. }
  1003. }
  1004. func (container *Container) isDestinationMounted(destination string) bool {
  1005. return container.MountPoints[destination] != nil
  1006. }
  1007. func (container *Container) prepareMountPoints() error {
  1008. for _, config := range container.MountPoints {
  1009. if len(config.Driver) > 0 {
  1010. v, err := createVolume(config.Name, config.Driver)
  1011. if err != nil {
  1012. return err
  1013. }
  1014. config.Volume = v
  1015. }
  1016. }
  1017. return nil
  1018. }
  1019. func (container *Container) removeMountPoints() error {
  1020. for _, m := range container.MountPoints {
  1021. if m.Volume != nil {
  1022. if err := removeVolume(m.Volume); err != nil {
  1023. return err
  1024. }
  1025. }
  1026. }
  1027. return nil
  1028. }
  1029. func (container *Container) shmPath() (string, error) {
  1030. return container.GetRootResourcePath("shm")
  1031. }
  1032. func (container *Container) mqueuePath() (string, error) {
  1033. return container.GetRootResourcePath("mqueue")
  1034. }
  1035. func (container *Container) setupIpcDirs() error {
  1036. shmPath, err := container.shmPath()
  1037. if err != nil {
  1038. return err
  1039. }
  1040. if err := os.MkdirAll(shmPath, 0700); err != nil {
  1041. return err
  1042. }
  1043. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel("mode=1777,size=65536k", container.GetMountLabel())); err != nil {
  1044. return fmt.Errorf("mounting shm tmpfs: %s", err)
  1045. }
  1046. mqueuePath, err := container.mqueuePath()
  1047. if err != nil {
  1048. return err
  1049. }
  1050. if err := os.MkdirAll(mqueuePath, 0700); err != nil {
  1051. return err
  1052. }
  1053. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  1054. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  1055. }
  1056. return nil
  1057. }
  1058. func (container *Container) unmountIpcMounts() error {
  1059. if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
  1060. return nil
  1061. }
  1062. shmPath, err := container.shmPath()
  1063. if err != nil {
  1064. return fmt.Errorf("shm path does not exist %v", err)
  1065. }
  1066. if err := syscall.Unmount(shmPath, syscall.MNT_DETACH); err != nil {
  1067. return fmt.Errorf("failed to umount %s filesystem %v", shmPath, err)
  1068. }
  1069. mqueuePath, err := container.mqueuePath()
  1070. if err != nil {
  1071. return fmt.Errorf("mqueue path does not exist %v", err)
  1072. }
  1073. if err := syscall.Unmount(mqueuePath, syscall.MNT_DETACH); err != nil {
  1074. return fmt.Errorf("failed to umount %s filesystem %v", mqueuePath, err)
  1075. }
  1076. return nil
  1077. }
  1078. func (container *Container) ipcMounts() []execdriver.Mount {
  1079. var mounts []execdriver.Mount
  1080. label.SetFileLabel(container.ShmPath, container.MountLabel)
  1081. mounts = append(mounts, execdriver.Mount{
  1082. Source: container.ShmPath,
  1083. Destination: "/dev/shm",
  1084. Writable: true,
  1085. Private: true,
  1086. })
  1087. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  1088. mounts = append(mounts, execdriver.Mount{
  1089. Source: container.MqueuePath,
  1090. Destination: "/dev/mqueue",
  1091. Writable: true,
  1092. Private: true,
  1093. })
  1094. return mounts
  1095. }