如何在Prometheus中使用过滤器编写API查询

时间:2018-11-06 03:22:45

标签: python api prometheus

我想要的是:使用python从Prometheus获取指标

示例代码在这里:

import requests
url='prometheus.cup.com'
response=requests.get("{0}/api/v1/query_range?query=container_cpu_load_average_10s&start=2018-11-05T00:59:00.781Z&end=2018-11-05T01:00:00.781Z&step=15s".format(url))

示例结果是:

{u'beta_kubernetes_io_os': u'linux', u'name': u'k8s_POD_nginx-bf8f468d8-gbjvp_openwhisk01_01f85b0c-9f87-11e8-893e-6c92bf025c32_5', u'image': u'openshift/origin-pod:v3.9.0', u'namespace': u'openwhisk01', u'instance': u'openshift-app1.cup.com', u'job': u'kubernetes-cadvisor', u'pod_name': u'nginx-bf8f468d8-gbjvp', u'container_name': u'POD', u'__name__': u'container_cpu_load_average_10s', u'beta_kubernetes_io_arch': u'amd64', u'id': u'/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod01f85b0c_9f87_11e8_893e_6c92bf025c32.slice/docker-d7422ab03a96a07395538e5fa5c9d971bb66855f94a45f4540f423cb1da3422f.scope', u'kubernetes_io_hostname': u'openshift-app1.cup.com'}

问题:我想通过某些过滤器来获得结果,例如

query=container_cpu_load_average_10s{container_name=POD}, 
(of course, this type is not right, just an example)

那么用python中的过滤器编写API查询的正确方法是什么?

预先感谢

2 个答案:

答案 0 :(得分:2)

您的代码几乎是正确的,只需将查询作为参数传递给URL。请参见代码taken from here的以下简短代码段:

response = requests.get('http://localhost:9090/api/v1/query'),
    params={'query': "query=container_cpu_load_average_10s{container_name=POD}"})
print(response.json()['data']['result'])

答案 1 :(得分:0)

奥利弗答案有一些错误,请解决。
#!/usr/bin/env python

import requests

prome_sql = "(node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) / node_memory_MemTotal_bytes * 100"

response = requests.get('http://192.168.20.249:9090/api/v1/query',
    params={'query': prome_sql})
print(response.json()["data"]['result'])