使用 Python 和 Prometheus 跟踪天气

创建一个自定义的 Prometheus 集成,以跟踪最大的云提供商:地球母亲。
164 位读者喜欢这篇文章。
14 facts about OpenStack Newton

Pixabay。 Opensource.com 修改。 CC BY-SA 4.0

开源监控系统 Prometheus 具有集成功能,可以跟踪多种类型的时间序列数据,但是如果您想要一个尚不存在的集成,则很容易构建一个。 一个常用的例子是与云提供商的自定义集成,该集成使用提供商的 API 来获取特定指标。 但是,在此示例中,我们将与最大的云提供商:地球集成。

幸运的是,美国政府已经测量了天气,并提供了一个易于集成的 API。 获取 Red Hat 总部接下来一小时的天气预报很简单。

import requests
HOURLY_RED_HAT = "https://api.weather.gov/gridpoints/RAH/73,57/forecast/hourly"
def get_temperature():
    result = requests.get(HOURLY_RED_HAT)
    return result.json()["properties"]["periods"][0]["temperature"]

既然我们与地球的集成已经完成,就该确保 Prometheus 可以理解我们在说什么了。 我们可以使用 Prometheus Python 库 创建一个注册表,其中包含一个计量器:Red Hat 总部的温度。

from prometheus_client import CollectorRegistry, Gauge
def prometheus_temperature(num):
    registry = CollectorRegistry()
    g = Gauge("red_hat_temp", "Temperature at Red Hat HQ", registry=registry)
    g.set(num)
    return registry

最后,我们需要以某种方式将其连接到 Prometheus。 这在某种程度上取决于 Prometheus 的网络拓扑:是 Prometheus 与我们的服务通信更容易,还是反过来更容易。

如果可能,通常建议使用第一种情况,因此我们需要构建一个 Web 服务器来公开注册表,然后配置 Prometheus 来抓取它。

我们可以使用 Pyramid 构建一个简单的 Web 服务器。

from pyramid.config import Configurator
from pyramid.response import Response
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST
def metrics_web(request):
    registry = prometheus_temperature(get_temperature())
    return Response(generate_latest(registry),
                    content_type=CONTENT_TYPE_LATEST)
config = Configurator()
config.add_route('metrics', '/metrics')
config.add_view(metrics_web, route_name='metrics')
app = config.make_wsgi_app()

这可以使用任何 Web 服务器网关接口 (WSGI) 服务器运行。 例如,我们可以使用 python -m twisted web --wsgi earth.app 运行它,假设我们将代码放在 earth.py 中。

或者,如果我们的代码更容易连接到 Prometheus,我们可以定期将其推送到 Prometheus 的 Push gateway

import time
from prometheus_client import push_to_gateway
def push_temperature(url):
    while True:
        registry = prometheus_temperature(get_temperature())
        push_to_gateway(url, "temperature collector", registry)
        time.sleep(60*60)

该 URL 是 Push gateway 的 URL;它通常以 :9091 结尾。

祝您成功构建自己的自定义 Prometheus 集成,以便您可以跟踪所有内容!

标签
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
自 1998 年以来,Moshe 一直参与 Linux 社区,帮助 Linux“安装聚会”。 自 1999 年以来,他一直在编写 Python 程序,并为核心 Python 解释器做出了贡献。 Moshe 自从这些术语出现之前就已经是一名 DevOps/SRE,非常关心软件的可靠性、构建的可重复性以及其他此类事情。

1 条评论

这是一段很好的代码。

Creative Commons License本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。
© . All rights reserved.