Reading Prometheus metric using python

2/4/2020

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))
-- 10101
kubernetes
prometheus
python

2 Answers

2/5/2020

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

-- MOBT
Source: StackOverflow

2/4/2020

Performing a GET request at <prom-server-ip>:9090/metrics returns the Prometheus metrics (not in JSON format) of the Prometheus server itself.

Since you're trying to perform query, you need to use the HTTP API endpoints like /api/v1/query or /api/v1/query_range instead of using /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" ]
         }
      ]
   }
}

For more detailed information visit Prometheus official docs.

-- Kamol Hasan
Source: StackOverflow