Skip to content

Instantly share code, notes, and snippets.

@sourceperl
Last active December 3, 2020 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sourceperl/6485a1d37a86087c49d8c90cf462b773 to your computer and use it in GitHub Desktop.
Save sourceperl/6485a1d37a86087c49d8c90cf462b773 to your computer and use it in GitHub Desktop.
Monitoring Raspberry Pi CPU temp + memory + a docker volume size to influxdb series
#!/usr/bin/env python3
import logging
import os
import sys
import time
import traceback
import influxdb
# logging setup
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.ERROR)
# db setup
db = influxdb.InfluxDBClient(host="172.18.0.3", port=8086, database='mydb')
while True:
# list of points to write in db
points_l = list()
# CPU temperature
try:
with open('/sys/class/thermal/thermal_zone0/temp', 'r') as f:
cpu_temp = float(f.read()) / 1000
points_l.append(dict(measurement='rpi', tags=dict(tag='cpu_temp'), fields=dict(value=cpu_temp)))
except Exception:
logging.error(traceback.format_exc())
# memory usage
try:
m_total, m_used, m_free = map(float, os.popen('free -t -m').readlines()[-1].split()[1:])
points_l.append(dict(measurement='rpi', tags=dict(tag='mem_total'), fields=dict(value=m_total)))
points_l.append(dict(measurement='rpi', tags=dict(tag='mem_used'), fields=dict(value=m_used)))
points_l.append(dict(measurement='rpi', tags=dict(tag='mem_free'), fields=dict(value=m_free)))
except Exception:
logging.error(traceback.format_exc())
# db volume usage
try:
db_size = float(os.popen('sudo du -sm /var/lib/docker/volumes/influxdb-data/_data/data/mydb').readlines()[-1].split()[0])
points_l.append(dict(measurement='rpi', tags=dict(tag='db_size'), fields=dict(value=db_size)))
except Exception:
logging.error(traceback.format_exc())
# db write
try:
if points_l:
db.write_points(points_l)
except Exception:
logging.error(traceback.format_exc())
time.sleep(60.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment