Skip to content

Fix PGconn leak in pgsql_retry_open_connection - #1202

Open
ritojoao wants to merge 1 commit into
hapostgres:mainfrom
ritojoao:fix-1178-pgconn-leak
Open

ritojoao wants to merge 1 commit into
hapostgres:mainfrom
ritojoao:fix-1178-pgconn-leak

Conversation

@ritojoao

Copy link
Copy Markdown

Fixes #1178

Hello, and thank you for maintaining pg_auto_failover.

In pgsql_retry_open_connection() (src/bin/common/pgsql.c), the PQPING_OK case assigns the result of PQconnectdb() to pgsql->connection without releasing the previous value. That value is either the failed first attempt made by pgsql_open_connection(), or the failed connection from the previous loop iteration, so the old PGconn was never freed.

This patch calls PQfinish() on the old connection and sets the pointer to NULL right before the new PQconnectdb(). The other exit paths go through pgsql_finish(), which already sets the pointer to NULL, so I do not see a double free risk. I used PQfinish() directly to avoid a "Disconnecting" log line on every retry.

How I tested: I built pg_autoctl from main with and without the patch, and ran pg_autoctl show state --monitor ... (with PGCONNECT_TIMEOUT=14 to allow several retries) against a small fake server that completes authentication and then stalls, so each attempt hits the connect timeout. An LD_PRELOAD counter showed 7 PGconn objects created and 1 released before the patch, and 7 created and 7 released after.

What I did not test: I could not reproduce the idle backends remaining on a real monitor (libpq closed the socket at the timeout in my setup, so only the client memory leaked), and I did not run the project's test suite. Happy to adjust if you prefer a different approach.

Release the previous failed PGconn (from the initial attempt made by
pgsql_open_connection, or from the previous retry iteration) before
PQconnectdb() overwrites pgsql->connection.

Fixes hapostgres#1178
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant