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