简介
Grafana一款非常美观而又强大的可视化监控指标展示工具,我们开发系统或者大数据平台都会使用grafana去展示我们的监控指标,但是每次都需要手动去配置我们监控指标的dashboard,如果监控很少还能接受,但是如果是平台类的需求,总不能让用户每次都去创建监控指标的dashboard.这时候Grafana给我们提供操作的restful api,可以通过代码以http请求的方式去创建指标dashboard,下面我们介绍一下具体的使用步骤。
第一步:获取API Keys
通过代码去操作Grafana,必须去创建我们的API Keys,然后放在http请求的Authorization
中,API Keys需要在Grafana的页面上创建 ,如下图:选择设置 -> 进图页面添加API Keys -> 角色最好设置为管理员,出现API Keys时粘贴保存下来,只出现一次,返回页面就不显示了。
第二步:通过restful api创建dashboard
当我们有了API Keys ,就可以查看官方文档:https://grafana.com/docs/grafana/latest/http_api/dashboard/,查看创建dashboard的restful 请求的格式以及需要的参数。
创建dashboard的restful 请求格式案例
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer APIKeys值" -i "https://地址:3000/api/dashboards/db" -d '{"dashboard": {"id": null,"uid": null,"title": "Production Overview","tags": [ "templated" ],"timezone": "browser","schemaVersion": 16,"version": 0},"folderId": 0,"overwrite": false}'
查询dashboard
curl -X GET -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer TOKEN值" -i "https://地址:3000/api/dashboards/uid/sRz3Bgbik"
我们执行一下创建dashboard的restful请求,看结果确实创建一个名为Production Overview的dashboard,但是内容为空,这样没法创建具体的监控指标的图表,下面介绍如何既创建dashboard,也能创建监控指标的图表。
自定义创建dashboard和图表
到此我们已经实现创建dashboard,但是自由度不高,限制太大,不符合实际需求,可以采用如下所示的方法来创建自定义的指标图标。可以现在dashboard先手动的创建出所需要展示监控指标的图标,然后复制json model,然后做如下的拼接,其中json model就是你复制的json model的数据,拼接后的数据作为创建图表的参数数据。
注意:"overwrite": true 的值一点设置为true,不然没法创建dashboard
{"dashboard":
json model,
"overwrite": true
}
创建自定义告警可以借鉴jsonmodel之中的某些属性,实现自由定制图标。如下:
创建(单个):
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer API Keys值" -i "https:/地址:3000/api/dashboards/db" -d '{"dashboard": {"id":XXXX,"uid":"XXX","title":"XXX","tags":[ "XXX" ],"panels": [{"datasource": "XXX","gridPos": {"h": 9,"w": 12,"x": 0,"y": 0},"targets": [{"aggregator": "none","alias": "$tag_server","downsampleAggregator": "sum","downsampleFillPolicy": "none","metric": "XXX"}],"title": "test","type": "graph"}]},"overwrite": true}'
其中"alias": "$tag_server"表示图中各个指标的别名为tag中的server,downsample表示采样(如一分钟内可能报多个数据,可以将采样间隔修改为一分钟)
创建精简版(多个):
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer TOKEN值" -i "https://网址:3000/api/dashboards/db" -d '{"dashboard": {"id":XXX,"uid":"XXX","title":"XXX","tags":[ "XXX" ],"panels": [{"datasource": "XXX","gridPos": {"h": 9,"w": 12,"x": 0,"y": 0},"targets": [{"aggregator": "none","alias": "$tag_server","downsampleAggregator": "sum","downsampleFillPolicy": "none","metric": "XXX"}],"title": "测试1","type": "graph"},{"datasource": "XXX","gridPos": {"h": 9,"w": 12,"x": 12,"y": 0},"targets": [{"aggregator": "none","alias": "$tag_server","downsampleAggregator": "sum","downsampleFillPolicy": "none","filters": [{"filter": ".*XX.*","groupBy": false,"tagk": "server","type": "wildcard"}],"metric": "XXX"}],"title": "测试2","type": "graph"}]},"overwrite": true}'
java代码创建Grafana案例
public class GrafanaAuto {
public static void main(String[] args) {
String token="eyJrIjoiV1VMR2hJWWtKb0htV3BaaFZaSWkwMHRhdVRya1NUSzQiLCJuIjoid2FuZ3poIiwiaWQiOjF9";
//String data="{\"dashboard\": {\"id\":null,\"uid\":null,\"title\":\"Production Overview\",\"tags\":[ \"templated\" ],\"timezone\": \"browser\",\"schemaVersion\": 16, \"version\": 0},\"overwrite\": true}";
//String data="{\"dashboard\": {\"id\":13,\"uid\":\"bJ2miYlWz\",\"title\":\"Production Overview\",\"tags\":[ \"templated\" ],\"timezone\": \"browser\",\"schemaVersion\": 16, \"version\": 0},\"panels\": [{\"datasource\": \"InfluxDB\",\"gridPos\": {\"h\": 9,\"w\": 12,\"x\": 0,\"y\": 0},\"targets\": [{\"groupBy\":[{\"params\":[\"tag1\"],\"type\":\"tag\"}],\"measurement\":\"success_no_session_20200217\",\"orderByTime\":\"ASC\",\"policy\":\"rp_name\",\"refId\":\"A\",\"resultFormat\":\"time_series\",\"select\":[[{\"params\":[\"auc\"],\"type\":\"field\"}]],\"tags\":[{\"key\":\"tag1\",\"operator\":\"=\",\"value\":\"galaxy\"}]}],\"title\": \"测试3\",\"type\": \"graph\"}]},\"overwrite\": true}";
String data="{\"dashboard\":\n" +
" {\n" +
" \"annotations\": {\n" +
" \"list\": [\n" +
" {\n" +
" \"builtIn\": 1,\n" +
" \"datasource\": \"-- Grafana --\",\n" +
" \"enable\": true,\n" +
" \"hide\": true,\n" +
" \"iconColor\": \"rgba(0, 211, 255, 1)\",\n" +
" \"name\": \"Annotations & Alerts\",\n" +
" \"type\": \"dashboard\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"editable\": true,\n" +
" \"gnetId\": null,\n" +
" \"graphTooltip\": 0,\n" +
" \"id\": null,\n" +
" \"links\": [],\n" +
" \"panels\": [\n" +
" {\n" +
" \"aliasColors\": {},\n" +
" \"bars\": false,\n" +
" \"dashLength\": 10,\n" +
" \"dashes\": false,\n" +
" \"fill\": 1,\n" +
" \"gridPos\": {\n" +
" \"h\": 8,\n" +
" \"w\": 12,\n" +
" \"x\": 0,\n" +
" \"y\": 0\n" +
" },\n" +
" \"id\": 2,\n" +
" \"legend\": {\n" +
" \"avg\": false,\n" +
" \"current\": false,\n" +
" \"max\": false,\n" +
" \"min\": false,\n" +
" \"show\": true,\n" +
" \"total\": false,\n" +
" \"values\": false\n" +
" },\n" +
" \"lines\": true,\n" +
" \"linewidth\": 1,\n" +
" \"links\": [],\n" +
" \"nullPointMode\": \"null\",\n" +
" \"percentage\": false,\n" +
" \"pointradius\": 2,\n" +
" \"points\": false,\n" +
" \"renderer\": \"flot\",\n" +
" \"seriesOverrides\": [],\n" +
" \"spaceLength\": 10,\n" +
" \"stack\": false,\n" +
" \"steppedLine\": false,\n" +
" \"targets\": [\n" +
" {\n" +
" \"groupBy\": [\n" +
" {\n" +
" \"params\": [\n" +
" \"tag1\"\n" +
" ],\n" +
" \"type\": \"tag\"\n" +
" }\n" +
" ],\n" +
" \"measurement\": \"tag_recall\",\n" +
" \"orderByTime\": \"ASC\",\n" +
" \"policy\": \"default\",\n" +
" \"refId\": \"A\",\n" +
" \"resultFormat\": \"time_series\",\n" +
" \"select\": [\n" +
" [\n" +
" {\n" +
" \"params\": [\n" +
" \"all_num\"\n" +
" ],\n" +
" \"type\": \"field\"\n" +
" }\n" +
" ]\n" +
" ],\n" +
" \"tags\": [\n" +
" {\n" +
" \"key\": \"tag1\",\n" +
" \"operator\": \"=\",\n" +
" \"value\": \"index\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"thresholds\": [],\n" +
" \"timeFrom\": null,\n" +
" \"timeRegions\": [],\n" +
" \"timeShift\": null,\n" +
" \"title\": \"flink-test\",\n" +
" \"tooltip\": {\n" +
" \"shared\": true,\n" +
" \"sort\": 0,\n" +
" \"value_type\": \"individual\"\n" +
" },\n" +
" \"type\": \"graph\",\n" +
" \"xaxis\": {\n" +
" \"buckets\": null,\n" +
" \"mode\": \"time\",\n" +
" \"name\": null,\n" +
" \"show\": true,\n" +
" \"values\": []\n" +
" },\n" +
" \"yaxes\": [\n" +
" {\n" +
" \"format\": \"short\",\n" +
" \"label\": null,\n" +
" \"logBase\": 1,\n" +
" \"max\": null,\n" +
" \"min\": null,\n" +
" \"show\": true\n" +
" },\n" +
" {\n" +
" \"format\": \"short\",\n" +
" \"label\": null,\n" +
" \"logBase\": 1,\n" +
" \"max\": null,\n" +
" \"min\": null,\n" +
" \"show\": true\n" +
" }\n" +
" ],\n" +
" \"yaxis\": {\n" +
" \"align\": false,\n" +
" \"alignLevel\": null\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"schemaVersion\": 18,\n" +
" \"style\": \"dark\",\n" +
" \"tags\": [\n" +
" \"templated\"\n" +
" ],\n" +
" \"templating\": {\n" +
" \"list\": []\n" +
" },\n" +
" \"time\": {\n" +
" \"from\": \"now-6h\",\n" +
" \"to\": \"now\"\n" +
" },\n" +
" \"timepicker\": {\n" +
" \"refresh_intervals\": [\n" +
" \"5s\",\n" +
" \"10s\",\n" +
" \"30s\",\n" +
" \"1m\",\n" +
" \"5m\",\n" +
" \"15m\",\n" +
" \"30m\",\n" +
" \"1h\",\n" +
" \"2h\",\n" +
" \"1d\"\n" +
" ],\n" +
" \"time_options\": [\n" +
" \"5m\",\n" +
" \"15m\",\n" +
" \"1h\",\n" +
" \"6h\",\n" +
" \"12h\",\n" +
" \"24h\",\n" +
" \"2d\",\n" +
" \"7d\",\n" +
" \"30d\"\n" +
" ]\n" +
" },\n" +
" \"timezone\": \"browser\",\n" +
" \"title\": \"lll\",\n" +
" \"uid\": null,\n" +
" \"version\": 1\n" +
" },\n" +
"\"overwrite\": true}"}";
String url="http://7.0.0.1/api/dashboards/db/";
interfaceUtil(url,data,token);
}
/**
* 调用对方接口方法
* @param path 对方或第三方提供的路径
* @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
*/
public static void interfaceUtil(String path, String data,String apiKey) {
try {
URL url = new URL(path);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
/**设置URLConnection的参数和普通的请求属性****start***/
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");//GET和POST必须全大写
conn.connect();
//POST请求
BufferedWriter out1 = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
out1.write(data);
out1.flush();
out1.close();
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
str = new String(str.getBytes(), "UTF-8");//解决中文乱码问题
System.out.println(str);
}
//关闭流
is.close();
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
System.out.println("完整结束");
} catch (Exception e) {
e.printStackTrace();
}
}
}
扫一扫加入大数据公众号和技术交流群,了解更多大数据技术,还有免费资料等你哦
扫一扫加入大数据公众号和技术交流群,了解更多大数据技术,还有免费资料等你哦
扫一扫加入大数据公众号和技术交流群,了解更多大数据技术,还有免费资料等你哦