zabbix_airflow_monitor.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import requests
  2. import json
  3. import urllib3
  4. import os
  5. from dotenv import load_dotenv
  6. load_dotenv()
  7. urllib3.disable_warnings()
  8. # Zabbix Server credentials loaded from environment
  9. ZABBIX_URL = os.environ.get('ZABBIX_URL', '')
  10. ZABBIX_USER = os.environ.get('ZABBIX_USER', '')
  11. ZABBIX_PASS = os.environ.get('ZABBIX_PASS', '')
  12. def zabbix_rpc(method, params, auth=None):
  13. payload = {
  14. "jsonrpc": "2.0",
  15. "method": method,
  16. "params": params,
  17. "id": 1
  18. }
  19. if auth:
  20. payload["auth"] = auth
  21. response = requests.post(ZABBIX_URL, json=payload, headers={'Content-Type': 'application/json-rpc'})
  22. return response.json()
  23. def main():
  24. print("Authenticating with Zabbix...")
  25. res = zabbix_rpc('user.login', {'username': ZABBIX_USER, 'password': ZABBIX_PASS})
  26. if 'error' in res:
  27. print("Login failed:", res['error'])
  28. return
  29. auth_token = res['result']
  30. print("Finding Zabbix server host...")
  31. hosts = zabbix_rpc('host.get', {
  32. 'filter': {'host': ['Zabbix server']}
  33. }, auth=auth_token)
  34. if not hosts['result']:
  35. print("Error: Could not find 'Zabbix server' host in Zabbix.")
  36. return
  37. host_id = hosts['result'][0]['hostid']
  38. print("Checking if Airflow Web Scenario already exists...")
  39. scenarios = zabbix_rpc('httptest.get', {
  40. 'hostids': host_id,
  41. 'filter': {'name': ['Airflow Supervisor Health']}
  42. }, auth=auth_token)
  43. if scenarios['result']:
  44. print("Airflow Web Scenario already exists. Deleting to recreate...")
  45. httptest_id = scenarios['result'][0]['httptestid']
  46. zabbix_rpc('httptest.delete', [httptest_id], auth=auth_token)
  47. print("Creating Airflow Web Scenario...")
  48. create_res = zabbix_rpc('httptest.create', {
  49. "name": "Airflow Supervisor Health",
  50. "hostid": host_id,
  51. "delay": "1m",
  52. "steps": [
  53. {
  54. "name": "Check Airflow Health Endpoint",
  55. "url": "http://172.18.0.1:8082/health",
  56. "status_codes": "200",
  57. "no": 1
  58. }
  59. ]
  60. }, auth=auth_token)
  61. if 'error' in create_res:
  62. print("Error creating web scenario:", create_res['error'])
  63. else:
  64. print("Successfully created Zabbix monitoring for Apache Airflow!")
  65. if __name__ == "__main__":
  66. main()