func fromAPIRules()

in pkg/operator/apis/monitoring/v1/rules_config.go [67:113]


func fromAPIRules(groups []RuleGroup) (result rulefmt.RuleGroups, err error) {
	for _, g := range groups {
		var rules []rulefmt.RuleNode

		for _, r := range g.Rules {
			rule := rulefmt.RuleNode{
				Labels:      r.Labels,
				Annotations: r.Annotations,
			}
			rule.Expr.SetString(r.Expr)
			if r.Record != "" {
				rule.Record.SetString(r.Record)
			}
			if r.Alert != "" {
				rule.Alert.SetString(r.Alert)
			}
			if r.For != "" {
				rule.For, err = model.ParseDuration(r.For)
				if err != nil {
					return result, fmt.Errorf("parse 'for' duration: %w", err)
				}
			}
			rules = append(rules, rule)
		}
		group := rulefmt.RuleGroup{
			Name:  g.Name,
			Rules: rules,
		}
		if g.Interval != "" {
			group.Interval, err = model.ParseDuration(g.Interval)
			if err != nil {
				return result, fmt.Errorf("parse evaluation interval: %w", err)
			}
		}
		result.Groups = append(result.Groups, group)
	}
	// Do a marshal/unmarshal cycle to run the upstream validation.
	b, err := yaml.Marshal(result)
	if err != nil {
		return result, err
	}
	var validate rulefmt.RuleGroups
	if err := yaml.Unmarshal(b, &validate); err != nil {
		return result, fmt.Errorf("loading rules failed: %w", err)
	}
	return result, nil
}