forked from open-falcon/falcon-plus
/
computer.go
69 lines (57 loc) · 1.3 KB
/
computer.go
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
package cron
import (
"errors"
"regexp"
"strconv"
)
func compute(operands []string, operators []string, computeMode string, hostname string, valMap map[string]float64) (val float64, err error) {
count := len(operands)
if count == 0 {
return val, errors.New("counter not found")
}
vals := queryOperands(operands, hostname, valMap)
if len(vals) != count {
return val, errors.New("value invalid")
}
sum := vals[0]
for i, v := range vals[1:] {
if operators[i] == "+" {
sum += v
} else {
sum -= v
}
}
if computeMode != "" {
if compareSum(sum, computeMode) {
val = 1
}
} else {
val = sum
}
return val, nil
}
func compareSum(sum float64, computeMode string) bool {
regMatch, _ := regexp.Compile(`([><=]+)([\d\.]+)`)
match := regMatch.FindStringSubmatch(computeMode)
mode := match[1]
val, _ := strconv.ParseFloat(match[2], 64)
switch {
case mode == ">" && sum > val:
case mode == "<" && sum < val:
case mode == "=" && sum == val:
case mode == ">=" && sum >= val:
case mode == "<=" && sum <= val:
default:
return false
}
return true
}
func queryOperands(counters []string, endpoint string, valMap map[string]float64) []float64 {
ret := []float64{}
for _, counter := range counters {
if v, ok := valMap[endpoint+counter]; ok {
ret = append(ret, v)
}
}
return ret
}