monitorcmd.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. termui.UseTheme("helloworld")
  100. rows := len(monitored)
  101. if max := ctx.Int(monitorCommandRowsFlag.Name); rows > max {
  102. rows = max
  103. }
  104. cols := (len(monitored) + rows - 1) / rows
  105. for i := 0; i < rows; i++ {
  106. termui.Body.AddRows(termui.NewRow())
  107. }
  108. // Create each individual data chart
  109. footer := termui.NewPar("")
  110. footer.HasBorder = true
  111. footer.Height = 3
  112. charts := make([]*termui.LineChart, len(monitored))
  113. units := make([]int, len(monitored))
  114. data := make([][]float64, len(monitored))
  115. for i := 0; i < len(monitored); i++ {
  116. charts[i] = createChart((termui.TermHeight() - footer.Height) / rows)
  117. row := termui.Body.Rows[i%rows]
  118. row.Cols = append(row.Cols, termui.NewCol(12/cols, 0, charts[i]))
  119. }
  120. termui.Body.AddRows(termui.NewRow(termui.NewCol(12, 0, footer)))
  121. refreshCharts(client, monitored, data, units, charts, ctx, footer)
  122. termui.Body.Align()
  123. termui.Render(termui.Body)
  124. // Watch for various system events, and periodically refresh the charts
  125. refresh := time.Tick(time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second)
  126. for {
  127. select {
  128. case event := <-termui.EventCh():
  129. if event.Type == termui.EventKey && event.Key == termui.KeyCtrlC {
  130. return
  131. }
  132. if event.Type == termui.EventResize {
  133. termui.Body.Width = termui.TermWidth()
  134. for _, chart := range charts {
  135. chart.Height = (termui.TermHeight() - footer.Height) / rows
  136. }
  137. termui.Body.Align()
  138. termui.Render(termui.Body)
  139. }
  140. case <-refresh:
  141. if refreshCharts(client, monitored, data, units, charts, ctx, footer) {
  142. termui.Body.Align()
  143. }
  144. termui.Render(termui.Body)
  145. }
  146. }
  147. }
  148. // retrieveMetrics contacts the attached geth node and retrieves the entire set
  149. // of collected system metrics.
  150. func retrieveMetrics(client rpc.Client) (map[string]interface{}, error) {
  151. req := map[string]interface{}{
  152. "id": new(int64),
  153. "method": "debug_metrics",
  154. "jsonrpc": "2.0",
  155. "params": []interface{}{true},
  156. }
  157. if err := client.Send(req); err != nil {
  158. return nil, err
  159. }
  160. var res rpc.JSONSuccessResponse
  161. if err := client.Recv(&res); err != nil {
  162. return nil, err
  163. }
  164. if res.Result != nil {
  165. if mets, ok := res.Result.(map[string]interface{}); ok {
  166. return mets, nil
  167. }
  168. }
  169. return nil, fmt.Errorf("unable to retrieve metrics")
  170. }
  171. // resolveMetrics takes a list of input metric patterns, and resolves each to one
  172. // or more canonical metric names.
  173. func resolveMetrics(metrics map[string]interface{}, patterns []string) []string {
  174. res := []string{}
  175. for _, pattern := range patterns {
  176. res = append(res, resolveMetric(metrics, pattern, "")...)
  177. }
  178. return res
  179. }
  180. // resolveMetrics takes a single of input metric pattern, and resolves it to one
  181. // or more canonical metric names.
  182. func resolveMetric(metrics map[string]interface{}, pattern string, path string) []string {
  183. results := []string{}
  184. // If a nested metric was requested, recurse optionally branching (via comma)
  185. parts := strings.SplitN(pattern, "/", 2)
  186. if len(parts) > 1 {
  187. for _, variation := range strings.Split(parts[0], ",") {
  188. if submetrics, ok := metrics[variation].(map[string]interface{}); !ok {
  189. utils.Fatalf("Failed to retrieve system metrics: %s", path+variation)
  190. return nil
  191. } else {
  192. results = append(results, resolveMetric(submetrics, parts[1], path+variation+"/")...)
  193. }
  194. }
  195. return results
  196. }
  197. // Depending what the last link is, return or expand
  198. for _, variation := range strings.Split(pattern, ",") {
  199. switch metric := metrics[variation].(type) {
  200. case float64:
  201. // Final metric value found, return as singleton
  202. results = append(results, path+variation)
  203. case map[string]interface{}:
  204. results = append(results, expandMetrics(metric, path+variation+"/")...)
  205. default:
  206. utils.Fatalf("Metric pattern resolved to unexpected type: %v", reflect.TypeOf(metric))
  207. return nil
  208. }
  209. }
  210. return results
  211. }
  212. // expandMetrics expands the entire tree of metrics into a flat list of paths.
  213. func expandMetrics(metrics map[string]interface{}, path string) []string {
  214. // Iterate over all fields and expand individually
  215. list := []string{}
  216. for name, metric := range metrics {
  217. switch metric := metric.(type) {
  218. case float64:
  219. // Final metric value found, append to list
  220. list = append(list, path+name)
  221. case map[string]interface{}:
  222. // Tree of metrics found, expand recursively
  223. list = append(list, expandMetrics(metric, path+name+"/")...)
  224. default:
  225. utils.Fatalf("Metric pattern %s resolved to unexpected type: %v", path+name, reflect.TypeOf(metric))
  226. return nil
  227. }
  228. }
  229. return list
  230. }
  231. // fetchMetric iterates over the metrics map and retrieves a specific one.
  232. func fetchMetric(metrics map[string]interface{}, metric string) float64 {
  233. parts, found := strings.Split(metric, "/"), true
  234. for _, part := range parts[:len(parts)-1] {
  235. metrics, found = metrics[part].(map[string]interface{})
  236. if !found {
  237. return 0
  238. }
  239. }
  240. if v, ok := metrics[parts[len(parts)-1]].(float64); ok {
  241. return v
  242. }
  243. return 0
  244. }
  245. // refreshCharts retrieves a next batch of metrics, and inserts all the new
  246. // values into the active datasets and charts
  247. func refreshCharts(client rpc.Client, metrics []string, data [][]float64, units []int, charts []*termui.LineChart, ctx *cli.Context, footer *termui.Par) (realign bool) {
  248. values, err := retrieveMetrics(client)
  249. for i, metric := range metrics {
  250. if len(data) < 512 {
  251. data[i] = append([]float64{fetchMetric(values, metric)}, data[i]...)
  252. } else {
  253. data[i] = append([]float64{fetchMetric(values, metric)}, data[i][:len(data[i])-1]...)
  254. }
  255. if updateChart(metric, data[i], &units[i], charts[i], err) {
  256. realign = true
  257. }
  258. }
  259. updateFooter(ctx, err, footer)
  260. return
  261. }
  262. // updateChart inserts a dataset into a line chart, scaling appropriately as to
  263. // not display weird labels, also updating the chart label accordingly.
  264. func updateChart(metric string, data []float64, base *int, chart *termui.LineChart, err error) (realign bool) {
  265. dataUnits := []string{"", "K", "M", "G", "T", "E"}
  266. timeUnits := []string{"ns", "µs", "ms", "s", "ks", "ms"}
  267. colors := []termui.Attribute{termui.ColorBlue, termui.ColorCyan, termui.ColorGreen, termui.ColorYellow, termui.ColorRed, termui.ColorRed}
  268. // Extract only part of the data that's actually visible
  269. if chart.Width*2 < len(data) {
  270. data = data[:chart.Width*2]
  271. }
  272. // Find the maximum value and scale under 1K
  273. high := 0.0
  274. if len(data) > 0 {
  275. high = data[0]
  276. for _, value := range data[1:] {
  277. high = math.Max(high, value)
  278. }
  279. }
  280. unit, scale := 0, 1.0
  281. for high >= 1000 && unit+1 < len(dataUnits) {
  282. high, unit, scale = high/1000, unit+1, scale*1000
  283. }
  284. // If the unit changes, re-create the chart (hack to set max height...)
  285. if unit != *base {
  286. realign, *base, *chart = true, unit, *createChart(chart.Height)
  287. }
  288. // Update the chart's data points with the scaled values
  289. if cap(chart.Data) < len(data) {
  290. chart.Data = make([]float64, len(data))
  291. }
  292. chart.Data = chart.Data[:len(data)]
  293. for i, value := range data {
  294. chart.Data[i] = value / scale
  295. }
  296. // Update the chart's label with the scale units
  297. units := dataUnits
  298. if strings.Contains(metric, "/Percentiles/") || strings.Contains(metric, "/pauses/") || strings.Contains(metric, "/time/") {
  299. units = timeUnits
  300. }
  301. chart.Border.Label = metric
  302. if len(units[unit]) > 0 {
  303. chart.Border.Label += " [" + units[unit] + "]"
  304. }
  305. chart.LineColor = colors[unit] | termui.AttrBold
  306. if err != nil {
  307. chart.LineColor = termui.ColorRed | termui.AttrBold
  308. }
  309. return
  310. }
  311. // createChart creates an empty line chart with the default configs.
  312. func createChart(height int) *termui.LineChart {
  313. chart := termui.NewLineChart()
  314. if runtime.GOOS == "windows" {
  315. chart.Mode = "dot"
  316. }
  317. chart.DataLabels = []string{""}
  318. chart.Height = height
  319. chart.AxesColor = termui.ColorWhite
  320. chart.PaddingBottom = -2
  321. chart.Border.LabelFgColor = chart.Border.FgColor | termui.AttrBold
  322. chart.Border.FgColor = chart.Border.BgColor
  323. return chart
  324. }
  325. // updateFooter updates the footer contents based on any encountered errors.
  326. func updateFooter(ctx *cli.Context, err error, footer *termui.Par) {
  327. // Generate the basic footer
  328. refresh := time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second
  329. footer.Text = fmt.Sprintf("Press Ctrl+C to quit. Refresh interval: %v.", refresh)
  330. footer.TextFgColor = termui.Theme().ParTextFg | termui.AttrBold
  331. // Append any encountered errors
  332. if err != nil {
  333. footer.Text = fmt.Sprintf("Error: %v.", err)
  334. footer.TextFgColor = termui.ColorRed | termui.AttrBold
  335. }
  336. }