【问题标题】:Reading Prometheus metric using python使用 python 读取 Prometheus 指标
【发布时间】:2020-02-04 04:17:17
【问题描述】:

我正在尝试读取 kubernetes 中 POD 的 Prometheus 指标(cpu 和内存值)。我安装了 Prometheus,一切都使用本地主机'http://localhost:9090/。我使用以下代码读取 pod 的 CPU 和内存,但出现错误 results = response.json()['data']['result'] , No JSON object could be decoded 。有人可以帮忙吗?

import datetime
import time
import requests  

PROMETHEUS = 'http://localhost:9090/'

end_of_month = datetime.datetime.today().replace(day=1).date()

last_day = end_of_month - datetime.timedelta(days=1)
duration = '[' + str(last_day.day) + 'd]'

response = requests.get(PROMETHEUS + '/metrics',
  params={
    'query': 'sum by (job)(increase(process_cpu_seconds_total' + duration + '))',
    'time': time.mktime(end_of_month.timetuple())})
results = response.json()['data']['result']

print('{:%B %Y}:'.format(last_day))
for result in results:
  print(' {metric}: {value[1]}'.format(**result))

【问题讨论】:

    标签: python kubernetes prometheus


    【解决方案1】:

    代码看起来是正确的,但是,您的响应命令中的查询是错误的。真正的甲酸是:

    response =requests.get(PROMETHEUS + '/api/v1/query', params={'query': 'container_cpu_user_seconds_total'}) 
    

    您可以将“container_cpu_user_seconds_total”更改为您想要阅读的任何查询。 .. 祝你好运

    【讨论】:

      【解决方案2】:

      <prom-server-ip>:9090/metrics 执行GET 请求会返回 Prometheus 服务器本身的 Prometheus 指标(不是 JSON 格式)。

      由于您尝试执行查询,因此您需要使用 HTTP API 端点,例如 /api/v1/query/api/v1/query_range,而不是使用 /metrics

      $ curl 'http://localhost:9090/api/v1/query?query=up&time=2015-07-01T20:10:51.781Z'
      {
         "status" : "success",
         "data" : {
            "resultType" : "vector",
            "result" : [
               {
                  "metric" : {
                     "__name__" : "up",
                     "job" : "prometheus",
                     "instance" : "localhost:9090"
                  },
                  "value": [ 1435781451.781, "1" ]
               },
               {
                  "metric" : {
                     "__name__" : "up",
                     "job" : "node",
                     "instance" : "localhost:9100"
                  },
                  "value" : [ 1435781451.781, "0" ]
               }
            ]
         }
      }
      

      如需更多详细信息,请访问Prometheus official docs

      【讨论】:

      • 谢谢你的回答,我试过这个命令 curl 'localhost:9090/api/v1/…' 答案是 {"status":"success","data":{"resultType":"vector", “结果”:[]}}。这是否意味着它正在阅读笔记?
      • @10101 状态为success,表示它有效。由于您没有名为 up 的指标,这就是结果为空的原因。使用有效的查询。你也会找到结果的。
      【解决方案3】:

      您使用了错误的端点。 docs 建议的正确端点应该是查询接口,就像

      http://pushgateway.example.org:9091/api/v1/status

      要在 python 中简单地使用 json 包。

      import json
      txt = requests.get(PROMETHEUS+'api/v1/metrics').text
      j = json.loads(txt)
      print(j['data'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-13
        • 2020-02-05
        • 1970-01-01
        • 2020-07-22
        • 1970-01-01
        • 2021-06-08
        相关资源
        最近更新 更多