@@ -308,19 +308,52 @@ func (rt *Router) alertRuleAddByImportPromRule(c *gin.Context) {
308308 var f promRuleForm
309309 ginx .Dangerous (c .BindJSON (& f ))
310310
311+ // 首先尝试解析带 groups 的格式
311312 var pr struct {
312313 Groups []models.PromRuleGroup `yaml:"groups"`
313314 }
314315 err := yaml .Unmarshal ([]byte (f .Payload ), & pr )
315- if err != nil {
316- ginx .Bomb (http .StatusBadRequest , "invalid yaml format, please use the example format. err: %v" , err )
317- }
318316
319- if len (pr .Groups ) == 0 {
320- ginx .Bomb (http .StatusBadRequest , "input yaml is empty" )
317+ var groups []models.PromRuleGroup
318+
319+ if err != nil || len (pr .Groups ) == 0 {
320+ // 如果解析失败或没有 groups,尝试解析规则数组格式
321+ var rules []models.PromRule
322+ err = yaml .Unmarshal ([]byte (f .Payload ), & rules )
323+ if err != nil {
324+ // 最后尝试解析单个规则格式
325+ var singleRule models.PromRule
326+ err = yaml .Unmarshal ([]byte (f .Payload ), & singleRule )
327+ if err != nil {
328+ ginx .Bomb (http .StatusBadRequest , "invalid yaml format. err: %v" , err )
329+ }
330+
331+ // 验证单个规则是否有效
332+ if singleRule .Alert == "" && singleRule .Record == "" {
333+ ginx .Bomb (http .StatusBadRequest , "input yaml is empty or invalid" )
334+ }
335+
336+ rules = []models.PromRule {singleRule }
337+ }
338+
339+ // 验证规则数组是否为空
340+ if len (rules ) == 0 {
341+ ginx .Bomb (http .StatusBadRequest , "input yaml contains no rules" )
342+ }
343+
344+ // 将规则数组包装成 group
345+ groups = []models.PromRuleGroup {
346+ {
347+ Name : "imported_rules" ,
348+ Rules : rules ,
349+ },
350+ }
351+ } else {
352+ // 使用已解析的 groups
353+ groups = pr .Groups
321354 }
322355
323- lst := models .DealPromGroup (pr . Groups , f .DatasourceQueries , f .Disabled )
356+ lst := models .DealPromGroup (groups , f .DatasourceQueries , f .Disabled )
324357 username := c .MustGet ("username" ).(string )
325358 bgid := ginx .UrlParamInt64 (c , "id" )
326359 ginx .NewRender (c ).Data (rt .alertRuleAdd (lst , username , bgid , c .GetHeader ("X-Language" )), nil )
0 commit comments