[COMMON] Fix shopt nullglob bashism
[oom.git] / kubernetes / portal / components / portal-mariadb / resources / config / mariadb / docker-entrypoint.sh
1 #!/bin/bash
2
3 set -eo pipefail
4
5 # logging functions
6 mysql_log() {
7     local type
8     type="$1"; shift
9     printf '%s [%s] [Entrypoint]: %s\n' "$(date --rfc-3339=seconds)" "$type" "$*"
10 }
11 mysql_note() {
12     mysql_log Note "$@"
13 }
14 mysql_warn() {
15     mysql_log Warn "$@" >&2
16 }
17 mysql_error() {
18     mysql_log ERROR "$@" >&2
19     exit 1
20 }
21
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)
26 file_env() {
27     local var
28     var="$1"
29     local fileVar
30     fileVar="${var}_FILE"
31     local def
32     def="${2:-}"
33     if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
34         mysql_error "Both $var and $fileVar are set (but are exclusive)"
35     fi
36     local val
37     val="$def"
38     # val="${!var}"
39     # val="$(< "${!fileVar}")"
40     # eval replacement of the bashism equivalents above presents no security issue here
41     # since var and fileVar variables contents are derived from the file_env() function arguments.
42     # This method is only called inside this script with a limited number of possible values.
43     if [ "${!var:-}" ]; then
44         eval val=\$$var
45     elif [ "${!fileVar:-}" ]; then
46         val="$(< "$(eval echo "\$$fileVar")")"
47     fi
48     export "$var"="$val"
49     unset "$fileVar"
50 }
51
52
53 # usage: docker_process_init_files [file [file [...]]]
54 #    ie: docker_process_init_files /always-initdb.d/*
55 # process initializer files, based on file extensions
56 docker_process_init_files() {
57     # mysql here for backwards compatibility "${mysql[@]}"
58     mysql=( docker_process_sql )
59
60     echo
61     local f
62     for f; do
63         case "$f" in
64             *.sh)
65                 # https://github.com/docker-library/postgres/issues/450#issuecomment-393167936
66                 # https://github.com/docker-library/postgres/pull/452
67                 if [ -x "$f" ]; then
68                     mysql_note "$0: running $f"
69                     "$f"
70                 else
71                     mysql_note "$0: sourcing $f"
72                     . "$f"
73                 fi
74                 ;;
75             *.sql)    mysql_note "$0: running $f"; docker_process_sql < "$f"; echo ;;
76             *.sql.gz) mysql_note "$0: running $f"; gunzip -c "$f" | docker_process_sql; echo ;;
77             *.sql.xz) mysql_note "$0: running $f"; xzcat "$f" | docker_process_sql; echo ;;
78             *)        mysql_warn "$0: ignoring $f" ;;
79         esac
80         echo
81     done
82 }
83
84 mysql_check_config() {
85     local toRun
86     local errors
87     toRun=( "$@" --verbose --help --log-bin-index="$(mktemp -u)" )
88     if ! errors="$("${toRun[@]}" 2>&1 >/dev/null)"; then
89         mysql_error "$(printf 'mysqld failed while attempting to check config\n\tcommand was: ')${toRun[*]}$(printf'\n\t')$errors"
90     fi
91 }
92
93 # Fetch value from server config
94 # We use mysqld --verbose --help instead of my_print_defaults because the
95 # latter only show values present in config files, and not server defaults
96 mysql_get_config() {
97     local conf
98     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)"
102 }
103
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"
108     local i
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
112         extraArgs=""
113         if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
114             extraArgs=${extraArgs}" --dont-use-mysql-root-password"
115         fi
116         if echo 'SELECT 1' |docker_process_sql ${extraArgs} --database=mysql >/dev/null 2>&1; then
117             break
118         fi
119         sleep 1
120     done
121     if [ "$i" = 0 ]; then
122         mysql_error "Unable to start server."
123     fi
124 }
125
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."
131     fi
132 }
133
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')"
138     fi
139 }
140
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
145     user="$(id -u)"
146
147     # TODO other directories that are used by default? like /var/lib/mysql-files
148     # see https://github.com/docker-library/mysql/issues/562
149     mkdir -p "$DATADIR"
150
151     if [ "$user" = "0" ]; then
152         # this will cause less disk access than `chown -R`
153         find "$DATADIR" \! -user mysql -exec chown mysql '{}' +
154     fi
155 }
156
157 # initializes the database directory
158 docker_init_database_dir() {
159     mysql_note "Initializing database files"
160     installArgs=" --datadir=$DATADIR --rpm "
161     if { mysql_install_db --help || :; } | grep -q -- '--auth-root-authentication-method'; then
162         # 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
163         # see https://github.com/MariaDB/server/commit/b9f3f06857ac6f9105dc65caae19782f09b47fb3
164         # (this flag doesn't exist in 10.0 and below)
165         installArgs=${installArgs}" --auth-root-authentication-method=normal"
166     fi
167     # "Other options are passed to mysqld." (so we pass all "mysqld" arguments directly here)
168     mysql_install_db ${installArgs} "$(echo ${@} | sed 's/^ *[^ ]* *//')"
169     mysql_note "Database files initialized"
170 }
171
172 # Loads various settings that are used elsewhere in the script
173 # This should be called after mysql_check_config, but before any other functions
174 docker_setup_env() {
175     # Get config
176     declare -g DATADIR SOCKET
177     DATADIR="$(mysql_get_config 'datadir' "$@")"
178     SOCKET="$(mysql_get_config 'socket' "$@")"
179
180     # Initialize values that might be stored in a file
181     file_env 'MYSQL_ROOT_HOST' '%'
182     file_env 'MYSQL_DATABASE'
183     file_env 'MYSQL_USER'
184     file_env 'MYSQL_PASSWORD'
185     file_env 'MYSQL_ROOT_PASSWORD'
186     file_env 'PORTAL_DB_TABLES'
187
188     declare -g DATABASE_ALREADY_EXISTS
189     if [ -d "$DATADIR/mysql" ]; then
190         DATABASE_ALREADY_EXISTS='true'
191     fi
192 }
193
194 # Execute sql script, passed via stdin
195 # usage: docker_process_sql [--dont-use-mysql-root-password] [mysql-cli-args]
196 #    ie: docker_process_sql --database=mydb <<<'INSERT ...'
197 #    ie: docker_process_sql --dont-use-mysql-root-password --database=mydb <my-file.sql
198 docker_process_sql() {
199     passfileArgs=""
200     if [ '--dont-use-mysql-root-password' = "$1" ]; then
201         passfileArgs=${passfileArgs}" $1"
202         shift
203     fi
204     # args sent in can override this db, since they will be later in the command
205     if [ -n "$MYSQL_DATABASE" ]; then
206         set -- --database="$MYSQL_DATABASE" "$@"
207     fi
208
209     mysql --defaults-extra-file=<( _mysql_passfile ${passfileArgs}) --protocol=socket -uroot -hlocalhost --socket="${SOCKET}" "$@"
210 }
211
212 # Initializes database with timezone info and root password, plus optional extra db/user
213 docker_setup_db() {
214     # Load timezone info into database
215     if [ -z "$MYSQL_INITDB_SKIP_TZINFO" ]; then
216         {
217             # Aria in 10.4+ is slow due to "transactional" (crash safety)
218             # https://jira.mariadb.org/browse/MDEV-23326
219             # https://github.com/docker-library/mariadb/issues/262
220             local tztables
221             tztables=( time_zone time_zone_leap_second time_zone_name time_zone_transition time_zone_transition_type )
222             for table in "${tztables[@]}"; do
223                 echo "/*!100400 ALTER TABLE $table TRANSACTIONAL=0 */;"
224             done
225
226             # sed is for https://bugs.mysql.com/bug.php?id=20545
227             mysql_tzinfo_to_sql /usr/share/zoneinfo \
228                 | sed 's/Local time zone must be set--see zic manual page/FCTY/'
229
230             for table in "${tztables[@]}"; do
231                 echo "/*!100400 ALTER TABLE $table TRANSACTIONAL=1 */;"
232             done
233         } | docker_process_sql --dont-use-mysql-root-password --database=mysql
234         # tell docker_process_sql to not use MYSQL_ROOT_PASSWORD since it is not set yet
235     fi
236     # Generate random root password
237     if [ -n "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
238         export MYSQL_ROOT_PASSWORD="$(pwgen -1 32)"
239         mysql_note "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD"
240     fi
241     # Sets root password and creates root users for non-localhost hosts
242     local rootCreate
243     rootCreate=
244     # default root to listen for connections from anywhere
245     if [ -n "$MYSQL_ROOT_HOST" ] && [ "$MYSQL_ROOT_HOST" != 'localhost' ]; then
246         # no, we don't care if read finds a terminating character in this heredoc
247         # https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151
248         read -r -d '' rootCreate <<-EOSQL || true
249             CREATE USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
250             GRANT ALL ON *.* TO 'root'@'${MYSQL_ROOT_HOST}' WITH GRANT OPTION ;
251 EOSQL
252     fi
253
254     # tell docker_process_sql to not use MYSQL_ROOT_PASSWORD since it is just now being set
255     docker_process_sql --dont-use-mysql-root-password --database=mysql <<-EOSQL
256         -- What's done in this file shouldn't be replicated
257         --  or products like mysql-fabric won't work
258         SET @@SESSION.SQL_LOG_BIN=0;
259
260         DELETE FROM mysql.user WHERE user NOT IN ('mysql.sys', 'mariadb.sys', 'mysqlxsys', 'root') OR host NOT IN ('localhost') ;
261         SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}') ;
262         -- 10.1: https://github.com/MariaDB/server/blob/d925aec1c10cebf6c34825a7de50afe4e630aff4/scripts/mysql_secure_installation.sh#L347-L365
263         -- 10.5: https://github.com/MariaDB/server/blob/00c3a28820c67c37ebbca72691f4897b57f2eed5/scripts/mysql_secure_installation.sh#L351-L369
264         DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%' ;
265
266         GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ;
267         FLUSH PRIVILEGES ;
268         ${rootCreate}
269         DROP DATABASE IF EXISTS test ;
270 EOSQL
271
272     # Creates a custom database and user if specified
273     if [ -n "$MYSQL_DATABASE" ]; then
274         mysql_note "Creating database ${MYSQL_DATABASE}"
275         echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" |docker_process_sql --database=mysql
276     fi
277
278     if [ -n "$MYSQL_USER" ] && [ -n "$MYSQL_PASSWORD" ]; then
279         mysql_note "Creating user ${MYSQL_USER}"
280         echo "CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD' ;" |docker_process_sql --database=mysql
281
282         if [ -n "$MYSQL_DATABASE" ]; then
283             mysql_note "Giving user ${MYSQL_USER} access to schema ${MYSQL_DATABASE}"
284             echo "GRANT ALL ON \`$(echo $MYSQL_DATABASE | sed 's@_@\\_@g')\`.* TO '$MYSQL_USER'@'%' ;" | docker_process_sql --database=mysql
285         fi
286
287         echo "FLUSH PRIVILEGES ;" | docker_process_sql --database=mysql
288     fi
289 }
290
291 _mysql_passfile() {
292     # echo the password to the "file" the client uses
293     # the client command will use process substitution to create a file on the fly
294     # ie: --defaults-extra-file=<( _mysql_passfile )
295     if [ '--dont-use-mysql-root-password' != "$1" ] && [ -n "$MYSQL_ROOT_PASSWORD" ]; then
296         cat <<-EOF
297             [client]
298             password="${MYSQL_ROOT_PASSWORD}"
299 EOF
300     fi
301 }
302
303 # check arguments for an option that would cause mysqld to stop
304 # return true if there is one
305 _mysql_want_help() {
306     local arg
307     for arg; do
308         case "$arg" in
309             -'?'|--help|--print-defaults|-V|--version)
310                 return 0
311                 ;;
312         esac
313     done
314     return 1
315 }
316
317 _main() {
318     # if command starts with an option, prepend mysqld
319     if echo "$1" | grep '^-' >/dev/null; then
320         set -- mysqld "$@"
321     fi
322
323     # skip setup if they aren't running mysqld or want an option that stops mysqld
324     if [ "$1" = 'mysqld' ] && ! _mysql_want_help "$@"; then
325         mysql_note "Entrypoint script for MySQL Server ${MARIADB_VERSION} started."
326
327         mysql_check_config "$@"
328         # Load various environment variables
329         docker_setup_env "$@"
330         docker_create_db_directories
331
332         # If container is started as root user, restart as dedicated mysql user
333         if [ "$(id -u)" = "0" ]; then
334             mysql_note "Switching to dedicated user 'mysql'"
335             exec gosu mysql "$0" "$@"
336         fi
337
338         # there's no database, so it needs to be initialized
339         if [ -z "$DATABASE_ALREADY_EXISTS" ]; then
340             docker_verify_minimum_env
341
342             # check dir permissions to reduce likelihood of half-initialized database
343             ls /docker-entrypoint-initdb.d/ > /dev/null
344
345             docker_init_database_dir "$@"
346
347             mysql_note "Starting temporary server"
348             docker_temp_server_start "$@"
349             mysql_note "Temporary server started."
350
351             docker_setup_db
352             docker_process_init_files /docker-entrypoint-initdb.d/*
353
354             for i in $(echo $PORTAL_DB_TABLES | sed "s/,/ /g")
355                 do
356                     echo "Granting portal user ALL PRIVILEGES for table $i"
357                     echo "GRANT ALL ON \`$i\`.* TO '$MYSQL_USER'@'%' ;" | "${mysql[@]}"
358                 done
359
360             mysql_note "Stopping temporary server"
361             docker_temp_server_stop
362             mysql_note "Temporary server stopped"
363
364             echo
365             mysql_note "MySQL init process done. Ready for start up."
366             echo
367         fi
368     fi
369     exec "$@"
370 }
371
372 # If we are sourced from elsewhere, don't perform any further actions
373 # https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced/2942183#2942183
374 if [ "$(basename $0)" = "docker-entrypoint.sh" ]; then
375     _main "$@"
376 fi