github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/internal/debug/flags.go (about)

     1  // Copyright 2016 The go-simplechain Authors
     2  // This file is part of the go-simplechain library.
     3  //
     4  // The go-simplechain 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-simplechain 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-simplechain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package debug
    18  
    19  import (
    20  	"fmt"
    21  	"github.com/mattn/go-isatty"
    22  	"io"
    23  	"net/http"
    24  	_ "net/http/pprof"
    25  	"os"
    26  	"runtime"
    27  
    28  	"github.com/bigzoro/my_simplechain/log"
    29  	"github.com/bigzoro/my_simplechain/metrics"
    30  	"github.com/bigzoro/my_simplechain/metrics/exp"
    31  	"github.com/fjl/memsize/memsizeui"
    32  	colorable "github.com/mattn/go-colorable"
    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  	backtraceAtFlag = cli.StringFlag{
    50  		Name:  "backtrace",
    51  		Usage: "Request a stack trace at a specific logging statement (e.g. \"block.go:271\")",
    52  		Value: "",
    53  	}
    54  	debugFlag = cli.BoolFlag{
    55  		Name:  "debug",
    56  		Usage: "Prepends log messages with call-site location (file and line number)",
    57  	}
    58  	pprofFlag = cli.BoolFlag{
    59  		Name:  "pprof",
    60  		Usage: "Enable the pprof HTTP server",
    61  	}
    62  	pprofPortFlag = cli.IntFlag{
    63  		Name:  "pprofport",
    64  		Usage: "pprof HTTP server listening port",
    65  		Value: 6060,
    66  	}
    67  	pprofAddrFlag = cli.StringFlag{
    68  		Name:  "pprofaddr",
    69  		Usage: "pprof HTTP server listening interface",
    70  		Value: "127.0.0.1",
    71  	}
    72  	memprofilerateFlag = cli.IntFlag{
    73  		Name:  "memprofilerate",
    74  		Usage: "Turn on memory profiling with the given rate",
    75  		Value: runtime.MemProfileRate,
    76  	}
    77  	blockprofilerateFlag = cli.IntFlag{
    78  		Name:  "blockprofilerate",
    79  		Usage: "Turn on block profiling with the given rate",
    80  	}
    81  	cpuprofileFlag = cli.StringFlag{
    82  		Name:  "cpuprofile",
    83  		Usage: "Write CPU profile to the given file",
    84  	}
    85  	traceFlag = cli.StringFlag{
    86  		Name:  "trace",
    87  		Usage: "Write execution trace to the given file",
    88  	}
    89  	logDirFlag = cli.StringFlag{
    90  		Name:  "log.dir",
    91  		Usage: "the file log write to",
    92  	}
    93  	logToFileFlag = cli.BoolFlag{
    94  		Name:  "log.to.file.enable",
    95  		Usage: "switch for log output to file",
    96  	}
    97  )
    98  
    99  // Flags holds all command-line flags required for debugging.
   100  var Flags = []cli.Flag{
   101  	verbosityFlag, vmoduleFlag, backtraceAtFlag, debugFlag,
   102  	pprofFlag, pprofAddrFlag, pprofPortFlag,
   103  	memprofilerateFlag, blockprofilerateFlag, cpuprofileFlag, traceFlag,
   104  	logDirFlag, logToFileFlag,
   105  }
   106  
   107  var (
   108  	ostream log.Handler
   109  	glogger *log.GlogHandler
   110  )
   111  
   112  func init() {
   113  	usecolor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"
   114  	output := io.Writer(os.Stderr)
   115  	if usecolor {
   116  		output = colorable.NewColorableStderr()
   117  	}
   118  	ostream = log.StreamHandler(output, log.TerminalFormat(usecolor))
   119  	glogger = log.NewGlogHandler(ostream)
   120  }
   121  
   122  // Setup initializes profiling and logging based on the CLI flags.
   123  // It should be called as early as possible in the program.
   124  func Setup(ctx *cli.Context, logdir string) error {
   125  	// logging
   126  	log.PrintOrigins(ctx.GlobalBool(debugFlag.Name))
   127  	if ctx.GlobalBool(logToFileFlag.Name) {
   128  		dir := ctx.GlobalString(logDirFlag.Name)
   129  		if dir != "" {
   130  			logdir = dir
   131  		}
   132  	}
   133  	if logdir != "" {
   134  		rfh, err := log.RotatingFileHandler(
   135  			logdir,
   136  			262144, //256k
   137  			log.JSONFormatOrderedEx(false, true),
   138  		)
   139  		if err != nil {
   140  			return err
   141  		}
   142  		glogger.SetHandler(log.MultiHandler(ostream, rfh))
   143  	}
   144  	glogger.Verbosity(log.Lvl(ctx.GlobalInt(verbosityFlag.Name)))
   145  	glogger.Vmodule(ctx.GlobalString(vmoduleFlag.Name))
   146  	glogger.BacktraceAt(ctx.GlobalString(backtraceAtFlag.Name))
   147  	log.Root().SetHandler(glogger)
   148  
   149  	// profiling, tracing
   150  	runtime.MemProfileRate = ctx.GlobalInt(memprofilerateFlag.Name)
   151  	Handler.SetBlockProfileRate(ctx.GlobalInt(blockprofilerateFlag.Name))
   152  	if traceFile := ctx.GlobalString(traceFlag.Name); traceFile != "" {
   153  		if err := Handler.StartGoTrace(traceFile); err != nil {
   154  			return err
   155  		}
   156  	}
   157  	if cpuFile := ctx.GlobalString(cpuprofileFlag.Name); cpuFile != "" {
   158  		if err := Handler.StartCPUProfile(cpuFile); err != nil {
   159  			return err
   160  		}
   161  	}
   162  
   163  	// pprof server
   164  	if ctx.GlobalBool(pprofFlag.Name) {
   165  		address := fmt.Sprintf("%s:%d", ctx.GlobalString(pprofAddrFlag.Name), ctx.GlobalInt(pprofPortFlag.Name))
   166  		StartPProf(address)
   167  	}
   168  	return nil
   169  }
   170  
   171  func StartPProf(address string) {
   172  	// Hook go-metrics into expvar on any /debug/metrics request, load all vars
   173  	// from the registry into expvar, and execute regular expvar handler.
   174  	exp.Exp(metrics.DefaultRegistry)
   175  	http.Handle("/memsize/", http.StripPrefix("/memsize", &Memsize))
   176  	log.Info("Starting pprof server", "addr", fmt.Sprintf("http://%s/debug/pprof", address))
   177  	go func() {
   178  		if err := http.ListenAndServe(address, nil); err != nil {
   179  			log.Error("Failure in running pprof server", "err", err)
   180  		}
   181  	}()
   182  }
   183  
   184  // Exit stops all running profiles, flushing their output to the
   185  // respective file.
   186  func Exit() {
   187  	Handler.StopCPUProfile()
   188  	Handler.StopGoTrace()
   189  }