healthcheck.sh 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/bin/bash
  2. # Declare log function for logfile inside container
  3. function log_to_file() {
  4. echo "$(date +"%Y-%m-%d %H:%M:%S"): $1" > /var/log/healthcheck.log
  5. }
  6. # General Ping function to check general pingability
  7. function check_ping() {
  8. declare -a ipstoping=("1.1.1.1" "8.8.8.8" "9.9.9.9")
  9. for ip in "${ipstoping[@]}" ; do
  10. ping -q -c 3 -w 5 "$ip"
  11. if [ $? -ne 0 ]; then
  12. log_to_file "Healthcheck: Couldn't ping $ip for 5 seconds... Gave up!"
  13. log_to_file "Please check your internet connection or firewall rules to fix this error, because a simple ping test should always go through from the unbound container!"
  14. return 1
  15. fi
  16. done
  17. log_to_file "Healthcheck: Ping Checks WORKING properly!"
  18. return 0
  19. }
  20. # General DNS Resolve Check against Unbound Resolver himself
  21. function check_dns() {
  22. declare -a domains=("mailcow.email" "github.com" "hub.docker.com")
  23. for domain in "${domains[@]}" ; do
  24. for ((i=1; i<=3; i++)); do
  25. dig +short +timeout=2 +tries=1 "$domain" @127.0.0.1 > /dev/null
  26. if [ $? -ne 0 ]; then
  27. log_to_file "Healthcheck: DNS Resolution Failed on $i attempt! Trying again..."
  28. if [ $i -eq 3 ]; then
  29. log_to_file "Healthcheck: DNS Resolution not possible after $i attempts... Gave up!"
  30. log_to_file "Maybe check your outbound firewall, as it needs to resolve DNS over TCP AND UDP!"
  31. return 1
  32. fi
  33. fi
  34. done
  35. done
  36. log_to_file "Healthcheck: DNS Resolver WORKING properly!"
  37. return 0
  38. }
  39. # Simple Netcat Check to connect to common webports
  40. function check_netcat() {
  41. declare -a domains=("mailcow.email" "github.com" "hub.docker.com")
  42. declare -a ports=("80" "443")
  43. for domain in "${domains[@]}" ; do
  44. for port in "${ports[@]}" ; do
  45. nc -z -w 2 $domain $port
  46. if [ $? -ne 0 ]; then
  47. log_to_file "Healthcheck: Could not reach $domain on Port $port... Gave up!"
  48. log_to_file "Please check your internet connection or firewall rules to fix this error."
  49. return 1
  50. fi
  51. done
  52. done
  53. log_to_file "Healthcheck: Netcat Checks WORKING properly!"
  54. return 0
  55. }
  56. # run checks, if check is not returning 0 (return value if check is ok), healthcheck will exit with 1 (marked in docker as unhealthy)
  57. check_ping
  58. if [ $? -ne 0 ]; then
  59. exit 1
  60. fi
  61. check_dns
  62. if [ $? -ne 0 ]; then
  63. exit 1
  64. fi
  65. check_netcat
  66. if [ $? -ne 0 ]; then
  67. exit 1
  68. fi
  69. log_to_file "Healthcheck: ALL CHECKS WERE SUCCESSFUL! Unbound is healthy!"
  70. exit 0