wrapper.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package exec
  2. import (
  3. "fmt"
  4. osExec "os/exec"
  5. "strconv"
  6. "github.com/docker/containerd/subreaper"
  7. )
  8. var ErrNotFound = osExec.ErrNotFound
  9. type Cmd struct {
  10. osExec.Cmd
  11. err error
  12. sub *subreaper.Subscription
  13. }
  14. type Error struct {
  15. Name string
  16. Err error
  17. }
  18. func (e *Error) Error() string {
  19. return "exec: " + strconv.Quote(e.Name) + ": " + e.Err.Error()
  20. }
  21. type ExitCodeError struct {
  22. Code int
  23. }
  24. func (e ExitCodeError) Error() string {
  25. return fmt.Sprintf("Non-zero exit code: %d", e.Code)
  26. }
  27. func LookPath(file string) (string, error) {
  28. v, err := osExec.LookPath(file)
  29. return v, translateError(err)
  30. }
  31. func Command(name string, args ...string) *Cmd {
  32. return &Cmd{
  33. Cmd: *osExec.Command(name, args...),
  34. }
  35. }
  36. func (c *Cmd) Start() error {
  37. c.sub = subreaper.Subscribe()
  38. err := c.Cmd.Start()
  39. if err != nil {
  40. subreaper.Unsubscribe(c.sub)
  41. c.sub = nil
  42. c.err = translateError(err)
  43. return c.err
  44. }
  45. c.sub.SetPid(c.Cmd.Process.Pid)
  46. return nil
  47. }
  48. func (c *Cmd) Wait() error {
  49. // c.Cmd.Wait() will always error because there is no child process anymore
  50. // This is called to ensure that the streams are closed and cleaned up properly
  51. defer c.Cmd.Wait()
  52. if c.sub == nil {
  53. return c.err
  54. }
  55. exitCode := c.sub.Wait()
  56. if exitCode == 0 {
  57. return nil
  58. }
  59. return ExitCodeError{Code: exitCode}
  60. }
  61. func translateError(err error) error {
  62. switch v := err.(type) {
  63. case *osExec.Error:
  64. return &Error{
  65. Name: v.Name,
  66. Err: v.Err,
  67. }
  68. }
  69. return err
  70. }