fix uptime regex and lazy coding for #34

This commit is contained in:
Steve Brunton
2019-02-21 22:34:39 -05:00
parent 9f22fc0232
commit 67c0848f6a
2 changed files with 21 additions and 13 deletions

View File

@@ -1,6 +1,7 @@
package collector package collector
import ( import (
"fmt"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@@ -15,7 +16,7 @@ var uptimeRegex *regexp.Regexp
var uptimeParts [5]time.Duration var uptimeParts [5]time.Duration
func init() { func init() {
uptimeRegex = regexp.MustCompile(`(?:(\d*)w)?(?:(\d*)d)?(?:(\d*)h)?(?:(\d*)m)?(?:(\d*)s)`) uptimeRegex = regexp.MustCompile(`(?:(\d*)w)?(?:(\d*)d)?(?:(\d*)h)?(?:(\d*)m)?(?:(\d*)s)?`)
uptimeParts = [5]time.Duration{time.Hour * 168, time.Hour * 24, time.Hour, time.Minute, time.Second} uptimeParts = [5]time.Duration{time.Hour * 168, time.Hour * 24, time.Hour, time.Minute, time.Second}
} }
@@ -105,7 +106,13 @@ func (c *resourceCollector) collectMetricForProperty(property string, re *proto.
func parseUptime(uptime string) (float64, error) { func parseUptime(uptime string) (float64, error) {
var u time.Duration var u time.Duration
for i, match := range uptimeRegex.FindAllStringSubmatch(uptime, -1)[0] { reMatch := uptimeRegex.FindAllStringSubmatch(uptime, -1)
// should get one and only one match back on the regex
if len(reMatch) != 1 {
return 0, fmt.Errorf("invalid uptime value sent to regex")
} else {
for i, match := range reMatch[0] {
if match != "" && i != 0 { if match != "" && i != 0 {
v, err := strconv.Atoi(match) v, err := strconv.Atoi(match)
if err != nil { if err != nil {
@@ -119,6 +126,6 @@ func parseUptime(uptime string) (float64, error) {
u += time.Duration(v) * uptimeParts[i-1] u += time.Duration(v) * uptimeParts[i-1]
} }
} }
}
return u.Seconds(), nil return u.Seconds(), nil
} }

View File

@@ -13,6 +13,7 @@ func TestParseUptime(t *testing.T) {
{"3d3h42m53s", 272573}, {"3d3h42m53s", 272573},
{"15w3d3h42m53s", 9344573}, {"15w3d3h42m53s", 9344573},
{"42m53s", 2573}, {"42m53s", 2573},
{"7w6d9h34m", 4786440},
} }
for _, uptime := range uptimes { for _, uptime := range uptimes {