github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/internal/debug/api.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 interfaces Go runtime debugging facilities.
    18  // This package is mostly glue code making these facilities available
    19  // through the CLI and RPC subsystem. If you want to use them from Go code,
    20  // use package runtime instead.
    21  package debug
    22  
    23  import (
    24  	"bytes"
    25  	"errors"
    26  	"io"
    27  	"os"
    28  	"os/user"
    29  	"path/filepath"
    30  	"regexp"
    31  	"runtime"
    32  	"runtime/debug"
    33  	"runtime/pprof"
    34  	"strings"
    35  	"sync"
    36  	"time"
    37  
    38  	"github.com/hashicorp/go-bexpr"
    39  
    40  	"github.com/scroll-tech/go-ethereum/log"
    41  )
    42  
    43  // Handler is the global debugging handler.
    44  var Handler = new(HandlerT)
    45  
    46  // HandlerT implements the debugging API.
    47  // Do not create values of this type, use the one
    48  // in the Handler variable instead.
    49  type HandlerT struct {
    50  	mu        sync.Mutex
    51  	cpuW      io.WriteCloser
    52  	cpuFile   string
    53  	traceW    io.WriteCloser
    54  	traceFile string
    55  }
    56  
    57  // Verbosity sets the log verbosity ceiling. The verbosity of individual packages
    58  // and source files can be raised using Vmodule.
    59  func (*HandlerT) Verbosity(level int) {
    60  	glogger.Verbosity(log.Lvl(level))
    61  }
    62  
    63  // Vmodule sets the log verbosity pattern. See package log for details on the
    64  // pattern syntax.
    65  func (*HandlerT) Vmodule(pattern string) error {
    66  	return glogger.Vmodule(pattern)
    67  }
    68  
    69  // BacktraceAt sets the log backtrace location. See package log for details on
    70  // the pattern syntax.
    71  func (*HandlerT) BacktraceAt(location string) error {
    72  	return glogger.BacktraceAt(location)
    73  }
    74  
    75  // MemStats returns detailed runtime memory statistics.
    76  func (*HandlerT) MemStats() *runtime.MemStats {
    77  	s := new(runtime.MemStats)
    78  	runtime.ReadMemStats(s)
    79  	return s
    80  }
    81  
    82  // GcStats returns GC statistics.
    83  func (*HandlerT) GcStats() *debug.GCStats {
    84  	s := new(debug.GCStats)
    85  	debug.ReadGCStats(s)
    86  	return s
    87  }
    88  
    89  // CpuProfile turns on CPU profiling for nsec seconds and writes
    90  // profile data to file.
    91  func (h *HandlerT) CpuProfile(file string, nsec uint) error {
    92  	if err := h.StartCPUProfile(file); err != nil {
    93  		return err
    94  	}
    95  	time.Sleep(time.Duration(nsec) * time.Second)
    96  	h.StopCPUProfile()
    97  	return nil
    98  }
    99  
   100  // StartCPUProfile turns on CPU profiling, writing to the given file.
   101  func (h *HandlerT) StartCPUProfile(file string) error {
   102  	h.mu.Lock()
   103  	defer h.mu.Unlock()
   104  	if h.cpuW != nil {
   105  		return errors.New("CPU profiling already in progress")
   106  	}
   107  	f, err := os.Create(expandHome(file))
   108  	if err != nil {
   109  		return err
   110  	}
   111  	if err := pprof.StartCPUProfile(f); err != nil {
   112  		f.Close()
   113  		return err
   114  	}
   115  	h.cpuW = f
   116  	h.cpuFile = file
   117  	log.Info("CPU profiling started", "dump", h.cpuFile)
   118  	return nil
   119  }
   120  
   121  // StopCPUProfile stops an ongoing CPU profile.
   122  func (h *HandlerT) StopCPUProfile() error {
   123  	h.mu.Lock()
   124  	defer h.mu.Unlock()
   125  	pprof.StopCPUProfile()
   126  	if h.cpuW == nil {
   127  		return errors.New("CPU profiling not in progress")
   128  	}
   129  	log.Info("Done writing CPU profile", "dump", h.cpuFile)
   130  	h.cpuW.Close()
   131  	h.cpuW = nil
   132  	h.cpuFile = ""
   133  	return nil
   134  }
   135  
   136  // GoTrace turns on tracing for nsec seconds and writes
   137  // trace data to file.
   138  func (h *HandlerT) GoTrace(file string, nsec uint) error {
   139  	if err := h.StartGoTrace(file); err != nil {
   140  		return err
   141  	}
   142  	time.Sleep(time.Duration(nsec) * time.Second)
   143  	h.StopGoTrace()
   144  	return nil
   145  }
   146  
   147  // BlockProfile turns on goroutine profiling for nsec seconds and writes profile data to
   148  // file. It uses a profile rate of 1 for most accurate information. If a different rate is
   149  // desired, set the rate and write the profile manually.
   150  func (*HandlerT) BlockProfile(file string, nsec uint) error {
   151  	runtime.SetBlockProfileRate(1)
   152  	time.Sleep(time.Duration(nsec) * time.Second)
   153  	defer runtime.SetBlockProfileRate(0)
   154  	return writeProfile("block", file)
   155  }
   156  
   157  // SetBlockProfileRate sets the rate of goroutine block profile data collection.
   158  // rate 0 disables block profiling.
   159  func (*HandlerT) SetBlockProfileRate(rate int) {
   160  	runtime.SetBlockProfileRate(rate)
   161  }
   162  
   163  // WriteBlockProfile writes a goroutine blocking profile to the given file.
   164  func (*HandlerT) WriteBlockProfile(file string) error {
   165  	return writeProfile("block", file)
   166  }
   167  
   168  // MutexProfile turns on mutex profiling for nsec seconds and writes profile data to file.
   169  // It uses a profile rate of 1 for most accurate information. If a different rate is
   170  // desired, set the rate and write the profile manually.
   171  func (*HandlerT) MutexProfile(file string, nsec uint) error {
   172  	runtime.SetMutexProfileFraction(1)
   173  	time.Sleep(time.Duration(nsec) * time.Second)
   174  	defer runtime.SetMutexProfileFraction(0)
   175  	return writeProfile("mutex", file)
   176  }
   177  
   178  // SetMutexProfileFraction sets the rate of mutex profiling.
   179  func (*HandlerT) SetMutexProfileFraction(rate int) {
   180  	runtime.SetMutexProfileFraction(rate)
   181  }
   182  
   183  // WriteMutexProfile writes a goroutine blocking profile to the given file.
   184  func (*HandlerT) WriteMutexProfile(file string) error {
   185  	return writeProfile("mutex", file)
   186  }
   187  
   188  // WriteMemProfile writes an allocation profile to the given file.
   189  // Note that the profiling rate cannot be set through the API,
   190  // it must be set on the command line.
   191  func (*HandlerT) WriteMemProfile(file string) error {
   192  	return writeProfile("heap", file)
   193  }
   194  
   195  // Stacks returns a printed representation of the stacks of all goroutines. It
   196  // also permits the following optional filters to be used:
   197  //   - filter: boolean expression of packages to filter for
   198  func (*HandlerT) Stacks(filter *string) string {
   199  	buf := new(bytes.Buffer)
   200  	pprof.Lookup("goroutine").WriteTo(buf, 2)
   201  
   202  	// If any filtering was requested, execute them now
   203  	if filter != nil && len(*filter) > 0 {
   204  		expanded := *filter
   205  
   206  		// The input filter is a logical expression of package names. Transform
   207  		// it into a proper boolean expression that can be fed into a parser and
   208  		// interpreter:
   209  		//
   210  		// E.g. (eth || snap) && !p2p -> (eth in Value || snap in Value) && p2p not in Value
   211  		expanded = regexp.MustCompile(`[:/\.A-Za-z0-9_-]+`).ReplaceAllString(expanded, "`$0` in Value")
   212  		expanded = regexp.MustCompile("!(`[:/\\.A-Za-z0-9_-]+`)").ReplaceAllString(expanded, "$1 not")
   213  		expanded = strings.Replace(expanded, "||", "or", -1)
   214  		expanded = strings.Replace(expanded, "&&", "and", -1)
   215  		log.Info("Expanded filter expression", "filter", *filter, "expanded", expanded)
   216  
   217  		expr, err := bexpr.CreateEvaluator(expanded)
   218  		if err != nil {
   219  			log.Error("Failed to parse filter expression", "expanded", expanded, "err", err)
   220  			return ""
   221  		}
   222  		// Split the goroutine dump into segments and filter each
   223  		dump := buf.String()
   224  		buf.Reset()
   225  
   226  		for _, trace := range strings.Split(dump, "\n\n") {
   227  			if ok, _ := expr.Evaluate(map[string]string{"Value": trace}); ok {
   228  				buf.WriteString(trace)
   229  				buf.WriteString("\n\n")
   230  			}
   231  		}
   232  	}
   233  	return buf.String()
   234  }
   235  
   236  // FreeOSMemory forces a garbage collection.
   237  func (*HandlerT) FreeOSMemory() {
   238  	debug.FreeOSMemory()
   239  }
   240  
   241  // SetGCPercent sets the garbage collection target percentage. It returns the previous
   242  // setting. A negative value disables GC.
   243  func (*HandlerT) SetGCPercent(v int) int {
   244  	return debug.SetGCPercent(v)
   245  }
   246  
   247  func writeProfile(name, file string) error {
   248  	p := pprof.Lookup(name)
   249  	log.Info("Writing profile records", "count", p.Count(), "type", name, "dump", file)
   250  	f, err := os.Create(expandHome(file))
   251  	if err != nil {
   252  		return err
   253  	}
   254  	defer f.Close()
   255  	return p.WriteTo(f, 0)
   256  }
   257  
   258  // expands home directory in file paths.
   259  // ~someuser/tmp will not be expanded.
   260  func expandHome(p string) string {
   261  	if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
   262  		home := os.Getenv("HOME")
   263  		if home == "" {
   264  			if usr, err := user.Current(); err == nil {
   265  				home = usr.HomeDir
   266  			}
   267  		}
   268  		if home != "" {
   269  			p = home + p[1:]
   270  		}
   271  	}
   272  	return filepath.Clean(p)
   273  }