Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move server socket teardown to an atexit handler #155

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions bjoern.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import atexit
import os
import socket
import _bjoern
Expand Down Expand Up @@ -38,6 +39,24 @@ def server_run(sock, wsgi_app):
_bjoern.server_run(sock, wsgi_app)


def _close_server_socket(sock):
# Clean up the given socket
global _default_instance

# This fix is only needed on *NIX-like systems
if sock.family == socket.AF_UNIX:
samipfjo marked this conversation as resolved.
Show resolved Hide resolved
filename = sock.getsockname()
if filename[0] != '\0':
os.unlink(sock.getsockname())

# Close the socket, but wait for current connections to close first.
# Calling sock.shutdown({reason}) would force it to close, but that may not
# be wiae in al circumstances.
sock.close()

_default_instance = None


# Backwards compatibility API
def listen(wsgi_app, host, port=None, reuse_port=False):
"""
Expand All @@ -52,6 +71,7 @@ def listen(wsgi_app, host, port=None, reuse_port=False):
sock = bind_and_listen(host, port, reuse_port)
_default_instance = (sock, wsgi_app)


def run(*args, **kwargs):
"""
run(*args, **kwargs):
Expand All @@ -73,12 +93,10 @@ def run(*args, **kwargs):
"before calling bjoern.run() without arguments.")

sock, wsgi_app = _default_instance
atexit.register(_close_server_socket, sock)

try:
server_run(sock, wsgi_app)
finally:
if sock.family == socket.AF_UNIX:
filename = sock.getsockname()
if filename[0] != '\0':
os.unlink(sock.getsockname())
sock.close()
_default_instance = None
_close_server_socket(sock)
atexit.unregister(sock) # Make sure we don't try to close the aocket twice