Spaces:
Running
Running
Update peer_discovery.py
Browse files7 unmodified lines89101112131415161718192021222324252 unmodified lines282930313233343514 unmodified lines5051525354558 unmodified lines64656667686911 unmodified lines81828384858616 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381392 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911927 unmodified linesfrom zeroconf import Zeroconf, ServiceInfo, ServiceBrowserimport random# منفذ عشوائي مكوَّن من 4 أرقام (مثلاً 0007، 8321…)PORT = int(os.getenv("CPU_PORT", random.randint(1, 9999)))# إذا كان باقي الكود يحتاج متغيّر rport iterable# أنشئ مجموعة تحتوي هذا المنفذ فقط (اختياري):rport = {f"{PORT:04}"}# 👇 إعداد الـ peer discovery عبر LAN وInternetSERVICE = "_tasknode._tcp.local."PORT = int(os.getenv("CPU_PORT", random.choice(list(rport))))PEERS = set() # مجموعة URLs للأقران (/run)# 🌐 قائمة السيرفرات (Failover List)BASES = ["https://cv4790811.regru.cloud","https://amaloffload.onrender.com",2 unmodified lines"http://10.229.228.178",]CENTRAL_REGISTRY_SERVERS = [f"{base}:{port}" for base in BASES for port in rport]current_server_index = 014 unmodified linestry: s.close()except: pass# 🔄 اختيار السيرفر المتاحdef get_active_central_server():global current_server_index8 unmodified linescontinuereturn None# ❶ تسجيل الخدمة في شبكة LANdef register_service_lan():zc = Zeroconf()11 unmodified linesexcept Exception as e:print(f"❌ LAN registration failed: {e}")# ❷ مستمع اكتشاف LANclass Listener:def add_service(self, zc, t, name):16 unmodified lineswhile True:time.sleep(5)# ❸ التسجيل في الخادم المركزي (مع Failover)def register_with_central():node_id = os.getenv("NODE_ID", socket.gethostname())info = {"node_id": node_id, "ip": get_local_ip(), "port": PORT}server = get_active_central_server()if not server:print("❌ لا يوجد أي سيرفر مركزي متاح حالياً")returntry:resp = requests.post(f"{server}/register", json=info, timeout=5)resp.raise_for_status()peers_list = resp.json()for p in peers_list:peer_url = f"http://{p['ip']}:{p['port']}/run"if peer_url not in PEERS:PEERS.add(peer_url)print(f"🌐 Registered and discovered central peer: {peer_url}")except Exception as e:print(f"❌ Central registration failed on {server}: {e}")# ❹ مزامنة الأقران مع السيرفر المركزي (مع Failover)def fetch_central_loop():print("🔄 Central registry sync loop started")while True:server = get_active_central_server()if not server:print("⚠️ لا يوجد سيرفر مركزي متاح للمزامنة")time.sleep(30)continuetry:resp = requests.get(f"{server}/peers", timeout=5)resp.raise_for_status()peers_list = resp.json()for p in peers_list:2 unmodified linesPEERS.add(peer_url)print(f"🌐 Central peer discovered: {peer_url}")except Exception as e:print(f"⚠️ Fetch central peers failed on {server}: {e}")time.sleep(300)def connect_until_success():"""يحاول الاتصال بكل سيرفر في CENTRAL_REGISTRY_SERVERSعلى كل منفذ في RPORTS بالتتابع (مع تأخير بسيط).لا يخرج إلا بعد نجاح التسجيل، ويُعيد السيرفر المختار وقائمة الأقران."""global PORT, current_server_indexwhile True:for port in RPORTS: # جرّب كل المنافذfor idx, server in enumerate(CENTRAL_REGISTRY_SERVERS):info = {"node_id": os.getenv("NODE_ID", socket.gethostname()),"ip": get_local_ip(),"port": port}try:resp = requests.post(f"{server}/register",json=info, timeout=5)resp.raise_for_status() # نجاحPORT = port # ثبّت المنفذ الناجحcurrent_server_index = idx # حدّث المؤشّرprint(f"✅ Connected: {server} on port {PORT}")return server, resp.json() # peers_listexcept Exception as e:logging.info("❌ %s:%s -> %s", server, port, e)time.sleep(5) # انتظر قليلاً ثم أَعِد الكرّة# 🚀 Maindef main():logging.basicConfig(level=logging.INFO)print("🚀 Peer Discovery System starting...")threading.Thread(target=register_service_lan, daemon=True).start()threading.Thread(target=discover_lan_loop, daemon=True).start()register_with_central()threading.Thread(target=fetch_central_loop, daemon=True).start()try:while True:time.sleep(60)except KeyboardInterrupt:print("🛑 Exiting...")if __name__ == "__main__":main()7 unmodified lines8910111213141516171819202122232 unmodified lines262728293031323314 unmodified lines484950515253548 unmodified lines6364656667686911 unmodified lines8182838485868716 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551562 unmodified lines1591601611621631641651661671681691701711721731741757 unmodified linesfrom zeroconf import Zeroconf, ServiceInfo, ServiceBrowserimport random# ---------- المتغيرات الأساسية ----------PORT = NoneCURRENT_SERVER = NoneCONNECTED = threading.Event()PEERS = set()SERVICE = "_tasknode._tcp.local."LAN_PORT = 7520 # منفذ LAN الداخلي# ---------- قائمة السيرفرات ----------BASES = ["https://cv4790811.regru.cloud","https://amaloffload.onrender.com",2 unmodified lines"http://10.229.228.178",]RPORTS = [f"{i:04}" for i in range(1, 10000)]CENTRAL_REGISTRY_SERVERS = [f"{base}:{port}" for base in BASES for port in RPORTS]current_server_index = 014 unmodified linestry: s.close()except: pass# 🔄 اختيار السيرفر المتاحdef get_active_central_server():global current_server_index8 unmodified linescontinuereturn None# ❶ تسجيل الخدمة في شبكة LANdef register_service_lan():zc = Zeroconf()11 unmodified linesexcept Exception as e:print(f"❌ LAN registration failed: {e}")# ❷ مستمع اكتشاف LANclass Listener:def add_service(self, zc, t, name):16 unmodified lineswhile True:time.sleep(5)# ❸ الاتصال بسيرفر مركزي (مع محاولات حتى النجاح)def connect_until_success():"""يحاول الاتصال بكل سيرفر وبورت بالتسلسل، ويتوقف عند أول نجاحويضبط PORT وCONNECTED وCENTRAL_REGISTRY"""global PORT, current_server_index, CURRENT_SERVERfor port_int in range(1, 10000):port = f"{port_int:04}"for idx, server_base in enumerate(BASES):server = f"{server_base}:{port}"info = {"node_id": os.getenv("NODE_ID", socket.gethostname()),"ip": get_local_ip(),"port": int(port)}try:resp = requests.post(f"{server}/register", json=info, timeout=5)resp.raise_for_status()PORT = int(port)CURRENT_SERVER = servercurrent_server_index = idxCONNECTED.set()print(f"✅ Connected: {server} on port {PORT}")peers = resp.json()for p in peers:peer_url = f"http://{p['ip']}:{p['port']}/run"if peer_url not in PEERS:PEERS.add(peer_url)print(f"🌐 Central peer: {peer_url}")returnexcept Exception as e:logging.info("❌ %s:%s -> %s", server_base, port, e)time.sleep(0.1)# ❹ مزامنة مستمرة مع السيرفر المركزيdef fetch_central_loop():print("🔄 Central registry sync loop started")while True:if not CONNECTED.is_set():time.sleep(5)continuetry:resp = requests.get(f"{CURRENT_SERVER}/peers", timeout=5)resp.raise_for_status()peers_list = resp.json()for p in peers_list:2 unmodified linesPEERS.add(peer_url)print(f"🌐 Central peer discovered: {peer_url}")except Exception as e:print(f"⚠️ Fetch central peers failed: {e}")time.sleep(300)# 🚀 تشغيل تلقائي عند الاستيرادdef _start():if not CONNECTED.is_set():print("🚀 Starting peer discovery...")connect_until_success()threading.Thread(target=register_service_lan, daemon=True).start()threading.Thread(target=discover_lan_loop, daemon=True).start()threading.Thread(target=fetch_central_loop, daemon=True).start()_start() # ← تشغيل تلقائي
peer_discovery.py+64-81