exec.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright 2017 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package build
  15. import (
  16. "bufio"
  17. "io"
  18. "os/exec"
  19. "strings"
  20. "syscall"
  21. "time"
  22. )
  23. // Cmd is a wrapper of os/exec.Cmd that integrates with the build context for
  24. // logging, the config's Environment for simpler environment modification, and
  25. // implements hooks for sandboxing
  26. type Cmd struct {
  27. *exec.Cmd
  28. Environment *Environment
  29. Sandbox Sandbox
  30. ctx Context
  31. config Config
  32. name string
  33. started time.Time
  34. }
  35. func Command(ctx Context, config Config, name string, executable string, args ...string) *Cmd {
  36. ret := &Cmd{
  37. Cmd: exec.CommandContext(ctx.Context, executable, args...),
  38. Environment: config.Environment().Copy(),
  39. Sandbox: noSandbox,
  40. ctx: ctx,
  41. config: config,
  42. name: name,
  43. }
  44. return ret
  45. }
  46. func (c *Cmd) prepare() {
  47. if c.Env == nil {
  48. c.Env = c.Environment.Environ()
  49. }
  50. if c.sandboxSupported() {
  51. c.wrapSandbox()
  52. }
  53. c.ctx.Verbosef("%q executing %q %v\n", c.name, c.Path, c.Args)
  54. c.started = time.Now()
  55. }
  56. func (c *Cmd) report() {
  57. if state := c.Cmd.ProcessState; state != nil {
  58. if c.ctx.Metrics != nil {
  59. c.ctx.Metrics.EventTracer.AddProcResInfo(c.name, state)
  60. }
  61. rusage := state.SysUsage().(*syscall.Rusage)
  62. c.ctx.Verbosef("%q finished with exit code %d (%s real, %s user, %s system, %dMB maxrss)",
  63. c.name, c.Cmd.ProcessState.ExitCode(),
  64. time.Since(c.started).Round(time.Millisecond),
  65. c.Cmd.ProcessState.UserTime().Round(time.Millisecond),
  66. c.Cmd.ProcessState.SystemTime().Round(time.Millisecond),
  67. rusage.Maxrss/1024)
  68. }
  69. }
  70. func (c *Cmd) Start() error {
  71. c.prepare()
  72. return c.Cmd.Start()
  73. }
  74. func (c *Cmd) Run() error {
  75. c.prepare()
  76. err := c.Cmd.Run()
  77. c.report()
  78. return err
  79. }
  80. func (c *Cmd) Output() ([]byte, error) {
  81. c.prepare()
  82. bytes, err := c.Cmd.Output()
  83. c.report()
  84. return bytes, err
  85. }
  86. func (c *Cmd) CombinedOutput() ([]byte, error) {
  87. c.prepare()
  88. bytes, err := c.Cmd.CombinedOutput()
  89. c.report()
  90. return bytes, err
  91. }
  92. func (c *Cmd) Wait() error {
  93. err := c.Cmd.Wait()
  94. c.report()
  95. return err
  96. }
  97. // StartOrFatal is equivalent to Start, but handles the error with a call to ctx.Fatal
  98. func (c *Cmd) StartOrFatal() {
  99. if err := c.Start(); err != nil {
  100. c.ctx.Fatalf("Failed to run %s: %v", c.name, err)
  101. }
  102. }
  103. func (c *Cmd) reportError(err error) {
  104. if err == nil {
  105. return
  106. }
  107. if e, ok := err.(*exec.ExitError); ok {
  108. c.ctx.Fatalf("%s failed with: %v", c.name, e.ProcessState.String())
  109. } else {
  110. c.ctx.Fatalf("Failed to run %s: %v", c.name, err)
  111. }
  112. }
  113. // RunOrFatal is equivalent to Run, but handles the error with a call to ctx.Fatal
  114. func (c *Cmd) RunOrFatal() {
  115. c.reportError(c.Run())
  116. }
  117. // WaitOrFatal is equivalent to Wait, but handles the error with a call to ctx.Fatal
  118. func (c *Cmd) WaitOrFatal() {
  119. c.reportError(c.Wait())
  120. }
  121. // OutputOrFatal is equivalent to Output, but handles the error with a call to ctx.Fatal
  122. func (c *Cmd) OutputOrFatal() []byte {
  123. ret, err := c.Output()
  124. c.reportError(err)
  125. return ret
  126. }
  127. // CombinedOutputOrFatal is equivalent to CombinedOutput, but handles the error with
  128. // a call to ctx.Fatal
  129. func (c *Cmd) CombinedOutputOrFatal() []byte {
  130. ret, err := c.CombinedOutput()
  131. c.reportError(err)
  132. return ret
  133. }
  134. // RunAndPrintOrFatal will run the command, then after finishing
  135. // print any output, then handling any errors with a call to
  136. // ctx.Fatal
  137. func (c *Cmd) RunAndPrintOrFatal() {
  138. ret, err := c.CombinedOutput()
  139. st := c.ctx.Status.StartTool()
  140. if len(ret) > 0 {
  141. if err != nil {
  142. st.Error(string(ret))
  143. } else {
  144. st.Print(string(ret))
  145. }
  146. }
  147. st.Finish()
  148. c.reportError(err)
  149. }
  150. // RunAndStreamOrFatal will run the command, while running print
  151. // any output, then handle any errors with a call to ctx.Fatal
  152. func (c *Cmd) RunAndStreamOrFatal() {
  153. out, err := c.StdoutPipe()
  154. if err != nil {
  155. c.ctx.Fatal(err)
  156. }
  157. c.Stderr = c.Stdout
  158. st := c.ctx.Status.StartTool()
  159. c.StartOrFatal()
  160. buf := bufio.NewReaderSize(out, 2*1024*1024)
  161. for {
  162. // Attempt to read whole lines, but write partial lines that are too long to fit in the buffer or hit EOF
  163. line, err := buf.ReadString('\n')
  164. if line != "" {
  165. st.Print(strings.TrimSuffix(line, "\n"))
  166. } else if err == io.EOF {
  167. break
  168. } else if err != nil {
  169. c.ctx.Fatal(err)
  170. }
  171. }
  172. err = c.Wait()
  173. st.Finish()
  174. c.reportError(err)
  175. }