Skip to content

Add dynamic port binding #10697

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions CHANGES/10665.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added `port` accessor for dynamic port allocations in `TCPSite` -- by :user:`twhittock-disguise`.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ Thomas Forbes
Thomas Grainger
Tim Menninger
Tolga Tezel
Tom Whittock
Tomasz Trebski
Toshiaki Tanaka
Trinh Hoang Nhu
Expand Down
9 changes: 9 additions & 0 deletions aiohttp/web_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ def name(self) -> str:
host = "0.0.0.0" if not self._host else self._host
return str(URL.build(scheme=scheme, host=host, port=self._port))

@property
def port(self) -> int:
"""Return the port number the server is bound to, useful for the dynamically allocated port (0)."""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, avoid having the docstring title line exceed 72 chars. You can have a longer paragraph below.
Also, referencing a magic number is not useful to readers unfamiliar with it. Use the ephemeral terminology so people could at least google it. Although, I would probably not even mention it since the underlying implementation details aren't really important to the end-users who'd just use this unconditionally.

return self._port

async def start(self) -> None:
await super().start()
loop = asyncio.get_event_loop()
Expand All @@ -127,6 +132,10 @@ async def start(self) -> None:
reuse_address=self._reuse_address,
reuse_port=self._reuse_port,
)
if self._port == 0:
# Port 0 means bind to any port, so we need to set the attribute
# to the port the server was actually bound to.
self._port = self._server.sockets[0].getsockname()[1]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't reassign this but track the bound port separately. This is so starting and stopping the TCP site multiple times would be able to get a new port allocated each time.



class UnixSite(BaseSite):
Expand Down
22 changes: 22 additions & 0 deletions docs/web_advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,28 @@ the middleware might use :meth:`BaseRequest.clone`.
for modifying *scheme*, *host* and *remote* attributes according
to ``Forwarded`` and ``X-Forwarded-*`` HTTP headers.

Deploying with a dynamic port
-----------------------------

When deploying aiohttp with zero-configuration networking, it may be useful
to have the server bind to a dynamic port. This can be done by
using the ``0`` port number. This will cause the OS to assign a
free port to the server. The assigned port can be retrieved
using the :attr:`TCPSite.port` property after the server has started.

For example::

app = web.Application()
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 0)
await site.start()

print(f"Server started on port {site.port}")
while True:
await asyncio.sleep(3600) # sleep forever


Swagger support
---------------

Expand Down
11 changes: 11 additions & 0 deletions docs/web_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2788,6 +2788,17 @@ application on specific TCP or Unix socket, e.g.::
this flag when being created. This option is not
supported on Windows.

.. attribute:: port

The port number the server is bound to. This is useful when the port
number is not known in advance, such as when constructing with
port 0 to request an ephemeral port or when not supplying the port
to the constructor.
This attribute is read-only and should not be modified.
This attribute is only guaranteed to be correct after the server has
been started.


.. class:: UnixSite(runner, path, *, \
shutdown_timeout=60.0, ssl_context=None, \
backlog=128)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_web_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,21 @@ async def test_tcpsite_empty_str_host(make_runner: _RunnerMaker) -> None:
runner = make_runner()
await runner.setup()
site = web.TCPSite(runner, host="")
assert site.port == 8080
assert site.name == "http://0.0.0.0:8080"


async def test_tcpsite_ephemeral_port(make_runner: _RunnerMaker) -> None:
runner = make_runner()
await runner.setup()
site = web.TCPSite(runner, port=0)

await site.start()
assert site.port != 0
assert site.name.startswith("http://0.0.0.0:")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we know the port, this could just compare the entire string..

await site.stop()


def test_run_after_asyncio_run() -> None:
called = False

Expand Down
Loading