command_backup.sh 9.0 KB

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