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
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user