package k8s import ( "encoding/json" "fmt" "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf" "gitlab.wodcloud.com/smart-operation/so-operation-api/src/util" "strings" "sync" monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" ) var ( promOnce sync.Once prometheusRuleName string alertOnce sync.Once alertDefLabels map[string]string ) func GetPrometheusRuleCRDName() string { promOnce.Do(func() { url := conf.Options.MonitorApiVersion // 请确保 conf 和其他相关配置可用 parts := strings.Split(url, "/") if len(parts) == 0 || parts[0] == "" { prometheusRuleName = "prometheusrules.monitoring.beagle.io" } else { prometheusRuleName = fmt.Sprintf("prometheusrules.%s", parts[0]) } }) return prometheusRuleName } func GetAlertDefLabels() map[string]string { alertOnce.Do(func() { alertDefLabels = make(map[string]string) err := json.Unmarshal([]byte(conf.Options.MonitorMatchLabelsStr), &alertDefLabels) if err != nil { fmt.Println("Error parsing JSON:", err) } }) return alertDefLabels } // GetPrometheusRuleId 获取规则CRD名称 func GetPrometheusRuleId(alertPolicyId string) string { return fmt.Sprintf("%s-%s", conf.Options.PrometheusRuleNamePrefix, alertPolicyId) } // GetPrometheusRuleGroupName 获取规则组名称 func GetPrometheusRuleGroupName(alertName string, groupInterval string) string { return fmt.Sprintf("%s-group-%s", alertName, groupInterval) } type PrometheusRule struct { Header map[string]string } func (p PrometheusRule) Create(pRule *monitoringv1.PrometheusRule) error { k8sSvc := K8sSvc{Header: p.Header} c := &Content{Kind: "PrometheusRule", ApiVersion: conf.Options.MonitorApiVersion, Metadata: pRule.ObjectMeta, Spec: pRule.Spec} _, err := k8sSvc.SendFile(c) return err } func (p PrometheusRule) Delete(namespace string, name string) error { delUrl := fmt.Sprintf("%s/kubernetes/api/v1/_raw/%s/namespace/%s/name/%s", conf.Options.AweRestURL, GetPrometheusRuleCRDName(), namespace, name) _, err := util.ProxySendRes("DELETE", delUrl, "", p.Header) return err } func (p PrometheusRule) Update(pRule *monitoringv1.PrometheusRule) error { updateUrl := fmt.Sprintf("%s/kubernetes/api/v1/_raw/%s/namespace/%s/name/%s", conf.Options.AweRestURL, GetPrometheusRuleCRDName(), pRule.Namespace, pRule.Name) body, _ := json.Marshal(pRule) p.Header["Content-Type"] = "application/json" _, err := util.ProxySendRes("PUT", updateUrl, string(body), p.Header) return err } func (p PrometheusRule) Get(namespace string, name string) (obj *monitoringv1.PrometheusRule, err error) { getUrl := fmt.Sprintf("%s/kubernetes/api/v1/_raw/%s/namespace/%s/name/%s", conf.Options.AweRestURL, GetPrometheusRuleCRDName(), namespace, name) res, err := util.ProxySendRes("GET", getUrl, "", p.Header) if err != nil { return } err = json.Unmarshal(res, &obj) return }