dashboard.go 7.8 KB

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