main.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import time
  2. import datetime
  3. import os
  4. import sys
  5. import logging
  6. from influxdb_client import InfluxDBClient, Point
  7. from influxdb_client.client.write_api import SYNCHRONOUS
  8. from pihole import PiHole
  9. logger = logging.Logger('pihole-to-influxdb')
  10. logger.addHandler(logging.StreamHandler(sys.stdout))
  11. try:
  12. # optional Logger Settings
  13. logging.basicConfig(level=os.getenv("LOGLEVEL", "DEBUG"))
  14. # InfluxDB Settings
  15. DB_URL = os.environ['INFLUX_DB_URL']
  16. DB_ORG = os.environ['INFLUX_DB_ORG']
  17. DB_TOKEN = os.environ['INFLUX_DB_TOKEN']
  18. DB_BUCKET = os.environ['INFLUX_DB_BUCKET']
  19. # PiHole Settings
  20. PIHOLE_HOSTNAME = str(os.environ['PIHOLE_HOSTNAME'])
  21. QUERY_LIVE = bool(os.getenv('PIHOLE_QUERY_LIVE', True))
  22. QUERY_INTERVAL = int(os.environ['PIHOLE_INTERVAL'])
  23. # optional Pi-hole authentication
  24. AUTHENTICATION_TOKEN = os.getenv('PIHOLE_AUTHENTICATION', None)
  25. except KeyError as e:
  26. logger.fatal('Missing environment variable: {}'.format(e))
  27. sys.exit(1)
  28. influxdb_client = InfluxDBClient(DB_URL, DB_TOKEN, org=DB_ORG)
  29. pihole = PiHole(PIHOLE_HOSTNAME, AUTHENTICATION_TOKEN)
  30. class Auth(object):
  31. def __init__(self, token):
  32. # PiHole's web token is just a double sha256 hash of the utf8 encoded password
  33. self.token = token
  34. self.auth_timestamp = time.time()
  35. def main():
  36. write_api = influxdb_client.write_api(write_options=SYNCHRONOUS)
  37. next_update = time.monotonic()
  38. while True:
  39. try:
  40. timestamp = datetime.datetime.now()
  41. if QUERY_LIVE:
  42. data = list(pihole.get_queries_for_influxdb(timestamp, QUERY_INTERVAL))
  43. else:
  44. data = list(pihole.get_totals_for_influxdb())
  45. logger.debug('Writing {} points to InfluxDB'.format(len(data)))
  46. write_api.write(bucket=DB_BUCKET, record=data)
  47. sleep_duration = QUERY_INTERVAL
  48. except Exception as e:
  49. logger.exception('Failed to get data from Pi-Hole to InfluxDB')
  50. # Sleep at most two minutes
  51. sleep_duration = min(QUERY_INTERVAL, 120)
  52. next_update = next_update + sleep_duration
  53. logger.debug("Now sleeping for {}".format(datetime.timedelta(seconds=sleep_duration)))
  54. time.sleep(max(0, next_update - time.monotonic()))
  55. if __name__ == '__main__':
  56. logger.info('PiHole Data Logger to InfluxDB')
  57. main()