Skip to content

Instantly share code, notes, and snippets.

@Da-Juan
Created March 1, 2022 16:12
Show Gist options
  • Save Da-Juan/dab24ce14997e1751ddc1ed7cf6c869d to your computer and use it in GitHub Desktop.
Save Da-Juan/dab24ce14997e1751ddc1ed7cf6c869d to your computer and use it in GitHub Desktop.
Run postgresqltuner.pl on each database and keep 3 copies of each database's report
#!/usr/bin/env bash
# This script requires postgresqltuner.pl:
# apt install libdbd-pg-perl libdbi-perl perl-modules
# wget -O /usr/local/bin/postgresqltuner.pl https://postgresqltuner.pl
# chmod +x /usr/local/bin/postgresqltuner.pl
OUTPUT_DIR="/var/lib/postgresqltuner"
# Max number of files to keep for each database
MAX_COPIES=3
# Do not run against those databases
IGNORE_dbs=("postgres" "template0" "template1")
function remove_old_files {
local db="$1"
local count
count="$(find "$OUTPUT_DIR" -name "${db}-*" | wc -l)"
if [ "$count" -gt "$MAX_COPIES" ]; then
while read -r file; do
rm "$file"
done < <(find "$OUTPUT_DIR" -name "${db}-*" | sort | head -"$((count - MAX_COPIES))")
fi
}
if [ ! -d "$OUTPUT_DIR" ]; then
mkdir -p "$OUTPUT_DIR"
setfacl -d -m u:postgres:rwX "$OUTPUT_DIR"
setfacl -m u:postgres:rwX "$OUTPUT_DIR"
fi
dbs="$(su -c "LC_ALL=C /usr/bin/psql -lqAx" postgres | awk -F\| '/^Name/{ print $2 }')"
for db in "${IGNORE_dbs[@]}"; do
dbs="${dbs//$db/}"
done
for db in $dbs; do
output="${OUTPUT_DIR}/${db}-$(date +"%Y%m%d")"
su -c "/usr/local/bin/postgresqltuner.pl --database $db >$output 2>&1" postgres
remove_old_files "$db"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment