| 1 | package parser |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "strings" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | type Status struct { |
| 10 | Version string |
| 11 | RouterID string |
| 12 | ServerTime time.Time |
| 13 | LastReboot time.Time |
| 14 | LastReconfig time.Time |
| 15 | DaemonUp bool |
| 16 | } |
| 17 | |
| 18 | var ( |
| 19 | reVersion = regexp.MustCompile(`BIRD (\S+)`) |
| 20 | reRouterID = regexp.MustCompile(`Router ID is (\S+)`) |
| 21 | reServerTime = regexp.MustCompile(`Current server time is (.+)`) |
| 22 | reReboot = regexp.MustCompile(`Last reboot on (.+)`) |
| 23 | reReconfig = regexp.MustCompile(`Last reconfiguration on (.+)`) |
| 24 | reDaemon = regexp.MustCompile(`Daemon is (.+)`) |
| 25 | timeLayout = "2006-01-02 15:04:05.000" // ref: https://pkg.go.dev/time#Parse |
| 26 | ) |
| 27 | |
| 28 | func ParseStatus(b []byte) *Status { |
| 29 | s := &Status{} |
| 30 | out := string(b) |
| 31 | |
| 32 | if m := reVersion.FindStringSubmatch(out); len(m) > 1 { |
| 33 | s.Version = m[1] |
| 34 | } |
| 35 | if m := reRouterID.FindStringSubmatch(out); len(m) > 1 { |
| 36 | s.RouterID = m[1] |
| 37 | } |
| 38 | if m := reServerTime.FindStringSubmatch(out); len(m) > 1 { |
| 39 | if t, err := time.Parse(timeLayout, strings.TrimSpace(m[1])); err == nil { |
| 40 | s.ServerTime = t |
| 41 | } |
| 42 | } |
| 43 | if m := reReboot.FindStringSubmatch(out); len(m) > 1 { |
| 44 | if t, err := time.Parse(timeLayout, strings.TrimSpace(m[1])); err == nil { |
| 45 | s.LastReboot = t |
| 46 | } |
| 47 | } |
| 48 | if m := reReconfig.FindStringSubmatch(out); len(m) > 1 { |
| 49 | if t, err := time.Parse(timeLayout, strings.TrimSpace(m[1])); err == nil { |
| 50 | s.LastReconfig = t |
| 51 | } |
| 52 | } |
| 53 | if m := reDaemon.FindStringSubmatch(out); len(m) > 1 { |
| 54 | s.DaemonUp = strings.Contains(m[1], "up") |
| 55 | } |
| 56 | |
| 57 | return s |
| 58 | } |