feat: NetBox insights, host tools and configurable TUI
Test / test (pull_request) Successful in 4m15s

- info/open/whois: NetBox details (site, nested locations, rack units,
  role, platform, tenant, IPs per interface), web page, reverse IP lookup
- cache status, site, role, platform, tenant, location chain and rack;
  ask before connecting to hosts in ssh.warn_status (--force skips)
- ssh rules and command restrictions match site/role/platform/tenant/status
- tui.columns selects what the TUI shows; optional TCP reachability column;
  detail view (Ctrl+L), NetBox page (Ctrl+G), status/location filters
- resolver.fallback tries other strategies' addresses when unreachable
- copy-id, known-hosts reset and address-change notices
- export ansible (YAML/INI) and export ssh-config
- token: keyring stores NetBox tokens in the system keyring
- fix stale menu number in testenv configure test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-18 12:33:59 +01:00
1 parent e5bde9c61f
commit 1660bb3098
39 files changed
+4868 -96

No files matched your search

+370 -23
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"net"
"sort"
"strconv"
"strings"
@@ -53,6 +54,25 @@ type noteResultMsg struct {
saved bool
}
// reachMsg is the result of probing a listed host's SSH port.
type reachMsg struct {
key string
state reachState
}
// detailMsg carries the text of the detail view (ctrl+l).
type detailMsg struct {
key string
text string
err error
}
// flashMsg is a short notice in the footer, e.g. after opening NetBox.
type flashMsg struct {
text string
err error
}
type searchResultMsg struct {
query string
seq int
@@ -73,6 +93,11 @@ type hostItem struct {
ip string
kind string
tags []string
status string
site, role string
platform, tenant string
cluster string
location string // site › locations › rack › U
}
func (h hostItem) Title() string {
@@ -86,8 +111,85 @@ func (h hostItem) FilterValue() string { return h.name }
// --- compact list delegate ---
// reachState is the result of the reachability probe of a host.
type reachState uint8
const (
reachUnknown reachState = iota
reachPending
reachUp
reachDown
reachSkipped // behind a jump host: not probed
)
// compactDelegate shares the model's marks so marked hosts show a dot.
type compactDelegate struct{ marked map[string]bool }
// With reach set, a column shows whether the SSH port answers.
type compactDelegate struct {
marked map[string]bool
reach map[string]reachState
columns []string // nil = defaultColumns
}
// defaultColumns matches config.DefaultTUIColumns.
var defaultColumns = []string{"alias", "ip", "source", "status"}
var (
dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
attrStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))
aliasStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("109"))
statusStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("214"))
)
// column renders one configured column of a host, or "" when it is empty.
func (h hostItem) column(name string) string {
attr := func(key, value string) string {
if value == "" {
return ""
}
return attrStyle.Render(key + ":" + value)
}
switch name {
case "alias":
if h.alias != "" {
return aliasStyle.Render("→ " + h.alias)
}
case "ip":
if h.ip != "" {
return dimStyle.Render(h.ip)
}
case "kind":
if h.kind != "" {
return "[" + h.kind + "]"
}
case "source":
if h.provenance != "" {
return "[" + h.provenance + "]"
}
case "status":
if h.status != "" && !strings.EqualFold(h.status, "active") {
return statusStyle.Render("[" + h.status + "]")
}
case "site":
return attr("site", h.site)
case "location":
if h.location != "" {
return attrStyle.Render("⌂ " + h.location)
}
case "role":
return attr("role", h.role)
case "platform":
return attr("platform", h.platform)
case "tenant":
return attr("tenant", h.tenant)
case "cluster":
return attr("cluster", h.cluster)
case "tags":
if len(h.tags) > 0 {
return attrStyle.Render("#" + strings.Join(h.tags, " #"))
}
}
return ""
}
func (d compactDelegate) Height() int { return 1 }
func (d compactDelegate) Spacing() int { return 0 }
@@ -101,19 +203,35 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
if d.marked[h.key()] {
mark = "● "
}
title := h.Title()
if h.alias != "" {
title += " " + lipgloss.NewStyle().Foreground(lipgloss.Color("109")).Render("→ "+h.alias)
}
badge := ""
if h.pinned {
badge = "◆ "
} else if h.favorite {
badge = "★ "
}
line := fmt.Sprintf(" %s%s %s", mark+badge, title, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
if h.provenance != "" {
line += " [" + h.provenance + "]"
columns := d.columns
if columns == nil {
columns = defaultColumns
}
// The reachability mark is a fixed-width prefix so names stay aligned.
reach := ""
if d.reach != nil {
switch d.reach[h.key()] {
case reachUp:
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("2")).Render("✓") + " "
case reachDown:
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("✗") + " "
case reachPending:
reach = dimStyle.Render("·") + " "
default:
reach = " "
}
}
line := " " + mark + reach + badge + h.Title()
for _, name := range columns {
if text := h.column(name); text != "" {
line += " " + text
}
}
if index == m.Index() {
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
@@ -124,24 +242,47 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
// --- filter ---
type filterOpts struct {
tags []string
kind string
tags []string
kind string
status, site, role, platform, tenant string
location string
}
func (f filterOpts) empty() bool {
return len(f.tags) == 0 && f.kind == "" && f.status == "" && f.site == "" && f.role == "" && f.platform == "" && f.tenant == "" && f.location == ""
}
func parseFilter(s string) filterOpts {
var f filterOpts
for _, part := range strings.Fields(s) {
if after, ok := strings.CutPrefix(part, "tag:"); ok {
f.tags = append(f.tags, after)
} else if after, ok := strings.CutPrefix(part, "kind:"); ok {
f.kind = after
key, value, ok := strings.Cut(part, ":")
if !ok {
continue
}
switch strings.ToLower(key) {
case "tag":
f.tags = append(f.tags, value)
case "kind":
f.kind = value
case "status":
f.status = value
case "site":
f.site = value
case "role":
f.role = value
case "platform":
f.platform = value
case "tenant":
f.tenant = value
case "location", "rack":
f.location = value
}
}
return f
}
func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
if len(f.tags) == 0 && f.kind == "" {
if f.empty() {
return entries
}
out := make([]netbox.HostEntry, 0, len(entries))
@@ -149,6 +290,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
if f.kind != "" && e.Kind != f.kind {
continue
}
if f.status != "" && !strings.EqualFold(e.Status, f.status) {
continue
}
if f.site != "" && !e.Site.Matches(f.site) || f.role != "" && !e.Role.Matches(f.role) ||
f.platform != "" && !e.Platform.Matches(f.platform) || f.tenant != "" && !e.Tenant.Matches(f.tenant) ||
f.location != "" && !inLocation(e, f.location) {
continue
}
if len(f.tags) > 0 {
tagSet := make(map[string]bool, len(e.Tags))
for _, t := range e.Tags {
@@ -215,6 +364,17 @@ type Model struct {
hostLabel func(string) string
aliasFor func(string) string // shortcut alias per target, "" for none
markOrder []string // targets in the order they were marked
columns []string // nil = defaultColumns
reach map[string]reachState // probe results by hostItem.key()
reachTimeout time.Duration
reachPort func(name, kind string, tags []string) (port int, probe bool)
opener func(name, kind string, id int) error
details func(name, kind string, id int) (string, error)
detailHost *hostItem
detailText string
detailErr error
flash string
}
func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model {
@@ -223,7 +383,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
ti.Focus()
fi := textinput.New()
fi.Placeholder = "tag:prod kind:vm"
fi.Placeholder = "tag:prod kind:vm status:active site:fsn1 location:room-2 role:router platform:junos"
fi.Prompt = "Filter: "
ei := textinput.New()
@@ -304,7 +464,7 @@ func (m *Model) loadRecent() tea.Cmd {
recent = favorites
entries := make([]netbox.HostEntry, len(recent))
for i, e := range recent {
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cached: true, CachedAt: e.CachedAt, Static: e.Static}
entries[i] = entryFromCache(e, false)
}
return searchResultMsg{query: "", entries: entries, recent: true}
}
@@ -328,6 +488,25 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return m, nil
case reachMsg:
if m.reach != nil {
m.reach[msg.key] = msg.state
}
return m, nil
case detailMsg:
if m.detailHost != nil && m.detailHost.key() == msg.key {
m.detailText, m.detailErr = msg.text, msg.err
}
return m, nil
case flashMsg:
m.flash = msg.text
if msg.err != nil {
m.flash = "error: " + msg.err.Error()
}
return m, nil
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
@@ -342,6 +521,23 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Quit
}
if m.flash != "" {
m.flash = ""
}
if m.detailHost != nil {
switch msg.String() {
case "esc", "ctrl+l", "q":
m.detailHost = nil
m.input.Focus()
case "enter":
h := m.detailHost
m.selected = &SelectedHost{Name: h.name, IP: h.ip, Kind: h.kind}
return m, tea.Quit
case "ctrl+g":
return m, m.openCmd(*m.detailHost)
}
return m, nil
}
if m.actionHost != nil {
switch msg.String() {
case "esc":
@@ -554,6 +750,25 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Quit
}
case "ctrl+g":
if item, ok := m.list.SelectedItem().(hostItem); ok {
return m, m.openCmd(item)
}
return m, nil
case "ctrl+l":
if item, ok := m.list.SelectedItem().(hostItem); ok && m.details != nil {
m.detailHost = &item
m.detailText, m.detailErr = "", nil
m.input.Blur()
details, key := m.details, item.key()
return m, func() tea.Msg {
text, err := details(item.name, item.kind, item.id)
return detailMsg{key: key, text: text, err: err}
}
}
return m, nil
case "ctrl+t":
if item, ok := m.list.SelectedItem().(hostItem); ok {
m.forwardMode = true
@@ -617,7 +832,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.recentMode = true
m.lastResults = msg.entries
m.updateListItems(msg.entries)
return m, nil
return m, m.probeCmd()
}
if msg.seq != m.seq || msg.query != m.input.Value() {
return m, nil // discard stale result
@@ -626,7 +841,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.err = msg.err
m.lastResults = msg.entries
m.updateListItems(msg.entries)
return m, nil
return m, m.probeCmd()
}
if m.noteMode {
@@ -675,6 +890,32 @@ func (m *Model) View() tea.View {
}
func (m *Model) viewContent() string {
if m.detailHost != nil {
var out strings.Builder
title := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("Details — " + m.detailHost.Title())
out.WriteString(title + "\n\n")
switch {
case m.detailErr != nil:
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("Error: "+m.detailErr.Error()) + "\n")
case m.detailText == "":
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("Loading…") + "\n")
default:
text := m.detailText
if m.height > 4 {
lines := strings.Split(strings.TrimRight(text, "\n"), "\n")
if len(lines) > m.height-4 {
lines = append(lines[:m.height-5], "…")
}
text = strings.Join(lines, "\n") + "\n"
}
out.WriteString(text)
}
if m.flash != "" {
out.WriteString("\n" + m.flash + "\n")
}
out.WriteString("\n" + lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("enter connect ctrl+g open in NetBox esc back") + "\n")
return out.String()
}
if m.actionHost != nil {
var out strings.Builder
fmt.Fprintf(&out, "Action for %s", m.actionHost.Title())
@@ -753,7 +994,10 @@ func (m *Model) viewContent() string {
sb.WriteString(m.editInput.View() + "\n")
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n")
} else {
hint := "ctrl+r actions ctrl+d favorite ctrl+p pin ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox"
hint := "ctrl+r actions ctrl+d favorite ctrl+p pin ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox ctrl+l details ctrl+g NetBox page"
if m.flash != "" {
hint = m.flash
}
if n := len(m.markOrder); n > 0 {
hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n)
}
@@ -781,8 +1025,7 @@ func (m *Model) doSearch(query string, seq int) tea.Cmd {
var cached []netbox.HostEntry
if m.cache != nil {
for _, entry := range m.cache.Search(query) {
source, name := netbox.SplitTarget(entry.Name)
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags, Cached: true, CachedAt: entry.CachedAt, Static: entry.Static})
cached = append(cached, entryFromCache(entry, true))
}
}
if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) {
@@ -816,6 +1059,18 @@ func (m *Model) netboxSearchOpts() netbox.SearchOptions {
return netbox.SearchOptions{Tag: tag, Kind: f.kind}
}
// entryFromCache converts a cache entry for the list. With split, the
// instance prefix becomes Source, like in live NetBox results.
func entryFromCache(e cache.Entry, split bool) netbox.HostEntry {
h := netbox.HostEntry{Name: e.Name, ID: e.ID, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Cached: true, CachedAt: e.CachedAt, Static: e.Static,
Status: e.Status, Site: cache.RefOf(e.Site), Role: cache.RefOf(e.Role), Platform: cache.RefOf(e.Platform), Tenant: cache.RefOf(e.Tenant),
Location: e.Location, Rack: e.Rack, Position: e.Position}
if split {
h.Source, h.Name = netbox.SplitTarget(e.Name)
}
return h
}
// updateListItems applies the active filter and sets the list items.
func (m *Model) updateListItems(entries []netbox.HostEntry) {
f := parseFilter(m.filterInput.Value())
@@ -876,7 +1131,8 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
}
}
}
items[i] = hostItem{provenance: provenance, favorite: m.favorites[e.Target()], pinned: m.pinned[e.Target()], label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
items[i] = hostItem{provenance: provenance, favorite: m.favorites[e.Target()], pinned: m.pinned[e.Target()], label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags, status: e.Status,
site: e.Site.Key(), role: e.Role.Key(), platform: e.Platform.Key(), tenant: e.Tenant.Key(), cluster: e.Cluster, location: e.LocationPath()}
}
m.list.SetItems(items)
m.resizeList()
@@ -1040,3 +1296,94 @@ func (m *Model) SetPreferences(favorites, pinned map[string]bool, save func(map[
func (m *Model) SetCommands(commands func(string, string, []string) []string) {
m.commandsFor = commands
}
// SetReachability enables the reachability column: listed hosts are probed
// with a TCP connect to the port returned by portFor, unless it returns
// probe=false (for hosts behind a jump host). Configure it before the program starts.
func (m *Model) SetReachability(timeout time.Duration, portFor func(name, kind string, tags []string) (port int, probe bool)) {
if timeout <= 0 {
timeout = 300 * time.Millisecond
}
m.reach = map[string]reachState{}
m.reachTimeout = timeout
m.reachPort = portFor
m.list.SetDelegate(m.delegate())
}
// SetColumns selects what is shown next to each hostname, in order (see
// config.TUIColumns). "reachability" is ignored here: SetReachability
// enables the check. Configure it before the program starts.
func (m *Model) SetColumns(columns []string) {
m.columns = append([]string{}, columns...)
m.list.SetDelegate(m.delegate())
}
func (m *Model) delegate() compactDelegate {
return compactDelegate{marked: m.marked, reach: m.reach, columns: m.columns}
}
// probeCmd starts probes for listed hosts that have no result yet.
func (m *Model) probeCmd() tea.Cmd {
if m.reach == nil {
return nil
}
var cmds []tea.Cmd
for _, it := range m.list.Items() {
h, ok := it.(hostItem)
if !ok || m.reach[h.key()] != reachUnknown {
continue
}
key := h.key()
port, probe := 22, true
if m.reachPort != nil {
port, probe = m.reachPort(h.name, h.kind, h.tags)
}
if !probe || h.ip == "" {
m.reach[key] = reachSkipped
continue
}
m.reach[key] = reachPending
address, timeout := h.ip, m.reachTimeout
cmds = append(cmds, func() tea.Msg {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(address, strconv.Itoa(port)), timeout)
if err != nil {
return reachMsg{key: key, state: reachDown}
}
_ = conn.Close()
return reachMsg{key: key, state: reachUp}
})
}
return tea.Batch(cmds...)
}
// SetOpener opens a host's NetBox page (ctrl+g). Configure it before the program starts.
func (m *Model) SetOpener(open func(name, kind string, id int) error) { m.opener = open }
// SetDetails provides the text of the detail view (ctrl+l). Configure it before the program starts.
func (m *Model) SetDetails(details func(name, kind string, id int) (string, error)) {
m.details = details
}
func (m *Model) openCmd(h hostItem) tea.Cmd {
if m.opener == nil {
return nil
}
open := m.opener
return func() tea.Msg {
if err := open(h.name, h.kind, h.id); err != nil {
return flashMsg{err: err}
}
return flashMsg{text: "opened " + h.name + " in NetBox"}
}
}
// inLocation reports whether a host is in the location want at any level of
// its location chain, or in the rack named want.
func inLocation(e netbox.HostEntry, want string) bool {
for _, location := range e.Location {
if location.Matches(want) {
return true
}
}
return want != "" && strings.EqualFold(e.Rack, want)
}