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