container_unix.go 34 KB

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