command_backup.sh 10 KB

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