Python, asyncio, and systemd

Christian Heimes christian at python.org
Tue Jan 17 12:19:05 EST 2017


On 2017-01-17 17:57, Chris Angelico wrote:
> If I write a web server using asyncio (and the aiohttp package), I can
> spin up the server with:
> 
> await loop.create_server(app.make_handler(), "0.0.0.0", 8080)
> 
> This works fine for a high port, but if I want to bind to port 80, I
> need to either start as root and then drop privileges, or get given
> the socket by someone else. With systemd, the latter is an option; you
> configure a service unit and a socket unit, and when the service gets
> started, it's given a bound listening socket as FD 3.
> 
> Most of the work is pretty straight-forward, but I ran into one
> problem. The event loop's create_server() method calls a private
> _start_serving method, which means I can't (or rather, I shouldn't)
> just replicate create_server. This works, but it's naughty:
> 
> sock = socket.socket(fileno=3)
> 
> sock.setblocking(False)
> loop._start_serving(app.make_handler(), sock)
> 
> What's the official way to say to asyncio "here's a listening socket,
> start managing it for me"?

Hi Chris,

you might be interested in ticket [1], my module socketfromfd [2] and
some code I wrote for a HTTP server with socket activation [3]. The
latter does not use asyncio but shows how to use socket activation with
systemd. The blog posting [4] has some example code in case you don't
want to use systemd's Python module.

[1] https://bugs.python.org/issue28134
[2] https://github.com/tiran/socketfromfd
[3]
https://github.com/latchset/custodia/blob/master/custodia/httpd/server.py#L491
[4] http://0pointer.de/blog/projects/socket-activation.html

Christian




More information about the Python-list mailing list