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