Skip to content

Commit

Permalink
fix uptime regex and lazy coding for #34
Browse files Browse the repository at this point in the history
  • Loading branch information
nshttpd committed Feb 22, 2019
1 parent 9f22fc0 commit 67c0848
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
33 changes: 20 additions & 13 deletions collector/resource_collector.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package collector

import (
"fmt"
"regexp"
"strconv"
"strings"
Expand All @@ -15,7 +16,7 @@ var uptimeRegex *regexp.Regexp
var uptimeParts [5]time.Duration

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}
}

Expand Down Expand Up @@ -105,20 +106,26 @@ func (c *resourceCollector) collectMetricForProperty(property string, re *proto.
func parseUptime(uptime string) (float64, error) {
var u time.Duration

for i, match := range uptimeRegex.FindAllStringSubmatch(uptime, -1)[0] {
if match != "" && i != 0 {
v, err := strconv.Atoi(match)
if err != nil {
log.WithFields(log.Fields{
"uptime": uptime,
"value": match,
"error": err,
}).Error("error parsing uptime field value")
return float64(0), err
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 {
v, err := strconv.Atoi(match)
if err != nil {
log.WithFields(log.Fields{
"uptime": uptime,
"value": match,
"error": err,
}).Error("error parsing uptime field value")
return float64(0), err
}
u += time.Duration(v) * uptimeParts[i-1]
}
u += time.Duration(v) * uptimeParts[i-1]
}
}

return u.Seconds(), nil
}
1 change: 1 addition & 0 deletions collector/resource_collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func TestParseUptime(t *testing.T) {
{"3d3h42m53s", 272573},
{"15w3d3h42m53s", 9344573},
{"42m53s", 2573},
{"7w6d9h34m", 4786440},
}

for _, uptime := range uptimes {
Expand Down

0 comments on commit 67c0848

Please sign in to comment.