cluster_manager.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import json
  2. import threading
  3. import urllib.request
  4. import config
  5. from core.file_manager import load_panel_settings, load_adblock_lists, load_custom_rules
  6. def broadcast_to_cluster(action, domain):
  7. def task():
  8. from core import dns
  9. import urllib.request, json
  10. settings = load_panel_settings()
  11. nodes = settings.get('cluster_nodes', [])
  12. masters = dns.get_zone_masters_list(domain)
  13. if not masters:
  14. master_ip = settings.get('server_public_ip', '').strip()
  15. if master_ip: masters = [master_ip]
  16. for node in nodes:
  17. try:
  18. url = f"{node['url'].rstrip('/')}/api/v1/cluster/zone"
  19. headers = {"X-API-Key": node['api_key'], "Content-Type": "application/json"}
  20. payload = {"domain": domain, "masters": masters}
  21. if action == 'add_slave':
  22. req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST')
  23. elif action == 'delete_zone':
  24. req = urllib.request.Request(f"{url}/{domain}", headers=headers, method='DELETE')
  25. urllib.request.urlopen(req, timeout=5, context=config.ssl_ctx)
  26. except Exception as e:
  27. print(f"Cluster Sync FAIL: {node['name']} -> {e}")
  28. import threading
  29. threading.Thread(target=task, daemon=True).start()
  30. def broadcast_adblock_to_cluster(action):
  31. def task():
  32. s = load_panel_settings()
  33. lists = load_adblock_lists()
  34. rules = load_custom_rules()
  35. count = s.get('adblock_domains_count', 0)
  36. update_time = s.get('adblock_last_update', 'Never')
  37. for node in s.get('cluster_nodes', []):
  38. try:
  39. url = f"{node['url'].rstrip('/')}/api/v1/cluster/adblock"
  40. headers = {"X-API-Key": node['api_key'], "Content-Type": "application/json"}
  41. payload = {
  42. "action": action,
  43. "lists": lists,
  44. "rules": rules,
  45. "count": count,
  46. "time": update_time
  47. }
  48. req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers=headers, method='POST')
  49. urllib.request.urlopen(req, timeout=10, context=config.ssl_ctx)
  50. print(f"Cluster AdBlock Sync OK: {node['name']} ({action})")
  51. except Exception as e:
  52. print(f"Cluster AdBlock Sync FAIL: {node['name']} -> {e}")
  53. threading.Thread(target=task, daemon=True).start()