Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Prometheus metric using python

I am trying to read Prometheus metrics (the cpu and memory values) of a POD in kubernetes. I have Prometheus install and everything is up using local host 'http://localhost:9090/. I used the following code to read the CPU and memory of a pod but I have an error results = response.json()['data']['result'] , No JSON object could be decoded . IS anyone can help please ?

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))
like image 902
10101 Avatar asked May 16 '26 10:05

10101


1 Answers

The code looks true, However,the query in your response command is wrong . the true formate is :

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

you can change "container_cpu_user_seconds_total" to any query that you want to read. .. good luck

like image 200
MOBT Avatar answered May 17 '26 22:05

MOBT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!