diff --git a/server_list/ping.py b/server_list/ping.py index 646c3c4..8b6daa8 100644 --- a/server_list/ping.py +++ b/server_list/ping.py @@ -1,6 +1,4 @@ -import asyncio import time -import random import socket from .app import app @@ -37,61 +35,6 @@ def get_ping_reply(data): return b"\x4f\x45\x74\x03" + peer_id + b"\x00\x00\x03" -class MinetestProtocol: - def connection_made(self, transport): - self.transport = transport - - def send_original(self): - self.transport.sendto(PING_PACKET) - - self.start = time.time() - - def datagram_received(self, data, addr): - end = time.time() - self.transport.sendto(get_ping_reply(data), addr) - - self.future.set_result(end - self.start) - self.transport.close() - - def connection_lost(self, exc): - if not self.future.done(): - self.future.set_result(None) - - def error_received(self, exc): - self.future.set_result(None) - - -async def ping_server_async(address, sock=None): - loop = asyncio.get_event_loop() - transport, protocol = await loop.create_datagram_endpoint( - MinetestProtocol, - remote_addr=address, - sock=sock) - attempts = 0 - pings = [] - while len(pings) < 3 and attempts - len(pings) < 3: - attempts += 1 - protocol.future = loop.create_future() - try: - # Sleep a bit to spread requests out - await asyncio.sleep(random.random()) - protocol.send_original() - ping = await asyncio.wait_for(asyncio.shield(protocol.future), 2) - if ping is not None: - pings.append(ping) - except asyncio.TimeoutError: - pass - - if len(pings) != 0: - return min(pings) - - return None - - -async def ping_servers_async(addresses): - return await asyncio.gather(*[ping_server_async(a) for a in addresses]) - - def ping_server_addresses(address, port): pings = [] addr_info = get_addr_info(address, port) diff --git a/server_list/tasks.py b/server_list/tasks.py index c861ce4..54a6812 100644 --- a/server_list/tasks.py +++ b/server_list/tasks.py @@ -1,11 +1,10 @@ -import asyncio import json import os from datetime import datetime from .app import app, celery, db from .models import Server, Stats -from .ping import ping_servers_async, ping_server_addresses +from .ping import ping_server_addresses from .util import get_geo_continent, server_ranking @@ -75,27 +74,6 @@ def update_list(): db.session.commit() -@celery.task -def update_ping(): - servers = Server.query.filter_by(online=True).all() - - addresses = [(s.address, s.port) for s in servers] - pings = [] - - async def do_ping(): - pings.extend(await ping_servers_async(addresses)) - asyncio.run(do_ping()) - - for i, server in enumerate(servers): - if pings[i] is None: - server.set_offline() - else: - server.ping = pings[i] - - db.session.commit() - - @celery.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(60, update_list.s(), name='Update server list') - sender.add_periodic_task(5*60, update_ping.s(), name='Update server ping')