95 lines
2.5 KiB
Bash
Executable File
95 lines
2.5 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
##################################################
|
|
# Mount file #
|
|
# - /etc/my.cnf #
|
|
# Mount dir #
|
|
# - LOG_DIR #
|
|
# - DATA_DIR #
|
|
# - BINLOG_DIR #
|
|
##################################################
|
|
|
|
set -euo pipefail
|
|
export LANG=en_US.UTF-8
|
|
trap Quit EXIT
|
|
|
|
PIDS=
|
|
GOT_SIGTERM=
|
|
LOG_DIR='/var/log/mysql'
|
|
DATA_DIR='/var/lib/mysql'
|
|
BINLOG_DIR='/var/lib/mysql-bin'
|
|
INIT_FLAG=${INIT_FLAG:-}
|
|
SOCK_FILE='/run/mysqld/mysqld.sock'
|
|
PID_FILE='/run/mysqld/mysqld.pid'
|
|
|
|
function Print {
|
|
local file=/dev/null
|
|
[ '-f' = "$1" ] && file=$2 && shift && shift
|
|
date +"[%F %T] $*" | tee -a $file
|
|
}
|
|
|
|
function Quit {
|
|
Print killing mysqld ...
|
|
mysqladmin shutdown --wait-for-all-slaves || true
|
|
while :; do
|
|
pkill -f mysqld && Print killing mysqld ... || break
|
|
sleep 1
|
|
done
|
|
Print Container stopped.
|
|
test -n "$GOT_SIGTERM"
|
|
}
|
|
|
|
function Init {
|
|
rm -f $SOCK_FILE $PID_FILE
|
|
chown -R mysql:mysql $LOG_DIR $BINLOG_DIR $DATA_DIR
|
|
if [ ! -d "$DATA_DIR/mysql" ]; then
|
|
Print Initing mysql db files ...
|
|
mysql_install_db --user=mysql > /dev/null
|
|
INIT_FLAG=1
|
|
fi
|
|
}
|
|
|
|
function StartProc {
|
|
local sql_file=
|
|
local sql_files=
|
|
Print Starting mysql ...
|
|
mysqld -u mysql &
|
|
PIDS="$PIDS $!"
|
|
while sleep 1; do
|
|
[ -e $SOCK_FILE ] && break || echo -n .
|
|
[ ! -e /proc/$! ] && echo && Print unexpected error! && exit
|
|
done
|
|
echo
|
|
if [ -n "$INIT_FLAG" ]; then
|
|
Print Securing database ...
|
|
mysql_secure_installation <<< "$(echo -e '\nn\nn\n\n\n\n\n')" > /dev/null
|
|
mysql -e "CREATE USER docker@localhost IDENTIFIED BY 'China_19\$(10)!'"
|
|
mysql -e "GRANT SHUTDOWN ON *.* TO docker@localhost"
|
|
if sql_files="$(ls $DATA_DIR/init_sql/*.sql 2>/dev/null)"; then
|
|
Print Importing the sql files ...
|
|
for sql_file in $sql_files; do
|
|
Print Importing $sql_file ...
|
|
mysql < $sql_file
|
|
done
|
|
Print Imported all sql files successfully.
|
|
fi
|
|
fi
|
|
Print MySQL is ready for connections.
|
|
}
|
|
|
|
function Main {
|
|
local pid=
|
|
Init
|
|
StartProc
|
|
trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
|
|
while [ -z "$GOT_SIGTERM" ] && sleep 2; do
|
|
for pid in $PIDS; do
|
|
[ ! -e /proc/$pid ] && Print Unexpected error! && exit
|
|
done
|
|
done
|
|
}
|
|
|
|
# Start here
|
|
Main
|
|
|