container_unix.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. // +build linux freebsd
  2. package container
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/daemon/execdriver"
  15. derr "github.com/docker/docker/errors"
  16. "github.com/docker/docker/pkg/chrootarchive"
  17. "github.com/docker/docker/pkg/symlink"
  18. "github.com/docker/docker/pkg/system"
  19. "github.com/docker/docker/utils"
  20. "github.com/docker/docker/volume"
  21. "github.com/docker/go-connections/nat"
  22. "github.com/docker/libnetwork"
  23. "github.com/docker/libnetwork/netlabel"
  24. "github.com/docker/libnetwork/options"
  25. "github.com/docker/libnetwork/types"
  26. "github.com/opencontainers/runc/libcontainer/label"
  27. )
  28. // DefaultSHMSize is the default size (64MB) of the SHM which will be mounted in the container
  29. const DefaultSHMSize int64 = 67108864
  30. // Container holds the fields specific to unixen implementations. See
  31. // CommonContainer for standard fields common to all containers.
  32. type Container struct {
  33. CommonContainer
  34. // Fields below here are platform specific.
  35. AppArmorProfile string
  36. HostnamePath string
  37. HostsPath string
  38. ShmPath string
  39. MqueuePath string
  40. ResolvConfPath string
  41. SeccompProfile string
  42. }
  43. // CreateDaemonEnvironment returns the list of all environment variables given the list of
  44. // environment variables related to links.
  45. // Sets PATH, HOSTNAME and if container.Config.Tty is set: TERM.
  46. // The defaults set here do not override the values in container.Config.Env
  47. func (container *Container) CreateDaemonEnvironment(linkedEnv []string) []string {
  48. // if a domain name was specified, append it to the hostname (see #7851)
  49. fullHostname := container.Config.Hostname
  50. if container.Config.Domainname != "" {
  51. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  52. }
  53. // Setup environment
  54. env := []string{
  55. "PATH=" + system.DefaultPathEnv,
  56. "HOSTNAME=" + fullHostname,
  57. // Note: we don't set HOME here because it'll get autoset intelligently
  58. // based on the value of USER inside dockerinit, but only if it isn't
  59. // set already (ie, that can be overridden by setting HOME via -e or ENV
  60. // in a Dockerfile).
  61. }
  62. if container.Config.Tty {
  63. env = append(env, "TERM=xterm")
  64. }
  65. env = append(env, linkedEnv...)
  66. // because the env on the container can override certain default values
  67. // we need to replace the 'env' keys where they match and append anything
  68. // else.
  69. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  70. return env
  71. }
  72. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  73. // the path to use for it; return true if the given destination was a network mount file
  74. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  75. if destination == "/etc/resolv.conf" {
  76. container.ResolvConfPath = path
  77. return true
  78. }
  79. if destination == "/etc/hostname" {
  80. container.HostnamePath = path
  81. return true
  82. }
  83. if destination == "/etc/hosts" {
  84. container.HostsPath = path
  85. return true
  86. }
  87. return false
  88. }
  89. // BuildHostnameFile writes the container's hostname file.
  90. func (container *Container) BuildHostnameFile() error {
  91. hostnamePath, err := container.GetRootResourcePath("hostname")
  92. if err != nil {
  93. return err
  94. }
  95. container.HostnamePath = hostnamePath
  96. if container.Config.Domainname != "" {
  97. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  98. }
  99. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  100. }
  101. // GetEndpointInNetwork returns the container's endpoint to the provided network.
  102. func (container *Container) GetEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
  103. endpointName := strings.TrimPrefix(container.Name, "/")
  104. return n.EndpointByName(endpointName)
  105. }
  106. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint) error {
  107. if ep == nil {
  108. return derr.ErrorCodeEmptyEndpoint
  109. }
  110. networkSettings := container.NetworkSettings
  111. if networkSettings == nil {
  112. return derr.ErrorCodeEmptyNetwork
  113. }
  114. driverInfo, err := ep.DriverInfo()
  115. if err != nil {
  116. return err
  117. }
  118. if driverInfo == nil {
  119. // It is not an error for epInfo to be nil
  120. return nil
  121. }
  122. if networkSettings.Ports == nil {
  123. networkSettings.Ports = nat.PortMap{}
  124. }
  125. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  126. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  127. for _, tp := range exposedPorts {
  128. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  129. if err != nil {
  130. return derr.ErrorCodeParsingPort.WithArgs(tp.Port, err)
  131. }
  132. networkSettings.Ports[natPort] = nil
  133. }
  134. }
  135. }
  136. mapData, ok := driverInfo[netlabel.PortMap]
  137. if !ok {
  138. return nil
  139. }
  140. if portMapping, ok := mapData.([]types.PortBinding); ok {
  141. for _, pp := range portMapping {
  142. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  143. if err != nil {
  144. return err
  145. }
  146. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  147. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  148. }
  149. }
  150. return nil
  151. }
  152. // BuildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
  153. func (container *Container) BuildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  154. if ep == nil {
  155. return derr.ErrorCodeEmptyEndpoint
  156. }
  157. networkSettings := container.NetworkSettings
  158. if networkSettings == nil {
  159. return derr.ErrorCodeEmptyNetwork
  160. }
  161. epInfo := ep.Info()
  162. if epInfo == nil {
  163. // It is not an error to get an empty endpoint info
  164. return nil
  165. }
  166. if _, ok := networkSettings.Networks[n.Name()]; !ok {
  167. networkSettings.Networks[n.Name()] = new(network.EndpointSettings)
  168. }
  169. networkSettings.Networks[n.Name()].EndpointID = ep.ID()
  170. iface := epInfo.Iface()
  171. if iface == nil {
  172. return nil
  173. }
  174. if iface.MacAddress() != nil {
  175. networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String()
  176. }
  177. if iface.Address() != nil {
  178. ones, _ := iface.Address().Mask.Size()
  179. networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
  180. networkSettings.Networks[n.Name()].IPPrefixLen = ones
  181. }
  182. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  183. onesv6, _ := iface.AddressIPv6().Mask.Size()
  184. networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
  185. networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
  186. }
  187. return nil
  188. }
  189. // UpdateJoinInfo updates network settings when container joins network n with endpoint ep.
  190. func (container *Container) UpdateJoinInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  191. if err := container.buildPortMapInfo(ep); err != nil {
  192. return err
  193. }
  194. epInfo := ep.Info()
  195. if epInfo == nil {
  196. // It is not an error to get an empty endpoint info
  197. return nil
  198. }
  199. if epInfo.Gateway() != nil {
  200. container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  201. }
  202. if epInfo.GatewayIPv6().To16() != nil {
  203. container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  204. }
  205. return nil
  206. }
  207. // UpdateSandboxNetworkSettings updates the sandbox ID and Key.
  208. func (container *Container) UpdateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  209. container.NetworkSettings.SandboxID = sb.ID()
  210. container.NetworkSettings.SandboxKey = sb.Key()
  211. return nil
  212. }
  213. // BuildCreateEndpointOptions builds endpoint options from a given network.
  214. func (container *Container) BuildCreateEndpointOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
  215. var (
  216. portSpecs = make(nat.PortSet)
  217. bindings = make(nat.PortMap)
  218. pbList []types.PortBinding
  219. exposeList []types.TransportPort
  220. createOptions []libnetwork.EndpointOption
  221. )
  222. if n.Name() == "bridge" || container.NetworkSettings.IsAnonymousEndpoint {
  223. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  224. }
  225. // Other configs are applicable only for the endpoint in the network
  226. // to which container was connected to on docker run.
  227. if n.Name() != container.HostConfig.NetworkMode.NetworkName() &&
  228. !(n.Name() == "bridge" && container.HostConfig.NetworkMode.IsDefault()) {
  229. return createOptions, nil
  230. }
  231. if container.Config.ExposedPorts != nil {
  232. portSpecs = container.Config.ExposedPorts
  233. }
  234. if container.HostConfig.PortBindings != nil {
  235. for p, b := range container.HostConfig.PortBindings {
  236. bindings[p] = []nat.PortBinding{}
  237. for _, bb := range b {
  238. bindings[p] = append(bindings[p], nat.PortBinding{
  239. HostIP: bb.HostIP,
  240. HostPort: bb.HostPort,
  241. })
  242. }
  243. }
  244. }
  245. ports := make([]nat.Port, len(portSpecs))
  246. var i int
  247. for p := range portSpecs {
  248. ports[i] = p
  249. i++
  250. }
  251. nat.SortPortMap(ports, bindings)
  252. for _, port := range ports {
  253. expose := types.TransportPort{}
  254. expose.Proto = types.ParseProtocol(port.Proto())
  255. expose.Port = uint16(port.Int())
  256. exposeList = append(exposeList, expose)
  257. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  258. binding := bindings[port]
  259. for i := 0; i < len(binding); i++ {
  260. pbCopy := pb.GetCopy()
  261. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  262. var portStart, portEnd int
  263. if err == nil {
  264. portStart, portEnd, err = newP.Range()
  265. }
  266. if err != nil {
  267. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  268. }
  269. pbCopy.HostPort = uint16(portStart)
  270. pbCopy.HostPortEnd = uint16(portEnd)
  271. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  272. pbList = append(pbList, pbCopy)
  273. }
  274. if container.HostConfig.PublishAllPorts && len(binding) == 0 {
  275. pbList = append(pbList, pb)
  276. }
  277. }
  278. createOptions = append(createOptions,
  279. libnetwork.CreateOptionPortMapping(pbList),
  280. libnetwork.CreateOptionExposedPorts(exposeList))
  281. if container.Config.MacAddress != "" {
  282. mac, err := net.ParseMAC(container.Config.MacAddress)
  283. if err != nil {
  284. return nil, err
  285. }
  286. genericOption := options.Generic{
  287. netlabel.MacAddress: mac,
  288. }
  289. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  290. }
  291. return createOptions, nil
  292. }
  293. // SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir
  294. func (container *Container) SetupWorkingDirectory() error {
  295. if container.Config.WorkingDir == "" {
  296. return nil
  297. }
  298. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  299. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  300. if err != nil {
  301. return err
  302. }
  303. pthInfo, err := os.Stat(pth)
  304. if err != nil {
  305. if !os.IsNotExist(err) {
  306. return err
  307. }
  308. if err := system.MkdirAll(pth, 0755); err != nil {
  309. return err
  310. }
  311. }
  312. if pthInfo != nil && !pthInfo.IsDir() {
  313. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  314. }
  315. return nil
  316. }
  317. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  318. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  319. for _, mnt := range container.NetworkMounts() {
  320. dest, err := container.GetResourcePath(mnt.Destination)
  321. if err != nil {
  322. return nil, err
  323. }
  324. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  325. }
  326. return volumeMounts, nil
  327. }
  328. // NetworkMounts returns the list of network mounts.
  329. func (container *Container) NetworkMounts() []execdriver.Mount {
  330. var mounts []execdriver.Mount
  331. shared := container.HostConfig.NetworkMode.IsContainer()
  332. if container.ResolvConfPath != "" {
  333. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  334. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  335. } else {
  336. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  337. writable := !container.HostConfig.ReadonlyRootfs
  338. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  339. writable = m.RW
  340. }
  341. mounts = append(mounts, execdriver.Mount{
  342. Source: container.ResolvConfPath,
  343. Destination: "/etc/resolv.conf",
  344. Writable: writable,
  345. Propagation: volume.DefaultPropagationMode,
  346. })
  347. }
  348. }
  349. if container.HostnamePath != "" {
  350. if _, err := os.Stat(container.HostnamePath); err != nil {
  351. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  352. } else {
  353. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  354. writable := !container.HostConfig.ReadonlyRootfs
  355. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  356. writable = m.RW
  357. }
  358. mounts = append(mounts, execdriver.Mount{
  359. Source: container.HostnamePath,
  360. Destination: "/etc/hostname",
  361. Writable: writable,
  362. Propagation: volume.DefaultPropagationMode,
  363. })
  364. }
  365. }
  366. if container.HostsPath != "" {
  367. if _, err := os.Stat(container.HostsPath); err != nil {
  368. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  369. } else {
  370. label.Relabel(container.HostsPath, container.MountLabel, shared)
  371. writable := !container.HostConfig.ReadonlyRootfs
  372. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  373. writable = m.RW
  374. }
  375. mounts = append(mounts, execdriver.Mount{
  376. Source: container.HostsPath,
  377. Destination: "/etc/hosts",
  378. Writable: writable,
  379. Propagation: volume.DefaultPropagationMode,
  380. })
  381. }
  382. }
  383. return mounts
  384. }
  385. // CopyImagePathContent copies files in destination to the volume.
  386. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  387. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  388. if err != nil {
  389. return err
  390. }
  391. if _, err = ioutil.ReadDir(rootfs); err != nil {
  392. if os.IsNotExist(err) {
  393. return nil
  394. }
  395. return err
  396. }
  397. path, err := v.Mount()
  398. if err != nil {
  399. return err
  400. }
  401. if err := copyExistingContents(rootfs, path); err != nil {
  402. return err
  403. }
  404. return v.Unmount()
  405. }
  406. // ShmResourcePath returns path to shm
  407. func (container *Container) ShmResourcePath() (string, error) {
  408. return container.GetRootResourcePath("shm")
  409. }
  410. // MqueueResourcePath returns path to mqueue
  411. func (container *Container) MqueueResourcePath() (string, error) {
  412. return container.GetRootResourcePath("mqueue")
  413. }
  414. // HasMountFor checks if path is a mountpoint
  415. func (container *Container) HasMountFor(path string) bool {
  416. _, exists := container.MountPoints[path]
  417. return exists
  418. }
  419. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  420. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  421. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  422. return
  423. }
  424. var warnings []string
  425. if !container.HasMountFor("/dev/shm") {
  426. shmPath, err := container.ShmResourcePath()
  427. if err != nil {
  428. logrus.Error(err)
  429. warnings = append(warnings, err.Error())
  430. } else if shmPath != "" {
  431. if err := unmount(shmPath); err != nil {
  432. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  433. }
  434. }
  435. }
  436. if !container.HasMountFor("/dev/mqueue") {
  437. mqueuePath, err := container.MqueueResourcePath()
  438. if err != nil {
  439. logrus.Error(err)
  440. warnings = append(warnings, err.Error())
  441. } else if mqueuePath != "" {
  442. if err := unmount(mqueuePath); err != nil {
  443. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", mqueuePath, err))
  444. }
  445. }
  446. }
  447. if len(warnings) > 0 {
  448. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  449. }
  450. }
  451. // IpcMounts returns the list of IPC mounts
  452. func (container *Container) IpcMounts() []execdriver.Mount {
  453. var mounts []execdriver.Mount
  454. if !container.HasMountFor("/dev/shm") {
  455. label.SetFileLabel(container.ShmPath, container.MountLabel)
  456. mounts = append(mounts, execdriver.Mount{
  457. Source: container.ShmPath,
  458. Destination: "/dev/shm",
  459. Writable: true,
  460. Propagation: volume.DefaultPropagationMode,
  461. })
  462. }
  463. if !container.HasMountFor("/dev/mqueue") {
  464. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  465. mounts = append(mounts, execdriver.Mount{
  466. Source: container.MqueuePath,
  467. Destination: "/dev/mqueue",
  468. Writable: true,
  469. Propagation: volume.DefaultPropagationMode,
  470. })
  471. }
  472. return mounts
  473. }
  474. func detachMounted(path string) error {
  475. return syscall.Unmount(path, syscall.MNT_DETACH)
  476. }
  477. // UnmountVolumes unmounts all volumes
  478. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  479. var (
  480. volumeMounts []volume.MountPoint
  481. err error
  482. )
  483. for _, mntPoint := range container.MountPoints {
  484. dest, err := container.GetResourcePath(mntPoint.Destination)
  485. if err != nil {
  486. return err
  487. }
  488. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume})
  489. }
  490. // Append any network mounts to the list (this is a no-op on Windows)
  491. if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
  492. return err
  493. }
  494. for _, volumeMount := range volumeMounts {
  495. if forceSyscall {
  496. if err := detachMounted(volumeMount.Destination); err != nil {
  497. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
  498. }
  499. }
  500. if volumeMount.Volume != nil {
  501. if err := volumeMount.Volume.Unmount(); err != nil {
  502. return err
  503. }
  504. }
  505. }
  506. return nil
  507. }
  508. // copyExistingContents copies from the source to the destination and
  509. // ensures the ownership is appropriately set.
  510. func copyExistingContents(source, destination string) error {
  511. volList, err := ioutil.ReadDir(source)
  512. if err != nil {
  513. return err
  514. }
  515. if len(volList) > 0 {
  516. srcList, err := ioutil.ReadDir(destination)
  517. if err != nil {
  518. return err
  519. }
  520. if len(srcList) == 0 {
  521. // If the source volume is empty copy files from the root into the volume
  522. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  523. return err
  524. }
  525. }
  526. }
  527. return copyOwnership(source, destination)
  528. }
  529. // copyOwnership copies the permissions and uid:gid of the source file
  530. // to the destination file
  531. func copyOwnership(source, destination string) error {
  532. stat, err := system.Stat(source)
  533. if err != nil {
  534. return err
  535. }
  536. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  537. return err
  538. }
  539. return os.Chmod(destination, os.FileMode(stat.Mode()))
  540. }
  541. // TmpfsMounts returns the list of tmpfs mounts
  542. func (container *Container) TmpfsMounts() []execdriver.Mount {
  543. var mounts []execdriver.Mount
  544. for dest, data := range container.HostConfig.Tmpfs {
  545. mounts = append(mounts, execdriver.Mount{
  546. Source: "tmpfs",
  547. Destination: dest,
  548. Data: data,
  549. })
  550. }
  551. return mounts
  552. }