watchdog.sh 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #!/bin/bash
  2. trap "exit" INT TERM
  3. trap "kill 0" EXIT
  4. # Prepare
  5. BACKGROUND_TASKS=()
  6. if [[ "${USE_WATCHDOG}" =~ ^([nN][oO]|[nN])+$ ]]; then
  7. echo -e "$(date) - USE_WATCHDOG=n, skipping watchdog..."
  8. sleep 365d
  9. exec $(readlink -f "$0")
  10. fi
  11. # Checks pipe their corresponding container name in this pipe
  12. if [[ ! -p /tmp/com_pipe ]]; then
  13. mkfifo /tmp/com_pipe
  14. fi
  15. # Common functions
  16. progress() {
  17. SERVICE=${1}
  18. TOTAL=${2}
  19. CURRENT=${3}
  20. DIFF=${4}
  21. [[ -z ${DIFF} ]] && DIFF=0
  22. [[ -z ${TOTAL} || -z ${CURRENT} ]] && return
  23. [[ ${CURRENT} -gt ${TOTAL} ]] && return
  24. [[ ${CURRENT} -lt 0 ]] && CURRENT=0
  25. PERCENT=$(( 200 * ${CURRENT} / ${TOTAL} % 2 + 100 * ${CURRENT} / ${TOTAL} ))
  26. redis-cli -h redis LPUSH WATCHDOG_LOG "{\"time\":\"$(date +%s)\",\"service\":\"${SERVICE}\",\"lvl\":\"${PERCENT}\",\"hpnow\":\"${CURRENT}\",\"hptotal\":\"${TOTAL}\",\"hpdiff\":\"${DIFF}\"}" > /dev/null
  27. log_msg "${SERVICE} health level: ${PERCENT}% (${CURRENT}/${TOTAL}), health trend: ${DIFF}" no_redis
  28. }
  29. log_msg() {
  30. if [[ ${2} != "no_redis" ]]; then
  31. redis-cli -h redis LPUSH WATCHDOG_LOG "{\"time\":\"$(date +%s)\",\"message\":\"$(printf '%s' "${1}" | \
  32. tr '%&;$"_[]{}-\r\n' ' ')\"}" > /dev/null
  33. fi
  34. redis-cli -h redis LTRIM WATCHDOG_LOG 0 ${LOG_LINES} > /dev/null
  35. echo $(date) $(printf '%s\n' "${1}")
  36. }
  37. function mail_error() {
  38. [[ -z ${1} ]] && return 1
  39. [[ -z ${2} ]] && return 2
  40. RCPT_DOMAIN=$(echo ${1} | awk -F @ {'print $NF'})
  41. RCPT_MX=$(dig +short ${RCPT_DOMAIN} mx | sort -n | awk '{print $2; exit}')
  42. if [[ -z ${RCPT_MX} ]]; then
  43. log_msg "Cannot determine MX for ${1}, skipping email notification..."
  44. return 1
  45. fi
  46. ./smtp-cli --missing-modules-ok \
  47. --subject="Watchdog: ${2} service hit the error rate limit" \
  48. --body-plain="Service was restarted, please check your mailcow installation." \
  49. --to=${1} \
  50. --from="watchdog@${MAILCOW_HOSTNAME}" \
  51. --server="${RCPT_MX}" \
  52. --hello-host=${MAILCOW_HOSTNAME}
  53. log_msg "Sent notification email to ${1}"
  54. }
  55. get_container_ip() {
  56. # ${1} is container
  57. CONTAINER_ID=()
  58. CONTAINER_IP=
  59. LOOP_C=1
  60. until [[ ${CONTAINER_IP} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || [[ ${LOOP_C} -gt 5 ]]; do
  61. sleep 0.5
  62. # get long container id for exact match
  63. CONTAINER_ID=($(curl --silent http://dockerapi:8080/containers/json | jq -r ".[] | {name: .Config.Labels[\"com.docker.compose.service\"], id: .Id}" | jq -rc "select( .name | tostring == \"${1}\") | .id"))
  64. # returned id can have multiple elements (if scaled), shuffle for random test
  65. CONTAINER_ID=($(printf "%s\n" "${CONTAINER_ID[@]}" | shuf))
  66. if [[ ! -z ${CONTAINER_ID} ]]; then
  67. for matched_container in "${CONTAINER_ID[@]}"; do
  68. CONTAINER_IP=$(curl --silent http://dockerapi:8080/containers/${matched_container}/json | jq -r '.NetworkSettings.Networks[].IPAddress')
  69. # grep will do nothing if one of these vars is empty
  70. [[ -z ${CONTAINER_IP} ]] && continue
  71. [[ -z ${IPV4_NETWORK} ]] && continue
  72. # only return ips that are part of our network
  73. if ! grep -q ${IPV4_NETWORK} <(echo ${CONTAINER_IP}); then
  74. CONTAINER_IP=
  75. fi
  76. done
  77. fi
  78. LOOP_C=$((LOOP_C + 1))
  79. done
  80. [[ ${LOOP_C} -gt 5 ]] && echo 240.0.0.0 || echo ${CONTAINER_IP}
  81. }
  82. # Check functions
  83. nginx_checks() {
  84. err_count=0
  85. diff_c=0
  86. THRESHOLD=16
  87. # Reduce error count by 2 after restarting an unhealthy container
  88. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  89. while [ ${err_count} -lt ${THRESHOLD} ]; do
  90. host_ip=$(get_container_ip nginx-mailcow)
  91. err_c_cur=${err_count}
  92. /usr/lib/nagios/plugins/check_ping -4 -H ${host_ip} -w 2000,10% -c 4000,100% -p2 1>&2; err_count=$(( ${err_count} + $? ))
  93. /usr/lib/nagios/plugins/check_http -4 -H ${host_ip} -u / -p 8081 1>&2; err_count=$(( ${err_count} + $? ))
  94. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  95. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  96. progress "Nginx" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  97. diff_c=0
  98. sleep $(( ( RANDOM % 30 ) + 10 ))
  99. done
  100. return 1
  101. }
  102. mysql_checks() {
  103. err_count=0
  104. diff_c=0
  105. THRESHOLD=12
  106. # Reduce error count by 2 after restarting an unhealthy container
  107. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  108. while [ ${err_count} -lt ${THRESHOLD} ]; do
  109. host_ip=$(get_container_ip mysql-mailcow)
  110. err_c_cur=${err_count}
  111. /usr/lib/nagios/plugins/check_mysql -H ${host_ip} -P 3306 -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 1>&2; err_count=$(( ${err_count} + $? ))
  112. /usr/lib/nagios/plugins/check_mysql_query -H ${host_ip} -P 3306 -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} -q "SELECT COUNT(*) FROM information_schema.tables" 1>&2; err_count=$(( ${err_count} + $? ))
  113. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  114. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  115. progress "MySQL/MariaDB" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  116. diff_c=0
  117. sleep $(( ( RANDOM % 30 ) + 10 ))
  118. done
  119. return 1
  120. }
  121. sogo_checks() {
  122. err_count=0
  123. diff_c=0
  124. THRESHOLD=20
  125. # Reduce error count by 2 after restarting an unhealthy container
  126. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  127. while [ ${err_count} -lt ${THRESHOLD} ]; do
  128. host_ip=$(get_container_ip sogo-mailcow)
  129. err_c_cur=${err_count}
  130. /usr/lib/nagios/plugins/check_http -4 -H ${host_ip} -u /WebServerResources/css/theme-default.css -p 9192 -R md-default-theme 1>&2; err_count=$(( ${err_count} + $? ))
  131. /usr/lib/nagios/plugins/check_http -4 -H ${host_ip} -u /SOGo.index/ -p 20000 -R "SOGo\.MainUI" 1>&2; err_count=$(( ${err_count} + $? ))
  132. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  133. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  134. progress "SOGo" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  135. diff_c=0
  136. sleep $(( ( RANDOM % 30 ) + 10 ))
  137. done
  138. return 1
  139. }
  140. postfix_checks() {
  141. err_count=0
  142. diff_c=0
  143. THRESHOLD=16
  144. # Reduce error count by 2 after restarting an unhealthy container
  145. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  146. while [ ${err_count} -lt ${THRESHOLD} ]; do
  147. host_ip=$(get_container_ip postfix-mailcow)
  148. err_c_cur=${err_count}
  149. /usr/lib/nagios/plugins/check_smtp -4 -H ${host_ip} -p 589 -f "watchdog@invalid" -C "RCPT TO:null@localhost" -C DATA -C . -R 250 1>&2; err_count=$(( ${err_count} + $? ))
  150. /usr/lib/nagios/plugins/check_smtp -4 -H ${host_ip} -p 589 -S 1>&2; err_count=$(( ${err_count} + $? ))
  151. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  152. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  153. progress "Postfix" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  154. diff_c=0
  155. sleep $(( ( RANDOM % 30 ) + 10 ))
  156. done
  157. return 1
  158. }
  159. dovecot_checks() {
  160. err_count=0
  161. diff_c=0
  162. THRESHOLD=24
  163. # Reduce error count by 2 after restarting an unhealthy container
  164. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  165. while [ ${err_count} -lt ${THRESHOLD} ]; do
  166. host_ip=$(get_container_ip dovecot-mailcow)
  167. err_c_cur=${err_count}
  168. /usr/lib/nagios/plugins/check_smtp -4 -H ${host_ip} -p 24 -f "watchdog@invalid" -C "RCPT TO:<watchdog@invalid>" -L -R "User doesn't exist" 1>&2; err_count=$(( ${err_count} + $? ))
  169. /usr/lib/nagios/plugins/check_imap -4 -H ${host_ip} -p 993 -S -e "OK " 1>&2; err_count=$(( ${err_count} + $? ))
  170. /usr/lib/nagios/plugins/check_imap -4 -H ${host_ip} -p 143 -e "OK " 1>&2; err_count=$(( ${err_count} + $? ))
  171. /usr/lib/nagios/plugins/check_tcp -4 -H ${host_ip} -p 10001 -e "VERSION" 1>&2; err_count=$(( ${err_count} + $? ))
  172. /usr/lib/nagios/plugins/check_tcp -4 -H ${host_ip} -p 4190 -e "Dovecot ready" 1>&2; err_count=$(( ${err_count} + $? ))
  173. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  174. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  175. progress "Dovecot" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  176. diff_c=0
  177. sleep $(( ( RANDOM % 30 ) + 10 ))
  178. done
  179. return 1
  180. }
  181. phpfpm_checks() {
  182. err_count=0
  183. diff_c=0
  184. THRESHOLD=10
  185. # Reduce error count by 2 after restarting an unhealthy container
  186. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  187. while [ ${err_count} -lt ${THRESHOLD} ]; do
  188. host_ip=$(get_container_ip php-fpm-mailcow)
  189. err_c_cur=${err_count}
  190. nc -z ${host_ip} 9001 ; err_count=$(( ${err_count} + ($? * 2)))
  191. nc -z ${host_ip} 9002 ; err_count=$(( ${err_count} + ($? * 2)))
  192. /usr/lib/nagios/plugins/check_ping -4 -H ${host_ip} -w 2000,10% -c 4000,100% -p2 1>&2; err_count=$(( ${err_count} + $? ))
  193. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  194. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  195. progress "PHP-FPM" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  196. diff_c=0
  197. sleep $(( ( RANDOM % 30 ) + 10 ))
  198. done
  199. return 1
  200. }
  201. rspamd_checks() {
  202. err_count=0
  203. diff_c=0
  204. THRESHOLD=10
  205. # Reduce error count by 2 after restarting an unhealthy container
  206. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  207. while [ ${err_count} -lt ${THRESHOLD} ]; do
  208. host_ip=$(get_container_ip rspamd-mailcow)
  209. err_c_cur=${err_count}
  210. SCORE=$(/usr/bin/curl -s --data-binary @- --unix-socket /rspamd-sock/rspamd.sock http://rspamd/scan -d '
  211. To: null@localhost
  212. From: watchdog@localhost
  213. Empty
  214. ' | jq -rc .required_score)
  215. if [[ ${SCORE} != "9999" ]]; then
  216. echo "Rspamd settings check failed" 1>&2
  217. err_count=$(( ${err_count} + 1))
  218. else
  219. echo "Rspamd settings check succeeded" 1>&2
  220. fi
  221. /usr/lib/nagios/plugins/check_ping -4 -H ${host_ip} -w 2000,10% -c 4000,100% -p2 1>&2; err_count=$(( ${err_count} + $? ))
  222. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  223. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  224. progress "Rspamd" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  225. diff_c=0
  226. sleep $(( ( RANDOM % 30 ) + 10 ))
  227. done
  228. return 1
  229. }
  230. # Create watchdog agents
  231. (
  232. while true; do
  233. if ! nginx_checks; then
  234. log_msg "Nginx hit error limit"
  235. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${WATCHDOG_NOTIFY_EMAIL}" "nginx-mailcow"
  236. echo nginx-mailcow > /tmp/com_pipe
  237. fi
  238. done
  239. ) &
  240. BACKGROUND_TASKS+=($!)
  241. (
  242. while true; do
  243. if ! mysql_checks; then
  244. log_msg "MySQL hit error limit"
  245. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${WATCHDOG_NOTIFY_EMAIL}" "mysql-mailcow"
  246. echo mysql-mailcow > /tmp/com_pipe
  247. fi
  248. done
  249. ) &
  250. BACKGROUND_TASKS+=($!)
  251. (
  252. while true; do
  253. if ! phpfpm_checks; then
  254. log_msg "PHP-FPM hit error limit"
  255. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${WATCHDOG_NOTIFY_EMAIL}" "php-fpm-mailcow"
  256. echo php-fpm-mailcow > /tmp/com_pipe
  257. fi
  258. done
  259. ) &
  260. BACKGROUND_TASKS+=($!)
  261. (
  262. while true; do
  263. if ! sogo_checks; then
  264. log_msg "SOGo hit error limit"
  265. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${WATCHDOG_NOTIFY_EMAIL}" "sogo-mailcow"
  266. echo sogo-mailcow > /tmp/com_pipe
  267. fi
  268. done
  269. ) &
  270. BACKGROUND_TASKS+=($!)
  271. (
  272. while true; do
  273. if ! postfix_checks; then
  274. log_msg "Postfix hit error limit"
  275. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${WATCHDOG_NOTIFY_EMAIL}" "postfix-mailcow"
  276. echo postfix-mailcow > /tmp/com_pipe
  277. fi
  278. done
  279. ) &
  280. BACKGROUND_TASKS+=($!)
  281. (
  282. while true; do
  283. if ! dovecot_checks; then
  284. log_msg "Dovecot hit error limit"
  285. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${WATCHDOG_NOTIFY_EMAIL}" "dovecot-mailcow"
  286. echo dovecot-mailcow > /tmp/com_pipe
  287. fi
  288. done
  289. ) &
  290. BACKGROUND_TASKS+=($!)
  291. (
  292. while true; do
  293. if ! rspamd_checks; then
  294. log_msg "Rspamd hit error limit"
  295. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${WATCHDOG_NOTIFY_EMAIL}" "rspamd-mailcow"
  296. echo rspamd-mailcow > /tmp/com_pipe
  297. fi
  298. done
  299. ) &
  300. BACKGROUND_TASKS+=($!)
  301. # Monitor watchdog agents, stop script when agents fails and wait for respawn by Docker (restart:always:n)
  302. (
  303. while true; do
  304. for bg_task in ${BACKGROUND_TASKS[*]}; do
  305. if ! kill -0 ${bg_task} 1>&2; then
  306. log_msg "Worker ${bg_task} died, stopping watchdog and waiting for respawn..."
  307. kill -TERM 1
  308. fi
  309. sleep 10
  310. done
  311. done
  312. ) &
  313. # Monitor dockerapi
  314. (
  315. while true; do
  316. while nc -z dockerapi 8080; do
  317. sleep 3
  318. done
  319. log_msg "Cannot find dockerapi-mailcow, waiting to recover..."
  320. kill -STOP ${BACKGROUND_TASKS[*]}
  321. until nc -z dockerapi 8080; do
  322. sleep 3
  323. done
  324. kill -CONT ${BACKGROUND_TASKS[*]}
  325. kill -USR1 ${BACKGROUND_TASKS[*]}
  326. done
  327. ) &
  328. # Restart container when threshold limit reached
  329. while true; do
  330. CONTAINER_ID=
  331. read com_pipe_answer </tmp/com_pipe
  332. if [[ ${com_pipe_answer} =~ .+-mailcow ]]; then
  333. kill -STOP ${BACKGROUND_TASKS[*]}
  334. sleep 3
  335. CONTAINER_ID=$(curl --silent http://dockerapi:8080/containers/json | jq -r ".[] | {name: .Config.Labels[\"com.docker.compose.service\"], id: .Id}" | jq -rc "select( .name | tostring | contains(\"${com_pipe_answer}\")) | .id")
  336. if [[ ! -z ${CONTAINER_ID} ]]; then
  337. log_msg "Sending restart command to ${CONTAINER_ID}..."
  338. curl --silent -XPOST http://dockerapi:8080/containers/${CONTAINER_ID}/restart
  339. fi
  340. log_msg "Wait for restarted container to settle and continue watching..."
  341. sleep 30s
  342. kill -CONT ${BACKGROUND_TASKS[*]}
  343. kill -USR1 ${BACKGROUND_TASKS[*]}
  344. fi
  345. done