Pushgatewayの概要
Pushgatewayとは
PushgatewayはPrometheusエコシステムに含まれるコンポーネントで、通常PrometheusがExporterからpull(取得)方式でメトリクスを収集するのに対し、Pushgatewayは外部スクリプトやジョブがpush(送信)方式でメトリクスを送り込むための中継ポイントとして機能します。これにより、一時的なバッチジョブやファイアウォール越しの監視対象など、Pullが困難なケースでも監視が可能になります。
利点
- Prometheusが直接アクセスできない環境(例:NAT内、ファイアウォール制限下)にあるターゲットのメトリクスを収集できる
- 複数のソースから集約されたカスタムメトリクスを一元的にPushgatewayに送信し、Prometheusがそこから一括取得可能
欠点
- PrometheusはPushgateway自体の健全性しか確認できず、個別のターゲットの状態までは把握できない
- Pushgatewayがダウンすると、その時点で保持されているすべてのメトリクスが失われる可能性がある
- ターゲットが終了しても古いメトリクスが残り続けるため、手動での削除が必要になる場合がある
テスト環境
| IPアドレス | ホスト名 |
|---|---|
| 192.168.2.139 | master1 |
| 192.168.40.140 | node1 |
インストールと設定
Pushgatewayのデプロイ
node1上で以下のDockerコマンドを実行:
docker pull prom/pushgateway
docker run -d --name pushgateway -p 9091:9091 prom/pushgateway
ブラウザで http://192.168.40.140:9091 にアクセスし、UIが表示されることを確認。
Prometheusへの統合
Prometheusの設定ファイル(例: prometheus-cfg.yaml)に以下ジョブを追加:
- job_name: 'pushgateway'
scrape_interval: 5s
honor_labels: true
static_configs:
- targets: ['192.168.40.140:9091']
設定を適用するためにKubernetesリソースを再デプロイ:
kubectl apply -f prometheus-alertmanager-cfg.yaml
kubectl delete -f prometheus-alertmanager-deploy.yaml
kubectl apply -f prometheus-alertmanager-deploy.yaml
Prometheus UI(例: http://192.168.2.139:30242/targets)でPushgatewayが正常にスクレイピングされていることを確認。
メトリクスの送信方法
単純なメトリクスの送信
echo "custom_metric 3.6" | curl --data-binary @- http://192.168.40.140:9091/metrics/job/test_job
このコマンドは、job="test_job" というラベルを持つグループに custom_metric というGaugeメトリクスを送信します。
複雑なメトリクスの送信
cat <<EOF | curl --data-binary @- http://192.168.40.140:9091/metrics/job/test_job/instance/test_instance
# TYPE memory_usage gauge
memory_usage 26
# TYPE total_memory_bytes gauge
total_memory_bytes 26000
EOF
URLパスの構造:
/metrics/job/<job_name>:Prometheus側で識別されるジョブ名/instance/<instance_name>:該当メトリクスに付与されるinstanceラベルの値
データの削除
# 特定インスタンスの全メトリクスを削除
curl -X DELETE http://192.168.40.140:9091/metrics/job/test_job/instance/test_instance
# ジョブ全体のメトリクスを削除
curl -X DELETE http://192.168.40.140:9091/metrics/job/test_job
Pythonクライアントによる送信
prometheus_clientライブラリを使用した例:
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
registry = CollectorRegistry()
request_counter = Gauge(
'http_requests_total',
'Total HTTP requests',
['status', 'method', 'endpoint'],
registry=registry
)
response_time = Gauge(
'http_response_time_seconds',
'Average response time over last minute',
['status', 'method', 'endpoint'],
registry=registry
)
request_counter.labels('200', 'GET', '/api/v1/data').set(42)
response_time.labels('200', 'GET', '/api/v1/data').set(0.85)
push_to_gateway('192.168.40.140:9091', job='BatchJobMetrics', registry=registry)
このスクリプトは、HTTPリクエスト数と平均応答時間をPushgatewayに送信します。ジョブ名は BatchJobMetrics として登録されます。