container_unix.go 35 KB

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