You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.2 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "text/tabwriter"
  7. "time"
  8. )
  9. const (
  10. // Default refresh rate - 200ms
  11. defaultRefreshRate = time.Millisecond * 200
  12. )
  13. // Ton - table of nodes.
  14. //
  15. // It produces the unordered list of nodes and updates it periodically.
  16. //
  17. // Default output is stdout, but it could be changed. Note if you want for
  18. // refresh to work properly, output must support [ANSI escape
  19. // codes](http://en.wikipedia.org/wiki/ANSI_escape_code).
  20. //
  21. // Ton was inspired by [Linux top
  22. // program](https://en.wikipedia.org/wiki/Top_(software)) as the name suggests.
  23. type Ton struct {
  24. monitor *Monitor
  25. RefreshRate time.Duration
  26. Output io.Writer
  27. quit chan struct{}
  28. }
  29. func NewTon(m *Monitor) *Ton {
  30. return &Ton{
  31. RefreshRate: defaultRefreshRate,
  32. Output: os.Stdout,
  33. quit: make(chan struct{}),
  34. monitor: m,
  35. }
  36. }
  37. func (o *Ton) Start() {
  38. clearScreen(o.Output)
  39. o.Print()
  40. go o.refresher()
  41. }
  42. func (o *Ton) Print() {
  43. moveCursor(o.Output, 1, 1)
  44. o.printHeader()
  45. fmt.Println()
  46. o.printTable()
  47. }
  48. func (o *Ton) Stop() {
  49. close(o.quit)
  50. }
  51. func (o *Ton) printHeader() {
  52. n := o.monitor.Network
  53. fmt.Fprintf(o.Output, "%v up %.2f%%\n", n.StartTime(), n.Uptime())
  54. fmt.Println()
  55. fmt.Fprintf(o.Output, "Height: %d\n", n.Height)
  56. fmt.Fprintf(o.Output, "Avg block time: %.3f ms\n", n.AvgBlockTime)
  57. fmt.Fprintf(o.Output, "Avg tx throughput: %.0f per sec\n", n.AvgTxThroughput)
  58. fmt.Fprintf(o.Output, "Avg block latency: %.3f ms\n", n.AvgBlockLatency)
  59. fmt.Fprintf(o.Output, "Active nodes: %d/%d (health: %s) Validators: %d\n", n.NumNodesMonitoredOnline, n.NumNodesMonitored, n.GetHealthString(), n.NumValidators)
  60. }
  61. func (o *Ton) printTable() {
  62. w := tabwriter.NewWriter(o.Output, 0, 0, 5, ' ', 0)
  63. fmt.Fprintln(w, "NAME\tHEIGHT\tBLOCK LATENCY\tONLINE\tVALIDATOR\t")
  64. for _, n := range o.monitor.Nodes {
  65. fmt.Fprintln(w, fmt.Sprintf("%s\t%d\t%.3f ms\t%v\t%v\t", n.Name, n.Height, n.BlockLatency, n.Online, n.IsValidator))
  66. }
  67. w.Flush()
  68. }
  69. // Internal loop for refreshing
  70. func (o *Ton) refresher() {
  71. for {
  72. select {
  73. case <-o.quit:
  74. return
  75. case <-time.After(o.RefreshRate):
  76. o.Print()
  77. }
  78. }
  79. }
  80. func clearScreen(w io.Writer) {
  81. fmt.Fprint(w, "\033[2J")
  82. }
  83. func moveCursor(w io.Writer, x int, y int) {
  84. fmt.Fprintf(w, "\033[%d;%dH", x, y)
  85. }