Prometheus使用Pushgateway推送数据

Pushgateway简介

Prometheus 的 Pushgateway 是一个简单的 HTTP 服务器,它允许数据被推送到该服务器,而不是通过拉取的方式获取。它的存在是为了让临时和批处理作业能够将其指标暴露给 Prometheus。由于这类作业可能存在的时长不足以被主动抓取,因此它们可以将指标推送到 Pushgateway。随后,Pushgateway 会将这些指标暴露给 Prometheus。

Pushgateway 作为中间件,保存推送的数据直到 Prometheus 抓取。它支持从多个来源推送指标,每个来源都通过唯一的 job 标签来标识,并且可以选择性地附加额外的标签

Pushgateway GitHub 地址:https://github.com/prometheus/pushgateway

安装

要安装 Pushgateway,你可以下载二进制包或使用包管理器,但更推荐使用 Docker。你可以在任何机器上安装 Pushgateway,通常只需要一台 Pushgateway 服务器即可处理来自所有来源的指标。以下是使用 Docker 设置 Pushgateway 的方法:

shell 复制代码
docker pull prom/pushgateway

docker run -d -p 9091:9091 prom/pushgateway

向 Pushgateway 推送指标

向 Pushgateway 推送指标时,你可以使用 curl 命令行工具或者开发自定义应用程序发送 HTTP 请求。此外,还有适用于多种编程语言的第三方库,可简化向 Pushgateway 发送指标的过程。

使用 curl

以下是一个向 Pushgateway 推送单个指标的例子:

shell 复制代码
curl -X POST http://{pushgateway_server}:{port}/metrics/job/myjob/instance/myinstance \
     --data 'my_metric{label="value"} 1.0'

此命令推送了一个名为 my_metric 的指标,其值为 1.0 并带有一个 label 设置为 value 的标签。

使用第三方库

有若干第三方库可以帮助你将 Pushgateway 的功能整合到你的应用程序中。这些库提供了一个更高层次的 API 来发送指标,使得与 Pushgateway 的交互更加容易管理。

例如,在 Python 中,你可以使用 prometheus_client 库,下面是一段实现代码:

python 复制代码
import csv
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

class PrometheusPusher:
    def __init__(self, metric_name: str, description: str, job_name: str, pushgateway_url: str = 'localhost:9091'):
        """
        Initialize an instance of PrometheusPusher.
        
        :param metric_name: The name of the metric.
        :param description: A description of the metric.
        :param job_name: Job name used to identify the source.
        :param pushgateway_url: URL of the Pushgateway service, default is localhost:9091.
        """
        self.metric_name = metric_name
        self.description = description
        self.job_name = job_name
        self.pushgateway_url = pushgateway_url
        self.registry = CollectorRegistry()
        self.gauge = None

    def create_gauge(self, label_names: list):
        """
        Create a gauge metric with labels.
        
        :param label_names: List of label names.
        """
        self.gauge = Gauge(self.metric_name, self.description, label_names, registry=self.registry)
    
    def push_metrics(self, label_values: list):
        """
        Push the metric value to the Pushgateway.
        
        :param label_values: List of label values.
        """
        if not self.gauge:
            print('Error: Gauge is not created')
            return
        self.gauge.labels(*label_values).set(1)
        try:
            push_to_gateway(self.pushgateway_url, job=self.job_name, registry=self.registry)
            print(f'Successfully pushed metrics for {label_values}')
        except Exception as e:
            print(f'Failed to push metrics for {label_values}. Error: {e}')
    
    def push_metrics_from_csv(self, csv_file_path: str):
        """
        Read data from a CSV file and push metrics.
        
        :param csv_file_path: Path to the CSV file.
        """
        with open(csv_file_path, mode='r') as file:
            reader = csv.reader(file)
            # Get the label names (first row)
            label_names = next(reader)
            self.create_gauge(label_names)
            for row in reader:
                if len(row) != len(label_names):
                    print(f"Warning: Ignoring row with incorrect number of columns: {row}")
                    continue
                self.push_metrics(row)

# Example CSV file format:
# label1, label2
# value1, value2
# ...

# Main entry point
if __name__ == '__main__':
    # Set CSV file path and other parameters
    csv_file_path = 'example_data.csv'
    metric_name = 'example_metric'
    description = 'An example metric for demonstration purposes.'
    job_name = "example_job"
    pushgateway_url = 'slcx-grafana.calix.local:9091'

    # Create an instance of PrometheusPusher and push data from CSV file
    pusher = PrometheusPusher(metric_name, description, job_name, pushgateway_url)
    pusher.push_metrics_from_csv(csv_file_path)
相关推荐
码农小卡拉10 小时前
Prometheus 监控 SpringBoot 应用完整教程
spring boot·后端·grafana·prometheus
牛奶咖啡1310 小时前
Prometheus+Grafana构建云原生分布式监控系统(十五)_Prometheus中PromQL使用(二)
云原生·prometheus·集合运算·对查询结果排序·直方图原理·统计掉线的实例·检查节点或指标是否存在
牛奶咖啡131 天前
Prometheus+Grafana构建云原生分布式监控系统(十四)_Prometheus中PromQL使用(一)
云原生·prometheus·promql·计算一个时间范围内的平均值·将相同数据整合查看整体趋势·计算时间范围内的最大最小比率·向量标量的算术运算
牛奶咖啡132 天前
Prometheus+Grafana构建云原生分布式监控系统(十三)_Prometheus数据模型及其PromQL
云原生·prometheus·prometheus数据类型·promql使用场景·promql表达式解析·promql数据类型·监控系统的方法论与指标
AC赳赳老秦3 天前
外文文献精读:DeepSeek翻译并解析顶会论文核心技术要点
前端·flutter·zookeeper·自动化·rabbitmq·prometheus·deepseek
牛奶咖啡135 天前
Prometheus+Grafana构建云原生分布式监控系统(十二)_基于DNS的服务发现
云原生·prometheus·dns·搭建自己的dns服务器·使用bind搭建dns服务器·配置正向解析·基于dns的服务发现
A-刘晨阳5 天前
Prometheus + Grafana + Alertmanager 实现邮件监控告警及配置告警信息
运维·云计算·grafana·prometheus·监控·邮件
饺子大魔王的男人5 天前
告别服务器失联!Prometheus+Alertmanager+cpolar 让监控告警不局限于内网
运维·服务器·prometheus
牛奶咖啡137 天前
Prometheus+Grafana构建云原生分布式监控系统(十一)_基于consul的服务发现
云原生·prometheus·consul的安装部署·consul服务自动发现·consul服务的注册删除·consul服务的更新·实现自动去consul注册服务
Otto_10277 天前
在 OpenStack Rocky 中部署 Prometheus + Grafana
openstack·grafana·prometheus