main.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Copyright 2015 Marc-Antoine Ruel. All rights reserved.
  2. // Use of this source code is governed under the Apache License, Version 2.0
  3. // that can be found in the LICENSE file.
  4. // Package internal implements panicparse
  5. //
  6. // It is mostly useful on servers will large number of identical goroutines,
  7. // making the crash dump harder to read than strictly necessary.
  8. //
  9. // Colors:
  10. // - Magenta: first goroutine to be listed.
  11. // - Yellow: main package.
  12. // - Green: standard library.
  13. // - Red: other packages.
  14. //
  15. // Bright colors are used for exported symbols.
  16. package internal
  17. import (
  18. "errors"
  19. "flag"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "log"
  24. "os"
  25. "os/signal"
  26. "regexp"
  27. "syscall"
  28. "notabug.org/themusicgod1/panicparse/stack"
  29. "github.com/mattn/go-colorable"
  30. "github.com/mattn/go-isatty"
  31. "github.com/mgutz/ansi"
  32. )
  33. // resetFG is similar to ansi.Reset except that it doesn't reset the
  34. // background color, only the foreground color and the style.
  35. //
  36. // That much for the "ansi" abstraction layer...
  37. const resetFG = ansi.DefaultFG + "\033[m"
  38. // defaultPalette is the default recommended palette.
  39. var defaultPalette = Palette{
  40. EOLReset: resetFG,
  41. RoutineFirst: ansi.ColorCode("magenta+b"),
  42. CreatedBy: ansi.LightBlack,
  43. Package: ansi.ColorCode("default+b"),
  44. SrcFile: resetFG,
  45. FuncStdLib: ansi.Green,
  46. FuncStdLibExported: ansi.ColorCode("green+b"),
  47. FuncMain: ansi.ColorCode("yellow+b"),
  48. FuncOther: ansi.Red,
  49. FuncOtherExported: ansi.ColorCode("red+b"),
  50. Arguments: resetFG,
  51. }
  52. func writeToConsole(out io.Writer, p *Palette, buckets []*stack.Bucket, fullPath, needsEnv bool, filter, match *regexp.Regexp) error {
  53. if needsEnv {
  54. _, _ = io.WriteString(out, "\nTo see all goroutines, visit https://notabug.org/themusicgod1/panicparse#gotraceback\n\n")
  55. }
  56. srcLen, pkgLen := CalcLengths(buckets, fullPath)
  57. for _, bucket := range buckets {
  58. header := p.BucketHeader(bucket, fullPath, len(buckets) > 1)
  59. if filter != nil && filter.MatchString(header) {
  60. continue
  61. }
  62. if match != nil && !match.MatchString(header) {
  63. continue
  64. }
  65. _, _ = io.WriteString(out, header)
  66. _, _ = io.WriteString(out, p.StackLines(&bucket.Signature, srcLen, pkgLen, fullPath))
  67. }
  68. return nil
  69. }
  70. // process copies stdin to stdout and processes any "panic: " line found.
  71. //
  72. // If html is used, a stack trace is written to this file instead.
  73. func process(in io.Reader, out io.Writer, p *Palette, s stack.Similarity, fullPath, parse, rebase bool, html string, filter, match *regexp.Regexp) error {
  74. c, err := stack.ParseDump(in, out, rebase)
  75. if c == nil || err != nil {
  76. return err
  77. }
  78. if rebase {
  79. log.Printf("GOROOT=%s", c.GOROOT)
  80. log.Printf("GOPATH=%s", c.GOPATHs)
  81. }
  82. needsEnv := len(c.Goroutines) == 1 && showBanner()
  83. if parse {
  84. stack.Augment(c.Goroutines)
  85. }
  86. buckets := stack.Aggregate(c.Goroutines, s)
  87. if html == "" {
  88. return writeToConsole(out, p, buckets, fullPath, needsEnv, filter, match)
  89. }
  90. return writeToHTML(html, buckets, needsEnv)
  91. }
  92. func showBanner() bool {
  93. if !showGOTRACEBACKBanner {
  94. return false
  95. }
  96. gtb := os.Getenv("GOTRACEBACK")
  97. return gtb == "" || gtb == "single"
  98. }
  99. // Main is implemented here so both 'pp' and 'panicparse' executables can be
  100. // compiled. This is to work around the Perl Package manager 'pp' that is
  101. // preinstalled on some OSes.
  102. func Main() error {
  103. aggressive := flag.Bool("aggressive", false, "Aggressive deduplication including non pointers")
  104. parse := flag.Bool("parse", true, "Parses source files to deduct types; use -parse=false to work around bugs in source parser")
  105. rebase := flag.Bool("rebase", true, "Guess GOROOT and GOPATH")
  106. verboseFlag := flag.Bool("v", false, "Enables verbose logging output")
  107. filterFlag := flag.String("f", "", "Regexp to filter out headers that match, ex: -f 'IO wait|syscall'")
  108. matchFlag := flag.String("m", "", "Regexp to filter by only headers that match, ex: -m 'semacquire'")
  109. // Console only.
  110. fullPath := flag.Bool("full-path", false, "Print full sources path")
  111. noColor := flag.Bool("no-color", !isatty.IsTerminal(os.Stdout.Fd()) || os.Getenv("TERM") == "dumb", "Disable coloring")
  112. forceColor := flag.Bool("force-color", false, "Forcibly enable coloring when with stdout is redirected")
  113. // HTML only.
  114. html := flag.String("html", "", "Output an HTML file")
  115. flag.Parse()
  116. log.SetFlags(log.Lmicroseconds)
  117. if !*verboseFlag {
  118. log.SetOutput(ioutil.Discard)
  119. }
  120. var err error
  121. var filter *regexp.Regexp
  122. if *filterFlag != "" {
  123. if filter, err = regexp.Compile(*filterFlag); err != nil {
  124. return err
  125. }
  126. }
  127. var match *regexp.Regexp
  128. if *matchFlag != "" {
  129. if match, err = regexp.Compile(*matchFlag); err != nil {
  130. return err
  131. }
  132. }
  133. s := stack.AnyPointer
  134. if *aggressive {
  135. s = stack.AnyValue
  136. }
  137. var out io.Writer = os.Stdout
  138. p := &defaultPalette
  139. if *html == "" {
  140. if *noColor && !*forceColor {
  141. p = &Palette{}
  142. } else {
  143. out = colorable.NewColorableStdout()
  144. }
  145. }
  146. var in *os.File
  147. switch flag.NArg() {
  148. case 0:
  149. in = os.Stdin
  150. // Explicitly silence SIGQUIT, as it is useful to gather the stack dump
  151. // from the piped command..
  152. signals := make(chan os.Signal)
  153. go func() {
  154. for {
  155. <-signals
  156. }
  157. }()
  158. signal.Notify(signals, os.Interrupt, syscall.SIGQUIT)
  159. case 1:
  160. // Do not handle SIGQUIT when passed a file to process.
  161. name := flag.Arg(0)
  162. if in, err = os.Open(name); err != nil {
  163. return fmt.Errorf("did you mean to specify a valid stack dump file name? %s", err)
  164. }
  165. defer in.Close()
  166. default:
  167. return errors.New("pipe from stdin or specify a single file")
  168. }
  169. return process(in, out, p, s, *fullPath, *parse, *rebase, *html, filter, match)
  170. }