package service import ( "fmt" monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" "github.com/spf13/cast" "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/entity" "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/response" "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf" "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/constant" "gitlab.wodcloud.com/smart-operation/so-operation-api/src/service/k8s" "k8s.io/apimachinery/pkg/util/intstr" "strings" ) type PrometheusRuleSvc struct { User entity.SystemUserInfo } func (p *PrometheusRuleSvc) Create(data response.AlertRulesItem) { header := make(map[string]string) header["Authorization"] = "Bearer " + conf.Options.KubernetesToken svc := k8s.PrometheusRule{Header: header} pr := monitoringv1.PrometheusRule{} prometheusRuleName := k8s.GetPrometheusRuleName(data.Id) pr.Name = prometheusRuleName pr.Namespace = k8s.Namespace pr.Labels = k8s.AlertDefLabels group := monitoringv1.RuleGroup{} groupInterval := monitoringv1.Duration(fmt.Sprintf("%d%s", data.CheckPeriod, "m")) group.Interval = &groupInterval ruleFor := monitoringv1.Duration(fmt.Sprintf("%d%s", data.Duration, data.DurationUnit)) // [{"variable_name":"$pod$","metric_name":"http_requests_total","metric_label":"pod","chinese_name":"demoString","is_required":true,"is_linked":true,"value":"LeaseGrant","compare":"="}] // [{"thresholds_max":100,"thresholds_min":0,"risk_level":4}] group.Name = k8s.GetPrometheusRuleGroupName(data.MetricConfigId, string(*group.Interval)) for _, v := range data.AlertRange { item := fmt.Sprintf("%s%s%s", v.MetricLabel, v.Compare, v.Value) // pod=LeaseGrant data.Expr = strings.ReplaceAll(data.Expr, v.VariableName, item) } for _, v := range data.AlertCondition { rule := monitoringv1.Rule{ Alert: data.MetricConfigName, For: &ruleFor, Labels: map[string]string{ "severity": "warning", "risk_level": cast.ToString(v.RiskLevel), "risk_level_name": constant.RiskLeveText(v.RiskLevel), "source": "so-operation-api", "alert_rules_id": data.MetricConfigId, }, Annotations: map[string]string{ "value": "{{ $value }}", "summary": "概述", "description": "描述", }, } expr := fmt.Sprintf("%d <= %s <=%d", v.ThresholdsMin, data.Expr, v.ThresholdsMax) rule.Expr = intstr.FromString(expr) group.Rules = append(group.Rules, rule) } _ = svc }