command_backup.sh 9.6 KB

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