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 }