monitor.sh 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/bin/sh
  2. set -e
  3. if [ -z "$TOR_HOST" ]; then
  4. echo 'missing $TOR_HOST'
  5. exit 1
  6. elif [ -z "$ONION_SERVICE_HOST" ]; then
  7. echo 'missing $ONION_SERVICE_HOST'
  8. exit 1
  9. elif [ -z "$ONION_SERVICE_PORT" ]; then
  10. echo 'missing $ONION_SERVICE_PORT'
  11. exit 1
  12. elif [ -z "$MAIL_TO" ]; then
  13. echo 'missing $MAIL_TO'
  14. exit 1
  15. fi
  16. sender_address="onion-service-status@$(hostname).local"
  17. ping_onion_service() {(
  18. if [ ! -z "$VERBOSE" ]; then
  19. set -x
  20. fi
  21. nc -z -w "$TIMEOUT_SECONDS" -x "$TOR_HOST:$TOR_PORT" "$ONION_SERVICE_HOST" "$ONION_SERVICE_PORT"
  22. )}
  23. send_report() {(
  24. if [ ! -z "$VERBOSE" ]; then
  25. set -x
  26. fi
  27. sendmail -t <<EOF
  28. From: $sender_address
  29. To: $MAIL_TO
  30. Subject: $ONION_SERVICE_HOST:$ONION_SERVICE_PORT $1
  31. EOF
  32. )}
  33. last_state=""
  34. left_retries="$RETRIES"
  35. while : ; do
  36. if ! nc -z -w "$TIMEOUT_SECONDS" "$TOR_HOST" "$TOR_PORT"; then
  37. echo "failed to connect to tor proxy at $TOR_HOST:$TOR_PORT"
  38. else
  39. if ping_onion_service; then
  40. if [ "$last_state" == "offline" ]; then
  41. echo went online
  42. send_report online
  43. fi
  44. last_state="online"
  45. left_retries=$RETRIES
  46. else
  47. if [ $left_retries -le 0 ]; then
  48. if [ "$last_state" == "online" ]; then
  49. echo went offline
  50. send_report offline
  51. fi
  52. last_state="offline"
  53. else
  54. left_retries=$((left_retries-1))
  55. [ ! -z "$VERBOSE" ] && echo "$left_retries retry/ies left"
  56. fi
  57. fi
  58. fi
  59. # flush queue
  60. dma -q1
  61. sleep "$SLEEP_DURATION"
  62. done