|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# please configure by setting the folloiwng shell variables |
| 4 | + |
| 5 | +# REQUIRED: set location of log file for logging killed transactions |
| 6 | +LOGFILE=/var/log/postgresql/kill_idle.log |
| 7 | + |
| 8 | +# REQUIRED: set timelimit for oldest idle transaction, in minutes |
| 9 | +IDLETIME=15 |
| 10 | + |
| 11 | +# REQUIRED: set timelimit for oldest non-idle long-running transaction |
| 12 | +# in minutes. Set to 1000 if you don't really want these cancelled |
| 13 | +XACTTIME=120 |
| 14 | + |
| 15 | +# REQUIRED: set users to be ignored and not kill idle transactions |
| 16 | +# generally you want to omit the postgres superuser and the user |
| 17 | +# pg_dump runs as from being killed |
| 18 | +# if you have no users like this, just set both to XXXXX |
| 19 | +SUPERUSER=postgres |
| 20 | +BACKUPUSER=XXXXX |
| 21 | + |
| 22 | +# REQUIRED: path to psql, since cron often lacks search paths |
| 23 | +PSQL=/usr/lib/postgresql/9.1/bin/psql |
| 24 | + |
| 25 | +# OPTIONAL: set these connection variables. if you are running as the |
| 26 | +# postgres user on the local machine with passwordless login, you will |
| 27 | +# not needto set any of these |
| 28 | +PGHOST= |
| 29 | +PGUSER= |
| 30 | +PGPORT= |
| 31 | +PGPASSWORD= |
| 32 | + |
| 33 | +# you should not need to change code below this line |
| 34 | +#################################################### |
| 35 | + |
| 36 | +export PGHOST |
| 37 | +export PGUSER |
| 38 | +export PGPORT |
| 39 | +export PGPASSWORD |
| 40 | +exec >> $LOGFILE 2>&1 |
| 41 | +SAFELIST="ARRAY['${SUPERUSER}', '${BACKUPUSER}']" |
| 42 | +IDLEPARAM="'${IDLETIME} minutes'" |
| 43 | +XACTPARAM="'${XACTTIME} minutes'" |
| 44 | + |
| 45 | +KILLQUERY="WITH idles AS ( |
| 46 | + SELECT datname, procpid, usename, application_name, |
| 47 | + client_addr, backend_start, xact_start, query_start, |
| 48 | + waiting, pg_terminate_backend(procpid) |
| 49 | + FROM pg_stat_activity |
| 50 | + WHERE current_query = '<IDLE> in transaction' |
| 51 | + AND usename != '${SUPERUSER}' |
| 52 | + AND usename != '${BACKUPUSER}' |
| 53 | + AND ( ( now() - xact_start ) > '${XACTTIME} minutes' |
| 54 | + OR ( now() - query_start ) > '${IDLETIME} minutes' ) |
| 55 | +) |
| 56 | +SELECT array_to_string(ARRAY[ now()::TEXT, |
| 57 | + idles.datname::TEXT, idles.procpid::TEXT, idles.usename::TEXT, |
| 58 | + idles.application_name, idles.client_addr::TEXT, |
| 59 | + idles.backend_start::TEXT, idles.xact_start::TEXT, |
| 60 | + idles.waiting::TEXT], '|') |
| 61 | +FROM idles |
| 62 | +ORDER BY xact_start;" |
| 63 | + |
| 64 | +psql -q -t -c "${KILLQUERY}" |
| 65 | + |
| 66 | +exit 0 |
| 67 | + |
0 commit comments