netbox

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2024 License: MIT Imports: 17 Imported by: 0

README

Netbox Go Client

This package provides a Go client for interacting with Netbox. Its main use is within the Netbox_SD project and as such this client provides currently very limited and read-only interfaces.

Documentation

Overview

Package netbox provides types and methods to read Netbox objects via REST/GraphQL API. As of this writing, there are only a subset of objects and actions that are supported.

This package implements the Prometheus collector interface to provide information about inner workings. For normalization of metrics all new instances of Client can be created with a given namespace (see Prometheus Go library for details) to attach to the existing namespace of your application. The subsystem name is always `netbox` and cannot be changed.

Exported metrics:

  • <namespace>_netbox_status{code,url} # number of API calls by response code and relative url
  • <namespace>_netbox_error{url} # number of failed HTTP requests (due to network or whatever)
  • <namespace>_netbox_failure # number of function invocations that resulted in an error being returned
  • <namespace>_netbox_duration{code,url} # (last) duration it took to perform an HTTP request to Netbox by response code and url

TODO: the logging stuff is probably wrong now By default this package logs through the Golang standard library log package. This is obviously annoying when adding this package to another project that uses it's own logging library. To easily change the log facility, this package provides special Interface called `Logger` that can be implemented by other packages and registered with `SetLogger()`. All log messages are then sent through the interface to the target functions that can then decide on how to process the message further.

WARNING: Most Netbox objects in this library contain a public struct attribute `IDString`. This is only used for a workaround when handling GraphQL requests. DO NOT use this attribute anywhere as it will be removed once the bug has been fixed.

Index

Constants

View Source
const (
	StatusDeviceActive          string = "ACTIVE"
	StatusDeviceOffline         string = "OFFLINE"
	StatusDevicePlanned         string = "PLANNED"
	StatusDeviceStaged          string = "STAGED"
	StatusDeviceFailed          string = "FAILED"
	StatusDeviceDecommissioning string = "DECOMMISSIONING"

	StatusIPActive     string = "ACTIVE"
	StatusIPReserved   string = "RESERVED"
	StatusIPDeprecated string = "DEPRECATED"
	StatusIPDHCP       string = "DHCP"
	StatusIPSLAAC      string = "SLAAC"
)

These constants are used to match values returned by Netbox to static names in go. Since Netbox happens to change API details frequently to address new use cases, these constants aim to provide some consistency across applications.

View Source
const (
	CustomFieldText   string = "text"
	CustomFieldNumber string = "integer"
	CustomFieldBool   string = "boolean"
)

Possible custom field value types.

View Source
const SubsystemName string = "netbox_api"

SubsystemName is used for Prometheus metrics subsystem name.

Variables

View Source
var (
	ErrCFMUnsupportedDataType = errors.New("custom field data type not supported")
	ErrCFCantConvertValue     = errors.New("custom field value cannot be converted to destination type")
)

Possible errors returned when working with custom fields.

View Source
var (
	ErrMissingURL           = errors.New("netbox url has not been provided")
	ErrMissingToken         = errors.New("netbox token has not been provided")
	ErrInvalidToken         = errors.New("provided token invalid or missing permissions")
	ErrInvalidURL           = errors.New("provided url invalid")
	ErrUnexpectedStatusCode = errors.New("received unexpected status code from netbox")
	ErrAmbiguous            = errors.New("provided search returned more than one possible result in netbox")
)

Errors exported by this package.

Functions

This section is empty.

Types

type CFMap

type CFMap struct {
	// contains filtered or unexported fields
}

CFMap implements the CustomFieldMap interface.

func (CFMap) GetAllEntries

func (cfm CFMap) GetAllEntries(callback func(string, *CustomField))

GetAllEntries implements CustomFieldMap.GetAllEntries.

func (CFMap) GetEntry

func (cfm CFMap) GetEntry(name string) *CustomField

GetEntry implements CustomFieldMap.GetEntry.

func (*CFMap) UnmarshalJSON

func (cfm *CFMap) UnmarshalJSON(b []byte) error

UnmarshalJSON implements a custom JSON unmarshal interface for CFMap (and therefore CustomFieldMap).

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client describes a Netbox API client to perform REST calls with.

func New

func New(baseURL, token, promNamespace string, withTLS bool, tlsInsecure bool) (*Client, error)

New creates a new Client to interact with a netbox API. baseURL must point to a valid Netbox installation (without /api or /graphql at the end) while token must be a valid Netbox API key. WithTLS enabled TLS for HTTP transport while tlsInsecure can be set to allow any certificate to be accepted.

In standard operation TLS should be used. System wide CAs are trusted.

func (*Client) Collect

func (client *Client) Collect(ch chan<- prometheus.Metric)

Collect implements the prometheus.Collect interface.

func (*Client) Copy

func (client *Client) Copy() ClientIface

Copy creates and returns an identical copy of client. The http.Client is not duplicated but instead points to the same http.Client used for other copies. "[..] Clients should be reused instead of created as needed [..]" as per net/http docs.

func (*Client) Describe

func (client *Client) Describe(ch chan<- *prometheus.Desc)

Describe implements the prometheus.Describe interface.

func (*Client) GetDevice

func (client *Client) GetDevice(id uint64) (*Device, error)

GetDevice returns information about a device gathered from Netbox. When error is not nil, the request failed and error gives further details what went wrong. Dev might point to an invalid address at that point and must not be used whenever an error has been returned. When no device with the given ID has been found, Device as well as error are nil.

func (*Client) GetDevices

func (client *Client) GetDevices() ([]*Device, error)

GetDevices returns a list of all devices.

func (*Client) GetDevicesByTag

func (client *Client) GetDevicesByTag(tag string) ([]*Device, error)

GetDevicesByTag returns a list of all devices with a given tag.

func (*Client) GetIPsByAddress

func (client *Client) GetIPsByAddress(ip string) ([]*IP, error)

GetIPsByAddress returns a list of netbox IP object based on a given address string (legacy IP or IPv6). This is the default option to get any IP object since an address can exist multiple times in various VRFs. The caller is responslible to filter through the result to find the IP it's looking for.

func (*Client) GetInterface

func (client *Client) GetInterface(id uint64) (*Interface, error)

GetInterface returns the device interface identified by id.

func (*Client) GetInterfaceIPs

func (client *Client) GetInterfaceIPs(id uint64) ([]*IP, error)

GetInterfaceIPs returns a list of all IPs associated with a given dcim interface id.

func (*Client) GetInterfacesByTag

func (client *Client) GetInterfacesByTag(tag string) ([]*Interface, error)

GetInterfacesByTag returns a list of all device interfaces having a specific tag set in Netbox.

func (*Client) GetServices

func (client *Client) GetServices() ([]*Service, error)

GetServices returns a list of all services that exists in Netbox.

func (*Client) GetServicesByName

func (client *Client) GetServicesByName(name string) ([]*Service, error)

GetServicesByName returns a list of all services that exists in Netbox based on the service's name.

func (*Client) GetVM

func (client *Client) GetVM(id uint64) (*Device, error)

GetVM returns information about a VM gathered from Netbox. When error is not nil, the request failed and error gives further details what went wrong. VM might point to an invalid address at that point and must not be used whenever an error has been returned. When no vm with the given ID has been found, Device as well as error are nil.

func (*Client) GetVMs

func (client *Client) GetVMs() ([]*Device, error)

GetVMs returns a list of all VMs.

func (*Client) GetVMsByTag

func (client *Client) GetVMsByTag(tag string) ([]*Device, error)

GetVMsByTag returns a list of all vms with a given tag.

func (*Client) GetVirtualInterface

func (client *Client) GetVirtualInterface(id uint64) (*Interface, error)

GetVirtualInterface returns the virtual interface identified by id.

func (*Client) GetVirtualInterfaceIPs

func (client *Client) GetVirtualInterfaceIPs(id uint64) ([]*IP, error)

GetVirtualInterfaceIPs returns a list of all IPs associated with a given virtual interface id.

func (*Client) GetVirtualInterfacesByTag

func (client *Client) GetVirtualInterfacesByTag(tag string) ([]*Interface, error)

GetVirtualInterfacesByTag returns a list of all virtual interfaces having a specific tag set in Netbox.

func (*Client) HTTPTracing

func (client *Client) HTTPTracing(val bool)

HTTPTracing enables or disables HTTP tracing. When enabled, the Logger's Tracef function is called and contains all HTTP request and response headers and payload as well as timing information. Use with care, this will expose secrets in plain text and affects performance.

func (*Client) SetLogger

func (client *Client) SetLogger(logger Logger)

SetLogger updates the Logger interface used by this Client for sending log messages. NOTE: there is no check in place that validates the correctness of the interface. Logging messages might cause panics when a specific interface method is not defined. Make sure all methods exist for an instance of Logger.

func (*Client) VerifyConnectivity

func (client *Client) VerifyConnectivity() error

VerifyConnectivity checks connectivity towards the netbox target machine. It also checks for validity of the API token. If connection and token are okay, nil is returned.

type ClientIface

type ClientIface interface {
	prometheus.Collector

	// GetDevice queries Netbox for a specific device, identified by its nummeric ID. An error is returned when the API
	// call failed. *Device and error may be nil when a device of the ID doesn't exist.
	GetDevice(uint64) (*Device, error)

	// GetDevices returns a list of all devices.
	GetDevices() ([]*Device, error)

	// GetDevicesByTag returns a list of all devices with a given tag.
	GetDevicesByTag(string) ([]*Device, error)

	// GetInterface returns a single interface identified by id.
	GetInterface(uint64) (*Interface, error)
	// GetInterfacesByTag returns a list of all interfaces having a specific tag set in Netbox.
	GetInterfacesByTag(string) ([]*Interface, error)

	// GetVirtualInterface returns a single VM interface identified by id.
	GetVirtualInterface(uint64) (*Interface, error)
	// GetVirtualInterfacesByTag returns a list of all VM interfaces having a specific tag set in Netbox.
	GetVirtualInterfacesByTag(string) ([]*Interface, error)

	// GetIPsByAddress searches Netbox for an IP object based on an address string given. Address MUST NOT be a cidr. An
	// error is returned when the API call failed. *IP and error may be nil when no ip matches the given address.
	GetIPsByAddress(string) ([]*IP, error)

	// GetInterfaceIPs returns a list of all IPs associated with a given interface id.
	GetInterfaceIPs(uint64) ([]*IP, error)
	// GetVirtualInterfaceIPs returns a list of all IPs associated with a given virtual interface id.
	GetVirtualInterfaceIPs(uint64) ([]*IP, error)

	// GetServices returns a list of all services that exists in Netbox.
	GetServices() ([]*Service, error)

	// GetServicesByName returns a list of all services that exists in Netbox based on the service's name.
	GetServicesByName(string) ([]*Service, error)

	// GetVM returns a device/vm identified by id.
	GetVM(uint64) (*Device, error)

	// GetVMs returns a list of all VMs.
	GetVMs() ([]*Device, error)

	// GetVMsByTag returns a list of all vms with a given tag.
	GetVMsByTag(string) ([]*Device, error)

	// SetLogger updates the instance of ClientIface with a new Logger implementation.
	SetLogger(Logger)
	// HTTPTracing allows for enabling/disabling http request tracing.
	HTTPTracing(bool)
	// Copy creates an identical copy of the Netbox client.
	Copy() ClientIface
	// VerifyConnectivity tries to connect to the Netbox API, read data from it and checks if this was successful. It
	// tries to differentiate errors and return ErrInvalidToken when connectivity was okay but Netbox refused to comply
	// because the token is not valid (no such token, missing permissions, etc).
	VerifyConnectivity() error
	// contains filtered or unexported methods
}

ClientIface defines function for interacting with the Netbox API.

type CustomField

type CustomField struct {
	Datatype string
	Value    interface{}
}

CustomField describes a single Netbox custom field's data. Fields are exported to allow for mocking.

func (*CustomField) AsBool

func (cf *CustomField) AsBool() (bool, error)

AsBool takes a given CustomField and tries to returns it's value as bool. If the underlying datatype doesn't support being returned as bool, an error is returned.

func (*CustomField) AsFloat

func (cf *CustomField) AsFloat() (float64, error)

AsFloat takes a given CustomField and tries to returns it's value as int64. If the underlying datatype doesn't support being returned as float64, an error is returned.

func (*CustomField) AsString

func (cf *CustomField) AsString() (string, error)

AsString takes a given CustomField and tries to returns it's value as string. If the underlying datatype doesn't support being returned as string, an error is returned.

type CustomFieldMap

type CustomFieldMap interface {
	// GetEntry returns a pointer to the CustomField identified by name. If no CustomField of that name exists, nil is
	// returned.
	GetEntry(string) *CustomField
	// GetAllEntries iterates over all CustomFields and calls the callback function with the field's name and a pointer to
	// the CustomField as arguments.
	GetAllEntries(func(string, *CustomField))
}

CustomFieldMap contains custom fields defined in Netbox associated with an entity (like device, interface, etc). It is used to access those custom fields.

type Device

type Device struct {
	ID           uint64 `json:"-"`
	IDString     string `json:"id"`
	Name         string `json:"name"`
	PrimaryIP4   *IP    `json:"primary_ip4"`
	PrimaryIP6   *IP    `json:"primary_ip6"`
	CustomFields CFMap  `json:"custom_fields"`
	Rack         Name   `json:"rack"`
	Site         Name   `json:"site"`
	Role         Name   `json:"role"`
	Tenant       Name   `json:"tenant"`
	Platform     Name   `json:"platform"`
	SerialNumber string `json:"serial"`
	AssetTag     string `json:"asset_tag"`
	Status       string `json:"status"`
	Tags         []Name `json:"tags"`
	// contains filtered or unexported fields
}

Device describes a subset of details of a Netbox device.

func (*Device) IsVirtual

func (d *Device) IsVirtual() bool

IsVirtual returns true if the device represents a virtual machine.

type IP

type IP struct {
	ID       uint64 `json:"-"`
	IDString string `json:"id"`
	Address  string `json:"address"`
	Status   string `json:"status"`
	VRF      *VRF   `json:"vrf"`
}

IP describes a subset of details of a Netbox ip.

func (*IP) Family

func (ip *IP) Family() int

Family returns the decimal number of the version that this IP represents.

func (*IP) ToAddr

func (ip *IP) ToAddr() string

ToAddr converts a given IP struct to a single IP (i.e. converting cidr to address).

type Interface

type Interface struct {
	ID           uint64  `json:"-"`
	IDString     string  `json:"id"`
	Name         string  `json:"name"`
	Enabled      bool    `json:"enabled"`
	CustomFields CFMap   `json:"custom_fields"`
	Device       *Device `json:"device"`
	Tags         []Name  `json:"tags"`
	// contains filtered or unexported fields
}

Interface describes a subset of details about a Netbox interface.

type Logger

type Logger interface {
	Infof(format string, val ...interface{})
	Errorf(format string, val ...interface{})
	Debugf(format string, val ...interface{})
	Tracef(format string, val ...interface{})
}

Logger implements log related methods to forward messages to the appropriate recipient.

type Name

type Name struct {
	Name string `json:"name"`
}

Name is a generic structure that is often used to define things like site, rack, etc.

type Service

type Service struct {
	ID           uint64  `json:"-"`
	IDString     string  `json:"id"`
	Name         string  `json:"name"`
	Device       *Device `json:"device"`
	VM           *Device `json:"virtual_machine"`
	Ports        []int   `json:"ports"`
	IPAddresses  []*IP   `json:"ipaddresses"`
	Protocol     string  `json:"protocol"`
	CustomFields CFMap   `json:"custom_fields"`
}

Service describes a subset of details of a netbox service

type VRF

type VRF struct {
	ID       uint64 `json:"-"`
	IDString string `json:"id"`
	Name     string `json:"name"`
}

VRF describes a subset of details of a Netbox vrf.

type Value

type Value struct {
	Value string `json:"value"`
}

Value is a generic structure that is often used to define a label and value of some kind (think interface type, etc)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL