前言
grafana自帶的alert功能是有限的,比如只能對某個query 配置alert,而不能對具體分類,當然我們也可以通過代碼來實現定製化的alert
因要定時監控grafana的數據變化情況,所以本篇文章使用
easyswoole的定時器
來做講解。
生成key
key爲調用grafana http api 所需的驗證信息
分析要請求的api和傳遞的參數
當然你可以去grafana官方文檔去翻一番http api 章節
Install easyswoole的http-client組件
composer require easyswoole\http-client
easyswoole 定時器
代碼實現
<?php
namespace EasySwoole\EasySwoole;
use EasySwoole\Component\Timer;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\HttpClient\HttpClient;
class EasySwooleEvent implements Event
{
public static function initialize()
{
// TODO: Implement initialize() method.
date_default_timezone_set('Asia/Shanghai');
}
public static function mainServerCreate(EventRegister $register)
{
// TODO: Implement mainServerCreate() method.
// 定時檢測數據是否超過閾值
Timer::getInstance()->loop(3 * 1000, function () {
// 指定要請求的grafana接口
$httpClient = new HttpClient('http://x.x.x.x./api/tsdb/query');
// 設置認證信息,grafana 生成的key
$httpClient->setHeaders([
'Authorization' => 'Bearer eyJrIjoiS1lTVWhrNjk5cFM1and4Y0kzNmM2SDNXQ2oyMm44Sk'
], true, false);
// 請求參數,這裏可以通過代碼控制from、to等參數
$params = '{"from":"1612458544257","to":"1612631344257","queries":[{"refId":"A","intervalMs":300000,"maxDataPoints":634,"datasourceId":1,"rawSql":"SELECT\n $__timeGroupAlias(ctime,5m),\n category2 AS metric,\n sum(price) as price\nFROM grafana_price\nWHERE\n $__timeFilter(ctime) AND (\n category2 = \"全部\"\n OR (\"水果\" = category1 and \"全部\" = \"全部\" and category2 <> \"\")\n )\nGROUP BY 1,2\nORDER BY $__timeGroup(ctime,5m)\n","format":"time_series"}]}';
$response = $httpClient->postJson($params);
$data = $response->getBody();
$data = json_decode($data, true);
// series 就是拿到的每個二級分類各時間節點的數據
$series = $data['results']['A']['series'];
// TODO: 後面就自定義報警(郵件通知、釘釘通知等)了
});
}
}
series結果
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "香蕉"
["points"]=>
array(2) {
[0]=>
array(2) {
[0]=>
int(88)
[1]=>
int(1612537500000)
}
[1]=>
array(2) {
[0]=>
int(121)
[1]=>
int(1612542000000)
}
}
}
[1]=>
array(2) {
["name"]=>
string(6) "西瓜"
["points"]=>
array(2) {
[0]=>
array(2) {
[0]=>
int(22)
[1]=>
int(1612540200000)
}
[1]=>
array(2) {
[0]=>
int(33)
[1]=>
int(1612544100000)
}
}
}
}
``