feat: NetBox insights, host tools and configurable TUI
Test / test (pull_request) Successful in 4m15s
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:
1 parent
e5bde9c61f
commit
1660bb3098
39 files changed
+4868
-96
No files matched your search
@@ -0,0 +1,233 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
)
|
||||
|
||||
func TestFilterByNetBoxAttributes(t *testing.T) {
|
||||
entries := []netbox.HostEntry{
|
||||
{Name: "sw1", Kind: "device", Status: "active", Site: config.Ref{Name: "FSN 1", Slug: "fsn1"}, Platform: config.Ref{Slug: "junos"}, Role: config.Ref{Slug: "core"}},
|
||||
{Name: "sw2", Kind: "device", Status: "offline", Site: config.Ref{Slug: "nbg1"}, Platform: config.Ref{Slug: "junos"}},
|
||||
{Name: "web", Kind: "vm", Status: "active", Site: config.Ref{Slug: "fsn1"}, Tenant: config.Ref{Name: "ACME"}},
|
||||
}
|
||||
for filter, want := range map[string]string{
|
||||
"status:active": "sw1 web",
|
||||
"site:fsn1": "sw1 web",
|
||||
"site:FSN-1": "sw1",
|
||||
"platform:junos status:active": "sw1",
|
||||
"role:core": "sw1",
|
||||
"tenant:acme kind:vm": "web",
|
||||
"bogus": "sw1 sw2 web",
|
||||
} {
|
||||
var names []string
|
||||
for _, e := range applyFilter(entries, parseFilter(filter)) {
|
||||
names = append(names, e.Name)
|
||||
}
|
||||
if got := strings.Join(names, " "); got != want {
|
||||
t.Errorf("%q: got %q, want %q", filter, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusBadgeShownForInactiveHosts(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "a", Status: "active"}, {Name: "b", Status: "offline"}})
|
||||
var out strings.Builder
|
||||
for i, it := range m.list.Items() {
|
||||
compactDelegate{marked: map[string]bool{}}.Render(&out, m.list, i, it)
|
||||
out.WriteString("\n")
|
||||
}
|
||||
if strings.Contains(out.String(), "[active]") || !strings.Contains(out.String(), "[offline]") {
|
||||
t.Fatalf("unexpected badges:\n%s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReachabilityProbesListedHosts(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
m := New(nil, nil, "")
|
||||
m.SetReachability(time.Second, func(name, kind string, tags []string) (int, bool) {
|
||||
return port, name != "behind-jump"
|
||||
})
|
||||
_, cmd := m.Update(searchResultMsg{query: "", recent: true, entries: []netbox.HostEntry{
|
||||
{Name: "up", PrimaryIP4: "127.0.0.1"},
|
||||
{Name: "behind-jump", PrimaryIP4: "127.0.0.1"},
|
||||
}})
|
||||
if cmd == nil {
|
||||
t.Fatal("no probe started")
|
||||
}
|
||||
for _, msg := range runBatch(cmd) {
|
||||
m.Update(msg)
|
||||
}
|
||||
up := hostItem{name: "up"}.key()
|
||||
skipped := hostItem{name: "behind-jump"}.key()
|
||||
if m.reach[up] != reachUp || m.reach[skipped] != reachSkipped {
|
||||
t.Fatalf("states: %v", m.reach)
|
||||
}
|
||||
var out strings.Builder
|
||||
m.list.Select(0)
|
||||
compactDelegate{marked: m.marked, reach: m.reach}.Render(&out, m.list, 0, m.list.Items()[0])
|
||||
if !strings.Contains(out.String(), "✓") {
|
||||
t.Fatalf("reachable mark missing: %q", out.String())
|
||||
}
|
||||
// A second result list does not probe hosts that already have a state.
|
||||
_, cmd = m.Update(searchResultMsg{query: "", recent: true, entries: []netbox.HostEntry{{Name: "up", PrimaryIP4: "127.0.0.1"}}})
|
||||
if len(runBatch(cmd)) != 0 {
|
||||
t.Fatal("host probed twice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnreachableHostMarked(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
ln.Close()
|
||||
m := New(nil, nil, "")
|
||||
m.SetReachability(200*time.Millisecond, func(string, string, []string) (int, bool) { return port, true })
|
||||
_, cmd := m.Update(searchResultMsg{recent: true, entries: []netbox.HostEntry{{Name: "down", PrimaryIP4: "127.0.0.1"}}})
|
||||
for _, msg := range runBatch(cmd) {
|
||||
m.Update(msg)
|
||||
}
|
||||
if m.reach[hostItem{name: "down"}.key()] != reachDown {
|
||||
t.Fatalf("states: %v", m.reach)
|
||||
}
|
||||
}
|
||||
|
||||
// runBatch executes a command and the commands of a batch it returns.
|
||||
func runBatch(cmd tea.Cmd) []tea.Msg {
|
||||
if cmd == nil {
|
||||
return nil
|
||||
}
|
||||
msg := cmd()
|
||||
if batch, ok := msg.(tea.BatchMsg); ok {
|
||||
var out []tea.Msg
|
||||
for _, c := range batch {
|
||||
out = append(out, runBatch(c)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
if msg == nil {
|
||||
return nil
|
||||
}
|
||||
return []tea.Msg{msg}
|
||||
}
|
||||
|
||||
func TestDetailViewLoadsAndConnects(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
var asked string
|
||||
m.SetDetails(func(name, kind string, id int) (string, error) {
|
||||
asked = name + "/" + strconv.Itoa(id)
|
||||
return "sw1 (device)\n Site FSN1\n", nil
|
||||
})
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "sw1", ID: 7, Kind: "device", PrimaryIP4: "10.0.0.7"}})
|
||||
_, cmd := m.Update(tea.KeyPressMsg{Code: 'l', Mod: tea.ModCtrl})
|
||||
if m.detailHost == nil || !strings.Contains(m.viewContent(), "Loading") {
|
||||
t.Fatal("detail view not opened")
|
||||
}
|
||||
m.Update(cmd())
|
||||
if asked != "sw1/7" || !strings.Contains(m.viewContent(), "Site FSN1") {
|
||||
t.Fatalf("details not shown (asked %q):\n%s", asked, m.viewContent())
|
||||
}
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected == nil || m.selected.Name != "sw1" {
|
||||
t.Fatalf("enter in detail view should connect: %+v", m.selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetailViewShowsErrorAndEscCloses(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.SetDetails(func(string, string, int) (string, error) { return "", errors.New("boom") })
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "sw1"}})
|
||||
_, cmd := m.Update(tea.KeyPressMsg{Code: 'l', Mod: tea.ModCtrl})
|
||||
m.Update(cmd())
|
||||
if !strings.Contains(m.viewContent(), "Error: boom") {
|
||||
t.Fatalf("error not shown:\n%s", m.viewContent())
|
||||
}
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEscape})
|
||||
if m.detailHost != nil || m.selected != nil {
|
||||
t.Fatal("esc should close the detail view without selecting")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCtrlGOpensNetBoxPage(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
var opened string
|
||||
m.SetOpener(func(name, kind string, id int) error { opened = name; return nil })
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "web", Kind: "vm"}})
|
||||
_, cmd := m.Update(tea.KeyPressMsg{Code: 'g', Mod: tea.ModCtrl})
|
||||
if cmd == nil || m.selected != nil {
|
||||
t.Fatal("ctrl+g must not quit the TUI")
|
||||
}
|
||||
m.Update(cmd())
|
||||
if opened != "web" || !strings.Contains(m.viewContent(), "opened web in NetBox") {
|
||||
t.Fatalf("opened %q:\n%s", opened, m.viewContent())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredColumns(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.SetColumns([]string{"platform", "site", "tags", "kind"})
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "sw1", Kind: "device", PrimaryIP4: "10.0.0.7", Status: "offline", Tags: []string{"core", "dc"},
|
||||
Site: config.Ref{Name: "FSN 1", Slug: "fsn1"}, Platform: config.Ref{Slug: "junos"}}})
|
||||
var out strings.Builder
|
||||
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
|
||||
got := out.String()
|
||||
for _, want := range []string{"platform:junos", "site:fsn1", "#core #dc", "[device]"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q in %q", want, got)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got, "10.0.0.7") || strings.Contains(got, "[offline]") || strings.Contains(got, "[live]") {
|
||||
t.Fatalf("columns not configured must be hidden: %q", got)
|
||||
}
|
||||
if strings.Index(got, "platform:") > strings.Index(got, "site:") {
|
||||
t.Fatalf("configured order not kept: %q", got)
|
||||
}
|
||||
|
||||
m.SetColumns(nil)
|
||||
out.Reset()
|
||||
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
|
||||
if got := out.String(); !strings.HasSuffix(strings.TrimSpace(got), "sw1") {
|
||||
t.Fatalf("empty column list should show only the name: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocationColumnAndFilter(t *testing.T) {
|
||||
entries := []netbox.HostEntry{
|
||||
{Name: "srv1", Site: config.Ref{Name: "FSN1"}, Location: []config.Ref{{Name: "Building A", Slug: "building-a"}, {Name: "Room 2.04", Slug: "room-2-04"}}, Rack: "R12", Position: "20"},
|
||||
{Name: "srv2", Site: config.Ref{Name: "NBG1"}, Location: []config.Ref{{Name: "Hall 1", Slug: "hall-1"}}, Rack: "B03"},
|
||||
}
|
||||
for filter, want := range map[string]string{"location:building-a": "srv1", "location:room-2-04": "srv1", "rack:b03": "srv2", "location:hall-1": "srv2"} {
|
||||
var names []string
|
||||
for _, e := range applyFilter(entries, parseFilter(filter)) {
|
||||
names = append(names, e.Name)
|
||||
}
|
||||
if got := strings.Join(names, " "); got != want {
|
||||
t.Errorf("%q: got %q, want %q", filter, got, want)
|
||||
}
|
||||
}
|
||||
m := New(nil, nil, "")
|
||||
m.SetColumns([]string{"location"})
|
||||
m.updateListItems(entries[:1])
|
||||
var out strings.Builder
|
||||
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
|
||||
if !strings.Contains(out.String(), "FSN1 › Building A › Room 2.04 › R12 › U20") {
|
||||
t.Fatalf("location column: %q", out.String())
|
||||
}
|
||||
}
|
||||
+370
-23
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user