Kapacitor通过REST API使用模板创建任务涉及以下核心概念和操作流程:
define-template
命令定义,变量通过vars
声明。/kapacitor/v1/templates
:管理模板/kapacitor/v1/tasks
:管理任务(通过模板创建的任务)POST /kapacitor/v1/templates HTTP/1.1
Content-Type: application/json
{
"id": "cpu_alert_template",
"type": "stream",
"script": "var threshold = {{.threshold}}\nstream\n |from()\n .measurement('cpu')\n |alert()\n .crit(lambda: \"usage_idle\" < threshold)\n .message('CPU idle is {{.message}}')",
"vars": {
"threshold": {
"value": 80,
"type": "float"
},
"message": {
"value": "CRITICAL",
"type": "string"
}
}
}
POST /kapacitor/v1/tasks HTTP/1.1
Content-Type: application/json
{
"id": "cpu_alert_task",
"template-id": "cpu_alert_template",
"vars": {
"threshold": {
"value": 90.0
},
"message": {
"value": "High CPU usage!"
}
},
"dbrps": [{"db": "telegraf", "rp": "autogen"}]
}
| 参数 | 说明 |
|----------------|----------------------------------------------------------------------|
| template-id
| 引用的模板ID |
| vars
| 覆盖模板中的变量值(需匹配模板定义的变量类型) |
| dbrps
| 必填,指定数据库和保留策略(Database/Retention Policy) |
invalid template vars
错误。vars
定义,确保任务提交的变量名称和类型一致。measurement
名称错误)或阈值设置不合理。cpu
measurement。kapacitor show cpu_alert_task
检查任务状态和日志。403 Forbidden
。auth-enabled
,并在请求头添加Authorization: Bearer <TOKEN>
。import requests
# 定义模板
template_url = "http://localhost:9092/kapacitor/v1/templates"
template_data = {
"id": "mem_alert_template",
"type": "batch",
"script": "var limit = {{.limit}}\nbatch\n |query('SELECT used_percent FROM mem')\n |alert()\n .warn(lambda: \"used_percent\" > limit)",
"vars": {"limit": {"value": 70, "type": "int"}}
}
requests.post(template_url, json=template_data)
# 创建任务
task_url = "http://localhost:9092/kapacitor/v1/tasks"
task_data = {
"id": "mem_alert_task1",
"template-id": "mem_alert_template",
"vars": {"limit": {"value": 85}},
"dbrps": [{"db": "telegraf", "rp": "autogen"}]
}
response = requests.post(task_url, json=task_data)
print(response.json())
通过上述流程,可高效利用模板化任务管理Kapacitor的告警或数据处理逻辑。
没有搜到相关的沙龙