proxy_linux.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package portmapper
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "strconv"
  9. "syscall"
  10. "time"
  11. )
  12. const userlandProxyCommandName = "docker-proxy"
  13. func newProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, proxyPath string) (userlandProxy, error) {
  14. path := proxyPath
  15. if proxyPath == "" {
  16. cmd, err := exec.LookPath(userlandProxyCommandName)
  17. if err != nil {
  18. return nil, err
  19. }
  20. path = cmd
  21. }
  22. args := []string{
  23. path,
  24. "-proto", proto,
  25. "-host-ip", hostIP.String(),
  26. "-host-port", strconv.Itoa(hostPort),
  27. "-container-ip", containerIP.String(),
  28. "-container-port", strconv.Itoa(containerPort),
  29. }
  30. return &proxyCommand{
  31. cmd: &exec.Cmd{
  32. Path: path,
  33. Args: args,
  34. SysProcAttr: &syscall.SysProcAttr{
  35. Pdeathsig: syscall.SIGTERM, // send a sigterm to the proxy if the daemon process dies
  36. },
  37. },
  38. }, nil
  39. }
  40. // proxyCommand wraps an exec.Cmd to run the userland TCP and UDP
  41. // proxies as separate processes.
  42. type proxyCommand struct {
  43. cmd *exec.Cmd
  44. }
  45. func (p *proxyCommand) Start() error {
  46. r, w, err := os.Pipe()
  47. if err != nil {
  48. return fmt.Errorf("proxy unable to open os.Pipe %s", err)
  49. }
  50. defer r.Close()
  51. p.cmd.ExtraFiles = []*os.File{w}
  52. if err := p.cmd.Start(); err != nil {
  53. return err
  54. }
  55. w.Close()
  56. errchan := make(chan error, 1)
  57. go func() {
  58. buf := make([]byte, 2)
  59. r.Read(buf)
  60. if string(buf) != "0\n" {
  61. errStr, err := io.ReadAll(r)
  62. if err != nil {
  63. errchan <- fmt.Errorf("Error reading exit status from userland proxy: %v", err)
  64. return
  65. }
  66. errchan <- fmt.Errorf("Error starting userland proxy: %s", errStr)
  67. return
  68. }
  69. errchan <- nil
  70. }()
  71. select {
  72. case err := <-errchan:
  73. return err
  74. case <-time.After(16 * time.Second):
  75. return fmt.Errorf("Timed out proxy starting the userland proxy")
  76. }
  77. }
  78. func (p *proxyCommand) Stop() error {
  79. if p.cmd.Process != nil {
  80. if err := p.cmd.Process.Signal(os.Interrupt); err != nil {
  81. return err
  82. }
  83. return p.cmd.Wait()
  84. }
  85. return nil
  86. }