Skip to content

Commit cb277e4

Browse files
committed
Add a script to terminate idle pg connections
Koji keeps opening new connections to the database, and keeps them open up to the point where no new connection can be open. Koji then starts to fail, with a database outage error message. This scripts terminates the connexions older that 10 minutes, and is intended to run every minute on the koji server. Signed-off-by: Gaëtan Lehmann <[email protected]>
1 parent 60dcc93 commit cb277e4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

scripts/terminate_idle_connections.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/usr/bin/env python3
2+
3+
import psycopg2
4+
5+
IDLE_TIMEOUT_MINUTES = 10
6+
7+
def main():
8+
with psycopg2.connect(dbname="postgres") as conn, conn.cursor() as cur:
9+
sql_query = f"""
10+
SELECT pg_terminate_backend(pid)
11+
FROM pg_stat_activity
12+
WHERE
13+
state = 'idle'
14+
AND NOW() - state_change > INTERVAL '{IDLE_TIMEOUT_MINUTES} minutes'
15+
AND pid <> pg_backend_pid();
16+
"""
17+
cur.execute(sql_query)
18+
num_terminated = len(cur.fetchall())
19+
if num_terminated > 0:
20+
print(f"terminated {num_terminated} connections")
21+
22+
if __name__ == "__main__":
23+
main()

0 commit comments

Comments
 (0)