command_backup.sh 10 KB

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