monitorcmd.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package main
  2. import (
  3. "math"
  4. "reflect"
  5. "sort"
  6. "strings"
  7. "time"
  8. "github.com/codegangsta/cli"
  9. "github.com/ethereum/go-ethereum/cmd/utils"
  10. "github.com/ethereum/go-ethereum/rpc"
  11. "github.com/ethereum/go-ethereum/rpc/codec"
  12. "github.com/ethereum/go-ethereum/rpc/comms"
  13. "github.com/gizak/termui"
  14. )
  15. // monitor starts a terminal UI based monitoring tool for the requested metrics.
  16. func monitor(ctx *cli.Context) {
  17. var (
  18. client comms.EthereumClient
  19. args []string
  20. err error
  21. )
  22. // Attach to an Ethereum node over IPC or RPC
  23. if ctx.Args().Present() {
  24. // Try to interpret the first parameter as an endpoint
  25. client, err = comms.ClientFromEndpoint(ctx.Args().First(), codec.JSON)
  26. if err == nil {
  27. args = ctx.Args().Tail()
  28. }
  29. }
  30. if !ctx.Args().Present() || err != nil {
  31. // Either no args were given, or not endpoint, use defaults
  32. cfg := comms.IpcConfig{
  33. Endpoint: ctx.GlobalString(utils.IPCPathFlag.Name),
  34. }
  35. args = ctx.Args()
  36. client, err = comms.NewIpcClient(cfg, codec.JSON)
  37. }
  38. if err != nil {
  39. utils.Fatalf("Unable to attach to geth node - %v", err)
  40. }
  41. defer client.Close()
  42. xeth := rpc.NewXeth(client)
  43. // Retrieve all the available metrics and resolve the user pattens
  44. metrics, err := xeth.Call("debug_metrics", []interface{}{true})
  45. if err != nil {
  46. utils.Fatalf("Failed to retrieve system metrics: %v", err)
  47. }
  48. monitored := resolveMetrics(metrics, args)
  49. sort.Strings(monitored)
  50. // Create the access function and check that the metric exists
  51. value := func(metrics map[string]interface{}, metric string) float64 {
  52. parts, found := strings.Split(metric, "/"), true
  53. for _, part := range parts[:len(parts)-1] {
  54. metrics, found = metrics[part].(map[string]interface{})
  55. if !found {
  56. utils.Fatalf("Metric not found: %s", metric)
  57. }
  58. }
  59. if v, ok := metrics[parts[len(parts)-1]].(float64); ok {
  60. return v
  61. }
  62. utils.Fatalf("Metric not float64: %s", metric)
  63. return 0
  64. }
  65. // Create and configure the chart UI defaults
  66. if err := termui.Init(); err != nil {
  67. utils.Fatalf("Unable to initialize terminal UI: %v", err)
  68. }
  69. defer termui.Close()
  70. termui.UseTheme("helloworld")
  71. rows := len(monitored)
  72. if rows > 5 {
  73. rows = 5
  74. }
  75. cols := (len(monitored) + rows - 1) / rows
  76. for i := 0; i < rows; i++ {
  77. termui.Body.AddRows(termui.NewRow())
  78. }
  79. // Create each individual data chart
  80. charts := make([]*termui.LineChart, len(monitored))
  81. data := make([][]float64, len(monitored))
  82. for i := 0; i < len(data); i++ {
  83. data[i] = make([]float64, 512)
  84. }
  85. for i, metric := range monitored {
  86. charts[i] = termui.NewLineChart()
  87. charts[i].Data = make([]float64, 512)
  88. charts[i].DataLabels = []string{""}
  89. charts[i].Height = termui.TermHeight() / rows
  90. charts[i].AxesColor = termui.ColorWhite
  91. charts[i].LineColor = termui.ColorGreen
  92. charts[i].PaddingBottom = -1
  93. charts[i].Border.Label = metric
  94. charts[i].Border.LabelFgColor = charts[i].Border.FgColor
  95. charts[i].Border.FgColor = charts[i].Border.BgColor
  96. row := termui.Body.Rows[i%rows]
  97. row.Cols = append(row.Cols, termui.NewCol(12/cols, 0, charts[i]))
  98. }
  99. termui.Body.Align()
  100. termui.Render(termui.Body)
  101. refresh := time.Tick(time.Second)
  102. for {
  103. select {
  104. case event := <-termui.EventCh():
  105. if event.Type == termui.EventKey && event.Ch == 'q' {
  106. return
  107. }
  108. if event.Type == termui.EventResize {
  109. termui.Body.Width = termui.TermWidth()
  110. for _, chart := range charts {
  111. chart.Height = termui.TermHeight() / rows
  112. }
  113. termui.Body.Align()
  114. termui.Render(termui.Body)
  115. }
  116. case <-refresh:
  117. metrics, err := xeth.Call("debug_metrics", []interface{}{true})
  118. if err != nil {
  119. utils.Fatalf("Failed to retrieve system metrics: %v", err)
  120. }
  121. for i, metric := range monitored {
  122. data[i] = append([]float64{value(metrics, metric)}, data[i][:len(data[i])-1]...)
  123. updateChart(metric, data[i], charts[i])
  124. }
  125. termui.Render(termui.Body)
  126. }
  127. }
  128. }
  129. // resolveMetrics takes a list of input metric patterns, and resolves each to one
  130. // or more canonical metric names.
  131. func resolveMetrics(metrics map[string]interface{}, patterns []string) []string {
  132. res := []string{}
  133. for _, pattern := range patterns {
  134. res = append(res, resolveMetric(metrics, pattern, "")...)
  135. }
  136. return res
  137. }
  138. // resolveMetrics takes a single of input metric pattern, and resolves it to one
  139. // or more canonical metric names.
  140. func resolveMetric(metrics map[string]interface{}, pattern string, path string) []string {
  141. results := []string{}
  142. // If a nested metric was requested, recurse optionally branching (via comma)
  143. parts := strings.SplitN(pattern, "/", 2)
  144. if len(parts) > 1 {
  145. for _, variation := range strings.Split(parts[0], ",") {
  146. if submetrics, ok := metrics[variation].(map[string]interface{}); !ok {
  147. utils.Fatalf("Failed to retrieve system metrics: %s", path+variation)
  148. return nil
  149. } else {
  150. results = append(results, resolveMetric(submetrics, parts[1], path+variation+"/")...)
  151. }
  152. }
  153. return results
  154. }
  155. // Depending what the last link is, return or expand
  156. for _, variation := range strings.Split(pattern, ",") {
  157. switch metric := metrics[variation].(type) {
  158. case float64:
  159. // Final metric value found, return as singleton
  160. results = append(results, path+variation)
  161. case map[string]interface{}:
  162. results = append(results, expandMetrics(metric, path+variation+"/")...)
  163. default:
  164. utils.Fatalf("Metric pattern resolved to unexpected type: %v", reflect.TypeOf(metric))
  165. return nil
  166. }
  167. }
  168. return results
  169. }
  170. // expandMetrics expands the entire tree of metrics into a flat list of paths.
  171. func expandMetrics(metrics map[string]interface{}, path string) []string {
  172. // Iterate over all fields and expand individually
  173. list := []string{}
  174. for name, metric := range metrics {
  175. switch metric := metric.(type) {
  176. case float64:
  177. // Final metric value found, append to list
  178. list = append(list, path+name)
  179. case map[string]interface{}:
  180. // Tree of metrics found, expand recursively
  181. list = append(list, expandMetrics(metric, path+name+"/")...)
  182. default:
  183. utils.Fatalf("Metric pattern %s resolved to unexpected type: %v", path+name, reflect.TypeOf(metric))
  184. return nil
  185. }
  186. }
  187. return list
  188. }
  189. // updateChart inserts a dataset into a line chart, scaling appropriately as to
  190. // not display weird labels, also updating the chart label accordingly.
  191. func updateChart(metric string, data []float64, chart *termui.LineChart) {
  192. dataUnits := []string{"", "K", "M", "G", "T", "E"}
  193. timeUnits := []string{"ns", "µs", "ms", "s", "ks", "ms"}
  194. colors := []termui.Attribute{termui.ColorBlue, termui.ColorCyan, termui.ColorGreen, termui.ColorYellow, termui.ColorRed, termui.ColorRed}
  195. // Find the maximum value and scale under 1K
  196. high := data[0]
  197. for _, value := range data[1:] {
  198. high = math.Max(high, value)
  199. }
  200. unit, scale := 0, 1.0
  201. for high >= 1000 {
  202. high, unit, scale = high/1000, unit+1, scale*1000
  203. }
  204. // Update the chart's data points with the scaled values
  205. for i, value := range data {
  206. chart.Data[i] = value / scale
  207. }
  208. // Update the chart's label with the scale units
  209. chart.Border.Label = metric
  210. units := dataUnits
  211. if strings.Contains(metric, "Percentiles") {
  212. units = timeUnits
  213. }
  214. if len(units[unit]) > 0 {
  215. chart.Border.Label += " [" + units[unit] + "]"
  216. }
  217. chart.LineColor = colors[unit]
  218. }