1
0

main.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import time
  2. import datetime
  3. import os
  4. import sys
  5. import logging
  6. from enum import Enum
  7. from influxdb_client import InfluxDBClient, Point
  8. from influxdb_client.client.write_api import SYNCHRONOUS
  9. from pihole import PiHole
  10. logger = logging.Logger('pihole-to-influxdb')
  11. logger.addHandler(logging.StreamHandler(sys.stdout))
  12. class AppMode(Enum):
  13. Live = 1
  14. Totals = 2
  15. Raw = 3
  16. try:
  17. # optional Logger Settings
  18. logging.basicConfig(level=os.getenv("LOG_LEVEL", "DEBUG"))
  19. # InfluxDB Settings
  20. DB_URL = os.environ['INFLUX_DB_URL']
  21. DB_ORG = os.environ['INFLUX_DB_ORG']
  22. DB_TOKEN = os.environ['INFLUX_DB_TOKEN']
  23. DB_BUCKET = os.environ['INFLUX_DB_BUCKET']
  24. # PiHole Settings
  25. PIHOLE_URL = str(os.environ['PIHOLE_URL'])
  26. QUERY_INTERVAL = int(os.environ['PIHOLE_INTERVAL'])
  27. # optional Pi-hole authentication
  28. AUTHENTICATION_TOKEN = os.getenv('PIHOLE_AUTHENTICATION', None)
  29. except KeyError as e:
  30. logger.fatal('Missing environment variable: {}'.format(e))
  31. sys.exit(1)
  32. try:
  33. # optional App Mode
  34. APP_MODE = AppMode[os.getenv('APP_MODE', 'Totals')]
  35. except KeyError as e:
  36. logger.fatal('{} is not a valid AppMode'.format(e))
  37. sys.exit(1)
  38. if APP_MODE != AppMode.Totals and not AUTHENTICATION_TOKEN:
  39. logger.fatal('Pi-hole authentication token is required for live data')
  40. sys.exit(1)
  41. influxdb_client = InfluxDBClient(DB_URL, DB_TOKEN, org=DB_ORG)
  42. pihole = PiHole(PIHOLE_URL, AUTHENTICATION_TOKEN)
  43. def main():
  44. write_api = influxdb_client.write_api(write_options=SYNCHRONOUS)
  45. next_update = time.monotonic()
  46. logger.info('Starting PiHole Data Logger to InfluxDB')
  47. logger.info('AppMode: {}'.format(APP_MODE.name))
  48. # Test Pi-hole connection
  49. try:
  50. pihole.request_summary()
  51. except Exception as e:
  52. logger.fatal('Unable to connect to Pi-hole: {}'.format(e))
  53. sys.exit(1)
  54. while True:
  55. try:
  56. if APP_MODE == AppMode.Live:
  57. timestamp = datetime.datetime.now()
  58. data = list(pihole.get_queries_for_influxdb(timestamp, QUERY_INTERVAL))
  59. elif APP_MODE == AppMode.Totals:
  60. data = list(pihole.get_totals_for_influxdb())
  61. elif APP_MODE == AppMode.Raw:
  62. data = list(pihole.get_query_logs_for_influxdb())
  63. logger.debug('Writing {} points to InfluxDB'.format(len(data)))
  64. write_api.write(bucket=DB_BUCKET, record=data)
  65. sleep_duration = QUERY_INTERVAL
  66. except Exception as e:
  67. logger.exception('Failed to get data from Pi-Hole to InfluxDB')
  68. # Sleep at most two minutes
  69. sleep_duration = min(QUERY_INTERVAL, 120)
  70. next_update = next_update + sleep_duration
  71. logger.debug("Now sleeping for {}".format(datetime.timedelta(seconds=sleep_duration)))
  72. time.sleep(max(0, next_update - time.monotonic()))
  73. if __name__ == '__main__':
  74. main()