monitorcmd.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "reflect"
  6. "runtime"
  7. "sort"
  8. "strings"
  9. "time"
  10. "github.com/codegangsta/cli"
  11. "github.com/ethereum/go-ethereum/cmd/utils"
  12. "github.com/ethereum/go-ethereum/common"
  13. "github.com/ethereum/go-ethereum/rpc"
  14. "github.com/ethereum/go-ethereum/rpc/codec"
  15. "github.com/ethereum/go-ethereum/rpc/comms"
  16. "github.com/gizak/termui"
  17. )
  18. var (
  19. monitorCommandAttachFlag = cli.StringFlag{
  20. Name: "attach",
  21. Value: "ipc:" + common.DefaultIpcPath(),
  22. Usage: "API endpoint to attach to",
  23. }
  24. monitorCommandRowsFlag = cli.IntFlag{
  25. Name: "rows",
  26. Value: 5,
  27. Usage: "Maximum rows in the chart grid",
  28. }
  29. monitorCommandRefreshFlag = cli.IntFlag{
  30. Name: "refresh",
  31. Value: 3,
  32. Usage: "Refresh interval in seconds",
  33. }
  34. monitorCommand = cli.Command{
  35. Action: monitor,
  36. Name: "monitor",
  37. Usage: `Geth Monitor: node metrics monitoring and visualization`,
  38. Description: `
  39. The Geth monitor is a tool to collect and visualize various internal metrics
  40. gathered by the node, supporting different chart types as well as the capacity
  41. to display multiple metrics simultaneously.
  42. `,
  43. Flags: []cli.Flag{
  44. monitorCommandAttachFlag,
  45. monitorCommandRowsFlag,
  46. monitorCommandRefreshFlag,
  47. },
  48. }
  49. )
  50. // monitor starts a terminal UI based monitoring tool for the requested metrics.
  51. func monitor(ctx *cli.Context) {
  52. var (
  53. client comms.EthereumClient
  54. err error
  55. )
  56. // Attach to an Ethereum node over IPC or RPC
  57. endpoint := ctx.String(monitorCommandAttachFlag.Name)
  58. if client, err = comms.ClientFromEndpoint(endpoint, codec.JSON); err != nil {
  59. utils.Fatalf("Unable to attach to geth node: %v", err)
  60. }
  61. defer client.Close()
  62. xeth := rpc.NewXeth(client)
  63. // Retrieve all the available metrics and resolve the user pattens
  64. metrics, err := retrieveMetrics(xeth)
  65. if err != nil {
  66. utils.Fatalf("Failed to retrieve system metrics: %v", err)
  67. }
  68. monitored := resolveMetrics(metrics, ctx.Args())
  69. if len(monitored) == 0 {
  70. list := expandMetrics(metrics, "")
  71. sort.Strings(list)
  72. utils.Fatalf("No metrics specified.\n\nAvailable:\n - %s", strings.Join(list, "\n - "))
  73. }
  74. sort.Strings(monitored)
  75. if cols := len(monitored) / ctx.Int(monitorCommandRowsFlag.Name); cols > 6 {
  76. utils.Fatalf("Requested metrics (%d) spans more that 6 columns:\n - %s", len(monitored), strings.Join(monitored, "\n - "))
  77. }
  78. // Create and configure the chart UI defaults
  79. if err := termui.Init(); err != nil {
  80. utils.Fatalf("Unable to initialize terminal UI: %v", err)
  81. }
  82. defer termui.Close()
  83. termui.UseTheme("helloworld")
  84. rows := len(monitored)
  85. if max := ctx.Int(monitorCommandRowsFlag.Name); rows > max {
  86. rows = max
  87. }
  88. cols := (len(monitored) + rows - 1) / rows
  89. for i := 0; i < rows; i++ {
  90. termui.Body.AddRows(termui.NewRow())
  91. }
  92. // Create each individual data chart
  93. footer := termui.NewPar("")
  94. footer.HasBorder = true
  95. footer.Height = 3
  96. charts := make([]*termui.LineChart, len(monitored))
  97. units := make([]int, len(monitored))
  98. data := make([][]float64, len(monitored))
  99. for i := 0; i < len(monitored); i++ {
  100. charts[i] = createChart((termui.TermHeight() - footer.Height) / rows)
  101. row := termui.Body.Rows[i%rows]
  102. row.Cols = append(row.Cols, termui.NewCol(12/cols, 0, charts[i]))
  103. }
  104. termui.Body.AddRows(termui.NewRow(termui.NewCol(12, 0, footer)))
  105. refreshCharts(xeth, monitored, data, units, charts, ctx, footer)
  106. termui.Body.Align()
  107. termui.Render(termui.Body)
  108. // Watch for various system events, and periodically refresh the charts
  109. refresh := time.Tick(time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second)
  110. for {
  111. select {
  112. case event := <-termui.EventCh():
  113. if event.Type == termui.EventKey && event.Key == termui.KeyCtrlC {
  114. return
  115. }
  116. if event.Type == termui.EventResize {
  117. termui.Body.Width = termui.TermWidth()
  118. for _, chart := range charts {
  119. chart.Height = (termui.TermHeight() - footer.Height) / rows
  120. }
  121. termui.Body.Align()
  122. termui.Render(termui.Body)
  123. }
  124. case <-refresh:
  125. if refreshCharts(xeth, monitored, data, units, charts, ctx, footer) {
  126. termui.Body.Align()
  127. }
  128. termui.Render(termui.Body)
  129. }
  130. }
  131. }
  132. // retrieveMetrics contacts the attached geth node and retrieves the entire set
  133. // of collected system metrics.
  134. func retrieveMetrics(xeth *rpc.Xeth) (map[string]interface{}, error) {
  135. return xeth.Call("debug_metrics", []interface{}{true})
  136. }
  137. // resolveMetrics takes a list of input metric patterns, and resolves each to one
  138. // or more canonical metric names.
  139. func resolveMetrics(metrics map[string]interface{}, patterns []string) []string {
  140. res := []string{}
  141. for _, pattern := range patterns {
  142. res = append(res, resolveMetric(metrics, pattern, "")...)
  143. }
  144. return res
  145. }
  146. // resolveMetrics takes a single of input metric pattern, and resolves it to one
  147. // or more canonical metric names.
  148. func resolveMetric(metrics map[string]interface{}, pattern string, path string) []string {
  149. results := []string{}
  150. // If a nested metric was requested, recurse optionally branching (via comma)
  151. parts := strings.SplitN(pattern, "/", 2)
  152. if len(parts) > 1 {
  153. for _, variation := range strings.Split(parts[0], ",") {
  154. if submetrics, ok := metrics[variation].(map[string]interface{}); !ok {
  155. utils.Fatalf("Failed to retrieve system metrics: %s", path+variation)
  156. return nil
  157. } else {
  158. results = append(results, resolveMetric(submetrics, parts[1], path+variation+"/")...)
  159. }
  160. }
  161. return results
  162. }
  163. // Depending what the last link is, return or expand
  164. for _, variation := range strings.Split(pattern, ",") {
  165. switch metric := metrics[variation].(type) {
  166. case float64:
  167. // Final metric value found, return as singleton
  168. results = append(results, path+variation)
  169. case map[string]interface{}:
  170. results = append(results, expandMetrics(metric, path+variation+"/")...)
  171. default:
  172. utils.Fatalf("Metric pattern resolved to unexpected type: %v", reflect.TypeOf(metric))
  173. return nil
  174. }
  175. }
  176. return results
  177. }
  178. // expandMetrics expands the entire tree of metrics into a flat list of paths.
  179. func expandMetrics(metrics map[string]interface{}, path string) []string {
  180. // Iterate over all fields and expand individually
  181. list := []string{}
  182. for name, metric := range metrics {
  183. switch metric := metric.(type) {
  184. case float64:
  185. // Final metric value found, append to list
  186. list = append(list, path+name)
  187. case map[string]interface{}:
  188. // Tree of metrics found, expand recursively
  189. list = append(list, expandMetrics(metric, path+name+"/")...)
  190. default:
  191. utils.Fatalf("Metric pattern %s resolved to unexpected type: %v", path+name, reflect.TypeOf(metric))
  192. return nil
  193. }
  194. }
  195. return list
  196. }
  197. // fetchMetric iterates over the metrics map and retrieves a specific one.
  198. func fetchMetric(metrics map[string]interface{}, metric string) float64 {
  199. parts, found := strings.Split(metric, "/"), true
  200. for _, part := range parts[:len(parts)-1] {
  201. metrics, found = metrics[part].(map[string]interface{})
  202. if !found {
  203. return 0
  204. }
  205. }
  206. if v, ok := metrics[parts[len(parts)-1]].(float64); ok {
  207. return v
  208. }
  209. return 0
  210. }
  211. // refreshCharts retrieves a next batch of metrics, and inserts all the new
  212. // values into the active datasets and charts
  213. func refreshCharts(xeth *rpc.Xeth, metrics []string, data [][]float64, units []int, charts []*termui.LineChart, ctx *cli.Context, footer *termui.Par) (realign bool) {
  214. values, err := retrieveMetrics(xeth)
  215. for i, metric := range metrics {
  216. if len(data) < 512 {
  217. data[i] = append([]float64{fetchMetric(values, metric)}, data[i]...)
  218. } else {
  219. data[i] = append([]float64{fetchMetric(values, metric)}, data[i][:len(data[i])-1]...)
  220. }
  221. if updateChart(metric, data[i], &units[i], charts[i], err) {
  222. realign = true
  223. }
  224. }
  225. updateFooter(ctx, err, footer)
  226. return
  227. }
  228. // updateChart inserts a dataset into a line chart, scaling appropriately as to
  229. // not display weird labels, also updating the chart label accordingly.
  230. func updateChart(metric string, data []float64, base *int, chart *termui.LineChart, err error) (realign bool) {
  231. dataUnits := []string{"", "K", "M", "G", "T", "E"}
  232. timeUnits := []string{"ns", "µs", "ms", "s", "ks", "ms"}
  233. colors := []termui.Attribute{termui.ColorBlue, termui.ColorCyan, termui.ColorGreen, termui.ColorYellow, termui.ColorRed, termui.ColorRed}
  234. // Extract only part of the data that's actually visible
  235. if chart.Width*2 < len(data) {
  236. data = data[:chart.Width*2]
  237. }
  238. // Find the maximum value and scale under 1K
  239. high := 0.0
  240. if len(data) > 0 {
  241. high = data[0]
  242. for _, value := range data[1:] {
  243. high = math.Max(high, value)
  244. }
  245. }
  246. unit, scale := 0, 1.0
  247. for high >= 1000 {
  248. high, unit, scale = high/1000, unit+1, scale*1000
  249. }
  250. // If the unit changes, re-create the chart (hack to set max height...)
  251. if unit != *base {
  252. realign, *base, *chart = true, unit, *createChart(chart.Height)
  253. }
  254. // Update the chart's data points with the scaled values
  255. if cap(chart.Data) < len(data) {
  256. chart.Data = make([]float64, len(data))
  257. }
  258. chart.Data = chart.Data[:len(data)]
  259. for i, value := range data {
  260. chart.Data[i] = value / scale
  261. }
  262. // Update the chart's label with the scale units
  263. units := dataUnits
  264. if strings.Contains(metric, "/Percentiles/") || strings.Contains(metric, "/pauses/") || strings.Contains(metric, "/time/") {
  265. units = timeUnits
  266. }
  267. chart.Border.Label = metric
  268. if len(units[unit]) > 0 {
  269. chart.Border.Label += " [" + units[unit] + "]"
  270. }
  271. chart.LineColor = colors[unit] | termui.AttrBold
  272. if err != nil {
  273. chart.LineColor = termui.ColorRed | termui.AttrBold
  274. }
  275. return
  276. }
  277. // createChart creates an empty line chart with the default configs.
  278. func createChart(height int) *termui.LineChart {
  279. chart := termui.NewLineChart()
  280. if runtime.GOOS == "windows" {
  281. chart.Mode = "dot"
  282. }
  283. chart.DataLabels = []string{""}
  284. chart.Height = height
  285. chart.AxesColor = termui.ColorWhite
  286. chart.PaddingBottom = -2
  287. chart.Border.LabelFgColor = chart.Border.FgColor | termui.AttrBold
  288. chart.Border.FgColor = chart.Border.BgColor
  289. return chart
  290. }
  291. // updateFooter updates the footer contents based on any encountered errors.
  292. func updateFooter(ctx *cli.Context, err error, footer *termui.Par) {
  293. // Generate the basic footer
  294. refresh := time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second
  295. footer.Text = fmt.Sprintf("Press Ctrl+C to quit. Refresh interval: %v.", refresh)
  296. footer.TextFgColor = termui.Theme().ParTextFg | termui.AttrBold
  297. // Append any encountered errors
  298. if err != nil {
  299. footer.Text = fmt.Sprintf("Error: %v.", err)
  300. footer.TextFgColor = termui.ColorRed | termui.AttrBold
  301. }
  302. }