panicwrap.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // The panicwrap package provides functions for capturing and handling
  2. // panics in your application. It does this by re-executing the running
  3. // application and monitoring stderr for any panics. At the same time,
  4. // stdout/stderr/etc. are set to the same values so that data is shuttled
  5. // through properly, making the existence of panicwrap mostly transparent.
  6. //
  7. // Panics are only detected when the subprocess exits with a non-zero
  8. // exit status, since this is the only time panics are real. Otherwise,
  9. // "panic-like" output is ignored.
  10. package panicwrap
  11. import (
  12. "bytes"
  13. "errors"
  14. "io"
  15. "os"
  16. "os/exec"
  17. "os/signal"
  18. "runtime"
  19. "sync/atomic"
  20. "syscall"
  21. "time"
  22. "github.com/kardianos/osext"
  23. )
  24. const (
  25. DEFAULT_COOKIE_KEY = "cccf35992f8f3cd8d1d28f0109dd953e26664531"
  26. DEFAULT_COOKIE_VAL = "7c28215aca87789f95b406b8dd91aa5198406750"
  27. )
  28. // HandlerFunc is the type called when a panic is detected.
  29. type HandlerFunc func(string)
  30. // WrapConfig is the configuration for panicwrap when wrapping an existing
  31. // binary. To get started, in general, you only need the BasicWrap function
  32. // that will set this up for you. However, for more customizability,
  33. // WrapConfig and Wrap can be used.
  34. type WrapConfig struct {
  35. // Handler is the function called when a panic occurs.
  36. Handler HandlerFunc
  37. // The cookie key and value are used within environmental variables
  38. // to tell the child process that it is already executing so that
  39. // wrap doesn't re-wrap itself.
  40. CookieKey string
  41. CookieValue string
  42. // If true, the panic will not be mirrored to the configured writer
  43. // and will instead ONLY go to the handler. This lets you effectively
  44. // hide panics from the end user. This is not recommended because if
  45. // your handler fails, the panic is effectively lost.
  46. HidePanic bool
  47. // The amount of time that a process must exit within after detecting
  48. // a panic header for panicwrap to assume it is a panic. Defaults to
  49. // 300 milliseconds.
  50. DetectDuration time.Duration
  51. // The writer to send the stderr to. If this is nil, then it defaults
  52. // to os.Stderr.
  53. Writer io.Writer
  54. // The writer to send stdout to. If this is nil, then it defaults to
  55. // os.Stdout.
  56. Stdout io.Writer
  57. // Catch and igore these signals in the parent process, let the child
  58. // handle them gracefully.
  59. IgnoreSignals []os.Signal
  60. // Catch these signals in the parent process and manually forward
  61. // them to the child process. Some signals such as SIGINT are usually
  62. // sent to the entire process group so setting it isn't necessary. Other
  63. // signals like SIGTERM are only sent to the parent process and need
  64. // to be forwarded. This defaults to empty.
  65. ForwardSignals []os.Signal
  66. }
  67. // BasicWrap calls Wrap with the given handler function, using defaults
  68. // for everything else. See Wrap and WrapConfig for more information on
  69. // functionality and return values.
  70. func BasicWrap(f HandlerFunc) (int, error) {
  71. return Wrap(&WrapConfig{
  72. Handler: f,
  73. })
  74. }
  75. // Wrap wraps the current executable in a handler to catch panics. It
  76. // returns an error if there was an error during the wrapping process.
  77. // If the error is nil, then the int result indicates the exit status of the
  78. // child process. If the exit status is -1, then this is the child process,
  79. // and execution should continue as normal. Otherwise, this is the parent
  80. // process and the child successfully ran already, and you should exit the
  81. // process with the returned exit status.
  82. //
  83. // This function should be called very very early in your program's execution.
  84. // Ideally, this runs as the first line of code of main.
  85. //
  86. // Once this is called, the given WrapConfig shouldn't be modified or used
  87. // any further.
  88. func Wrap(c *WrapConfig) (int, error) {
  89. if c.Handler == nil {
  90. return -1, errors.New("Handler must be set")
  91. }
  92. if c.DetectDuration == 0 {
  93. c.DetectDuration = 300 * time.Millisecond
  94. }
  95. if c.Writer == nil {
  96. c.Writer = os.Stderr
  97. }
  98. // If we're already wrapped, exit out.
  99. if Wrapped(c) {
  100. return -1, nil
  101. }
  102. // Get the path to our current executable
  103. exePath, err := osext.Executable()
  104. if err != nil {
  105. return -1, err
  106. }
  107. // Pipe the stderr so we can read all the data as we look for panics
  108. stderr_r, stderr_w := io.Pipe()
  109. // doneCh is closed when we're done, signaling any other goroutines
  110. // to end immediately.
  111. doneCh := make(chan struct{})
  112. // panicCh is the channel on which the panic text will actually be
  113. // sent.
  114. panicCh := make(chan string)
  115. // On close, make sure to finish off the copying of data to stderr
  116. defer func() {
  117. defer close(doneCh)
  118. stderr_w.Close()
  119. <-panicCh
  120. }()
  121. // Start the goroutine that will watch stderr for any panics
  122. go trackPanic(stderr_r, c.Writer, c.DetectDuration, panicCh)
  123. // Create the writer for stdout that we're going to use
  124. var stdout_w io.Writer = os.Stdout
  125. if c.Stdout != nil {
  126. stdout_w = c.Stdout
  127. }
  128. // Build a subcommand to re-execute ourselves. We make sure to
  129. // set the environmental variable to include our cookie. We also
  130. // set stdin/stdout to match the config. Finally, we pipe stderr
  131. // through ourselves in order to watch for panics.
  132. cmd := exec.Command(exePath, os.Args[1:]...)
  133. cmd.Env = append(os.Environ(), c.CookieKey+"="+c.CookieValue)
  134. cmd.Stdin = os.Stdin
  135. cmd.Stdout = stdout_w
  136. cmd.Stderr = stderr_w
  137. // Windows doesn't support this, but on other platforms pass in
  138. // the original file descriptors so they can be used.
  139. if runtime.GOOS != "windows" {
  140. cmd.ExtraFiles = []*os.File{os.Stdin, os.Stdout, os.Stderr}
  141. }
  142. if err := cmd.Start(); err != nil {
  143. return 1, err
  144. }
  145. // Listen to signals and capture them forever. We allow the child
  146. // process to handle them in some way.
  147. sigCh := make(chan os.Signal)
  148. fwdSigCh := make(chan os.Signal)
  149. if len(c.IgnoreSignals) == 0 {
  150. c.IgnoreSignals = []os.Signal{os.Interrupt}
  151. }
  152. signal.Notify(sigCh, c.IgnoreSignals...)
  153. signal.Notify(fwdSigCh, c.ForwardSignals...)
  154. go func() {
  155. defer signal.Stop(sigCh)
  156. defer signal.Stop(fwdSigCh)
  157. for {
  158. select {
  159. case <-doneCh:
  160. return
  161. case s := <-fwdSigCh:
  162. if cmd.Process != nil {
  163. cmd.Process.Signal(s)
  164. }
  165. case <-sigCh:
  166. }
  167. }
  168. }()
  169. if err := cmd.Wait(); err != nil {
  170. exitErr, ok := err.(*exec.ExitError)
  171. if !ok {
  172. // This is some other kind of subprocessing error.
  173. return 1, err
  174. }
  175. exitStatus := 1
  176. if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
  177. exitStatus = status.ExitStatus()
  178. }
  179. // Close the writer end so that the tracker goroutine ends at some point
  180. stderr_w.Close()
  181. // Wait on the panic data
  182. panicTxt := <-panicCh
  183. if panicTxt != "" {
  184. if !c.HidePanic {
  185. c.Writer.Write([]byte(panicTxt))
  186. }
  187. c.Handler(panicTxt)
  188. }
  189. return exitStatus, nil
  190. }
  191. return 0, nil
  192. }
  193. // Wrapped checks if we're already wrapped according to the configuration
  194. // given.
  195. //
  196. // Wrapped is very cheap and can be used early to short-circuit some pre-wrap
  197. // logic your application may have.
  198. //
  199. // If the given configuration is nil, then this will return a cached
  200. // value of Wrapped. This is useful because Wrapped is usually called early
  201. // to verify a process hasn't been wrapped before wrapping. After this,
  202. // the value of Wrapped hardly changes and is process-global, so other
  203. // libraries can check with Wrapped(nil).
  204. func Wrapped(c *WrapConfig) bool {
  205. if c == nil {
  206. return wrapCache.Load().(bool)
  207. }
  208. if c.CookieKey == "" {
  209. c.CookieKey = DEFAULT_COOKIE_KEY
  210. }
  211. if c.CookieValue == "" {
  212. c.CookieValue = DEFAULT_COOKIE_VAL
  213. }
  214. // If the cookie key/value match our environment, then we are the
  215. // child, so just exit now and tell the caller that we're the child
  216. result := os.Getenv(c.CookieKey) == c.CookieValue
  217. wrapCache.Store(result)
  218. return result
  219. }
  220. // wrapCache is the cached value for Wrapped when called with nil
  221. var wrapCache atomic.Value
  222. func init() {
  223. wrapCache.Store(false)
  224. }
  225. // trackPanic monitors the given reader for a panic. If a panic is detected,
  226. // it is outputted on the result channel. This will close the channel once
  227. // it is complete.
  228. func trackPanic(r io.Reader, w io.Writer, dur time.Duration, result chan<- string) {
  229. defer close(result)
  230. var panicTimer <-chan time.Time
  231. panicBuf := new(bytes.Buffer)
  232. panicHeaders := [][]byte{
  233. []byte("panic:"),
  234. []byte("fatal error: fault"),
  235. }
  236. panicType := -1
  237. tempBuf := make([]byte, 2048)
  238. for {
  239. var buf []byte
  240. var n int
  241. if panicTimer == nil && panicBuf.Len() > 0 {
  242. // We're not tracking a panic but the buffer length is
  243. // greater than 0. We need to clear out that buffer, but
  244. // look for another panic along the way.
  245. // First, remove the previous panic header so we don't loop
  246. w.Write(panicBuf.Next(len(panicHeaders[panicType])))
  247. // Next, assume that this is our new buffer to inspect
  248. n = panicBuf.Len()
  249. buf = make([]byte, n)
  250. copy(buf, panicBuf.Bytes())
  251. panicBuf.Reset()
  252. } else {
  253. var err error
  254. buf = tempBuf
  255. n, err = r.Read(buf)
  256. if n <= 0 && err == io.EOF {
  257. if panicBuf.Len() > 0 {
  258. // We were tracking a panic, assume it was a panic
  259. // and return that as the result.
  260. result <- panicBuf.String()
  261. }
  262. return
  263. }
  264. }
  265. if panicTimer != nil {
  266. // We're tracking what we think is a panic right now.
  267. // If the timer ended, then it is not a panic.
  268. isPanic := true
  269. select {
  270. case <-panicTimer:
  271. isPanic = false
  272. default:
  273. }
  274. // No matter what, buffer the text some more.
  275. panicBuf.Write(buf[0:n])
  276. if !isPanic {
  277. // It isn't a panic, stop tracking. Clean-up will happen
  278. // on the next iteration.
  279. panicTimer = nil
  280. }
  281. continue
  282. }
  283. panicType = -1
  284. flushIdx := n
  285. for i, header := range panicHeaders {
  286. idx := bytes.Index(buf[0:n], header)
  287. if idx >= 0 {
  288. panicType = i
  289. flushIdx = idx
  290. break
  291. }
  292. }
  293. // Flush to stderr what isn't a panic
  294. w.Write(buf[0:flushIdx])
  295. if panicType == -1 {
  296. // Not a panic so just continue along
  297. continue
  298. }
  299. // We have a panic header. Write we assume is a panic os far.
  300. panicBuf.Write(buf[flushIdx:n])
  301. panicTimer = time.After(dur)
  302. }
  303. }