watchdog.sh 30 KB

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