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