前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Prometheus 二次开发之 API 接口

Prometheus 二次开发之 API 接口

作者头像
我是阳明
发布2021-05-17 14:56:38
6K0
发布2021-05-17 14:56:38
举报
文章被收录于专栏:k8s技术圈

Prometheus在/api/v1的路径下开放了HTTP接口,用户可以通过这些接口进行二次开发。这篇笔记挑选了此次监控平台可能会用到的接口进行解析。

1请求&响应格式

1.JSON响应格式

以JSON格式进行响应。若API请求成功 返回一个2xx的状态码。若请求失败,分情况返回以下状态码:

  • 400 Bad Request 参数丢失或不正确;
  • 422 Unprocessable Entity无法执行表达式时;
  • 503 Service Unavailable 查询超时或中止时。

响应JSON内容如下:

代码语言:javascript
复制
{
  "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>"]
}

2.时间戳格式

输出中的时间戳为以秒为单位的Unix时间戳,故若请求中有时间戳,推荐使用以秒为单位的Unix时间戳。

3.其他格式

可以重复查询的参数名称应用[]为后缀。

<series_selector>占位符指Prometheus的时间序列选择器,例如http_requests_total或http_requests_totalmethod=~"(GETPOST)"并且需要进行URL编码。

占位符指Prometheus持续时间字符串。[0-9]+[smhdwy]。例如,5m指持续时间为5分钟。

占位符指布尔值(字符串true和false)。

2表达式查询

用户可以通过接口使用promQL查询瞬时或某一个时间段的值,

1.瞬时查询

url地址:

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

URL查询参数:

  • query= Prometheus表达式查询字符串,必选。t ime=<rfc3339 | unix_timestamp> *查询的时间戳,可选。
  • timeout=*超时时间,可选。默认为启动参数-query.timeout标志的值,并由该标志的值限制。

如果time参数未填写,则使用当前服务器时间。

使用POST方法和 Content-Type: application/x-www-form-urlencoded 标头直接在请求正文中对这些参数进行URL编码。返回结果格式:

代码语言:javascript
复制
{
  "resultType": "matrix" | "vector" | "scalar" | "string",
  "result": <value>
}

示例1:查询Prometheus自带metric

代码语言:javascript
复制
$ curl 'http://localhost:9090/api/v1/query?query=up
{
   "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" ]
         }
      ]
   }
}

示例2:使用promQL查询

代码语言:javascript
复制
$ curl 'http://localhost:9090/api/v1/query?query=sum(time() - node_boot_time_seconds)
{
   "status": "success",
   "data":    {
      "resultType": "vector",
      "result": [      {
         "metric": {},
         "value":          [
            1.581498526305E9,
            "6767484.305000067"
         ]
      }]
   }
}

2.范围查询

ur地址:

  • GET /api/v1/query_range
  • POST /api/v1/query_range

URL查询参数:

  • query=*Prometheus表达式查询字符串,必选。
  • start=<rfc3339 | unix_timestamp>*开始时间戳,必选。
  • end=<rfc3339 | unix_timestamp>*结束时间戳,必选。
  • step=<duration | float>*以持续时间格式或秒数查询步长。
  • timeout=*超时时间,可选。默认为启动参数-query.timeout标志的值,并由该标志的值限制

返回结果可能有以下字段:

代码语言:javascript
复制
{
  "resultType": "matrix",
  "result": <value>
}

示例1:

代码语言:javascript
复制
$ curl 'http://localhost:9090/api/v1/query_range?query=up&start=2015-07-01T20:10:30.781Z&end=2015-07-01T20:11:00.781Z&step=15s'
{
   "status" : "success",
   "data" : {
      "resultType" : "matrix",
      "result" : [
         {
            "metric" : {
               "__name__" : "up",
               "job" : "prometheus",
               "instance" : "localhost:9090"
            },
            "values" : [
               [ 1435781430.781, "1" ],
               [ 1435781445.781, "1" ],
               [ 1435781460.781, "1" ]
            ]
         },
         {
            "metric" : {
               "__name__" : "up",
               "job" : "node",
               "instance" : "localhost:9091"
            },
            "values" : [
               [ 1435781430.781, "0" ],
               [ 1435781445.781, "0" ],
               [ 1435781460.781, "1" ]
            ]
         }
      ]
   }
}

3统计Prometheus全局配置

查询Prometheus所监控的目标端、rules等,主要用作全局配置

1. 查询target

返回Prometheus所监控的目标端的当前状态的概述。

URL地址:

  • GET /api/v1/targets

默认会返回所有的端点,包括当前检测端点和已经删除的端点。其中

  • labels 表示通过Prometheus配置文件重新贴标签后的标签集;
  • discoveredLabels 表示重新标记前的未修改标签。

例如:

代码语言:javascript
复制
$ curl http://localhost:9090/api/v1/targets
{
  "status": "success",
  "data": {
    "activeTargets": [
      {
        "discoveredLabels": {
          "__address__": "127.0.0.1:9090",
          "__metrics_path__": "/metrics",
          "__scheme__": "http",
          "job": "prometheus"
        },
        "labels": {
          "instance": "127.0.0.1:9090",
          "job": "prometheus"
        },
        "scrapePool": "prometheus",
        "scrapeUrl": "http://127.0.0.1:9090/metrics",
        "lastError": "",
        "lastScrape": "2017-01-17T15:07:44.723715405+01:00",
        "lastScrapeDuration": 0.050688943,
        "health": "up"
      }
    ],
    "droppedTargets": [
      {
        "discoveredLabels": {
          "__address__": "127.0.0.1:9100",
          "__metrics_path__": "/metrics",
          "__scheme__": "http",
          "job": "node"
        }
      }
    ]
  }
}

可以看到Prometheus将监控的target节点以json的格式返回,我们可以通过处理Json数据来统计当前处于各种状态的主机数量。

prometheuse还提供了state查询参数,用来过滤target state可以选填 state=active,state=dropped,state=any

例如:

代码语言:javascript
复制
$ curl 'http://localhost:9090/api/v1/targets?state=active'
{
  "status": "success",
  "data": {
    "activeTargets": [
      {
        "discoveredLabels": {
          "__address__": "127.0.0.1:9090",
          "__metrics_path__": "/metrics",
          "__scheme__": "http",
          "job": "prometheus"
        },
        "labels": {
          "instance": "127.0.0.1:9090",
          "job": "prometheus"
        },
        "scrapePool": "prometheus",
        "scrapeUrl": "http://127.0.0.1:9090/metrics",
        "lastError": "",
        "lastScrape": "2017-01-17T15:07:44.723715405+01:00",
        "lastScrapeDuration": 50688943,
        "health": "up"
      }
    ],
    "droppedTargets": []
  }
}

2. 查询规则

该接口返回告警并记录当前配置生效的规则列表,此外,还返回当前活动的告警实例;

URL地址:

  • GET /api/v1/rules

URL查询参数 - type=alert|record::仅返回警报规则(例如type=alert)或记录规则(例如type=record)。如果该参数不存在或为空,则不执行任何过滤。

代码语言:javascript
复制
$ curl http://localhost:9090/api/v1/rules
{
    "data": {
        "groups": [
            {
                "rules": [
                    {
                        "alerts": [
                            {
                                "activeAt": "2018-07-04T20:27:12.60602144+02:00",
                                "annotations": {
                                    "summary": "High request latency"
                                },
                                "labels": {
                                    "alertname": "HighRequestLatency",
                                    "severity": "page"
                                },
                                "state": "firing",
                                "value": "1e+00"
                            }
                        ],
                        "annotations": {
                            "summary": "High request latency"
                        },
                        "duration": 600,
                        "health": "ok",
                        "labels": {
                            "severity": "page"
                        },
                        "name": "HighRequestLatency",
                        "query": "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
                        "type": "alerting"
                    },
                    {
                        "health": "ok",
                        "name": "job:http_inprogress_requests:sum",
                        "query": "sum(http_inprogress_requests) by (job)",
                        "type": "recording"
                    }
                ],
                "file": "/rules.yaml",
                "interval": 60,
                "name": "example"
            }
        ]
    },
    "status": "success"
}

可以看到这个接口会返回告警信息,所以这个接口也可以用来获取当前告警。

3. 查询告警

/alerts 路径返回所有活动警报的列表。

URL地址:

  • GET /api/v1/alerts
代码语言:javascript
复制
$ curl http://localhost:9090/api/v1/alerts
{
    "data": {
        "alerts": [
            {
                "activeAt": "2018-07-04T20:27:12.60602144+02:00",
                "annotations": {},
                "labels": {
                    "alertname": "my-alert"
                },
                "state": "firing",
                "value": "1e+00"
            }
        ]
    },
    "status": "success"
}

此处返回告警信息,需要注意的是返回信息中的标签字段返回的是rules中配置的标签值,如果要根据对metrics的标签进行告警的区分还需要通过其他手段来获取。

4查询元数据

1.按标签查询匹配

URL地址:

  • GET /api/v1/series
  • POST /api/v1/series

URL查询参数:

  • match[]=<series_selector>:必填,标签选择器。
  • start=<rfc3339 | unix_timestamp>*启动时间戳。
  • end=<rfc3339 | unix_timestamp>*结束时间戳。

返回结果的data部分由匹配到的标签名称/值对的对象列表组成。以下示例返回与选择器up或匹配的所有系列 process_start_time_seconds{job=“prometheus”}

代码语言:javascript
复制
$ curl -g 'http://localhost:9090/api/v1/series?' --data-urlencode 'match[]=up' --data-urlencode 'match[]=process_start_time_seconds{job="prometheus"}'
{
   "status" : "success",
   "data" : [
      {
         "__name__" : "up",
         "job" : "prometheus",
         "instance" : "localhost:9090"
      },
      {
         "__name__" : "up",
         "job" : "node",
         "instance" : "localhost:9091"
      },
      {
         "__name__" : "process_start_time_seconds",
         "job" : "prometheus",
         "instance" : "localhost:9090"
      }
   ]
}

原文链接:https://blog.csdn.net/weixin_44723434/article/details/104282636

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-05-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 k8s技术圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1请求&响应格式
  • 2表达式查询
  • 3统计Prometheus全局配置
  • 4查询元数据
相关产品与服务
Prometheus 监控服务
Prometheus 监控服务(TencentCloud Managed Service for Prometheus,TMP)是基于开源 Prometheus 构建的高可用、全托管的服务,与腾讯云容器服务(TKE)高度集成,兼容开源生态丰富多样的应用组件,结合腾讯云可观测平台-告警管理和 Prometheus Alertmanager 能力,为您提供免搭建的高效运维能力,减少开发及运维成本。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档