Redian新闻
>
Prometheus API 使用介绍

Prometheus API 使用介绍

公众号新闻

做为一位优秀的技术人员,往往能通过对数据的最大化利用来产生更多价值。而Prometheus的监控数据则是可以为我们所用的重要数据,它并不只能用于日常的监控和告警使用,也可以用于数据分析、成本管理等企业需求。

在这种场景下,需要我们从Prometheus去获取相关的数据,并对其进行处理加工。关于数据的获取方法,通常会使用Prometheus提供的API来操作,本文将会对此进行讲解介绍。


01

API格式
目前,Prometheus API 的稳定版本为V1,针对该API的访问路径为 /api/v1。API支持的请求模式有GET和POST两种,当正常响应时,会返回2xx的状态码。
反之,当API调用失败时,则可能返回以下几种常见的错误提示码:
400 Bad Request  参数丢失或不正确时出现。
422 Unprocessable Entity 当表达无法被执行时。
503 Service Unavailiable 查询超时或中止时。
在功能上,Prometheus  API 提供了丰富的接口类型,包括表达式查询、元数据查询、配置查询、规则查询等多个功能,甚至还有清理数据的接口。
当API正常响应后,将返回如下的Json数据格式。
{
  "status""success" | "error",
  "data": <data>,

  // Only set if status is "error". The data field may still hold
  // additional data.
  "errorType""<string>",
  "error""<string>",

  // Only if there were warnings while executing the request.
  // There will still be data in the data field.
  "warnings": ["<string>"]
}



02

API调用

下面,我们将以两个样例来演示关于API的调用,方便大家理解掌握。

  1.   即时查询 

说明:该接口属于表达式查询,将根据表达式返回单个时间点的数据。

GET /api/v1/query
POST /api/v1/query

该接口可使用如下参数进行查询,其中time为需要获取值的时间戳,如果不填则默认返回最新的值 。

  • query=<string>:Prometheus 表达式查询字符串。

  • time=<rfc3339 | unix_timestamp> :评估时间戳,可选参数。

  • timeout=<duration>:  查询超时设置,可选参数,默认将使用-query.timeout的全局参数。

示例:

获取实例"192.168.214.108"的node_load5值。

请求的参数如下:

curl http://localhost:9090/api/v1/query?query=node_load5{instance="192.168.214.108:9100"}
返回数据:

status 字段为success,表明请求成功;data字段包括了数据的相关参数,其中value为对应的时间戳和数据值 ,也即是node_load5的值。

{
    "status""success",
    "data": {
        "resultType""vector",
        "result": [
            {
                "metric": {
                    "__name__""node_load5",
                    "instance""192.168.214.108:9100",
                    "job""node"
                },
                "value": [
                    1666865246.993,   # 时间戳
                    "0.04"            # 数据值 
                ]
            }
        ]
    }
}

2. 范围查询 

说明:接口将根据表达式,返回指定时间范围内的数据。
GET /api/v1/query_range
POST /api/v1/query_range

该接口支持如下参数查询:

  • query=<string>:Prometheus 表达式查询字符串。

  • start=<rfc3339 | unix_timestamp>:开始时间戳。

  • end=<rfc3339 | unix_timestamp> :结束时间戳。

  • step=<duration | float>:查询分辨率步长。

  • timeout=<duration>:查询超时设置,可选参数,默认将使用-query.timeout的全局参数。


示例:

获取实例"192.168.214.108"在某段时间内node_load5的所有值。

请求的参数如下 :

curl http://localhost:9090/api/v1/query_range?query=node_load5{instance="192.168.214.108:9100"}&start=2022-10-28T02:10:10.000Z&end=2022-10-28T02:13:00.000Z&step=60s
返回数据 :

以下示例为3分钟范围内的表达式返回值,查询分辨率为60秒,故返回三次值。

{
    "status""success",
    "data": {
        "resultType""matrix",
        "result": [
            {
                "metric": {
                    "__name__""node_load5",
                    "instance""192.168.214.108:9100",
                    "job""node"
                },
                "values": [
                    [
                        1666923010,
                        "0.04"
                    ],
                    [
                        1666923070,
                        "0.04"
                    ],
                    [
                        1666923130,
                        "0.03"
                    ]
                ]
            }
        ]
    }
}

03

获取数据

上面的curl访问方式更多是用于测试,在实际应用中,我们通常会用代码的方式来获取数据并进行处理。

此处以Python为例,演示关于代码调用接口的应用方法。(PS:这里需要具备一点Python编程基础)

  1. 安装requests库,用于url访问。
$ pip install requests

2. 编写python脚本test_api.py。

# -*- coding: utf-8 -*-

import requests

# 定义参数
url = 'http://192.168.214.108:9090'
query_api = '/api/v1/query'
params = 'query=node_load5{instance="192.168.214.108:9100"}'
# 访问prometheus API获取数据
res = requests.get(url + query_api, params)
metrics = res.json().get("data").get("result")
# 判断结果是否为空
if metrics:
    value = metrics[0].get('value')[1]
    print('服务器 192.168.214.108的node_load5值为 %s' % value)
else:
    print('无法获取有效数据')

脚本运行结果:

$ python test_api.py 
服务器 192.168.214.108的node_load5值为 0.01

结语:

本文仅展示了Prometheus API的简单应用,更多的接口使用可参考官方文献:https://prometheus.io/docs/prometheus/latest/querying/api/。

链接:https://mp.weixin.qq.com/s/5dnsMkncMDWj1Q7H02zHRA

(版权归原作者所有,侵删)

微信扫码关注该文公众号作者

戳这里提交新闻线索和高质量文章给我们。
相关阅读
一起见证:Ethereum MergeRecommend somebody to do something是错误说法吗?PromptCLUE:大规模多任务Prompt预训练中文开源模型【明日截单】埃及风机娘HEMET NETHEL,粘土人锦木千束最后预定!依靠1个产品获4240万美元融资,解码人类“黑暗”基因组的nucleome therapeutic是什么来头?Key Highlights From China’s Newly Revised Women’s Protection LawAnother ‘Three-Body’ Animation Wins Praise From Sci-Fi FansThe Publisher Who Rekindled China’s Curiosity About the World威胁救命恩人:我,可以变成农夫怀里的那,条,蛇在 Linux 中使用 Etcher 创建可启动 USB – 下载和使用指南 | Linux 中国A Beijing Theater Is Committed to Screening Movies for the BlindFor Gen-Z, Entrepreneurship Represents a Ticket to Freedom主流监控系统 Prometheus 学习指南美中冲突下,首访Manzanar (多图)九大投行|Deutsche Bank 2023 China Graduate Programme 火热进行中!同样是PM,Product Manager、Program Manager、Project Manager的薪资哪个更高?Gurman:苹果M2 Pro / Max MacBook Pro14/16英寸和Mac Pro新款将于23年Q1发布2022 重返小树林·艺术生活节 Return To The Woods · Art In The NatureThe Chinese Online Slang That Took Over the Internet in 2022Prompt总结 | 从MLM预训任务到Prompt Learning原理解析与Zero-shot分类、NER简单实践凡尔赛本周必buy | David Jones低至6折,THE ICONIC无门槛8折,THE OUTNET全场2折起神经网络高斯过程 (Neural Network Gaussian Process)西行漫记 --- 峡谷之乡(Canyonlands National Park)《西罗普郡一少年》:32: 从黄昏到早晨,从远方Out with the old, in with the new. JuniorCoach is here for youSpringBoot + Prometheus + Grafana 打造可视化监控一条龙!Ousted Luckin Founder Charts Comeback With New Coffee BusinessCombo(i7-9700f/16gram 2666mhz/msi z390-a pro motherboard)CLUE社区最新神器!PromptCLUE:大规模多任务Prompt预训练中文开源模型SpringBoot+Prometheus+Grafana 实现自定义监控如何快速构建Prometheus监控体系,架构、指标、数据、告警… | 极客时间不要写suggest somebody to do somethingWhat Happens When Women Are the Breadwinners?Wu Zetian and the Quest for Feminism in All the Wrong Places
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。