Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ metric (`#filter=http&metric=…`), so a link reopens the same view. The page on
`localhost`; `-web-addr 0.0.0.0:9999` exposes it to the network on purpose. `$BROWSER` picks the
browser (`BROWSER=true` just prints the URL).

From the terminal UI, `w` starts the same page on the side and opens it; the footer shows its
URL. It is fed by the terminal's scrapes, so it follows its interval and pause, and its history
starts at the press.

![promtop web dashboard on the bundled demo](docs/web.png)

## Embed in your service
Expand Down Expand Up @@ -218,6 +222,7 @@ Layout:
| `a` | show all metrics / curated |
| `p`, `space` | pause |
| `+` / `-` | longer / shorter scrape interval |
| `w` | open the web dashboard (started on first press) |
| `?` | help |
| `esc`, `q` | back / quit |

Expand All @@ -237,7 +242,7 @@ wheel, right-click to go back.
-width n width for -once
-no-color disable colours (NO_COLOR is honoured too)
-web serve the dashboard over HTTP and open it in the browser
-web-addr addr listen address for -web (default 127.0.0.1:0, a free local port)
-web-addr addr listen address for -web and the w key (default 127.0.0.1:0, a free local port)
```

`promtop render -h` and `promtop record -h` list the flags of the snapshot commands.
Expand Down
4 changes: 2 additions & 2 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func runLive(args []string) int {
filter = fs.String("f", "", "only show metrics matching this regex")
showVer = fs.Bool("version", false, "print version and exit")
web = fs.Bool("web", false, "serve the dashboard over HTTP and open it in the browser instead of the terminal UI")
webAddr = fs.String("web-addr", "127.0.0.1:0", "listen address for -web (default: a free port on localhost)")
webAddr = fs.String("web-addr", "127.0.0.1:0", "listen address for -web and the w key (default: a free port on localhost)")
)
fs.Usage = func() {
_, _ = fmt.Fprint(fs.Output(), usage)
Expand Down Expand Up @@ -109,7 +109,7 @@ func runLive(args []string) int {
}
app := ui.New(ui.Config{
Source: src, Interval: *sf.interval, History: *history, Color: color,
ShowAll: *all, Filter: *filter, Width: *width,
ShowAll: *all, Filter: *filter, Width: *width, WebAddr: *webAddr,
})
if *once {
err = app.RunOnce(ctx)
Expand Down
64 changes: 60 additions & 4 deletions internal/ui/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ import (
"github.com/charmbracelet/colorprofile"
"github.com/charmbracelet/x/term"

"github.com/igorrius/promtop/internal/expo"
"github.com/igorrius/promtop/internal/scrape"
"github.com/igorrius/promtop/internal/store"
"github.com/igorrius/promtop/internal/view"
webui "github.com/igorrius/promtop/internal/web"
)

// Config configures the application.
Expand All @@ -36,6 +38,7 @@ type Config struct {
Filter string
Width int // --once: render width (0 = terminal or 120)
Out io.Writer
WebAddr string // listen address of the web dashboard the w key starts
}

// App is the Bubble Tea model.
Expand Down Expand Up @@ -72,6 +75,11 @@ type App struct {
lastDur time.Duration
lastAt time.Time
inflight bool
lastFams []*expo.Family // the last good scrape, to seed the web dashboard

web *webui.Server // started by the w key, fed with our scrapes
webURL string
webErr error
}

type (
Expand Down Expand Up @@ -144,6 +152,7 @@ func (a *App) ingest(r scrape.Result) {
return
}
a.lastErr = nil
a.lastFams = r.Families
a.st.Ingest(r.Families, r.At)
a.dirty = true
if n := len(a.st.Families); n != a.families {
Expand Down Expand Up @@ -252,6 +261,8 @@ func (a *App) Run(ctx context.Context) error {
if !ok || !term.IsTerminal(f.Fd()) {
return errors.New("stdout is not a terminal; use --once for a one-shot snapshot")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel() // stops the web dashboard too
a.ctx = ctx
opts := []tea.ProgramOption{tea.WithContext(ctx), tea.WithOutput(a.cfg.Out)}
if !a.cfg.Color {
Expand Down Expand Up @@ -298,6 +309,9 @@ func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case scrapeMsg:
a.inflight = false
a.ingest(scrape.Result(msg))
if a.web != nil {
a.web.Ingest(scrape.Result(msg))
}
case tea.KeyPressMsg:
cmd = a.handleKey(msg)
case tea.MouseClickMsg:
Expand Down Expand Up @@ -347,7 +361,7 @@ func (a *App) handleKey(k tea.KeyPressMsg) tea.Cmd {
}
switch {
case key.Matches(k, km.Quit):
if a.detail != nil && k.String() == "q" {
if a.detail != nil && k.String() != "ctrl+c" {
a.detail = nil
return nil
}
Expand All @@ -362,9 +376,11 @@ func (a *App) handleKey(k tea.KeyPressMsg) tea.Cmd {
a.showAll = !a.showAll
a.dirty = true
case key.Matches(k, km.Longer):
a.interval = nextInterval(a.interval, 1)
a.setInterval(nextInterval(a.interval, 1))
case key.Matches(k, km.Shorter):
a.interval = nextInterval(a.interval, -1)
a.setInterval(nextInterval(a.interval, -1))
case key.Matches(k, km.Web):
a.openWeb()
case key.Matches(k, km.Help):
a.showHelp = true
case key.Matches(k, km.Clear):
Expand All @@ -385,6 +401,40 @@ func (a *App) handleKey(k tea.KeyPressMsg) tea.Cmd {
return nil
}

func (a *App) setInterval(d time.Duration) {
a.interval = d
if a.web != nil {
a.web.SetInterval(d)
}
}

// openWeb starts the web dashboard on the first press and opens it in the
// browser. The page shows the scrapes this app makes from then on.
func (a *App) openWeb() {
if a.web == nil {
srv := webui.New(webui.Config{
Source: a.cfg.Source, Interval: a.interval, History: a.cfg.History,
ShowAll: a.showAll, Filter: a.filterSrc, Addr: a.cfg.WebAddr, Fed: true,
})
u, err := srv.Listen()
if err != nil {
a.webErr = err
return
}
a.web, a.webURL = srv, u
ctx := a.ctx
go func() { _ = srv.Serve(ctx) }()
// The latest scrape, so the page has something to show at once.
if a.lastFams != nil {
srv.Ingest(scrape.Result{Families: a.lastFams, At: a.lastAt, Duration: a.lastDur})
}
}
a.webErr = nil
if err := webui.OpenBrowser(a.webURL); err != nil {
a.webErr = fmt.Errorf("no browser (%w); open %s", err, a.webURL)
}
}

func (a *App) gridKey(k tea.KeyPressMsg) {
km, lay := a.keys, a.lay
page := max(1, a.bodyHeight()/PanelHeight)
Expand Down Expand Up @@ -559,10 +609,16 @@ func (a *App) footer() string {
}
bindings := a.keys.gridHelp()
prefix := ""
switch {
case a.webErr != nil:
prefix = t.bold(t.err, "web: "+a.webErr.Error()) + " "
case a.web != nil:
prefix = t.bold(t.ok, "web ") + t.paint(t.dim, a.webURL) + " "
}
if a.detail != nil {
bindings = a.keys.detailHelp()
} else if a.filter != nil {
prefix = t.bold(t.warn, "filter: "+a.input.Value()) + " " + t.bold(t.accent, "c") + t.paint(t.dim, " clear") + " "
prefix += t.bold(t.warn, "filter: "+a.input.Value()) + " " + t.bold(t.accent, "c") + t.paint(t.dim, " clear") + " "
}
a.help.SetWidth(a.w - 2 - vlen(prefix))
return " " + prefix + a.help.ShortHelpView(bindings)
Expand Down
9 changes: 5 additions & 4 deletions internal/ui/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type keyMap struct {
Open, Back key.Binding
Filter, Clear, All key.Binding
Pause, Longer, Shorter key.Binding
Help, Quit key.Binding
Web, Help, Quit key.Binding

// Detail view
Series, Line key.Binding
Expand Down Expand Up @@ -39,8 +39,9 @@ func newKeyMap() keyMap {
Pause: b([]string{"p", "space"}, "p", "pause"),
Longer: b([]string{"+", "="}, "+", "longer interval"),
Shorter: b([]string{"-", "_"}, "-", "shorter interval"),
Web: b([]string{"w", "W"}, "w", "web"),
Help: b([]string{"?"}, "?", "help"),
Quit: b([]string{"q", "ctrl+c"}, "q", "quit"),
Quit: b([]string{"q", "Q", "ctrl+c"}, "q", "quit"),
Series: b([]string{"up", "down"}, "↑↓", "series"),
Line: b([]string{"left", "right", "tab"}, "←→", "line"),
}
Expand All @@ -56,7 +57,7 @@ var (

func (k keyMap) gridHelp() []key.Binding {
return []key.Binding{
move, k.Open, k.Filter, k.All, sections, k.Pause, interval, k.Help, k.Quit,
move, k.Open, k.Filter, k.All, sections, k.Pause, interval, k.Web, k.Help, k.Quit,
}
}

Expand All @@ -69,6 +70,6 @@ func (k keyMap) fullHelp() [][]key.Binding {
{k.Up, k.Down, k.Left, k.Right, k.PgUp, k.PgDown},
{k.Home, k.End, k.PrevSec, k.NextSec, k.Open, k.Back},
{k.Filter, k.Clear, k.All, k.Pause, k.Longer, k.Shorter},
{k.Help, k.Quit},
{k.Web, k.Help, k.Quit},
}
}
56 changes: 56 additions & 0 deletions internal/ui/ui_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package ui

import (
"fmt"
"io"
"math"
"net/http"
"os"
"strings"
"testing"
Expand Down Expand Up @@ -376,3 +378,57 @@ func TestDetailAxis(t *testing.T) {
t.Error("type and widget repeated in the title")
}
}

func TestQuitAnyCase(t *testing.T) {
for _, k := range []string{"q", "Q"} {
a := newTestApp(t, 120, 40)
if _, cmd := a.Update(tea.KeyPressMsg{Code: []rune(k)[0], Text: k}); cmd == nil {
t.Errorf("%s did not quit", k)
}
press(a, "enter", k)
if a.detail != nil {
t.Errorf("%s did not close details", k)
}
}
}

func TestWebKey(t *testing.T) {
t.Setenv("BROWSER", "true")
a := newTestApp(t, 120, 40)
a.cfg.WebAddr = "127.0.0.1:0"
a.ctx = t.Context()
press(a, "w")
if a.web == nil || a.webErr != nil {
t.Fatalf("w: web = %v, err = %v", a.web, a.webErr)
}
defer a.web.Close()
if !strings.Contains(a.footer(), a.webURL) {
t.Errorf("footer does not show %s: %q", a.webURL, a.footer())
}
get := func(path string) string {
t.Helper()
res, err := http.Get(strings.TrimSuffix(a.webURL, "/") + path)
if err != nil {
t.Fatal(err)
}
defer func() { _ = res.Body.Close() }()
b, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
t.Fatalf("%s: %d %s", path, res.StatusCode, b)
}
return string(b)
}
// Seeded with the last scrape, then fed with ours.
if body := get("/api/panel?id=demo_requests_total"); !strings.Contains(body, "demo_requests_total") {
t.Errorf("panel = %s", body)
}
srv := a.web
press(a, "w")
if a.web != srv {
t.Error("second w started another server")
}
press(a, "+")
if !strings.Contains(get("/api/panel?id=demo_requests_total"), fmt.Sprintf(`"interval":%g`, a.interval.Seconds())) {
t.Error("interval change did not reach the web dashboard")
}
}
Loading
Loading