watchdog.sh 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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_LOG_STATUS=$(redis-cli -h redis GET ACME_FAIL_TIME)
  454. if [[ ${ACME_LOG_STATUS_PREV} != ${ACME_LOG_STATUS} ]]; then
  455. err_count=$(( ${err_count} + 1 ))
  456. fi
  457. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  458. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  459. progress "ACME" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  460. if [[ $? == 10 ]]; then
  461. diff_c=0
  462. sleep 1
  463. else
  464. diff_c=0
  465. sleep $(( ( RANDOM % 60 ) + 20 ))
  466. fi
  467. done
  468. return 1
  469. }
  470. ipv6nat_checks() {
  471. err_count=0
  472. diff_c=0
  473. THRESHOLD=1
  474. # Reduce error count by 2 after restarting an unhealthy container
  475. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  476. while [ ${err_count} -lt ${THRESHOLD} ]; do
  477. err_c_cur=${err_count}
  478. CONTAINERS=$(curl --silent --insecure https://dockerapi/containers/json)
  479. 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")
  480. if [[ ! -z ${IPV6NAT_CONTAINER_ID} ]]; then
  481. 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)"
  482. 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)"
  483. DIFFERENCE_START_TIME=$(expr ${LATEST_IPV6NAT} - ${LATEST_STARTED} 2>/dev/null)
  484. if [[ "${DIFFERENCE_START_TIME}" -lt 30 ]]; then
  485. err_count=$(( ${err_count} + 1 ))
  486. fi
  487. fi
  488. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  489. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  490. progress "IPv6 NAT" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  491. if [[ $? == 10 ]]; then
  492. diff_c=0
  493. sleep 30
  494. else
  495. diff_c=0
  496. sleep 300
  497. fi
  498. done
  499. return 1
  500. }
  501. rspamd_checks() {
  502. err_count=0
  503. diff_c=0
  504. THRESHOLD=5
  505. # Reduce error count by 2 after restarting an unhealthy container
  506. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  507. while [ ${err_count} -lt ${THRESHOLD} ]; do
  508. touch /tmp/rspamd-mailcow; echo "$(tail -50 /tmp/rspamd-mailcow)" > /tmp/rspamd-mailcow
  509. host_ip=$(get_container_ip rspamd-mailcow)
  510. err_c_cur=${err_count}
  511. SCORE=$(echo 'To: null@localhost
  512. From: watchdog@localhost
  513. Empty
  514. ' | usr/bin/curl -s --data-binary @- --unix-socket /var/lib/rspamd/rspamd.sock http://rspamd/scan | jq -rc .default.required_score)
  515. if [[ ${SCORE} != "9999" ]]; then
  516. echo "Rspamd settings check failed" 2>> /tmp/rspamd-mailcow 1>&2
  517. err_count=$(( ${err_count} + 1))
  518. else
  519. echo "Rspamd settings check succeeded" 2>> /tmp/rspamd-mailcow 1>&2
  520. fi
  521. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  522. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  523. progress "Rspamd" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  524. if [[ $? == 10 ]]; then
  525. diff_c=0
  526. sleep 1
  527. else
  528. diff_c=0
  529. sleep $(( ( RANDOM % 60 ) + 20 ))
  530. fi
  531. done
  532. return 1
  533. }
  534. olefy_checks() {
  535. err_count=0
  536. diff_c=0
  537. THRESHOLD=5
  538. # Reduce error count by 2 after restarting an unhealthy container
  539. trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1
  540. while [ ${err_count} -lt ${THRESHOLD} ]; do
  541. touch /tmp/olefy-mailcow; echo "$(tail -50 /tmp/olefy-mailcow)" > /tmp/olefy-mailcow
  542. host_ip=$(get_container_ip olefy-mailcow)
  543. err_c_cur=${err_count}
  544. /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} + $? ))
  545. [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1
  546. [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} ))
  547. progress "Olefy" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c}
  548. if [[ $? == 10 ]]; then
  549. diff_c=0
  550. sleep 1
  551. else
  552. diff_c=0
  553. sleep $(( ( RANDOM % 60 ) + 20 ))
  554. fi
  555. done
  556. return 1
  557. }
  558. # Notify about start
  559. if [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]]; then
  560. mail_error "watchdog-mailcow" "Watchdog started monitoring mailcow."
  561. fi
  562. # Create watchdog agents
  563. (
  564. while true; do
  565. if ! nginx_checks; then
  566. log_msg "Nginx hit error limit"
  567. echo nginx-mailcow > /tmp/com_pipe
  568. fi
  569. done
  570. ) &
  571. PID=$!
  572. echo "Spawned nginx_checks with PID ${PID}"
  573. BACKGROUND_TASKS+=(${PID})
  574. (
  575. while true; do
  576. if ! mysql_checks; then
  577. log_msg "MySQL hit error limit"
  578. echo mysql-mailcow > /tmp/com_pipe
  579. fi
  580. done
  581. ) &
  582. PID=$!
  583. echo "Spawned mysql_checks with PID ${PID}"
  584. BACKGROUND_TASKS+=(${PID})
  585. (
  586. while true; do
  587. if ! redis_checks; then
  588. log_msg "Redis hit error limit"
  589. echo redis-mailcow > /tmp/com_pipe
  590. fi
  591. done
  592. ) &
  593. PID=$!
  594. echo "Spawned redis_checks with PID ${PID}"
  595. BACKGROUND_TASKS+=(${PID})
  596. (
  597. while true; do
  598. if ! phpfpm_checks; then
  599. log_msg "PHP-FPM hit error limit"
  600. echo php-fpm-mailcow > /tmp/com_pipe
  601. fi
  602. done
  603. ) &
  604. PID=$!
  605. echo "Spawned phpfpm_checks with PID ${PID}"
  606. BACKGROUND_TASKS+=(${PID})
  607. (
  608. while true; do
  609. if ! sogo_checks; then
  610. log_msg "SOGo hit error limit"
  611. echo sogo-mailcow > /tmp/com_pipe
  612. fi
  613. done
  614. ) &
  615. PID=$!
  616. echo "Spawned sogo_checks with PID ${PID}"
  617. BACKGROUND_TASKS+=(${PID})
  618. if [ ${CHECK_UNBOUND} -eq 1 ]; then
  619. (
  620. while true; do
  621. if ! unbound_checks; then
  622. log_msg "Unbound hit error limit"
  623. echo unbound-mailcow > /tmp/com_pipe
  624. fi
  625. done
  626. ) &
  627. PID=$!
  628. echo "Spawned unbound_checks with PID ${PID}"
  629. BACKGROUND_TASKS+=(${PID})
  630. fi
  631. if [[ "${SKIP_CLAMD}" =~ ^([nN][oO]|[nN])+$ ]]; then
  632. (
  633. while true; do
  634. if ! clamd_checks; then
  635. log_msg "Clamd hit error limit"
  636. echo clamd-mailcow > /tmp/com_pipe
  637. fi
  638. done
  639. ) &
  640. PID=$!
  641. echo "Spawned clamd_checks with PID ${PID}"
  642. BACKGROUND_TASKS+=(${PID})
  643. fi
  644. (
  645. while true; do
  646. if ! postfix_checks; then
  647. log_msg "Postfix hit error limit"
  648. echo postfix-mailcow > /tmp/com_pipe
  649. fi
  650. done
  651. ) &
  652. PID=$!
  653. echo "Spawned postfix_checks with PID ${PID}"
  654. BACKGROUND_TASKS+=(${PID})
  655. (
  656. while true; do
  657. if ! dovecot_checks; then
  658. log_msg "Dovecot hit error limit"
  659. echo dovecot-mailcow > /tmp/com_pipe
  660. fi
  661. done
  662. ) &
  663. PID=$!
  664. echo "Spawned dovecot_checks with PID ${PID}"
  665. BACKGROUND_TASKS+=(${PID})
  666. (
  667. while true; do
  668. if ! rspamd_checks; then
  669. log_msg "Rspamd hit error limit"
  670. echo rspamd-mailcow > /tmp/com_pipe
  671. fi
  672. done
  673. ) &
  674. PID=$!
  675. echo "Spawned rspamd_checks with PID ${PID}"
  676. BACKGROUND_TASKS+=(${PID})
  677. (
  678. while true; do
  679. if ! ratelimit_checks; then
  680. log_msg "Ratelimit hit error limit"
  681. echo ratelimit > /tmp/com_pipe
  682. fi
  683. done
  684. ) &
  685. PID=$!
  686. echo "Spawned ratelimit_checks with PID ${PID}"
  687. BACKGROUND_TASKS+=(${PID})
  688. (
  689. while true; do
  690. if ! fail2ban_checks; then
  691. log_msg "Fail2ban hit error limit"
  692. echo fail2ban > /tmp/com_pipe
  693. fi
  694. done
  695. ) &
  696. PID=$!
  697. echo "Spawned fail2ban_checks with PID ${PID}"
  698. BACKGROUND_TASKS+=(${PID})
  699. (
  700. while true; do
  701. if ! olefy_checks; then
  702. log_msg "Olefy hit error limit"
  703. echo olefy-mailcow > /tmp/com_pipe
  704. fi
  705. done
  706. ) &
  707. PID=$!
  708. echo "Spawned olefy_checks with PID ${PID}"
  709. BACKGROUND_TASKS+=(${PID})
  710. (
  711. while true; do
  712. if ! acme_checks; then
  713. log_msg "ACME client hit error limit"
  714. echo acme-mailcow > /tmp/com_pipe
  715. fi
  716. done
  717. ) &
  718. PID=$!
  719. echo "Spawned acme_checks with PID ${PID}"
  720. BACKGROUND_TASKS+=(${PID})
  721. (
  722. while true; do
  723. if ! ipv6nat_checks; then
  724. log_msg "IPv6 NAT warning: ipv6nat-mailcow container was not started at least 30s after siblings (not an error)"
  725. echo ipv6nat-mailcow > /tmp/com_pipe
  726. fi
  727. done
  728. ) &
  729. PID=$!
  730. echo "Spawned ipv6nat_checks with PID ${PID}"
  731. BACKGROUND_TASKS+=(${PID})
  732. # Monitor watchdog agents, stop script when agents fails and wait for respawn by Docker (restart:always:n)
  733. (
  734. while true; do
  735. for bg_task in ${BACKGROUND_TASKS[*]}; do
  736. if ! kill -0 ${bg_task} 1>&2; then
  737. log_msg "Worker ${bg_task} died, stopping watchdog and waiting for respawn..."
  738. kill -TERM 1
  739. fi
  740. sleep 10
  741. done
  742. done
  743. ) &
  744. # Monitor dockerapi
  745. (
  746. while true; do
  747. while nc -z dockerapi 443; do
  748. sleep 3
  749. done
  750. log_msg "Cannot find dockerapi-mailcow, waiting to recover..."
  751. kill -STOP ${BACKGROUND_TASKS[*]}
  752. until nc -z dockerapi 443; do
  753. sleep 3
  754. done
  755. kill -CONT ${BACKGROUND_TASKS[*]}
  756. kill -USR1 ${BACKGROUND_TASKS[*]}
  757. done
  758. ) &
  759. # Actions when threshold limit is reached
  760. while true; do
  761. CONTAINER_ID=
  762. HAS_INITDB=
  763. read com_pipe_answer </tmp/com_pipe
  764. if [ -s "/tmp/${com_pipe_answer}" ]; then
  765. cat "/tmp/${com_pipe_answer}"
  766. fi
  767. if [[ ${com_pipe_answer} == "ratelimit" ]]; then
  768. log_msg "At least one ratelimit was applied"
  769. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${com_pipe_answer}" "Please see mailcow UI logs for further information."
  770. elif [[ ${com_pipe_answer} == "acme-mailcow" ]]; then
  771. log_msg "acme-mailcow did not complete successfully"
  772. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${com_pipe_answer}" "Please check acme-mailcow for further information."
  773. elif [[ ${com_pipe_answer} == "fail2ban" ]]; then
  774. F2B_RES=($(timeout 4s redis-cli -h redis-mailcow --raw GET F2B_RES 2> /dev/null))
  775. if [[ ! -z "${F2B_RES}" ]]; then
  776. redis-cli -h redis-mailcow DEL F2B_RES > /dev/null
  777. host=
  778. for host in "${F2B_RES[@]}"; do
  779. log_msg "Banned ${host}"
  780. rm /tmp/fail2ban 2> /dev/null
  781. timeout 2s whois "${host}" > /tmp/fail2ban
  782. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && [[ ${WATCHDOG_NOTIFY_BAN} =~ ^([yY][eE][sS]|[yY])+$ ]] && mail_error "${com_pipe_answer}" "IP ban: ${host}"
  783. done
  784. fi
  785. elif [[ ${com_pipe_answer} =~ .+-mailcow ]]; then
  786. kill -STOP ${BACKGROUND_TASKS[*]}
  787. sleep 10
  788. 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")
  789. if [[ ! -z ${CONTAINER_ID} ]]; then
  790. if [[ "${com_pipe_answer}" == "php-fpm-mailcow" ]]; then
  791. 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)
  792. fi
  793. S_RUNNING=$(($(date +%s) - $(curl --silent --insecure https://dockerapi/containers/${CONTAINER_ID}/json | jq .State.StartedAt | xargs -n1 date +%s -d)))
  794. if [ ${S_RUNNING} -lt 360 ]; then
  795. log_msg "Container is running for less than 360 seconds, skipping action..."
  796. elif [[ ! -z ${HAS_INITDB} ]]; then
  797. log_msg "Database is being initialized by php-fpm-mailcow, not restarting but delaying checks for a minute..."
  798. sleep 60
  799. else
  800. log_msg "Sending restart command to ${CONTAINER_ID}..."
  801. curl --silent --insecure -XPOST https://dockerapi/containers/${CONTAINER_ID}/restart
  802. if [[ ${com_pipe_answer} != "ipv6nat-mailcow" ]]; then
  803. [[ ! -z ${WATCHDOG_NOTIFY_EMAIL} ]] && mail_error "${com_pipe_answer}"
  804. fi
  805. log_msg "Wait for restarted container to settle and continue watching..."
  806. sleep 35
  807. fi
  808. fi
  809. kill -CONT ${BACKGROUND_TASKS[*]}
  810. sleep 1
  811. kill -USR1 ${BACKGROUND_TASKS[*]}
  812. fi
  813. done