diff --git a/README.md b/README.md index 75d4b8b..63a7826 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 | @@ -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. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 01b9410..3860f53 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -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) @@ -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) diff --git a/internal/ui/app.go b/internal/ui/app.go index 2c09994..ec7c0d9 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -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. @@ -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. @@ -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 ( @@ -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 { @@ -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 { @@ -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: @@ -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 } @@ -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): @@ -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) @@ -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) diff --git a/internal/ui/keys.go b/internal/ui/keys.go index 185767b..dd4af7f 100644 --- a/internal/ui/keys.go +++ b/internal/ui/keys.go @@ -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 @@ -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"), } @@ -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, } } @@ -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}, } } diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index d4858f4..edaada6 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -2,7 +2,9 @@ package ui import ( "fmt" + "io" "math" + "net/http" "os" "strings" "testing" @@ -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") + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 6702bc1..ba431eb 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -44,6 +44,7 @@ type Config struct { Open bool // open the page in the default browser Out io.Writer Denied string // body of a 403; default "promtop only answers to localhost" + Fed bool // scrapes arrive through Ingest; Start runs no scrape loop } // Server scrapes the target and serves the dashboard. @@ -61,6 +62,9 @@ type Server struct { cacheSeq int cache map[string][]byte // frame JSON by options, for the current seq + ln net.Listener // set by Listen + page string + start sync.Once stop sync.Once done chan struct{} // closed by Close: ends polling and event streams @@ -81,7 +85,9 @@ func New(cfg Config) *Server { // Start begins scraping in the background; calls after the first do nothing. func (s *Server) Start() { s.start.Do(func() { - s.wg.Go(s.scrapeLoop) + if !s.cfg.Fed { + s.wg.Go(s.scrapeLoop) + } }) } @@ -94,10 +100,29 @@ func (s *Server) Close() { // Run listens, opens the browser if asked and serves until ctx is done. func (s *Server) Run(ctx context.Context) error { - ln, err := net.Listen("tcp", s.cfg.Addr) + page, err := s.Listen() if err != nil { return err } + _, _ = fmt.Fprintf(s.cfg.Out, "promtop: dashboard for %s at %s (Ctrl+C to stop)\n", s.cfg.Source, page) + if addr := s.ln.Addr().(*net.TCPAddr); !addr.IP.IsLoopback() { + _, _ = fmt.Fprintf(s.cfg.Out, "promtop: listening on %s — anyone who can reach it sees these metrics\n", addr) + } + if s.cfg.Open { + if err := OpenBrowser(page); err != nil { + _, _ = fmt.Fprintf(s.cfg.Out, "promtop: could not open a browser (%v); open %s yourself\n", err, page) + } + } + return s.Serve(ctx) +} + +// Listen binds the configured address and returns the page's URL. Serve +// then answers on it. +func (s *Server) Listen() (string, error) { + ln, err := net.Listen("tcp", s.cfg.Addr) + if err != nil { + return "", err + } addr := ln.Addr().(*net.TCPAddr) host := addr.IP.String() if addr.IP.IsUnspecified() { @@ -107,13 +132,18 @@ func (s *Server) Run(ctx context.Context) error { if q := s.query(); q != "" { page += "#" + q } - _, _ = fmt.Fprintf(s.cfg.Out, "promtop: dashboard for %s at %s (Ctrl+C to stop)\n", s.cfg.Source, page) - if !addr.IP.IsLoopback() { - _, _ = fmt.Fprintf(s.cfg.Out, "promtop: listening on %s — anyone who can reach it sees these metrics\n", addr) - } + s.ln, s.page = ln, page + return page, nil +} +// Serve starts scraping and serves on the listener from Listen until ctx is +// done. A loopback listener only answers to loopback host names. +func (s *Server) Serve(ctx context.Context) error { + if s.ln == nil { + return errors.New("web: Serve before Listen") + } var allow func(*http.Request) bool - if addr.IP.IsLoopback() { + if s.ln.Addr().(*net.TCPAddr).IP.IsLoopback() { allow = HostOnly } s.Start() @@ -125,12 +155,7 @@ func (s *Server) Run(ctx context.Context) error { defer cancel() _ = srv.Shutdown(sctx) }() - if s.cfg.Open { - if err := openBrowser(page); err != nil { - _, _ = fmt.Fprintf(s.cfg.Out, "promtop: could not open a browser (%v); open %s yourself\n", err, page) - } - } - if err := srv.Serve(ln); !errors.Is(err, http.ErrServerClosed) { + if err := srv.Serve(s.ln); !errors.Is(err, http.ErrServerClosed) { return err } return nil @@ -170,6 +195,19 @@ func (s *Server) scrapeLoop() { } } +// Ingest adds a scrape made elsewhere; it is how a Fed server gets data. +// The families are only read, so the caller may keep using them. +func (s *Server) Ingest(r scrape.Result) { s.ingest(r) } + +// SetInterval updates the scrape interval the page shows; for a Fed server +// whose feeder changes its pace. +func (s *Server) SetInterval(d time.Duration) { + s.mu.Lock() + s.cfg.Interval = d + s.seq++ // drop cached frames + s.mu.Unlock() +} + func (s *Server) ingest(r scrape.Result) { s.mu.Lock() s.lastDur, s.lastAt, s.lastErr = r.Duration, r.At, r.Err @@ -441,9 +479,9 @@ func (s *Server) panel(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(append(body, '\n')) } -// openBrowser opens url with $BROWSER when set (BROWSER=true turns it off), +// OpenBrowser opens url with $BROWSER when set (BROWSER=true turns it off), // otherwise with the platform's default handler. -func openBrowser(url string) error { +func OpenBrowser(url string) error { var cmd *exec.Cmd switch b := os.Getenv("BROWSER"); { case b != "":