Advertisement
Guest User

snapraid script

a guest
Jul 15th, 2019
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 16.77 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. #######################################################################
  4. # This is a helper script that keeps snapraid parity info in sync with
  5. # your data and optionally verifies the parity info. Here's how it works:
  6. #   1) Shuts down configured services
  7. #   2) Calls diff to figure out if the parity info is out of sync.
  8. #   3) If parity info is out of sync, AND the number of deleted or changed files exceed
  9. #      X (each configurable), it triggers an alert email and stops. (In case of
  10. #      accidental deletions, you have the opportunity to recover them from
  11. #      the existing parity info. This also mitigates to a degree encryption malware.)
  12. #   4) If partiy info is out of sync, AND the number of deleted or changed files exceed X
  13. #      AND it has reached/exceeded Y (configurable) number of warnings, force
  14. #      a sync. (Useful when you get a false alarm above and you can't be bothered
  15. #      to login and do a manual sync. Note the risk is if its not a false alarm
  16. #      and you can't access the box before Y number of times the job is run  to
  17. #      fix the issue... Well I hope you have other backups...)
  18. #   5) If parity info is out of sync BUT the number of deleted files did NOT
  19. #      exceed X, it calls sync to update the parity info.
  20. #   6) If the parity info is in sync (either because nothing changed or after it
  21. #      has successfully completed the sync job, it runs the scrub command to
  22. #      validate the integrity of the data (both the files and the parity info).
  23. #      Note that each run of the scrub command will validate only a (configurable)
  24. #      portion of parity info to avoid having a long running job and affecting
  25. #      the performance of the box.
  26. #   7) Once all jobs are completed, it sends an email with the output to user
  27. #      (if configured).
  28. #
  29. #   Inspired by Zack Reed (http://zackreed.me/articles/83-updated-snapraid-sync-script)
  30. #   Modified version of mtompkins version of my script (https://gist.github.com/mtompkins/91cf0b8be36064c237da3f39ff5cc49d)
  31. #
  32. #######################################################################
  33.  
  34. ######################
  35. #   USER VARIABLES   #
  36. ######################
  37.  
  38. ####################### USER CONFIGURATION START #######################
  39.  
  40. # address where the output of the jobs will be emailed to.
  41. EMAIL_ADDRESS="[email protected]"
  42.  
  43. # Set the threshold of deleted files to stop the sync job from running.
  44. # NOTE that depending on how active your filesystem is being used, a low
  45. # number here may result in your parity info being out of sync often and/or
  46. # you having to do lots of manual syncing.
  47. DEL_THRESHOLD=50
  48. UP_THRESHOLD=500
  49.  
  50. # Set number of warnings before we force a sync job.
  51. # This option comes in handy when you cannot be bothered to manually
  52. # start a sync job when DEL_THRESHOLD is breached due to false alarm.
  53. # Set to 0 to ALWAYS force a sync (i.e. ignore the delete threshold above)
  54. # Set to -1 to NEVER force a sync (i.e. need to manual sync if delete threshold is breached)
  55. #SYNC_WARN_THRESHOLD=3
  56. SYNC_WARN_THRESHOLD=-1
  57.  
  58. # Set percentage of array to scrub if it is in sync.
  59. # i.e. 0 to disable and 100 to scrub the full array in one go
  60. # WARNING - depending on size of your array, setting to 100 will take a very long time!
  61. SCRUB_PERCENT=25
  62. SCRUB_AGE=10
  63.  
  64. # Set the option to log SMART info. 1 to enable, any other values to disable
  65. SMART_LOG=1
  66.  
  67. # location of the snapraid binary
  68. SNAPRAID_BIN="/usr/local/bin/snapraid"
  69. # location of the mail program binary
  70. MAIL_BIN="/usr/bin/mail"
  71.  
  72. function main(){
  73.  
  74.   ######################
  75.   #   INIT VARIABLES   #
  76.   ######################
  77.   CHK_FAIL=0
  78.   DO_SYNC=0
  79.   EMAIL_SUBJECT_PREFIX="(SnapRAID on `hostname`)"
  80.   GRACEFUL=0
  81.   SYNC_WARN_FILE="/tmp/snapRAID.warnCount"
  82.   SYNC_WARN_COUNT=""
  83.   TMP_OUTPUT="/tmp/snapRAID.out"
  84.   # Capture time
  85.   SECONDS=0
  86.  
  87.   ###############################
  88.   #   MANAGE DOCKER CONTAINERS  #
  89.   ###############################
  90.   # Set to 0 to not manage any containers.
  91.   MANAGE_SERVICES=1
  92.  
  93.   # Containers to manage (separated with spaces).
  94.   SERVICES='nzbget sonarr radarr lidarr jackett bazarr plex transmission prometheus grafana nextcloud nextcloud-mariadb watchtower organizr portainer'
  95.  
  96.   # Build Services Array...
  97.   service_array_setup
  98.  
  99.   # Expand PATH for smartctl
  100.   PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
  101.  
  102.   # Determine names of first content file...
  103.   CONTENT_FILE=`grep -v '^$\|^\s*\#' /etc/snapraid.conf | grep snapraid.content | head -n 1 | cut -d " " -f2`
  104.  
  105.   # Build an array of parity all files...
  106.   #PARITY_FILES[0]=`cat /etc/snapraid.conf | grep "^[^#;]" | grep parity | head -n 1 | cut -d " " -f 2 | cut -d "," -f 1`
  107.   #PARITY_FILES[1]=`cat /etc/snapraid.conf | grep "^[^#;]" | grep parity | head -n 1 | cut -d " " -f 2 | cut -d "," -f 2`
  108.   #PARITY_FILES[2]=`cat /etc/snapraid.conf | grep "^[^#;]" | grep 2-parity | head -n 1 | cut -d " " -f 2 | cut -d "," -f 1`
  109.   #PARITY_FILES[3]=`cat /etc/snapraid.conf | grep "^[^#;]" | grep 2-parity | head -n 1 | cut -d " " -f 2 | cut -d "," -f 2`
  110.   IFS=$'\n' PARITY_FILES=(`cat /etc/snapraid.conf | grep "^[^#;]" | grep "^\([2-6z]-\)*parity" | cut -d " " -f 2 | tr ',' '\n'`)
  111.  
  112. ##### USER CONFIGURATION STOP ##### MAKE NO CHANGES BELOW THIS LINE ####
  113.  
  114.   # redirect all output to screen and file
  115.   > $TMP_OUTPUT
  116.   exec 3>&1 4>&2
  117.   # NOTE: Not preferred format but valid: exec &> >(tee -ia "${TMP_OUTPUT}" )
  118.   exec > >(tee -ia "${TMP_OUTPUT}" ) 2>&1
  119.  
  120.   # timestamp the job
  121.   echo "SnapRAID Script Job started [`date`]"
  122.   echo
  123.   echo "----------------------------------------"
  124.  
  125.   # Remove any plex created anomolies
  126.   echo "##Preprocessing"
  127.  
  128.   # Stop any services that may inhibit optimum execution
  129.   if [ $MANAGE_SERVICES -eq 1 ]; then
  130.     echo "###Stop Services [`date`]"
  131.     stop_services
  132.   fi
  133.  
  134.   # sanity check first to make sure we can access the content and parity files
  135.   sanity_check
  136.  
  137.   echo
  138.   echo "----------------------------------------"
  139.   echo "##Processing"
  140.  
  141.   # Fix timestamps
  142.   chk_zero
  143.  
  144.   # run the snapraid DIFF command
  145.   echo "###SnapRAID DIFF [`date`]"
  146.   $SNAPRAID_BIN diff
  147.   # wait for the above cmd to finish
  148.   diff_pid=$!
  149.   echo "#### Diff Pid  [$diff_pid]  ####"
  150.   wait
  151.   echo
  152.   echo "DIFF finished [`date`]"
  153.   JOBS_DONE="DIFF"
  154.  
  155.   # Get number of deleted, updated, and modified files...
  156.   get_counts
  157.  
  158.   # sanity check to make sure that we were able to get our counts from the output of the DIFF job
  159.   if [ -z "$DEL_COUNT" -o -z "$ADD_COUNT" -o -z "$MOVE_COUNT" -o -z "$COPY_COUNT" -o -z "$UPDATE_COUNT" ]; then
  160.     # failed to get one or more of the count values, lets report to user and exit with error code
  161.     echo "**ERROR** - failed to get one or more count values. Unable to proceed."
  162.     echo "Exiting script. [`date`]"
  163.     if [ $EMAIL_ADDRESS ]; then
  164.       SUBJECT="$EMAIL_SUBJECT_PREFIX WARNING - Unable to proceed with SYNC/SCRUB job(s). Check DIFF job output."
  165.       send_mail
  166.     fi
  167.     exit 1;
  168.   fi
  169.   echo
  170.   echo "**SUMMARY of changes - Added [$ADD_COUNT] - Deleted [$DEL_COUNT] - Moved [$MOVE_COUNT] - Copied [$COPY_COUNT] - Updated [$UPDATE_COUNT]**"
  171.   echo
  172.  
  173.   # check if the conditions to run SYNC are met
  174.   # CHK 1 - if files have changed
  175.   if [ $DEL_COUNT -gt 0 -o $ADD_COUNT -gt 0 -o $MOVE_COUNT -gt 0 -o $COPY_COUNT -gt 0 -o $UPDATE_COUNT -gt 0 ]; then
  176.     chk_del
  177.  
  178.     if [ $CHK_FAIL -eq 0 ]; then
  179.       chk_updated
  180.     fi
  181.  
  182.     if [ $CHK_FAIL -eq 1 ]; then
  183.       chk_sync_warn
  184.     fi
  185.   else
  186.     # NO, so let's skip SYNC
  187.     echo "No change detected. Not running SYNC job. [`date`] "
  188.     DO_SYNC=0
  189.   fi
  190.  
  191.   # Now run sync if conditions are met
  192.   if [ $DO_SYNC -eq 1 ]; then
  193.     echo "###SnapRAID SYNC [`date`]"
  194.     $SNAPRAID_BIN sync -q
  195.     #wait for the job to finish
  196.     wait
  197.     echo "SYNC finished [`date`]"
  198.     JOBS_DONE="$JOBS_DONE + SYNC"
  199.     # insert SYNC marker to 'Everything OK' or 'Nothing to do' string to differentiate it from SCRUB job later
  200.     sed_me "s/^Everything OK/SYNC_JOB--Everything OK/g;s/^Nothing to do/SYNC_JOB--Nothing to do/g" "$TMP_OUTPUT"
  201.     # Remove any warning flags if set previously. This is done in this step to take care of scenarios when user
  202.     # has manually synced or restored deleted files and we will have missed it in the checks above.
  203.     if [ -e $SYNC_WARN_FILE ]; then
  204.       rm $SYNC_WARN_FILE
  205.     fi
  206.     echo
  207.   fi
  208.  
  209.   # Moving onto scrub now. Check if user has enabled scrub
  210.   if [ $SCRUB_PERCENT -gt 0 ]; then
  211.     # YES, first let's check if delete threshold has been breached and we have not forced a sync.
  212.     if [ $CHK_FAIL -eq 1 -a $DO_SYNC -eq 0 ]; then
  213.       # YES, parity is out of sync so let's not run scrub job
  214.       echo "Scrub job cancelled as parity info is out of sync (deleted or changed files threshold has been breached). [`date`]"
  215.     else
  216.       # NO, delete threshold has not been breached OR we forced a sync, but we have one last test -
  217.       # let's make sure if sync ran, it completed successfully (by checking for our marker text "SYNC_JOB--" in the output).
  218.       if [ $DO_SYNC -eq 1 -a -z "$(grep -w "SYNC_JOB-" $TMP_OUTPUT)" ]; then
  219.         # Sync ran but did not complete successfully so lets not run scrub to be safe
  220.         echo "**WARNING** - check output of SYNC job. Could not detect marker . Not proceeding with SCRUB job. [`date`]"
  221.       else
  222.         # Everything ok - let's run the scrub job!
  223.         echo "###SnapRAID SCRUB [`date`]"
  224.         $SNAPRAID_BIN scrub -p $SCRUB_PERCENT -o $SCRUB_AGE -q
  225.         #wait for the job to finish
  226.           wait
  227.         echo "SCRUB finished [`date`]"
  228.         echo
  229.         JOBS_DONE="$JOBS_DONE + SCRUB"
  230.         # insert SCRUB marker to 'Everything OK' or 'Nothing to do' string to differentiate it from SYNC job above
  231.         sed_me "s/^Everything OK/SCRUB_JOB--Everything OK/g;s/^Nothing to do/SCRUB_JOB--Nothing to do/g" "$TMP_OUTPUT"
  232.       fi
  233.     fi
  234.   else
  235.     echo "Scrub job is not enabled. Not running SCRUB job. [`date`] "
  236.   fi
  237.  
  238.   echo
  239.   echo "----------------------------------------"
  240.   echo "##Postprocessing"
  241.  
  242.   # Moving onto logging SMART info if enabled
  243.   if [ $SMART_LOG -eq 1 ]; then
  244.     echo
  245.     $SNAPRAID_BIN smart
  246.     #smart_pid=$!
  247.     wait
  248.   fi
  249.  
  250.   echo "Spinning down disks..."
  251.   $SNAPRAID_BIN down
  252.  
  253.   # Graceful restore of services outside of trap - for messaging
  254.   GRACEFUL=1
  255.   if [ $MANAGE_SERVICES -eq 1 ]; then
  256.     restore_services
  257.   fi  
  258.  
  259.   echo "All jobs ended. [`date`] "
  260.  
  261.   # all jobs done, let's send output to user if configured
  262.   if [ $EMAIL_ADDRESS ]; then
  263.     echo -e "Email address is set. Sending email report to **$EMAIL_ADDRESS** [`date`]"
  264.     # check if deleted count exceeded threshold
  265.     prepare_mail
  266.  
  267.     ELAPSED="$(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
  268.     echo
  269.     echo "----------------------------------------"
  270.     echo "##Total time elapsed for SnapRAID: $ELAPSED"
  271.  
  272.     # Add a topline to email body
  273.     sed_me "1s/^/##$SUBJECT \n/" "${TMP_OUTPUT}"
  274.     send_mail
  275.   fi
  276.  
  277.   clean_desc
  278.  
  279.   exit 0;
  280. }
  281.  
  282. #######################
  283. # FUNCTIONS & METHODS #
  284. #######################
  285.  
  286. function sanity_check() {
  287.   if [ ! -e $CONTENT_FILE ]; then
  288.     echo "**ERROR** Content file ($CONTENT_FILE) not found!"
  289.     exit 1;
  290.   fi
  291.  
  292.   echo "Testing that all parity files are present."
  293.   for i in "${PARITY_FILES[@]}"
  294.     do
  295.       if [ ! -e $i ]; then
  296.         echo "[`date`] ERROR - Parity file ($i) not found!"
  297.         echo "ERROR - Parity file ($i) not found!" >> $TMP_OUTPUT
  298.         exit 1;
  299.       fi
  300.   done
  301.   echo "All parity files found. Continuing..."
  302. }
  303.  
  304. function get_counts() {
  305.   DEL_COUNT=$(grep -w '^ \{1,\}[0-9]* removed' $TMP_OUTPUT | sed 's/^ *//g' | cut -d ' ' -f1)
  306.   ADD_COUNT=$(grep -w '^ \{1,\}[0-9]* added' $TMP_OUTPUT | sed 's/^ *//g' | cut -d ' ' -f1)
  307.   MOVE_COUNT=$(grep -w '^ \{1,\}[0-9]* moved' $TMP_OUTPUT | sed 's/^ *//g' | cut -d ' ' -f1)
  308.   COPY_COUNT=$(grep -w '^ \{1,\}[0-9]* copied' $TMP_OUTPUT | sed 's/^ *//g' | cut -d ' ' -f1)
  309.   UPDATE_COUNT=$(grep -w '^ \{1,\}[0-9]* updated' $TMP_OUTPUT | sed 's/^ *//g' | cut -d ' ' -f1)
  310. }
  311.  
  312. function sed_me(){
  313.   # The various redirects used force us to be a bit hands-on with sed
  314.   exec 1>&3 2>&4 3>&- 4>&-
  315.   $(sed -i "$1" "$2")
  316.   exec 3>&1 4>&2
  317.   exec > >(tee -ia "${TMP_OUTPUT}" ) 2>&1
  318.   sedme_pid=$!
  319.   echo "#### SedMe Pid  [$sedme_pid]  ####"
  320.   wait
  321. }
  322.  
  323. function chk_del(){
  324.   if [ $DEL_COUNT -lt $DEL_THRESHOLD ]; then
  325.     # NO, delete threshold not reached, lets run the sync job
  326.     echo "There are deleted files. The number of deleted files, ($DEL_COUNT), is below the threshold of ($DEL_THRESHOLD). SYNC Authorized."
  327.     DO_SYNC=1
  328.   else
  329.     echo "**WARNING** Deleted files ($DEL_COUNT) exceeded threshold ($DEL_THRESHOLD)."
  330.     CHK_FAIL=1
  331.   fi
  332. }
  333.  
  334. function chk_updated(){
  335.   if [ $UPDATE_COUNT -lt $UP_THRESHOLD ]; then
  336.     echo "There are updated files. The number of updated files, ($UPDATE_COUNT), is below the threshold of ($UP_THRESHOLD). SYNC Authorized."
  337.     DO_SYNC=1
  338.   else
  339.     echo "**WARNING** Updated files ($UPDATE_COUNT) exceeded threshold ($UP_THRESHOLD)."
  340.     CHK_FAIL=1
  341.   fi
  342. }
  343.  
  344. function chk_sync_warn(){
  345.   if [ $SYNC_WARN_THRESHOLD -gt -1 ]; then
  346.     echo "Forced sync is enabled. [`date`]"
  347.  
  348.     SYNC_WARN_COUNT=$(sed 'q;/^[0-9][0-9]*$/!d' $SYNC_WARN_FILE 2>/dev/null)
  349.     SYNC_WARN_COUNT=${SYNC_WARN_COUNT:-0} #value is zero if file does not exist or does not contain what we are expecting
  350.  
  351.     if [ $SYNC_WARN_COUNT -ge $SYNC_WARN_THRESHOLD ]; then
  352.       # YES, lets force a sync job. Do not need to remove warning marker here as it is automatically removed when the sync job is run by this script
  353.       echo "Number of warning(s) ($SYNC_WARN_COUNT) has reached/exceeded threshold ($SYNC_WARN_THRESHOLD). Forcing a SYNC job to run. [`date`]"
  354.       DO_SYNC=1
  355.     else
  356.       # NO, so let's increment the warning count and skip the sync job
  357.       ((SYNC_WARN_COUNT += 1))
  358.       echo $SYNC_WARN_COUNT > $SYNC_WARN_FILE
  359.       echo "$((SYNC_WARN_THRESHOLD - SYNC_WARN_COUNT)) warning(s) till forced sync. NOT proceeding with SYNC job. [`date`]"
  360.       DO_SYNC=0
  361.     fi
  362.   else
  363.     # NO, so let's skip SYNC
  364.     echo "Forced sync is not enabled. Check $TMP_OUTPUT for details. NOT proceeding with SYNC job. [`date`]"
  365.     DO_SYNC=0
  366.   fi
  367. }
  368.  
  369. function chk_zero(){
  370.   echo "###SnapRAID TOUCH [`date`]"
  371.   echo "Checking for zero sub-second files."
  372.   TIMESTATUS=$($SNAPRAID_BIN status | grep 'You have [1-9][0-9]* files with zero sub-second timestamp\.' | sed 's/^You have/Found/g')
  373.   if [ -n "$TIMESTATUS" ]; then
  374.     echo "$TIMESTATUS"
  375.     echo "Running TOUCH job to timestamp. [`date`]"
  376.     $SNAPRAID_BIN touch
  377.     touch_pid=$!
  378.     echo "#### Touch Pid  [$touch_pid]  ####"
  379.     wait
  380.     echo "TOUCH finished [`date`]"
  381.   else
  382.     echo "No zero sub-second timestamp files found."
  383.   fi
  384. }
  385.  
  386. function service_array_setup() {
  387.   if [ -z "$SERVICES" ]; then
  388.     echo "Please configure serivces"
  389.   else
  390.     echo "Setting up service array"
  391.     read -a service_array <<<$SERVICES
  392.   fi
  393. }
  394.  
  395. function stop_services(){
  396.   for i in ${service_array[@]}; do
  397.     echo "Pausing Service - ""${i^}";
  398.     docker pause $i
  399.   done
  400. }
  401.  
  402. function restore_services(){
  403.   for i in ${service_array[@]}; do
  404.     echo "Unpausing Service - ""${i^}";
  405.     docker unpause $i
  406.   done
  407.  
  408.   if [ $GRACEFUL -eq 1 ]; then
  409.     return
  410.   fi
  411.  
  412.   clean_desc
  413.  
  414.   exit
  415. }
  416.  
  417. function clean_desc(){
  418.   # Cleanup file descriptors
  419.   exec 1>&3 2>&4
  420.  
  421.   # If interactive shell restore output
  422.   [[ $- == *i* ]] && exec &>/dev/tty
  423. }
  424.  
  425. function prepare_mail() {
  426.   if [ $CHK_FAIL -eq 1 ]; then
  427.     if [ $DEL_COUNT -gt $DEL_THRESHOLD -a $DO_SYNC -eq 0 ]; then
  428.       MSG="Deleted Files ($DEL_COUNT) / ($DEL_THRESHOLD) Violation"
  429.     fi
  430.  
  431.     if [ $DEL_COUNT -gt $DEL_THRESHOLD -a $UPDATE_COUNT -gt $UP_THRESHOLD -a $DO_SYNC -eq 0 ]; then
  432.       MSG="$MSG & "
  433.     fi
  434.  
  435.     if [ $UPDATE_COUNT -gt $UP_THRESHOLD -a $DO_SYNC -eq 0 ]; then
  436.       MSG="$MSG Changed Files ($UPDATE_COUNT) / ($UP_THRESHOLD) Violation"
  437.     fi
  438.  
  439.     SUBJECT="[WARNING] $SYNC_WARN_COUNT - ($MSG) $EMAIL_SUBJECT_PREFIX"
  440.   elif [ -z "${JOBS_DONE##*"SYNC"*}" -a -z "$(grep -w "SYNC_JOB-" $TMP_OUTPUT)" ]; then
  441.     # Sync ran but did not complete successfully so lets warn the user
  442.     SUBJECT="[WARNING] SYNC job ran but did not complete successfully $EMAIL_SUBJECT_PREFIX"
  443.   elif [ -z "${JOBS_DONE##*"SCRUB"*}" -a -z "$(grep -w "SCRUB_JOB-" $TMP_OUTPUT)" ]; then
  444.     # Scrub ran but did not complete successfully so lets warn the user
  445.     SUBJECT="[WARNING] SCRUB job ran but did not complete successfully $EMAIL_SUBJECT_PREFIX"
  446.   else
  447.     SUBJECT="[COMPLETED] $JOBS_DONE Jobs $EMAIL_SUBJECT_PREFIX"
  448.   fi
  449. }
  450.  
  451. function send_mail(){
  452.   # Format for markdown
  453.   sed_me "s/$/  /" "$TMP_OUTPUT"
  454.   $MAIL_BIN -s "$SUBJECT" "$EMAIL_ADDRESS" < $TMP_OUTPUT
  455. }
  456.  
  457. # Set TRAP
  458. trap restore_services INT EXIT
  459.  
  460. main "$@"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement