monitorcmd.go 11 KB

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