debug.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Copyright 2015 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 api
  17. import (
  18. "fmt"
  19. "strings"
  20. "time"
  21. "github.com/ethereum/ethash"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/core/vm"
  24. "github.com/ethereum/go-ethereum/eth"
  25. "github.com/ethereum/go-ethereum/rlp"
  26. "github.com/ethereum/go-ethereum/rpc/codec"
  27. "github.com/ethereum/go-ethereum/rpc/shared"
  28. "github.com/ethereum/go-ethereum/xeth"
  29. "github.com/rcrowley/go-metrics"
  30. )
  31. const (
  32. DebugApiVersion = "1.0"
  33. )
  34. var (
  35. // mapping between methods and handlers
  36. DebugMapping = map[string]debughandler{
  37. "debug_dumpBlock": (*debugApi).DumpBlock,
  38. "debug_getBlockRlp": (*debugApi).GetBlockRlp,
  39. "debug_printBlock": (*debugApi).PrintBlock,
  40. "debug_processBlock": (*debugApi).ProcessBlock,
  41. "debug_seedHash": (*debugApi).SeedHash,
  42. "debug_setHead": (*debugApi).SetHead,
  43. "debug_metrics": (*debugApi).Metrics,
  44. }
  45. )
  46. // debug callback handler
  47. type debughandler func(*debugApi, *shared.Request) (interface{}, error)
  48. // admin api provider
  49. type debugApi struct {
  50. xeth *xeth.XEth
  51. ethereum *eth.Ethereum
  52. methods map[string]debughandler
  53. codec codec.ApiCoder
  54. }
  55. // create a new debug api instance
  56. func NewDebugApi(xeth *xeth.XEth, ethereum *eth.Ethereum, coder codec.Codec) *debugApi {
  57. return &debugApi{
  58. xeth: xeth,
  59. ethereum: ethereum,
  60. methods: DebugMapping,
  61. codec: coder.New(nil),
  62. }
  63. }
  64. // collection with supported methods
  65. func (self *debugApi) Methods() []string {
  66. methods := make([]string, len(self.methods))
  67. i := 0
  68. for k := range self.methods {
  69. methods[i] = k
  70. i++
  71. }
  72. return methods
  73. }
  74. // Execute given request
  75. func (self *debugApi) Execute(req *shared.Request) (interface{}, error) {
  76. if callback, ok := self.methods[req.Method]; ok {
  77. return callback(self, req)
  78. }
  79. return nil, &shared.NotImplementedError{req.Method}
  80. }
  81. func (self *debugApi) Name() string {
  82. return shared.DebugApiName
  83. }
  84. func (self *debugApi) ApiVersion() string {
  85. return DebugApiVersion
  86. }
  87. func (self *debugApi) PrintBlock(req *shared.Request) (interface{}, error) {
  88. args := new(BlockNumArg)
  89. if err := self.codec.Decode(req.Params, &args); err != nil {
  90. return nil, shared.NewDecodeParamError(err.Error())
  91. }
  92. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  93. return fmt.Sprintf("%s", block), nil
  94. }
  95. func (self *debugApi) DumpBlock(req *shared.Request) (interface{}, error) {
  96. args := new(BlockNumArg)
  97. if err := self.codec.Decode(req.Params, &args); err != nil {
  98. return nil, shared.NewDecodeParamError(err.Error())
  99. }
  100. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  101. if block == nil {
  102. return nil, fmt.Errorf("block #%d not found", args.BlockNumber)
  103. }
  104. stateDb, err := state.New(block.Root(), self.ethereum.ChainDb())
  105. if err != nil {
  106. return nil, err
  107. }
  108. return stateDb.RawDump(), nil
  109. }
  110. func (self *debugApi) GetBlockRlp(req *shared.Request) (interface{}, error) {
  111. args := new(BlockNumArg)
  112. if err := self.codec.Decode(req.Params, &args); err != nil {
  113. return nil, shared.NewDecodeParamError(err.Error())
  114. }
  115. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  116. if block == nil {
  117. return nil, fmt.Errorf("block #%d not found", args.BlockNumber)
  118. }
  119. encoded, err := rlp.EncodeToBytes(block)
  120. return fmt.Sprintf("%x", encoded), err
  121. }
  122. func (self *debugApi) SetHead(req *shared.Request) (interface{}, error) {
  123. args := new(BlockNumArg)
  124. if err := self.codec.Decode(req.Params, &args); err != nil {
  125. return nil, shared.NewDecodeParamError(err.Error())
  126. }
  127. self.ethereum.BlockChain().SetHead(uint64(args.BlockNumber))
  128. return nil, nil
  129. }
  130. func (self *debugApi) ProcessBlock(req *shared.Request) (interface{}, error) {
  131. args := new(BlockNumArg)
  132. if err := self.codec.Decode(req.Params, &args); err != nil {
  133. return nil, shared.NewDecodeParamError(err.Error())
  134. }
  135. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  136. if block == nil {
  137. return nil, fmt.Errorf("block #%d not found", args.BlockNumber)
  138. }
  139. old := vm.Debug
  140. defer func() { vm.Debug = old }()
  141. vm.Debug = true
  142. _, err := self.ethereum.BlockProcessor().RetryProcess(block)
  143. if err == nil {
  144. return true, nil
  145. }
  146. return false, err
  147. }
  148. func (self *debugApi) SeedHash(req *shared.Request) (interface{}, error) {
  149. args := new(BlockNumArg)
  150. if err := self.codec.Decode(req.Params, &args); err != nil {
  151. return nil, shared.NewDecodeParamError(err.Error())
  152. }
  153. if hash, err := ethash.GetSeedHash(uint64(args.BlockNumber)); err == nil {
  154. return fmt.Sprintf("0x%x", hash), nil
  155. } else {
  156. return nil, err
  157. }
  158. }
  159. func (self *debugApi) Metrics(req *shared.Request) (interface{}, error) {
  160. args := new(MetricsArgs)
  161. if err := self.codec.Decode(req.Params, &args); err != nil {
  162. return nil, shared.NewDecodeParamError(err.Error())
  163. }
  164. // Create a rate formatter
  165. units := []string{"", "K", "M", "G", "T", "E", "P"}
  166. round := func(value float64, prec int) string {
  167. unit := 0
  168. for value >= 1000 {
  169. unit, value, prec = unit+1, value/1000, 2
  170. }
  171. return fmt.Sprintf(fmt.Sprintf("%%.%df%s", prec, units[unit]), value)
  172. }
  173. format := func(total float64, rate float64) string {
  174. return fmt.Sprintf("%s (%s/s)", round(total, 0), round(rate, 2))
  175. }
  176. // Iterate over all the metrics, and just dump for now
  177. counters := make(map[string]interface{})
  178. metrics.DefaultRegistry.Each(func(name string, metric interface{}) {
  179. // Create or retrieve the counter hierarchy for this metric
  180. root, parts := counters, strings.Split(name, "/")
  181. for _, part := range parts[:len(parts)-1] {
  182. if _, ok := root[part]; !ok {
  183. root[part] = make(map[string]interface{})
  184. }
  185. root = root[part].(map[string]interface{})
  186. }
  187. name = parts[len(parts)-1]
  188. // Fill the counter with the metric details, formatting if requested
  189. if args.Raw {
  190. switch metric := metric.(type) {
  191. case metrics.Meter:
  192. root[name] = map[string]interface{}{
  193. "AvgRate01Min": metric.Rate1(),
  194. "AvgRate05Min": metric.Rate5(),
  195. "AvgRate15Min": metric.Rate15(),
  196. "MeanRate": metric.RateMean(),
  197. "Overall": float64(metric.Count()),
  198. }
  199. case metrics.Timer:
  200. root[name] = map[string]interface{}{
  201. "AvgRate01Min": metric.Rate1(),
  202. "AvgRate05Min": metric.Rate5(),
  203. "AvgRate15Min": metric.Rate15(),
  204. "MeanRate": metric.RateMean(),
  205. "Overall": float64(metric.Count()),
  206. "Percentiles": map[string]interface{}{
  207. "5": metric.Percentile(0.05),
  208. "20": metric.Percentile(0.2),
  209. "50": metric.Percentile(0.5),
  210. "80": metric.Percentile(0.8),
  211. "95": metric.Percentile(0.95),
  212. },
  213. }
  214. default:
  215. root[name] = "Unknown metric type"
  216. }
  217. } else {
  218. switch metric := metric.(type) {
  219. case metrics.Meter:
  220. root[name] = map[string]interface{}{
  221. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  222. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  223. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  224. "Overall": format(float64(metric.Count()), metric.RateMean()),
  225. }
  226. case metrics.Timer:
  227. root[name] = map[string]interface{}{
  228. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  229. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  230. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  231. "Overall": format(float64(metric.Count()), metric.RateMean()),
  232. "Maximum": time.Duration(metric.Max()).String(),
  233. "Minimum": time.Duration(metric.Min()).String(),
  234. "Percentiles": map[string]interface{}{
  235. "5": time.Duration(metric.Percentile(0.05)).String(),
  236. "20": time.Duration(metric.Percentile(0.2)).String(),
  237. "50": time.Duration(metric.Percentile(0.5)).String(),
  238. "80": time.Duration(metric.Percentile(0.8)).String(),
  239. "95": time.Duration(metric.Percentile(0.95)).String(),
  240. },
  241. }
  242. default:
  243. root[name] = "Unknown metric type"
  244. }
  245. }
  246. })
  247. return counters, nil
  248. }