mount.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. //go:build linux
  2. // +build linux
  3. package overlay2 // import "github.com/docker/docker/daemon/graphdriver/overlay2"
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "os"
  10. "runtime"
  11. "github.com/docker/docker/pkg/reexec"
  12. "golang.org/x/sys/unix"
  13. )
  14. func init() {
  15. reexec.Register("docker-mountfrom", mountFromMain)
  16. }
  17. func fatal(err error) {
  18. fmt.Fprint(os.Stderr, err)
  19. os.Exit(1)
  20. }
  21. type mountOptions struct {
  22. Device string
  23. Target string
  24. Type string
  25. Label string
  26. Flag uint32
  27. }
  28. func mountFrom(dir, device, target, mType string, flags uintptr, label string) error {
  29. options := &mountOptions{
  30. Device: device,
  31. Target: target,
  32. Type: mType,
  33. Flag: uint32(flags),
  34. Label: label,
  35. }
  36. cmd := reexec.Command("docker-mountfrom", dir)
  37. w, err := cmd.StdinPipe()
  38. if err != nil {
  39. return fmt.Errorf("mountfrom error on pipe creation: %v", err)
  40. }
  41. output := bytes.NewBuffer(nil)
  42. cmd.Stdout = output
  43. cmd.Stderr = output
  44. // reexec.Command() sets cmd.SysProcAttr.Pdeathsig on Linux, which
  45. // causes the started process to be signaled when the creating OS thread
  46. // dies. Ensure that the reexec is not prematurely signaled. See
  47. // https://go.dev/issue/27505 for more information.
  48. runtime.LockOSThread()
  49. defer runtime.UnlockOSThread()
  50. if err := cmd.Start(); err != nil {
  51. w.Close()
  52. return fmt.Errorf("mountfrom error on re-exec cmd: %v", err)
  53. }
  54. // write the options to the pipe for the untar exec to read
  55. if err := json.NewEncoder(w).Encode(options); err != nil {
  56. w.Close()
  57. return fmt.Errorf("mountfrom json encode to pipe failed: %v", err)
  58. }
  59. w.Close()
  60. if err := cmd.Wait(); err != nil {
  61. return fmt.Errorf("mountfrom re-exec error: %v: output: %v", err, output)
  62. }
  63. return nil
  64. }
  65. // mountfromMain is the entry-point for docker-mountfrom on re-exec.
  66. func mountFromMain() {
  67. runtime.LockOSThread()
  68. flag.Parse()
  69. var options *mountOptions
  70. if err := json.NewDecoder(os.Stdin).Decode(&options); err != nil {
  71. fatal(err)
  72. }
  73. if err := os.Chdir(flag.Arg(0)); err != nil {
  74. fatal(err)
  75. }
  76. if err := unix.Mount(options.Device, options.Target, options.Type, uintptr(options.Flag), options.Label); err != nil {
  77. fatal(err)
  78. }
  79. os.Exit(0)
  80. }