Skip to content

Leaked connections caused by asyncio.CancelledError#464

@nevladov

Description

@nevladov
  • asyncpg version: 0.18.2
  • PostgreSQL version: 10
  • Do you use a PostgreSQL SaaS? If so, which? Can you reproduce
    the issue with a local PostgreSQL install?
    :
  • Python version: 3.6.6
  • Platform:
  • Do you use pgbouncer?: yes
  • Did you install asyncpg with pip?:
  • If you built asyncpg locally, which version of Cython did you use?:
  • Can the issue be reproduced under both asyncio and
    uvloop?
    :

asyncio.CancelledError occured in this place may be cause of connection leak.
The code below reproduces this problem:

importasyncpgimporttracebackasyncdeftest_connect(): conn=Nonetry: print('started') conn=awaitasyncpg.connect( host='your_host', port='6432', database='db', user='user', password='password', ssl=True, ) exceptasyncio.CancelledError: print('CancelledError occured') traceback.print_exc() finally: ifconn: awaitconn.close() print('connection closed') returnprint('connection was not closed, maybe leaked') asyncdeftest_cancel(): foriinrange(50): # try 50 timesfuture=asyncio.ensure_future(test_connect()) awaitasyncio.sleep(0.09) # this sleep allows to call connectfuture.cancel() awaitasyncio.sleep(600) importasyncioloop=asyncio.get_event_loop() loop.run_until_complete(test_cancel())

Printed traceback:

Traceback (most recent call last): File "<stdin>", line 11, in test_connect File "python3.6/site-packages/asyncpg/connection.py", line 1688, in connect max_cacheable_statement_size=max_cacheable_statement_size) File "python3.6/site-packages/asyncpg/connect_utils.py", line 543, in _connect connection_class=connection_class) File "python3.6/site-packages/asyncpg/connect_utils.py", line 519, in _connect_addr await asyncio.wait_for(connected, loop=loop, timeout=timeout) File "python3.6/asyncio/tasks.py", line 351, in wait_for yield from waiter concurrent.futures._base.CancelledError 

After running this script 3-6 iterations of 50 lead to connection leaks:

$ netstat -a | grep 6432 | awk '{print $6 }' ESTABLISHED ESTABLISHED ESTABLISHED ESTABLISHED 

These connections remain establised while python process is running.
Our service is based on aiohttp application. Servise has about 5K request per second. When client request is finished by timeout aiohttp cancels handler task. This situation occurrs very often when we have network problem. And in this case we have thousands of lost connections.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions