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