9 printf '%s [%s] [Entrypoint]: %s\n' "$(date --rfc-3339=seconds)" "$type" "$*"
15 mysql_log Warn "$@" >&2
18 mysql_log ERROR "$@" >&2
22 # usage: file_env VAR [DEFAULT]
23 # ie: file_env 'XYZ_DB_PASSWORD' 'example'
24 # (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
25 # "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
28 local fileVar="${var}_FILE"
30 if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
31 mysql_error "Both $var and $fileVar are set (but are exclusive)"
35 # val="$(< "${!fileVar}")"
36 # eval replacement of the bashism equivalents above presents no security issue here
37 # since var and fileVar variables contents are derived from the file_env() function arguments.
38 # This method is only called inside this script with a limited number of possible values.
39 if [ "${!var:-}" ]; then
41 elif [ "${!fileVar:-}" ]; then
42 val="$(< "$(eval echo "\$$fileVar")")"
48 # check to see if this file is being run or sourced from another script
50 # https://unix.stackexchange.com/a/215279
51 [ "${#FUNCNAME[@]}" -ge 2 ] \
52 && [ "${FUNCNAME[0]}" = '_is_sourced' ] \
53 && [ "${FUNCNAME[1]}" = 'source' ]
56 # usage: docker_process_init_files [file [file [...]]]
57 # ie: docker_process_init_files /always-initdb.d/*
58 # process initializer files, based on file extensions
59 docker_process_init_files() {
60 # mysql here for backwards compatibility "${mysql[@]}"
61 mysql=( docker_process_sql )
68 # https://github.com/docker-library/postgres/issues/450#issuecomment-393167936
69 # https://github.com/docker-library/postgres/pull/452
71 mysql_note "$0: running $f"
74 mysql_note "$0: sourcing $f"
78 *.sql) mysql_note "$0: running $f"; docker_process_sql < "$f"; echo ;;
79 *.sql.gz) mysql_note "$0: running $f"; gunzip -c "$f" | docker_process_sql; echo ;;
80 *.sql.xz) mysql_note "$0: running $f"; xzcat "$f" | docker_process_sql; echo ;;
81 *) mysql_warn "$0: ignoring $f" ;;
87 mysql_check_config() {
88 local toRun=( "$@" --verbose --help --log-bin-index="$(mktemp -u)" ) errors
89 if ! errors="$("${toRun[@]}" 2>&1 >/dev/null)"; then
90 mysql_error "$(printf 'mysqld failed while attempting to check config\n\tcommand was: ')${toRun[*]}$(printf'\n\t')$errors"
94 # Fetch value from server config
95 # We use mysqld --verbose --help instead of my_print_defaults because the
96 # latter only show values present in config files, and not server defaults
98 local conf="$1"; shift
99 "$@" --verbose --help --log-bin-index="$(mktemp -u)" 2>/dev/null \
100 | awk -v conf="$conf" '$1 == conf && /^[^ \t]/ { sub(/^[^ \t]+[ \t]+/, ""); print; exit }'
101 # match "datadir /some/path with/spaces in/it here" but not "--xyz=abc\n datadir (xyz)"
104 # Do a temporary startup of the MySQL server, for init purposes
105 docker_temp_server_start() {
106 "$@" --skip-networking --socket="${SOCKET}" &
107 mysql_note "Waiting for server startup"
109 for i in $(seq 30 -1 0); do
110 # only use the root password if the database has already been initializaed
111 # so that it won't try to fill in a password file when it hasn't been set yet
113 if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
114 extraArgs=${extraArgs}" --dont-use-mysql-root-password"
116 if echo 'SELECT 1' |docker_process_sql ${extraArgs} --database=mysql >/dev/null 2>&1; then
121 if [ "$i" = 0 ]; then
122 mysql_error "Unable to start server."
126 # Stop the server. When using a local socket file mysqladmin will block until
127 # the shutdown is complete.
128 docker_temp_server_stop() {
129 if ! mysqladmin --defaults-extra-file=<( _mysql_passfile ) shutdown -uroot --socket="${SOCKET}"; then
130 mysql_error "Unable to shut down server."
134 # Verify that the minimally required password settings are set for new databases.
135 docker_verify_minimum_env() {
136 if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
137 mysql_error "$(printf'Database is uninitialized and password option is not specified\n\tYou need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD')"
141 # creates folders for the database
142 # also ensures permission for user mysql of run as root
143 docker_create_db_directories() {
144 local user; user="$(id -u)"
146 # TODO other directories that are used by default? like /var/lib/mysql-files
147 # see https://github.com/docker-library/mysql/issues/562
150 if [ "$user" = "0" ]; then
151 # this will cause less disk access than `chown -R`
152 find "$DATADIR" \! -user mysql -exec chown mysql '{}' +
156 # initializes the database directory
157 docker_init_database_dir() {
158 mysql_note "Initializing database files"
159 installArgs=" --datadir=$DATADIR --rpm "
160 if { mysql_install_db --help || :; } | grep -q -- '--auth-root-authentication-method'; then
161 # beginning in 10.4.3, install_db uses "socket" which only allows system user root to connect, switch back to "normal" to allow mysql root without a password
162 # see https://github.com/MariaDB/server/commit/b9f3f06857ac6f9105dc65caae19782f09b47fb3
163 # (this flag doesn't exist in 10.0 and below)
164 installArgs=${installArgs}" --auth-root-authentication-method=normal"
166 # "Other options are passed to mysqld." (so we pass all "mysqld" arguments directly here)
167 mysql_install_db ${installArgs} "$(echo ${@} | sed 's/^ *[^ ]* *//')"
168 mysql_note "Database files initialized"
171 # Loads various settings that are used elsewhere in the script
172 # This should be called after mysql_check_config, but before any other functions
175 declare -g DATADIR SOCKET
176 DATADIR="$(mysql_get_config 'datadir' "$@")"
177 SOCKET="$(mysql_get_config 'socket' "$@")"
179 # Initialize values that might be stored in a file
180 file_env 'MYSQL_ROOT_HOST' '%'
181 file_env 'MYSQL_DATABASE'
182 file_env 'MYSQL_USER'
183 file_env 'MYSQL_PASSWORD'
184 file_env 'MYSQL_ROOT_PASSWORD'
185 file_env 'PORTAL_DB_TABLES'
187 declare -g DATABASE_ALREADY_EXISTS
188 if [ -d "$DATADIR/mysql" ]; then
189 DATABASE_ALREADY_EXISTS='true'
193 # Execute sql script, passed via stdin
194 # usage: docker_process_sql [--dont-use-mysql-root-password] [mysql-cli-args]
195 # ie: docker_process_sql --database=mydb <<<'INSERT ...'
196 # ie: docker_process_sql --dont-use-mysql-root-password --database=mydb <my-file.sql
197 docker_process_sql() {
199 if [ '--dont-use-mysql-root-password' = "$1" ]; then
200 passfileArgs=${passfileArgs}" $1"
203 # args sent in can override this db, since they will be later in the command
204 if [ -n "$MYSQL_DATABASE" ]; then
205 set -- --database="$MYSQL_DATABASE" "$@"
208 mysql --defaults-extra-file=<( _mysql_passfile ${passfileArgs}) --protocol=socket -uroot -hlocalhost --socket="${SOCKET}" "$@"
211 # Initializes database with timezone info and root password, plus optional extra db/user
213 # Load timezone info into database
214 if [ -z "$MYSQL_INITDB_SKIP_TZINFO" ]; then
216 # Aria in 10.4+ is slow due to "transactional" (crash safety)
217 # https://jira.mariadb.org/browse/MDEV-23326
218 # https://github.com/docker-library/mariadb/issues/262
219 local tztables=( time_zone time_zone_leap_second time_zone_name time_zone_transition time_zone_transition_type )
220 for table in "${tztables[@]}"; do
221 echo "/*!100400 ALTER TABLE $table TRANSACTIONAL=0 */;"
224 # sed is for https://bugs.mysql.com/bug.php?id=20545
225 mysql_tzinfo_to_sql /usr/share/zoneinfo \
226 | sed 's/Local time zone must be set--see zic manual page/FCTY/'
228 for table in "${tztables[@]}"; do
229 echo "/*!100400 ALTER TABLE $table TRANSACTIONAL=1 */;"
231 } | docker_process_sql --dont-use-mysql-root-password --database=mysql
232 # tell docker_process_sql to not use MYSQL_ROOT_PASSWORD since it is not set yet
234 # Generate random root password
235 if [ -n "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
236 export MYSQL_ROOT_PASSWORD="$(pwgen -1 32)"
237 mysql_note "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD"
239 # Sets root password and creates root users for non-localhost hosts
241 # default root to listen for connections from anywhere
242 if [ -n "$MYSQL_ROOT_HOST" ] && [ "$MYSQL_ROOT_HOST" != 'localhost' ]; then
243 # no, we don't care if read finds a terminating character in this heredoc
244 # https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151
245 read -r -d '' rootCreate <<-EOSQL || true
246 CREATE USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
247 GRANT ALL ON *.* TO 'root'@'${MYSQL_ROOT_HOST}' WITH GRANT OPTION ;
251 # tell docker_process_sql to not use MYSQL_ROOT_PASSWORD since it is just now being set
252 docker_process_sql --dont-use-mysql-root-password --database=mysql <<-EOSQL
253 -- What's done in this file shouldn't be replicated
254 -- or products like mysql-fabric won't work
255 SET @@SESSION.SQL_LOG_BIN=0;
257 DELETE FROM mysql.user WHERE user NOT IN ('mysql.sys', 'mariadb.sys', 'mysqlxsys', 'root') OR host NOT IN ('localhost') ;
258 SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}') ;
259 -- 10.1: https://github.com/MariaDB/server/blob/d925aec1c10cebf6c34825a7de50afe4e630aff4/scripts/mysql_secure_installation.sh#L347-L365
260 -- 10.5: https://github.com/MariaDB/server/blob/00c3a28820c67c37ebbca72691f4897b57f2eed5/scripts/mysql_secure_installation.sh#L351-L369
261 DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%' ;
263 GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ;
266 DROP DATABASE IF EXISTS test ;
269 # Creates a custom database and user if specified
270 if [ -n "$MYSQL_DATABASE" ]; then
271 mysql_note "Creating database ${MYSQL_DATABASE}"
272 echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" |docker_process_sql --database=mysql
275 if [ -n "$MYSQL_USER" ] && [ -n "$MYSQL_PASSWORD" ]; then
276 mysql_note "Creating user ${MYSQL_USER}"
277 echo "CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD' ;" |docker_process_sql --database=mysql
279 if [ -n "$MYSQL_DATABASE" ]; then
280 mysql_note "Giving user ${MYSQL_USER} access to schema ${MYSQL_DATABASE}"
281 echo "GRANT ALL ON \`$(echo $MYSQL_DATABASE | sed 's@_@\\_@g')\`.* TO '$MYSQL_USER'@'%' ;" | docker_process_sql --database=mysql
284 echo "FLUSH PRIVILEGES ;" | docker_process_sql --database=mysql
289 # echo the password to the "file" the client uses
290 # the client command will use process substitution to create a file on the fly
291 # ie: --defaults-extra-file=<( _mysql_passfile )
292 if [ '--dont-use-mysql-root-password' != "$1" ] && [ -n "$MYSQL_ROOT_PASSWORD" ]; then
295 password="${MYSQL_ROOT_PASSWORD}"
300 # check arguments for an option that would cause mysqld to stop
301 # return true if there is one
306 -'?'|--help|--print-defaults|-V|--version)
315 # if command starts with an option, prepend mysqld
316 if echo "$1" | grep '^-' >/dev/null; then
320 # skip setup if they aren't running mysqld or want an option that stops mysqld
321 if [ "$1" = 'mysqld' ] && ! _mysql_want_help "$@"; then
322 mysql_note "Entrypoint script for MySQL Server ${MARIADB_VERSION} started."
324 mysql_check_config "$@"
325 # Load various environment variables
326 docker_setup_env "$@"
327 docker_create_db_directories
329 # If container is started as root user, restart as dedicated mysql user
330 if [ "$(id -u)" = "0" ]; then
331 mysql_note "Switching to dedicated user 'mysql'"
332 exec gosu mysql "$0" "$@"
335 # there's no database, so it needs to be initialized
336 if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
337 docker_verify_minimum_env
339 # check dir permissions to reduce likelihood of half-initialized database
340 ls /docker-entrypoint-initdb.d/ > /dev/null
342 docker_init_database_dir "$@"
344 mysql_note "Starting temporary server"
345 docker_temp_server_start "$@"
346 mysql_note "Temporary server started."
349 docker_process_init_files /docker-entrypoint-initdb.d/*
351 for i in $(echo $PORTAL_DB_TABLES | sed "s/,/ /g")
353 echo "Granting portal user ALL PRIVILEGES for table $i"
354 echo "GRANT ALL ON \`$i\`.* TO '$MYSQL_USER'@'%' ;" | "${mysql[@]}"
357 mysql_note "Stopping temporary server"
358 docker_temp_server_stop
359 mysql_note "Temporary server stopped"
362 mysql_note "MySQL init process done. Ready for start up."
369 # If we are sourced from elsewhere, don't perform any further actions
370 if ! _is_sourced; then