docker-entrypoint.sh 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. #!/bin/bash
  2. function array_by_comma { local IFS=","; echo "$*"; }
  3. # Wait for containers
  4. while ! mysqladmin status --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do
  5. echo "Waiting for SQL..."
  6. sleep 2
  7. done
  8. # Do not attempt to write to slave
  9. if [[ ! -z ${REDIS_SLAVEOF_IP} ]]; then
  10. REDIS_CMDLINE="redis-cli -h ${REDIS_SLAVEOF_IP} -p ${REDIS_SLAVEOF_PORT}"
  11. else
  12. REDIS_CMDLINE="redis-cli -h redis -p 6379"
  13. fi
  14. until [[ $(${REDIS_CMDLINE} PING) == "PONG" ]]; do
  15. echo "Waiting for Redis..."
  16. sleep 2
  17. done
  18. # Check mysql_upgrade (master and slave)
  19. CONTAINER_ID=
  20. until [[ ! -z "${CONTAINER_ID}" ]] && [[ "${CONTAINER_ID}" =~ ^[[:alnum:]]*$ ]]; do
  21. CONTAINER_ID=$(curl --silent --insecure https://dockerapi/containers/json | jq -r ".[] | {name: .Config.Labels[\"com.docker.compose.service\"], project: .Config.Labels[\"com.docker.compose.project\"], id: .Id}" 2> /dev/null | jq -rc "select( .name | tostring | contains(\"mysql-mailcow\")) | select( .project | tostring | contains(\"${COMPOSE_PROJECT_NAME,,}\")) | .id" 2> /dev/null)
  22. sleep 2
  23. done
  24. echo "MySQL @ ${CONTAINER_ID}"
  25. SQL_LOOP_C=0
  26. SQL_CHANGED=0
  27. until [[ ${SQL_UPGRADE_STATUS} == 'success' ]]; do
  28. if [ ${SQL_LOOP_C} -gt 4 ]; then
  29. echo "Tried to upgrade MySQL and failed, giving up after ${SQL_LOOP_C} retries and starting container (oops, not good)"
  30. break
  31. fi
  32. SQL_FULL_UPGRADE_RETURN=$(curl --silent --insecure -XPOST https://dockerapi/containers/${CONTAINER_ID}/exec -d '{"cmd":"system", "task":"mysql_upgrade"}' --silent -H 'Content-type: application/json')
  33. SQL_UPGRADE_STATUS=$(echo ${SQL_FULL_UPGRADE_RETURN} | jq -r .type)
  34. SQL_LOOP_C=$((SQL_LOOP_C+1))
  35. echo "SQL upgrade iteration #${SQL_LOOP_C}"
  36. if [[ ${SQL_UPGRADE_STATUS} == 'warning' ]]; then
  37. SQL_CHANGED=1
  38. echo "MySQL applied an upgrade, debug output:"
  39. echo ${SQL_FULL_UPGRADE_RETURN}
  40. sleep 3
  41. while ! mysqladmin status --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do
  42. echo "Waiting for SQL to return, please wait"
  43. sleep 2
  44. done
  45. continue
  46. elif [[ ${SQL_UPGRADE_STATUS} == 'success' ]]; then
  47. echo "MySQL is up-to-date - debug output:"
  48. echo ${SQL_FULL_UPGRADE_RETURN}
  49. else
  50. echo "No valid reponse for mysql_upgrade was received, debug output:"
  51. echo ${SQL_FULL_UPGRADE_RETURN}
  52. fi
  53. done
  54. # doing post-installation stuff, if SQL was upgraded (master and slave)
  55. if [ ${SQL_CHANGED} -eq 1 ]; then
  56. POSTFIX=$(curl --silent --insecure https://dockerapi/containers/json | jq -r ".[] | {name: .Config.Labels[\"com.docker.compose.service\"], project: .Config.Labels[\"com.docker.compose.project\"], id: .Id}" 2> /dev/null | jq -rc "select( .name | tostring | contains(\"postfix-mailcow\")) | select( .project | tostring | contains(\"${COMPOSE_PROJECT_NAME,,}\")) | .id" 2> /dev/null)
  57. if [[ -z "${POSTFIX}" ]] || ! [[ "${POSTFIX}" =~ ^[[:alnum:]]*$ ]]; then
  58. echo "Could not determine Postfix container ID, skipping Postfix restart."
  59. else
  60. echo "Restarting Postfix"
  61. curl -X POST --silent --insecure https://dockerapi/containers/${POSTFIX}/restart | jq -r '.msg'
  62. echo "Sleeping 5 seconds..."
  63. sleep 5
  64. fi
  65. fi
  66. # Check mysql tz import (master and slave)
  67. TZ_CHECK=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT CONVERT_TZ('2019-11-02 23:33:00','Europe/Berlin','UTC') AS time;" -BN 2> /dev/null)
  68. if [[ -z ${TZ_CHECK} ]] || [[ "${TZ_CHECK}" == "NULL" ]]; then
  69. SQL_FULL_TZINFO_IMPORT_RETURN=$(curl --silent --insecure -XPOST https://dockerapi/containers/${CONTAINER_ID}/exec -d '{"cmd":"system", "task":"mysql_tzinfo_to_sql"}' --silent -H 'Content-type: application/json')
  70. echo "MySQL mysql_tzinfo_to_sql - debug output:"
  71. echo ${SQL_FULL_TZINFO_IMPORT_RETURN}
  72. fi
  73. if [[ "${MASTER}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
  74. echo "We are master, preparing..."
  75. # Set a default release format
  76. if [[ -z $(${REDIS_CMDLINE} --raw GET Q_RELEASE_FORMAT) ]]; then
  77. ${REDIS_CMDLINE} --raw SET Q_RELEASE_FORMAT raw
  78. fi
  79. # Set max age of q items - if unset
  80. if [[ -z $(${REDIS_CMDLINE} --raw GET Q_MAX_AGE) ]]; then
  81. ${REDIS_CMDLINE} --raw SET Q_MAX_AGE 365
  82. fi
  83. # Set default password policy - if unset
  84. if [[ -z $(${REDIS_CMDLINE} --raw HGET PASSWD_POLICY length) ]]; then
  85. ${REDIS_CMDLINE} --raw HSET PASSWD_POLICY length 6
  86. ${REDIS_CMDLINE} --raw HSET PASSWD_POLICY chars 0
  87. ${REDIS_CMDLINE} --raw HSET PASSWD_POLICY special_chars 0
  88. ${REDIS_CMDLINE} --raw HSET PASSWD_POLICY lowerupper 0
  89. ${REDIS_CMDLINE} --raw HSET PASSWD_POLICY numbers 0
  90. fi
  91. # Trigger db init
  92. echo "Running DB init..."
  93. php -c /usr/local/etc/php -f /web/inc/init_db.inc.php
  94. # Recreating domain map
  95. echo "Rebuilding domain map in Redis..."
  96. declare -a DOMAIN_ARR
  97. ${REDIS_CMDLINE} DEL DOMAIN_MAP > /dev/null
  98. while read line
  99. do
  100. DOMAIN_ARR+=("$line")
  101. done < <(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain" -Bs)
  102. while read line
  103. do
  104. DOMAIN_ARR+=("$line")
  105. done < <(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT alias_domain FROM alias_domain" -Bs)
  106. if [[ ! -z ${DOMAIN_ARR} ]]; then
  107. for domain in "${DOMAIN_ARR[@]}"; do
  108. ${REDIS_CMDLINE} HSET DOMAIN_MAP ${domain} 1 > /dev/null
  109. done
  110. fi
  111. # Set API options if env vars are not empty
  112. if [[ ${API_ALLOW_FROM} != "invalid" ]] && [[ ! -z ${API_ALLOW_FROM} ]]; then
  113. IFS=',' read -r -a API_ALLOW_FROM_ARR <<< "${API_ALLOW_FROM}"
  114. declare -a VALIDATED_API_ALLOW_FROM_ARR
  115. REGEX_IP6='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}(/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$'
  116. REGEX_IP4='^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(/([0-9]|[1-2][0-9]|3[0-2]))?$'
  117. for IP in "${API_ALLOW_FROM_ARR[@]}"; do
  118. if [[ ${IP} =~ ${REGEX_IP6} ]] || [[ ${IP} =~ ${REGEX_IP4} ]]; then
  119. VALIDATED_API_ALLOW_FROM_ARR+=("${IP}")
  120. fi
  121. done
  122. VALIDATED_IPS=$(array_by_comma ${VALIDATED_API_ALLOW_FROM_ARR[*]})
  123. if [[ ! -z ${VALIDATED_IPS} ]]; then
  124. if [[ ${API_KEY} != "invalid" ]] && [[ ! -z ${API_KEY} ]]; then
  125. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF
  126. DELETE FROM api WHERE access = 'rw';
  127. INSERT INTO api (api_key, active, allow_from, access) VALUES ("${API_KEY}", "1", "${VALIDATED_IPS}", "rw");
  128. EOF
  129. fi
  130. if [[ ${API_KEY_READ_ONLY} != "invalid" ]] && [[ ! -z ${API_KEY_READ_ONLY} ]]; then
  131. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF
  132. DELETE FROM api WHERE access = 'ro';
  133. INSERT INTO api (api_key, active, allow_from, access) VALUES ("${API_KEY_READ_ONLY}", "1", "${VALIDATED_IPS}", "ro");
  134. EOF
  135. fi
  136. fi
  137. fi
  138. # Create events (master only, STATUS for event on slave will be SLAVESIDE_DISABLED)
  139. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF
  140. DROP EVENT IF EXISTS clean_spamalias;
  141. DELIMITER //
  142. CREATE EVENT clean_spamalias
  143. ON SCHEDULE EVERY 1 DAY DO
  144. BEGIN
  145. DELETE FROM spamalias WHERE validity < UNIX_TIMESTAMP();
  146. END;
  147. //
  148. DELIMITER ;
  149. DROP EVENT IF EXISTS clean_oauth2;
  150. DELIMITER //
  151. CREATE EVENT clean_oauth2
  152. ON SCHEDULE EVERY 1 DAY DO
  153. BEGIN
  154. DELETE FROM oauth_refresh_tokens WHERE expires < NOW();
  155. DELETE FROM oauth_access_tokens WHERE expires < NOW();
  156. DELETE FROM oauth_authorization_codes WHERE expires < NOW();
  157. END;
  158. //
  159. DELIMITER ;
  160. DROP EVENT IF EXISTS clean_sasl_log;
  161. DELIMITER //
  162. CREATE EVENT clean_sasl_log
  163. ON SCHEDULE EVERY 1 DAY DO
  164. BEGIN
  165. DELETE sasl_log.* FROM sasl_log
  166. LEFT JOIN (
  167. SELECT username, service, MAX(datetime) AS lastdate
  168. FROM sasl_log
  169. GROUP BY username, service
  170. ) AS last ON sasl_log.username = last.username AND sasl_log.service = last.service
  171. WHERE datetime < DATE_SUB(NOW(), INTERVAL 31 DAY) AND datetime < lastdate;
  172. DELETE FROM sasl_log
  173. WHERE username NOT IN (SELECT username FROM mailbox) AND
  174. datetime < DATE_SUB(NOW(), INTERVAL 31 DAY);
  175. END;
  176. //
  177. DELIMITER ;
  178. EOF
  179. fi
  180. # Create dummy for custom overrides of mailcow style
  181. [[ ! -f /web/css/build/0081-custom-mailcow.css ]] && echo '/* Autogenerated by mailcow */' > /web/css/build/0081-custom-mailcow.css
  182. # Fix permissions for global filters
  183. chown -R 82:82 /global_sieve/*
  184. # Fix permissions on twig cache folder
  185. chown -R 82:82 /web/templates/cache
  186. # Clear cache
  187. find /web/templates/cache/* -not -name '.gitkeep' -delete
  188. # list client ca of all domains for
  189. CA_LIST="/etc/nginx/conf.d/client_cas.crt"
  190. # Clear the output file
  191. > "$CA_LIST"
  192. # Execute the query and append each value to the output file
  193. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT ssl_client_ca FROM domain;" | while read -r ca; do
  194. echo "$ca" >> "$CA_LIST"
  195. done
  196. echo "SSL client CAs have been appended to $CA_LIST"
  197. # Run hooks
  198. for file in /hooks/*; do
  199. if [ -x "${file}" ]; then
  200. echo "Running hook ${file}"
  201. "${file}"
  202. fi
  203. done
  204. exec "$@"