api.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. "errors"
  23. "io"
  24. "os"
  25. "os/user"
  26. "path/filepath"
  27. "runtime"
  28. "runtime/debug"
  29. "runtime/pprof"
  30. "strings"
  31. "sync"
  32. "time"
  33. "github.com/ethereum/go-ethereum/log"
  34. )
  35. // Handler is the global debugging handler.
  36. var Handler = new(HandlerT)
  37. // HandlerT implements the debugging API.
  38. // Do not create values of this type, use the one
  39. // in the Handler variable instead.
  40. type HandlerT struct {
  41. mu sync.Mutex
  42. cpuW io.WriteCloser
  43. cpuFile string
  44. traceW io.WriteCloser
  45. traceFile string
  46. }
  47. // Verbosity sets the log verbosity ceiling. The verbosity of individual packages
  48. // and source files can be raised using Vmodule.
  49. func (*HandlerT) Verbosity(level int) {
  50. glogger.Verbosity(log.Lvl(level))
  51. }
  52. // Vmodule sets the log verbosity pattern. See package log for details on the
  53. // pattern syntax.
  54. func (*HandlerT) Vmodule(pattern string) error {
  55. return glogger.Vmodule(pattern)
  56. }
  57. // BacktraceAt sets the log backtrace location. See package log for details on
  58. // the pattern syntax.
  59. func (*HandlerT) BacktraceAt(location string) error {
  60. return glogger.BacktraceAt(location)
  61. }
  62. // MemStats returns detailed runtime memory statistics.
  63. func (*HandlerT) MemStats() *runtime.MemStats {
  64. s := new(runtime.MemStats)
  65. runtime.ReadMemStats(s)
  66. return s
  67. }
  68. // GcStats returns GC statistics.
  69. func (*HandlerT) GcStats() *debug.GCStats {
  70. s := new(debug.GCStats)
  71. debug.ReadGCStats(s)
  72. return s
  73. }
  74. // CpuProfile turns on CPU profiling for nsec seconds and writes
  75. // profile data to file.
  76. func (h *HandlerT) CpuProfile(file string, nsec uint) error {
  77. if err := h.StartCPUProfile(file); err != nil {
  78. return err
  79. }
  80. time.Sleep(time.Duration(nsec) * time.Second)
  81. h.StopCPUProfile()
  82. return nil
  83. }
  84. // StartCPUProfile turns on CPU profiling, writing to the given file.
  85. func (h *HandlerT) StartCPUProfile(file string) error {
  86. h.mu.Lock()
  87. defer h.mu.Unlock()
  88. if h.cpuW != nil {
  89. return errors.New("CPU profiling already in progress")
  90. }
  91. f, err := os.Create(expandHome(file))
  92. if err != nil {
  93. return err
  94. }
  95. if err := pprof.StartCPUProfile(f); err != nil {
  96. f.Close()
  97. return err
  98. }
  99. h.cpuW = f
  100. h.cpuFile = file
  101. log.Info("CPU profiling started", "dump", h.cpuFile)
  102. return nil
  103. }
  104. // StopCPUProfile stops an ongoing CPU profile.
  105. func (h *HandlerT) StopCPUProfile() error {
  106. h.mu.Lock()
  107. defer h.mu.Unlock()
  108. pprof.StopCPUProfile()
  109. if h.cpuW == nil {
  110. return errors.New("CPU profiling not in progress")
  111. }
  112. log.Info("Done writing CPU profile", "dump", h.cpuFile)
  113. h.cpuW.Close()
  114. h.cpuW = nil
  115. h.cpuFile = ""
  116. return nil
  117. }
  118. // GoTrace turns on tracing for nsec seconds and writes
  119. // trace data to file.
  120. func (h *HandlerT) GoTrace(file string, nsec uint) error {
  121. if err := h.StartGoTrace(file); err != nil {
  122. return err
  123. }
  124. time.Sleep(time.Duration(nsec) * time.Second)
  125. h.StopGoTrace()
  126. return nil
  127. }
  128. // BlockProfile turns on goroutine profiling for nsec seconds and writes profile data to
  129. // file. It uses a profile rate of 1 for most accurate information. If a different rate is
  130. // desired, set the rate and write the profile manually.
  131. func (*HandlerT) BlockProfile(file string, nsec uint) error {
  132. runtime.SetBlockProfileRate(1)
  133. time.Sleep(time.Duration(nsec) * time.Second)
  134. defer runtime.SetBlockProfileRate(0)
  135. return writeProfile("block", file)
  136. }
  137. // SetBlockProfileRate sets the rate of goroutine block profile data collection.
  138. // rate 0 disables block profiling.
  139. func (*HandlerT) SetBlockProfileRate(rate int) {
  140. runtime.SetBlockProfileRate(rate)
  141. }
  142. // WriteBlockProfile writes a goroutine blocking profile to the given file.
  143. func (*HandlerT) WriteBlockProfile(file string) error {
  144. return writeProfile("block", file)
  145. }
  146. // MutexProfile turns on mutex profiling for nsec seconds and writes profile data to file.
  147. // It uses a profile rate of 1 for most accurate information. If a different rate is
  148. // desired, set the rate and write the profile manually.
  149. func (*HandlerT) MutexProfile(file string, nsec uint) error {
  150. runtime.SetMutexProfileFraction(1)
  151. time.Sleep(time.Duration(nsec) * time.Second)
  152. defer runtime.SetMutexProfileFraction(0)
  153. return writeProfile("mutex", file)
  154. }
  155. // SetMutexProfileFraction sets the rate of mutex profiling.
  156. func (*HandlerT) SetMutexProfileFraction(rate int) {
  157. runtime.SetMutexProfileFraction(rate)
  158. }
  159. // WriteMutexProfile writes a goroutine blocking profile to the given file.
  160. func (*HandlerT) WriteMutexProfile(file string) error {
  161. return writeProfile("mutex", file)
  162. }
  163. // WriteMemProfile writes an allocation profile to the given file.
  164. // Note that the profiling rate cannot be set through the API,
  165. // it must be set on the command line.
  166. func (*HandlerT) WriteMemProfile(file string) error {
  167. return writeProfile("heap", file)
  168. }
  169. // Stacks returns a printed representation of the stacks of all goroutines.
  170. func (*HandlerT) Stacks() string {
  171. buf := make([]byte, 1024*1024)
  172. buf = buf[:runtime.Stack(buf, true)]
  173. return string(buf)
  174. }
  175. // FreeOSMemory returns unused memory to the OS.
  176. func (*HandlerT) FreeOSMemory() {
  177. debug.FreeOSMemory()
  178. }
  179. // SetGCPercent sets the garbage collection target percentage. It returns the previous
  180. // setting. A negative value disables GC.
  181. func (*HandlerT) SetGCPercent(v int) int {
  182. return debug.SetGCPercent(v)
  183. }
  184. func writeProfile(name, file string) error {
  185. p := pprof.Lookup(name)
  186. log.Info("Writing profile records", "count", p.Count(), "type", name, "dump", file)
  187. f, err := os.Create(expandHome(file))
  188. if err != nil {
  189. return err
  190. }
  191. defer f.Close()
  192. return p.WriteTo(f, 0)
  193. }
  194. // expands home directory in file paths.
  195. // ~someuser/tmp will not be expanded.
  196. func expandHome(p string) string {
  197. if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
  198. home := os.Getenv("HOME")
  199. if home == "" {
  200. if usr, err := user.Current(); err == nil {
  201. home = usr.HomeDir
  202. }
  203. }
  204. if home != "" {
  205. p = home + p[1:]
  206. }
  207. }
  208. return filepath.Clean(p)
  209. }