pg_backup.sh 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/bin/bash
  2. # ██╗ ██╗ ██████╗ ██╗ ██╗ ████████╗ ██████╗ ██╗ ██╗███████╗███████╗
  3. # ██║ ██║██╔═══██╗██║ ██║ ╚══██╔══╝██╔═══██╗ ██║ ██║██╔════╝██╔════╝
  4. # ███████║██║ ██║██║ █╗ ██║ ██║ ██║ ██║ ██║ ██║███████╗█████╗
  5. # ██╔══██║██║ ██║██║███╗██║ ██║ ██║ ██║ ██║ ██║╚════██║██╔══╝
  6. # ██║ ██║╚██████╔╝╚███╔███╔╝ ██║ ╚██████╔╝ ╚██████╔╝███████║███████╗
  7. #╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝
  8. #
  9. # 1. set exec perms
  10. # chmod +x pg_backup.sh
  11. # 2. run .pg_backup db_01 db_02 ... db_n
  12. #
  13. set -e
  14. # CONTAINER="database"
  15. CONTAINER="postgres"
  16. # DB_USER="odoo"
  17. DB_USER="postgres"
  18. DATE=$(date +%Y%m%d)
  19. TIME=$(date +%H%M%S)
  20. DAYS_TO_KEEP=7
  21. # BACKUP_PATH="/mnt/backup/local"
  22. # CLONE_PATH="/mnt/backup/nfs"
  23. BKP_PATH="/home/robert/test_pg_backup"
  24. SYNC_PATH="/home/robert/test_sync_backup"
  25. TMP_PATH="."
  26. # perform database backup if docker exist
  27. perform_backups()
  28. {
  29. if [ ! -x "$(command -v docker)" ]; then
  30. echo "cannot perform backup"
  31. exit 1
  32. fi
  33. local BKP_TODAY_PATH=$(printf "%s/backup_%s" "$BKP_PATH" "$DATE")
  34. if [ ! -d "$BKP_TODAY_PATH" ]; then
  35. mkdir "$BKP_TODAY_PATH"
  36. fi
  37. for DB_NAME in $@; do
  38. local TMP_FILE=$(printf "%s/%s_%s.tar" "$TMP_PATH" "$DB_NAME" "$TIME")
  39. docker exec $CONTAINER pg_dump -U $DB_USER -d $DB_NAME -F tar -C -b -c -f $TMP_FILE
  40. docker cp $CONTAINER:$TMP_FILE $BKP_TODAY_PATH
  41. docker exec $CONTAINER rm $TMP_FILE
  42. done
  43. }
  44. # delete old backups
  45. delete_old_backups()
  46. {
  47. find $1 -maxdepth 1 -type d -name "backup_*" -mtime +$2 -exec rm -rf '{}' ';'
  48. }
  49. # sync two backup paths
  50. local_sync_backups_path()
  51. {
  52. if [ ! -x "$(command -v rsync)" ]; then
  53. echo "cannot sync backups path"
  54. exit 1
  55. fi
  56. rsync -arz $1 $2
  57. }
  58. # sync two backup paths remotely
  59. remote_sync_backups_path()
  60. {
  61. if [ ! -x "$(command -v rsync)" ]; then
  62. echo "cannot sync backups path"
  63. exit 1
  64. fi
  65. rsync -arz "ssh -p $1" "$2@$3:$4" $5
  66. }
  67. perform_backups $@
  68. delete_old_backups $BKP_PATH $DAYS_TO_KEEP
  69. sync_local_backups_path $BKP_PATH $SYNC_PATH
  70. exit 0