mysql docker-entrypoint.sh分析

Docker Hub中有不少好用的Docker鏡像,但鏡像到底如何工做、能作什麼、怎麼作值得咱們研究,以下所示爲MySQL官方鏡像的docker-entrypoint.sh腳本分析:php

#!/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 "$@"
相關文章
相關標籤/搜索