setup_unix.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // +build linux freebsd
  2. package initlayer
  3. import (
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "syscall"
  8. "github.com/docker/docker/pkg/idtools"
  9. )
  10. // Setup populates a directory with mountpoints suitable
  11. // for bind-mounting things into the container.
  12. //
  13. // This extra layer is used by all containers as the top-most ro layer. It protects
  14. // the container from unwanted side-effects on the rw layer.
  15. func Setup(initLayer string, rootUID, rootGID int) error {
  16. for pth, typ := range map[string]string{
  17. "/dev/pts": "dir",
  18. "/dev/shm": "dir",
  19. "/proc": "dir",
  20. "/sys": "dir",
  21. "/.dockerenv": "file",
  22. "/etc/resolv.conf": "file",
  23. "/etc/hosts": "file",
  24. "/etc/hostname": "file",
  25. "/dev/console": "file",
  26. "/etc/mtab": "/proc/mounts",
  27. } {
  28. parts := strings.Split(pth, "/")
  29. prev := "/"
  30. for _, p := range parts[1:] {
  31. prev = filepath.Join(prev, p)
  32. syscall.Unlink(filepath.Join(initLayer, prev))
  33. }
  34. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  35. if os.IsNotExist(err) {
  36. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  37. return err
  38. }
  39. switch typ {
  40. case "dir":
  41. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  42. return err
  43. }
  44. case "file":
  45. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  46. if err != nil {
  47. return err
  48. }
  49. f.Chown(rootUID, rootGID)
  50. f.Close()
  51. default:
  52. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  53. return err
  54. }
  55. }
  56. } else {
  57. return err
  58. }
  59. }
  60. }
  61. // Layer is ready to use, if it wasn't before.
  62. return nil
  63. }