python - 如何从多个子进程公开普罗米修斯指标?

标签 python subprocess prometheus

我有一项服务,当前通过端口 8000 的 prometheus 客户端公开指标。

我想将此进程更改为控制父进程,它为每个“事物”生成一个(独立)子进程,即子进程由 thing_id 参数化,父进程调用 systemctl start child@thing_id

公开的指标是独立于每个“事物”的,因此我仍然想公开每个进程的这些指标,并使用标签 thing 来进行相应的识别和分析。

但是,我似乎必须在每个服务中运行 start_http_server(8000) ,这会由于“端口已在使用中”而出错。我尝试只在父进程中启动服务器,但没有观察到子进程的任何指标。

我可以定义一些端口范围,并为每个进程配备一个 http 服务器,并相应地增加目标数量,但这看起来相当笨重。

我调查过https://github.com/prometheus/client_python/blob/master/prometheus_client/multiprocess.py我相信这可能是一个解决方案,但认为可能有一种更简单的方法,只需使用子处理和 systemctl ...

最佳答案

最后,我使用 prometheus“推送网关”来实现这一目标 - 在每个子服务中创建一个基于作业 ID 进行推送的 GatewayClient。当父服务使用 delete_from_gateway 停止子进程时,它会进行清理。

https://sysadmins.co.za/install-pushgateway-to-expose-metrics-to-prometheus/ 的帮助下安装了推送网关

下面是基本客户端代码

from prometheus_client import push_to_gateway, CollectorRegistry

class GatewayClient:
    def __init__(self, addr, thing_id):
        self.gateway_address = addr
        self.job_id = "thing-{}".format(thing_id)
        self.registry = CollectorRegistry()
        # define metrics etc
        self.some_counter = Counter('some_counter', 'A counter', registry=self.registry)

    async def start(self):
        while True:
            # push latest data
            push_to_gateway(self.gateway_address, job=self.job_id, registry=self.registry
            await asyncio.sleep(15)

    # methods to set metrics etc
    def inc_some_counter(self):
        self.some_counter.inc()

关于python - 如何从多个子进程公开普罗米修斯指标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61785170/

相关文章:

python - 动态创建python函数

函数内的Python多处理: calling pool.映射

python - 如何在进程终止时清理 subprocess.Popen 实例

python - 使用参数启动 gnome 终端

spring-boot - 不能在 Spring Boot 2(版本 2.0.0.M7)中包含 Prometheus 指标

python - 如何动态更改数据框名称

python - 在 Raspberry Pi 上用 Python 包装 Lua 代码

python - 由 python 的子进程启动的进程不存在

kubernetes - 安装了 prometheus-community/helm-charts 但我无法获取 "default"命名空间的指标

amazon-web-services - Prometheus 指标中 post_seconds_count、post_seconds_sum 和 post_seconds_max 的吞吐量计算