dashboard.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright 2017 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 dashboard
  17. //go:generate yarn --cwd ./assets install
  18. //go:generate yarn --cwd ./assets build
  19. //go:generate yarn --cwd ./assets js-beautify -f bundle.js.map -r -w 1
  20. //go:generate go-bindata -nometadata -o assets.go -prefix assets -nocompress -pkg dashboard assets/index.html assets/bundle.js assets/bundle.js.map
  21. //go:generate sh -c "sed 's#var _bundleJs#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
  22. //go:generate sh -c "sed 's#var _bundleJsMap#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
  23. //go:generate sh -c "sed 's#var _indexHtml#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
  24. //go:generate gofmt -w -s assets.go
  25. import (
  26. "fmt"
  27. "io"
  28. "net"
  29. "net/http"
  30. "sync"
  31. "sync/atomic"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/eth"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/les"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/p2p"
  38. "github.com/ethereum/go-ethereum/params"
  39. "github.com/ethereum/go-ethereum/rpc"
  40. "github.com/mohae/deepcopy"
  41. "golang.org/x/net/websocket"
  42. )
  43. const (
  44. sampleLimit = 200 // Maximum number of data samples
  45. dataCollectorCount = 4
  46. )
  47. // Dashboard contains the dashboard internals.
  48. type Dashboard struct {
  49. config *Config // Configuration values for the dashboard
  50. listener net.Listener // Network listener listening for dashboard clients
  51. conns map[uint32]*client // Currently live websocket connections
  52. nextConnID uint32 // Next connection id
  53. history *Message // Stored historical data
  54. lock sync.Mutex // Lock protecting the dashboard's internals
  55. chainLock sync.RWMutex // Lock protecting the stored blockchain data
  56. sysLock sync.RWMutex // Lock protecting the stored system data
  57. peerLock sync.RWMutex // Lock protecting the stored peer data
  58. logLock sync.RWMutex // Lock protecting the stored log data
  59. geodb *geoDB // geoip database instance for IP to geographical information conversions
  60. logdir string // Directory containing the log files
  61. quit chan chan error // Channel used for graceful exit
  62. wg sync.WaitGroup // Wait group used to close the data collector threads
  63. peerCh chan p2p.MeteredPeerEvent // Peer event channel.
  64. subPeer event.Subscription // Peer event subscription.
  65. ethServ *eth.Ethereum // Ethereum object serving internals.
  66. lesServ *les.LightEthereum // LightEthereum object serving internals.
  67. }
  68. // client represents active websocket connection with a remote browser.
  69. type client struct {
  70. conn *websocket.Conn // Particular live websocket connection
  71. msg chan *Message // Message queue for the update messages
  72. logger log.Logger // Logger for the particular live websocket connection
  73. }
  74. // New creates a new dashboard instance with the given configuration.
  75. func New(config *Config, ethServ *eth.Ethereum, lesServ *les.LightEthereum, commit string, logdir string) *Dashboard {
  76. // There is a data race between the network layer and the dashboard, which
  77. // can cause some lost peer events, therefore some peers might not appear
  78. // on the dashboard.
  79. // In order to solve this problem, the peer event subscription is registered
  80. // here, before the network layer starts.
  81. peerCh := make(chan p2p.MeteredPeerEvent, p2p.MeteredPeerLimit)
  82. versionMeta := ""
  83. if len(params.VersionMeta) > 0 {
  84. versionMeta = fmt.Sprintf(" (%s)", params.VersionMeta)
  85. }
  86. var genesis common.Hash
  87. if ethServ != nil {
  88. genesis = ethServ.BlockChain().Genesis().Hash()
  89. } else if lesServ != nil {
  90. genesis = lesServ.BlockChain().Genesis().Hash()
  91. }
  92. return &Dashboard{
  93. conns: make(map[uint32]*client),
  94. config: config,
  95. quit: make(chan chan error),
  96. history: &Message{
  97. General: &GeneralMessage{
  98. Commit: commit,
  99. Version: fmt.Sprintf("v%d.%d.%d%s", params.VersionMajor, params.VersionMinor, params.VersionPatch, versionMeta),
  100. Genesis: genesis,
  101. },
  102. System: &SystemMessage{
  103. ActiveMemory: emptyChartEntries(sampleLimit),
  104. VirtualMemory: emptyChartEntries(sampleLimit),
  105. NetworkIngress: emptyChartEntries(sampleLimit),
  106. NetworkEgress: emptyChartEntries(sampleLimit),
  107. ProcessCPU: emptyChartEntries(sampleLimit),
  108. SystemCPU: emptyChartEntries(sampleLimit),
  109. DiskRead: emptyChartEntries(sampleLimit),
  110. DiskWrite: emptyChartEntries(sampleLimit),
  111. },
  112. },
  113. logdir: logdir,
  114. peerCh: peerCh,
  115. subPeer: p2p.SubscribeMeteredPeerEvent(peerCh),
  116. ethServ: ethServ,
  117. lesServ: lesServ,
  118. }
  119. }
  120. // emptyChartEntries returns a ChartEntry array containing limit number of empty samples.
  121. func emptyChartEntries(limit int) ChartEntries {
  122. ce := make(ChartEntries, limit)
  123. for i := 0; i < limit; i++ {
  124. ce[i] = new(ChartEntry)
  125. }
  126. return ce
  127. }
  128. // Protocols implements the node.Service interface.
  129. func (db *Dashboard) Protocols() []p2p.Protocol { return nil }
  130. // APIs implements the node.Service interface.
  131. func (db *Dashboard) APIs() []rpc.API { return nil }
  132. // Start starts the data collection thread and the listening server of the dashboard.
  133. // Implements the node.Service interface.
  134. func (db *Dashboard) Start(server *p2p.Server) error {
  135. log.Info("Starting dashboard", "url", fmt.Sprintf("http://%s:%d", db.config.Host, db.config.Port))
  136. db.wg.Add(dataCollectorCount)
  137. go db.collectChainData()
  138. go db.collectSystemData()
  139. go db.streamLogs()
  140. go db.collectPeerData()
  141. http.HandleFunc("/", db.webHandler)
  142. http.Handle("/api", websocket.Handler(db.apiHandler))
  143. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", db.config.Host, db.config.Port))
  144. if err != nil {
  145. return err
  146. }
  147. db.listener = listener
  148. go func() {
  149. if err := http.Serve(listener, nil); err != http.ErrServerClosed {
  150. log.Warn("Could not accept incoming HTTP connections", "err", err)
  151. }
  152. }()
  153. return nil
  154. }
  155. // Stop stops the data collection thread and the connection listener of the dashboard.
  156. // Implements the node.Service interface.
  157. func (db *Dashboard) Stop() error {
  158. // Close the connection listener.
  159. var errs []error
  160. if err := db.listener.Close(); err != nil {
  161. errs = append(errs, err)
  162. }
  163. // Close the collectors.
  164. errc := make(chan error, dataCollectorCount)
  165. for i := 0; i < dataCollectorCount; i++ {
  166. db.quit <- errc
  167. if err := <-errc; err != nil {
  168. errs = append(errs, err)
  169. }
  170. }
  171. // Close the connections.
  172. db.lock.Lock()
  173. for _, c := range db.conns {
  174. if err := c.conn.Close(); err != nil {
  175. c.logger.Warn("Failed to close connection", "err", err)
  176. }
  177. }
  178. db.lock.Unlock()
  179. // Wait until every goroutine terminates.
  180. db.wg.Wait()
  181. log.Info("Dashboard stopped")
  182. var err error
  183. if len(errs) > 0 {
  184. err = fmt.Errorf("%v", errs)
  185. }
  186. return err
  187. }
  188. // webHandler handles all non-api requests, simply flattening and returning the dashboard website.
  189. func (db *Dashboard) webHandler(w http.ResponseWriter, r *http.Request) {
  190. log.Debug("Request", "URL", r.URL)
  191. path := r.URL.String()
  192. if path == "/" {
  193. path = "/index.html"
  194. }
  195. blob, err := Asset(path[1:])
  196. if err != nil {
  197. log.Warn("Failed to load the asset", "path", path, "err", err)
  198. http.Error(w, "not found", http.StatusNotFound)
  199. return
  200. }
  201. w.Write(blob)
  202. }
  203. // apiHandler handles requests for the dashboard.
  204. func (db *Dashboard) apiHandler(conn *websocket.Conn) {
  205. id := atomic.AddUint32(&db.nextConnID, 1)
  206. client := &client{
  207. conn: conn,
  208. msg: make(chan *Message, 128),
  209. logger: log.New("id", id),
  210. }
  211. done := make(chan struct{})
  212. // Start listening for messages to send.
  213. db.wg.Add(1)
  214. go func() {
  215. defer db.wg.Done()
  216. for {
  217. select {
  218. case <-done:
  219. return
  220. case msg := <-client.msg:
  221. if err := websocket.JSON.Send(client.conn, msg); err != nil {
  222. client.logger.Warn("Failed to send the message", "msg", msg, "err", err)
  223. client.conn.Close()
  224. return
  225. }
  226. }
  227. }
  228. }()
  229. // Send the past data.
  230. db.chainLock.RLock()
  231. db.sysLock.RLock()
  232. db.peerLock.RLock()
  233. db.logLock.RLock()
  234. h := deepcopy.Copy(db.history).(*Message)
  235. db.chainLock.RUnlock()
  236. db.sysLock.RUnlock()
  237. db.peerLock.RUnlock()
  238. db.logLock.RUnlock()
  239. // Start tracking the connection and drop at connection loss.
  240. db.lock.Lock()
  241. client.msg <- h
  242. db.conns[id] = client
  243. db.lock.Unlock()
  244. defer func() {
  245. db.lock.Lock()
  246. delete(db.conns, id)
  247. db.lock.Unlock()
  248. }()
  249. for {
  250. r := new(Request)
  251. if err := websocket.JSON.Receive(conn, r); err != nil {
  252. if err != io.EOF {
  253. client.logger.Warn("Failed to receive request", "err", err)
  254. }
  255. close(done)
  256. return
  257. }
  258. if r.Logs != nil {
  259. db.handleLogRequest(r.Logs, client)
  260. }
  261. }
  262. }
  263. // sendToAll sends the given message to the active dashboards.
  264. func (db *Dashboard) sendToAll(msg *Message) {
  265. db.lock.Lock()
  266. for _, c := range db.conns {
  267. select {
  268. case c.msg <- msg:
  269. default:
  270. c.conn.Close()
  271. }
  272. }
  273. db.lock.Unlock()
  274. }