28fcee1551b63e7245bc3c0d93561c4e87c8533d
[oom.git] / kubernetes / portal / charts / portal-mariadb / resources / config / mariadb / docker-entrypoint.sh
1 #!/bin/bash
2 set -eo pipefail
3 shopt -s nullglob
4
5 # if command starts with an option, prepend mysqld
6 if [ "${1:0:1}" = '-' ]; then
7         set -- mysqld "$@"
8 fi
9
10 # skip setup if they want an option that stops mysqld
11 wantHelp=
12 for arg; do
13         case "$arg" in
14                 -'?'|--help|--print-defaults|-V|--version)
15                         wantHelp=1
16                         break
17                         ;;
18         esac
19 done
20
21 # usage: file_env VAR [DEFAULT]
22 #    ie: file_env 'XYZ_DB_PASSWORD' 'example'
23 # (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
24 #  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
25 file_env() {
26         local var="$1"
27         local fileVar="${var}_FILE"
28         local def="${2:-}"
29         if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
30                 echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
31                 exit 1
32         fi
33         local val="$def"
34         if [ "${!var:-}" ]; then
35                 val="${!var}"
36         elif [ "${!fileVar:-}" ]; then
37                 val="$(< "${!fileVar}")"
38         fi
39         export "$var"="$val"
40         unset "$fileVar"
41 }
42
43 _check_config() {
44         toRun=( "$@" --verbose --help --log-bin-index="$(mktemp -u)" )
45         if ! errors="$("${toRun[@]}" 2>&1 >/dev/null)"; then
46                 cat >&2 <<-EOM
47                         ERROR: mysqld failed while attempting to check config
48                         command was: "${toRun[*]}"
49                         $errors
50                 EOM
51                 exit 1
52         fi
53 }
54
55 # Fetch value from server config
56 # We use mysqld --verbose --help instead of my_print_defaults because the
57 # latter only show values present in config files, and not server defaults
58 _get_config() {
59         local conf="$1"; shift
60         "$@" --verbose --help --log-bin-index="$(mktemp -u)" 2>/dev/null \
61                 | awk '$1 == "'"$conf"'" && /^[^ \t]/ { sub(/^[^ \t]+[ \t]+/, ""); print; exit }'
62         # match "datadir      /some/path with/spaces in/it here" but not "--xyz=abc\n     datadir (xyz)"
63 }
64
65 # allow the container to be started with `--user`
66 if [ "$1" = 'mysqld' -a -z "$wantHelp" -a "$(id -u)" = '0' ]; then
67         _check_config "$@"
68         DATADIR="$(_get_config 'datadir' "$@")"
69         mkdir -p "$DATADIR"
70         find "$DATADIR" \! -user mysql -exec chown mysql '{}' +
71         exec gosu mysql "$BASH_SOURCE" "$@"
72 fi
73
74 if [ "$1" = 'mysqld' -a -z "$wantHelp" ]; then
75         # still need to check config, container may have started with --user
76         _check_config "$@"
77         # Get config
78         DATADIR="$(_get_config 'datadir' "$@")"
79
80         if [ ! -d "$DATADIR/mysql" ]; then
81                 file_env 'MYSQL_ROOT_PASSWORD'
82                 if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
83                         echo >&2 'error: database is uninitialized and password option is not specified '
84                         echo >&2 '  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD'
85                         exit 1
86                 fi
87
88                 mkdir -p "$DATADIR"
89
90                 echo 'Initializing database'
91                 installArgs=( --datadir="$DATADIR" --rpm )
92                 if { mysql_install_db --help || :; } | grep -q -- '--auth-root-authentication-method'; then
93                         # 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
94                         # see https://github.com/MariaDB/server/commit/b9f3f06857ac6f9105dc65caae19782f09b47fb3
95                         # (this flag doesn't exist in 10.0 and below)
96                         installArgs+=( --auth-root-authentication-method=normal )
97                 fi
98                 # "Other options are passed to mysqld." (so we pass all "mysqld" arguments directly here)
99                 mysql_install_db "${installArgs[@]}" "${@:2}"
100                 echo 'Database initialized'
101
102                 SOCKET="$(_get_config 'socket' "$@")"
103                 "$@" --skip-networking --socket="${SOCKET}" &
104                 pid="$!"
105
106                 mysql=( mysql --protocol=socket -uroot -hlocalhost --socket="${SOCKET}" )
107
108                 for i in {60..0}; do
109                         if echo 'SELECT 1' | "${mysql[@]}" &> /dev/null; then
110                                 break
111                         fi
112                         echo 'MySQL init process in progress...'
113                         sleep 1
114                 done
115                 if [ "$i" = 0 ]; then
116                         echo >&2 'MySQL init process failed.'
117                         exit 1
118                 fi
119
120                 if [ -z "$MYSQL_INITDB_SKIP_TZINFO" ]; then
121                         # sed is for https://bugs.mysql.com/bug.php?id=20545
122                         mysql_tzinfo_to_sql /usr/share/zoneinfo | sed 's/Local time zone must be set--see zic manual page/FCTY/' | "${mysql[@]}" mysql
123                 fi
124
125                 if [ ! -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
126                         export MYSQL_ROOT_PASSWORD="$(pwgen -1 32)"
127                         echo "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD"
128                 fi
129
130                 rootCreate=
131                 # default root to listen for connections from anywhere
132                 file_env 'MYSQL_ROOT_HOST' '%'
133                 if [ ! -z "$MYSQL_ROOT_HOST" -a "$MYSQL_ROOT_HOST" != 'localhost' ]; then
134                         # no, we don't care if read finds a terminating character in this heredoc
135                         # https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151
136                         read -r -d '' rootCreate <<-EOSQL || true
137                                 CREATE USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
138                                 GRANT ALL ON *.* TO 'root'@'${MYSQL_ROOT_HOST}' WITH GRANT OPTION ;
139                         EOSQL
140                 fi
141
142                 "${mysql[@]}" <<-EOSQL
143                         -- What's done in this file shouldn't be replicated
144                         --  or products like mysql-fabric won't work
145                         SET @@SESSION.SQL_LOG_BIN=0;
146                         DELETE FROM mysql.user WHERE user NOT IN ('mysql.sys', 'mysqlxsys', 'root') OR host NOT IN ('localhost') ;
147                         SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}') ;
148                         GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ;
149                         ${rootCreate}
150                         DROP DATABASE IF EXISTS test ;
151                         FLUSH PRIVILEGES ;
152                 EOSQL
153
154                 if [ ! -z "$MYSQL_ROOT_PASSWORD" ]; then
155                         mysql+=( -p"${MYSQL_ROOT_PASSWORD}" )
156                 fi
157
158                 file_env 'MYSQL_DATABASE'
159                 if [ "$MYSQL_DATABASE" ]; then
160                         echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" | "${mysql[@]}"
161                         mysql+=( "$MYSQL_DATABASE" )
162                 fi
163
164                 file_env 'MYSQL_USER'
165                 file_env 'MYSQL_PASSWORD'
166                 if [ "$MYSQL_USER" -a "$MYSQL_PASSWORD" ]; then
167                         echo "CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD' ;" | "${mysql[@]}"
168
169                         if [ "$MYSQL_DATABASE" ]; then
170                                 echo "GRANT ALL ON \`$MYSQL_DATABASE\`.* TO '$MYSQL_USER'@'%' ;" | "${mysql[@]}"
171                         fi
172                 fi
173
174                 echo
175                 for f in /docker-entrypoint-initdb.d/*; do
176                         case "$f" in
177                                 *.sh)     echo "$0: running $f"; . "$f" ;;
178                                 *.sql)    echo "$0: running $f"; "${mysql[@]}" < "$f"; echo ;;
179                                 *.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${mysql[@]}"; echo ;;
180                                 *)        echo "$0: ignoring $f" ;;
181                         esac
182                         echo
183                 done
184
185                 if ! kill -s TERM "$pid" || ! wait "$pid"; then
186                         echo >&2 'MySQL init process failed.'
187                         exit 1
188                 fi
189
190                 echo
191                 echo 'MySQL init process done. Ready for start up.'
192                 echo
193         fi
194 fi
195
196 exec "$@"