dashboard.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. "net"
  28. "net/http"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "io"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/p2p"
  35. "github.com/ethereum/go-ethereum/params"
  36. "github.com/ethereum/go-ethereum/rpc"
  37. "github.com/mohae/deepcopy"
  38. "golang.org/x/net/websocket"
  39. )
  40. const (
  41. sampleLimit = 200 // Maximum number of data samples
  42. )
  43. // Dashboard contains the dashboard internals.
  44. type Dashboard struct {
  45. config *Config // Configuration values for the dashboard
  46. listener net.Listener // Network listener listening for dashboard clients
  47. conns map[uint32]*client // Currently live websocket connections
  48. nextConnID uint32 // Next connection id
  49. history *Message // Stored historical data
  50. lock sync.Mutex // Lock protecting the dashboard's internals
  51. sysLock sync.RWMutex // Lock protecting the stored system data
  52. peerLock sync.RWMutex // Lock protecting the stored peer data
  53. logLock sync.RWMutex // Lock protecting the stored log data
  54. geodb *geoDB // geoip database instance for IP to geographical information conversions
  55. logdir string // Directory containing the log files
  56. quit chan chan error // Channel used for graceful exit
  57. wg sync.WaitGroup // Wait group used to close the data collector threads
  58. }
  59. // client represents active websocket connection with a remote browser.
  60. type client struct {
  61. conn *websocket.Conn // Particular live websocket connection
  62. msg chan *Message // Message queue for the update messages
  63. logger log.Logger // Logger for the particular live websocket connection
  64. }
  65. // New creates a new dashboard instance with the given configuration.
  66. func New(config *Config, commit string, logdir string) *Dashboard {
  67. now := time.Now()
  68. versionMeta := ""
  69. if len(params.VersionMeta) > 0 {
  70. versionMeta = fmt.Sprintf(" (%s)", params.VersionMeta)
  71. }
  72. return &Dashboard{
  73. conns: make(map[uint32]*client),
  74. config: config,
  75. quit: make(chan chan error),
  76. history: &Message{
  77. General: &GeneralMessage{
  78. Commit: commit,
  79. Version: fmt.Sprintf("v%d.%d.%d%s", params.VersionMajor, params.VersionMinor, params.VersionPatch, versionMeta),
  80. },
  81. System: &SystemMessage{
  82. ActiveMemory: emptyChartEntries(now, sampleLimit),
  83. VirtualMemory: emptyChartEntries(now, sampleLimit),
  84. NetworkIngress: emptyChartEntries(now, sampleLimit),
  85. NetworkEgress: emptyChartEntries(now, sampleLimit),
  86. ProcessCPU: emptyChartEntries(now, sampleLimit),
  87. SystemCPU: emptyChartEntries(now, sampleLimit),
  88. DiskRead: emptyChartEntries(now, sampleLimit),
  89. DiskWrite: emptyChartEntries(now, sampleLimit),
  90. },
  91. },
  92. logdir: logdir,
  93. }
  94. }
  95. // emptyChartEntries returns a ChartEntry array containing limit number of empty samples.
  96. func emptyChartEntries(t time.Time, limit int) ChartEntries {
  97. ce := make(ChartEntries, limit)
  98. for i := 0; i < limit; i++ {
  99. ce[i] = new(ChartEntry)
  100. }
  101. return ce
  102. }
  103. // Protocols implements the node.Service interface.
  104. func (db *Dashboard) Protocols() []p2p.Protocol { return nil }
  105. // APIs implements the node.Service interface.
  106. func (db *Dashboard) APIs() []rpc.API { return nil }
  107. // Start starts the data collection thread and the listening server of the dashboard.
  108. // Implements the node.Service interface.
  109. func (db *Dashboard) Start(server *p2p.Server) error {
  110. log.Info("Starting dashboard", "url", fmt.Sprintf("http://%s:%d", db.config.Host, db.config.Port))
  111. db.wg.Add(3)
  112. go db.collectSystemData()
  113. go db.streamLogs()
  114. go db.collectPeerData()
  115. http.HandleFunc("/", db.webHandler)
  116. http.Handle("/api", websocket.Handler(db.apiHandler))
  117. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", db.config.Host, db.config.Port))
  118. if err != nil {
  119. return err
  120. }
  121. db.listener = listener
  122. go http.Serve(listener, nil)
  123. return nil
  124. }
  125. // Stop stops the data collection thread and the connection listener of the dashboard.
  126. // Implements the node.Service interface.
  127. func (db *Dashboard) Stop() error {
  128. // Close the connection listener.
  129. var errs []error
  130. if err := db.listener.Close(); err != nil {
  131. errs = append(errs, err)
  132. }
  133. // Close the collectors.
  134. errc := make(chan error, 1)
  135. for i := 0; i < 3; i++ {
  136. db.quit <- errc
  137. if err := <-errc; err != nil {
  138. errs = append(errs, err)
  139. }
  140. }
  141. // Close the connections.
  142. db.lock.Lock()
  143. for _, c := range db.conns {
  144. if err := c.conn.Close(); err != nil {
  145. c.logger.Warn("Failed to close connection", "err", err)
  146. }
  147. }
  148. db.lock.Unlock()
  149. // Wait until every goroutine terminates.
  150. db.wg.Wait()
  151. log.Info("Dashboard stopped")
  152. var err error
  153. if len(errs) > 0 {
  154. err = fmt.Errorf("%v", errs)
  155. }
  156. return err
  157. }
  158. // webHandler handles all non-api requests, simply flattening and returning the dashboard website.
  159. func (db *Dashboard) webHandler(w http.ResponseWriter, r *http.Request) {
  160. log.Debug("Request", "URL", r.URL)
  161. path := r.URL.String()
  162. if path == "/" {
  163. path = "/index.html"
  164. }
  165. blob, err := Asset(path[1:])
  166. if err != nil {
  167. log.Warn("Failed to load the asset", "path", path, "err", err)
  168. http.Error(w, "not found", http.StatusNotFound)
  169. return
  170. }
  171. w.Write(blob)
  172. }
  173. // apiHandler handles requests for the dashboard.
  174. func (db *Dashboard) apiHandler(conn *websocket.Conn) {
  175. id := atomic.AddUint32(&db.nextConnID, 1)
  176. client := &client{
  177. conn: conn,
  178. msg: make(chan *Message, 128),
  179. logger: log.New("id", id),
  180. }
  181. done := make(chan struct{})
  182. // Start listening for messages to send.
  183. db.wg.Add(1)
  184. go func() {
  185. defer db.wg.Done()
  186. for {
  187. select {
  188. case <-done:
  189. return
  190. case msg := <-client.msg:
  191. if err := websocket.JSON.Send(client.conn, msg); err != nil {
  192. client.logger.Warn("Failed to send the message", "msg", msg, "err", err)
  193. client.conn.Close()
  194. return
  195. }
  196. }
  197. }
  198. }()
  199. // Send the past data.
  200. db.sysLock.RLock()
  201. db.peerLock.RLock()
  202. db.logLock.RLock()
  203. h := deepcopy.Copy(db.history).(*Message)
  204. db.sysLock.RUnlock()
  205. db.peerLock.RUnlock()
  206. db.logLock.RUnlock()
  207. client.msg <- h
  208. // Start tracking the connection and drop at connection loss.
  209. db.lock.Lock()
  210. db.conns[id] = client
  211. db.lock.Unlock()
  212. defer func() {
  213. db.lock.Lock()
  214. delete(db.conns, id)
  215. db.lock.Unlock()
  216. }()
  217. for {
  218. r := new(Request)
  219. if err := websocket.JSON.Receive(conn, r); err != nil {
  220. if err != io.EOF {
  221. client.logger.Warn("Failed to receive request", "err", err)
  222. }
  223. close(done)
  224. return
  225. }
  226. if r.Logs != nil {
  227. db.handleLogRequest(r.Logs, client)
  228. }
  229. }
  230. }
  231. // sendToAll sends the given message to the active dashboards.
  232. func (db *Dashboard) sendToAll(msg *Message) {
  233. db.lock.Lock()
  234. for _, c := range db.conns {
  235. select {
  236. case c.msg <- msg:
  237. default:
  238. c.conn.Close()
  239. }
  240. }
  241. db.lock.Unlock()
  242. }