api.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "fmt"
  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(fmt.Sprint("CPU profiling started, writing to", 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(fmt.Sprint("done writing CPU profile to", 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 CPU profiling for nsec seconds and writes
  130. // profile data to file. It uses a profile rate of 1 for most accurate
  131. // information. If a different rate is desired, set the rate
  132. // and write the profile manually.
  133. func (*HandlerT) BlockProfile(file string, nsec uint) error {
  134. runtime.SetBlockProfileRate(1)
  135. time.Sleep(time.Duration(nsec) * time.Second)
  136. defer runtime.SetBlockProfileRate(0)
  137. return writeProfile("block", file)
  138. }
  139. // SetBlockProfileRate sets the rate of goroutine block profile data collection.
  140. // rate 0 disables block profiling.
  141. func (*HandlerT) SetBlockProfileRate(rate int) {
  142. runtime.SetBlockProfileRate(rate)
  143. }
  144. // WriteBlockProfile writes a goroutine blocking profile to the given file.
  145. func (*HandlerT) WriteBlockProfile(file string) error {
  146. return writeProfile("block", file)
  147. }
  148. // WriteMemProfile writes an allocation profile to the given file.
  149. // Note that the profiling rate cannot be set through the API,
  150. // it must be set on the command line.
  151. func (*HandlerT) WriteMemProfile(file string) error {
  152. return writeProfile("heap", file)
  153. }
  154. // Stacks returns a printed representation of the stacks of all goroutines.
  155. func (*HandlerT) Stacks() string {
  156. buf := make([]byte, 1024*1024)
  157. buf = buf[:runtime.Stack(buf, true)]
  158. return string(buf)
  159. }
  160. func writeProfile(name, file string) error {
  161. p := pprof.Lookup(name)
  162. log.Info(fmt.Sprintf("writing %d %s profile records to %s", p.Count(), name, file))
  163. f, err := os.Create(expandHome(file))
  164. if err != nil {
  165. return err
  166. }
  167. defer f.Close()
  168. return p.WriteTo(f, 0)
  169. }
  170. // expands home directory in file paths.
  171. // ~someuser/tmp will not be expanded.
  172. func expandHome(p string) string {
  173. if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
  174. home := os.Getenv("HOME")
  175. if home == "" {
  176. if usr, err := user.Current(); err == nil {
  177. home = usr.HomeDir
  178. }
  179. }
  180. if home != "" {
  181. p = home + p[1:]
  182. }
  183. }
  184. return filepath.Clean(p)
  185. }