🐙
InfluxDB + Grafanaで時系列データを可視化するサンプル
目的: 時系列データ監視用のdashboradを作る
登場人物
- influxdb: 時系列データ用のDB
- grafana: 色んな情報ソースを表示できるdashboard
setup
docker-composeを使える前提 (macの場合は権限の問題でdocker for macを使う collimaではダメ)
docker-compose.yml
services:
influxdb:
image: influxdb:latest
container_name: influxdb-local
volumes:
- ./docker/influxdb2/data:/var/lib/influxdb2
- ./docker/influxdb2/config:/etc/influxdb2
ports:
- 8086:8086
environment:
- DOCKER_INFLUXDB_INIT_MODE=setup
- DOCKER_INFLUXDB_INIT_USERNAME=admin
- DOCKER_INFLUXDB_INIT_PASSWORD=password
- DOCKER_INFLUXDB_INIT_ORG=organization
- DOCKER_INFLUXDB_INIT_BUCKET=bucket
grafana:
image: grafana/grafana-oss:9.5.5
container_name: grafana-local
ports:
- 8085:3000
user: "472"
volumes:
- ./docker/grafana/data:/var/lib/grafana
depends_on:
- influxdb
environment:
- GF_SERVER_ROOT_URL=http://localhost:8085
- GF_SECURITY_ADMIN_PASSWORD=admin
docker-compose up -d
ブラウザで確認
influxdb: http://localhost:8086/
user: admin
password: password
grafana: http://localhost:8085/
user: admin
password: admin
influx dbでのtokenの取得
api tokenからtokenを生成。今後influx dbのアクセスはこのトークンを使う
pythonでinflux dbへランダム時系列を書き込む
取得したトークンをtoken ="xxxx"に上書きする
write_random_data.py
import time
import random
from influxdb_client import InfluxDBClient, Point, WritePrecision
# ==============================
# ▼ 必要に応じて書き換えてください
# ==============================
url = "http://localhost:8086" # InfluxDBのURL
token = "xxxx" # 取得したトークン
org = "organization" # DOCKER_INFLUXDB_INIT_ORG と同じ
bucket = "bucket" # DOCKER_INFLUXDB_INIT_BUCKET と同じ
# ==============================
# クライアント作成
# ==============================
client = InfluxDBClient(url=url, token=token, org=org)
write_api = client.write_api()
try:
while True:
# ランダム値生成 (0 ~ 100 の範囲)
value = random.uniform(0, 100)
# Measurement 名を "random_measure" とし、tag に host=server01 を付与
# Time は省略すると自動で書き込み時刻になる
point = (
Point("random_measure")
.tag("host", "server01")
.field("value", value)
.time(int(time.time_ns()), WritePrecision.NS)
)
# バケット、Org を指定して書き込み
write_api.write(bucket=bucket, org=org, record=point)
print(f"Write value={value:.3f} to InfluxDB")
time.sleep(3)
except KeyboardInterrupt:
print("Stopped by Ctrl+C")
finally:
client.close()
grafanaで連携
情報ソースとしてinfluxdbを指定
今回のバージョンだとconnect dataから
以下を設定する
- qery language: Flux (InfluxDB 2.x なので Flux が標準推奨)
- url (influxdbを指す)
- Auth: 不要 下にあるtokenで認証するから
- organization: docker-compose中で指定したもの 今回はorganization
- token: influxdbで生成したtoken
grafanaでクエリの作成
from(bucket: "bucket")
|> range(start: -15m) // 過去15分間のデータを参照
|> filter(fn: (r) => r._measurement == "random_measure" and r._field == "value")
|> filter(fn: (r) => r.host == "server01")
|> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
|> yield(name: "mean")
以上!
Discussion