flags.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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"
  22. "os"
  23. "runtime"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/metrics"
  26. "github.com/ethereum/go-ethereum/metrics/exp"
  27. "github.com/fjl/memsize/memsizeui"
  28. "github.com/mattn/go-colorable"
  29. "github.com/mattn/go-isatty"
  30. "gopkg.in/urfave/cli.v1"
  31. )
  32. var Memsize memsizeui.Handler
  33. var (
  34. verbosityFlag = cli.IntFlag{
  35. Name: "verbosity",
  36. Usage: "Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail",
  37. Value: 3,
  38. }
  39. vmoduleFlag = cli.StringFlag{
  40. Name: "vmodule",
  41. Usage: "Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)",
  42. Value: "",
  43. }
  44. logjsonFlag = cli.BoolFlag{
  45. Name: "log.json",
  46. Usage: "Format logs with JSON",
  47. }
  48. backtraceAtFlag = cli.StringFlag{
  49. Name: "log.backtrace",
  50. Usage: "Request a stack trace at a specific logging statement (e.g. \"block.go:271\")",
  51. Value: "",
  52. }
  53. debugFlag = cli.BoolFlag{
  54. Name: "log.debug",
  55. Usage: "Prepends log messages with call-site location (file and line number)",
  56. }
  57. pprofFlag = cli.BoolFlag{
  58. Name: "pprof",
  59. Usage: "Enable the pprof HTTP server",
  60. }
  61. pprofPortFlag = cli.IntFlag{
  62. Name: "pprof.port",
  63. Usage: "pprof HTTP server listening port",
  64. Value: 6060,
  65. }
  66. pprofAddrFlag = cli.StringFlag{
  67. Name: "pprof.addr",
  68. Usage: "pprof HTTP server listening interface",
  69. Value: "127.0.0.1",
  70. }
  71. memprofilerateFlag = cli.IntFlag{
  72. Name: "pprof.memprofilerate",
  73. Usage: "Turn on memory profiling with the given rate",
  74. Value: runtime.MemProfileRate,
  75. }
  76. blockprofilerateFlag = cli.IntFlag{
  77. Name: "pprof.blockprofilerate",
  78. Usage: "Turn on block profiling with the given rate",
  79. }
  80. cpuprofileFlag = cli.StringFlag{
  81. Name: "pprof.cpuprofile",
  82. Usage: "Write CPU profile to the given file",
  83. }
  84. traceFlag = cli.StringFlag{
  85. Name: "trace",
  86. Usage: "Write execution trace to the given file",
  87. }
  88. // (Deprecated April 2020)
  89. legacyPprofPortFlag = cli.IntFlag{
  90. Name: "pprofport",
  91. Usage: "pprof HTTP server listening port (deprecated, use --pprof.port)",
  92. Value: 6060,
  93. }
  94. legacyPprofAddrFlag = cli.StringFlag{
  95. Name: "pprofaddr",
  96. Usage: "pprof HTTP server listening interface (deprecated, use --pprof.addr)",
  97. Value: "127.0.0.1",
  98. }
  99. legacyMemprofilerateFlag = cli.IntFlag{
  100. Name: "memprofilerate",
  101. Usage: "Turn on memory profiling with the given rate (deprecated, use --pprof.memprofilerate)",
  102. Value: runtime.MemProfileRate,
  103. }
  104. legacyBlockprofilerateFlag = cli.IntFlag{
  105. Name: "blockprofilerate",
  106. Usage: "Turn on block profiling with the given rate (deprecated, use --pprof.blockprofilerate)",
  107. }
  108. legacyCpuprofileFlag = cli.StringFlag{
  109. Name: "cpuprofile",
  110. Usage: "Write CPU profile to the given file (deprecated, use --pprof.cpuprofile)",
  111. }
  112. legacyBacktraceAtFlag = cli.StringFlag{
  113. Name: "backtrace",
  114. Usage: "Request a stack trace at a specific logging statement (e.g. \"block.go:271\") (deprecated, use --log.backtrace)",
  115. Value: "",
  116. }
  117. legacyDebugFlag = cli.BoolFlag{
  118. Name: "debug",
  119. Usage: "Prepends log messages with call-site location (file and line number) (deprecated, use --log.debug)",
  120. }
  121. )
  122. // Flags holds all command-line flags required for debugging.
  123. var Flags = []cli.Flag{
  124. verbosityFlag,
  125. vmoduleFlag,
  126. logjsonFlag,
  127. backtraceAtFlag,
  128. debugFlag,
  129. pprofFlag,
  130. pprofAddrFlag,
  131. pprofPortFlag,
  132. memprofilerateFlag,
  133. blockprofilerateFlag,
  134. cpuprofileFlag,
  135. traceFlag,
  136. }
  137. // This is the list of deprecated debugging flags.
  138. var DeprecatedFlags = []cli.Flag{
  139. legacyPprofPortFlag,
  140. legacyPprofAddrFlag,
  141. legacyMemprofilerateFlag,
  142. legacyBlockprofilerateFlag,
  143. legacyCpuprofileFlag,
  144. legacyBacktraceAtFlag,
  145. legacyDebugFlag,
  146. }
  147. var glogger *log.GlogHandler
  148. func init() {
  149. glogger = log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
  150. glogger.Verbosity(log.LvlInfo)
  151. log.Root().SetHandler(glogger)
  152. }
  153. // Setup initializes profiling and logging based on the CLI flags.
  154. // It should be called as early as possible in the program.
  155. func Setup(ctx *cli.Context) error {
  156. var ostream log.Handler
  157. output := io.Writer(os.Stderr)
  158. if ctx.GlobalBool(logjsonFlag.Name) {
  159. ostream = log.StreamHandler(output, log.JSONFormat())
  160. } else {
  161. usecolor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"
  162. if usecolor {
  163. output = colorable.NewColorableStderr()
  164. }
  165. ostream = log.StreamHandler(output, log.TerminalFormat(usecolor))
  166. }
  167. glogger.SetHandler(ostream)
  168. // logging
  169. verbosity := ctx.GlobalInt(verbosityFlag.Name)
  170. glogger.Verbosity(log.Lvl(verbosity))
  171. vmodule := ctx.GlobalString(vmoduleFlag.Name)
  172. glogger.Vmodule(vmodule)
  173. debug := ctx.GlobalBool(debugFlag.Name)
  174. if ctx.GlobalIsSet(legacyDebugFlag.Name) {
  175. debug = ctx.GlobalBool(legacyDebugFlag.Name)
  176. log.Warn("The flag --debug is deprecated and will be removed in the future, please use --log.debug")
  177. }
  178. if ctx.GlobalIsSet(debugFlag.Name) {
  179. debug = ctx.GlobalBool(debugFlag.Name)
  180. }
  181. log.PrintOrigins(debug)
  182. backtrace := ctx.GlobalString(backtraceAtFlag.Name)
  183. if b := ctx.GlobalString(legacyBacktraceAtFlag.Name); b != "" {
  184. backtrace = b
  185. log.Warn("The flag --backtrace is deprecated and will be removed in the future, please use --log.backtrace")
  186. }
  187. if b := ctx.GlobalString(backtraceAtFlag.Name); b != "" {
  188. backtrace = b
  189. }
  190. glogger.BacktraceAt(backtrace)
  191. log.Root().SetHandler(glogger)
  192. // profiling, tracing
  193. runtime.MemProfileRate = memprofilerateFlag.Value
  194. if ctx.GlobalIsSet(legacyMemprofilerateFlag.Name) {
  195. runtime.MemProfileRate = ctx.GlobalInt(legacyMemprofilerateFlag.Name)
  196. log.Warn("The flag --memprofilerate is deprecated and will be removed in the future, please use --pprof.memprofilerate")
  197. }
  198. if ctx.GlobalIsSet(memprofilerateFlag.Name) {
  199. runtime.MemProfileRate = ctx.GlobalInt(memprofilerateFlag.Name)
  200. }
  201. blockProfileRate := blockprofilerateFlag.Value
  202. if ctx.GlobalIsSet(legacyBlockprofilerateFlag.Name) {
  203. blockProfileRate = ctx.GlobalInt(legacyBlockprofilerateFlag.Name)
  204. log.Warn("The flag --blockprofilerate is deprecated and will be removed in the future, please use --pprof.blockprofilerate")
  205. }
  206. if ctx.GlobalIsSet(blockprofilerateFlag.Name) {
  207. blockProfileRate = ctx.GlobalInt(blockprofilerateFlag.Name)
  208. }
  209. Handler.SetBlockProfileRate(blockProfileRate)
  210. if traceFile := ctx.GlobalString(traceFlag.Name); traceFile != "" {
  211. if err := Handler.StartGoTrace(traceFile); err != nil {
  212. return err
  213. }
  214. }
  215. if cpuFile := ctx.GlobalString(cpuprofileFlag.Name); cpuFile != "" {
  216. if err := Handler.StartCPUProfile(cpuFile); err != nil {
  217. return err
  218. }
  219. }
  220. // pprof server
  221. if ctx.GlobalBool(pprofFlag.Name) {
  222. listenHost := ctx.GlobalString(pprofAddrFlag.Name)
  223. port := ctx.GlobalInt(pprofPortFlag.Name)
  224. address := fmt.Sprintf("%s:%d", listenHost, port)
  225. // This context value ("metrics.addr") represents the utils.MetricsHTTPFlag.Name.
  226. // It cannot be imported because it will cause a cyclical dependency.
  227. StartPProf(address, !ctx.GlobalIsSet("metrics.addr"))
  228. }
  229. return nil
  230. }
  231. func StartPProf(address string, withMetrics bool) {
  232. // Hook go-metrics into expvar on any /debug/metrics request, load all vars
  233. // from the registry into expvar, and execute regular expvar handler.
  234. if withMetrics {
  235. exp.Exp(metrics.DefaultRegistry)
  236. }
  237. http.Handle("/memsize/", http.StripPrefix("/memsize", &Memsize))
  238. log.Info("Starting pprof server", "addr", fmt.Sprintf("http://%s/debug/pprof", address))
  239. go func() {
  240. if err := http.ListenAndServe(address, nil); err != nil {
  241. log.Error("Failure in running pprof server", "err", err)
  242. }
  243. }()
  244. }
  245. // Exit stops all running profiles, flushing their output to the
  246. // respective file.
  247. func Exit() {
  248. Handler.StopCPUProfile()
  249. Handler.StopGoTrace()
  250. }