watchdog.sh 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. #!/bin/bash
  2. trap "exit" INT TERM
  3. trap "kill 0" EXIT
  4. # Prepare
  5. BACKGROUND_TASKS=()
  6. echo "Waiting for containers to settle..."
  7. sleep 10
  8. if [[ "${USE_WATCHDOG}" =~ ^([nN][oO]|[nN])+$ ]]; then
  9. echo -e "$(date) - USE_WATCHDOG=n, skipping watchdog..."
  10. sleep 365d
  11. exec $(readlink -f "$0")
  12. fi
  13. # Checks pipe their corresponding container name in this pipe
  14. if [[ ! -p /tmp/com_pipe ]]; then
  15. mkfifo /tmp/com_pipe
  16. fi
  17. redis-cli -h redis-mailcow DEL F2B_RES > /dev/null
  18. # Common functions
  19. array_diff() {
  20. # https://stackoverflow.com/questions/2312762, Alex Offshore
  21. eval local ARR1=\(\"\${$2[@]}\"\)
  22. eval local ARR2=\(\"\${$3[@]}\"\)
  23. local IFS=$'\n'
  24. mapfile -t $1 < <(comm -23 <(echo "${ARR1[*]}" | sort) <(echo "${ARR2[*]}" | sort))
  25. }
  26. progress() {
  27. SERVICE=${1}
  28. TOTAL=${2}
  29. CURRENT=${3}
  30. DIFF=${4}
  31. [[ -z ${DIFF} ]] && DIFF=0
  32. [[ -z ${TOTAL} || -z ${CURRENT} ]] && return
  33. [[ ${CURRENT} -gt ${TOTAL} ]] && return
  34. [[ ${CURRENT} -lt 0 ]] && CURRENT=0
  35. PERCENT=$(( 200 * ${CURRENT} / ${TOTAL} % 2 + 100 * ${CURRENT} / ${TOTAL} ))
  36. redis-cli -h redis LPUSH WATCHDOG_LOG "{\"time\":\"$(date +%s)\",\"service\":\"${SERVICE}\",\"lvl\":\"${PERCENT}\",\"hpnow\":\"${CURRENT}\",\"hptotal\":\"${TOTAL}\",\"hpdiff\":\"${DIFF}\"}" > /dev/null
  37. log_msg "${SERVICE} health level: ${PERCENT}% (${CURRENT}/${TOTAL}), health trend: ${DIFF}" no_redis
  38. # Return 10 to indicate a dead service
  39. [ ${CURRENT} -le 0 ] && return 10
  40. }
  41. log_msg() {
  42. if [[ ${2} != "no_redis" ]]; then
  43. redis-cli -h redis LPUSH WATCHDOG_LOG "{\"time\":\"$(date +%s)\",\"message\":\"$(printf '%s' "${1}" | \
  44. tr '\r\n%&;$"_[]{}-' ' ')\"}" > /dev/null
  45. fi
  46. echo $(date) $(printf '%s\n' "${1}")
  47. }
  48. function mail_error() {
  49. [[ -z ${1} ]] && return 1
  50. [[ -z ${2} ]] && BODY="Service was restarted on $(date), please check your mailcow installation." || BODY="$(date) - ${2}"
  51. WATCHDOG_NOTIFY_EMAIL=$(echo "${WATCHDOG_NOTIFY_EMAIL}" | sed 's/"//;s|"$||')
  52. # Some exceptions for subject and body formats
  53. if [[ ${1} == "fail2ban" ]]; then
  54. SUBJECT="${BODY}"
  55. BODY="Please see netfilter-mailcow for more details and triggered rules."
  56. else
  57. SUBJECT="Watchdog ALERT: ${1}"
  58. fi
  59. IFS=',' read -r -a MAIL_RCPTS <<< "${WATCHDOG_NOTIFY_EMAIL}"
  60. for rcpt in "${MAIL_RCPTS[@]}"; do
  61. RCPT_DOMAIN=
  62. RCPT_MX=
  63. RCPT_DOMAIN=$(echo ${rcpt} | awk -F @ {'print $NF'})
  64. RCPT_MX=$(dig +short ${RCPT_DOMAIN} mx | sort -n | awk '{print $2; exit}')
  65. if [[ -z ${RCPT_MX} ]]; then
  66. log_msg "Cannot determine MX for ${rcpt}, skipping email notification..."
  67. return 1
  68. fi
  69. [ -f "/tmp/${1}" ] && BODY="/tmp/${1}"
  70. ./smtp-cli --missing-modules-ok \
  71. --charset=UTF-8 \
  72. --subject="${SUBJECT}" \
  73. --body-plain="${BODY}" \
  74. --to=${rcpt} \
  75. --from="watchdog@${MAILCOW_HOSTNAME}" \
  76. --server="${RCPT_MX}" \
  77. --hello-host=${MAILCOW_HOSTNAME}
  78. log_msg "Sent notification email to ${rcpt}"
  79. done
  80. }
  81. get_container_ip() {
  82. # ${1} is container
  83. CONTAINER_ID=()
  84. CONTAINER_IPS=()
  85. CONTAINER_IP=
  86. LOOP_C=1
  87. until [[ ${CONTAINER_IP} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || [[ ${LOOP_C} -gt 5 ]]; do
  88. if [ ${IP_BY_DOCKER_API} -eq 0 ]; then
  89. CONTAINER_IP=$(dig a "${1}" +short)
  90. else
  91. sleep 0.5
  92. # get long container id for exact match
  93. 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"))
  94. # returned id can have multiple elements (if scaled), shuffle for random test
  95. CONTAINER_ID=($(printf "%s\n" "${CONTAINER_ID[@]}" | shuf))
  96. if [[ ! -z ${CONTAINER_ID} ]]; then
  97. for matched_container in "${CONTAINER_ID[@]}"; do
  98. CONTAINER_IPS=($(curl --silent --insecure https://dockerapi/containers/${matched_container}/json | jq -r '.NetworkSettings.Networks[].IPAddress'))
  99. for ip_match in "${CONTAINER_IPS[@]}"; do
  100. # grep will do nothing if one of these vars is empty
  101. [[ -z ${ip_match} ]] && continue
  102. [[ -z ${IPV4_NETWORK} ]] && continue
  103. # only return ips that are part of our network
  104. if ! grep -q ${IPV4_NETWORK} <(echo ${ip_match}); then
  105. continue
  106. else
  107. CONTAINER_IP=${ip_match}
  108. break
  109. fi
  110. done
  111. [[ ! -z ${CONTAINER_IP} ]] && break
  112. done
  113. fi
  114. fi
  115. LOOP_C=$((LOOP_C + 1))
  116. done
  117. [[ ${LOOP_C} -gt 5 ]] && echo 240.0.0.0 || echo ${CONTAINER_IP}
  118. }
  119. nginx_checks() {
  120. err_count=0
  121. diff_c=0
  122. THRESHOLD=5
  123. # Reduce error count by 2 after restarting an unhealthy container
  124. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  125. while [ ${err_count} -lt ${THRESHOLD} ]; do
  126. touch /tmp/nginx-mailcow; echo "$(tail -50 /tmp/nginx-mailcow)" > /tmp/nginx-mailcow
  127. host_ip=$(get_container_ip nginx-mailcow)
  128. err_c_cur=${err_count}
  129. /usr/lib/nagios/plugins/check_http -4 -H ${host_ip} -u / -p 8081 2>> /tmp/nginx-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  130. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  131. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  132. progress "Nginx" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  133. if [[ $? == 10 ]]; then
  134. diff_c=0
  135. sleep 1
  136. else
  137. diff_c=0
  138. sleep $(( ( RANDOM % 60 ) + 20 ))
  139. fi
  140. done
  141. return 1
  142. }
  143. unbound_checks() {
  144. err_count=0
  145. diff_c=0
  146. THRESHOLD=5
  147. # Reduce error count by 2 after restarting an unhealthy container
  148. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  149. while [ ${err_count} -lt ${THRESHOLD} ]; do
  150. touch /tmp/unbound-mailcow; echo "$(tail -50 /tmp/unbound-mailcow)" > /tmp/unbound-mailcow
  151. host_ip=$(get_container_ip unbound-mailcow)
  152. err_c_cur=${err_count}
  153. /usr/lib/nagios/plugins/check_dns -s ${host_ip} -H stackoverflow.com 2>> /tmp/unbound-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  154. DNSSEC=$(dig com +dnssec | egrep 'flags:.+ad')
  155. if [[ -z ${DNSSEC} ]]; then
  156. echo "DNSSEC failure" 2>> /tmp/unbound-mailcow 1>&2
  157. err_count=$(( ${err_count} + 1))
  158. else
  159. echo "DNSSEC check succeeded" 2>> /tmp/unbound-mailcow 1>&2
  160. fi
  161. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  162. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  163. progress "Unbound" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  164. if [[ $? == 10 ]]; then
  165. diff_c=0
  166. sleep 1
  167. else
  168. diff_c=0
  169. sleep $(( ( RANDOM % 60 ) + 20 ))
  170. fi
  171. done
  172. return 1
  173. }
  174. mysql_checks() {
  175. err_count=0
  176. diff_c=0
  177. THRESHOLD=5
  178. # Reduce error count by 2 after restarting an unhealthy container
  179. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  180. while [ ${err_count} -lt ${THRESHOLD} ]; do
  181. touch /tmp/mysql-mailcow; echo "$(tail -50 /tmp/mysql-mailcow)" > /tmp/mysql-mailcow
  182. host_ip=$(get_container_ip mysql-mailcow)
  183. err_c_cur=${err_count}
  184. /usr/lib/nagios/plugins/check_mysql -s /var/run/mysqld/mysqld.sock -u ${DBUSER} -p ${DBPASS} -d ${DBNAME} 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  185. /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" 2>> /tmp/mysql-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  186. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  187. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  188. progress "MySQL/MariaDB" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  189. if [[ $? == 10 ]]; then
  190. diff_c=0
  191. sleep 1
  192. else
  193. diff_c=0
  194. sleep $(( ( RANDOM % 60 ) + 20 ))
  195. fi
  196. done
  197. return 1
  198. }
  199. sogo_checks() {
  200. err_count=0
  201. diff_c=0
  202. THRESHOLD=5
  203. # Reduce error count by 2 after restarting an unhealthy container
  204. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  205. while [ ${err_count} -lt ${THRESHOLD} ]; do
  206. touch /tmp/sogo-mailcow; echo "$(tail -50 /tmp/sogo-mailcow)" > /tmp/sogo-mailcow
  207. host_ip=$(get_container_ip sogo-mailcow)
  208. err_c_cur=${err_count}
  209. /usr/lib/nagios/plugins/check_http -4 -H ${host_ip} -u /SOGo.index/ -p 20000 -R "SOGo\.MainUI" 2>> /tmp/sogo-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  210. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  211. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  212. progress "SOGo" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  213. if [[ $? == 10 ]]; then
  214. diff_c=0
  215. sleep 1
  216. else
  217. diff_c=0
  218. sleep $(( ( RANDOM % 60 ) + 20 ))
  219. fi
  220. done
  221. return 1
  222. }
  223. postfix_checks() {
  224. err_count=0
  225. diff_c=0
  226. THRESHOLD=8
  227. # Reduce error count by 2 after restarting an unhealthy container
  228. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  229. while [ ${err_count} -lt ${THRESHOLD} ]; do
  230. touch /tmp/postfix-mailcow; echo "$(tail -50 /tmp/postfix-mailcow)" > /tmp/postfix-mailcow
  231. host_ip=$(get_container_ip postfix-mailcow)
  232. err_c_cur=${err_count}
  233. /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 2>> /tmp/postfix-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  234. /usr/lib/nagios/plugins/check_smtp -4 -H ${host_ip} -p 589 -S 2>> /tmp/postfix-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  235. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  236. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  237. progress "Postfix" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  238. if [[ $? == 10 ]]; then
  239. diff_c=0
  240. sleep 1
  241. else
  242. diff_c=0
  243. sleep $(( ( RANDOM % 60 ) + 20 ))
  244. fi
  245. done
  246. return 1
  247. }
  248. clamd_checks() {
  249. err_count=0
  250. diff_c=0
  251. THRESHOLD=15
  252. # Reduce error count by 2 after restarting an unhealthy container
  253. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  254. while [ ${err_count} -lt ${THRESHOLD} ]; do
  255. touch /tmp/clamd-mailcow; echo "$(tail -50 /tmp/clamd-mailcow)" > /tmp/clamd-mailcow
  256. host_ip=$(get_container_ip clamd-mailcow)
  257. err_c_cur=${err_count}
  258. /usr/lib/nagios/plugins/check_clamd -4 -H ${host_ip} 2>> /tmp/clamd-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  259. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  260. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  261. progress "Clamd" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  262. if [[ $? == 10 ]]; then
  263. diff_c=0
  264. sleep 1
  265. else
  266. diff_c=0
  267. sleep $(( ( RANDOM % 120 ) + 20 ))
  268. fi
  269. done
  270. return 1
  271. }
  272. dovecot_checks() {
  273. err_count=0
  274. diff_c=0
  275. THRESHOLD=12
  276. # Reduce error count by 2 after restarting an unhealthy container
  277. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  278. while [ ${err_count} -lt ${THRESHOLD} ]; do
  279. touch /tmp/dovecot-mailcow; echo "$(tail -50 /tmp/dovecot-mailcow)" > /tmp/dovecot-mailcow
  280. host_ip=$(get_container_ip dovecot-mailcow)
  281. err_c_cur=${err_count}
  282. /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" 2>> /tmp/dovecot-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  283. /usr/lib/nagios/plugins/check_imap -4 -H ${host_ip} -p 993 -S -e "OK " 2>> /tmp/dovecot-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  284. /usr/lib/nagios/plugins/check_imap -4 -H ${host_ip} -p 143 -e "OK " 2>> /tmp/dovecot-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  285. /usr/lib/nagios/plugins/check_tcp -4 -H ${host_ip} -p 10001 -e "VERSION" 2>> /tmp/dovecot-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  286. /usr/lib/nagios/plugins/check_tcp -4 -H ${host_ip} -p 4190 -e "Dovecot ready" 2>> /tmp/dovecot-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  287. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  288. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  289. progress "Dovecot" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  290. if [[ $? == 10 ]]; then
  291. diff_c=0
  292. sleep 1
  293. else
  294. diff_c=0
  295. sleep $(( ( RANDOM % 60 ) + 20 ))
  296. fi
  297. done
  298. return 1
  299. }
  300. phpfpm_checks() {
  301. err_count=0
  302. diff_c=0
  303. THRESHOLD=5
  304. # Reduce error count by 2 after restarting an unhealthy container
  305. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  306. while [ ${err_count} -lt ${THRESHOLD} ]; do
  307. touch /tmp/php-fpm-mailcow; echo "$(tail -50 /tmp/php-fpm-mailcow)" > /tmp/php-fpm-mailcow
  308. host_ip=$(get_container_ip php-fpm-mailcow)
  309. err_c_cur=${err_count}
  310. /usr/lib/nagios/plugins/check_tcp -H ${host_ip} -p 9001 2>> /tmp/php-fpm-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  311. /usr/lib/nagios/plugins/check_tcp -H ${host_ip} -p 9002 2>> /tmp/php-fpm-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  312. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  313. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  314. progress "PHP-FPM" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  315. if [[ $? == 10 ]]; then
  316. diff_c=0
  317. sleep 1
  318. else
  319. diff_c=0
  320. sleep $(( ( RANDOM % 60 ) + 20 ))
  321. fi
  322. done
  323. return 1
  324. }
  325. ratelimit_checks() {
  326. err_count=0
  327. diff_c=0
  328. THRESHOLD=1
  329. RL_LOG_STATUS=$(redis-cli -h redis LRANGE RL_LOG 0 0 | jq .qid)
  330. # Reduce error count by 2 after restarting an unhealthy container
  331. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  332. while [ ${err_count} -lt ${THRESHOLD} ]; do
  333. err_c_cur=${err_count}
  334. RL_LOG_STATUS_PREV=${RL_LOG_STATUS}
  335. RL_LOG_STATUS=$(redis-cli -h redis LRANGE RL_LOG 0 0 | jq .qid)
  336. if [[ ${RL_LOG_STATUS_PREV} != ${RL_LOG_STATUS} ]]; then
  337. err_count=$(( ${err_count} + 1 ))
  338. fi
  339. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  340. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  341. progress "Ratelimit" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  342. if [[ $? == 10 ]]; then
  343. diff_c=0
  344. sleep 1
  345. else
  346. diff_c=0
  347. sleep $(( ( RANDOM % 60 ) + 20 ))
  348. fi
  349. done
  350. return 1
  351. }
  352. fail2ban_checks() {
  353. err_count=0
  354. diff_c=0
  355. THRESHOLD=1
  356. F2B_LOG_STATUS=($(redis-cli -h redis-mailcow --raw HKEYS F2B_ACTIVE_BANS))
  357. F2B_RES=
  358. # Reduce error count by 2 after restarting an unhealthy container
  359. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  360. while [ ${err_count} -lt ${THRESHOLD} ]; do
  361. err_c_cur=${err_count}
  362. F2B_LOG_STATUS_PREV=(${F2B_LOG_STATUS[@]})
  363. F2B_LOG_STATUS=($(redis-cli -h redis-mailcow --raw HKEYS F2B_ACTIVE_BANS))
  364. array_diff F2B_RES F2B_LOG_STATUS F2B_LOG_STATUS_PREV
  365. if [[ ! -z "${F2B_RES}" ]]; then
  366. err_count=$(( ${err_count} + 1 ))
  367. echo -n "${F2B_RES[@]}" | tr -cd "[a-fA-F0-9.:/] " | timeout 3s redis-cli -x -h redis-mailcow SET F2B_RES > /dev/null
  368. if [ $? -ne 0 ]; then
  369. redis-cli -x -h redis-mailcow DEL F2B_RES
  370. fi
  371. fi
  372. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  373. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  374. progress "Fail2ban" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  375. if [[ $? == 10 ]]; then
  376. diff_c=0
  377. sleep 1
  378. else
  379. diff_c=0
  380. sleep $(( ( RANDOM % 60 ) + 20 ))
  381. fi
  382. done
  383. return 1
  384. }
  385. acme_checks() {
  386. err_count=0
  387. diff_c=0
  388. THRESHOLD=1
  389. ACME_LOG_STATUS=$(redis-cli -h redis GET ACME_FAIL_TIME)
  390. if [[ -z "${ACME_LOG_STATUS}" ]]; then
  391. redis-cli -h redis SET ACME_FAIL_TIME 0
  392. ACME_LOG_STATUS=0
  393. fi
  394. # Reduce error count by 2 after restarting an unhealthy container
  395. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  396. while [ ${err_count} -lt ${THRESHOLD} ]; do
  397. err_c_cur=${err_count}
  398. ACME_LOG_STATUS_PREV=${ACME_LOG_STATUS}
  399. ACME_LOG_STATUS=$(redis-cli -h redis GET ACME_FAIL_TIME)
  400. if [[ ${ACME_LOG_STATUS_PREV} != ${ACME_LOG_STATUS} ]]; then
  401. err_count=$(( ${err_count} + 1 ))
  402. fi
  403. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  404. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  405. progress "ACME" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  406. if [[ $? == 10 ]]; then
  407. diff_c=0
  408. sleep 1
  409. else
  410. diff_c=0
  411. sleep $(( ( RANDOM % 60 ) + 20 ))
  412. fi
  413. done
  414. return 1
  415. }
  416. ipv6nat_checks() {
  417. err_count=0
  418. diff_c=0
  419. THRESHOLD=1
  420. # Reduce error count by 2 after restarting an unhealthy container
  421. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  422. while [ ${err_count} -lt ${THRESHOLD} ]; do
  423. err_c_cur=${err_count}
  424. CONTAINERS=$(curl --silent --insecure https://dockerapi/containers/json)
  425. IPV6NAT_CONTAINER_ID=$(echo ${CONTAINERS} | jq -r ".[] | {name: .Config.Labels[\"com.docker.compose.service\"], id: .Id}" | jq -rc "select( .name | tostring | contains(\"ipv6nat-mailcow\")) | .id")
  426. if [[ ! -z ${IPV6NAT_CONTAINER_ID} ]]; then
  427. LATEST_STARTED="$(echo ${CONTAINERS} | jq -r ".[] | {name: .Config.Labels[\"com.docker.compose.service\"], StartedAt: .State.StartedAt}" | jq -rc "select( .name | tostring | contains(\"ipv6nat-mailcow\") | not)" | jq -rc .StartedAt | xargs -n1 date +%s -d | sort | tail -n1)"
  428. LATEST_IPV6NAT="$(echo ${CONTAINERS} | jq -r ".[] | {name: .Config.Labels[\"com.docker.compose.service\"], StartedAt: .State.StartedAt}" | jq -rc "select( .name | tostring | contains(\"ipv6nat-mailcow\"))" | jq -rc .StartedAt | xargs -n1 date +%s -d | sort | tail -n1)"
  429. DIFFERENCE_START_TIME=$(expr ${LATEST_IPV6NAT} - ${LATEST_STARTED} 2>/dev/null)
  430. if [[ "${DIFFERENCE_START_TIME}" -lt 30 ]]; then
  431. err_count=$(( ${err_count} + 1 ))
  432. fi
  433. fi
  434. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  435. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  436. progress "IPv6 NAT" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  437. if [[ $? == 10 ]]; then
  438. diff_c=0
  439. sleep 30
  440. else
  441. diff_c=0
  442. sleep 300
  443. fi
  444. done
  445. return 1
  446. }
  447. rspamd_checks() {
  448. err_count=0
  449. diff_c=0
  450. THRESHOLD=5
  451. # Reduce error count by 2 after restarting an unhealthy container
  452. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  453. while [ ${err_count} -lt ${THRESHOLD} ]; do
  454. touch /tmp/rspamd-mailcow; echo "$(tail -50 /tmp/rspamd-mailcow)" > /tmp/rspamd-mailcow
  455. host_ip=$(get_container_ip rspamd-mailcow)
  456. err_c_cur=${err_count}
  457. SCORE=$(echo 'To: null@localhost
  458. From: watchdog@localhost
  459. Empty
  460. ' | usr/bin/curl -s --data-binary @- --unix-socket /var/lib/rspamd/rspamd.sock http://rspamd/scan | jq -rc .required_score)
  461. if [[ ${SCORE} != "9999" ]]; then
  462. echo "Rspamd settings check failed" 2>> /tmp/rspamd-mailcow 1>&2
  463. err_count=$(( ${err_count} + 1))
  464. else
  465. echo "Rspamd settings check succeeded" 2>> /tmp/rspamd-mailcow 1>&2
  466. fi
  467. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  468. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  469. progress "Rspamd" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  470. if [[ $? == 10 ]]; then
  471. diff_c=0
  472. sleep 1
  473. else
  474. diff_c=0
  475. sleep $(( ( RANDOM % 60 ) + 20 ))
  476. fi
  477. done
  478. return 1
  479. }
  480. olefy_checks() {
  481. err_count=0
  482. diff_c=0
  483. THRESHOLD=5
  484. # Reduce error count by 2 after restarting an unhealthy container
  485. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  486. while [ ${err_count} -lt ${THRESHOLD} ]; do
  487. touch /tmp/olefy-mailcow; echo "$(tail -50 /tmp/olefy-mailcow)" > /tmp/olefy-mailcow
  488. host_ip=$(get_container_ip olefy-mailcow)
  489. err_c_cur=${err_count}
  490. /usr/lib/nagios/plugins/check_tcp -4 -H ${host_ip} -p 10055 2>> /tmp/olefy-mailcow 1>&2; err_count=$(( ${err_count} + $? ))
  491. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  492. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  493. progress "Olefy" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  494. if [[ $? == 10 ]]; then
  495. diff_c=0
  496. sleep 1
  497. else
  498. diff_c=0
  499. sleep $(( ( RANDOM % 60 ) + 20 ))
  500. fi
  501. done
  502. return 1
  503. }
  504. # Notify about start
  505. if [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && [[ ! -f /tmp/watchdog_reload ]]; then
  506. mail_error "watchdog-mailcow" "Watchdog started monitoring mailcow."
  507. rm /tmp/watchdog_reload
  508. fi
  509. # Create watchdog agents
  510. (
  511. touch /tmp/watchdog_reload
  512. sleep 86400
  513. echo "Reloading watchdog"
  514. kill 1
  515. ) &
  516. (
  517. while true; do
  518. if ! nginx_checks; then
  519. log_msg "Nginx hit error limit"
  520. echo nginx-mailcow > /tmp/com_pipe
  521. fi
  522. done
  523. ) &
  524. PID=$!
  525. echo "Spawned nginx_checks with PID ${PID}"
  526. BACKGROUND_TASKS+=(${PID})
  527. (
  528. while true; do
  529. if ! mysql_checks; then
  530. log_msg "MySQL hit error limit"
  531. echo mysql-mailcow > /tmp/com_pipe
  532. fi
  533. done
  534. ) &
  535. PID=$!
  536. echo "Spawned mysql_checks with PID ${PID}"
  537. BACKGROUND_TASKS+=(${PID})
  538. (
  539. while true; do
  540. if ! phpfpm_checks; then
  541. log_msg "PHP-FPM hit error limit"
  542. echo php-fpm-mailcow > /tmp/com_pipe
  543. fi
  544. done
  545. ) &
  546. PID=$!
  547. echo "Spawned phpfpm_checks with PID ${PID}"
  548. BACKGROUND_TASKS+=(${PID})
  549. (
  550. while true; do
  551. if ! sogo_checks; then
  552. log_msg "SOGo hit error limit"
  553. echo sogo-mailcow > /tmp/com_pipe
  554. fi
  555. done
  556. ) &
  557. PID=$!
  558. echo "Spawned sogo_checks with PID ${PID}"
  559. BACKGROUND_TASKS+=(${PID})
  560. if [ ${CHECK_UNBOUND} -eq 1 ]; then
  561. (
  562. while true; do
  563. if ! unbound_checks; then
  564. log_msg "Unbound hit error limit"
  565. echo unbound-mailcow > /tmp/com_pipe
  566. fi
  567. done
  568. ) &
  569. PID=$!
  570. echo "Spawned unbound_checks with PID ${PID}"
  571. BACKGROUND_TASKS+=(${PID})
  572. fi
  573. if [[ "${SKIP_CLAMD}" =~ ^([nN][oO]|[nN])+$ ]]; then
  574. (
  575. while true; do
  576. if ! clamd_checks; then
  577. log_msg "Clamd hit error limit"
  578. echo clamd-mailcow > /tmp/com_pipe
  579. fi
  580. done
  581. ) &
  582. PID=$!
  583. echo "Spawned clamd_checks with PID ${PID}"
  584. BACKGROUND_TASKS+=(${PID})
  585. fi
  586. (
  587. while true; do
  588. if ! postfix_checks; then
  589. log_msg "Postfix hit error limit"
  590. echo postfix-mailcow > /tmp/com_pipe
  591. fi
  592. done
  593. ) &
  594. PID=$!
  595. echo "Spawned postfix_checks with PID ${PID}"
  596. BACKGROUND_TASKS+=(${PID})
  597. (
  598. while true; do
  599. if ! dovecot_checks; then
  600. log_msg "Dovecot hit error limit"
  601. echo dovecot-mailcow > /tmp/com_pipe
  602. fi
  603. done
  604. ) &
  605. PID=$!
  606. echo "Spawned dovecot_checks with PID ${PID}"
  607. BACKGROUND_TASKS+=(${PID})
  608. (
  609. while true; do
  610. if ! rspamd_checks; then
  611. log_msg "Rspamd hit error limit"
  612. echo rspamd-mailcow > /tmp/com_pipe
  613. fi
  614. done
  615. ) &
  616. PID=$!
  617. echo "Spawned rspamd_checks with PID ${PID}"
  618. BACKGROUND_TASKS+=(${PID})
  619. (
  620. while true; do
  621. if ! ratelimit_checks; then
  622. log_msg "Ratelimit hit error limit"
  623. echo ratelimit > /tmp/com_pipe
  624. fi
  625. done
  626. ) &
  627. PID=$!
  628. echo "Spawned ratelimit_checks with PID ${PID}"
  629. BACKGROUND_TASKS+=(${PID})
  630. (
  631. while true; do
  632. if ! fail2ban_checks; then
  633. log_msg "Fail2ban hit error limit"
  634. echo fail2ban > /tmp/com_pipe
  635. fi
  636. done
  637. ) &
  638. PID=$!
  639. echo "Spawned fail2ban_checks with PID ${PID}"
  640. BACKGROUND_TASKS+=(${PID})
  641. #(
  642. #while true; do
  643. # if ! olefy_checks; then
  644. # log_msg "Olefy hit error limit"
  645. # echo olefy-mailcow > /tmp/com_pipe
  646. # fi
  647. #done
  648. #) &
  649. #PID=$!
  650. #echo "Spawned olefy_checks with PID ${PID}"
  651. #BACKGROUND_TASKS+=(${PID})
  652. (
  653. while true; do
  654. if ! acme_checks; then
  655. log_msg "ACME client hit error limit"
  656. echo acme-mailcow > /tmp/com_pipe
  657. fi
  658. done
  659. ) &
  660. PID=$!
  661. echo "Spawned acme_checks with PID ${PID}"
  662. BACKGROUND_TASKS+=(${PID})
  663. (
  664. while true; do
  665. if ! ipv6nat_checks; then
  666. log_msg "IPv6 NAT warning: ipv6nat-mailcow container was not started at least 30s after siblings (not an error)"
  667. echo ipv6nat-mailcow > /tmp/com_pipe
  668. fi
  669. done
  670. ) &
  671. PID=$!
  672. echo "Spawned ipv6nat_checks with PID ${PID}"
  673. BACKGROUND_TASKS+=(${PID})
  674. # Monitor watchdog agents, stop script when agents fails and wait for respawn by Docker (restart:always:n)
  675. (
  676. while true; do
  677. for bg_task in ${BACKGROUND_TASKS[*]}; do
  678. if ! kill -0 ${bg_task} 1>&2; then
  679. log_msg "Worker ${bg_task} died, stopping watchdog and waiting for respawn..."
  680. kill -TERM 1
  681. fi
  682. sleep 10
  683. done
  684. done
  685. ) &
  686. # Monitor dockerapi
  687. (
  688. while true; do
  689. while nc -z dockerapi 443; do
  690. sleep 3
  691. done
  692. log_msg "Cannot find dockerapi-mailcow, waiting to recover..."
  693. kill -STOP ${BACKGROUND_TASKS[*]}
  694. until nc -z dockerapi 443; do
  695. sleep 3
  696. done
  697. kill -CONT ${BACKGROUND_TASKS[*]}
  698. kill -USR1 ${BACKGROUND_TASKS[*]}
  699. done
  700. ) &
  701. # Actions when threshold limit is reached
  702. while true; do
  703. CONTAINER_ID=
  704. HAS_INITDB=
  705. read com_pipe_answer </tmp/com_pipe
  706. if [ -s "/tmp/${com_pipe_answer}" ]; then
  707. cat "/tmp/${com_pipe_answer}"
  708. fi
  709. if [[ ${com_pipe_answer} == "ratelimit" ]]; then
  710. log_msg "At least one ratelimit was applied"
  711. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${com_pipe_answer}" "Please see mailcow UI logs for further information."
  712. elif [[ ${com_pipe_answer} == "acme-mailcow" ]]; then
  713. log_msg "acme-mailcow did not complete successfully"
  714. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${com_pipe_answer}" "Please check acme-mailcow for further information."
  715. elif [[ ${com_pipe_answer} == "fail2ban" ]]; then
  716. F2B_RES=($(redis-cli -h redis-mailcow --raw GET F2B_RES))
  717. if [[ ! -z "${F2B_RES}" ]]; then
  718. redis-cli -h redis-mailcow DEL F2B_RES > /dev/null
  719. host=
  720. for host in "${F2B_RES[@]}"; do
  721. log_msg "Banned ${host}"
  722. rm /tmp/fail2ban 2> /dev/null
  723. timeout 2s whois ${host} > /tmp/fail2ban
  724. sleep 2.5
  725. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && [[ ${WATCHDOG_NOTIFY_BAN} =~ ^([yY][eE][sS]|[yY])+$ ]] && mail_error "${com_pipe_answer}" "IP ban: ${host}"
  726. done
  727. fi
  728. elif [[ ${com_pipe_answer} =~ .+-mailcow ]]; then
  729. kill -STOP ${BACKGROUND_TASKS[*]}
  730. sleep 10
  731. 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")
  732. if [[ ! -z ${CONTAINER_ID} ]]; then
  733. if [[ "${com_pipe_answer}" == "php-fpm-mailcow" ]]; then
  734. HAS_INITDB=$(curl --silent --insecure -XPOST https://dockerapi/containers/${CONTAINER_ID}/top | jq '.msg.Processes[] | contains(["php -c /usr/local/etc/php -f /web/inc/init_db.inc.php"])' | grep true)
  735. fi
  736. S_RUNNING=$(($(date +%s) - $(curl --silent --insecure https://dockerapi/containers/${CONTAINER_ID}/json | jq .State.StartedAt | xargs -n1 date +%s -d)))
  737. if [ ${S_RUNNING} -lt 360 ]; then
  738. log_msg "Container is running for less than 360 seconds, skipping action..."
  739. elif [[ ! -z ${HAS_INITDB} ]]; then
  740. log_msg "Database is being initialized by php-fpm-mailcow, not restarting but delaying checks for a minute..."
  741. sleep 60
  742. else
  743. log_msg "Sending restart command to ${CONTAINER_ID}..."
  744. curl --silent --insecure -XPOST https://dockerapi/containers/${CONTAINER_ID}/restart
  745. if [[ ${com_pipe_answer} != "ipv6nat-mailcow" ]]; then
  746. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${com_pipe_answer}"
  747. fi
  748. log_msg "Wait for restarted container to settle and continue watching..."
  749. sleep 35
  750. fi
  751. fi
  752. kill -CONT ${BACKGROUND_TASKS[*]}
  753. sleep 1
  754. kill -USR1 ${BACKGROUND_TASKS[*]}
  755. fi
  756. done