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
- Variables
- type CFMap
- type Client
- func (client *Client) Collect(ch chan<- prometheus.Metric)
- func (client *Client) Copy() ClientIface
- func (client *Client) Describe(ch chan<- *prometheus.Desc)
- func (client *Client) GetDevice(id uint64) (*Device, error)
- func (client *Client) GetDevices() ([]*Device, error)
- func (client *Client) GetDevicesByTag(tag string) ([]*Device, error)
- func (client *Client) GetIPsByAddress(ip string) ([]*IP, error)
- func (client *Client) GetInterface(id uint64) (*Interface, error)
- func (client *Client) GetInterfaceIPs(id uint64) ([]*IP, error)
- func (client *Client) GetInterfacesByTag(tag string) ([]*Interface, error)
- func (client *Client) GetServices() ([]*Service, error)
- func (client *Client) GetServicesByName(name string) ([]*Service, error)
- func (client *Client) GetVM(id uint64) (*Device, error)
- func (client *Client) GetVMs() ([]*Device, error)
- func (client *Client) GetVMsByTag(tag string) ([]*Device, error)
- func (client *Client) GetVirtualInterface(id uint64) (*Interface, error)
- func (client *Client) GetVirtualInterfaceIPs(id uint64) ([]*IP, error)
- func (client *Client) GetVirtualInterfacesByTag(tag string) ([]*Interface, error)
- func (client *Client) HTTPTracing(val bool)
- func (client *Client) SetLogger(logger Logger)
- func (client *Client) VerifyConnectivity() error
- type ClientIface
- type CustomField
- type CustomFieldMap
- type Device
- type IP
- type Interface
- type Logger
- type Name
- type Service
- type VRF
- type Value
Constants ¶
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.
const ( CustomFieldText string = "text" CustomFieldNumber string = "integer" CustomFieldBool string = "boolean" )
Possible custom field value types.
const SubsystemName string = "netbox_api"
SubsystemName is used for Prometheus metrics subsystem name.
Variables ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
GetDevices returns a list of all devices.
func (*Client) GetDevicesByTag ¶
GetDevicesByTag returns a list of all devices with a given tag.
func (*Client) GetIPsByAddress ¶
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 ¶
GetInterface returns the device interface identified by id.
func (*Client) GetInterfaceIPs ¶
GetInterfaceIPs returns a list of all IPs associated with a given dcim interface id.
func (*Client) GetInterfacesByTag ¶
GetInterfacesByTag returns a list of all device interfaces having a specific tag set in Netbox.
func (*Client) GetServices ¶
GetServices returns a list of all services that exists in Netbox.
func (*Client) GetServicesByName ¶
GetServicesByName returns a list of all services that exists in Netbox based on the service's name.
func (*Client) GetVM ¶
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) GetVMsByTag ¶
GetVMsByTag returns a list of all vms with a given tag.
func (*Client) GetVirtualInterface ¶
GetVirtualInterface returns the virtual interface identified by id.
func (*Client) GetVirtualInterfaceIPs ¶
GetVirtualInterfaceIPs returns a list of all IPs associated with a given virtual interface id.
func (*Client) GetVirtualInterfacesByTag ¶
GetVirtualInterfacesByTag returns a list of all virtual interfaces having a specific tag set in Netbox.
func (*Client) HTTPTracing ¶
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 ¶
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 ¶
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.
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.
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