LoginSignup
3
9

More than 1 year has passed since last update.

Raspberry Piで計測した温度と湿度をPrometheusでグラフ化

Last updated at Posted at 2018-04-17

はじめに

Raspberry Piで計測した温度・湿度をMuninでグラフ化していたが,
今どきのツールでグラフを見たかったので, Prometheusに移行した.

環境

  • Raspbian 9.1 (stretch)
  • 温度・湿度の計測はUSBRHを使用

設定方法

Prometheusをインストール

Debian系はapt-getでPrometheusとNode exporterをインストール可能なので,
簡単にメトリクスが自動取得されてグラフが見える.

$ sudo apt-get install prometheus
$ systemctl status prometheus
$ systemctl status prometheus-node-exporter

なお, リポジトリにあるPrometheusのバージョンは古い (1系) ため, 新しいバージョン (2系) を使いたい場合は,
Debian sid (不安定版) 用のページなどからパッケージをダウンロードしてくることもできる.

$ wget http://ftp.jp.debian.org/debian/pool/main/p/prometheus/prometheus_2.2.1+ds-2_armhf.deb
$ sudo dpkg -i prometheus_2.2.1+ds-2_armhf.deb

取得状況は, http://IPアドレス:9090 へのアクセスや, curlで確認できる.

$ curl localhost:9100/metrics

ちなみに, Prometheusの設定ファイルは, /etc/prometheus/prometheus.yml にある.

Node exporterを自作

USBRHで計測した温度・湿度をPrometheusに取り込むために,
Node exporterのTextfile collectorを自作する.

node-exporterのオプションは, /etc/default/prometheus-node-exporterで下記のように設定されている.
Textfile collectorのディレクトリは-collector.textfile.directoryオプションで,
/var/lib/prometheus/node-exporterに指定されている.

/etc/default/prometheus-node-exporter
ARGS="-collector.diskstats.ignored-devices=^(ram|loop|fd)\d+$ \
      -collector.filesystem.ignored-mount-points=^/(sys|proc|dev|run)($|/) \
      -collector.textfile.directory=/var/lib/prometheus/node-exporter"

ディレクトリのパーミッションを見ると, オーナーはprometheusで, モードは755となっているが,
他のユーザでも書き込めるようにした方が楽なので, モードは777に変更した.

$ ls -l /var/lib/prometheus
drwxr-xr-x 262 prometheus prometheus 4.0K  yy月 dd hh:mm metrics/
drwxr-xr-x   2 prometheus prometheus 4.0K  yy月 dd hh:mm node-exporter/
$ sudo chmod 777 /var/lib/prometheus/node-exporter

Textfile collectorを自作するには, Prometheus用のライブラリを利用する.
言語はGo, Java, Python, Rubyがあるが, Pythonを利用した.

$ pip install prometheus_client

公式ページなどを参考に下記のように自作した.

usbrh.py
#!/usr/bin/env python

from prometheus_client import CollectorRegistry, Gauge, write_to_textfile
import subprocess

bin = '/usr/local/bin'
lib = '/var/lib/prometheus/node-exporter'

registry = CollectorRegistry()

g = Gauge('usbrh', 'USBRH', ['kind'], registry=registry)
usbrh = subprocess.check_output(bin + '/usbrh').split()

g.labels('temperature').set(usbrh[0])
g.labels('humidity').set(usbrh[1])

write_to_textfile(lib + '/usbrh.prom', registry)

試しに動作確認してみる.

$ ./usbrh.py
$ cat /var/lib/prometheus/node-exporter/usbrh.prom
# HELP usbrh USBRH
# TYPE usbrh gauge
usbrh{kind="humidity"} 46.42
usbrh{kind="temperature"} 26.07
$ curl localhost:9100/metrics

問題なければ, 定期取得するために, スクリプトをcronなどに設定する.

Prometheusで温度・湿度を確認

しばらくしたら, Prometheusで温度・湿度をグラフで見れるようになっている.
Grafanaを使えば、グラフをより見やすくしたり, 簡単にカスタマイズできたりする.

参考

Prometheus

Node exporter

USBRH

3
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
9