Files
zulip/scripts/setup/terminate-psql-sessions
Anders Kaseorg 9937734e50 terminate-psql-sessions: Only terminate if we have permissions.
We have been semi-accidentally relying on the fact that terminate-psql-sessions 
fails silently when there are PIDs we don't have permission to terminate.

This actually happens somewhat often, generally when we're doing a series of
operations in quick succession by different users, because postgres processes
live a little longer than the `psql` shell that started them.

As part of adding ON_STOP_ERROR to all of our postgres commands, it makes
sense to enforce we don't fail here, but that means we need to actually filter
the target PIDs to only ones we can actually kill.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-04-23 14:41:42 -07:00

37 lines
714 B
Bash
Executable File

#!/usr/bin/env bash
set -e
POSTGRES_USER="postgres"
if [ "$(uname)" = "OpenBSD" ]; then
POSTGRES_USER="_postgresql"
fi
cd /
username=$1
shift
tables="$(printf "'%s'," "${@//\'/\'\'}")"
tables="${tables%,}"
case "$(id -un)" in
root)
psql=(su -s /usr/bin/env - -- "$POSTGRES_USER" psql postgres "$POSTGRES_USER")
;;
"$POSTGRES_USER")
psql=(psql postgres "$POSTGRES_USER")
;;
*)
psql=(psql -h localhost postgres "$username")
;;
esac
"${psql[@]}" -v ON_ERROR_STOP=1 <<EOF
SELECT pg_terminate_backend(s.pid)
FROM pg_stat_activity s, pg_roles r
WHERE
s.datname IN ($tables)
AND r.rolname = CURRENT_USER
AND (s.usename = r.rolname OR r.rolsuper = 't');
EOF