乐趣区

mysql-dockerentrypointsh分析

Docker Hub中有很多好用的 Docker 镜像,但镜像到底如何工作、能做什么、怎么做值得我们研究,如下所示为 MySQL 官方镜像的 docker-entrypoint.sh 脚本分析:

#!/bin/bash
set -eo pipefail
shopt -s nullglob

################################################################
# 若启动命令时附加了参数,则在参数前添加 mysqld,如 $0 -f test,则经过此代码处理后,# $@参数变 mysqld -f test。其中 ${1:0:1}从 $1 参数第 0 个位置取 1 字符,如 $1 为 -f,则
# 取 '-' 字符,若条件为真,通过 set 命令重置 $@参数,添加 mysqld 前缀,即经过处理后 $1 变
# 为 mysqld。################################################################
# if command starts with an option, prepend mysqld
if ["${1:0:1}" = '-' ]; then
    set -- mysqld "$@"
fi

# 解析参数,是否是获取帮助信息参数,并设置 wantHelp 值
#####################################################
# skip setup if they want an option that stops mysqld
wantHelp=
for arg; do
    case "$arg" in
        -'?'|--help|--print-defaults|-V|--version)
            wantHelp=1
            break
            ;;
    esac
done

#############################
# 从文件中读取变量值
#############################
# usage: file_env VAR [DEFAULT]
#    ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
#  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
    local var="$1"
    local fileVar="${var}_FILE"
    local def="${2:-}"
    if ["${!var:-}" ] && ["${!fileVar:-}" ]; then
        echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
        exit 1
    fi
    local val="$def"
    if ["${!var:-}" ]; then
        val="${!var}"
    elif ["${!fileVar:-}" ]; then
        val="$(<"${!fileVar}")"
    fi
    export "$var"="$val"
    unset "$fileVar"
}

###########################################################################
# 运行 mysqld --help --verbose --help 2>&1 >/dev/null 命令,# 此命令会检查配置文件,若配置文件没问题,则成功,不成功则输出错误信息,及 if 中添
# 加!取不成功。###########################################################################
_check_config() {toRun=( "$@" --verbose --help)
        if ! errors="$("${toRun[@]}"2>&1 >/dev/null)"; then
                cat >&2 <<-EOM
                        ERROR: mysqld failed while attempting to check config
                        command was: "${toRun[*]}"
                        $errors
                EOM
                exit 1
        fi
}

# 1. $1 参数为 mysqld 以及 wanthelp 参数为空 以及 root 用户,执行此代码;# 2. _check_config 检查配置文件是否正确
# 3. 获取 DATADIR 目录,执行 mysqld --verbose --help --log-bin-index=/tmp/tmp.4SyApJWeIo| \
#         awk '$1 =="'"datadir"'"{print $2; exit}'
# 4. 创建并修改目录权限
# 5. 执行 exec gosu mysql docker-entrypoint.sh "$@",即重新以 mysql 用户再次调用脚
#    本
# allow the container to be started with `--user`
if ["$1" = 'mysqld' -a -z "$wantHelp" -a "$(id -u)" = '0' ]; then
        _check_config "$@"
        DATADIR="$(_get_config'datadir'"$@")"mkdir -p"$DATADIR"chown -R mysql:mysql"$DATADIR"exec gosu mysql"$BASH_SOURCE""$@"
fi

# 1. $1 参数为 mysqld 以及 wanthelp 参数为空,执行此代码,及 exec gosu 会执行此代码;if ["$1" = 'mysqld' -a -z "$wantHelp"]; then

# 2. 仍然检查配置文件以及获取 datadir 目录
    # still need to check config, container may have started with --user
    _check_config "$@"
    # Get config
    DATADIR="$(_get_config'datadir'"$@")"

# 3. 若 mysql 数据库未创建,则执行本段逻辑
    if [! -d "$DATADIR/mysql"]; then
# 4. 检查是否设置变量,如 root 密码、允许 root 密码为空亦或者随机密码
        file_env 'MYSQL_ROOT_PASSWORD'
        if [-z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD"]; then
            echo >&2 'error: database is uninitialized and password option is not specified'
            echo >&2 'You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD'
            exit 1
        fi
# 5. 创建目录
        mkdir -p "$DATADIR"

# 6. 执行 mysqld 命令初始化数据库
        echo 'Initializing database'
        "$@" --initialize-insecure
        echo 'Database initialized'

# 7. command -v mysql_ssl_rsa_setup 检查命令是否可执行,以及是否存在
# server-key.pem 文件,若不存在,则生成证书
        if command -v mysql_ssl_rsa_setup > /dev/null && [! -e "$DATADIR/server-key.pem"]; then
            # https://github.com/mysql/mysql-server/blob/23032807537d8dd8ee4ec1c4d40f0633cd4e12f9/packaging/deb-in/extra/mysql-systemd-start#L81-L84
            echo 'Initializing certificates'
            mysql_ssl_rsa_setup --datadir="$DATADIR"
            echo 'Certificates initialized'
        fi

# 8. 获取 socket 值并启动 mysql
        SOCKET="$(_get_config'socket'"$@")""$@" --skip-networking --socket="${SOCKET}" &
        pid="$!"

# 9. 设置 mysql 变量(列表形式),而后可以 ${mysql[@]}调用
        mysql=(mysql --protocol=socket -uroot -hlocalhost --socket="${SOCKET}" )

# 10. 运行 30 次,验证 mysql 是否已经启动完毕
        for i in {30..0}; do
            if echo 'SELECT 1' | "${mysql[@]}" &> /dev/null; then
                break
            fi
            echo 'MySQL init process in progress...'
            sleep 1
        done
# 11. 若 i 为 0 值,则表明 mysql 启动失败
        if ["$i" = 0]; then
            echo >&2 'MySQL init process failed.'
            exit 1
        fi

# 11. 解决时区 bug
        if [-z "$MYSQL_INITDB_SKIP_TZINFO"]; then
            # sed is for https://bugs.mysql.com/bug.php?id=20545
            mysql_tzinfo_to_sql /usr/share/zoneinfo | \
                         sed 's/Local time zone must be set--see zic manual page/FCTY/' | "${mysql[@]}" mysql
        fi

# 12. 生成 root 随机密码
        if [! -z "$MYSQL_RANDOM_ROOT_PASSWORD"]; then
            export MYSQL_ROOT_PASSWORD="$(pwgen -1 32)"
            echo "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD"
        fi

# 13. 若 MYSQL_ROOT_HOST 不为空亦或者不为 localhost,则创建 root 用户
        rootCreate=
        # default root to listen for connections from anywhere
        file_env 'MYSQL_ROOT_HOST' '%'
        if [! -z "$MYSQL_ROOT_HOST" -a "$MYSQL_ROOT_HOST" != 'localhost']; then
            # no, we don't care if read finds a terminating character in this heredoc
            # https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151
            read -r -d '' rootCreate <<-EOSQL || true
                CREATE USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
                GRANT ALL ON *.* TO 'root'@'${MYSQL_ROOT_HOST}' WITH GRANT OPTION ;
            EOSQL
        fi

# 14. 为 'root'@'localhost' 重置 root 密码
#     使用 $rootCreate 创建 root
        "${mysql[@]}" <<-EOSQL
            -- What's done in this file shouldn't be replicated
            --  or products like mysql-fabric won't work
            SET @@SESSION.SQL_LOG_BIN=0;
            SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}') ;
            GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ;
            ${rootCreate}
            DROP DATABASE IF EXISTS test ;
            FLUSH PRIVILEGES ;
        EOSQL

# 15. 已设置 root 密码,故 mysql 需加上 root 密码
        if [! -z "$MYSQL_ROOT_PASSWORD"]; then
            mysql+=(-p"${MYSQL_ROOT_PASSWORD}" )
        fi

# 16. 若配置了 MYSQL_DATABASE 变量,则创建
        file_env 'MYSQL_DATABASE'
        if ["$MYSQL_DATABASE"]; then
            echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" | "${mysql[@]}"
            mysql+=("$MYSQL_DATABASE")
        fi

# 17. 在数据库内创建用户
        file_env 'MYSQL_USER'
        file_env 'MYSQL_PASSWORD'
        if ["$MYSQL_USER" -a "$MYSQL_PASSWORD"]; then
            echo "CREATE USER'$MYSQL_USER'@'%'IDENTIFIED BY'$MYSQL_PASSWORD';" | "${mysql[@]}"

            if ["$MYSQL_DATABASE"]; then
                echo "GRANT ALL ON \`$MYSQL_DATABASE\`.* TO'$MYSQL_USER'@'%';" | "${mysql[@]}"
            fi

            echo 'FLUSH PRIVILEGES ;' | "${mysql[@]}"
        fi

# 18. 执行 /docker-entrypoint-initdb.d 目录下面的脚本,包含 shell、sql
        echo
        for f in /docker-entrypoint-initdb.d/*; do
            case "$f" in
                *.sh)     echo "$0: running $f"; . "$f" ;;
                *.sql)    echo "$0: running $f"; "${mysql[@]}" < "$f"; echo ;;
                *.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${mysql[@]}"; echo ;;
                *)        echo "$0: ignoring $f" ;;
            esac
            echo
        done

# 19. 设置 root 密码是否过期
        if [! -z "$MYSQL_ONETIME_PASSWORD"]; then
            "${mysql[@]}" <<-EOSQL
                ALTER USER 'root'@'%' PASSWORD EXPIRE;
            EOSQL
        fi

# 20. kill -s TERM "$pid" 杀掉 mysql 进程,执行成功则返回 0,而!kill 取反,即 kill 成
#     功后才执行后面的!wait 命令
        if ! kill -s TERM "$pid" || ! wait "$pid"; then
            echo >&2 'MySQL init process failed.'
            exit 1
        fi

# 21. 初始化成功后,再次启动
        echo
        echo 'MySQL init process done. Ready for start up.'
        echo
    fi
fi

# 22. 正式启动数据库
exec "$@"
退出移动版