使用 Python 和 Prometheus 跟蹤天氣

建立自定義 Prometheus 集成以跟蹤最大的雲端提供商:地球母親。python

Tree clouds
Tree clouds

開源監控系統 Prometheus 集成了跟蹤多種類型的時間序列數據,但若是沒有集成你想要的數據,那麼很容易構建一個。一個常常使用的例子使用雲端提供商的自定義集成,它使用提供商的 API 抓取特定的指標。可是,在這個例子中,咱們將與最大雲端提供商集成:地球。linux

幸運的是,美國政府已經測量了天氣併爲集成提供了一個簡單的 API。獲取紅帽總部下一個小時的天氣預報很簡單。git

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 庫中的 gauge 建立一個註冊項:紅帽總部的溫度。github

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

第一種是一般建議的狀況,若是可能的話,咱們須要構建一個公開註冊入口的 Web 服務器,並配置 Prometheus 收刮(scrape)它。json

咱們可使用 Pyramid 構建一個簡單的 Web 服務器。api

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)服務器運行。例如,假設咱們將代碼放在 earth.py 中,咱們可使用 python -m twisted web --wsgi earth.app 來運行它。bash

或者,若是咱們的代碼鏈接到 Prometheus 更容易,咱們能夠按期將其推送到 Prometheus 的推送網關服務器

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 是推送網關的 URL。它一般以 :9091 結尾。網絡

祝你構建自定義 Prometheus 集成成功,以便跟蹤一切!


via: opensource.com/article/19/…

做者:Moshe Zadka 選題:lujun9972 譯者:geekpi 校對:wxy

本文由 LCTT 原創編譯,Linux中國 榮譽推出

相關文章
相關標籤/搜索