github.com/ethw3/go-ethereuma@v0.0.0-20221013053120-c14602a4c23c/internal/debug/flags.go (about)

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