github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/chain/neatio/monitorcmd.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"reflect"
     7  	"runtime"
     8  	"sort"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/gizak/termui"
    13  	"github.com/neatlab/neatio/network/node"
    14  	"github.com/neatlab/neatio/network/rpc"
    15  	"github.com/neatlab/neatio/utilities/utils"
    16  	"gopkg.in/urfave/cli.v1"
    17  )
    18  
    19  var (
    20  	monitorCommandAttachFlag = cli.StringFlag{
    21  		Name:  "attach",
    22  		Value: node.DefaultIPCEndpoint(clientIdentifier),
    23  		Usage: "API endpoint to attach to",
    24  	}
    25  	monitorCommandRowsFlag = cli.IntFlag{
    26  		Name:  "rows",
    27  		Value: 5,
    28  		Usage: "Maximum rows in the chart grid",
    29  	}
    30  	monitorCommandRefreshFlag = cli.IntFlag{
    31  		Name:  "refresh",
    32  		Value: 3,
    33  		Usage: "Refresh interval in seconds",
    34  	}
    35  	monitorCommand = cli.Command{
    36  		Action:    utils.MigrateFlags(monitor),
    37  		Name:      "monitor",
    38  		Usage:     "Monitor and visualize node metrics",
    39  		ArgsUsage: " ",
    40  		Category:  "MONITOR COMMANDS",
    41  		Description: `
    42  The Geth monitor is a tool to collect and visualize various internal metrics
    43  gathered by the node, supporting different chart types as well as the capacity
    44  to display multiple metrics simultaneously.
    45  `,
    46  		Flags: []cli.Flag{
    47  			monitorCommandAttachFlag,
    48  			monitorCommandRowsFlag,
    49  			monitorCommandRefreshFlag,
    50  		},
    51  	}
    52  )
    53  
    54  func monitor(ctx *cli.Context) error {
    55  	var (
    56  		client *rpc.Client
    57  		err    error
    58  	)
    59  
    60  	endpoint := ctx.String(monitorCommandAttachFlag.Name)
    61  	if client, err = dialRPC(endpoint); err != nil {
    62  		utils.Fatalf("Unable to attach to neatio node: %v", err)
    63  	}
    64  	defer client.Close()
    65  
    66  	metrics, err := retrieveMetrics(client)
    67  	if err != nil {
    68  		utils.Fatalf("Failed to retrieve system metrics: %v", err)
    69  	}
    70  	monitored := resolveMetrics(metrics, ctx.Args())
    71  	if len(monitored) == 0 {
    72  		list := expandMetrics(metrics, "")
    73  		sort.Strings(list)
    74  
    75  		if len(list) > 0 {
    76  			utils.Fatalf("No metrics specified.\n\nAvailable:\n - %s", strings.Join(list, "\n - "))
    77  		} else {
    78  			utils.Fatalf("No metrics collected by neatio (--%s).\n", utils.MetricsEnabledFlag.Name)
    79  		}
    80  	}
    81  	sort.Strings(monitored)
    82  	if cols := len(monitored) / ctx.Int(monitorCommandRowsFlag.Name); cols > 6 {
    83  		utils.Fatalf("Requested metrics (%d) spans more that 6 columns:\n - %s", len(monitored), strings.Join(monitored, "\n - "))
    84  	}
    85  
    86  	if err := termui.Init(); err != nil {
    87  		utils.Fatalf("Unable to initialize terminal UI: %v", err)
    88  	}
    89  	defer termui.Close()
    90  
    91  	rows := len(monitored)
    92  	if max := ctx.Int(monitorCommandRowsFlag.Name); rows > max {
    93  		rows = max
    94  	}
    95  	cols := (len(monitored) + rows - 1) / rows
    96  	for i := 0; i < rows; i++ {
    97  		termui.Body.AddRows(termui.NewRow())
    98  	}
    99  
   100  	footer := termui.NewPar("")
   101  	footer.Block.Border = true
   102  	footer.Height = 3
   103  
   104  	charts := make([]*termui.LineChart, len(monitored))
   105  	units := make([]int, len(monitored))
   106  	data := make([][]float64, len(monitored))
   107  	for i := 0; i < len(monitored); i++ {
   108  		charts[i] = createChart((termui.TermHeight() - footer.Height) / rows)
   109  		row := termui.Body.Rows[i%rows]
   110  		row.Cols = append(row.Cols, termui.NewCol(12/cols, 0, charts[i]))
   111  	}
   112  	termui.Body.AddRows(termui.NewRow(termui.NewCol(12, 0, footer)))
   113  
   114  	refreshCharts(client, monitored, data, units, charts, ctx, footer)
   115  	termui.Body.Align()
   116  	termui.Render(termui.Body)
   117  
   118  	termui.Handle("/sys/kbd/C-c", func(termui.Event) {
   119  		termui.StopLoop()
   120  	})
   121  	termui.Handle("/sys/wnd/resize", func(termui.Event) {
   122  		termui.Body.Width = termui.TermWidth()
   123  		for _, chart := range charts {
   124  			chart.Height = (termui.TermHeight() - footer.Height) / rows
   125  		}
   126  		termui.Body.Align()
   127  		termui.Render(termui.Body)
   128  	})
   129  	go func() {
   130  		tick := time.NewTicker(time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second)
   131  		for range tick.C {
   132  			if refreshCharts(client, monitored, data, units, charts, ctx, footer) {
   133  				termui.Body.Align()
   134  			}
   135  			termui.Render(termui.Body)
   136  		}
   137  	}()
   138  	termui.Loop()
   139  	return nil
   140  }
   141  
   142  func retrieveMetrics(client *rpc.Client) (map[string]interface{}, error) {
   143  	var metrics map[string]interface{}
   144  	err := client.Call(&metrics, "debug_metrics", true)
   145  	return metrics, err
   146  }
   147  
   148  func resolveMetrics(metrics map[string]interface{}, patterns []string) []string {
   149  	res := []string{}
   150  	for _, pattern := range patterns {
   151  		res = append(res, resolveMetric(metrics, pattern, "")...)
   152  	}
   153  	return res
   154  }
   155  
   156  func resolveMetric(metrics map[string]interface{}, pattern string, path string) []string {
   157  	results := []string{}
   158  
   159  	parts := strings.SplitN(pattern, "/", 2)
   160  	if len(parts) > 1 {
   161  		for _, variation := range strings.Split(parts[0], ",") {
   162  			if submetrics, ok := metrics[variation].(map[string]interface{}); !ok {
   163  				utils.Fatalf("Failed to retrieve system metrics: %s", path+variation)
   164  				return nil
   165  			} else {
   166  				results = append(results, resolveMetric(submetrics, parts[1], path+variation+"/")...)
   167  			}
   168  		}
   169  		return results
   170  	}
   171  
   172  	for _, variation := range strings.Split(pattern, ",") {
   173  		switch metric := metrics[variation].(type) {
   174  		case float64:
   175  
   176  			results = append(results, path+variation)
   177  
   178  		case map[string]interface{}:
   179  			results = append(results, expandMetrics(metric, path+variation+"/")...)
   180  
   181  		default:
   182  			utils.Fatalf("Metric pattern resolved to unexpected type: %v", reflect.TypeOf(metric))
   183  			return nil
   184  		}
   185  	}
   186  	return results
   187  }
   188  
   189  func expandMetrics(metrics map[string]interface{}, path string) []string {
   190  
   191  	list := []string{}
   192  	for name, metric := range metrics {
   193  		switch metric := metric.(type) {
   194  		case float64:
   195  
   196  			list = append(list, path+name)
   197  
   198  		case map[string]interface{}:
   199  
   200  			list = append(list, expandMetrics(metric, path+name+"/")...)
   201  
   202  		default:
   203  			utils.Fatalf("Metric pattern %s resolved to unexpected type: %v", path+name, reflect.TypeOf(metric))
   204  			return nil
   205  		}
   206  	}
   207  	return list
   208  }
   209  
   210  func fetchMetric(metrics map[string]interface{}, metric string) float64 {
   211  	parts := strings.Split(metric, "/")
   212  	for _, part := range parts[:len(parts)-1] {
   213  		var found bool
   214  		metrics, found = metrics[part].(map[string]interface{})
   215  		if !found {
   216  			return 0
   217  		}
   218  	}
   219  	if v, ok := metrics[parts[len(parts)-1]].(float64); ok {
   220  		return v
   221  	}
   222  	return 0
   223  }
   224  
   225  func refreshCharts(client *rpc.Client, metrics []string, data [][]float64, units []int, charts []*termui.LineChart, ctx *cli.Context, footer *termui.Par) (realign bool) {
   226  	values, err := retrieveMetrics(client)
   227  	for i, metric := range metrics {
   228  		if len(data) < 512 {
   229  			data[i] = append([]float64{fetchMetric(values, metric)}, data[i]...)
   230  		} else {
   231  			data[i] = append([]float64{fetchMetric(values, metric)}, data[i][:len(data[i])-1]...)
   232  		}
   233  		if updateChart(metric, data[i], &units[i], charts[i], err) {
   234  			realign = true
   235  		}
   236  	}
   237  	updateFooter(ctx, err, footer)
   238  	return
   239  }
   240  
   241  func updateChart(metric string, data []float64, base *int, chart *termui.LineChart, err error) (realign bool) {
   242  	dataUnits := []string{"", "K", "M", "G", "T", "E"}
   243  	timeUnits := []string{"ns", "µs", "ms", "s", "ks", "ms"}
   244  	colors := []termui.Attribute{termui.ColorBlue, termui.ColorCyan, termui.ColorGreen, termui.ColorYellow, termui.ColorRed, termui.ColorRed}
   245  
   246  	if chart.Width*2 < len(data) {
   247  		data = data[:chart.Width*2]
   248  	}
   249  
   250  	high := 0.0
   251  	if len(data) > 0 {
   252  		high = data[0]
   253  		for _, value := range data[1:] {
   254  			high = math.Max(high, value)
   255  		}
   256  	}
   257  	unit, scale := 0, 1.0
   258  	for high >= 1000 && unit+1 < len(dataUnits) {
   259  		high, unit, scale = high/1000, unit+1, scale*1000
   260  	}
   261  
   262  	if unit != *base {
   263  		realign, *base, *chart = true, unit, *createChart(chart.Height)
   264  	}
   265  
   266  	if cap(chart.Data) < len(data) {
   267  		chart.Data = make([]float64, len(data))
   268  	}
   269  	chart.Data = chart.Data[:len(data)]
   270  	for i, value := range data {
   271  		chart.Data[i] = value / scale
   272  	}
   273  
   274  	units := dataUnits
   275  	if strings.Contains(metric, "/Percentiles/") || strings.Contains(metric, "/pauses/") || strings.Contains(metric, "/time/") {
   276  		units = timeUnits
   277  	}
   278  	chart.BorderLabel = metric
   279  	if len(units[unit]) > 0 {
   280  		chart.BorderLabel += " [" + units[unit] + "]"
   281  	}
   282  	chart.LineColor = colors[unit] | termui.AttrBold
   283  	if err != nil {
   284  		chart.LineColor = termui.ColorRed | termui.AttrBold
   285  	}
   286  	return
   287  }
   288  
   289  func createChart(height int) *termui.LineChart {
   290  	chart := termui.NewLineChart()
   291  	if runtime.GOOS == "windows" {
   292  		chart.Mode = "dot"
   293  	}
   294  	chart.DataLabels = []string{""}
   295  	chart.Height = height
   296  	chart.AxesColor = termui.ColorWhite
   297  	chart.PaddingBottom = -2
   298  
   299  	chart.BorderLabelFg = chart.BorderFg | termui.AttrBold
   300  	chart.BorderFg = chart.BorderBg
   301  
   302  	return chart
   303  }
   304  
   305  func updateFooter(ctx *cli.Context, err error, footer *termui.Par) {
   306  
   307  	refresh := time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second
   308  	footer.Text = fmt.Sprintf("Press Ctrl+C to quit. Refresh interval: %v.", refresh)
   309  	footer.TextFgColor = termui.ThemeAttr("par.fg") | termui.AttrBold
   310  
   311  	if err != nil {
   312  		footer.Text = fmt.Sprintf("Error: %v.", err)
   313  		footer.TextFgColor = termui.ColorRed | termui.AttrBold
   314  	}
   315  }