当前位置:   article > 正文

Python:获取Prometheus接口数据并存入MySQL_prometheus 接口

prometheus 接口

目录

一、Prometheus接口

二、JSON文件

三、代码

一、Prometheus接口

        prometheus统一http接口为/api/v1,其数据响应文件格式为JSON。目前一些常用稳定接口如下:
1、/api/v1/query(GET/POST)
     即时查询,使用参数如下:
     - query=<查询语句>
     - time=<rfc3339 | unix_timestamp>时间戳,可选项
     - timeout=<duration>: 超时时间,-query.timeout限制,可选项
     若time不给定,默认为服务器当前时间。

  1. 例:
  2. curl 'http://localhost:9090/api/v1/query?query=up'
  3. 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>:结束时间
  1. 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>:结束时间
  1. 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"]}]

三、代码

  1. import json
  2. import time
  3. import pymysql as pymysql
  4. import requests
  5. def get_io_write(url):
  6. res = json.loads(requests.post(url=url).content.decode('utf8', 'ignore'))
  7. # 获取API响应的JSON文件
  8. result = {}
  9. for da in res.get('data').get('result'):
  10. # da 即为一个对象
  11. values = da.get('value') # 获取value
  12. io_write = round(float(values[1]), 2)
  13. ip = da.get('metric').get('instance') #获取IP
  14. ip = ip[:ip.index(':')] if ':' in ip else ip
  15. result[ip] = io_write # 存入字典
  16. return result
  17. def get_io_read(url):
  18. # 利用json文件来获取API接口数据
  19. res = json.loads(requests.post(url=url).content.decode('utf8', 'ignore'))
  20. result = {} # 定义一个字典来返回数据
  21. for da in res.get('data').get('result'):
  22. values = da.get('value')
  23. io_read = round(float(values[1]), 2)
  24. ip = da.get('metric').get('instance')
  25. ip = ip[:ip.index(':')] if ':' in ip else ip # 提取ip地址
  26. result[ip] = io_read
  27. return result
  28. if __name__ == "__main__":
  29. wurl = 'http://localhost:9090/api/v1/query?query=\
  30. max(rate(node_disk_writes_completed_total{device=~"sd.*|dm.*"}[1d]))by(instance)'
  31. # 我这里查询的是一天中IO最大值
  32. rurl = 'http://localhost:9090/api/v1/query?query=\
  33. max(rate(node_disk_reads_completed_total{device=~"sd.*|dm.*"}[1d]))by(instance)'
  34. wr = get_io_write(wurl) # 获取写IO的字典
  35. re = get_io_read(rurl) # 获取读IO的字典
  36. date_now = time.strftime("%Y%m%d%H") # 加一个时间值
  37. value = []
  38. # print(wr)
  39. # print(len(wr))
  40. for key in wr.keys():
  41. # print(key, " ", wr[key], re[key])
  42. for i in [key, date_now, re[key], wr[key]]:
  43. value.append(i)
  44. # 连接数据库
  45. db = pymysql.connect(host='192.168.1.9', user='root', passwd='123456', port=3306, db='prometheus')
  46. cur = db.cursor() # 游标
  47. # 以下注释行为写入Excel文件
  48. # workbook = xlwt.Workbook() # 新建工作薄
  49. # sheet = workbook.add_sheet("test.xlsx") #在工作薄中新建工作表
  50. k = 0
  51. for i in range(0, len(value), 4):
  52. # for j in range(0, 4): # 一行元素只有4列
  53. # sheet.write(k, j, value[i + j]) # 在表中写入数据
  54. sql = "insert into disk_io(ip,date,read_io,write_io) values(%s,%s,%s,%s)"
  55. try:
  56. cur.execute(sql, [value[i], value[i + 1], value[i + 2], value[i + 3]]) #执行SQL语句
  57. db.commit() # 提交
  58. except Exception as e:
  59. print(e)
  60. db.rollback() # 错误回滚
  61. k = k + 1
  62. # workbook.save("C:/Users/123/Desktop/test.xlsx") #保存工作薄
  63. cur.close()
  64. db.close()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/963539
推荐阅读
相关标签
  

闽ICP备14008679号