flags.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package debug
  17. import (
  18. "fmt"
  19. "io"
  20. "net/http"
  21. _ "net/http/pprof" // nolint: gosec
  22. "os"
  23. "runtime"
  24. "github.com/ethereum/go-ethereum/internal/flags"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/metrics"
  27. "github.com/ethereum/go-ethereum/metrics/exp"
  28. "github.com/fjl/memsize/memsizeui"
  29. "github.com/mattn/go-colorable"
  30. "github.com/mattn/go-isatty"
  31. "github.com/urfave/cli/v2"
  32. )
  33. var Memsize memsizeui.Handler
  34. var (
  35. verbosityFlag = &cli.IntFlag{
  36. Name: "verbosity",
  37. Usage: "Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail",
  38. Value: 3,
  39. Category: flags.LoggingCategory,
  40. }
  41. vmoduleFlag = &cli.StringFlag{
  42. Name: "vmodule",
  43. Usage: "Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)",
  44. Value: "",
  45. Category: flags.LoggingCategory,
  46. }
  47. logjsonFlag = &cli.BoolFlag{
  48. Name: "log.json",
  49. Usage: "Format logs with JSON",
  50. Category: flags.LoggingCategory,
  51. }
  52. backtraceAtFlag = &cli.StringFlag{
  53. Name: "log.backtrace",
  54. Usage: "Request a stack trace at a specific logging statement (e.g. \"block.go:271\")",
  55. Value: "",
  56. Category: flags.LoggingCategory,
  57. }
  58. debugFlag = &cli.BoolFlag{
  59. Name: "log.debug",
  60. Usage: "Prepends log messages with call-site location (file and line number)",
  61. Category: flags.LoggingCategory,
  62. }
  63. pprofFlag = &cli.BoolFlag{
  64. Name: "pprof",
  65. Usage: "Enable the pprof HTTP server",
  66. Category: flags.LoggingCategory,
  67. }
  68. pprofPortFlag = &cli.IntFlag{
  69. Name: "pprof.port",
  70. Usage: "pprof HTTP server listening port",
  71. Value: 6060,
  72. Category: flags.LoggingCategory,
  73. }
  74. pprofAddrFlag = &cli.StringFlag{
  75. Name: "pprof.addr",
  76. Usage: "pprof HTTP server listening interface",
  77. Value: "127.0.0.1",
  78. Category: flags.LoggingCategory,
  79. }
  80. memprofilerateFlag = &cli.IntFlag{
  81. Name: "pprof.memprofilerate",
  82. Usage: "Turn on memory profiling with the given rate",
  83. Value: runtime.MemProfileRate,
  84. Category: flags.LoggingCategory,
  85. }
  86. blockprofilerateFlag = &cli.IntFlag{
  87. Name: "pprof.blockprofilerate",
  88. Usage: "Turn on block profiling with the given rate",
  89. Category: flags.LoggingCategory,
  90. }
  91. cpuprofileFlag = &cli.StringFlag{
  92. Name: "pprof.cpuprofile",
  93. Usage: "Write CPU profile to the given file",
  94. Category: flags.LoggingCategory,
  95. }
  96. traceFlag = &cli.StringFlag{
  97. Name: "trace",
  98. Usage: "Write execution trace to the given file",
  99. Category: flags.LoggingCategory,
  100. }
  101. )
  102. // Flags holds all command-line flags required for debugging.
  103. var Flags = []cli.Flag{
  104. verbosityFlag,
  105. vmoduleFlag,
  106. logjsonFlag,
  107. backtraceAtFlag,
  108. debugFlag,
  109. pprofFlag,
  110. pprofAddrFlag,
  111. pprofPortFlag,
  112. memprofilerateFlag,
  113. blockprofilerateFlag,
  114. cpuprofileFlag,
  115. traceFlag,
  116. }
  117. var glogger *log.GlogHandler
  118. func init() {
  119. glogger = log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
  120. glogger.Verbosity(log.LvlInfo)
  121. log.Root().SetHandler(glogger)
  122. }
  123. // Setup initializes profiling and logging based on the CLI flags.
  124. // It should be called as early as possible in the program.
  125. func Setup(ctx *cli.Context) error {
  126. var ostream log.Handler
  127. output := io.Writer(os.Stderr)
  128. if ctx.Bool(logjsonFlag.Name) {
  129. ostream = log.StreamHandler(output, log.JSONFormat())
  130. } else {
  131. usecolor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"
  132. if usecolor {
  133. output = colorable.NewColorableStderr()
  134. }
  135. ostream = log.StreamHandler(output, log.TerminalFormat(usecolor))
  136. }
  137. glogger.SetHandler(ostream)
  138. // logging
  139. verbosity := ctx.Int(verbosityFlag.Name)
  140. glogger.Verbosity(log.Lvl(verbosity))
  141. vmodule := ctx.String(vmoduleFlag.Name)
  142. glogger.Vmodule(vmodule)
  143. debug := ctx.Bool(debugFlag.Name)
  144. if ctx.IsSet(debugFlag.Name) {
  145. debug = ctx.Bool(debugFlag.Name)
  146. }
  147. log.PrintOrigins(debug)
  148. backtrace := ctx.String(backtraceAtFlag.Name)
  149. glogger.BacktraceAt(backtrace)
  150. log.Root().SetHandler(glogger)
  151. // profiling, tracing
  152. runtime.MemProfileRate = memprofilerateFlag.Value
  153. if ctx.IsSet(memprofilerateFlag.Name) {
  154. runtime.MemProfileRate = ctx.Int(memprofilerateFlag.Name)
  155. }
  156. blockProfileRate := ctx.Int(blockprofilerateFlag.Name)
  157. Handler.SetBlockProfileRate(blockProfileRate)
  158. if traceFile := ctx.String(traceFlag.Name); traceFile != "" {
  159. if err := Handler.StartGoTrace(traceFile); err != nil {
  160. return err
  161. }
  162. }
  163. if cpuFile := ctx.String(cpuprofileFlag.Name); cpuFile != "" {
  164. if err := Handler.StartCPUProfile(cpuFile); err != nil {
  165. return err
  166. }
  167. }
  168. // pprof server
  169. if ctx.Bool(pprofFlag.Name) {
  170. listenHost := ctx.String(pprofAddrFlag.Name)
  171. port := ctx.Int(pprofPortFlag.Name)
  172. address := fmt.Sprintf("%s:%d", listenHost, port)
  173. // This context value ("metrics.addr") represents the utils.MetricsHTTPFlag.Name.
  174. // It cannot be imported because it will cause a cyclical dependency.
  175. StartPProf(address, !ctx.IsSet("metrics.addr"))
  176. }
  177. return nil
  178. }
  179. func StartPProf(address string, withMetrics bool) {
  180. // Hook go-metrics into expvar on any /debug/metrics request, load all vars
  181. // from the registry into expvar, and execute regular expvar handler.
  182. if withMetrics {
  183. exp.Exp(metrics.DefaultRegistry)
  184. }
  185. http.Handle("/memsize/", http.StripPrefix("/memsize", &Memsize))
  186. log.Info("Starting pprof server", "addr", fmt.Sprintf("http://%s/debug/pprof", address))
  187. go func() {
  188. if err := http.ListenAndServe(address, nil); err != nil {
  189. log.Error("Failure in running pprof server", "err", err)
  190. }
  191. }()
  192. }
  193. // Exit stops all running profiles, flushing their output to the
  194. // respective file.
  195. func Exit() {
  196. Handler.StopCPUProfile()
  197. Handler.StopGoTrace()
  198. }