container_unix.go 34 KB

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