zabbix_telemetry.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import os
  2. import time
  3. import pymysql
  4. from snmp_notifier import notifier
  5. def get_db_connection():
  6. try:
  7. # Defaults to host environment or localhost for external execution
  8. db_host = os.environ.get('DB_HOST', '127.0.0.1')
  9. db_user = os.environ.get('DB_READER_USER', 'db_reader')
  10. db_pass = os.environ.get('DB_READER_PASS', 'reader_pass')
  11. return pymysql.connect(
  12. host=db_host,
  13. user=db_user,
  14. password=db_pass,
  15. database='food_db',
  16. cursorclass=pymysql.cursors.DictCursor
  17. )
  18. except Exception as e:
  19. print(f"DB Connection Error: {e}")
  20. return None
  21. def report_telemetry():
  22. conn = get_db_connection()
  23. if not conn:
  24. print("Failed to connect to database for telemetry.")
  25. return
  26. try:
  27. with conn.cursor() as cursor:
  28. # Get products count
  29. cursor.execute("SELECT COUNT(*) as cnt FROM food_db.products_core")
  30. products_count = cursor.fetchone()['cnt']
  31. # Get users count
  32. cursor.execute("SELECT COUNT(*) as cnt FROM food_db.users")
  33. users_count = cursor.fetchone()['cnt']
  34. msg = f"TELEMETRY: products_core_count={products_count}, users_count={users_count}"
  35. print(f"Sending to Zabbix: {msg}")
  36. # Push via SNMP Trap (which is hooked into Zabbix server on 192.168.130.170)
  37. notifier.send_alert(msg)
  38. except Exception as e:
  39. print(f"Telemetry error: {e}")
  40. finally:
  41. conn.close()
  42. if __name__ == "__main__":
  43. report_telemetry()