dashboard.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 npm --prefix ./assets install
  18. //go:generate ./assets/node_modules/.bin/webpack --config ./assets/webpack.config.js --context ./assets
  19. //go:generate go-bindata -nometadata -o assets.go -prefix assets -nocompress -pkg dashboard assets/dashboard.html assets/bundle.js
  20. //go:generate sh -c "sed 's#var _bundleJs#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
  21. //go:generate sh -c "sed 's#var _dashboardHtml#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
  22. //go:generate gofmt -w -s assets.go
  23. import (
  24. "fmt"
  25. "io/ioutil"
  26. "net"
  27. "net/http"
  28. "path/filepath"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/p2p"
  34. "github.com/ethereum/go-ethereum/params"
  35. "github.com/ethereum/go-ethereum/rpc"
  36. "github.com/rcrowley/go-metrics"
  37. "golang.org/x/net/websocket"
  38. )
  39. const (
  40. memorySampleLimit = 200 // Maximum number of memory data samples
  41. trafficSampleLimit = 200 // Maximum number of traffic data samples
  42. )
  43. var nextID uint32 // Next connection id
  44. // Dashboard contains the dashboard internals.
  45. type Dashboard struct {
  46. config *Config
  47. listener net.Listener
  48. conns map[uint32]*client // Currently live websocket connections
  49. charts *HomeMessage
  50. commit string
  51. lock sync.RWMutex // Lock protecting the dashboard's internals
  52. quit chan chan error // Channel used for graceful exit
  53. wg sync.WaitGroup
  54. }
  55. // client represents active websocket connection with a remote browser.
  56. type client struct {
  57. conn *websocket.Conn // Particular live websocket connection
  58. msg chan Message // Message queue for the update messages
  59. logger log.Logger // Logger for the particular live websocket connection
  60. }
  61. // New creates a new dashboard instance with the given configuration.
  62. func New(config *Config, commit string) (*Dashboard, error) {
  63. return &Dashboard{
  64. conns: make(map[uint32]*client),
  65. config: config,
  66. quit: make(chan chan error),
  67. charts: &HomeMessage{
  68. Memory: ChartEntries{},
  69. Traffic: ChartEntries{},
  70. },
  71. commit: commit,
  72. }, nil
  73. }
  74. // Protocols is a meaningless implementation of node.Service.
  75. func (db *Dashboard) Protocols() []p2p.Protocol { return nil }
  76. // APIs is a meaningless implementation of node.Service.
  77. func (db *Dashboard) APIs() []rpc.API { return nil }
  78. // Start implements node.Service, starting the data collection thread and the listening server of the dashboard.
  79. func (db *Dashboard) Start(server *p2p.Server) error {
  80. log.Info("Starting dashboard")
  81. db.wg.Add(2)
  82. go db.collectData()
  83. go db.collectLogs() // In case of removing this line change 2 back to 1 in wg.Add.
  84. http.HandleFunc("/", db.webHandler)
  85. http.Handle("/api", websocket.Handler(db.apiHandler))
  86. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", db.config.Host, db.config.Port))
  87. if err != nil {
  88. return err
  89. }
  90. db.listener = listener
  91. go http.Serve(listener, nil)
  92. return nil
  93. }
  94. // Stop implements node.Service, stopping the data collection thread and the connection listener of the dashboard.
  95. func (db *Dashboard) Stop() error {
  96. // Close the connection listener.
  97. var errs []error
  98. if err := db.listener.Close(); err != nil {
  99. errs = append(errs, err)
  100. }
  101. // Close the collectors.
  102. errc := make(chan error, 1)
  103. for i := 0; i < 2; i++ {
  104. db.quit <- errc
  105. if err := <-errc; err != nil {
  106. errs = append(errs, err)
  107. }
  108. }
  109. // Close the connections.
  110. db.lock.Lock()
  111. for _, c := range db.conns {
  112. if err := c.conn.Close(); err != nil {
  113. c.logger.Warn("Failed to close connection", "err", err)
  114. }
  115. }
  116. db.lock.Unlock()
  117. // Wait until every goroutine terminates.
  118. db.wg.Wait()
  119. log.Info("Dashboard stopped")
  120. var err error
  121. if len(errs) > 0 {
  122. err = fmt.Errorf("%v", errs)
  123. }
  124. return err
  125. }
  126. // webHandler handles all non-api requests, simply flattening and returning the dashboard website.
  127. func (db *Dashboard) webHandler(w http.ResponseWriter, r *http.Request) {
  128. log.Debug("Request", "URL", r.URL)
  129. path := r.URL.String()
  130. if path == "/" {
  131. path = "/dashboard.html"
  132. }
  133. // If the path of the assets is manually set
  134. if db.config.Assets != "" {
  135. blob, err := ioutil.ReadFile(filepath.Join(db.config.Assets, path))
  136. if err != nil {
  137. log.Warn("Failed to read file", "path", path, "err", err)
  138. http.Error(w, "not found", http.StatusNotFound)
  139. return
  140. }
  141. w.Write(blob)
  142. return
  143. }
  144. blob, err := Asset(path[1:])
  145. if err != nil {
  146. log.Warn("Failed to load the asset", "path", path, "err", err)
  147. http.Error(w, "not found", http.StatusNotFound)
  148. return
  149. }
  150. w.Write(blob)
  151. }
  152. // apiHandler handles requests for the dashboard.
  153. func (db *Dashboard) apiHandler(conn *websocket.Conn) {
  154. id := atomic.AddUint32(&nextID, 1)
  155. client := &client{
  156. conn: conn,
  157. msg: make(chan Message, 128),
  158. logger: log.New("id", id),
  159. }
  160. done := make(chan struct{})
  161. // Start listening for messages to send.
  162. db.wg.Add(1)
  163. go func() {
  164. defer db.wg.Done()
  165. for {
  166. select {
  167. case <-done:
  168. return
  169. case msg := <-client.msg:
  170. if err := websocket.JSON.Send(client.conn, msg); err != nil {
  171. client.logger.Warn("Failed to send the message", "msg", msg, "err", err)
  172. client.conn.Close()
  173. return
  174. }
  175. }
  176. }
  177. }()
  178. versionMeta := ""
  179. if len(params.VersionMeta) > 0 {
  180. versionMeta = fmt.Sprintf(" (%s)", params.VersionMeta)
  181. }
  182. // Send the past data.
  183. client.msg <- Message{
  184. General: &GeneralMessage{
  185. Version: fmt.Sprintf("v%d.%d.%d%s", params.VersionMajor, params.VersionMinor, params.VersionPatch, versionMeta),
  186. Commit: db.commit,
  187. },
  188. Home: &HomeMessage{
  189. Memory: db.charts.Memory,
  190. Traffic: db.charts.Traffic,
  191. },
  192. }
  193. // Start tracking the connection and drop at connection loss.
  194. db.lock.Lock()
  195. db.conns[id] = client
  196. db.lock.Unlock()
  197. defer func() {
  198. db.lock.Lock()
  199. delete(db.conns, id)
  200. db.lock.Unlock()
  201. }()
  202. for {
  203. fail := []byte{}
  204. if _, err := conn.Read(fail); err != nil {
  205. close(done)
  206. return
  207. }
  208. // Ignore all messages
  209. }
  210. }
  211. // collectData collects the required data to plot on the dashboard.
  212. func (db *Dashboard) collectData() {
  213. defer db.wg.Done()
  214. for {
  215. select {
  216. case errc := <-db.quit:
  217. errc <- nil
  218. return
  219. case <-time.After(db.config.Refresh):
  220. inboundTraffic := metrics.DefaultRegistry.Get("p2p/InboundTraffic").(metrics.Meter).Rate1()
  221. memoryInUse := metrics.DefaultRegistry.Get("system/memory/inuse").(metrics.Meter).Rate1()
  222. now := time.Now()
  223. memory := &ChartEntry{
  224. Time: now,
  225. Value: memoryInUse,
  226. }
  227. traffic := &ChartEntry{
  228. Time: now,
  229. Value: inboundTraffic,
  230. }
  231. first := 0
  232. if len(db.charts.Memory) == memorySampleLimit {
  233. first = 1
  234. }
  235. db.charts.Memory = append(db.charts.Memory[first:], memory)
  236. first = 0
  237. if len(db.charts.Traffic) == trafficSampleLimit {
  238. first = 1
  239. }
  240. db.charts.Traffic = append(db.charts.Traffic[first:], traffic)
  241. db.sendToAll(&Message{
  242. Home: &HomeMessage{
  243. Memory: ChartEntries{memory},
  244. Traffic: ChartEntries{traffic},
  245. },
  246. })
  247. }
  248. }
  249. }
  250. // collectLogs collects and sends the logs to the active dashboards.
  251. func (db *Dashboard) collectLogs() {
  252. defer db.wg.Done()
  253. id := 1
  254. // TODO (kurkomisi): log collection comes here.
  255. for {
  256. select {
  257. case errc := <-db.quit:
  258. errc <- nil
  259. return
  260. case <-time.After(db.config.Refresh / 2):
  261. db.sendToAll(&Message{
  262. Logs: &LogsMessage{
  263. Log: []string{fmt.Sprintf("%-4d: This is a fake log.", id)},
  264. },
  265. })
  266. id++
  267. }
  268. }
  269. }
  270. // sendToAll sends the given message to the active dashboards.
  271. func (db *Dashboard) sendToAll(msg *Message) {
  272. db.lock.Lock()
  273. for _, c := range db.conns {
  274. select {
  275. case c.msg <- *msg:
  276. default:
  277. c.conn.Close()
  278. }
  279. }
  280. db.lock.Unlock()
  281. }