| 1 | package parser |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/czerwonk/bird_exporter/protocol" |
| 11 | ) |
| 12 | |
| 13 | type ospfRegex struct { |
| 14 | area *regexp.Regexp |
| 15 | counters *regexp.Regexp |
| 16 | } |
| 17 | |
| 18 | type ospfContext struct { |
| 19 | line string |
| 20 | areas []*protocol.OSPFArea |
| 21 | current *protocol.OSPFArea |
| 22 | } |
| 23 | |
| 24 | func init() { |
| 25 | ospf = &ospfRegex{ |
| 26 | area: regexp.MustCompile("Area: [^\\s]+ \\(([^\\s]+)\\)"), |
| 27 | counters: regexp.MustCompile("Number of ([^:]+):\\s*(\\d+)"), |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | var ospf *ospfRegex |
| 32 | |
| 33 | func ParseOSPF(data []byte) []*protocol.OSPFArea { |
| 34 | reader := bytes.NewReader(data) |
| 35 | scanner := bufio.NewScanner(reader) |
| 36 | |
| 37 | c := &ospfContext{ |
| 38 | areas: make([]*protocol.OSPFArea, 0), |
| 39 | } |
| 40 | |
| 41 | for scanner.Scan() { |
| 42 | c.line = strings.Trim(scanner.Text(), " ") |
| 43 | parseLineForOspfArea(c) |
| 44 | parseLineForOspfCounters(c) |
| 45 | } |
| 46 | |
| 47 | return c.areas |
| 48 | } |
| 49 | |
| 50 | func parseLineForOspfArea(c *ospfContext) { |
| 51 | m := ospf.area.FindStringSubmatch(c.line) |
| 52 | if m == nil { |
| 53 | return |
| 54 | } |
| 55 | |
| 56 | a := &protocol.OSPFArea{Name: m[1]} |
| 57 | c.current = a |
| 58 | c.areas = append(c.areas, a) |
| 59 | } |
| 60 | |
| 61 | func parseLineForOspfCounters(c *ospfContext) { |
| 62 | if c.current == nil { |
| 63 | return |
| 64 | } |
| 65 | |
| 66 | m := ospf.counters.FindStringSubmatch(c.line) |
| 67 | if m == nil { |
| 68 | return |
| 69 | } |
| 70 | |
| 71 | name := m[1] |
| 72 | value := parseInt(m[2]) |
| 73 | |
| 74 | if name == "interfaces" { |
| 75 | c.current.InterfaceCount = value |
| 76 | } |
| 77 | |
| 78 | if name == "neighbors" { |
| 79 | c.current.NeighborCount = value |
| 80 | } |
| 81 | |
| 82 | if name == "adjacent neighbors" { |
| 83 | c.current.NeighborAdjacentCount = value |
| 84 | } |
| 85 | } |