0

我将编写“pseudo-python-jsonnet”代码来展示我想要实现的目标。我真的不知道如何在 jsonnet 中做类似的事情。

local createCopy(gname, rname, kp) =                                        
    for topLvlKey in std.objectFieldsAll(kp):                                   
        for subKey in std.objectFieldsAll(kp[topLvlKey]):                       
            if kp[topLvlKey][subKey].get("kind", "") == "PrometheusRule":       
                for group in kp[topLvlKey][subKey]["spec"]["groups"]:           
                    if group["name"] == gname:                              
                        for rule in group["rules"]:                             
                            if rule.get("alert", "") == rname:              
                                return rule
                        return null                                    
    return null 

所以基本上我想在深层对象结构中搜索特定的子对象并将其返回,如果找不到则返回 null/None。

https://jsonnet.org/learning/tutorial.html有点好,但只显示“简单”的部分,如果你想用 jsonnet 做更复杂的事情,似乎你只能靠自己了。我是 jsonnet 的新手,它真的让我很头疼,所以我希望有人能帮助我。

4

1 回答 1

1

下面的scriptlet实现了它

// filterArray by func() (returning bool)
local filterArray(array, func) = [elem for elem in array if func(elem)];

// search Prometheus' rule groups by groupName, alertName
local getPrometheusRule(groups, groupName, alertName) = (
  local group = filterArray(groups, function(x) std.objectHas(x, 'name') && x.name == groupName);
  if std.length(group) > 0
  then (
    assert std.length(group) == 1 : 'Duplicated group.name "%s"' % groupName;
    local rule = filterArray(group[0].rules, function(x) std.objectHas(x, 'alert') && x.alert == alertName);
    if std.length(rule) > 0
    then (
      assert std.length(rule) == 1 : 'Duplicated alert "%s"' % alertName;
      rule[0]
    )
  )
);

local createCopy(gname, rname, kp) = [
  if std.objectHas(kp[topLvlKey][subKey], 'kind') && kp[topLvlKey][subKey].kind == 'PrometheusRule'
  then getPrometheusRule(kp[topLvlKey][subKey].spec.groups, gname, rname)
  for topLvlKey in std.objectFieldsAll(kp)
  for subKey in std.objectFieldsAll(kp[topLvlKey])
];

/* Simple unit-tests follow */

local stack = {
  fooService: {
    fooResource: {
      kind: 'PrometheusRule',
      spec: {
        groups: [
          { name: 'fooGroup', rules: [{ alert: 'fooAlert', expr: 'fooExpr' }] },
          { name: 'barGroup', rules: [{ alert: 'fooAlert', expr: 'fooExpr' }] },
        ],
      },
    },
  },
};

{
  test_01_Found: createCopy('fooGroup', 'fooAlert', stack),
  test_02_NotFound: createCopy('fooGroup', 'fooAlerX', stack),
  test_03_NotFound: createCopy('fooGrouX', 'fooAlert', stack),
}

虽然取决于您的具体问题,但您可能需要查看https://github.com/kubernetes-monitoring/kubernetes-mixin/blob/master/README.md#customising-alert-annotationsutils.mapRuleGroups()方法(当然它会改变规则(s))。

于 2021-10-28T18:32:01.443 回答