Skip to content

Commit

Permalink
Move signal handling out of the controller
Browse files Browse the repository at this point in the history
  • Loading branch information
Neil Booth committed Nov 7, 2016
1 parent 680eb83 commit 1393f6a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 20 deletions.
37 changes: 30 additions & 7 deletions electrumx_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,29 @@

'''Script to kick off the server.'''


import asyncio
import logging
import os
import signal
import traceback
from functools import partial

from server.env import Env
from server.controller import Controller


def cancel_tasks(loop):
# Cancel and collect the remaining tasks
tasks = asyncio.Task.all_tasks()
for task in tasks:
task.cancel()

try:
loop.run_until_complete(asyncio.gather(*tasks))
except asyncio.CancelledError:
pass


def main_loop():
'''Get tasks; loop until complete.'''
if os.geteuid() == 0:
Expand All @@ -33,16 +46,26 @@ def main_loop():
#loop.set_debug(True)

controller = Controller(loop, env)
controller.start()

tasks = asyncio.Task.all_tasks(loop)
# Signal handlers
def on_signal(signame):
'''Call on receipt of a signal to cleanly shutdown.'''
logging.warning('received {} signal, preparing to shut down'
.format(signame))
loop.stop()

for signame in ('SIGINT', 'SIGTERM'):
loop.add_signal_handler(getattr(signal, signame),
partial(on_signal, signame))

controller.start()
try:
loop.run_until_complete(asyncio.gather(*tasks))
except asyncio.CancelledError:
logging.warning('task cancelled; asyncio event loop closing')
loop.run_forever()
finally:
controller.stop()
loop.close()
cancel_tasks(loop)

loop.close()


def main():
Expand Down
13 changes: 0 additions & 13 deletions server/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
'''

import asyncio
import signal
import ssl
from functools import partial

Expand Down Expand Up @@ -46,11 +45,6 @@ def start(self):
for coro in coros:
asyncio.ensure_future(coro)

# Signal handlers
for signame in ('SIGINT', 'SIGTERM'):
self.loop.add_signal_handler(getattr(signal, signame),
partial(self.on_signal, signame))

async def on_update(self, height, touched):
if not self.servers:
self.servers = await self.start_servers()
Expand Down Expand Up @@ -98,10 +92,3 @@ def stop(self):
'''Close the listening servers.'''
for server in self.servers:
server.close()

def on_signal(self, signame):
'''Call on receipt of a signal to cleanly shutdown.'''
self.logger.warning('received {} signal, preparing to shut down'
.format(signame))
for task in asyncio.Task.all_tasks(self.loop):
task.cancel()

0 comments on commit 1393f6a

Please sign in to comment.