api.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 node
  17. import (
  18. "fmt"
  19. "strings"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/p2p"
  24. "github.com/ethereum/go-ethereum/p2p/discover"
  25. "github.com/rcrowley/go-metrics"
  26. )
  27. // PrivateAdminAPI is the collection of administrative API methods exposed only
  28. // over a secure RPC channel.
  29. type PrivateAdminAPI struct {
  30. node *Node // Node interfaced by this API
  31. }
  32. // NewPrivateAdminAPI creates a new API definition for the private admin methods
  33. // of the node itself.
  34. func NewPrivateAdminAPI(node *Node) *PrivateAdminAPI {
  35. return &PrivateAdminAPI{node: node}
  36. }
  37. // AddPeer requests connecting to a remote node, and also maintaining the new
  38. // connection at all times, even reconnecting if it is lost.
  39. func (api *PrivateAdminAPI) AddPeer(url string) (bool, error) {
  40. // Make sure the server is running, fail otherwise
  41. server := api.node.Server()
  42. if server == nil {
  43. return false, ErrNodeStopped
  44. }
  45. // Try to add the url as a static peer and return
  46. node, err := discover.ParseNode(url)
  47. if err != nil {
  48. return false, fmt.Errorf("invalid enode: %v", err)
  49. }
  50. server.AddPeer(node)
  51. return true, nil
  52. }
  53. // StartRPC starts the HTTP RPC API server.
  54. func (api *PrivateAdminAPI) StartRPC(host string, port int, cors string, apis string) (bool, error) {
  55. api.node.lock.Lock()
  56. defer api.node.lock.Unlock()
  57. if api.node.httpHandler != nil {
  58. return false, fmt.Errorf("HTTP RPC already running on %s", api.node.httpEndpoint)
  59. }
  60. if err := api.node.startHTTP(fmt.Sprintf("%s:%d", host, port), api.node.rpcAPIs, strings.Split(apis, ","), cors); err != nil {
  61. return false, err
  62. }
  63. return true, nil
  64. }
  65. // StopRPC terminates an already running HTTP RPC API endpoint.
  66. func (api *PrivateAdminAPI) StopRPC() (bool, error) {
  67. api.node.lock.Lock()
  68. defer api.node.lock.Unlock()
  69. if api.node.httpHandler == nil {
  70. return false, fmt.Errorf("HTTP RPC not running")
  71. }
  72. api.node.stopHTTP()
  73. return true, nil
  74. }
  75. // StartWS starts the websocket RPC API server.
  76. func (api *PrivateAdminAPI) StartWS(host string, port int, cors string, apis string) (bool, error) {
  77. api.node.lock.Lock()
  78. defer api.node.lock.Unlock()
  79. if api.node.wsHandler != nil {
  80. return false, fmt.Errorf("WebSocket RPC already running on %s", api.node.wsEndpoint)
  81. }
  82. if err := api.node.startWS(fmt.Sprintf("%s:%d", host, port), api.node.rpcAPIs, strings.Split(apis, ","), cors); err != nil {
  83. return false, err
  84. }
  85. return true, nil
  86. }
  87. // StopRPC terminates an already running websocket RPC API endpoint.
  88. func (api *PrivateAdminAPI) StopWS() (bool, error) {
  89. api.node.lock.Lock()
  90. defer api.node.lock.Unlock()
  91. if api.node.wsHandler == nil {
  92. return false, fmt.Errorf("WebSocket RPC not running")
  93. }
  94. api.node.stopWS()
  95. return true, nil
  96. }
  97. // PublicAdminAPI is the collection of administrative API methods exposed over
  98. // both secure and unsecure RPC channels.
  99. type PublicAdminAPI struct {
  100. node *Node // Node interfaced by this API
  101. }
  102. // NewPublicAdminAPI creates a new API definition for the public admin methods
  103. // of the node itself.
  104. func NewPublicAdminAPI(node *Node) *PublicAdminAPI {
  105. return &PublicAdminAPI{node: node}
  106. }
  107. // Peers retrieves all the information we know about each individual peer at the
  108. // protocol granularity.
  109. func (api *PublicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  110. server := api.node.Server()
  111. if server == nil {
  112. return nil, ErrNodeStopped
  113. }
  114. return server.PeersInfo(), nil
  115. }
  116. // NodeInfo retrieves all the information we know about the host node at the
  117. // protocol granularity.
  118. func (api *PublicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
  119. server := api.node.Server()
  120. if server == nil {
  121. return nil, ErrNodeStopped
  122. }
  123. return server.NodeInfo(), nil
  124. }
  125. // Datadir retrieves the current data directory the node is using.
  126. func (api *PublicAdminAPI) Datadir() string {
  127. return api.node.DataDir()
  128. }
  129. // PublicDebugAPI is the collection of debugging related API methods exposed over
  130. // both secure and unsecure RPC channels.
  131. type PublicDebugAPI struct {
  132. node *Node // Node interfaced by this API
  133. }
  134. // NewPublicDebugAPI creates a new API definition for the public debug methods
  135. // of the node itself.
  136. func NewPublicDebugAPI(node *Node) *PublicDebugAPI {
  137. return &PublicDebugAPI{node: node}
  138. }
  139. // Metrics retrieves all the known system metric collected by the node.
  140. func (api *PublicDebugAPI) Metrics(raw bool) (map[string]interface{}, error) {
  141. // Create a rate formatter
  142. units := []string{"", "K", "M", "G", "T", "E", "P"}
  143. round := func(value float64, prec int) string {
  144. unit := 0
  145. for value >= 1000 {
  146. unit, value, prec = unit+1, value/1000, 2
  147. }
  148. return fmt.Sprintf(fmt.Sprintf("%%.%df%s", prec, units[unit]), value)
  149. }
  150. format := func(total float64, rate float64) string {
  151. return fmt.Sprintf("%s (%s/s)", round(total, 0), round(rate, 2))
  152. }
  153. // Iterate over all the metrics, and just dump for now
  154. counters := make(map[string]interface{})
  155. metrics.DefaultRegistry.Each(func(name string, metric interface{}) {
  156. // Create or retrieve the counter hierarchy for this metric
  157. root, parts := counters, strings.Split(name, "/")
  158. for _, part := range parts[:len(parts)-1] {
  159. if _, ok := root[part]; !ok {
  160. root[part] = make(map[string]interface{})
  161. }
  162. root = root[part].(map[string]interface{})
  163. }
  164. name = parts[len(parts)-1]
  165. // Fill the counter with the metric details, formatting if requested
  166. if raw {
  167. switch metric := metric.(type) {
  168. case metrics.Meter:
  169. root[name] = map[string]interface{}{
  170. "AvgRate01Min": metric.Rate1(),
  171. "AvgRate05Min": metric.Rate5(),
  172. "AvgRate15Min": metric.Rate15(),
  173. "MeanRate": metric.RateMean(),
  174. "Overall": float64(metric.Count()),
  175. }
  176. case metrics.Timer:
  177. root[name] = map[string]interface{}{
  178. "AvgRate01Min": metric.Rate1(),
  179. "AvgRate05Min": metric.Rate5(),
  180. "AvgRate15Min": metric.Rate15(),
  181. "MeanRate": metric.RateMean(),
  182. "Overall": float64(metric.Count()),
  183. "Percentiles": map[string]interface{}{
  184. "5": metric.Percentile(0.05),
  185. "20": metric.Percentile(0.2),
  186. "50": metric.Percentile(0.5),
  187. "80": metric.Percentile(0.8),
  188. "95": metric.Percentile(0.95),
  189. },
  190. }
  191. default:
  192. root[name] = "Unknown metric type"
  193. }
  194. } else {
  195. switch metric := metric.(type) {
  196. case metrics.Meter:
  197. root[name] = map[string]interface{}{
  198. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  199. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  200. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  201. "Overall": format(float64(metric.Count()), metric.RateMean()),
  202. }
  203. case metrics.Timer:
  204. root[name] = map[string]interface{}{
  205. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  206. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  207. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  208. "Overall": format(float64(metric.Count()), metric.RateMean()),
  209. "Maximum": time.Duration(metric.Max()).String(),
  210. "Minimum": time.Duration(metric.Min()).String(),
  211. "Percentiles": map[string]interface{}{
  212. "5": time.Duration(metric.Percentile(0.05)).String(),
  213. "20": time.Duration(metric.Percentile(0.2)).String(),
  214. "50": time.Duration(metric.Percentile(0.5)).String(),
  215. "80": time.Duration(metric.Percentile(0.8)).String(),
  216. "95": time.Duration(metric.Percentile(0.95)).String(),
  217. },
  218. }
  219. default:
  220. root[name] = "Unknown metric type"
  221. }
  222. }
  223. })
  224. return counters, nil
  225. }
  226. // PublicWeb3API offers helper utils
  227. type PublicWeb3API struct {
  228. stack *Node
  229. }
  230. // NewPublicWeb3API creates a new Web3Service instance
  231. func NewPublicWeb3API(stack *Node) *PublicWeb3API {
  232. return &PublicWeb3API{stack}
  233. }
  234. // ClientVersion returns the node name
  235. func (s *PublicWeb3API) ClientVersion() string {
  236. return s.stack.Server().Name
  237. }
  238. // Sha3 applies the ethereum sha3 implementation on the input.
  239. // It assumes the input is hex encoded.
  240. func (s *PublicWeb3API) Sha3(input string) string {
  241. return common.ToHex(crypto.Keccak256(common.FromHex(input)))
  242. }