Bootstrap

Grafana使用API创建报警


前言

调用API接口创建报警规则,参考:官方文档

POST:/api/v1/provisioning/alert-rules

示例

这里使用的是MySQL数据源。

1. 请求体

{
    "orgID": 2,
    "folderUID": "f790d5a3-50d4-4863-9fd3-3f0d76dbd13a",
    "ruleGroup": "one/1m",
    "title": "api 002: 8365/8366  bid_price", // ruleGroup下唯一
    "condition": "C",
    "data": [
        {
            "refId": "A",
            "relativeTimeRange": { // 查询过去15分钟的数据
                "from": 900,// 900: now-900s
                "to": 0 // 0: now
            },
            "datasourceUid": "b522dfe4-713f-4edd-833e-0c3a135d8c7a",
            "model": {
                "dataset": "...", // 数据集
                "datasource": {
                    "type": "mysql",
                    "uid": "b522dfe4-713f-4edd-833e-0c3a135d8c7a"
                },
                "editorMode": "code", // sql code 模式
                "format": "time_series",
                "rawQuery": true,
                "rawSql": "SELECT UNIX_TIMESTAMP(<time_column>) as time_sec <value column> as value, <series name column> as metric FROM <table name> WHERE $__timeFilter(time_column) ORDER BY <time_column> ASC ",
                "refId": "A"
            }
        },
        {
            "refId": "B",
            "datasourceUid": "__expr__",
            "model": {
                "expression": "A", // 使用A作为输入
                "reducer": "mean", // 聚合A的查询结果取均值, 也可取 last,max,min,sum,count
                "refId": "B",
                "type": "reduce" // 聚合
            }
        },
        {
            "refId": "C",
            "datasourceUid": "__expr__",
            "model": {
                "conditions": [
                    {
                        "evaluator": { //阈值: v < -0.2 || v > 0.2
                            "params": [
                                -0.2,
                                0.2
                            ],
                            "type": "outside_range" // 也可取 gt, lt, within_range
                        },
                        "operator": {
                            "type": "and" // 多个阈值条件间的关系: and, or
                        }
                    }
                ],
                "expression": "B", // 使用B作为输入
                "refId": "C",
                "type": "threshold" // 阈值
            }
        }
    ],
    "noDataState": "NoData",
    "execErrState": "Error",
    "for": "5m", // 持续命中规则5分钟报警
    "annotations": { // 自定义key/value, 报警时会附加在消息中
        "__dashboardUid__": "a633cceb-3e90-4f9a-9752-b5afa2c7d710",
        "__panelId__": "1",
        "自定义key": "报警消息附带信息"
    },
    "labels": {// 标签:可以在后台配置触发的报警点
        "test_alert": "dingding_test"
    }
}

2. 响应体

{
  "id": 184,
  "uid": "f790d5a3-50d4-4863-9fd3-3f0d76dbd13f", // 返回的报警规则uid, 可用于查询、修改、删除报警
  ...
}
;