通过访问Prometheus HTTP API,可以获取监控数据。本文分享如何使用query
.
query
query用于查询距PromQL查询时间最近的样本值。
查询instant vector
request
GET /api/v1/query?query=rate(node_network_receive_bytes_total[5m])
query=rate(node_network_receive_bytes_total[5m])
的数据类型为Gauge,该查询返回当前的网络包处理速率。
response
{
"status": "success",
"data": {
"resultType": "vector", // instant vector 类型
"result": [
{
"metric": { // label
"device": "eth0",
"group": "production",
"instance": "192.168.10.57:9100",
"job": "node"
},
"value": [
1639512157.396, // 样本时间戳(据你执行PromQL查询时间最近)
"101.99827121574211" //样本值
]
},
{
"metric": {
"device": "lo",
"group": "production",
"instance": "192.168.10.57:9100",
"job": "node"
},
"value": [
1639512157.396,
"0"
]
}
]
}
}
range vector
instant vector每个样本点有一个值,而range verctor每个样本点有多个值。通常情况下,要使用rate函数处理
range vector来计算出有意义指标。
request
GET /api/v1/query?query=node_network_receive_bytes_total[5m]
获取近5min的全部网络包收发指标node_network_receive_bytes_total
的全部样本数据。
response
{
"status": "success",
"data": {
"resultType": "matrix", // 这里从vector -> matrix, 代表每个样本的值从一个变成多个
"result": [
{
"metric": { // laebl
"__name__": "node_network_receive_bytes_total",
"device": "eth0",
"group": "production",
"instance": "192.168.10.57:9100",
"job": "node"
},
"values": [
[
1639513177.547,
"4705916"
],
[
1639513182.546,
"4706426"
]
// omit...
]
},
{
"metric": {
"__name__": "node_network_receive_bytes_total",
"device": "lo",
"group": "production",
"instance": "192.168.10.57:9100",
"job": "node"
},
"values": [
// omit
]
}
]
}
}
query_range
查询某个时间段下指标的变化值,通常用于绘图。
request
比如计算指标node_network_receive_bytes_total
(网络收发包速率)在某个时间段的变化。
GET http://${prometheus_ip}:9090/api/v1/query_range?query=rate(node_network_receive_bytes_total[5m])&start=1639469367&end=1639509133&step=60
其中
- start 开始时间
- end 结束时间
- step 步长
- query PromQL表达式
response
返回体格式
{
"status": "success", // 如果错误是error
"data": {
"resultType": "matrix", //返回的数据类型
"result": [
{
"metric": { // 数据的label
"device": "eth0",
"group": "production",
"instance": "192.168.10.57:9100",
"job": "node"
},
// 查询结果,可以利用这些查询结果做基于时间的图表
"values": [
[
1639469367, //时间戳
"101.99930847926453" // 样本值
],
[
1639469427,
"101.99827121574211"
],
// ... omit for brevity
[
1639509087,
"0"
]
]
}
]
}
}