dashboard.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. "runtime"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "github.com/elastic/gosigar"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/metrics"
  36. "github.com/ethereum/go-ethereum/p2p"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/rpc"
  39. "golang.org/x/net/websocket"
  40. )
  41. const (
  42. activeMemorySampleLimit = 200 // Maximum number of active memory data samples
  43. virtualMemorySampleLimit = 200 // Maximum number of virtual memory data samples
  44. networkIngressSampleLimit = 200 // Maximum number of network ingress data samples
  45. networkEgressSampleLimit = 200 // Maximum number of network egress data samples
  46. processCPUSampleLimit = 200 // Maximum number of process cpu data samples
  47. systemCPUSampleLimit = 200 // Maximum number of system cpu data samples
  48. diskReadSampleLimit = 200 // Maximum number of disk read data samples
  49. diskWriteSampleLimit = 200 // Maximum number of disk write data samples
  50. )
  51. var nextID uint32 // Next connection id
  52. // Dashboard contains the dashboard internals.
  53. type Dashboard struct {
  54. config *Config
  55. listener net.Listener
  56. conns map[uint32]*client // Currently live websocket connections
  57. charts *HomeMessage
  58. commit string
  59. lock sync.RWMutex // Lock protecting the dashboard's internals
  60. quit chan chan error // Channel used for graceful exit
  61. wg sync.WaitGroup
  62. }
  63. // client represents active websocket connection with a remote browser.
  64. type client struct {
  65. conn *websocket.Conn // Particular live websocket connection
  66. msg chan Message // Message queue for the update messages
  67. logger log.Logger // Logger for the particular live websocket connection
  68. }
  69. // New creates a new dashboard instance with the given configuration.
  70. func New(config *Config, commit string) (*Dashboard, error) {
  71. now := time.Now()
  72. db := &Dashboard{
  73. conns: make(map[uint32]*client),
  74. config: config,
  75. quit: make(chan chan error),
  76. charts: &HomeMessage{
  77. ActiveMemory: emptyChartEntries(now, activeMemorySampleLimit, config.Refresh),
  78. VirtualMemory: emptyChartEntries(now, virtualMemorySampleLimit, config.Refresh),
  79. NetworkIngress: emptyChartEntries(now, networkIngressSampleLimit, config.Refresh),
  80. NetworkEgress: emptyChartEntries(now, networkEgressSampleLimit, config.Refresh),
  81. ProcessCPU: emptyChartEntries(now, processCPUSampleLimit, config.Refresh),
  82. SystemCPU: emptyChartEntries(now, systemCPUSampleLimit, config.Refresh),
  83. DiskRead: emptyChartEntries(now, diskReadSampleLimit, config.Refresh),
  84. DiskWrite: emptyChartEntries(now, diskWriteSampleLimit, config.Refresh),
  85. },
  86. commit: commit,
  87. }
  88. return db, nil
  89. }
  90. // emptyChartEntries returns a ChartEntry array containing limit number of empty samples.
  91. func emptyChartEntries(t time.Time, limit int, refresh time.Duration) ChartEntries {
  92. ce := make(ChartEntries, limit)
  93. for i := 0; i < limit; i++ {
  94. ce[i] = &ChartEntry{
  95. Time: t.Add(-time.Duration(i) * refresh),
  96. }
  97. }
  98. return ce
  99. }
  100. // Protocols is a meaningless implementation of node.Service.
  101. func (db *Dashboard) Protocols() []p2p.Protocol { return nil }
  102. // APIs is a meaningless implementation of node.Service.
  103. func (db *Dashboard) APIs() []rpc.API { return nil }
  104. // Start implements node.Service, starting the data collection thread and the listening server of the dashboard.
  105. func (db *Dashboard) Start(server *p2p.Server) error {
  106. log.Info("Starting dashboard")
  107. db.wg.Add(2)
  108. go db.collectData()
  109. go db.collectLogs() // In case of removing this line change 2 back to 1 in wg.Add.
  110. http.HandleFunc("/", db.webHandler)
  111. http.Handle("/api", websocket.Handler(db.apiHandler))
  112. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", db.config.Host, db.config.Port))
  113. if err != nil {
  114. return err
  115. }
  116. db.listener = listener
  117. go http.Serve(listener, nil)
  118. return nil
  119. }
  120. // Stop implements node.Service, stopping the data collection thread and the connection listener of the dashboard.
  121. func (db *Dashboard) Stop() error {
  122. // Close the connection listener.
  123. var errs []error
  124. if err := db.listener.Close(); err != nil {
  125. errs = append(errs, err)
  126. }
  127. // Close the collectors.
  128. errc := make(chan error, 1)
  129. for i := 0; i < 2; i++ {
  130. db.quit <- errc
  131. if err := <-errc; err != nil {
  132. errs = append(errs, err)
  133. }
  134. }
  135. // Close the connections.
  136. db.lock.Lock()
  137. for _, c := range db.conns {
  138. if err := c.conn.Close(); err != nil {
  139. c.logger.Warn("Failed to close connection", "err", err)
  140. }
  141. }
  142. db.lock.Unlock()
  143. // Wait until every goroutine terminates.
  144. db.wg.Wait()
  145. log.Info("Dashboard stopped")
  146. var err error
  147. if len(errs) > 0 {
  148. err = fmt.Errorf("%v", errs)
  149. }
  150. return err
  151. }
  152. // webHandler handles all non-api requests, simply flattening and returning the dashboard website.
  153. func (db *Dashboard) webHandler(w http.ResponseWriter, r *http.Request) {
  154. log.Debug("Request", "URL", r.URL)
  155. path := r.URL.String()
  156. if path == "/" {
  157. path = "/dashboard.html"
  158. }
  159. // If the path of the assets is manually set
  160. if db.config.Assets != "" {
  161. blob, err := ioutil.ReadFile(filepath.Join(db.config.Assets, path))
  162. if err != nil {
  163. log.Warn("Failed to read file", "path", path, "err", err)
  164. http.Error(w, "not found", http.StatusNotFound)
  165. return
  166. }
  167. w.Write(blob)
  168. return
  169. }
  170. blob, err := Asset(path[1:])
  171. if err != nil {
  172. log.Warn("Failed to load the asset", "path", path, "err", err)
  173. http.Error(w, "not found", http.StatusNotFound)
  174. return
  175. }
  176. w.Write(blob)
  177. }
  178. // apiHandler handles requests for the dashboard.
  179. func (db *Dashboard) apiHandler(conn *websocket.Conn) {
  180. id := atomic.AddUint32(&nextID, 1)
  181. client := &client{
  182. conn: conn,
  183. msg: make(chan Message, 128),
  184. logger: log.New("id", id),
  185. }
  186. done := make(chan struct{})
  187. // Start listening for messages to send.
  188. db.wg.Add(1)
  189. go func() {
  190. defer db.wg.Done()
  191. for {
  192. select {
  193. case <-done:
  194. return
  195. case msg := <-client.msg:
  196. if err := websocket.JSON.Send(client.conn, msg); err != nil {
  197. client.logger.Warn("Failed to send the message", "msg", msg, "err", err)
  198. client.conn.Close()
  199. return
  200. }
  201. }
  202. }
  203. }()
  204. versionMeta := ""
  205. if len(params.VersionMeta) > 0 {
  206. versionMeta = fmt.Sprintf(" (%s)", params.VersionMeta)
  207. }
  208. // Send the past data.
  209. client.msg <- Message{
  210. General: &GeneralMessage{
  211. Version: fmt.Sprintf("v%d.%d.%d%s", params.VersionMajor, params.VersionMinor, params.VersionPatch, versionMeta),
  212. Commit: db.commit,
  213. },
  214. Home: &HomeMessage{
  215. ActiveMemory: db.charts.ActiveMemory,
  216. VirtualMemory: db.charts.VirtualMemory,
  217. NetworkIngress: db.charts.NetworkIngress,
  218. NetworkEgress: db.charts.NetworkEgress,
  219. ProcessCPU: db.charts.ProcessCPU,
  220. SystemCPU: db.charts.SystemCPU,
  221. DiskRead: db.charts.DiskRead,
  222. DiskWrite: db.charts.DiskWrite,
  223. },
  224. }
  225. // Start tracking the connection and drop at connection loss.
  226. db.lock.Lock()
  227. db.conns[id] = client
  228. db.lock.Unlock()
  229. defer func() {
  230. db.lock.Lock()
  231. delete(db.conns, id)
  232. db.lock.Unlock()
  233. }()
  234. for {
  235. fail := []byte{}
  236. if _, err := conn.Read(fail); err != nil {
  237. close(done)
  238. return
  239. }
  240. // Ignore all messages
  241. }
  242. }
  243. // collectData collects the required data to plot on the dashboard.
  244. func (db *Dashboard) collectData() {
  245. defer db.wg.Done()
  246. systemCPUUsage := gosigar.Cpu{}
  247. systemCPUUsage.Get()
  248. var (
  249. prevNetworkIngress = metrics.DefaultRegistry.Get("p2p/InboundTraffic").(metrics.Meter).Count()
  250. prevNetworkEgress = metrics.DefaultRegistry.Get("p2p/OutboundTraffic").(metrics.Meter).Count()
  251. prevProcessCPUTime = getProcessCPUTime()
  252. prevSystemCPUUsage = systemCPUUsage
  253. prevDiskRead = metrics.DefaultRegistry.Get("eth/db/chaindata/compact/input").(metrics.Meter).Count()
  254. prevDiskWrite = metrics.DefaultRegistry.Get("eth/db/chaindata/compact/output").(metrics.Meter).Count()
  255. frequency = float64(db.config.Refresh / time.Second)
  256. numCPU = float64(runtime.NumCPU())
  257. )
  258. for {
  259. select {
  260. case errc := <-db.quit:
  261. errc <- nil
  262. return
  263. case <-time.After(db.config.Refresh):
  264. systemCPUUsage.Get()
  265. var (
  266. curNetworkIngress = metrics.DefaultRegistry.Get("p2p/InboundTraffic").(metrics.Meter).Count()
  267. curNetworkEgress = metrics.DefaultRegistry.Get("p2p/OutboundTraffic").(metrics.Meter).Count()
  268. curProcessCPUTime = getProcessCPUTime()
  269. curSystemCPUUsage = systemCPUUsage
  270. curDiskRead = metrics.DefaultRegistry.Get("eth/db/chaindata/compact/input").(metrics.Meter).Count()
  271. curDiskWrite = metrics.DefaultRegistry.Get("eth/db/chaindata/compact/output").(metrics.Meter).Count()
  272. deltaNetworkIngress = float64(curNetworkIngress - prevNetworkIngress)
  273. deltaNetworkEgress = float64(curNetworkEgress - prevNetworkEgress)
  274. deltaProcessCPUTime = curProcessCPUTime - prevProcessCPUTime
  275. deltaSystemCPUUsage = systemCPUUsage.Delta(prevSystemCPUUsage)
  276. deltaDiskRead = curDiskRead - prevDiskRead
  277. deltaDiskWrite = curDiskWrite - prevDiskWrite
  278. )
  279. prevNetworkIngress = curNetworkIngress
  280. prevNetworkEgress = curNetworkEgress
  281. prevProcessCPUTime = curProcessCPUTime
  282. prevSystemCPUUsage = curSystemCPUUsage
  283. prevDiskRead = curDiskRead
  284. prevDiskWrite = curDiskWrite
  285. now := time.Now()
  286. var mem runtime.MemStats
  287. runtime.ReadMemStats(&mem)
  288. activeMemory := &ChartEntry{
  289. Time: now,
  290. Value: float64(mem.Alloc) / frequency,
  291. }
  292. virtualMemory := &ChartEntry{
  293. Time: now,
  294. Value: float64(mem.Sys) / frequency,
  295. }
  296. networkIngress := &ChartEntry{
  297. Time: now,
  298. Value: deltaNetworkIngress / frequency,
  299. }
  300. networkEgress := &ChartEntry{
  301. Time: now,
  302. Value: deltaNetworkEgress / frequency,
  303. }
  304. processCPU := &ChartEntry{
  305. Time: now,
  306. Value: deltaProcessCPUTime / frequency / numCPU * 100,
  307. }
  308. systemCPU := &ChartEntry{
  309. Time: now,
  310. Value: float64(deltaSystemCPUUsage.Sys+deltaSystemCPUUsage.User) / frequency / numCPU,
  311. }
  312. diskRead := &ChartEntry{
  313. Time: now,
  314. Value: float64(deltaDiskRead) / frequency,
  315. }
  316. diskWrite := &ChartEntry{
  317. Time: now,
  318. Value: float64(deltaDiskWrite) / frequency,
  319. }
  320. db.charts.ActiveMemory = append(db.charts.ActiveMemory[1:], activeMemory)
  321. db.charts.VirtualMemory = append(db.charts.VirtualMemory[1:], virtualMemory)
  322. db.charts.NetworkIngress = append(db.charts.NetworkIngress[1:], networkIngress)
  323. db.charts.NetworkEgress = append(db.charts.NetworkEgress[1:], networkEgress)
  324. db.charts.ProcessCPU = append(db.charts.ProcessCPU[1:], processCPU)
  325. db.charts.SystemCPU = append(db.charts.SystemCPU[1:], systemCPU)
  326. db.charts.DiskRead = append(db.charts.DiskRead[1:], diskRead)
  327. db.charts.DiskWrite = append(db.charts.DiskRead[1:], diskWrite)
  328. db.sendToAll(&Message{
  329. Home: &HomeMessage{
  330. ActiveMemory: ChartEntries{activeMemory},
  331. VirtualMemory: ChartEntries{virtualMemory},
  332. NetworkIngress: ChartEntries{networkIngress},
  333. NetworkEgress: ChartEntries{networkEgress},
  334. ProcessCPU: ChartEntries{processCPU},
  335. SystemCPU: ChartEntries{systemCPU},
  336. DiskRead: ChartEntries{diskRead},
  337. DiskWrite: ChartEntries{diskWrite},
  338. },
  339. })
  340. }
  341. }
  342. }
  343. // collectLogs collects and sends the logs to the active dashboards.
  344. func (db *Dashboard) collectLogs() {
  345. defer db.wg.Done()
  346. id := 1
  347. // TODO (kurkomisi): log collection comes here.
  348. for {
  349. select {
  350. case errc := <-db.quit:
  351. errc <- nil
  352. return
  353. case <-time.After(db.config.Refresh / 2):
  354. db.sendToAll(&Message{
  355. Logs: &LogsMessage{
  356. Log: []string{fmt.Sprintf("%-4d: This is a fake log.", id)},
  357. },
  358. })
  359. id++
  360. }
  361. }
  362. }
  363. // sendToAll sends the given message to the active dashboards.
  364. func (db *Dashboard) sendToAll(msg *Message) {
  365. db.lock.Lock()
  366. for _, c := range db.conns {
  367. select {
  368. case c.msg <- *msg:
  369. default:
  370. c.conn.Close()
  371. }
  372. }
  373. db.lock.Unlock()
  374. }