Python:获取Prometheus接口数据并存入MySQL
一、Prometheus接口prometheus统一http接口为/api/v1,其数据响应文件格式为JSON。目前一些常用稳定接口如下:1、
目录
一、Prometheus接口
prometheus统一http接口为/api/v1,其数据响应文件格式为JSON。目前一些常用稳定接口如下:
1、/api/v1/query(GET/POST)
即时查询,使用参数如下:
- query=<查询语句>
- time=<rfc3339 | unix_timestamp>时间戳,可选项
- timeout=<duration>: 超时时间,-query.timeout限制,可选项
若time不给定,默认为服务器当前时间。
例:
curl 'http://localhost:9090/api/v1/query?query=up'
curl 'http://localhost:9090/api/v1/query?query=up&time=2022-04-01T00:00:00.781Z'
2、/api/v1/query_range(GET/POST)
范围查询,使用参数如下:
- query=<查询语句>
- start=<rfc3339 | unix_timestamp>:开始时间(包含该值)
- end=<rfc3339 | unix_timestamp>:结束时间(包含该值)
- step=<duration | float>duration:浮点格式的步长
- timeout=<duration>: 超时时间
3、/api/v1/series(GET/POST)
元数据序列查询,使用参数如下:
- match[]=<series_selector>:选择返回参数
- start=<rfc3339 | unix_timestamp>:开始时间
- end=<rfc3339 | unix_timestamp>:结束时间
例
curl -g 'http://localhost:9090/api/v1/series?''match[]=up'
4、/api/v1/labels
获取元数据标签
- match[]=<series_selector>:选择返回参数
- start=<rfc3339 | unix_timestamp>:开始时间
- end=<rfc3339 | unix_timestamp>:结束时间
例
curl 'localhost:9090/api/v1/labels'
具体api接口及使用可访问官网:https://prometheus.io/docs/introduction/overview/
二、JSON文件
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,是JavaScript的子集。主要用来存储和交换文本信息,具有易于读写、占用带宽小、网络传输速度快的特性,适用于数据量大,不要求保留原有类型的情况。prometheus采用JSON作为接口响应文件格式。
在JSON中,花括号保存对象、方括号保存数组。名称为双引号,数据在value中。例:执行curl 'http://localhost:9090/api/v1/query?query=up',获得的数据中:
[{"metric":{"__name__":"up","instance":"192.168.1.1:9090","job":"federate"},"value":[1649314698.292,"1"]},{"metric":{"__name__":"up","instance":"192.168.1.2:9090","job":"prometheus"},"value":[1649314698.292,"1"]}]
三、代码
import json
import time
import pymysql as pymysql
import requests
def get_io_write(url):
res = json.loads(requests.post(url=url).content.decode('utf8', 'ignore'))
# 获取API响应的JSON文件
result = {}
for da in res.get('data').get('result'):
# da 即为一个对象
values = da.get('value') # 获取value
io_write = round(float(values[1]), 2)
ip = da.get('metric').get('instance') #获取IP
ip = ip[:ip.index(':')] if ':' in ip else ip
result[ip] = io_write # 存入字典
return result
def get_io_read(url):
# 利用json文件来获取API接口数据
res = json.loads(requests.post(url=url).content.decode('utf8', 'ignore'))
result = {} # 定义一个字典来返回数据
for da in res.get('data').get('result'):
values = da.get('value')
io_read = round(float(values[1]), 2)
ip = da.get('metric').get('instance')
ip = ip[:ip.index(':')] if ':' in ip else ip # 提取ip地址
result[ip] = io_read
return result
if __name__ == "__main__":
wurl = 'http://localhost:9090/api/v1/query?query=\
max(rate(node_disk_writes_completed_total{device=~"sd.*|dm.*"}[1d]))by(instance)'
# 我这里查询的是一天中IO最大值
rurl = 'http://localhost:9090/api/v1/query?query=\
max(rate(node_disk_reads_completed_total{device=~"sd.*|dm.*"}[1d]))by(instance)'
wr = get_io_write(wurl) # 获取写IO的字典
re = get_io_read(rurl) # 获取读IO的字典
date_now = time.strftime("%Y%m%d%H") # 加一个时间值
value = []
# print(wr)
# print(len(wr))
for key in wr.keys():
# print(key, " ", wr[key], re[key])
for i in [key, date_now, re[key], wr[key]]:
value.append(i)
# 连接数据库
db = pymysql.connect(host='192.168.1.9', user='root', passwd='123456', port=3306, db='prometheus')
cur = db.cursor() # 游标
# 以下注释行为写入Excel文件
# workbook = xlwt.Workbook() # 新建工作薄
# sheet = workbook.add_sheet("test.xlsx") #在工作薄中新建工作表
k = 0
for i in range(0, len(value), 4):
# for j in range(0, 4): # 一行元素只有4列
# sheet.write(k, j, value[i + j]) # 在表中写入数据
sql = "insert into disk_io(ip,date,read_io,write_io) values(%s,%s,%s,%s)"
try:
cur.execute(sql, [value[i], value[i + 1], value[i + 2], value[i + 3]]) #执行SQL语句
db.commit() # 提交
except Exception as e:
print(e)
db.rollback() # 错误回滚
k = k + 1
# workbook.save("C:/Users/123/Desktop/test.xlsx") #保存工作薄
cur.close()
db.close()
更多推荐
所有评论(0)