command_backup.sh 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #!/bin/bash
  2. # LinuxGSM command_backup.sh function
  3. # Author: Daniel Gibbs
  4. # Contributor: UltimateByte
  5. # Website: https://linuxgsm.com
  6. # Description: Creates a .tar.gz file in the backup directory.
  7. local commandname="BACKUP"
  8. local commandaction="Backup"
  9. local function_selfname="$(basename "$(readlink -f "${BASH_SOURCE[0]}")")"
  10. check.sh
  11. # Trap to remove lockfile on quit.
  12. fn_backup_trap(){
  13. echo ""
  14. echo -en "backup ${backupname}.tar.gz..."
  15. fn_print_canceled_eol_nl
  16. fn_script_log_info "Backup ${backupname}.tar.gz: CANCELED"
  17. rm -f "${backupdir}/${backupname}.tar.gz" | tee -a "${lgsmlog}"
  18. echo -en "backup ${backupname}.tar.gz..."
  19. fn_print_removed_eol_nl
  20. fn_script_log_info "Backup ${backupname}.tar.gz: REMOVED"
  21. # Remove lock file.
  22. rm -f "${tmpdir}/.backup.lock"
  23. core_exit.sh
  24. }
  25. # Check if a backup is pending or has been aborted using .backup.lock.
  26. fn_backup_check_lockfile(){
  27. if [ -f "${tmpdir}/.backup.lock" ]; then
  28. fn_print_info_nl "Lock file found: Backup is currently running"
  29. fn_script_log_error "Lock file found: Backup is currently running: ${tmpdir}/.backup.lock"
  30. core_exit.sh
  31. fi
  32. }
  33. # Initialisation.
  34. fn_backup_init(){
  35. # Backup file name with servicename and current date.
  36. backupname="${servicename}-$(date '+%Y-%m-%d-%H%M%S')"
  37. info_distro.sh
  38. fn_print_dots "Backup starting"
  39. fn_script_log_info "Backup starting"
  40. fn_print_ok_nl "Backup starting"
  41. if [ ! -d "${backupdir}" ]||[ "${backupcount}" == "0" ]; then
  42. fn_print_info_nl "There are no previous backups"
  43. else
  44. if [ "${lastbackupdaysago}" == "0" ]; then
  45. daysago="less than 1 day ago"
  46. elif [ "${lastbackupdaysago}" == "1" ]; then
  47. daysago="1 day ago"
  48. else
  49. daysago="${lastbackupdaysago} days ago"
  50. fi
  51. echo " * Previous backup was created ${daysago}, total size ${lastbackupsize}"
  52. fi
  53. }
  54. # Check if server is started and whether to stop it.
  55. fn_backup_stop_server(){
  56. check_status.sh
  57. # Server is stopped.
  58. if [ "${status}" == "0" ]; then
  59. serverstopped="no"
  60. # Server is running and stoponbackup=off.
  61. elif [ "${stoponbackup}" == "off" ]; then
  62. serverstopped="no"
  63. fn_print_warn_nl "${servicename} is currently running"
  64. echo " * Although unlikely; creating a backup while ${servicename} is running might corrupt the backup."
  65. fn_script_log_warn "${servicename} is currently running"
  66. fn_script_log_warn "Although unlikely; creating a backup while ${servicename} is running might corrupt the backup"
  67. # Server is running and will be stopped if stoponbackup=on or unset.
  68. else
  69. fn_print_warn_nl "${servicename} will be stopped during the backup"
  70. fn_script_log_warn "${servicename} will be stopped during the backup"
  71. serverstopped="yes"
  72. exitbypass=1
  73. command_stop.sh
  74. fi
  75. }
  76. # Create required folders.
  77. fn_backup_dir(){
  78. # Create backupdir if it doesn't exist.
  79. if [ ! -d "${backupdir}" ]; then
  80. mkdir -p "${backupdir}"
  81. fi
  82. }
  83. fn_backup_create_lockfile(){
  84. # Create lockfile.
  85. date '+%s' > "${tmpdir}/.backup.lock"
  86. fn_script_log_info "Lockfile generated"
  87. fn_script_log_info "${tmpdir}/.backup.lock"
  88. # trap to remove lockfile on quit.
  89. trap fn_backup_trap INT
  90. }
  91. # Compressing files.
  92. fn_backup_compression(){
  93. # Tells how much will be compressed using rootdirduexbackup value from info_distro and prompt for continue.
  94. fn_print_info "A total of ${rootdirduexbackup} will be compressed."
  95. fn_script_log_info "A total of ${rootdirduexbackup} will be compressed: ${backupdir}/${backupname}.tar.gz"
  96. fn_print_dots "Backup (${rootdirduexbackup}) ${backupname}.tar.gz, in progress..."
  97. fn_script_log_info "backup ${rootdirduexbackup} ${backupname}.tar.gz, in progress"
  98. excludedir=$(fn_backup_relpath)
  99. # Check that excludedir is a valid path.
  100. if [ ! -d "${excludedir}" ] ; then
  101. fn_print_fail_nl "Problem identifying the previous backup directory for exclusion."
  102. fn_script_log_fatal "Problem identifying the previous backup directory for exclusion"
  103. core_exit.sh
  104. fi
  105. tar -czf "${backupdir}/${backupname}.tar.gz" -C "${rootdir}" --exclude "${excludedir}" --exclude "${tmpdir}/.backup.lock" ./.
  106. local exitcode=$?
  107. if [ ${exitcode} -ne 0 ]; then
  108. fn_print_fail_eol
  109. fn_script_log_fatal "Backup in progress: FAIL"
  110. echo "${tarcmd}" | tee -a "${lgsmlog}"
  111. fn_print_fail_nl "Starting backup"
  112. fn_script_log_fatal "Starting backup"
  113. else
  114. fn_print_ok_eol
  115. fn_print_ok_nl "Completed: ${backupname}.tar.gz, total size $(du -sh "${backupdir}/${backupname}.tar.gz" | awk '{print $1}')"
  116. fn_script_log_pass "Backup created: ${backupname}.tar.gz, total size $(du -sh "${backupdir}/${backupname}.tar.gz" | awk '{print $1}')"
  117. fi
  118. # Remove lock file
  119. rm -f "${tmpdir}/.backup.lock"
  120. }
  121. # Clear old backups according to maxbackups and maxbackupdays variables.
  122. fn_backup_prune(){
  123. # Clear if backup variables are set.
  124. if [ -n "${maxbackups}" ]&&[ -n "${maxbackupdays}" ]; then
  125. # How many backups there are.
  126. info_distro.sh
  127. # How many backups exceed maxbackups.
  128. backupquotadiff=$((backupcount-maxbackups))
  129. # How many backups exceed maxbackupdays.
  130. backupsoudatedcount=$(find "${backupdir}"/ -type f -name "*.tar.gz" -mtime +"${maxbackupdays}"|wc -l)
  131. # If anything can be cleared.
  132. if [ "${backupquotadiff}" -gt "0" ]||[ "${backupsoudatedcount}" -gt "0" ]; then
  133. fn_print_dots "Pruning"
  134. fn_script_log_info "Backup pruning activated"
  135. fn_print_ok_nl "Pruning"
  136. # If maxbackups greater or equal to backupsoutdatedcount, then it is over maxbackupdays.
  137. if [ "${backupquotadiff}" -ge "${backupsoudatedcount}" ]; then
  138. # Display how many backups will be cleared.
  139. echo " * Pruning: ${backupquotadiff} backup(s) has exceeded the ${maxbackups} backups limit"
  140. fn_script_log_info "Pruning: ${backupquotadiff} backup(s) has exceeded the ${maxbackups} backups limit"
  141. fn_sleep_time
  142. fn_print_dots "Pruning: Clearing ${backupquotadiff} backup(s)"
  143. fn_script_log_info "Pruning: Clearing ${backupquotadiff} backup(s)"
  144. # Clear backups over quota.
  145. find "${backupdir}"/ -type f -name "*.tar.gz" -printf '%T@ %p\n' | sort -rn | tail -${backupquotadiff} | cut -f2- -d" " | xargs rm
  146. fn_print_ok_nl "Pruning: Clearing ${backupquotadiff} backup(s)"
  147. fn_script_log_pass "Pruning: Cleared ${backupquotadiff} backup(s)"
  148. # If maxbackupdays is used over maxbackups.
  149. elif [ "${backupquotadiff}" -lt "${backupsoudatedcount}" ]; then
  150. # Display how many backups will be cleared.
  151. echo " * Pruning: ${backupsoudatedcount} backup(s) are older than ${maxbackupdays} days."
  152. fn_script_log_info "Pruning: ${backupsoudatedcount} backup(s) older than ${maxbackupdays} days."
  153. fn_sleep_time
  154. fn_print_dots "Pruning: Clearing ${backupquotadiff} backup(s)."
  155. fn_script_log_info "Pruning: Clearing ${backupquotadiff} backup(s)"
  156. # Clear backups over quota
  157. find "${backupdir}"/ -type f -mtime +"${maxbackupdays}" -exec rm -f {} \;
  158. fn_print_ok_nl "Pruning: Clearing ${backupquotadiff} backup(s)"
  159. fn_script_log_pass "Pruning: Cleared ${backupquotadiff} backup(s)"
  160. fi
  161. fi
  162. fi
  163. }
  164. fn_backup_relpath() {
  165. # Written by CedarLUG as a "realpath --relative-to" alternative in bash.
  166. # Populate an array of tokens initialized from the rootdir components.
  167. declare -a rdirtoks=($(readlink -f "${rootdir}" | sed "s/\// /g"))
  168. if [ ${#rdirtoks[@]} -eq 0 ]; then
  169. fn_print_fail_nl "Problem assessing rootdir during relative path assessment"
  170. fn_script_log_fatal "Problem assessing rootdir during relative path assessment: ${rootdir}"
  171. core_exit.sh
  172. fi
  173. # Populate an array of tokens initialized from the backupdir components.
  174. declare -a bdirtoks=($(readlink -f "${backupdir}" | sed "s/\// /g"))
  175. if [ ${#bdirtoks[@]} -eq 0 ]; then
  176. fn_print_fail_nl "Problem assessing backupdir during relative path assessment"
  177. fn_script_log_fatal "Problem assessing backupdir during relative path assessment: ${rootdir}"
  178. core_exit.sh
  179. fi
  180. # Compare the leading entries of each array. These common elements will be clipped off.
  181. # for the relative path output.
  182. for ((base=0; base<${#rdirtoks[@]}; base++))
  183. do
  184. [[ "${rdirtoks[$base]}" != "${bdirtoks[$base]}" ]] && break
  185. done
  186. # Next, climb out of the remaining rootdir location with updir references.
  187. for ((x=base;x<${#rdirtoks[@]};x++))
  188. do
  189. echo -n "../"
  190. done
  191. # Climb down the remaining components of the backupdir location.
  192. for ((x=base;x<$(( ${#bdirtoks[@]} - 1 ));x++))
  193. do
  194. echo -n "${bdirtoks[$x]}/"
  195. done
  196. # In the event there were no directories left in the backupdir above to
  197. # traverse down, just add a newline. Otherwise at this point, there is
  198. # one remaining directory component in the backupdir to navigate.
  199. if (( "$base" < "${#bdirtoks[@]}" )) ; then
  200. echo "${bdirtoks[ $(( ${#bdirtoks[@]} - 1)) ]}"
  201. else
  202. echo
  203. fi
  204. }
  205. # Restart the server if it was stopped for the backup.
  206. fn_backup_start_server(){
  207. if [ "${serverstopped}" == "yes" ]; then
  208. exitbypass=1
  209. command_start.sh
  210. fi
  211. }
  212. # Run functions.
  213. fn_backup_check_lockfile
  214. fn_backup_create_lockfile
  215. fn_backup_init
  216. fn_backup_stop_server
  217. fn_backup_dir
  218. fn_backup_compression
  219. fn_backup_prune
  220. fn_backup_start_server
  221. core_exit.sh