api.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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/pprof"
  29. "strings"
  30. "sync"
  31. "time"
  32. "github.com/ethereum/go-ethereum/logger"
  33. "github.com/ethereum/go-ethereum/logger/glog"
  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 glog verbosity floor.
  48. // The verbosity of individual packages and source files
  49. // can be raised using Vmodule.
  50. func (*HandlerT) Verbosity(level int) {
  51. glog.SetV(level)
  52. }
  53. // Vmodule sets the glog verbosity pattern. See package
  54. // glog for details on pattern syntax.
  55. func (*HandlerT) Vmodule(pattern string) error {
  56. return glog.GetVModule().Set(pattern)
  57. }
  58. // BacktraceAt sets the glog backtrace location.
  59. // See package glog for details on pattern syntax.
  60. func (*HandlerT) BacktraceAt(location string) error {
  61. return glog.GetTraceLocation().Set(location)
  62. }
  63. // CpuProfile turns on CPU profiling for nsec seconds and writes
  64. // profile data to file.
  65. func (h *HandlerT) CpuProfile(file string, nsec uint) error {
  66. if err := h.StartCPUProfile(file); err != nil {
  67. return err
  68. }
  69. time.Sleep(time.Duration(nsec) * time.Second)
  70. h.StopCPUProfile()
  71. return nil
  72. }
  73. // StartCPUProfile turns on CPU profiling, writing to the given file.
  74. func (h *HandlerT) StartCPUProfile(file string) error {
  75. h.mu.Lock()
  76. defer h.mu.Unlock()
  77. if h.cpuW != nil {
  78. return errors.New("CPU profiling already in progress")
  79. }
  80. f, err := os.Create(expandHome(file))
  81. if err != nil {
  82. return err
  83. }
  84. if err := pprof.StartCPUProfile(f); err != nil {
  85. f.Close()
  86. return err
  87. }
  88. h.cpuW = f
  89. h.cpuFile = file
  90. glog.V(logger.Info).Infoln("CPU profiling started, writing to", h.cpuFile)
  91. return nil
  92. }
  93. // StopCPUProfile stops an ongoing CPU profile.
  94. func (h *HandlerT) StopCPUProfile() error {
  95. h.mu.Lock()
  96. defer h.mu.Unlock()
  97. pprof.StopCPUProfile()
  98. if h.cpuW == nil {
  99. return errors.New("CPU profiling not in progress")
  100. }
  101. glog.V(logger.Info).Infoln("done writing CPU profile to", h.cpuFile)
  102. h.cpuW.Close()
  103. h.cpuW = nil
  104. h.cpuFile = ""
  105. return nil
  106. }
  107. // Trace turns on tracing for nsec seconds and writes
  108. // trace data to file.
  109. func (h *HandlerT) Trace(file string, nsec uint) error {
  110. if err := h.StartTrace(file); err != nil {
  111. return err
  112. }
  113. time.Sleep(time.Duration(nsec) * time.Second)
  114. h.StopTrace()
  115. return nil
  116. }
  117. // BlockProfile turns on CPU profiling for nsec seconds and writes
  118. // profile data to file. It uses a profile rate of 1 for most accurate
  119. // information. If a different rate is desired, set the rate
  120. // and write the profile manually.
  121. func (*HandlerT) BlockProfile(file string, nsec uint) error {
  122. runtime.SetBlockProfileRate(1)
  123. time.Sleep(time.Duration(nsec) * time.Second)
  124. defer runtime.SetBlockProfileRate(0)
  125. return writeProfile("block", file)
  126. }
  127. // SetBlockProfileRate sets the rate of goroutine block profile data collection.
  128. // rate 0 disables block profiling.
  129. func (*HandlerT) SetBlockProfileRate(rate int) {
  130. runtime.SetBlockProfileRate(rate)
  131. }
  132. // WriteBlockProfile writes a goroutine blocking profile to the given file.
  133. func (*HandlerT) WriteBlockProfile(file string) error {
  134. return writeProfile("block", file)
  135. }
  136. // WriteMemProfile writes an allocation profile to the given file.
  137. // Note that the profiling rate cannot be set through the API,
  138. // it must be set on the command line.
  139. func (*HandlerT) WriteMemProfile(file string) error {
  140. return writeProfile("heap", file)
  141. }
  142. // Stacks returns a printed representation of the stacks of all goroutines.
  143. func (*HandlerT) Stacks() string {
  144. buf := make([]byte, 1024*1024)
  145. buf = buf[:runtime.Stack(buf, true)]
  146. return string(buf)
  147. }
  148. func writeProfile(name, file string) error {
  149. p := pprof.Lookup(name)
  150. glog.V(logger.Info).Infof("writing %d %s profile records to %s", p.Count(), name, file)
  151. f, err := os.Create(expandHome(file))
  152. if err != nil {
  153. return err
  154. }
  155. defer f.Close()
  156. return p.WriteTo(f, 0)
  157. }
  158. // expands home directory in file paths.
  159. // ~someuser/tmp will not be expanded.
  160. func expandHome(p string) string {
  161. if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
  162. home := os.Getenv("HOME")
  163. if home == "" {
  164. if usr, err := user.Current(); err == nil {
  165. home = usr.HomeDir
  166. }
  167. }
  168. if home != "" {
  169. p = home + p[1:]
  170. }
  171. }
  172. return filepath.Clean(p)
  173. }