Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@athoune
Created June 28, 2016 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save athoune/d5a4125fb00e010116c1393ba5af99a9 to your computer and use it in GitHub Desktop.
Save athoune/d5a4125fb00e010116c1393ba5af99a9 to your computer and use it in GitHub Desktop.
Ping all the ping
#!/usr/bin/env python3
import os
import asyncio
import aiohttp
from aiohttp import web
@asyncio.coroutine
def do_ping(session, domain):
try:
response = yield from session.get('http://%s/ping' % domain)
if response.status != 200:
response.close()
return domain, False, "Status code %i" % response.status
body = yield from response.read()
except Exception as e:
raise Exception(domain, e)
return domain, body == b"pong", body.decode("utf8")
class Pingator:
domains = []
def read_conf(self, path):
self.domains = []
with open(path, 'r') as conf:
for line in conf:
line = line.strip()
if len(line) == 0:
continue
if line[0] == '#':
continue
self.domains.append(line)
@asyncio.coroutine
def handle(self, request):
loop = request.app.loop
cpt = len(self.domains)
with aiohttp.ClientSession(loop=loop) as session:
responses = dict((a, dict(ok=False, msg="Unknow")) for a
in self.domains)
tasks = [do_ping(session, d)
for d in self.domains]
done, _ = yield from asyncio.wait(tasks, timeout=5)
for response in done:
try:
domain, ping, response = response.result()
cpt -= 1
except Exception as e:
responses[e.args[0]] = dict(ok=False, msg=e.args[1].args[1])
else:
responses[domain] = dict(ok=ping, msg=response)
return web.json_response(responses, status=200 if cpt==0 else 418)
@asyncio.coroutine
def init(loop):
host = os.getenv('METAPING_HOST', '127.0.0.1')
port = int(os.getenv('METAPING_PORT', 8080))
conf = os.getenv('METAPING_CONF', '/etc/metaping.conf')
ping = Pingator()
ping.read_conf(conf)
app = web.Application(loop=loop)
app.router.add_route('GET', '/ping', ping.handle)
srv = yield from loop.create_server(app.make_handler(), host, port)
print("Server started at http://%s:%i" % (host, port))
return srv
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment