使用python读取普罗米修斯公制

2022-04-03 00:00:00 python kubernetes prometheus

问题描述

我正在尝试读取Kubernetes中POD的普罗米修斯指标(CPU和内存值)。我已经安装了Prometheus,并且使用本地主机‘http://localhost:9090/一切正常。我使用以下代码来读取Pod的CPU和内存,但出现错误Results=Response.json()[‘data’][‘Result’],No JSON对象无法解码。有谁能帮忙吗?

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))

解决方案

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

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

您可以将"CONTAINER_CPU_USER_SECONDS_TOTAL"更改为您想要读取的任何查询。 。。 祝你好运

相关文章