-
Notifications
You must be signed in to change notification settings - Fork 53
/
kube_state.go
62 lines (59 loc) · 1.52 KB
/
kube_state.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
package metrics
import (
"bytes"
"fmt"
"github.com/prometheus/common/model"
"github.com/rancher/opni/pkg/alerting/metrics/naming"
"github.com/rancher/opni/pkg/alerting/shared"
)
func NewKubeStateRule(
objType string,
objName string,
namespace string,
podState string,
forDuration string,
annotations map[string]string,
) (*AlertingRule, error) {
if objType == "" {
return nil, fmt.Errorf("kubernetes object type should not be empty")
}
if objName == "" {
return nil, fmt.Errorf("kubernetes objects cannot have an empty name")
}
var kubeMetricNameBuffer bytes.Buffer
err := naming.KubeObjMetricCreator.Execute(&kubeMetricNameBuffer, map[string]string{
"ObjType": objType,
})
if err != nil {
return nil, err
}
kubeMetricName := kubeMetricNameBuffer.String()
objectFilter := objType + fmt.Sprintf("= \"%s\"", objName)
validState := false
for _, state := range shared.KubeStates {
if state == podState {
validState = true
}
}
if !validState {
return nil, fmt.Errorf("invalid pod state provided %s", podState)
}
dur, err := model.ParseDuration(forDuration)
if err != nil {
return nil, err
}
//handle empty namespace
var namespaceFilter string
if namespace != "" {
namespaceFilter = "namespace=\"" + namespace + "\""
} else {
namespaceFilter = ""
}
return &AlertingRule{
Alert: "",
Expr: fmt.Sprintf("(%s{%s, %s, state=\"%s\"} > bool 0)", kubeMetricName, namespaceFilter, objectFilter, podState),
For: dur,
Labels: annotations,
Annotations: annotations,
}, nil
}