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
Vendored
+36
-8
@@ -17,14 +17,26 @@ import (
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
Resolver string `json:"resolver,omitempty"`
|
||||
Name string `json:"name"`
|
||||
IP string `json:"ip"`
|
||||
Kind string `json:"kind"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Cluster string `json:"cluster,omitempty"`
|
||||
CachedAt time.Time `json:"cached_at"`
|
||||
LastUsed time.Time `json:"last_used,omitempty"`
|
||||
Resolver string `json:"resolver,omitempty"`
|
||||
Name string `json:"name"`
|
||||
IP string `json:"ip"`
|
||||
Kind string `json:"kind"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Cluster string `json:"cluster,omitempty"`
|
||||
// ID, Status, Site, Role, Platform and Tenant come from NetBox; entries
|
||||
// written by older versions lack them until the next refresh.
|
||||
ID int `json:"id,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Site *config.Ref `json:"site,omitempty"`
|
||||
Role *config.Ref `json:"role,omitempty"`
|
||||
Platform *config.Ref `json:"platform,omitempty"`
|
||||
Tenant *config.Ref `json:"tenant,omitempty"`
|
||||
// Location is the chain of nested locations below the site, outermost first.
|
||||
Location []config.Ref `json:"location,omitempty"`
|
||||
Rack string `json:"rack,omitempty"`
|
||||
Position string `json:"position,omitempty"`
|
||||
CachedAt time.Time `json:"cached_at"`
|
||||
LastUsed time.Time `json:"last_used,omitempty"`
|
||||
// Static marks a host from the config's hosts: list. It never expires;
|
||||
// it is stored only to remember LastUsed for the recently-used list.
|
||||
Static bool `json:"static,omitempty"`
|
||||
@@ -427,3 +439,19 @@ func (c *Cache) All() []Entry {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RefPtr returns nil for an empty reference, keeping the cache file small.
|
||||
func RefPtr(r config.Ref) *config.Ref {
|
||||
if r == (config.Ref{}) {
|
||||
return nil
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
// RefOf returns the referenced value, or an empty Ref.
|
||||
func RefOf(r *config.Ref) config.Ref {
|
||||
if r == nil {
|
||||
return config.Ref{}
|
||||
}
|
||||
return *r
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
@@ -42,6 +43,11 @@ type NetBoxConfig struct {
|
||||
}
|
||||
|
||||
type ResolverConfig struct {
|
||||
// Fallback tries the addresses of the other strategies when the chosen
|
||||
// address does not accept TCP connections on the SSH port.
|
||||
Fallback bool `mapstructure:"fallback"`
|
||||
// FallbackTimeout is the per-address connect timeout in milliseconds; 0 = 1000.
|
||||
FallbackTimeout int `mapstructure:"fallback_timeout"`
|
||||
Strategies []string `mapstructure:"strategies"`
|
||||
ManagementSubnets []string `mapstructure:"management_subnets"`
|
||||
InterfaceName string `mapstructure:"interface_name"`
|
||||
@@ -57,8 +63,11 @@ type CacheConfig struct {
|
||||
type SSHConfig struct {
|
||||
DefaultUser string `mapstructure:"default_user"`
|
||||
DefaultPort int `mapstructure:"default_port"`
|
||||
SSHOptions `mapstructure:",squash"`
|
||||
Rules []SSHRule `mapstructure:"rules"`
|
||||
// WarnStatus lists NetBox status values that ask before connecting;
|
||||
// nil means DefaultWarnStatus, an empty list disables the question.
|
||||
WarnStatus []string `mapstructure:"warn_status"`
|
||||
SSHOptions `mapstructure:",squash"`
|
||||
Rules []SSHRule `mapstructure:"rules"`
|
||||
}
|
||||
|
||||
type CompletionConfig struct {
|
||||
@@ -100,6 +109,51 @@ func (s ShortcutsConfig) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DefaultWarnStatus are the NetBox status values that ask before connecting.
|
||||
var DefaultWarnStatus = []string{"offline", "planned", "staged", "failed", "inventory", "decommissioning"}
|
||||
|
||||
// KeyringToken as a token value reads the token from the system keyring.
|
||||
const KeyringToken = "keyring"
|
||||
|
||||
// IsKeyringToken reports whether token refers to the system keyring.
|
||||
func IsKeyringToken(token string) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(token), KeyringToken)
|
||||
}
|
||||
|
||||
// KeyringAccount is the keyring entry of a NetBox instance; the unnamed
|
||||
// single-instance configuration uses "default".
|
||||
func (n NetBoxConfig) KeyringAccount() string {
|
||||
if n.Name == "" {
|
||||
return "default"
|
||||
}
|
||||
return strings.ToLower(n.Name)
|
||||
}
|
||||
|
||||
// WarnsStatus reports whether status is configured to ask before connecting.
|
||||
func (s SSHConfig) WarnsStatus(status string) bool {
|
||||
if status == "" {
|
||||
return false
|
||||
}
|
||||
list := s.WarnStatus
|
||||
if list == nil {
|
||||
list = DefaultWarnStatus
|
||||
}
|
||||
for _, warn := range list {
|
||||
if strings.EqualFold(strings.TrimSpace(warn), status) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// FallbackTimeoutDuration returns resolver.fallback_timeout, 1s by default.
|
||||
func (r ResolverConfig) FallbackTimeoutDuration() time.Duration {
|
||||
if r.FallbackTimeout <= 0 {
|
||||
return time.Second
|
||||
}
|
||||
return time.Duration(r.FallbackTimeout) * time.Millisecond
|
||||
}
|
||||
|
||||
// Path returns the canonical config file path.
|
||||
func Path() string {
|
||||
configDir, err := os.UserConfigDir()
|
||||
@@ -131,7 +185,7 @@ func Load() (*Config, error) {
|
||||
v.SetEnvPrefix("NETSSH")
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
v.AutomaticEnv()
|
||||
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
|
||||
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window", "ssh.warn_status", "tui.columns", "tui.reachability_timeout", "resolver.fallback", "resolver.fallback_timeout"} {
|
||||
if err := v.BindEnv(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -147,6 +201,14 @@ func Load() (*Config, error) {
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return nil, fmt.Errorf("parsing config: %w", err)
|
||||
}
|
||||
// "columns: []" shows only the hostname; only a missing key means the default.
|
||||
if cfg.TUI.Columns == nil && v.IsSet("tui.columns") {
|
||||
cfg.TUI.Columns = []string{}
|
||||
}
|
||||
// "warn_status: []" disables the question; only a missing key means the default.
|
||||
if cfg.SSH.WarnStatus == nil && v.IsSet("ssh.warn_status") {
|
||||
cfg.SSH.WarnStatus = []string{}
|
||||
}
|
||||
// Legacy environment variables must not invent an additional unnamed source
|
||||
// when a file explicitly configures named instances (including wizard migration).
|
||||
if len(cfg.NetBoxes) > 0 && !v.InConfig("netbox.url") {
|
||||
@@ -157,7 +219,7 @@ func Load() (*Config, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" {
|
||||
if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" && !IsKeyringToken(cfg.NetBox.Token) {
|
||||
if strings.HasPrefix(cfg.NetBox.Token, "nbt_") {
|
||||
cfg.NetBox.TokenVersion = 2
|
||||
} else {
|
||||
@@ -189,7 +251,7 @@ func Load() (*Config, error) {
|
||||
for i := range cfg.NetBoxes {
|
||||
source := &cfg.NetBoxes[i]
|
||||
source.Name = strings.ToLower(source.Name)
|
||||
if source.TokenVersion == 0 && source.Token != "" {
|
||||
if source.TokenVersion == 0 && source.Token != "" && !IsKeyringToken(source.Token) {
|
||||
source.TokenVersion = 1
|
||||
if strings.HasPrefix(source.Token, "nbt_") {
|
||||
source.TokenVersion = 2
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSSHRuleMatchesNetBoxAttributes(t *testing.T) {
|
||||
host := SSHHost{Name: "sw1", Kind: "device", Status: "active",
|
||||
Site: Ref{Name: "Falkenstein 1", Slug: "fsn1"}, Role: Ref{Name: "Core Switch", Slug: "core-switch"},
|
||||
Platform: Ref{Name: "Juniper Junos", Slug: "junos"}, Tenant: Ref{Name: "ACME"}}
|
||||
for _, tc := range []struct {
|
||||
match SSHMatch
|
||||
want bool
|
||||
}{
|
||||
{SSHMatch{Platform: "junos"}, true},
|
||||
{SSHMatch{Platform: "juniper junos"}, true},
|
||||
{SSHMatch{Platform: "eos"}, false},
|
||||
{SSHMatch{Site: "fsn1", Role: "core-switch"}, true},
|
||||
{SSHMatch{Role: "Core Switch"}, true},
|
||||
{SSHMatch{Site: "falkenstein-1"}, true},
|
||||
{SSHMatch{Tenant: "acme"}, true},
|
||||
{SSHMatch{Status: "ACTIVE"}, true},
|
||||
{SSHMatch{Status: "offline"}, false},
|
||||
{SSHMatch{Platform: "junos", Kind: "vm"}, false},
|
||||
} {
|
||||
if got := tc.match.matches(host); got != tc.want {
|
||||
t.Errorf("%+v: got %v, want %v", tc.match, got, tc.want)
|
||||
}
|
||||
}
|
||||
if err := (SSHMatch{Platform: "junos"}).Validate("rule"); err != nil {
|
||||
t.Fatalf("platform-only match rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHOptionsForPlatformRule(t *testing.T) {
|
||||
cfg := &Config{SSH: SSHConfig{Rules: []SSHRule{{Match: SSHMatch{Platform: "junos"}, SSHOptions: SSHOptions{Options: map[string]string{"KexAlgorithms": "+diffie-hellman-group14-sha1"}}}}}}
|
||||
opts := cfg.SSHOptionsFor(SSHHost{Name: "sw1", Kind: "device", Platform: Ref{Slug: "junos"}})
|
||||
if opts.Options["kexalgorithms"] != "+diffie-hellman-group14-sha1" {
|
||||
t.Fatalf("platform rule not applied: %+v", opts.Options)
|
||||
}
|
||||
if opts := cfg.SSHOptionsFor(SSHHost{Name: "web", Kind: "vm"}); len(opts.Options) != 0 {
|
||||
t.Fatalf("rule applied to other platform: %+v", opts.Options)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWarnStatusDefaultsAndOverrides(t *testing.T) {
|
||||
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
|
||||
if cfg.SSH.WarnStatus != nil || !cfg.SSH.WarnsStatus("offline") || cfg.SSH.WarnsStatus("active") || cfg.SSH.WarnsStatus("") {
|
||||
t.Fatalf("default warn_status wrong: %#v", cfg.SSH.WarnStatus)
|
||||
}
|
||||
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: []\n"))
|
||||
if cfg.SSH.WarnStatus == nil || cfg.SSH.WarnsStatus("offline") {
|
||||
t.Fatalf("empty warn_status should disable the question: %#v", cfg.SSH.WarnStatus)
|
||||
}
|
||||
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: [planned]\n"))
|
||||
if !cfg.SSH.WarnsStatus("Planned") || cfg.SSH.WarnsStatus("offline") {
|
||||
t.Fatalf("custom warn_status wrong: %#v", cfg.SSH.WarnStatus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReachabilityAndFallbackDefaults(t *testing.T) {
|
||||
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
|
||||
if cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 300 {
|
||||
t.Fatalf("reachability must be opt-in: %+v", cfg.TUI)
|
||||
}
|
||||
if strings.Join(cfg.TUI.EffectiveColumns(), ",") != "alias,ip,source,status" {
|
||||
t.Fatalf("default columns: %v", cfg.TUI.EffectiveColumns())
|
||||
}
|
||||
if cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 1000 {
|
||||
t.Fatalf("fallback defaults wrong: %+v", cfg.Resolver)
|
||||
}
|
||||
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: [Reachability, ip, platform]\n reachability_timeout: 800\nresolver:\n fallback: true\n fallback_timeout: 250\n"))
|
||||
if !cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 800 || strings.Join(cfg.TUI.Columns, ",") != "reachability,ip,platform" {
|
||||
t.Fatalf("reachability settings ignored: %+v", cfg.TUI)
|
||||
}
|
||||
if !cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 250 {
|
||||
t.Fatalf("fallback settings ignored: %+v", cfg.Resolver)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyringTokenKeepsVersionUndetected(t *testing.T) {
|
||||
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n token: keyring\nnetboxes: []\n"))
|
||||
if !IsKeyringToken(cfg.NetBox.Token) || cfg.NetBox.TokenVersion != 0 {
|
||||
t.Fatalf("keyring token treated as literal: %+v", cfg.NetBox)
|
||||
}
|
||||
if cfg.NetBox.KeyringAccount() != "default" || (NetBoxConfig{Name: "Prod"}).KeyringAccount() != "prod" {
|
||||
t.Fatal("unexpected keyring account names")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTUIColumnsValidation(t *testing.T) {
|
||||
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: []\n"))
|
||||
if cfg.TUI.Columns == nil || len(cfg.TUI.EffectiveColumns()) != 0 {
|
||||
t.Fatalf("empty columns should show only the hostname: %#v", cfg.TUI.Columns)
|
||||
}
|
||||
for _, bad := range []string{"[ip, colour]", "[ip, ip]"} {
|
||||
dir := writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: "+bad+"\n")
|
||||
orig := os.Getenv("XDG_CONFIG_HOME")
|
||||
os.Setenv("XDG_CONFIG_HOME", dir)
|
||||
_, err := Load()
|
||||
os.Setenv("XDG_CONFIG_HOME", orig)
|
||||
if err == nil || !strings.Contains(err.Error(), "tui.columns") {
|
||||
t.Errorf("%s accepted: %v", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,51 @@ package config
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TUIConfig struct {
|
||||
HistoryLimit int `mapstructure:"history_limit"`
|
||||
// Columns selects what the TUI shows next to each hostname, in order;
|
||||
// nil means DefaultTUIColumns. "reachability" enables the TCP check.
|
||||
Columns []string `mapstructure:"columns"`
|
||||
// ReachabilityTimeout is the probe timeout in milliseconds; 0 = 300.
|
||||
ReachabilityTimeout int `mapstructure:"reachability_timeout"`
|
||||
}
|
||||
|
||||
// TUIColumns are the values tui.columns accepts.
|
||||
var TUIColumns = []string{"alias", "ip", "kind", "source", "status", "site", "location", "role", "platform", "tenant", "cluster", "tags", "reachability"}
|
||||
|
||||
// DefaultTUIColumns is the layout without tui.columns. The TCP reachability
|
||||
// check is opt-in, since it opens connections to every listed host.
|
||||
var DefaultTUIColumns = []string{"alias", "ip", "source", "status"}
|
||||
|
||||
// EffectiveColumns returns tui.columns, or the default layout.
|
||||
func (t TUIConfig) EffectiveColumns() []string {
|
||||
if t.Columns == nil {
|
||||
return DefaultTUIColumns
|
||||
}
|
||||
return t.Columns
|
||||
}
|
||||
|
||||
// ReachabilityEnabled reports whether the TUI probes listed hosts.
|
||||
func (t TUIConfig) ReachabilityEnabled() bool {
|
||||
for _, column := range t.EffectiveColumns() {
|
||||
if column == "reachability" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ReachabilityTimeoutDuration returns tui.reachability_timeout, 300ms by default.
|
||||
func (t TUIConfig) ReachabilityTimeoutDuration() time.Duration {
|
||||
if t.ReachabilityTimeout <= 0 {
|
||||
return 300 * time.Millisecond
|
||||
}
|
||||
return time.Duration(t.ReachabilityTimeout) * time.Millisecond
|
||||
}
|
||||
|
||||
type ActivityConfig struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
RetentionDays int `mapstructure:"retention_days"`
|
||||
@@ -21,6 +61,33 @@ func (c *Config) ValidateOperations() error {
|
||||
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
|
||||
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i, column := range c.TUI.Columns {
|
||||
column = strings.ToLower(strings.TrimSpace(column))
|
||||
c.TUI.Columns[i] = column
|
||||
known := false
|
||||
for _, valid := range TUIColumns {
|
||||
known = known || column == valid
|
||||
}
|
||||
if !known {
|
||||
return fmt.Errorf("tui.columns: unknown column %q; use %s", column, strings.Join(TUIColumns, ", "))
|
||||
}
|
||||
if seen[column] {
|
||||
return fmt.Errorf("tui.columns: %q is listed twice", column)
|
||||
}
|
||||
seen[column] = true
|
||||
}
|
||||
if c.TUI.ReachabilityTimeout < 0 || c.TUI.ReachabilityTimeout > 10000 {
|
||||
return fmt.Errorf("tui.reachability_timeout must be between 0 and 10000 milliseconds")
|
||||
}
|
||||
if c.Resolver.FallbackTimeout < 0 || c.Resolver.FallbackTimeout > 30000 {
|
||||
return fmt.Errorf("resolver.fallback_timeout must be between 0 and 30000 milliseconds")
|
||||
}
|
||||
for _, status := range c.SSH.WarnStatus {
|
||||
if strings.TrimSpace(status) == "" || strings.ContainsAny(status, " \t\n") {
|
||||
return fmt.Errorf("ssh.warn_status: invalid status %q", status)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
|
||||
|
||||
+68
-1
@@ -94,6 +94,57 @@ type SSHMatch struct {
|
||||
Instance string `mapstructure:"instance"`
|
||||
Kind string `mapstructure:"kind"`
|
||||
Name string `mapstructure:"name"` // shell-style glob, e.g. "*.dmz.example.com"
|
||||
// Site, Role, Platform and Tenant match the NetBox name or slug.
|
||||
Site string `mapstructure:"site"`
|
||||
Role string `mapstructure:"role"`
|
||||
Platform string `mapstructure:"platform"`
|
||||
Tenant string `mapstructure:"tenant"`
|
||||
// Status matches the NetBox status value, e.g. active or offline.
|
||||
Status string `mapstructure:"status"`
|
||||
}
|
||||
|
||||
// Ref is a NetBox object referenced by a host, such as its site or platform.
|
||||
type Ref struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Slug string `json:"slug,omitempty"`
|
||||
}
|
||||
|
||||
// Matches compares want with the name or slug, ignoring case.
|
||||
func (r Ref) Matches(want string) bool {
|
||||
return want != "" && (strings.EqualFold(r.Name, want) || strings.EqualFold(r.Slug, want) || strings.EqualFold(tagSlug(r.Name), want))
|
||||
}
|
||||
|
||||
// Key returns the slug, or the name when NetBox sent no slug.
|
||||
func (r Ref) Key() string {
|
||||
if r.Slug != "" {
|
||||
return r.Slug
|
||||
}
|
||||
return r.Name
|
||||
}
|
||||
|
||||
// LocationPath renders a host's place as "site › location › … › rack › U20",
|
||||
// leaving out levels that are not set.
|
||||
func LocationPath(site Ref, locations []Ref, rack, position string) string {
|
||||
var parts []string
|
||||
if site.Name != "" {
|
||||
parts = append(parts, site.Name)
|
||||
} else if site.Slug != "" {
|
||||
parts = append(parts, site.Slug)
|
||||
}
|
||||
for _, location := range locations {
|
||||
if location.Name != "" {
|
||||
parts = append(parts, location.Name)
|
||||
} else if location.Slug != "" {
|
||||
parts = append(parts, location.Slug)
|
||||
}
|
||||
}
|
||||
if rack != "" {
|
||||
parts = append(parts, rack)
|
||||
}
|
||||
if position != "" {
|
||||
parts = append(parts, "U"+position)
|
||||
}
|
||||
return strings.Join(parts, " › ")
|
||||
}
|
||||
|
||||
// SSHHost identifies the resolved host that SSH options are computed for.
|
||||
@@ -102,6 +153,11 @@ type SSHHost struct {
|
||||
Name string // NetBox name without the instance prefix
|
||||
Kind string
|
||||
Tags []string
|
||||
Status string
|
||||
Site Ref
|
||||
Role Ref
|
||||
Platform Ref
|
||||
Tenant Ref
|
||||
}
|
||||
|
||||
var sshOptionKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`)
|
||||
@@ -138,7 +194,7 @@ func (r SSHRule) Validate(scope string) error {
|
||||
// Validate requires at least one selector and a well-formed name pattern.
|
||||
func (m SSHMatch) Validate(scope string) error {
|
||||
if m == (SSHMatch{}) {
|
||||
return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name", scope)
|
||||
return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name, site, role, platform, tenant, status", scope)
|
||||
}
|
||||
if _, err := path.Match(m.Name, ""); err != nil {
|
||||
return fmt.Errorf("%s: invalid name pattern %q", scope, m.Name)
|
||||
@@ -264,6 +320,17 @@ func (m SSHMatch) matches(host SSHHost) bool {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, ref := range []struct {
|
||||
want string
|
||||
have Ref
|
||||
}{{m.Site, host.Site}, {m.Role, host.Role}, {m.Platform, host.Platform}, {m.Tenant, host.Tenant}} {
|
||||
if ref.want != "" && !ref.have.Matches(ref.want) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if m.Status != "" && !strings.EqualFold(m.Status, host.Status) {
|
||||
return false
|
||||
}
|
||||
if m.Tag != "" {
|
||||
found := false
|
||||
for _, tag := range host.Tags {
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -20,6 +22,9 @@ type Client struct {
|
||||
token string
|
||||
tokenVersion int
|
||||
httpClient *http.Client
|
||||
|
||||
locMu sync.Mutex
|
||||
locations map[int]locationNode // location ID → name and parent, per client
|
||||
}
|
||||
|
||||
// NewClient creates a NetBox API client. Pass tokenVersion=0 to auto-detect
|
||||
@@ -227,6 +232,7 @@ func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEn
|
||||
for _, d := range resp.Results {
|
||||
entries = append(entries, deviceToEntry(d))
|
||||
}
|
||||
c.fillLocations(ctx, entries)
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
@@ -278,6 +284,7 @@ func (c *Client) fetchAllDevices(ctx context.Context, query, filters string) ([]
|
||||
break
|
||||
}
|
||||
}
|
||||
c.fillLocations(ctx, all)
|
||||
return all, nil
|
||||
}
|
||||
|
||||
@@ -370,6 +377,20 @@ func deviceToEntry(d netboxDevice) HostEntry {
|
||||
if d.Cluster != nil {
|
||||
e.Cluster = d.Cluster.Name
|
||||
}
|
||||
e.Status = d.Status.value()
|
||||
e.Site, e.Platform, e.Tenant = d.Site.ref(), d.Platform.ref(), d.Tenant.ref()
|
||||
e.Role = d.Role.ref()
|
||||
if d.Role == nil {
|
||||
e.Role = d.DeviceRole.ref()
|
||||
}
|
||||
if d.Location != nil {
|
||||
e.locationID = d.Location.ID
|
||||
e.Location = []config.Ref{{Name: d.Location.Name, Slug: d.Location.Slug}}
|
||||
}
|
||||
if d.Rack != nil {
|
||||
e.Rack = d.Rack.Name
|
||||
}
|
||||
e.Position = rackUnit(d.Position)
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -387,6 +408,20 @@ func vmToEntry(v netboxVM) HostEntry {
|
||||
if v.Cluster != nil {
|
||||
e.Cluster = v.Cluster.Name
|
||||
}
|
||||
e.Status = v.Status.value()
|
||||
e.Site, e.Platform, e.Tenant = v.Site.ref(), v.Platform.ref(), v.Tenant.ref()
|
||||
e.Role = v.Role.ref()
|
||||
if v.Role == nil {
|
||||
e.Role = v.DeviceRole.ref()
|
||||
}
|
||||
if v.Location != nil {
|
||||
e.locationID = v.Location.ID
|
||||
e.Location = []config.Ref{{Name: v.Location.Name, Slug: v.Location.Slug}}
|
||||
}
|
||||
if v.Rack != nil {
|
||||
e.Rack = v.Rack.Name
|
||||
}
|
||||
e.Position = rackUnit(v.Position)
|
||||
return e
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
package netbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// HostDetails is everything netssh info shows about a device or VM.
|
||||
type HostDetails struct {
|
||||
HostEntry
|
||||
URL string `json:"url"`
|
||||
StatusLabel string `json:"status_label,omitempty"`
|
||||
HeightU string `json:"height_u,omitempty"` // rack units the device occupies
|
||||
Face string `json:"face,omitempty"` // front | rear
|
||||
DeviceType string `json:"device_type,omitempty"`
|
||||
Serial string `json:"serial,omitempty"`
|
||||
AssetTag string `json:"asset_tag,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
VCPUs string `json:"vcpus,omitempty"`
|
||||
MemoryMB int `json:"memory_mb,omitempty"`
|
||||
DiskGB int `json:"disk_gb,omitempty"`
|
||||
IPs []IPAssignment `json:"ips"`
|
||||
}
|
||||
|
||||
// IPAssignment is one IP address of a host with the interface it is on.
|
||||
type IPAssignment struct {
|
||||
Address string `json:"address"` // CIDR notation
|
||||
Interface string `json:"interface,omitempty"`
|
||||
DNSName string `json:"dns_name,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
VRF string `json:"vrf,omitempty"`
|
||||
Primary bool `json:"primary,omitempty"`
|
||||
}
|
||||
|
||||
// IPOwner is a NetBox IP address found by LookupIP, with the host and
|
||||
// interface it is assigned to.
|
||||
type IPOwner struct {
|
||||
Source string `json:"instance,omitempty"`
|
||||
Address string `json:"address"`
|
||||
Status string `json:"status,omitempty"`
|
||||
DNSName string `json:"dns_name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
VRF string `json:"vrf,omitempty"`
|
||||
Interface string `json:"interface,omitempty"`
|
||||
HostKind string `json:"kind,omitempty"` // device | vm; empty when unassigned
|
||||
HostName string `json:"host,omitempty"`
|
||||
HostID int `json:"host_id,omitempty"`
|
||||
}
|
||||
|
||||
// Target returns the selector of the owning host, or "" when unassigned.
|
||||
func (o IPOwner) Target() string {
|
||||
if o.HostName == "" {
|
||||
return ""
|
||||
}
|
||||
return HostEntry{Source: o.Source, Name: o.HostName}.Target()
|
||||
}
|
||||
|
||||
// PrefixInfo is a NetBox prefix that contains an address.
|
||||
type PrefixInfo struct {
|
||||
Source string `json:"instance,omitempty"`
|
||||
Prefix string `json:"prefix"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
Site string `json:"site,omitempty"`
|
||||
VLAN string `json:"vlan,omitempty"`
|
||||
VRF string `json:"vrf,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type netboxHostDetail struct {
|
||||
netboxDevice
|
||||
Face *netboxStatus `json:"face"`
|
||||
Serial string `json:"serial"`
|
||||
AssetTag *string `json:"asset_tag"`
|
||||
DeviceType *struct {
|
||||
ID int `json:"id"`
|
||||
Model string `json:"model"`
|
||||
Manufacturer *netboxRef `json:"manufacturer"`
|
||||
} `json:"device_type"`
|
||||
Description string `json:"description"`
|
||||
VCPUs json.Number `json:"vcpus"`
|
||||
Memory *int `json:"memory"`
|
||||
Disk *int `json:"disk"`
|
||||
}
|
||||
|
||||
type netboxIPAddress struct {
|
||||
Address string `json:"address"`
|
||||
Status *netboxStatus `json:"status"`
|
||||
Role *netboxStatus `json:"role"`
|
||||
DNSName string `json:"dns_name"`
|
||||
Description string `json:"description"`
|
||||
VRF *netboxRef `json:"vrf"`
|
||||
ObjectType string `json:"assigned_object_type"`
|
||||
Object *struct {
|
||||
Name string `json:"name"`
|
||||
Device *struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"device"`
|
||||
VirtualMachine *struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"virtual_machine"`
|
||||
} `json:"assigned_object"`
|
||||
}
|
||||
|
||||
type netboxPrefix struct {
|
||||
Prefix string `json:"prefix"`
|
||||
Status *netboxStatus `json:"status"`
|
||||
Role *netboxRef `json:"role"`
|
||||
Site *netboxRef `json:"site"`
|
||||
Scope *netboxRef `json:"scope"`
|
||||
VRF *netboxRef `json:"vrf"`
|
||||
Description string `json:"description"`
|
||||
VLAN *struct {
|
||||
VID int `json:"vid"`
|
||||
Name string `json:"name"`
|
||||
} `json:"vlan"`
|
||||
}
|
||||
|
||||
func hostPath(kind string) (string, error) {
|
||||
switch kind {
|
||||
case "device":
|
||||
return "dcim/devices", nil
|
||||
case "vm":
|
||||
return "virtualization/virtual-machines", nil
|
||||
}
|
||||
return "", fmt.Errorf("invalid host kind %q", kind)
|
||||
}
|
||||
|
||||
// WebURL returns the page of a host in the NetBox web interface.
|
||||
func (c *Client) WebURL(host HostEntry) (string, error) {
|
||||
source, host, err := c.sourceForHost(host)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path, err := hostPath(host.Kind)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if host.ID <= 0 {
|
||||
return "", fmt.Errorf("NetBox ID of %s is unknown", host.Target())
|
||||
}
|
||||
return fmt.Sprintf("%s/%s/%d/", source.baseURL, path, host.ID), nil
|
||||
}
|
||||
|
||||
// GetDetails fetches the full record and all IP addresses of a host.
|
||||
func (c *Client) GetDetails(ctx context.Context, host HostEntry) (HostDetails, error) {
|
||||
source, host, err := c.sourceForHost(host)
|
||||
if err != nil {
|
||||
return HostDetails{}, err
|
||||
}
|
||||
apiURL, err := source.hostURL(host)
|
||||
if err != nil {
|
||||
return HostDetails{}, err
|
||||
}
|
||||
var raw netboxHostDetail
|
||||
if err := source.get(ctx, apiURL, &raw); err != nil {
|
||||
return HostDetails{}, err
|
||||
}
|
||||
entry := deviceToEntry(raw.netboxDevice)
|
||||
entry.Kind, entry.Source = host.Kind, host.Source
|
||||
entries := []HostEntry{entry}
|
||||
source.fillLocations(ctx, entries)
|
||||
entry = entries[0]
|
||||
d := HostDetails{HostEntry: entry, Serial: raw.Serial, Description: raw.Description}
|
||||
d.URL, _ = c.WebURL(entry)
|
||||
if raw.Status != nil {
|
||||
d.StatusLabel = raw.Status.Label
|
||||
}
|
||||
if raw.Face != nil {
|
||||
d.Face = raw.Face.Value
|
||||
}
|
||||
if raw.AssetTag != nil {
|
||||
d.AssetTag = *raw.AssetTag
|
||||
}
|
||||
if raw.DeviceType != nil && entry.Position != "" && raw.DeviceType.ID > 0 {
|
||||
var deviceType struct {
|
||||
UHeight json.Number `json:"u_height"`
|
||||
}
|
||||
if err := source.get(ctx, fmt.Sprintf("%s/api/dcim/device-types/%d/", source.baseURL, raw.DeviceType.ID), &deviceType); err == nil {
|
||||
d.HeightU = rackUnit(deviceType.UHeight)
|
||||
}
|
||||
}
|
||||
if raw.DeviceType != nil {
|
||||
d.DeviceType = raw.DeviceType.Model
|
||||
if raw.DeviceType.Manufacturer != nil && raw.DeviceType.Manufacturer.Name != "" {
|
||||
d.DeviceType = raw.DeviceType.Manufacturer.Name + " " + d.DeviceType
|
||||
}
|
||||
}
|
||||
if raw.VCPUs != "" {
|
||||
d.VCPUs = strings.TrimSuffix(strings.TrimSuffix(raw.VCPUs.String(), ".00"), ".0")
|
||||
}
|
||||
if raw.Memory != nil {
|
||||
d.MemoryMB = *raw.Memory
|
||||
}
|
||||
if raw.Disk != nil {
|
||||
d.DiskGB = *raw.Disk
|
||||
}
|
||||
|
||||
filter := fmt.Sprintf("device_id=%d", host.ID)
|
||||
if host.Kind == "vm" {
|
||||
filter = fmt.Sprintf("virtual_machine_id=%d", host.ID)
|
||||
}
|
||||
addresses, err := source.fetchIPAddresses(ctx, filter)
|
||||
if err != nil {
|
||||
return d, fmt.Errorf("IP addresses: %w", err)
|
||||
}
|
||||
for _, a := range addresses {
|
||||
ip := IPAssignment{Address: a.Address, DNSName: a.DNSName, Status: a.Status.value(), Role: a.Role.value()}
|
||||
if a.VRF != nil {
|
||||
ip.VRF = a.VRF.Name
|
||||
}
|
||||
if a.Object != nil {
|
||||
ip.Interface = a.Object.Name
|
||||
}
|
||||
addr := stripPrefix(a.Address)
|
||||
ip.Primary = addr == entry.PrimaryIP4 || addr == entry.PrimaryIP6
|
||||
d.IPs = append(d.IPs, ip)
|
||||
}
|
||||
sort.SliceStable(d.IPs, func(i, j int) bool {
|
||||
if d.IPs[i].Primary != d.IPs[j].Primary {
|
||||
return d.IPs[i].Primary
|
||||
}
|
||||
return d.IPs[i].Interface < d.IPs[j].Interface
|
||||
})
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (c *Client) fetchIPAddresses(ctx context.Context, filter string) ([]netboxIPAddress, error) {
|
||||
const pageSize = 100
|
||||
var out []netboxIPAddress
|
||||
for offset := 0; ; offset += pageSize {
|
||||
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=%d&offset=%d", c.baseURL, filter, pageSize, offset)
|
||||
var resp netboxListResponse[netboxIPAddress]
|
||||
if err := c.get(ctx, apiURL, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, resp.Results...)
|
||||
if len(resp.Results) < pageSize || len(out) >= resp.Count {
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// eachSource runs fn for every configured instance in name order, or once
|
||||
// for a single-instance client. It keeps going after an error, so one
|
||||
// unreachable instance does not hide answers from the others.
|
||||
func (c *Client) eachSource(fn func(name string, source *Client) error) error {
|
||||
if c.sources == nil {
|
||||
return fn("", c)
|
||||
}
|
||||
names := make([]string, 0, len(c.sources))
|
||||
for name := range c.sources {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
var errs []error
|
||||
for _, name := range names {
|
||||
if err := fn(name, c.sources[name]); err != nil {
|
||||
errs = append(errs, fmt.Errorf("NetBox %s: %w", name, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// LookupIP finds the NetBox IP address records of ip in every instance.
|
||||
func (c *Client) LookupIP(ctx context.Context, ip string) ([]IPOwner, error) {
|
||||
var out []IPOwner
|
||||
err := c.eachSource(func(name string, source *Client) error {
|
||||
found, err := source.fetchIPAddresses(ctx, "address="+url.QueryEscape(ip))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, a := range found {
|
||||
owner := IPOwner{Source: name, Address: a.Address, Status: a.Status.value(), DNSName: a.DNSName, Description: a.Description}
|
||||
if a.VRF != nil {
|
||||
owner.VRF = a.VRF.Name
|
||||
}
|
||||
if a.Object != nil {
|
||||
owner.Interface = a.Object.Name
|
||||
switch {
|
||||
case a.Object.Device != nil:
|
||||
owner.HostKind, owner.HostName, owner.HostID = "device", a.Object.Device.Name, a.Object.Device.ID
|
||||
case a.Object.VirtualMachine != nil:
|
||||
owner.HostKind, owner.HostName, owner.HostID = "vm", a.Object.VirtualMachine.Name, a.Object.VirtualMachine.ID
|
||||
}
|
||||
}
|
||||
out = append(out, owner)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// PrefixesContaining returns the prefixes containing ip, most specific last.
|
||||
func (c *Client) PrefixesContaining(ctx context.Context, ip string) ([]PrefixInfo, error) {
|
||||
var out []PrefixInfo
|
||||
err := c.eachSource(func(name string, source *Client) error {
|
||||
apiURL := fmt.Sprintf("%s/api/ipam/prefixes/?contains=%s&limit=100", source.baseURL, url.QueryEscape(ip))
|
||||
var resp netboxListResponse[netboxPrefix]
|
||||
if err := source.get(ctx, apiURL, &resp); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, p := range resp.Results {
|
||||
info := PrefixInfo{Source: name, Prefix: p.Prefix, Status: p.Status.value(), Description: p.Description}
|
||||
if p.Role != nil {
|
||||
info.Role = p.Role.Name
|
||||
}
|
||||
if p.Site != nil {
|
||||
info.Site = p.Site.Name
|
||||
} else if p.Scope != nil {
|
||||
info.Site = p.Scope.Name
|
||||
}
|
||||
if p.VRF != nil {
|
||||
info.VRF = p.VRF.Name
|
||||
}
|
||||
if p.VLAN != nil {
|
||||
info.VLAN = strconv.Itoa(p.VLAN.VID)
|
||||
if p.VLAN.Name != "" {
|
||||
info.VLAN += " (" + p.VLAN.Name + ")"
|
||||
}
|
||||
}
|
||||
out = append(out, info)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.SliceStable(out, func(i, j int) bool { return prefixLen(out[i].Prefix) < prefixLen(out[j].Prefix) })
|
||||
return out, err
|
||||
}
|
||||
|
||||
func prefixLen(prefix string) int {
|
||||
_, bits, _ := strings.Cut(prefix, "/")
|
||||
n, _ := strconv.Atoi(bits)
|
||||
return n
|
||||
}
|
||||
|
||||
// RackUnits renders the occupied units, e.g. "U20-21 (2U, front)".
|
||||
func (d HostDetails) RackUnits() string {
|
||||
if d.Position == "" {
|
||||
return ""
|
||||
}
|
||||
units := "U" + d.Position
|
||||
var extra []string
|
||||
if height, err := strconv.ParseFloat(d.HeightU, 64); err == nil && height > 0 {
|
||||
if start, err := strconv.ParseFloat(d.Position, 64); err == nil && height > 1 {
|
||||
units += "-" + strconv.FormatFloat(start+height-1, 'f', -1, 64)
|
||||
}
|
||||
extra = append(extra, d.HeightU+"U")
|
||||
}
|
||||
if d.Face != "" {
|
||||
extra = append(extra, d.Face)
|
||||
}
|
||||
if len(extra) > 0 {
|
||||
units += " (" + strings.Join(extra, ", ") + ")"
|
||||
}
|
||||
return units
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package netbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func detailServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.URL.Path == "/api/dcim/devices/7/":
|
||||
fmt.Fprint(w, `{"id":7,"name":"sw1","status":{"value":"offline","label":"Offline"},
|
||||
"site":{"name":"Falkenstein 1","slug":"fsn1"},"rack":{"name":"R12"},"position":20.0,
|
||||
"device_role":{"name":"Core Switch","slug":"core-switch"},"platform":{"name":"Junos","slug":"junos"},
|
||||
"tenant":null,"serial":"ABC","asset_tag":null,"device_type":{"model":"QFX5120","manufacturer":{"name":"Juniper"}},
|
||||
"primary_ip4":{"address":"10.0.0.7/24"},"tags":[{"name":"core"}]}`)
|
||||
case r.URL.Path == "/api/ipam/ip-addresses/" && r.URL.Query().Get("device_id") == "7":
|
||||
fmt.Fprint(w, `{"count":2,"results":[
|
||||
{"address":"192.0.2.7/24","assigned_object":{"name":"xe-0/0/1"},"status":{"value":"active"}},
|
||||
{"address":"10.0.0.7/24","assigned_object":{"name":"em0"},"dns_name":"sw1.example.com","status":{"value":"active"}}]}`)
|
||||
case r.URL.Path == "/api/ipam/ip-addresses/" && r.URL.Query().Get("address") != "":
|
||||
fmt.Fprint(w, `{"count":1,"results":[{"address":"10.0.0.7/24","status":{"value":"active"},
|
||||
"assigned_object_type":"dcim.interface","assigned_object":{"name":"em0","device":{"id":7,"name":"sw1"}}}]}`)
|
||||
case r.URL.Path == "/api/ipam/prefixes/":
|
||||
if r.URL.Query().Get("contains") != "10.0.0.7" {
|
||||
t.Errorf("unexpected contains %q", r.URL.Query().Get("contains"))
|
||||
}
|
||||
fmt.Fprint(w, `{"count":2,"results":[
|
||||
{"prefix":"10.0.0.0/24","status":{"value":"active"},"vlan":{"vid":100,"name":"mgmt"},"site":{"name":"FSN1"}},
|
||||
{"prefix":"10.0.0.0/8","description":"internal"}]}`)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func TestDeviceAttributesAndDetails(t *testing.T) {
|
||||
srv := detailServer(t)
|
||||
c := NewClient(srv.URL, "token", 0)
|
||||
d, err := c.GetDetails(context.Background(), HostEntry{ID: 7, Name: "sw1", Kind: "device"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Status != "offline" || d.StatusLabel != "Offline" || d.Site.Slug != "fsn1" || d.Role.Slug != "core-switch" || d.Platform.Slug != "junos" {
|
||||
t.Fatalf("attributes not parsed: %+v", d.HostEntry)
|
||||
}
|
||||
if d.Rack != "R12" || d.Position != "20" || d.DeviceType != "Juniper QFX5120" || d.Serial != "ABC" {
|
||||
t.Fatalf("details not parsed: %+v", d)
|
||||
}
|
||||
if d.URL != srv.URL+"/dcim/devices/7/" {
|
||||
t.Fatalf("web URL %q", d.URL)
|
||||
}
|
||||
if len(d.IPs) != 2 || !d.IPs[0].Primary || d.IPs[0].Interface != "em0" || d.IPs[0].DNSName != "sw1.example.com" {
|
||||
t.Fatalf("IPs not sorted primary first: %+v", d.IPs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebURLForInstances(t *testing.T) {
|
||||
c := NewMultiClient([]Source{{Name: "prod", URL: "https://nb.example/", Token: "t"}})
|
||||
got, err := c.WebURL(HostEntry{Source: "prod", Name: "web", Kind: "vm", ID: 3})
|
||||
if err != nil || got != "https://nb.example/virtualization/virtual-machines/3/" {
|
||||
t.Fatalf("got %q, %v", got, err)
|
||||
}
|
||||
if _, err := c.WebURL(HostEntry{Source: "prod", Name: "web", Kind: "vm"}); err == nil {
|
||||
t.Fatal("missing ID accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupIPAndPrefixes(t *testing.T) {
|
||||
srv := detailServer(t)
|
||||
c := NewMultiClient([]Source{{Name: "prod", URL: srv.URL, Token: "t"}})
|
||||
owners, err := c.LookupIP(context.Background(), "10.0.0.7")
|
||||
if err != nil || len(owners) != 1 || owners[0].Target() != "prod/sw1" || owners[0].Interface != "em0" || owners[0].HostKind != "device" {
|
||||
t.Fatalf("owners %+v, %v", owners, err)
|
||||
}
|
||||
prefixes, err := c.PrefixesContaining(context.Background(), "10.0.0.7")
|
||||
if err != nil || len(prefixes) != 2 || prefixes[0].Prefix != "10.0.0.0/8" || prefixes[1].VLAN != "100 (mgmt)" || prefixes[1].Source != "prod" {
|
||||
t.Fatalf("prefixes %+v, %v", prefixes, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupIPReportsFailingInstanceButKeepsOthers(t *testing.T) {
|
||||
good := detailServer(t)
|
||||
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "down", http.StatusBadGateway)
|
||||
}))
|
||||
defer bad.Close()
|
||||
c := NewMultiClient([]Source{{Name: "a", URL: bad.URL, Token: "t"}, {Name: "b", URL: good.URL, Token: "t"}})
|
||||
owners, err := c.LookupIP(context.Background(), "10.0.0.7")
|
||||
if err == nil || !strings.Contains(err.Error(), "NetBox a") || len(owners) != 1 {
|
||||
t.Fatalf("owners %+v, err %v", owners, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package netbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
)
|
||||
|
||||
// maxLocationDepth stops walking up a broken (cyclic) location tree.
|
||||
const maxLocationDepth = 16
|
||||
|
||||
type locationNode struct {
|
||||
ref config.Ref
|
||||
parent int
|
||||
}
|
||||
|
||||
type netboxLocation struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Parent *struct {
|
||||
ID int `json:"id"`
|
||||
} `json:"parent"`
|
||||
}
|
||||
|
||||
// rackUnit formats a NetBox rack position (a decimal such as 20.0 or 20.5).
|
||||
func rackUnit(n json.Number) string {
|
||||
if n == "" {
|
||||
return ""
|
||||
}
|
||||
s := n.String()
|
||||
if strings.Contains(s, ".") {
|
||||
s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// locationChain returns the locations from the outermost to id. NetBox nests
|
||||
// locations through "parent"; each location is fetched once per client.
|
||||
func (c *Client) locationChain(ctx context.Context, id int) ([]config.Ref, error) {
|
||||
var chain []config.Ref
|
||||
for depth := 0; id > 0 && depth < maxLocationDepth; depth++ {
|
||||
node, err := c.location(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chain = append([]config.Ref{node.ref}, chain...)
|
||||
id = node.parent
|
||||
}
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
func (c *Client) location(ctx context.Context, id int) (locationNode, error) {
|
||||
c.locMu.Lock()
|
||||
node, ok := c.locations[id]
|
||||
c.locMu.Unlock()
|
||||
if ok {
|
||||
return node, nil
|
||||
}
|
||||
var raw netboxLocation
|
||||
if err := c.get(ctx, fmt.Sprintf("%s/api/dcim/locations/%d/", c.baseURL, id), &raw); err != nil {
|
||||
return locationNode{}, err
|
||||
}
|
||||
node = locationNode{ref: config.Ref{Name: raw.Name, Slug: raw.Slug}}
|
||||
if raw.Parent != nil {
|
||||
node.parent = raw.Parent.ID
|
||||
}
|
||||
c.locMu.Lock()
|
||||
if c.locations == nil {
|
||||
c.locations = map[int]locationNode{}
|
||||
}
|
||||
c.locations[id] = node
|
||||
c.locMu.Unlock()
|
||||
return node, nil
|
||||
}
|
||||
|
||||
// fillLocations replaces each device's own location with the full chain of
|
||||
// parent locations. A failed lookup keeps the device's own location: the
|
||||
// location is informational and must not break a search or a connection.
|
||||
func (c *Client) fillLocations(ctx context.Context, entries []HostEntry) {
|
||||
for i := range entries {
|
||||
if entries[i].locationID <= 0 {
|
||||
continue
|
||||
}
|
||||
if chain, err := c.locationChain(ctx, entries[i].locationID); err == nil && len(chain) > 0 {
|
||||
entries[i].Location = chain
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package netbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// locationServer serves a site with Building A › Floor 2 › Room 2.04 and two
|
||||
// racked devices in Room 2.04, plus a location loop 90 ↔ 91.
|
||||
func locationServer(t *testing.T, calls *int32) *httptest.Server {
|
||||
t.Helper()
|
||||
locations := map[string]string{
|
||||
"1": `{"id":1,"name":"Building A","slug":"building-a","parent":null}`,
|
||||
"2": `{"id":2,"name":"Floor 2","slug":"floor-2","parent":{"id":1}}`,
|
||||
"3": `{"id":3,"name":"Room 2.04","slug":"room-2-04","parent":{"id":2}}`,
|
||||
"90": `{"id":90,"name":"Loop A","slug":"loop-a","parent":{"id":91}}`,
|
||||
"91": `{"id":91,"name":"Loop B","slug":"loop-b","parent":{"id":90}}`,
|
||||
}
|
||||
device := func(id int, name string, location int, position string) string {
|
||||
return fmt.Sprintf(`{"id":%d,"name":%q,"site":{"name":"FSN1","slug":"fsn1"},"location":{"id":%d,"name":"x","slug":"x"},
|
||||
"rack":{"name":"R12"},"position":%s,"face":{"value":"front"},"device_type":{"id":9,"model":"R640"}}`, id, name, location, position)
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasPrefix(r.URL.Path, "/api/dcim/locations/"):
|
||||
atomic.AddInt32(calls, 1)
|
||||
id := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/dcim/locations/"), "/")
|
||||
if body, ok := locations[id]; ok {
|
||||
fmt.Fprint(w, body)
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
case r.URL.Path == "/api/dcim/devices/":
|
||||
fmt.Fprintf(w, `{"count":3,"results":[%s,%s,%s]}`, device(1, "srv1", 3, "20.0"), device(2, "srv2", 3, "22"), device(3, "loopy", 90, "null"))
|
||||
case r.URL.Path == "/api/dcim/devices/1/":
|
||||
fmt.Fprint(w, device(1, "srv1", 3, "20.0"))
|
||||
case r.URL.Path == "/api/dcim/device-types/9/":
|
||||
fmt.Fprint(w, `{"id":9,"u_height":2.0}`)
|
||||
case r.URL.Path == "/api/virtualization/virtual-machines/", r.URL.Path == "/api/ipam/ip-addresses/":
|
||||
fmt.Fprint(w, `{"count":0,"results":[]}`)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func TestSearchAllResolvesNestedLocations(t *testing.T) {
|
||||
var calls int32
|
||||
srv := locationServer(t, &calls)
|
||||
entries, err := NewClient(srv.URL, "t", 0).SearchAll(context.Background(), "", SearchOptions{Kind: "device"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byName := map[string]HostEntry{}
|
||||
for _, e := range entries {
|
||||
byName[e.Name] = e
|
||||
}
|
||||
srv1 := byName["srv1"]
|
||||
if got := srv1.LocationPath(); got != "FSN1 › Building A › Floor 2 › Room 2.04 › R12 › U20" {
|
||||
t.Fatalf("path %q", got)
|
||||
}
|
||||
if srv1.Location[0].Slug != "building-a" || srv1.Location[2].Slug != "room-2-04" {
|
||||
t.Fatalf("chain order: %+v", srv1.Location)
|
||||
}
|
||||
// Room, floor and building are fetched once for both devices, the loop
|
||||
// stops at the depth limit instead of hanging.
|
||||
if n := atomic.LoadInt32(&calls); n != 5 {
|
||||
t.Fatalf("location requests: %d", n)
|
||||
}
|
||||
if len(byName["loopy"].Location) != maxLocationDepth || byName["loopy"].Position != "" {
|
||||
t.Fatalf("loop not bounded: %d", len(byName["loopy"].Location))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetailsShowRackUnits(t *testing.T) {
|
||||
var calls int32
|
||||
srv := locationServer(t, &calls)
|
||||
d, err := NewClient(srv.URL, "t", 0).GetDetails(context.Background(), HostEntry{ID: 1, Name: "srv1", Kind: "device"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Rack != "R12" || d.Position != "20" || d.HeightU != "2" || d.RackUnits() != "U20-21 (2U, front)" {
|
||||
t.Fatalf("rack: %q %q %q %q", d.Rack, d.Position, d.HeightU, d.RackUnits())
|
||||
}
|
||||
if len(d.Location) != 3 {
|
||||
t.Fatalf("details lack location chain: %+v", d.Location)
|
||||
}
|
||||
if (HostDetails{HostEntry: HostEntry{Position: "7"}, HeightU: "1"}).RackUnits() != "U7 (1U)" {
|
||||
t.Fatal("single unit")
|
||||
}
|
||||
if (HostDetails{}).RackUnits() != "" {
|
||||
t.Fatal("unracked device should have no units")
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package netbox
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
)
|
||||
|
||||
// SearchOptions filters a Search or SearchAll query.
|
||||
@@ -27,6 +30,49 @@ type HostEntry struct {
|
||||
PrimaryIP6 string
|
||||
Tags []string
|
||||
Cluster string // virtualization cluster name, if assigned
|
||||
Status string // NetBox status value, e.g. "active"
|
||||
Site config.Ref
|
||||
Role config.Ref
|
||||
Platform config.Ref
|
||||
Tenant config.Ref
|
||||
// Location is the chain of nested NetBox locations from the outermost
|
||||
// (directly below the site) to the device's own location.
|
||||
Location []config.Ref
|
||||
Rack string
|
||||
Position string // lowest rack unit, e.g. "20"; empty when not racked
|
||||
|
||||
locationID int // the device's own location, before the chain is resolved
|
||||
}
|
||||
|
||||
// LocationPath renders site › locations › rack › U position.
|
||||
func (h HostEntry) LocationPath() string {
|
||||
return config.LocationPath(h.Site, h.Location, h.Rack, h.Position)
|
||||
}
|
||||
|
||||
// netboxRef is a nested NetBox object with a name and slug.
|
||||
type netboxRef struct {
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
}
|
||||
|
||||
func (r *netboxRef) ref() config.Ref {
|
||||
if r == nil {
|
||||
return config.Ref{}
|
||||
}
|
||||
return config.Ref{Name: r.Name, Slug: r.Slug}
|
||||
}
|
||||
|
||||
// netboxStatus is a NetBox choice field such as status.
|
||||
type netboxStatus struct {
|
||||
Value string `json:"value"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
func (s *netboxStatus) value() string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return s.Value
|
||||
}
|
||||
|
||||
// netboxCluster is the nested cluster of a device or virtual machine.
|
||||
@@ -50,6 +96,21 @@ type netboxDevice struct {
|
||||
PrimaryIP4 *netboxIP `json:"primary_ip4"`
|
||||
PrimaryIP6 *netboxIP `json:"primary_ip6"`
|
||||
Cluster *netboxCluster `json:"cluster"`
|
||||
Status *netboxStatus `json:"status"`
|
||||
Site *netboxRef `json:"site"`
|
||||
Role *netboxRef `json:"role"`
|
||||
DeviceRole *netboxRef `json:"device_role"` // NetBox < 3.6
|
||||
Platform *netboxRef `json:"platform"`
|
||||
Tenant *netboxRef `json:"tenant"`
|
||||
Location *struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
} `json:"location"`
|
||||
Rack *struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"rack"`
|
||||
Position json.Number `json:"position"`
|
||||
}
|
||||
|
||||
// netboxVM matches the relevant fields of the NetBox /virtualization/virtual-machines/ response.
|
||||
@@ -62,6 +123,21 @@ type netboxVM struct {
|
||||
PrimaryIP4 *netboxIP `json:"primary_ip4"`
|
||||
PrimaryIP6 *netboxIP `json:"primary_ip6"`
|
||||
Cluster *netboxCluster `json:"cluster"`
|
||||
Status *netboxStatus `json:"status"`
|
||||
Site *netboxRef `json:"site"`
|
||||
Role *netboxRef `json:"role"`
|
||||
DeviceRole *netboxRef `json:"device_role"` // NetBox < 3.6
|
||||
Platform *netboxRef `json:"platform"`
|
||||
Tenant *netboxRef `json:"tenant"`
|
||||
Location *struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
} `json:"location"`
|
||||
Rack *struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"rack"`
|
||||
Position json.Number `json:"position"`
|
||||
}
|
||||
|
||||
type netboxListResponse[T any] struct {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package resolver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
)
|
||||
|
||||
func TestCandidatesListsEveryStrategyOnce(t *testing.T) {
|
||||
chain, err := New(config.ResolverConfig{Strategies: []string{"primary_ip", "hostname"}, HostnameDomain: "example.com"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry := &netbox.HostEntry{Name: "web", Kind: "vm", PrimaryIP4: "10.0.0.1", PrimaryIP6: "2001:db8::1"}
|
||||
got, err := chain.Candidates(context.Background(), entry, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []Candidate{{"10.0.0.1", "primary_ip"}, {"web.example.com", "hostname"}, {"2001:db8::1", "primary_ip"}}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("got %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,3 +69,43 @@ func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
|
||||
return nil, fmt.Errorf("unknown strategy %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
// Candidate is an address one strategy resolved for a host.
|
||||
type Candidate struct {
|
||||
Address string
|
||||
Strategy string
|
||||
}
|
||||
|
||||
// Candidates runs every strategy and returns their distinct addresses in the
|
||||
// configured order. Unlike Resolve, an API failure of one strategy does not
|
||||
// stop the others: candidates are only used as fallbacks for an address that
|
||||
// was already chosen by Resolve and turned out to be unreachable.
|
||||
func (c *Chain) Candidates(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) ([]Candidate, error) {
|
||||
var out []Candidate
|
||||
var errs []error
|
||||
seen := map[string]bool{}
|
||||
for _, s := range c.strategies {
|
||||
ip, err := s.Resolve(ctx, entry, client)
|
||||
if err != nil {
|
||||
if !errors.Is(err, ErrNoIP) {
|
||||
errs = append(errs, fmt.Errorf("%s: %w", s.Name(), err))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !seen[ip] {
|
||||
seen[ip] = true
|
||||
out = append(out, Candidate{Address: ip, Strategy: s.Name()})
|
||||
}
|
||||
}
|
||||
// Both addresses of a dual-stack host are worth trying.
|
||||
for _, ip := range []string{entry.PrimaryIP4, entry.PrimaryIP6} {
|
||||
if ip != "" && !seen[ip] {
|
||||
seen[ip] = true
|
||||
out = append(out, Candidate{Address: ip, Strategy: "primary_ip"})
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, errors.Join(errs...)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Package secret keeps NetBox API tokens in the operating system's keyring
|
||||
// (Secret Service on Linux, Keychain on macOS) instead of the config file.
|
||||
package secret
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/zalando/go-keyring"
|
||||
)
|
||||
|
||||
// Service is the keyring service name of all netssh entries.
|
||||
const Service = "netssh"
|
||||
|
||||
// ErrNotFound means the keyring has no token for the account.
|
||||
var ErrNotFound = errors.New("no token in the system keyring")
|
||||
|
||||
// Get returns the token stored for account.
|
||||
func Get(account string) (string, error) {
|
||||
token, err := keyring.Get(Service, account)
|
||||
if errors.Is(err, keyring.ErrNotFound) {
|
||||
return "", fmt.Errorf("%w for %q (store one with: netssh token set %s)", ErrNotFound, account, account)
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("system keyring: %w", err)
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// Set stores token for account, replacing an existing one.
|
||||
func Set(account, token string) error {
|
||||
if err := keyring.Set(Service, account, token); err != nil {
|
||||
return fmt.Errorf("system keyring: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete removes the token of account; a missing entry is not an error.
|
||||
func Delete(account string) error {
|
||||
err := keyring.Delete(Service, account)
|
||||
if err != nil && !errors.Is(err, keyring.ErrNotFound) {
|
||||
return fmt.Errorf("system keyring: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MockInit replaces the system keyring with an in-memory one, for tests.
|
||||
func MockInit() { keyring.MockInit() }
|
||||
@@ -71,10 +71,15 @@ func editCommands(cfg *config.Config) error {
|
||||
huh.NewInput().Title("Only for instance").Value(&command.Match.Instance),
|
||||
huh.NewInput().Title("Only for kind").Description("device, vm or static; empty means all.").Value(&command.Match.Kind),
|
||||
huh.NewInput().Title("Only for hostname pattern").Description("For example router*; all specified filters must match.").Value(&command.Match.Name),
|
||||
huh.NewInput().Title("Only for site").Description("NetBox site name or slug.").Value(&command.Match.Site),
|
||||
huh.NewInput().Title("Only for role").Description("NetBox device/VM role name or slug.").Value(&command.Match.Role),
|
||||
huh.NewInput().Title("Only for platform").Description("NetBox platform name or slug, e.g. junos.").Value(&command.Match.Platform),
|
||||
huh.NewInput().Title("Only for status").Description("NetBox status value, e.g. active.").Value(&command.Match.Status),
|
||||
).Title("Local command")).Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
command.Match = trimMatch(command.Match)
|
||||
command.Args = []string{binary}
|
||||
if arguments != "" {
|
||||
command.Args = append(command.Args, strings.Split(arguments, "\n")...)
|
||||
|
||||
@@ -11,6 +11,12 @@ import (
|
||||
func editOperations(cfg *config.Config) error {
|
||||
history, days, entries := strconv.Itoa(cfg.TUI.HistoryLimit), strconv.Itoa(cfg.Activity.RetentionDays), strconv.Itoa(cfg.Activity.MaxEntries)
|
||||
enabled := cfg.Activity.Enabled
|
||||
columns := append([]string(nil), cfg.TUI.EffectiveColumns()...)
|
||||
timeout := strconv.Itoa(int(cfg.TUI.ReachabilityTimeoutDuration().Milliseconds()))
|
||||
columnOptions := make([]huh.Option[string], 0, len(config.TUIColumns))
|
||||
for _, column := range config.TUIColumns {
|
||||
columnOptions = append(columnOptions, huh.NewOption(columnLabels[column], column).Selected(contains(columns, column)))
|
||||
}
|
||||
valid := func(s string) error {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 0 {
|
||||
@@ -23,13 +29,56 @@ func editOperations(cfg *config.Config) error {
|
||||
huh.NewConfirm().Title("Record local action history?").Description("Stores host, command name, duration and exit code; no arguments or output.").Value(&enabled),
|
||||
huh.NewInput().Title("Retention in days").Description("0 = no age limit").Value(&days).Validate(valid),
|
||||
huh.NewInput().Title("Maximum recorded actions").Description("0 = no count limit").Value(&entries).Validate(valid),
|
||||
).Title("History & activity")).Run()
|
||||
).Title("History & activity"), huh.NewGroup(
|
||||
huh.NewMultiSelect[string]().Title("Shown in the TUI next to each host").
|
||||
Description("Reachability opens a TCP connection to every listed host's SSH port.").
|
||||
Options(columnOptions...).Value(&columns),
|
||||
huh.NewInput().Title("Reachability timeout (ms)").Description("300 by default").Value(&timeout).Validate(valid),
|
||||
).Title("TUI display")).Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.TUI.Columns = orderColumns(cfg.TUI.EffectiveColumns(), columns)
|
||||
if ms, _ := strconv.Atoi(timeout); ms != 300 {
|
||||
cfg.TUI.ReachabilityTimeout = ms
|
||||
} else {
|
||||
cfg.TUI.ReachabilityTimeout = 0
|
||||
}
|
||||
cfg.TUI.HistoryLimit, _ = strconv.Atoi(history)
|
||||
cfg.Activity.RetentionDays, _ = strconv.Atoi(days)
|
||||
cfg.Activity.MaxEntries, _ = strconv.Atoi(entries)
|
||||
cfg.Activity.Enabled = enabled
|
||||
return nil
|
||||
}
|
||||
|
||||
var columnLabels = map[string]string{
|
||||
"alias": "Shortcut alias", "ip": "IP address", "kind": "Kind (device/vm/static)", "source": "Source (live/cache/static)",
|
||||
"status": "NetBox status (if not active)", "site": "Site", "location": "Location (site › locations › rack › U)", "role": "Role", "platform": "Platform", "tenant": "Tenant",
|
||||
"cluster": "Cluster", "tags": "Tags", "reachability": "Reachability (TCP check ✓/✗)",
|
||||
}
|
||||
|
||||
func contains(list []string, value string) bool {
|
||||
for _, item := range list {
|
||||
if item == value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// orderColumns keeps an existing custom order and appends new selections in
|
||||
// the canonical order; the multi-select itself does not preserve order.
|
||||
func orderColumns(previous, selected []string) []string {
|
||||
out := []string{}
|
||||
for _, column := range previous {
|
||||
if contains(selected, column) {
|
||||
out = append(out, column)
|
||||
}
|
||||
}
|
||||
for _, column := range config.TUIColumns {
|
||||
if contains(selected, column) && !contains(out, column) {
|
||||
out = append(out, column)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
+28
-6
@@ -262,22 +262,36 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
|
||||
Title("Kind").
|
||||
Options(huh.NewOption("(any)", ""), huh.NewOption("device", "device"), huh.NewOption("vm", "vm")).
|
||||
Value(&match.Kind),
|
||||
huh.NewInput().
|
||||
Title("Site").
|
||||
Description("NetBox site name or slug, e.g. fsn1").
|
||||
Value(&match.Site),
|
||||
huh.NewInput().
|
||||
Title("Role").
|
||||
Description("NetBox device/VM role name or slug, e.g. core-switch").
|
||||
Value(&match.Role),
|
||||
huh.NewInput().
|
||||
Title("Platform").
|
||||
Description("NetBox platform name or slug, e.g. junos").
|
||||
Value(&match.Platform),
|
||||
huh.NewInput().
|
||||
Title("Status").
|
||||
Description("NetBox status value, e.g. active").
|
||||
Value(&match.Status),
|
||||
huh.NewInput().
|
||||
Title("Name pattern").
|
||||
Description("Shell-style glob without instance prefix, e.g. *.dmz.example.com").
|
||||
Value(&match.Name).
|
||||
Validate(func(s string) error {
|
||||
candidate := match
|
||||
candidate.Tag = strings.TrimSpace(candidate.Tag)
|
||||
candidate.Name = strings.TrimSpace(s)
|
||||
return candidate.Validate("rule")
|
||||
candidate.Name = s
|
||||
return trimMatch(candidate).Validate("rule")
|
||||
}),
|
||||
).Title("Rule match")).Run()
|
||||
if err != nil {
|
||||
return rule, err
|
||||
}
|
||||
match.Tag = strings.TrimSpace(match.Tag)
|
||||
match.Name = strings.TrimSpace(match.Name)
|
||||
match = trimMatch(match)
|
||||
|
||||
options, err := editSSHOptions("SSH options for rule "+describeMatch(match), rule.SSHOptions)
|
||||
if err != nil {
|
||||
@@ -288,10 +302,18 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
|
||||
|
||||
func describeMatch(m config.SSHMatch) string {
|
||||
var parts []string
|
||||
for _, field := range [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name}} {
|
||||
for _, field := range matchFields(m) {
|
||||
if field[1] != "" {
|
||||
parts = append(parts, field[0]+"="+field[1])
|
||||
}
|
||||
}
|
||||
return "[" + strings.Join(parts, " ") + "]"
|
||||
}
|
||||
|
||||
// trimMatch removes surrounding spaces from every selector.
|
||||
func trimMatch(m config.SSHMatch) config.SSHMatch {
|
||||
for _, field := range []*string{&m.Tag, &m.Instance, &m.Kind, &m.Name, &m.Site, &m.Role, &m.Platform, &m.Tenant, &m.Status} {
|
||||
*field = strings.TrimSpace(*field)
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -426,6 +426,12 @@ func save(cfg config.Config) error {
|
||||
for _, s := range cfg.Resolver.Strategies {
|
||||
fmt.Fprintf(&b, " - %s\n", s)
|
||||
}
|
||||
if cfg.Resolver.Fallback {
|
||||
b.WriteString(" fallback: true\n")
|
||||
}
|
||||
if cfg.Resolver.FallbackTimeout > 0 {
|
||||
fmt.Fprintf(&b, " fallback_timeout: %d\n", cfg.Resolver.FallbackTimeout)
|
||||
}
|
||||
if len(cfg.Resolver.ManagementSubnets) > 0 {
|
||||
b.WriteString(" management_subnets:\n")
|
||||
for _, s := range cfg.Resolver.ManagementSubnets {
|
||||
@@ -452,12 +458,19 @@ func save(cfg config.Config) error {
|
||||
if cfg.SSH.DefaultPort > 0 {
|
||||
fmt.Fprintf(&b, " default_port: %d\n", cfg.SSH.DefaultPort)
|
||||
}
|
||||
if cfg.SSH.WarnStatus != nil && !sameStrings(cfg.SSH.WarnStatus, config.DefaultWarnStatus) {
|
||||
quoted := make([]string, 0, len(cfg.SSH.WarnStatus))
|
||||
for _, status := range cfg.SSH.WarnStatus {
|
||||
quoted = append(quoted, strconv.Quote(status))
|
||||
}
|
||||
fmt.Fprintf(&b, " warn_status: [%s]\n", strings.Join(quoted, ", "))
|
||||
}
|
||||
writeSSHOptions(&b, " ", cfg.SSH.SSHOptions)
|
||||
if len(cfg.SSH.Rules) > 0 {
|
||||
b.WriteString(" rules:\n")
|
||||
for _, rule := range cfg.SSH.Rules {
|
||||
b.WriteString(" - match:\n")
|
||||
for _, field := range [][2]string{{"tag", rule.Match.Tag}, {"instance", rule.Match.Instance}, {"kind", rule.Match.Kind}, {"name", rule.Match.Name}} {
|
||||
for _, field := range matchFields(rule.Match) {
|
||||
if field[1] != "" {
|
||||
fmt.Fprintf(&b, " %s: %q\n", field[0], field[1])
|
||||
}
|
||||
@@ -561,7 +574,7 @@ func save(cfg config.Config) error {
|
||||
fmt.Fprintf(&b, " confirm: %t\n timeout: %q\n post_run: %q\n", command.Confirm, command.Timeout, command.PostRun)
|
||||
if command.Match != (config.SSHMatch{}) {
|
||||
b.WriteString(" match:\n")
|
||||
for _, pair := range [][2]string{{"tag", command.Match.Tag}, {"instance", command.Match.Instance}, {"kind", command.Match.Kind}, {"name", command.Match.Name}} {
|
||||
for _, pair := range matchFields(command.Match) {
|
||||
if pair[1] != "" {
|
||||
fmt.Fprintf(&b, " %s: %q\n", pair[0], pair[1])
|
||||
}
|
||||
@@ -570,7 +583,14 @@ func save(cfg config.Config) error {
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\nactivity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.TUI.HistoryLimit, cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
|
||||
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\n", cfg.TUI.HistoryLimit)
|
||||
if cfg.TUI.Columns != nil && !sameStrings(cfg.TUI.Columns, config.DefaultTUIColumns) {
|
||||
fmt.Fprintf(&b, " columns: [%s]\n", strings.Join(cfg.TUI.Columns, ", "))
|
||||
}
|
||||
if cfg.TUI.ReachabilityTimeout > 0 {
|
||||
fmt.Fprintf(&b, " reachability_timeout: %d\n", cfg.TUI.ReachabilityTimeout)
|
||||
}
|
||||
fmt.Fprintf(&b, "activity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
|
||||
if cfg.Shell.Alias != "" {
|
||||
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
|
||||
}
|
||||
@@ -628,3 +648,21 @@ func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// matchFields lists the selectors of a rule or command match in config order.
|
||||
func matchFields(m config.SSHMatch) [][2]string {
|
||||
return [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name},
|
||||
{"site", m.Site}, {"role", m.Role}, {"platform", m.Platform}, {"tenant", m.Tenant}, {"status", m.Status}}
|
||||
}
|
||||
|
||||
func sameStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if !strings.EqualFold(a[i], b[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -715,7 +715,59 @@ func TestOperationsRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TUI != cfg.TUI || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
|
||||
if !reflect.DeepEqual(got.TUI, cfg.TUI) || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
|
||||
t.Fatalf("round trip lost operations: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveRoundtripNetBoxInsightSettings(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", dir)
|
||||
cfg := config.Config{
|
||||
NetBox: config.NetBoxConfig{URL: "https://nb.example", Token: "keyring"},
|
||||
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}, Fallback: true, FallbackTimeout: 400},
|
||||
TUI: config.TUIConfig{HistoryLimit: 10, Columns: []string{"ip", "platform", "reachability"}, ReachabilityTimeout: 900},
|
||||
SSH: config.SSHConfig{WarnStatus: []string{"planned"}, Rules: []config.SSHRule{{
|
||||
Match: config.SSHMatch{Platform: "junos", Site: "fsn1", Role: "core", Tenant: "acme", Status: "active"},
|
||||
SSHOptions: config.SSHOptions{ProxyJump: "jump"},
|
||||
}}},
|
||||
Commands: map[string]config.HostCommand{"cli": {Args: []string{"cli", "{address}"}, Match: config.SSHMatch{Platform: "eos"}}},
|
||||
}
|
||||
if err := Save(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !loaded.Resolver.Fallback || loaded.Resolver.FallbackTimeout != 400 {
|
||||
t.Fatalf("resolver lost: %+v", loaded.Resolver)
|
||||
}
|
||||
if !reflect.DeepEqual(loaded.TUI.Columns, []string{"ip", "platform", "reachability"}) || !loaded.TUI.ReachabilityEnabled() || loaded.TUI.ReachabilityTimeout != 900 {
|
||||
t.Fatalf("tui lost: %+v", loaded.TUI)
|
||||
}
|
||||
if !loaded.SSH.WarnsStatus("planned") || loaded.SSH.WarnsStatus("offline") {
|
||||
t.Fatalf("warn_status lost: %v", loaded.SSH.WarnStatus)
|
||||
}
|
||||
if got := loaded.SSH.Rules[0].Match; got != cfg.SSH.Rules[0].Match {
|
||||
t.Fatalf("rule match lost: %+v", got)
|
||||
}
|
||||
if loaded.Commands["cli"].Match.Platform != "eos" {
|
||||
t.Fatalf("command match lost: %+v", loaded.Commands["cli"].Match)
|
||||
}
|
||||
if !config.IsKeyringToken(loaded.NetBox.Token) || loaded.NetBox.TokenVersion != 0 {
|
||||
t.Fatalf("keyring token changed: %+v", loaded.NetBox)
|
||||
}
|
||||
|
||||
// Defaults stay implicit, so later default changes reach existing configs.
|
||||
cfg = config.Config{NetBox: config.NetBoxConfig{URL: "https://nb.example"}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}}
|
||||
if err := Save(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
|
||||
for _, key := range []string{"warn_status", "columns", "reachability", "fallback"} {
|
||||
if strings.Contains(string(data), key) {
|
||||
t.Errorf("default %s written:\n%s", key, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ type WrapperFlags struct {
|
||||
ForwardArgs []string
|
||||
// Tunnel runs ssh without a remote command (-N), for netssh tunnel.
|
||||
Tunnel bool
|
||||
// Force connects without asking about a NetBox status in ssh.warn_status.
|
||||
Force bool
|
||||
}
|
||||
|
||||
// ExtractWrapperFlags removes netssh's long options that appear before the
|
||||
@@ -40,6 +42,8 @@ func (c Client) ExtractWrapperFlags(args []string) (WrapperFlags, []string, erro
|
||||
flags.DryRun = true
|
||||
case arg == "--no-jump":
|
||||
flags.NoJump = true
|
||||
case arg == "--force":
|
||||
flags.Force = true
|
||||
case arg == "--jump":
|
||||
if i+1 >= len(args) {
|
||||
return flags, nil, fmt.Errorf("--jump requires a host")
|
||||
|
||||
@@ -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