api.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 CPU profiling for nsec seconds and writes
  129. // profile data to file. It uses a profile rate of 1 for most accurate
  130. // information. If a different rate is desired, set the rate
  131. // 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. // WriteMemProfile writes an allocation profile to the given file.
  148. // Note that the profiling rate cannot be set through the API,
  149. // it must be set on the command line.
  150. func (*HandlerT) WriteMemProfile(file string) error {
  151. return writeProfile("heap", file)
  152. }
  153. // Stacks returns a printed representation of the stacks of all goroutines.
  154. func (*HandlerT) Stacks() string {
  155. buf := make([]byte, 1024*1024)
  156. buf = buf[:runtime.Stack(buf, true)]
  157. return string(buf)
  158. }
  159. func writeProfile(name, file string) error {
  160. p := pprof.Lookup(name)
  161. log.Info("Writing profile records", "count", p.Count(), "type", name, "dump", file)
  162. f, err := os.Create(expandHome(file))
  163. if err != nil {
  164. return err
  165. }
  166. defer f.Close()
  167. return p.WriteTo(f, 0)
  168. }
  169. // expands home directory in file paths.
  170. // ~someuser/tmp will not be expanded.
  171. func expandHome(p string) string {
  172. if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
  173. home := os.Getenv("HOME")
  174. if home == "" {
  175. if usr, err := user.Current(); err == nil {
  176. home = usr.HomeDir
  177. }
  178. }
  179. if home != "" {
  180. p = home + p[1:]
  181. }
  182. }
  183. return filepath.Clean(p)
  184. }