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