1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
|
package collector
import (
"encoding/json"
"fmt"
"log/slog"
"strconv"
"strings"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
ospfSubsystem = "ospf"
frrOSPFInstances = kingpin.Flag("collector.ospf.instances", "Comma-separated list of instance IDs if using multiple OSPF instances").Default("").String()
)
func init() {
registerCollector(ospfSubsystem, enabledByDefault, NewOSPFCollector)
}
type ospfCollector struct {
logger *slog.Logger
ospfIfaceDescriptions map[string]*prometheus.Desc
ospfDescriptions map[string]*prometheus.Desc
ospfNeighDescriptions map[string]*prometheus.Desc
ospfDataMaxAgeDescriptions map[string]*prometheus.Desc
instanceIDs []int
}
// NewOSPFCollector collects OSPF metrics, implemented as per the Collector interface.
func NewOSPFCollector(logger *slog.Logger) (Collector, error) {
var instanceIDs []int
if len(*frrOSPFInstances) > 0 {
// FRR Exporter does not support multi-instance when using `vtysh` to interface with FRR
// via the `--frr.vtysh` flag for the following reasons:
// * Invalid JSON is returned when OSPF commands are executed by `vtysh`. For example,
// `show ip ospf vrf all interface json` returns the concatenated JSON from each OSPF instance.
// * Vtysh does not support `vrf` and `instance` in the same commend. For example,
// `show ip ospf 1 vrf all interface json` is an invalid command.
if *vtyshEnable {
return nil, fmt.Errorf("cannot use --frr.vtysh with --collector.ospf.instances")
}
instances := strings.Split(*frrOSPFInstances, ",")
for _, id := range instances {
i, err := strconv.Atoi(id)
if err != nil {
return nil, fmt.Errorf("unable to parse instance ID %s: %w", id, err)
}
instanceIDs = append(instanceIDs, i)
}
}
return &ospfCollector{logger: logger, instanceIDs: instanceIDs, ospfIfaceDescriptions: getOSPFIfaceDesc(), ospfDescriptions: getOSPFDesc(), ospfNeighDescriptions: getOSPFNeighDesc(), ospfDataMaxAgeDescriptions: getOSPFDataMaxAgeDesc()}, nil
}
// Update satisfies Collector.
func (c *ospfCollector) Update(ch chan<- prometheus.Metric) error {
steps := []struct {
cmd string
desc map[string]*prometheus.Desc
processor func(chan<- prometheus.Metric, []byte, map[string]*prometheus.Desc, int) error
}{
{
cmd: "show ip ospf vrf all json",
desc: c.ospfDescriptions,
processor: processOSPF,
},
{
cmd: "show ip ospf vrf all interface json",
desc: c.ospfIfaceDescriptions,
processor: processOSPFInterface,
},
{
cmd: "show ip ospf vrf all neighbor json",
desc: c.ospfNeighDescriptions,
processor: processOSPFNeigh,
},
{
cmd: "show ip ospf vrf all database max-age json",
desc: c.ospfDataMaxAgeDescriptions,
processor: processOSPFDataMaxAge,
},
}
for _, s := range steps {
if err := c.update(ch, s.cmd, s.desc, s.processor); err != nil {
return err
}
}
return nil
}
func (c *ospfCollector) update(
ch chan<- prometheus.Metric,
cmd string,
descriptions map[string]*prometheus.Desc,
process func(chan<- prometheus.Metric, []byte, map[string]*prometheus.Desc, int) error,
) error {
if len(c.instanceIDs) > 0 {
for _, id := range c.instanceIDs {
jsonBytes, err := executeOSPFMultiInstanceCommand(cmd, id)
if err != nil {
return err
}
if err := process(ch, jsonBytes, descriptions, id); err != nil {
return cmdOutputProcessError(cmd, string(jsonBytes), err)
}
}
return nil
}
jsonBytes, err := executeOSPFCommand(cmd)
if err != nil {
return err
}
if err := process(ch, jsonBytes, descriptions, 0); err != nil {
return cmdOutputProcessError(cmd, string(jsonBytes), err)
}
return nil
}
func getOSPFIfaceDesc() map[string]*prometheus.Desc {
labels := []string{"vrf", "iface", "area"}
if len(*frrOSPFInstances) > 0 {
labels = append(labels, "instance")
}
return map[string]*prometheus.Desc{
"ospfIfaceNeigh": colPromDesc(ospfSubsystem, "neighbors", "Number of neighbors detected.", labels),
"ospfIfaceNeighAdj": colPromDesc(ospfSubsystem, "neighbor_adjacencies", "Number of neighbor adjacencies formed.", labels),
}
}
func getOSPFDesc() map[string]*prometheus.Desc {
routerLabels := []string{"vrf"}
areaLabels := []string{"vrf", "area"}
if len(*frrOSPFInstances) > 0 {
routerLabels = append(routerLabels, "instance")
areaLabels = append(areaLabels, "instance")
}
return map[string]*prometheus.Desc{
"ospfLsaExternalCounter": colPromDesc(ospfSubsystem, "lsa_external_counter", "Number of external LSAs.", routerLabels),
"ospfLsaAsOpaqueCounter": colPromDesc(ospfSubsystem, "lsa_as_opaque_counter", "Number of AS Opaque LSAs.", routerLabels),
"ospfAreaLsaNumber": colPromDesc(ospfSubsystem, "area_lsa_number", "Number of LSAs in the area.", areaLabels),
"ospfAreaLsaNetworkNumber": colPromDesc(ospfSubsystem, "area_lsa_network_number", "Number of network LSAs in the area.", areaLabels),
"ospfAreaLsaSummaryNumber": colPromDesc(ospfSubsystem, "area_lsa_summary_number", "Number of summary LSAs in the area.", areaLabels),
"ospfAreaLsaAsbrNumber": colPromDesc(ospfSubsystem, "area_lsa_asbr_number", "Number of ASBR LSAs in the area.", areaLabels),
"ospfAreaLsaNssaNumber": colPromDesc(ospfSubsystem, "area_lsa_nssa_number", "Number of NSSA LSAs in the area.", areaLabels),
}
}
func getOSPFNeighDesc() map[string]*prometheus.Desc {
var labels []string
if len(*frrOSPFInstances) > 0 {
labels = append(labels, "instance")
}
labels = append(labels, "vrf", "neighbor", "iface", "local_address", "remote_address")
return map[string]*prometheus.Desc{
"ospfNeighState": colPromDesc(ospfSubsystem, "neighbor_state", "OSPF neighbor state (1=Down, 2=Init, 3=2-Way, 4=ExStart, 5=Exchange, 6=Loading, 7=Full).", labels),
}
}
func getOSPFDataMaxAgeDesc() map[string]*prometheus.Desc {
var labels []string
if len(*frrOSPFInstances) > 0 {
labels = append(labels, "instance")
}
labels = append(labels, "vrf")
return map[string]*prometheus.Desc{
"ospfDataMaxAge": colPromDesc(ospfSubsystem, "data_ls_max_age", "Amount of link state max age entries.", labels),
}
}
func processOSPFInterface(ch chan<- prometheus.Metric, jsonOSPFInterface []byte, ospfDesc map[string]*prometheus.Desc, instanceID int) error {
// Unfortunately, the 'show ip ospf vrf all interface json' JSON output is poorly structured. Instead
// of all interfaces being in a list, each interface is added as a key on the same level of vrfName and
// vrfId. As such, we have to loop through each key and apply logic to determine whether the key is an
// interface.
var jsonMap map[string]json.RawMessage
if err := json.Unmarshal(jsonOSPFInterface, &jsonMap); err != nil {
return fmt.Errorf("cannot unmarshal ospf interface json: %s", err)
}
for vrfName, vrfData := range jsonMap {
var _tempvrfInstance map[string]json.RawMessage
switch vrfName {
case "ospfInstance":
// Do nothing
default:
if err := json.Unmarshal(vrfData, &_tempvrfInstance); err != nil {
return fmt.Errorf("cannot unmarshal VRF instance json: %s", err)
}
}
for ospfInstanceKey, ospfInstanceVal := range _tempvrfInstance {
switch ospfInstanceKey {
case "vrfName", "vrfId":
// Do nothing as we do not need the value of these keys.
case "interfaces":
var _tempInterfaceInstance map[string]json.RawMessage
if err := json.Unmarshal(ospfInstanceVal, &_tempInterfaceInstance); err != nil {
return fmt.Errorf("cannot unmarshal VRF instance json: %s", err)
}
for interfaceKey, interfaceValue := range _tempInterfaceInstance {
var newIface ospfIface
if err := json.Unmarshal(interfaceValue, &newIface); err != nil {
return fmt.Errorf("cannot unmarshal interface json: %s", err)
}
if !newIface.TimerPassiveIface {
// The labels are "vrf", "newIface", "area"
labels := []string{strings.ToLower(vrfName), interfaceKey, newIface.Area}
ospfIfaceMetrics(ch, newIface, labels, ospfDesc, instanceID)
}
}
default:
// All other keys are interfaces.
var iface ospfIface
if err := json.Unmarshal(ospfInstanceVal, &iface); err != nil {
return fmt.Errorf("cannot unmarshal interface json: %s", err)
}
if !iface.TimerPassiveIface {
// The labels are "vrf", "iface", "area"
labels := []string{strings.ToLower(vrfName), ospfInstanceKey, iface.Area}
ospfIfaceMetrics(ch, iface, labels, ospfDesc, instanceID)
}
}
}
}
return nil
}
func ospfIfaceMetrics(ch chan<- prometheus.Metric, iface ospfIface, labels []string, ospfDesc map[string]*prometheus.Desc, instanceID int) {
if instanceID != 0 {
labels = append(labels, strconv.Itoa(instanceID))
}
newGauge(ch, ospfDesc["ospfIfaceNeigh"], float64(iface.NbrCount), labels...)
newGauge(ch, ospfDesc["ospfIfaceNeighAdj"], float64(iface.NbrAdjacentCount), labels...)
}
type ospfIface struct {
NbrCount uint32
NbrAdjacentCount uint32
Area string
TimerPassiveIface bool
}
func processOSPF(ch chan<- prometheus.Metric, jsonOSPF []byte, ospfDesc map[string]*prometheus.Desc, instanceID int) error {
var all map[string]ospfInstance
if err := json.Unmarshal(jsonOSPF, &all); err != nil {
return fmt.Errorf("cannot unmarshal ospf json: %w", err)
}
for vrfName, vrfData := range all {
ospfMetrics(ch, vrfData, vrfName, ospfDesc, instanceID)
}
return nil
}
func ospfMetrics(ch chan<- prometheus.Metric, ospfData ospfInstance, vrfName string, ospfDesc map[string]*prometheus.Desc, instanceID int) {
routerLabels := []string{strings.ToLower(vrfName)}
if instanceID != 0 {
routerLabels = append(routerLabels, strconv.Itoa(instanceID))
}
newGauge(ch, ospfDesc["ospfLsaExternalCounter"], float64(ospfData.LsaExternalCounter), routerLabels...)
newGauge(ch, ospfDesc["ospfLsaAsOpaqueCounter"], float64(ospfData.LsaAsopaqueCounter), routerLabels...)
for areaName, area := range ospfData.Areas {
areaLabels := []string{strings.ToLower(vrfName), areaName}
if instanceID != 0 {
areaLabels = append(areaLabels, strconv.Itoa(instanceID))
}
newGauge(ch, ospfDesc["ospfAreaLsaNumber"], float64(area.LsaNumber), areaLabels...)
newGauge(ch, ospfDesc["ospfAreaLsaNetworkNumber"], float64(area.LsaNetworkNumber), areaLabels...)
newGauge(ch, ospfDesc["ospfAreaLsaSummaryNumber"], float64(area.LsaSummaryNumber), areaLabels...)
newGauge(ch, ospfDesc["ospfAreaLsaAsbrNumber"], float64(area.LsaAsbrNumber), areaLabels...)
newGauge(ch, ospfDesc["ospfAreaLsaNssaNumber"], float64(area.LsaNssaNumber), areaLabels...)
}
}
type ospfInstance struct {
LsaExternalCounter uint32
LsaAsopaqueCounter uint32
Areas map[string]ospfArea
}
type ospfArea struct {
LsaNumber uint32
LsaNetworkNumber uint32
LsaSummaryNumber uint32
LsaAsbrNumber uint32
LsaNssaNumber uint32
}
func processOSPFNeigh(ch chan<- prometheus.Metric, jsonOSPFNeigh []byte, ospfDesc map[string]*prometheus.Desc, instanceID int) error {
var vrfNeighs map[string]vrfNeighbors
if err := json.Unmarshal(jsonOSPFNeigh, &vrfNeighs); err != nil {
return fmt.Errorf("cannot unmarshal ospf neighbor json: %w", err)
}
for vrfName, vrfData := range vrfNeighs {
for neighborName, neighbors := range vrfData.Neighbors {
ospfNeighMetrics(ch, neighborName, neighbors, vrfName, ospfDesc, instanceID)
}
}
return nil
}
func ospfNeighMetrics(ch chan<- prometheus.Metric, neighborName string, neighbors []ospfNeighbor, vrfName string, ospfDesc map[string]*prometheus.Desc, instanceID int) {
var labels []string
if instanceID != 0 {
labels = append(labels, strconv.Itoa(instanceID))
}
labels = append(labels, strings.ToLower(vrfName), neighborName)
for _, neighbor := range neighbors {
var state float64
switch neighbor.State {
case "Down":
state = 1
case "Init":
state = 2
case "2-Way":
state = 3
case "ExStart":
state = 4
case "Exchange":
state = 5
case "Loading":
state = 6
case "Full":
state = 7
default:
continue
}
newGauge(ch, ospfDesc["ospfNeighState"], state, append(labels, neighbor.IfaceName, neighbor.LocalAddress, neighbor.RemoteAddress)...)
}
}
type vrfNeighbors struct {
VRFName string
Neighbors map[string][]ospfNeighbor
}
func GetOSPFState(nbrState, state string) string {
if nbrState != "" {
return nbrState
}
return state
}
type ospfNeighbor struct {
State string `json:"state"`
NbrState string `json:"nbrState"`
IfaceName string `json:"ifaceName"`
LocalAddress string `json:"localAddress"`
RemoteAddress string `json:"address"`
}
func (n *ospfNeighbor) UnmarshalJSON(data []byte) error {
var temp struct {
NbrState string `json:"nbrState"`
State string `json:"state"`
IfaceName string `json:"ifaceName"`
LocalAddr string `json:"localAddress"`
RemoteAddr string `json:"address"`
}
if err := json.Unmarshal(data, &temp); err != nil {
return fmt.Errorf("cannot unmarshal ospf neighbor json: %w", err)
}
iface := strings.Split(temp.IfaceName, ":")
if len(iface) == 2 {
n.IfaceName = iface[0]
n.LocalAddress = iface[1]
} else {
return fmt.Errorf("cannot unmarshal ospf neighbor iface: %s", iface)
}
state := strings.Split(GetOSPFState(temp.NbrState, temp.State), "/")
if len(state) > 0 {
n.State = state[0]
} else {
return fmt.Errorf("cannot unmarshal ospf neighbor state: %s", state)
}
n.RemoteAddress = temp.RemoteAddr
return nil
}
func processOSPFDataMaxAge(ch chan<- prometheus.Metric, jsonOSPFMaxAge []byte, ospfDesc map[string]*prometheus.Desc, instanceID int) error {
var all map[string]ospfDataMaxAge
if err := json.Unmarshal(jsonOSPFMaxAge, &all); err != nil {
return fmt.Errorf("cannot unmarshal ospf max age json: %w", err)
}
for vrfName, vrfData := range all {
ospfDataMaxAgeMetrics(ch, vrfData, vrfName, ospfDesc, instanceID)
}
return nil
}
func ospfDataMaxAgeMetrics(ch chan<- prometheus.Metric, ospfData ospfDataMaxAge, vrfName string, ospfDesc map[string]*prometheus.Desc, instanceID int) {
labels := []string{strings.ToLower(vrfName)}
if instanceID != 0 {
labels = append(labels, strconv.Itoa(instanceID))
}
newGauge(ch, ospfDesc["ospfDataMaxAge"], float64(len(ospfData.MaxAgeLinkStates)), labels...)
}
type ospfDataMaxAge struct {
VRFName string
MaxAgeLinkStates map[string]struct{}
}
|