wrapper.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. if c.sub == nil {
  50. return c.err
  51. }
  52. exitCode := c.sub.Wait()
  53. if exitCode == 0 {
  54. return nil
  55. }
  56. return ExitCodeError{Code: exitCode}
  57. }
  58. func translateError(err error) error {
  59. switch v := err.(type) {
  60. case *osExec.Error:
  61. return &Error{
  62. Name: v.Name,
  63. Err: v.Err,
  64. }
  65. }
  66. return err
  67. }