container_unix.go 36 KB

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