Advertisement
Guest User

Untitled

a guest
Sep 24th, 2022
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.13 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3.  
  4. # max attempts before failure
  5. ATTEMPTS=5
  6. if [ $# -gt 1 ]; then
  7.   ATTEMPTS=$1
  8.   shift
  9. fi
  10.  
  11. TIMEOUT=1
  12. if [ $# -gt 1 ]; then
  13.   TIMEOUT=$1
  14.   shift
  15. fi
  16.  
  17. REINIT_AFTER=3600
  18. if [ $# -gt 1 ]; then
  19.   REINIT_AFTER=$4
  20.   shift
  21. fi
  22.  
  23. # process to watch
  24. PROCESS=$1
  25.  
  26. STATE_FILE="/var/run/backoff/$PROCESS.state"
  27.  
  28. if ! [ -f "$STATE_FILE" ]; then
  29.   mkdir -p $(dirname "$STATE_FILE")
  30.   echo 0 > "$STATE_FILE"
  31. fi
  32.  
  33. function get_time_delta_of_last_attempt {
  34.   let diff=$(date +%s)-$(stat -c %Y "$STATE_FILE")
  35.   echo $diff
  36. }
  37.  
  38. if [ $(get_time_delta_of_last_attempt) -gt $REINIT_AFTER ]; then
  39.   echo 0 > "$STATE_FILE"
  40. fi
  41.  
  42. function with_backoff {
  43.   local max_attempts=$ATTEMPTS
  44.   local timeout=$TIMEOUT
  45.   local attempt=$(cat "$STATE_FILE")
  46.   local exitCode=0
  47.  
  48.   i=0
  49.   while [ $i -lt $attempt ]; do
  50.     let i=$i+1
  51.     let timeout=$timeout*2
  52.     if [ $timeout -gt $REINIT_AFTER ]; then
  53.       timeout=$REINIT_AFTER
  54.     fi
  55.   done
  56.  
  57.   let attempt=$attempt+1
  58.   echo $attempt > "$STATE_FILE"
  59.   sleep $timeout
  60.   if [ $attempt -le $max_attempts ] || [ $max_attempts -eq 0 ]; then
  61.     exec "$@"
  62.   fi
  63.  
  64. }
  65.  
  66. with_backoff "$@"
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement