watchdog.sh 14 KB

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