command_backup.sh 9.7 KB

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