cluster_manager.py 2.4 KB

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