create.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. // +build linux,cgo
  2. package native
  3. import (
  4. "fmt"
  5. "path/filepath"
  6. "strings"
  7. "syscall"
  8. "github.com/docker/docker/daemon/execdriver"
  9. "github.com/docker/docker/pkg/mount"
  10. "github.com/docker/docker/profiles/seccomp"
  11. "github.com/docker/docker/volume"
  12. "github.com/opencontainers/runc/libcontainer/apparmor"
  13. "github.com/opencontainers/runc/libcontainer/configs"
  14. "github.com/opencontainers/runc/libcontainer/devices"
  15. )
  16. // createContainer populates and configures the container type with the
  17. // data provided by the execdriver.Command
  18. func (d *Driver) createContainer(c *execdriver.Command, hooks execdriver.Hooks) (container *configs.Config, err error) {
  19. container = execdriver.InitContainer(c)
  20. if err := d.createIpc(container, c); err != nil {
  21. return nil, err
  22. }
  23. if err := d.createPid(container, c); err != nil {
  24. return nil, err
  25. }
  26. if err := d.createUTS(container, c); err != nil {
  27. return nil, err
  28. }
  29. if err := d.setupRemappedRoot(container, c); err != nil {
  30. return nil, err
  31. }
  32. if err := d.createNetwork(container, c, hooks); err != nil {
  33. return nil, err
  34. }
  35. if c.ProcessConfig.Privileged {
  36. if !container.Readonlyfs {
  37. // clear readonly for /sys
  38. for i := range container.Mounts {
  39. if container.Mounts[i].Destination == "/sys" {
  40. container.Mounts[i].Flags &= ^syscall.MS_RDONLY
  41. }
  42. }
  43. container.ReadonlyPaths = nil
  44. }
  45. // clear readonly for cgroup
  46. for i := range container.Mounts {
  47. if container.Mounts[i].Device == "cgroup" {
  48. container.Mounts[i].Flags &= ^syscall.MS_RDONLY
  49. }
  50. }
  51. container.MaskPaths = nil
  52. if err := d.setPrivileged(container); err != nil {
  53. return nil, err
  54. }
  55. } else {
  56. if err := d.setCapabilities(container, c); err != nil {
  57. return nil, err
  58. }
  59. if c.SeccompProfile == "" {
  60. container.Seccomp, err = seccomp.GetDefaultProfile()
  61. if err != nil {
  62. return nil, err
  63. }
  64. }
  65. }
  66. // add CAP_ prefix to all caps for new libcontainer update to match
  67. // the spec format.
  68. for i, s := range container.Capabilities {
  69. if !strings.HasPrefix(s, "CAP_") {
  70. container.Capabilities[i] = fmt.Sprintf("CAP_%s", s)
  71. }
  72. }
  73. container.AdditionalGroups = c.GroupAdd
  74. if c.AppArmorProfile != "" {
  75. container.AppArmorProfile = c.AppArmorProfile
  76. }
  77. if c.SeccompProfile != "" && c.SeccompProfile != "unconfined" {
  78. container.Seccomp, err = seccomp.LoadProfile(c.SeccompProfile)
  79. if err != nil {
  80. return nil, err
  81. }
  82. }
  83. if err := execdriver.SetupCgroups(container, c); err != nil {
  84. return nil, err
  85. }
  86. container.OomScoreAdj = c.OomScoreAdj
  87. if container.Readonlyfs {
  88. for i := range container.Mounts {
  89. switch container.Mounts[i].Destination {
  90. case "/proc", "/dev", "/dev/pts", "/dev/mqueue":
  91. continue
  92. }
  93. container.Mounts[i].Flags |= syscall.MS_RDONLY
  94. }
  95. /* These paths must be remounted as r/o */
  96. container.ReadonlyPaths = append(container.ReadonlyPaths, "/dev")
  97. }
  98. if err := d.setupMounts(container, c); err != nil {
  99. return nil, err
  100. }
  101. d.setupLabels(container, c)
  102. d.setupRlimits(container, c)
  103. return container, nil
  104. }
  105. func (d *Driver) createNetwork(container *configs.Config, c *execdriver.Command, hooks execdriver.Hooks) error {
  106. if c.Network == nil {
  107. return nil
  108. }
  109. if c.Network.ContainerID != "" {
  110. d.Lock()
  111. active := d.activeContainers[c.Network.ContainerID]
  112. d.Unlock()
  113. if active == nil {
  114. return fmt.Errorf("%s is not a valid running container to join", c.Network.ContainerID)
  115. }
  116. state, err := active.State()
  117. if err != nil {
  118. return err
  119. }
  120. container.Namespaces.Add(configs.NEWNET, state.NamespacePaths[configs.NEWNET])
  121. return nil
  122. }
  123. if c.Network.NamespacePath != "" {
  124. container.Namespaces.Add(configs.NEWNET, c.Network.NamespacePath)
  125. return nil
  126. }
  127. // only set up prestart hook if the namespace path is not set (this should be
  128. // all cases *except* for --net=host shared networking)
  129. container.Hooks = &configs.Hooks{
  130. Prestart: []configs.Hook{
  131. configs.NewFunctionHook(func(s configs.HookState) error {
  132. if len(hooks.PreStart) > 0 {
  133. for _, fnHook := range hooks.PreStart {
  134. // A closed channel for OOM is returned here as it will be
  135. // non-blocking and return the correct result when read.
  136. chOOM := make(chan struct{})
  137. close(chOOM)
  138. if err := fnHook(&c.ProcessConfig, s.Pid, chOOM); err != nil {
  139. return err
  140. }
  141. }
  142. }
  143. return nil
  144. }),
  145. },
  146. }
  147. return nil
  148. }
  149. func (d *Driver) createIpc(container *configs.Config, c *execdriver.Command) error {
  150. if c.Ipc.HostIpc {
  151. container.Namespaces.Remove(configs.NEWIPC)
  152. return nil
  153. }
  154. if c.Ipc.ContainerID != "" {
  155. d.Lock()
  156. active := d.activeContainers[c.Ipc.ContainerID]
  157. d.Unlock()
  158. if active == nil {
  159. return fmt.Errorf("%s is not a valid running container to join", c.Ipc.ContainerID)
  160. }
  161. state, err := active.State()
  162. if err != nil {
  163. return err
  164. }
  165. container.Namespaces.Add(configs.NEWIPC, state.NamespacePaths[configs.NEWIPC])
  166. }
  167. return nil
  168. }
  169. func (d *Driver) createPid(container *configs.Config, c *execdriver.Command) error {
  170. if c.Pid.HostPid {
  171. container.Namespaces.Remove(configs.NEWPID)
  172. return nil
  173. }
  174. return nil
  175. }
  176. func (d *Driver) createUTS(container *configs.Config, c *execdriver.Command) error {
  177. if c.UTS.HostUTS {
  178. container.Namespaces.Remove(configs.NEWUTS)
  179. container.Hostname = ""
  180. return nil
  181. }
  182. return nil
  183. }
  184. func (d *Driver) setupRemappedRoot(container *configs.Config, c *execdriver.Command) error {
  185. if c.RemappedRoot.UID == 0 {
  186. container.Namespaces.Remove(configs.NEWUSER)
  187. return nil
  188. }
  189. // convert the Docker daemon id map to the libcontainer variant of the same struct
  190. // this keeps us from having to import libcontainer code across Docker client + daemon packages
  191. cuidMaps := []configs.IDMap{}
  192. cgidMaps := []configs.IDMap{}
  193. for _, idMap := range c.UIDMapping {
  194. cuidMaps = append(cuidMaps, configs.IDMap(idMap))
  195. }
  196. for _, idMap := range c.GIDMapping {
  197. cgidMaps = append(cgidMaps, configs.IDMap(idMap))
  198. }
  199. container.UidMappings = cuidMaps
  200. container.GidMappings = cgidMaps
  201. for _, node := range container.Devices {
  202. node.Uid = uint32(c.RemappedRoot.UID)
  203. node.Gid = uint32(c.RemappedRoot.GID)
  204. }
  205. // TODO: until a kernel/mount solution exists for handling remount in a user namespace,
  206. // we must clear the readonly flag for the cgroups mount (@mrunalp concurs)
  207. for i := range container.Mounts {
  208. if container.Mounts[i].Device == "cgroup" {
  209. container.Mounts[i].Flags &= ^syscall.MS_RDONLY
  210. }
  211. }
  212. return nil
  213. }
  214. func (d *Driver) setPrivileged(container *configs.Config) (err error) {
  215. container.Capabilities = execdriver.GetAllCapabilities()
  216. container.Cgroups.Resources.AllowAllDevices = true
  217. hostDevices, err := devices.HostDevices()
  218. if err != nil {
  219. return err
  220. }
  221. container.Devices = hostDevices
  222. if apparmor.IsEnabled() {
  223. container.AppArmorProfile = "unconfined"
  224. }
  225. return nil
  226. }
  227. func (d *Driver) setCapabilities(container *configs.Config, c *execdriver.Command) (err error) {
  228. container.Capabilities, err = execdriver.TweakCapabilities(container.Capabilities, c.CapAdd, c.CapDrop)
  229. return err
  230. }
  231. func (d *Driver) setupRlimits(container *configs.Config, c *execdriver.Command) {
  232. if c.Resources == nil {
  233. return
  234. }
  235. for _, rlimit := range c.Resources.Rlimits {
  236. container.Rlimits = append(container.Rlimits, configs.Rlimit{
  237. Type: rlimit.Type,
  238. Hard: rlimit.Hard,
  239. Soft: rlimit.Soft,
  240. })
  241. }
  242. }
  243. // If rootfs mount propagation is RPRIVATE, that means all the volumes are
  244. // going to be private anyway. There is no need to apply per volume
  245. // propagation on top. This is just an optimization so that cost of per volume
  246. // propagation is paid only if user decides to make some volume non-private
  247. // which will force rootfs mount propagation to be non RPRIVATE.
  248. func checkResetVolumePropagation(container *configs.Config) {
  249. if container.RootPropagation != mount.RPRIVATE {
  250. return
  251. }
  252. for _, m := range container.Mounts {
  253. m.PropagationFlags = nil
  254. }
  255. }
  256. func getMountInfo(mountinfo []*mount.Info, dir string) *mount.Info {
  257. for _, m := range mountinfo {
  258. if m.Mountpoint == dir {
  259. return m
  260. }
  261. }
  262. return nil
  263. }
  264. // Get the source mount point of directory passed in as argument. Also return
  265. // optional fields.
  266. func getSourceMount(source string) (string, string, error) {
  267. // Ensure any symlinks are resolved.
  268. sourcePath, err := filepath.EvalSymlinks(source)
  269. if err != nil {
  270. return "", "", err
  271. }
  272. mountinfos, err := mount.GetMounts()
  273. if err != nil {
  274. return "", "", err
  275. }
  276. mountinfo := getMountInfo(mountinfos, sourcePath)
  277. if mountinfo != nil {
  278. return sourcePath, mountinfo.Optional, nil
  279. }
  280. path := sourcePath
  281. for {
  282. path = filepath.Dir(path)
  283. mountinfo = getMountInfo(mountinfos, path)
  284. if mountinfo != nil {
  285. return path, mountinfo.Optional, nil
  286. }
  287. if path == "/" {
  288. break
  289. }
  290. }
  291. // If we are here, we did not find parent mount. Something is wrong.
  292. return "", "", fmt.Errorf("Could not find source mount of %s", source)
  293. }
  294. // Ensure mount point on which path is mounted, is shared.
  295. func ensureShared(path string) error {
  296. sharedMount := false
  297. sourceMount, optionalOpts, err := getSourceMount(path)
  298. if err != nil {
  299. return err
  300. }
  301. // Make sure source mount point is shared.
  302. optsSplit := strings.Split(optionalOpts, " ")
  303. for _, opt := range optsSplit {
  304. if strings.HasPrefix(opt, "shared:") {
  305. sharedMount = true
  306. break
  307. }
  308. }
  309. if !sharedMount {
  310. return fmt.Errorf("Path %s is mounted on %s but it is not a shared mount.", path, sourceMount)
  311. }
  312. return nil
  313. }
  314. // Ensure mount point on which path is mounted, is either shared or slave.
  315. func ensureSharedOrSlave(path string) error {
  316. sharedMount := false
  317. slaveMount := false
  318. sourceMount, optionalOpts, err := getSourceMount(path)
  319. if err != nil {
  320. return err
  321. }
  322. // Make sure source mount point is shared.
  323. optsSplit := strings.Split(optionalOpts, " ")
  324. for _, opt := range optsSplit {
  325. if strings.HasPrefix(opt, "shared:") {
  326. sharedMount = true
  327. break
  328. } else if strings.HasPrefix(opt, "master:") {
  329. slaveMount = true
  330. break
  331. }
  332. }
  333. if !sharedMount && !slaveMount {
  334. return fmt.Errorf("Path %s is mounted on %s but it is not a shared or slave mount.", path, sourceMount)
  335. }
  336. return nil
  337. }
  338. func (d *Driver) setupMounts(container *configs.Config, c *execdriver.Command) error {
  339. userMounts := make(map[string]struct{})
  340. for _, m := range c.Mounts {
  341. userMounts[m.Destination] = struct{}{}
  342. }
  343. // Filter out mounts that are overridden by user supplied mounts
  344. var defaultMounts []*configs.Mount
  345. _, mountDev := userMounts["/dev"]
  346. for _, m := range container.Mounts {
  347. if _, ok := userMounts[m.Destination]; !ok {
  348. if mountDev && strings.HasPrefix(m.Destination, "/dev/") {
  349. container.Devices = nil
  350. continue
  351. }
  352. defaultMounts = append(defaultMounts, m)
  353. }
  354. }
  355. container.Mounts = defaultMounts
  356. mountPropagationMap := map[string]int{
  357. "private": mount.PRIVATE,
  358. "rprivate": mount.RPRIVATE,
  359. "shared": mount.SHARED,
  360. "rshared": mount.RSHARED,
  361. "slave": mount.SLAVE,
  362. "rslave": mount.RSLAVE,
  363. }
  364. for _, m := range c.Mounts {
  365. for _, cm := range container.Mounts {
  366. if cm.Destination == m.Destination {
  367. return fmt.Errorf("Duplicate mount point '%s'", m.Destination)
  368. }
  369. }
  370. if m.Source == "tmpfs" {
  371. var (
  372. data = "size=65536k"
  373. flags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
  374. err error
  375. )
  376. if m.Data != "" {
  377. flags, data, err = mount.ParseTmpfsOptions(m.Data)
  378. if err != nil {
  379. return err
  380. }
  381. }
  382. container.Mounts = append(container.Mounts, &configs.Mount{
  383. Source: m.Source,
  384. Destination: m.Destination,
  385. Data: data,
  386. Device: "tmpfs",
  387. Flags: flags,
  388. PropagationFlags: []int{mountPropagationMap[volume.DefaultPropagationMode]},
  389. })
  390. continue
  391. }
  392. flags := syscall.MS_BIND | syscall.MS_REC
  393. var pFlag int
  394. if !m.Writable {
  395. flags |= syscall.MS_RDONLY
  396. }
  397. // Determine property of RootPropagation based on volume
  398. // properties. If a volume is shared, then keep root propagation
  399. // shared. This should work for slave and private volumes too.
  400. //
  401. // For slave volumes, it can be either [r]shared/[r]slave.
  402. //
  403. // For private volumes any root propagation value should work.
  404. pFlag = mountPropagationMap[m.Propagation]
  405. if pFlag == mount.SHARED || pFlag == mount.RSHARED {
  406. if err := ensureShared(m.Source); err != nil {
  407. return err
  408. }
  409. rootpg := container.RootPropagation
  410. if rootpg != mount.SHARED && rootpg != mount.RSHARED {
  411. execdriver.SetRootPropagation(container, mount.SHARED)
  412. }
  413. } else if pFlag == mount.SLAVE || pFlag == mount.RSLAVE {
  414. if err := ensureSharedOrSlave(m.Source); err != nil {
  415. return err
  416. }
  417. rootpg := container.RootPropagation
  418. if rootpg != mount.SHARED && rootpg != mount.RSHARED && rootpg != mount.SLAVE && rootpg != mount.RSLAVE {
  419. execdriver.SetRootPropagation(container, mount.RSLAVE)
  420. }
  421. }
  422. mount := &configs.Mount{
  423. Source: m.Source,
  424. Destination: m.Destination,
  425. Device: "bind",
  426. Flags: flags,
  427. }
  428. if pFlag != 0 {
  429. mount.PropagationFlags = []int{pFlag}
  430. }
  431. container.Mounts = append(container.Mounts, mount)
  432. }
  433. checkResetVolumePropagation(container)
  434. return nil
  435. }
  436. func (d *Driver) setupLabels(container *configs.Config, c *execdriver.Command) {
  437. container.ProcessLabel = c.ProcessLabel
  438. container.MountLabel = c.MountLabel
  439. }