-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
76 lines (65 loc) · 2.2 KB
/
validator.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
70
71
72
73
74
75
76
package alert
import (
"fmt"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/management.cattle.io/v3"
v3client "github.com/rancher/types/client/management/v3"
)
const monitoringEnabled = "MonitoringEnabled"
func ClusterAlertRuleValidator(resquest *types.APIContext, schema *types.Schema, data map[string]interface{}) error {
var clusterID string
if resquest.ID != "" {
clusterID, _ = ref.Parse(resquest.ID)
} else {
if cid := data["clusterId"]; cid != nil {
clusterID = cid.(string)
} else {
return fmt.Errorf("cluster id is empty")
}
}
var spec v3.ClusterAlertRuleSpec
if err := convert.ToObj(data, &spec); err != nil {
return httperror.NewAPIError(httperror.InvalidBodyContent, fmt.Sprintf("%v", err))
}
if spec.MetricRule != nil {
var cluster v3client.Cluster
if err := access.ByID(resquest, resquest.Version, v3client.ClusterType, clusterID, &cluster); err != nil {
return err
}
if cluster.Conditions != nil {
for _, v := range cluster.Conditions {
if v.Type == monitoringEnabled && v.Status == "True" {
return nil
}
}
}
return fmt.Errorf("if you want to use metric alert, need to enable monitoring for cluster %s", clusterID)
}
return nil
}
func ProjectAlertRuleValidator(resquest *types.APIContext, schema *types.Schema, data map[string]interface{}) error {
projectID := data["projectId"].(string)
var spec v3.ProjectAlertRuleSpec
if err := convert.ToObj(data, &spec); err != nil {
return httperror.NewAPIError(httperror.InvalidBodyContent, fmt.Sprintf("%v", err))
}
if spec.MetricRule != nil {
project := &v3client.Project{}
if err := access.ByID(resquest, resquest.Version, v3client.ProjectType, projectID, project); err != nil {
return fmt.Errorf("access project by id failed, %v", err)
}
if project.Conditions != nil {
for _, v := range project.Conditions {
if v.Type == monitoringEnabled && v.Status == "True" {
return nil
}
}
}
return fmt.Errorf("if you want to use metric alert, need to enable monitoring for project %s", projectID)
}
return nil
}