From bde27382b73b871eaa5e5507991cf35774ada300 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 15:40:52 +0800 Subject: [PATCH 01/40] Update install.sh --- plugins/mysql-apt/install.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/plugins/mysql-apt/install.sh b/plugins/mysql-apt/install.sh index 592dca39bb..701a0866e0 100755 --- a/plugins/mysql-apt/install.sh +++ b/plugins/mysql-apt/install.sh @@ -57,7 +57,12 @@ if [ "${action}" == "uninstall" ];then fi fi -sh -x $curPath/versions/$2/install.sh $1 + +if [ "$2" == "8.4" ];then + sh -x $curPath/versions/$2/install_generic.sh $1 +else + sh -x $curPath/versions/$2/install.sh $1 +fi if [ "${action}" == "install" ];then #初始化 From 3e5c005f2550a9abf91adb661833153e068bc0fb Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 15:50:31 +0800 Subject: [PATCH 02/40] update_dev --- .../mysql-apt/versions/8.4/install_generic.sh | 30 ++++--------------- scripts/install/debian.sh | 4 +++ scripts/install/ubuntu.sh | 4 +++ 3 files changed, 13 insertions(+), 25 deletions(-) diff --git a/plugins/mysql-apt/versions/8.4/install_generic.sh b/plugins/mysql-apt/versions/8.4/install_generic.sh index e2a2195fdb..7812c18713 100755 --- a/plugins/mysql-apt/versions/8.4/install_generic.sh +++ b/plugins/mysql-apt/versions/8.4/install_generic.sh @@ -44,7 +44,7 @@ fi MYSQL_VER=8.4.2 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28_${TMP_ARCH} # /lib/systemd/system/mysql.service @@ -60,33 +60,13 @@ mkdir -p /var/run/mysqld chown mysql -R /var/run/mysqld # Linux - Generic - # https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz +wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz -# SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28_${TMP_ARCH} -# wget --no-check-certificate -O mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - +if [ -d ${myDir} ];then + cd ${myDir} && tar zvxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +fi # 测试时可关闭 rm -rf $myDir diff --git a/scripts/install/debian.sh b/scripts/install/debian.sh index 5bf39008c9..04e4ec5613 100644 --- a/scripts/install/debian.sh +++ b/scripts/install/debian.sh @@ -82,6 +82,10 @@ apt install -y libncurses5 apt install -y libncurses5-dev apt install -y bzip2 +apt install -y libnuma1 +apt install -y libaio1 +apt install -y libmecab2 + P_VER=`python3 -V | awk '{print $2}'` if version_ge "$P_VER" "3.11.0" ;then echo -e "\e[1;31mapt install python3.12-venv\e[0m" diff --git a/scripts/install/ubuntu.sh b/scripts/install/ubuntu.sh index 8dbccc416b..caf980e624 100644 --- a/scripts/install/ubuntu.sh +++ b/scripts/install/ubuntu.sh @@ -39,6 +39,10 @@ apt install -y libncurses5-dev apt install -y software-properties-common apt install -y bzip2 +apt install -y libnuma1 +apt install -y libaio1 +apt install -y libmecab2 + P_VER=`python3 -V | awk '{print $2}'` if version_ge "$P_VER" "3.11.0" ;then echo -e "\e[1;31mapt install python3.12-venv\e[0m" From aeb0f866c8d8fcd76e16c569829223759e61264d Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 16:39:32 +0800 Subject: [PATCH 03/40] Update mysql8.4.service.tpl --- plugins/mysql-apt/init.d/mysql8.4.service.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/mysql-apt/init.d/mysql8.4.service.tpl b/plugins/mysql-apt/init.d/mysql8.4.service.tpl index a0a8924936..8c4e39fdc2 100644 --- a/plugins/mysql-apt/init.d/mysql8.4.service.tpl +++ b/plugins/mysql-apt/init.d/mysql8.4.service.tpl @@ -35,7 +35,7 @@ WantedBy=multi-user.target User=mysql Group=mysql Type=notify -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 10000 Restart=on-failure From 43e69909cda117739f1b7d38ce7bb68b1d9256e4 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 16:59:35 +0800 Subject: [PATCH 04/40] update --- plugins/mysql-apt/index.py | 32 +++++++++---------- plugins/mysql-apt/index_mysql_apt.py | 10 +++--- .../mysql-apt/versions/8.4/install_generic.sh | 29 ++++++++--------- 3 files changed, 34 insertions(+), 37 deletions(-) diff --git a/plugins/mysql-apt/index.py b/plugins/mysql-apt/index.py index 4b9f03c7e5..baa342bc1f 100755 --- a/plugins/mysql-apt/index.py +++ b/plugins/mysql-apt/index.py @@ -416,7 +416,7 @@ def initMysql57Data(): myconf = serverdir + "/etc/my.cnf" user = pGetDbUser() - cmd = serverdir + '/bin/usr/sbin/mysqld --basedir=' + serverdir + '/bin/usr --datadir=' + \ + cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + \ datadir + ' --initialize-insecure --explicit_defaults_for_timestamp' data = mw.execShell(cmd) if data[1].lower().find('error') != -1: @@ -444,7 +444,7 @@ def initMysql8Data(): serverdir = getServerDir() user = pGetDbUser() - cmd = serverdir + '/bin/usr/sbin/mysqld --basedir=' + serverdir + '/bin/usr --datadir=' + datadir + \ + cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + datadir + \ ' --initialize-insecure --lower-case-table-names=1' data = mw.execShell(cmd) if data[1].lower().find('error') != -1: @@ -470,7 +470,7 @@ def initMysql8Pwd(): myconf = serverdir + "/etc/my.cnf" pwd = mw.getRandomString(16) - cmd_my = serverdir + '/bin/usr/bin/mysql' + cmd_my = serverdir + '/bin/mysql' cmd_pass = cmd_my + ' --defaults-file=' + myconf + ' -uroot -e' cmd_pass = cmd_pass + '"alter user \'root\'@\'localhost\' identified by \'' + pwd + '\';' @@ -494,12 +494,10 @@ def initMysql8Pwd(): # 删除冗余账户 hostname = mw.execShell('hostname')[0].strip() if hostname != 'localhost': - drop_hostname = cmd_my + ' --defaults-file=' + \ - myconf + ' -uroot -p' + pwd + ' -e "drop user \'\'@\'' + hostname + '\'";' + drop_hostname = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + pwd + ' -e "drop user \'\'@\'' + hostname + '\'";' mw.execShell(drop_hostname) - drop_root_hostname = cmd_my + ' --defaults-file=' + \ - myconf + ' -uroot -p' + pwd + ' -e "drop user \'root\'@\'' + hostname + '\'";' + drop_root_hostname = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + pwd + ' -e "drop user \'root\'@\'' + hostname + '\'";' mw.execShell(drop_root_hostname) return True @@ -898,7 +896,7 @@ def importDbExternal(): sock = getSocketFile() os.environ["MYSQL_PWD"] = pwd - mysql_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + \ + mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + \ pwd + ' ' + name + ' < ' + import_sql # print(mysql_cmd) @@ -984,7 +982,7 @@ def importDbExternalProgressBar(): # option = ' --set-gtid-purged=off ' my_cnf = getConf() - mysql_cmd = getServerDir() + '/bin/usr/bin/mysql --defaults-file=' + my_cnf + \ + mysql_cmd = getServerDir() + '/bin/mysql --defaults-file=' + my_cnf + \ ' -uroot -p"' + pwd + '" -f ' + name mysql_cmd_progress_bar = "pv -t -p " + import_sql + '|'+ mysql_cmd print(mysql_cmd_progress_bar) @@ -1009,7 +1007,7 @@ def importDbBackup(): pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') sock = getSocketFile() - mysql_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ + mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ ' ' + name + ' < ' + file_path_sql # print(mysql_cmd) @@ -1514,7 +1512,7 @@ def resetDbRootPwd(version): pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) mdb8 = getMdb8Ver() if not mw.inArray(mdb8, version): - cmd_pass = serverdir + '/bin/usr/bin/mysql --defaults-file=' + myconf + ' -uroot -e' + cmd_pass = serverdir + '/bin/mysql --defaults-file=' + myconf + ' -uroot -e' cmd_pass = cmd_pass + '"UPDATE mysql.user SET password=PASSWORD(\'' + pwd + "') WHERE user='root';" cmd_pass = cmd_pass + 'flush privileges;"' data = mw.execShell(cmd_pass) @@ -1534,7 +1532,7 @@ def resetDbRootPwd(version): tmp_file = "/tmp/mysql_init_tmp.log" mw.writeFile(tmp_file, reset_pwd) - cmd_pass = serverdir + '/bin/usr/bin/mysql --defaults-file=' + myconf + ' -uroot -proot < ' + tmp_file + cmd_pass = serverdir + '/bin/mysql --defaults-file=' + myconf + ' -uroot -proot < ' + tmp_file data = mw.execShell(cmd_pass) # print(data) @@ -3245,7 +3243,7 @@ def doFullSyncUser(version=''): dmp_option += " --master-data=1 --apply-slave-statements --include-master-host-port --compress " - dump_sql_data = getServerDir() + "/bin/usr/bin/mysqldump --single-transaction --default-character-set=utf8mb4 -q " + dmp_option + " -h" + \ + dump_sql_data = getServerDir() + "/bin/mysqldump --single-transaction --default-character-set=utf8mb4 -q " + dmp_option + " -h" + \ ip + " -P" + port + " -u" + user + ' -p"' + apass + '" --ssl-mode=DISABLED ' + sync_db + " > " + bak_file print(dump_sql_data) time_s = time.time() @@ -3276,16 +3274,16 @@ def doFullSyncUser(version=''): sock = getSocketFile() if is_exist_pv: - my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import + my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import my_import_cmd = "pv -t -p " + bak_file + '|' + my_import_cmd print(my_import_cmd) os.system(my_import_cmd) else: - my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import + ' < ' + bak_file + my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import + ' < ' + bak_file print(my_import_cmd) mw.execShell(my_import_cmd) - my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ + my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ ' ' + sync_db_import + ' < ' + bak_file mw.execShell(my_import_cmd) @@ -3420,7 +3418,7 @@ def doFullSyncSSH(version=''): root_dir = getServerDir() msock = root_dir + "/mysql.sock" mw.execShell("cd /tmp && gzip -d dump.sql.gz") - cmd = root_dir + "/bin/usr/bin/mysql -S " + msock + \ + cmd = root_dir + "/bin/mysql -S " + msock + \ " -uroot -p" + pwd + " < /tmp/dump.sql" print(cmd) diff --git a/plugins/mysql-apt/index_mysql_apt.py b/plugins/mysql-apt/index_mysql_apt.py index d252c1cea2..54414ce26f 100644 --- a/plugins/mysql-apt/index_mysql_apt.py +++ b/plugins/mysql-apt/index_mysql_apt.py @@ -15,11 +15,11 @@ import core.mw as mw -if mw.isAppleSystem(): - cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\'' - info = mw.execShell(cmd) - p = "/usr/local/lib/" + info[0].strip() + "/site-packages" - sys.path.append(p) +# if mw.isAppleSystem(): +# cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\'' +# info = mw.execShell(cmd) +# p = "/usr/local/lib/" + info[0].strip() + "/site-packages" +# sys.path.append(p) app_debug = False diff --git a/plugins/mysql-apt/versions/8.4/install_generic.sh b/plugins/mysql-apt/versions/8.4/install_generic.sh index 7812c18713..4790c85bda 100755 --- a/plugins/mysql-apt/versions/8.4/install_generic.sh +++ b/plugins/mysql-apt/versions/8.4/install_generic.sh @@ -27,6 +27,12 @@ if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then fi +# /lib/systemd/system/mysql.service +# /etc/mysql/my.cnf + +APT_INSTALL() +{ + ARCH="amd64" TMP_ARCH=`arch` if [ "$TMP_ARCH" == "x86_64" ];then @@ -44,32 +50,25 @@ fi MYSQL_VER=8.4.2 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28_${TMP_ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${TMP_ARCH} -APT_INSTALL() -{ ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld +mkdir -p $serverPath/mysql-apt # Linux - Generic # https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz -wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz +fi if [ -d ${myDir} ];then - cd ${myDir} && tar zvxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt fi # 测试时可关闭 -rm -rf $myDir +rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } From 6385d49eeb9b3b28737e93d504c92b6b62809604 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:00:49 +0800 Subject: [PATCH 05/40] Update install_generic.sh --- plugins/mysql-apt/versions/8.4/install_generic.sh | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/plugins/mysql-apt/versions/8.4/install_generic.sh b/plugins/mysql-apt/versions/8.4/install_generic.sh index 4790c85bda..1370fe8854 100755 --- a/plugins/mysql-apt/versions/8.4/install_generic.sh +++ b/plugins/mysql-apt/versions/8.4/install_generic.sh @@ -15,21 +15,8 @@ sysName=`uname` myDir=${serverPath}/source/mysql-apt -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 - -if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then - VERSION_ID="12" -fi - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - APT_INSTALL() { From 698cf0d2638a099a6611c709b672e236e45238db Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:03:45 +0800 Subject: [PATCH 06/40] update --- .../mysql-apt/versions/9.0/install_generic.sh | 106 +++++++++++++++++ .../mysql-apt/versions/9.1/install_generic.sh | 107 ++++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100755 plugins/mysql-apt/versions/9.0/install_generic.sh create mode 100755 plugins/mysql-apt/versions/9.1/install_generic.sh diff --git a/plugins/mysql-apt/versions/9.0/install_generic.sh b/plugins/mysql-apt/versions/9.0/install_generic.sh new file mode 100755 index 0000000000..c3ea97b92f --- /dev/null +++ b/plugins/mysql-apt/versions/9.0/install_generic.sh @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.0 +APT_INSTALL() +{ + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=9.0.1 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${TMP_ARCH} + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +# https://cdn.mysql.com/archives/mysql-9.0/mysql-9.0.1-linux-glibc2.28-x86_64.tar.xz +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-9.0/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '9.0' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '9.0' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-apt/versions/9.1/install_generic.sh b/plugins/mysql-apt/versions/9.1/install_generic.sh new file mode 100755 index 0000000000..1370fe8854 --- /dev/null +++ b/plugins/mysql-apt/versions/9.1/install_generic.sh @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 +APT_INSTALL() +{ + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=8.4.2 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${TMP_ARCH} + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +# https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.4' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.4' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi From 8b8a63c35273bb3de79eea721faf2bbac7ecb55f Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:04:50 +0800 Subject: [PATCH 07/40] update --- plugins/mysql-apt/init.d/mysql5.7.service.tpl | 3 +-- plugins/mysql-apt/init.d/mysql8.0.service.tpl | 2 +- plugins/mysql-apt/init.d/mysql8.1.service.tpl | 2 +- plugins/mysql-apt/init.d/mysql8.2.service.tpl | 2 +- plugins/mysql-apt/init.d/mysql8.3.service.tpl | 2 +- plugins/mysql-apt/init.d/mysql9.0.service.tpl | 2 +- plugins/mysql-apt/init.d/mysql9.1.service.tpl | 2 +- 7 files changed, 7 insertions(+), 8 deletions(-) diff --git a/plugins/mysql-apt/init.d/mysql5.7.service.tpl b/plugins/mysql-apt/init.d/mysql5.7.service.tpl index e9c46ad414..bd43bd9d51 100644 --- a/plugins/mysql-apt/init.d/mysql5.7.service.tpl +++ b/plugins/mysql-apt/init.d/mysql5.7.service.tpl @@ -31,8 +31,7 @@ User=mysql Group=mysql Type=simple PermissionsStartOnly=true -#ExecStartPre={$SERVER_PATH}/mysql-apt/bin/usr/share/mysql/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 5000 Restart=on-failure diff --git a/plugins/mysql-apt/init.d/mysql8.0.service.tpl b/plugins/mysql-apt/init.d/mysql8.0.service.tpl index 8dacece560..e9eb04dbe2 100644 --- a/plugins/mysql-apt/init.d/mysql8.0.service.tpl +++ b/plugins/mysql-apt/init.d/mysql8.0.service.tpl @@ -36,7 +36,7 @@ User=mysql Group=mysql Type=notify #ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 10000 Restart=on-failure diff --git a/plugins/mysql-apt/init.d/mysql8.1.service.tpl b/plugins/mysql-apt/init.d/mysql8.1.service.tpl index 8dacece560..e9eb04dbe2 100644 --- a/plugins/mysql-apt/init.d/mysql8.1.service.tpl +++ b/plugins/mysql-apt/init.d/mysql8.1.service.tpl @@ -36,7 +36,7 @@ User=mysql Group=mysql Type=notify #ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 10000 Restart=on-failure diff --git a/plugins/mysql-apt/init.d/mysql8.2.service.tpl b/plugins/mysql-apt/init.d/mysql8.2.service.tpl index 8dacece560..e9eb04dbe2 100644 --- a/plugins/mysql-apt/init.d/mysql8.2.service.tpl +++ b/plugins/mysql-apt/init.d/mysql8.2.service.tpl @@ -36,7 +36,7 @@ User=mysql Group=mysql Type=notify #ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 10000 Restart=on-failure diff --git a/plugins/mysql-apt/init.d/mysql8.3.service.tpl b/plugins/mysql-apt/init.d/mysql8.3.service.tpl index 8dacece560..e9eb04dbe2 100644 --- a/plugins/mysql-apt/init.d/mysql8.3.service.tpl +++ b/plugins/mysql-apt/init.d/mysql8.3.service.tpl @@ -36,7 +36,7 @@ User=mysql Group=mysql Type=notify #ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 10000 Restart=on-failure diff --git a/plugins/mysql-apt/init.d/mysql9.0.service.tpl b/plugins/mysql-apt/init.d/mysql9.0.service.tpl index a0a8924936..8c4e39fdc2 100644 --- a/plugins/mysql-apt/init.d/mysql9.0.service.tpl +++ b/plugins/mysql-apt/init.d/mysql9.0.service.tpl @@ -35,7 +35,7 @@ WantedBy=multi-user.target User=mysql Group=mysql Type=notify -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 10000 Restart=on-failure diff --git a/plugins/mysql-apt/init.d/mysql9.1.service.tpl b/plugins/mysql-apt/init.d/mysql9.1.service.tpl index a0a8924936..8c4e39fdc2 100644 --- a/plugins/mysql-apt/init.d/mysql9.1.service.tpl +++ b/plugins/mysql-apt/init.d/mysql9.1.service.tpl @@ -35,7 +35,7 @@ WantedBy=multi-user.target User=mysql Group=mysql Type=notify -ExecStart={$SERVER_PATH}/mysql-apt/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf +ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf TimeoutSec=600 LimitNOFILE = 10000 Restart=on-failure From 16db84793d697b91af3d52d57936958a522b82e6 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:15:27 +0800 Subject: [PATCH 08/40] update --- plugins/mysql-apt/install.sh | 10 +-- .../mysql-apt/versions/5.7/install_generic.sh | 90 +++++++++++++++++++ plugins/mysql-apt/versions/8.0/install.sh | 2 +- .../mysql-apt/versions/8.0/install_generic.sh | 90 +++++++++++++++++++ .../mysql-apt/versions/8.2/install_generic.sh | 90 +++++++++++++++++++ .../mysql-apt/versions/8.3/install_generic.sh | 90 +++++++++++++++++++ .../mysql-apt/versions/8.4/install_generic.sh | 24 ++--- .../mysql-apt/versions/9.0/install_generic.sh | 26 ++---- .../mysql-apt/versions/9.1/install_generic.sh | 32 ++----- 9 files changed, 383 insertions(+), 71 deletions(-) create mode 100755 plugins/mysql-apt/versions/5.7/install_generic.sh create mode 100755 plugins/mysql-apt/versions/8.0/install_generic.sh create mode 100755 plugins/mysql-apt/versions/8.2/install_generic.sh create mode 100755 plugins/mysql-apt/versions/8.3/install_generic.sh diff --git a/plugins/mysql-apt/install.sh b/plugins/mysql-apt/install.sh index 701a0866e0..0bd1fd3b12 100755 --- a/plugins/mysql-apt/install.sh +++ b/plugins/mysql-apt/install.sh @@ -7,8 +7,10 @@ rootPath=$(dirname "$curPath") rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") +# https://dev.mysql.com/downloads/mysql/ # https://downloads.mysql.com/archives/community/ + # /www/server/mysql-apt/bin/usr/sbin/mysqld --basedir=/www/server/mysql-apt/bin/usr --datadir=/www/server/mysql-apt/data --initialize-insecure --explicit_defaults_for_timestamp @@ -18,8 +20,6 @@ serverPath=$(dirname "$rootPath") # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py fix_db_access # cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql/index.py do_full_sync {"db":"xxx","sign":"","begin":1} - - action=$1 type=$2 @@ -58,11 +58,7 @@ if [ "${action}" == "uninstall" ];then fi -if [ "$2" == "8.4" ];then - sh -x $curPath/versions/$2/install_generic.sh $1 -else - sh -x $curPath/versions/$2/install.sh $1 -fi +sh -x $curPath/versions/$2/install_generic.sh $1 if [ "${action}" == "install" ];then #初始化 diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh new file mode 100755 index 0000000000..583790c493 --- /dev/null +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=5.7.39 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '5.7' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '5.7' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-apt/versions/8.0/install.sh b/plugins/mysql-apt/versions/8.0/install.sh index 75ab8ab167..082460a6e7 100755 --- a/plugins/mysql-apt/versions/8.0/install.sh +++ b/plugins/mysql-apt/versions/8.0/install.sh @@ -45,7 +45,7 @@ if [ "$ARCH" != "amd64" ];then fi -MYSQL_VER=8.0.36 +MYSQL_VER=8.0.39 SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} diff --git a/plugins/mysql-apt/versions/8.0/install_generic.sh b/plugins/mysql-apt/versions/8.0/install_generic.sh new file mode 100755 index 0000000000..5a080cd694 --- /dev/null +++ b/plugins/mysql-apt/versions/8.0/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=8.0.39 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.0 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.0/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.0' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.0' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-apt/versions/8.2/install_generic.sh b/plugins/mysql-apt/versions/8.2/install_generic.sh new file mode 100755 index 0000000000..769c583981 --- /dev/null +++ b/plugins/mysql-apt/versions/8.2/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=8.2.0 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.2 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.2 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.2/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.2' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.2' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-apt/versions/8.3/install_generic.sh b/plugins/mysql-apt/versions/8.3/install_generic.sh new file mode 100755 index 0000000000..c451fbd36d --- /dev/null +++ b/plugins/mysql-apt/versions/8.3/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=8.3.0 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.3 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.3 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.3/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.3' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.3' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-apt/versions/8.4/install_generic.sh b/plugins/mysql-apt/versions/8.4/install_generic.sh index 1370fe8854..5932cb0fa3 100755 --- a/plugins/mysql-apt/versions/8.4/install_generic.sh +++ b/plugins/mysql-apt/versions/8.4/install_generic.sh @@ -15,29 +15,16 @@ sysName=`uname` myDir=${serverPath}/source/mysql-apt +OS_ARCH=`arch` +MYSQL_VER=8.4.2 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 APT_INSTALL() { -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.4.2 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${TMP_ARCH} ######## mkdir -p $myDir @@ -62,8 +49,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} APT_UNINSTALL() { ### -rm -rf $myDir -# apt remove -y mysql-server +rm -rf $myDir/mysql-${SUFFIX_NAME} ### } diff --git a/plugins/mysql-apt/versions/9.0/install_generic.sh b/plugins/mysql-apt/versions/9.0/install_generic.sh index c3ea97b92f..2a8cf58683 100755 --- a/plugins/mysql-apt/versions/9.0/install_generic.sh +++ b/plugins/mysql-apt/versions/9.0/install_generic.sh @@ -14,30 +14,15 @@ sysName=`uname` myDir=${serverPath}/source/mysql-apt +OS_ARCH=`arch` +MYSQL_VER=9.0.1 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.0 APT_INSTALL() { -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=9.0.1 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${TMP_ARCH} - ######## mkdir -p $myDir mkdir -p $serverPath/mysql-apt @@ -61,8 +46,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} APT_UNINSTALL() { ### -rm -rf $myDir -# apt remove -y mysql-server +rm -rf $myDir/mysql-${SUFFIX_NAME} ### } diff --git a/plugins/mysql-apt/versions/9.1/install_generic.sh b/plugins/mysql-apt/versions/9.1/install_generic.sh index 1370fe8854..582611d9e9 100755 --- a/plugins/mysql-apt/versions/9.1/install_generic.sh +++ b/plugins/mysql-apt/versions/9.1/install_generic.sh @@ -15,38 +15,24 @@ sysName=`uname` myDir=${serverPath}/source/mysql-apt +OS_ARCH=`arch` +MYSQL_VER=9.1.0 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 APT_INSTALL() { -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.4.2 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${TMP_ARCH} - ######## mkdir -p $myDir mkdir -p $serverPath/mysql-apt # Linux - Generic # https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz +# https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-mysql-${SUFFIX_NAME}.tar.xz if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-mysql-${SUFFIX_NAME}.tar.xz fi if [ -d ${myDir} ];then @@ -62,7 +48,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} APT_UNINSTALL() { ### -rm -rf $myDir +rm -rf $myDir/mysql-${SUFFIX_NAME} # apt remove -y mysql-server ### } @@ -79,10 +65,10 @@ Install_mysql() if [ "$?" == "0" ];then mkdir -p $serverPath/mysql-apt - echo '8.4' > $serverPath/mysql-apt/version.pl + echo '9.1' > $serverPath/mysql-apt/version.pl echo '安装完成' else - echo '8.4' > $serverPath/mysql-apt/version.pl + echo '9.1' > $serverPath/mysql-apt/version.pl echo "暂时不支持该系统" fi } From 6d5c3e81c837787407db321dbe46c3a9da78e3a2 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:17:48 +0800 Subject: [PATCH 09/40] Update install_generic.sh --- plugins/mysql-apt/versions/5.7/install_generic.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh index 583790c493..be583f04b8 100755 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -16,7 +16,7 @@ sysName=`uname` myDir=${serverPath}/source/mysql-apt OS_ARCH=`arch` -MYSQL_VER=5.7.39 +MYSQL_VER=5.7.44 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 From 84035e0cb183d95dd6dfda8b6e6d8b3d2e4f8019 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:18:55 +0800 Subject: [PATCH 10/40] Update install_generic.sh --- plugins/mysql-apt/versions/5.7/install_generic.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh index be583f04b8..d527a4e4b7 100755 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -17,7 +17,7 @@ myDir=${serverPath}/source/mysql-apt OS_ARCH=`arch` MYSQL_VER=5.7.44 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.12-${OS_ARCH} # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 From f5b4af6e38a5a5973ef0b0568c9c19b956380d7a Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:20:32 +0800 Subject: [PATCH 11/40] Update install_generic.sh --- plugins/mysql-apt/versions/5.7/install_generic.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh index d527a4e4b7..227028890e 100755 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -19,6 +19,10 @@ OS_ARCH=`arch` MYSQL_VER=5.7.44 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.12-${OS_ARCH} +if [ "$OS_ARCH" != "x86_64" ];then + echo "暂时不支持该${OS_ARCH}" + exit 0 + # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 APT_INSTALL() From ae888e6d48007c603368a70b398f686a5222a720 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:22:16 +0800 Subject: [PATCH 12/40] Update install_generic.sh --- plugins/mysql-apt/versions/5.7/install_generic.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh index 227028890e..d456296061 100755 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -19,7 +19,9 @@ OS_ARCH=`arch` MYSQL_VER=5.7.44 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.12-${OS_ARCH} -if [ "$OS_ARCH" != "x86_64" ];then +if [ "$OS_ARCH" == "x86_64" ] || [ "$OS_ARCH" == "i686" ];then + echo "ok" +else echo "暂时不支持该${OS_ARCH}" exit 0 From 9f5844c4de7b9f527a22ffc1a363dde4be194a51 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:29:31 +0800 Subject: [PATCH 13/40] Update install_generic.sh --- plugins/mysql-apt/versions/5.7/install_generic.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh index d456296061..7719481473 100755 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -24,6 +24,7 @@ if [ "$OS_ARCH" == "x86_64" ] || [ "$OS_ARCH" == "i686" ];then else echo "暂时不支持该${OS_ARCH}" exit 0 +fi # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 # cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 From 5b11b35d5d78ee7273f5655979e9ef9ede068654 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:31:21 +0800 Subject: [PATCH 14/40] Update install_generic.sh --- plugins/mysql-apt/versions/5.7/install_generic.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh index 7719481473..298dabe66d 100755 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -36,12 +36,12 @@ mkdir -p $myDir mkdir -p $serverPath/mysql-apt # Linux - Generic -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.tar.xz +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.gz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.gz https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.tar.gz fi if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.gz cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt fi From 05278bdacb9603fc803ab7125601b7af4585a7e3 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:38:01 +0800 Subject: [PATCH 15/40] Update install_generic.sh --- plugins/mysql-apt/versions/5.7/install_generic.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh index 298dabe66d..cd2f003db8 100755 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ b/plugins/mysql-apt/versions/5.7/install_generic.sh @@ -41,7 +41,7 @@ if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.gz ];then fi if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.gz + cd ${myDir} && tar -zvxf ${myDir}/mysql-${SUFFIX_NAME}.tar.gz cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt fi From 208e418bba8384eb0754be7bc0cb2556523029b6 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 17:41:59 +0800 Subject: [PATCH 16/40] Update index_mysql_apt.py --- plugins/mysql-apt/index_mysql_apt.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/mysql-apt/index_mysql_apt.py b/plugins/mysql-apt/index_mysql_apt.py index 54414ce26f..5292151111 100644 --- a/plugins/mysql-apt/index_mysql_apt.py +++ b/plugins/mysql-apt/index_mysql_apt.py @@ -78,7 +78,7 @@ def binLogListLook(args): line = args['line'] data_dir = getDataDir() - my_bin = getServerDir() + '/bin/usr/bin' + my_bin = getServerDir() + '/bin' my_binlog_cmd = my_bin + '/mysqlbinlog' cmd = my_binlog_cmd + ' --no-defaults ' + \ @@ -99,7 +99,7 @@ def binLogListLookDecode(args): line = args['line'] data_dir = getDataDir() - my_bin = getServerDir() + '/bin/usr/bin' + my_bin = getServerDir() + '/bin' my_binlog_cmd = my_bin + '/mysqlbinlog' cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ @@ -137,7 +137,7 @@ def binLogListTraceRelay(args): file = relay_list[0] - my_bin = getServerDir() + '/bin/usr/bin' + my_bin = getServerDir() + '/bin' my_binlog_cmd = my_bin + '/mysqlbinlog' cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ @@ -175,7 +175,7 @@ def binLogListTraceBinLog(args): log_bin_l = sorted(log_bin_l, reverse=True) file = log_bin_l[0] - my_bin = getServerDir() + '/bin/usr/bin' + my_bin = getServerDir() + '/bin' my_binlog_cmd = my_bin + '/mysqlbinlog' cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ From 8c9bfd7e2de1b70437bba5162ed6021f1b81023b Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 18:03:18 +0800 Subject: [PATCH 17/40] update --- plugins/mysql-apt/install.sh | 2 +- plugins/mysql-apt/versions/9.1/install_generic.sh | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/plugins/mysql-apt/install.sh b/plugins/mysql-apt/install.sh index 0bd1fd3b12..f1c494d019 100755 --- a/plugins/mysql-apt/install.sh +++ b/plugins/mysql-apt/install.sh @@ -11,7 +11,7 @@ serverPath=$(dirname "$rootPath") # https://downloads.mysql.com/archives/community/ -# /www/server/mysql-apt/bin/usr/sbin/mysqld --basedir=/www/server/mysql-apt/bin/usr --datadir=/www/server/mysql-apt/data --initialize-insecure --explicit_defaults_for_timestamp +# /www/server/mysql-apt/bin/mysqld --basedir=/www/server/mysql-apt --datadir=/www/server/mysql-apt/data --initialize-insecure --explicit_defaults_for_timestamp # cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 diff --git a/plugins/mysql-apt/versions/9.1/install_generic.sh b/plugins/mysql-apt/versions/9.1/install_generic.sh index 582611d9e9..0c0ea4bb53 100755 --- a/plugins/mysql-apt/versions/9.1/install_generic.sh +++ b/plugins/mysql-apt/versions/9.1/install_generic.sh @@ -19,8 +19,8 @@ OS_ARCH=`arch` MYSQL_VER=9.1.0 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.1 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.1 APT_INSTALL() { @@ -30,9 +30,9 @@ mkdir -p $serverPath/mysql-apt # Linux - Generic # https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz -# https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-mysql-${SUFFIX_NAME}.tar.xz +# https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-${SUFFIX_NAME}.tar.xz if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-mysql-${SUFFIX_NAME}.tar.xz + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-${SUFFIX_NAME}.tar.xz fi if [ -d ${myDir} ];then From e45b9b410106d906e8fcdba50836fbe8fe2274cf Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 20:48:23 +0800 Subject: [PATCH 18/40] =?UTF-8?q?mysql=E6=9E=81=E9=80=9F=E5=8A=9E=E7=89=88?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugins/mysql-community/conf/classic.cnf | 0 plugins/mysql-community/conf/gtid.cnf | 4 + plugins/mysql-community/conf/my5.7.cnf | 110 + plugins/mysql-community/conf/my8.0.cnf | 103 + plugins/mysql-community/conf/my8.2.cnf | 103 + plugins/mysql-community/conf/my8.3.cnf | 103 + plugins/mysql-community/conf/my8.4.cnf | 103 + plugins/mysql-community/conf/my9.0.cnf | 103 + plugins/mysql-community/conf/my9.1.cnf | 103 + plugins/mysql-community/conf/mysql.sql | 58 + plugins/mysql-community/ico.png | Bin 0 -> 1135 bytes plugins/mysql-community/index.html | 59 + plugins/mysql-community/index.py | 3713 +++++++++++++++++ .../mysql-community/index_mysql_community.py | 189 + plugins/mysql-community/info.json | 19 + .../init.d/mysql5.7.service.tpl | 43 + .../init.d/mysql8.0.service.tpl | 50 + .../init.d/mysql8.1.service.tpl | 50 + .../init.d/mysql8.2.service.tpl | 50 + .../init.d/mysql8.3.service.tpl | 50 + .../init.d/mysql8.4.service.tpl | 49 + .../init.d/mysql9.0.service.tpl | 49 + .../init.d/mysql9.1.service.tpl | 49 + plugins/mysql-community/install.sh | 71 + plugins/mysql-community/js/mysql-community.js | 2968 +++++++++++++ plugins/mysql-community/scripts/backup.py | 116 + .../mysql-community/versions/5.7/install.sh | 132 + .../versions/5.7/install_generic.sh | 97 + .../mysql-community/versions/8.0/install.sh | 137 + .../versions/8.0/install_generic.sh | 90 + .../mysql-community/versions/8.2/install.sh | 137 + .../versions/8.2/install_generic.sh | 90 + .../mysql-community/versions/8.3/install.sh | 135 + .../versions/8.3/install_generic.sh | 90 + .../mysql-community/versions/8.4/install.sh | 137 + .../versions/8.4/install_generic.sh | 93 + .../mysql-community/versions/9.0/install.sh | 138 + .../versions/9.0/install_generic.sh | 90 + .../mysql-community/versions/9.1/install.sh | 144 + .../versions/9.1/install_generic.sh | 93 + 40 files changed, 9918 insertions(+) create mode 100644 plugins/mysql-community/conf/classic.cnf create mode 100644 plugins/mysql-community/conf/gtid.cnf create mode 100644 plugins/mysql-community/conf/my5.7.cnf create mode 100644 plugins/mysql-community/conf/my8.0.cnf create mode 100644 plugins/mysql-community/conf/my8.2.cnf create mode 100644 plugins/mysql-community/conf/my8.3.cnf create mode 100644 plugins/mysql-community/conf/my8.4.cnf create mode 100644 plugins/mysql-community/conf/my9.0.cnf create mode 100644 plugins/mysql-community/conf/my9.1.cnf create mode 100755 plugins/mysql-community/conf/mysql.sql create mode 100644 plugins/mysql-community/ico.png create mode 100755 plugins/mysql-community/index.html create mode 100755 plugins/mysql-community/index.py create mode 100644 plugins/mysql-community/index_mysql_community.py create mode 100755 plugins/mysql-community/info.json create mode 100644 plugins/mysql-community/init.d/mysql5.7.service.tpl create mode 100644 plugins/mysql-community/init.d/mysql8.0.service.tpl create mode 100644 plugins/mysql-community/init.d/mysql8.1.service.tpl create mode 100644 plugins/mysql-community/init.d/mysql8.2.service.tpl create mode 100644 plugins/mysql-community/init.d/mysql8.3.service.tpl create mode 100644 plugins/mysql-community/init.d/mysql8.4.service.tpl create mode 100644 plugins/mysql-community/init.d/mysql9.0.service.tpl create mode 100644 plugins/mysql-community/init.d/mysql9.1.service.tpl create mode 100755 plugins/mysql-community/install.sh create mode 100755 plugins/mysql-community/js/mysql-community.js create mode 100755 plugins/mysql-community/scripts/backup.py create mode 100755 plugins/mysql-community/versions/5.7/install.sh create mode 100755 plugins/mysql-community/versions/5.7/install_generic.sh create mode 100755 plugins/mysql-community/versions/8.0/install.sh create mode 100755 plugins/mysql-community/versions/8.0/install_generic.sh create mode 100755 plugins/mysql-community/versions/8.2/install.sh create mode 100755 plugins/mysql-community/versions/8.2/install_generic.sh create mode 100755 plugins/mysql-community/versions/8.3/install.sh create mode 100755 plugins/mysql-community/versions/8.3/install_generic.sh create mode 100755 plugins/mysql-community/versions/8.4/install.sh create mode 100755 plugins/mysql-community/versions/8.4/install_generic.sh create mode 100755 plugins/mysql-community/versions/9.0/install.sh create mode 100755 plugins/mysql-community/versions/9.0/install_generic.sh create mode 100755 plugins/mysql-community/versions/9.1/install.sh create mode 100755 plugins/mysql-community/versions/9.1/install_generic.sh diff --git a/plugins/mysql-community/conf/classic.cnf b/plugins/mysql-community/conf/classic.cnf new file mode 100644 index 0000000000..e69de29bb2 diff --git a/plugins/mysql-community/conf/gtid.cnf b/plugins/mysql-community/conf/gtid.cnf new file mode 100644 index 0000000000..5076776a65 --- /dev/null +++ b/plugins/mysql-community/conf/gtid.cnf @@ -0,0 +1,4 @@ +[mysqld] +# SHOW GLOBAL VARIABLES LIKE '%gtid%' +gtid_mode=ON +enforce_gtid_consistency=ON \ No newline at end of file diff --git a/plugins/mysql-community/conf/my5.7.cnf b/plugins/mysql-community/conf/my5.7.cnf new file mode 100644 index 0000000000..d04b185ad8 --- /dev/null +++ b/plugins/mysql-community/conf/my5.7.cnf @@ -0,0 +1,110 @@ +[client] +user = root +#password = your_password +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +default-character-set = UTF8MB4 + +[mysqld] +!include {$SERVER_APP_PATH}/etc/mode/classic.cnf + +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +server-id = {$SERVER_ID} +sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES + +default_storage_engine = InnoDB +language={$SERVER_APP_PATH}/bin/usr/share/mysql/english + +key_buffer_size = 8M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=0 +character-set-server = UTF8MB4 + +query_cache_type = 1 +query_cache_size = 64M + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 2560 +max_allowed_packet = 128M + +skip_name_resolve = 1 +skip-ssl +#skip-networking +#skip-external-locking +#loose-skip-innodb +#skip-grant-tables + +log-bin=mysql-bin +binlog_format=mixed +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +expire_logs_days=30 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#sync_binlog=1 + +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log-slave-updates +#replicate-do-db +slave_skip_errors=1062,1396 +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +master_info_repository = table +relay_log_info_repository = table + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_log_file_size = 5M +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-community/conf/my8.0.cnf b/plugins/mysql-community/conf/my8.0.cnf new file mode 100644 index 0000000000..388b397eb7 --- /dev/null +++ b/plugins/mysql-community/conf/my8.0.cnf @@ -0,0 +1,103 @@ +[client] +user = root +#password = your_password +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +default-character-set = UTF8MB4 + +[mysqld] +!include {$SERVER_APP_PATH}/etc/mode/classic.cnf + +authentication_policy=mysql_native_password +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33206 +mysqlx_port = 33260 +socket = {$SERVER_APP_PATH}/mysql.sock +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +server-id = {$SERVER_ID} + +default_storage_engine = InnoDB + +key_buffer_size = 8M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=1 +tmp_table_size = 8M +character-set-server = UTF8MB4 + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 2560 +max_allowed_packet = 128M + +#skip-external-locking +#skip-grant-tables +#loose-skip-innodb +#skip-networking +#skip-name-resolve + +log-bin=mysql-bin +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#sync_binlog=1 + +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log_replica_updates +#replicate-do-db +replica_skip_errors=1062,1396 +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_redo_log_capacity=10485760 +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 +binlog_expire_logs_seconds=2592000 + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-community/conf/my8.2.cnf b/plugins/mysql-community/conf/my8.2.cnf new file mode 100644 index 0000000000..1b7ff7b943 --- /dev/null +++ b/plugins/mysql-community/conf/my8.2.cnf @@ -0,0 +1,103 @@ +[client] +user = root +#password = your_password +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +default-character-set = UTF8MB4 + +[mysqld] +!include {$SERVER_APP_PATH}/etc/mode/classic.cnf + +authentication_policy=caching_sha2_password +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33206 +mysqlx_port = 33260 +socket = {$SERVER_APP_PATH}/mysql.sock +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +server-id = {$SERVER_ID} + +default_storage_engine = InnoDB + +key_buffer_size = 8M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=1 +tmp_table_size = 8M +character-set-server = UTF8MB4 + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 2560 +max_allowed_packet = 128M + +#skip-external-locking +#skip-grant-tables +#loose-skip-innodb +#skip-networking +#skip-name-resolve + +log-bin=mysql-bin +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#sync_binlog=1 + +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log_replica_updates +#replicate-do-db +replica_skip_errors=1062,1396 +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_redo_log_capacity=10485760 +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 +binlog_expire_logs_seconds=2592000 + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-community/conf/my8.3.cnf b/plugins/mysql-community/conf/my8.3.cnf new file mode 100644 index 0000000000..1b7ff7b943 --- /dev/null +++ b/plugins/mysql-community/conf/my8.3.cnf @@ -0,0 +1,103 @@ +[client] +user = root +#password = your_password +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +default-character-set = UTF8MB4 + +[mysqld] +!include {$SERVER_APP_PATH}/etc/mode/classic.cnf + +authentication_policy=caching_sha2_password +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33206 +mysqlx_port = 33260 +socket = {$SERVER_APP_PATH}/mysql.sock +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +server-id = {$SERVER_ID} + +default_storage_engine = InnoDB + +key_buffer_size = 8M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=1 +tmp_table_size = 8M +character-set-server = UTF8MB4 + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 2560 +max_allowed_packet = 128M + +#skip-external-locking +#skip-grant-tables +#loose-skip-innodb +#skip-networking +#skip-name-resolve + +log-bin=mysql-bin +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#sync_binlog=1 + +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log_replica_updates +#replicate-do-db +replica_skip_errors=1062,1396 +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_redo_log_capacity=10485760 +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 +binlog_expire_logs_seconds=2592000 + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-community/conf/my8.4.cnf b/plugins/mysql-community/conf/my8.4.cnf new file mode 100644 index 0000000000..1b7ff7b943 --- /dev/null +++ b/plugins/mysql-community/conf/my8.4.cnf @@ -0,0 +1,103 @@ +[client] +user = root +#password = your_password +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +default-character-set = UTF8MB4 + +[mysqld] +!include {$SERVER_APP_PATH}/etc/mode/classic.cnf + +authentication_policy=caching_sha2_password +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33206 +mysqlx_port = 33260 +socket = {$SERVER_APP_PATH}/mysql.sock +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +server-id = {$SERVER_ID} + +default_storage_engine = InnoDB + +key_buffer_size = 8M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=1 +tmp_table_size = 8M +character-set-server = UTF8MB4 + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 2560 +max_allowed_packet = 128M + +#skip-external-locking +#skip-grant-tables +#loose-skip-innodb +#skip-networking +#skip-name-resolve + +log-bin=mysql-bin +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#sync_binlog=1 + +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log_replica_updates +#replicate-do-db +replica_skip_errors=1062,1396 +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_redo_log_capacity=10485760 +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 +binlog_expire_logs_seconds=2592000 + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-community/conf/my9.0.cnf b/plugins/mysql-community/conf/my9.0.cnf new file mode 100644 index 0000000000..1b7ff7b943 --- /dev/null +++ b/plugins/mysql-community/conf/my9.0.cnf @@ -0,0 +1,103 @@ +[client] +user = root +#password = your_password +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +default-character-set = UTF8MB4 + +[mysqld] +!include {$SERVER_APP_PATH}/etc/mode/classic.cnf + +authentication_policy=caching_sha2_password +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33206 +mysqlx_port = 33260 +socket = {$SERVER_APP_PATH}/mysql.sock +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +server-id = {$SERVER_ID} + +default_storage_engine = InnoDB + +key_buffer_size = 8M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=1 +tmp_table_size = 8M +character-set-server = UTF8MB4 + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 2560 +max_allowed_packet = 128M + +#skip-external-locking +#skip-grant-tables +#loose-skip-innodb +#skip-networking +#skip-name-resolve + +log-bin=mysql-bin +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#sync_binlog=1 + +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log_replica_updates +#replicate-do-db +replica_skip_errors=1062,1396 +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_redo_log_capacity=10485760 +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 +binlog_expire_logs_seconds=2592000 + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-community/conf/my9.1.cnf b/plugins/mysql-community/conf/my9.1.cnf new file mode 100644 index 0000000000..1b7ff7b943 --- /dev/null +++ b/plugins/mysql-community/conf/my9.1.cnf @@ -0,0 +1,103 @@ +[client] +user = root +#password = your_password +port = 33206 +socket = {$SERVER_APP_PATH}/mysql.sock +default-character-set = UTF8MB4 + +[mysqld] +!include {$SERVER_APP_PATH}/etc/mode/classic.cnf + +authentication_policy=caching_sha2_password +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33206 +mysqlx_port = 33260 +socket = {$SERVER_APP_PATH}/mysql.sock +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +server-id = {$SERVER_ID} + +default_storage_engine = InnoDB + +key_buffer_size = 8M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=1 +tmp_table_size = 8M +character-set-server = UTF8MB4 + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 2560 +max_allowed_packet = 128M + +#skip-external-locking +#skip-grant-tables +#loose-skip-innodb +#skip-networking +#skip-name-resolve + +log-bin=mysql-bin +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#sync_binlog=1 + +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log_replica_updates +#replicate-do-db +replica_skip_errors=1062,1396 +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_redo_log_capacity=10485760 +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 +binlog_expire_logs_seconds=2592000 + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-community/conf/mysql.sql b/plugins/mysql-community/conf/mysql.sql new file mode 100755 index 0000000000..f98ddf79b9 --- /dev/null +++ b/plugins/mysql-community/conf/mysql.sql @@ -0,0 +1,58 @@ +CREATE TABLE IF NOT EXISTS `config` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `mysql_root` TEXT +); + +INSERT INTO `config` (`id`, `mysql_root`) VALUES (1, 'admin'); + +CREATE TABLE IF NOT EXISTS `databases` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `pid` INTEGER, + `name` TEXT, + `username` TEXT, + `password` TEXT, + `accept` TEXT, + `rw` TEXT DEFAULT 'rw', + `ps` TEXT, + `addtime` TEXT +); +-- ALTER TABLE `databases` ADD COLUMN `rw` TEXT DEFAULT 'rw'; + +CREATE TABLE IF NOT EXISTS `master_replication_user` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `username` TEXT, + `password` TEXT, + `accept` TEXT, + `ps` TEXT, + `addtime` TEXT +); + +-- 从库配置主库的[ssh private key] +-- drop table `slave_id_rsa`; +CREATE TABLE IF NOT EXISTS `slave_id_rsa` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `ip` TEXT, + `port` TEXT, + `user` TEXT, + `db_user` TEXT, + `id_rsa` TEXT, + `ps` TEXT, + `addtime` TEXT +); + +-- 从库配置主库的[user] +-- drop table `slave_user`; +CREATE TABLE IF NOT EXISTS `slave_sync_user` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `ip` TEXT, + `port` TEXT, + `user` TEXT, + `pass` TEXT, + `mode` TEXT, + `cmd` TEXT, + `db` TEXT, + `addtime` TEXT +); +ALTER TABLE `slave_sync_user` ADD COLUMN `db` TEXT DEFAULT ''; + + diff --git a/plugins/mysql-community/ico.png b/plugins/mysql-community/ico.png new file mode 100644 index 0000000000000000000000000000000000000000..ead815fc20cc747780967ef2871b83c000e4f82d GIT binary patch literal 1135 zcmV-#1d#iQP)>{3lQ%rYE>EIo|Bc9O8-^_)1agG}q9>-P216(B zK}1dolB(O#w(T^gZ+;f7TTURgp@*LLi%EvgY=cZDhv*1Q%s|VgV~ETx1Bb!tAi=x$ zUWdVBccSOOP0TAdp?2kNQqbh`6_+AM=z=O#FWZiQgf#GjdIS}L4KI9; zf}sTnN>=9>ibj?}Z*{;EbY?5sx1YxBZ7&Kol9MINSyjpHnF1j5xR->al|lgp3yToqeV zi#1Puj`)fuTy=C78)}wr|E;r9Us(3QJIL;u;2qai|6mNCx)=S2ZoTRgD-Cf~i(61M zx(o`X3N_1iVCx${VeI@Pv@i2P$%IaC9>B`SKIRNTVJVXE z2#%m|zDZ4GHL+7*QfNoPf=^*t~;eZXN43`ND z7cv<&LC*S9H$H{xrQ7Jlg9?E+DPi*uMqb|xC2+^ia|lk(@-ihrD=Xzh`OJFMEZYt$ z$xJyfgDMjpD9034i#I2DjNYWkmE7JWBqSsxeg^A1@>H +
+
+
+ +

服务

+

自启动

+

配置文件

+

存储位置

+

端口

+

当前状态

+

性能优化

+

日志

+

慢日志

+

BINLOG

+

管理列表

+

主从配置

+
+
+
+
+
+ + + + + + \ No newline at end of file diff --git a/plugins/mysql-community/index.py b/plugins/mysql-community/index.py new file mode 100755 index 0000000000..79bd47afa4 --- /dev/null +++ b/plugins/mysql-community/index.py @@ -0,0 +1,3713 @@ +# coding=utf-8 + +import sys +import io +import os +import time +import subprocess +import re +import json + + +web_dir = os.getcwd() + "/web" +if os.path.exists(web_dir): + sys.path.append(web_dir) + os.chdir(web_dir) + +import core.mw as mw + +app_debug = False +if mw.isAppleSystem(): + app_debug = True + + +def getPluginName(): + return 'mysql-community' + + +def getPluginDir(): + return mw.getPluginDir() + '/' + getPluginName() + + +def getSPluginDir(): + return '/www/server/mdserver-web/plugins/' + getPluginName() + + +def getServerDir(): + return mw.getServerDir() + '/' + getPluginName() + + +def is_number(s): + try: + float(s) + return True + except ValueError: + pass + + try: + import unicodedata + unicodedata.numeric(s) + return True + except (TypeError, ValueError): + pass + + return False + + +def getArgs(): + args = sys.argv[2:] + tmp = {} + args_len = len(args) + if args_len == 1: + t = args[0].strip('{').strip('}') + if t.strip() == '': + tmp = [] + else: + t = t.split(':', 1) + tmp[t[0]] = t[1] + tmp[t[0]] = t[1] + elif args_len > 1: + for i in range(len(args)): + t = args[i].split(':', 1) + tmp[t[0]] = t[1] + return tmp + + +def getBackupDir(): + bk_path = mw.getBackupDir() + "/database/mysql-community" + if not os.path.isdir(bk_path): + mw.execShell("mkdir -p {}".format(bk_path)) + return bk_path + + +def checkArgs(data, ck=[]): + for i in range(len(ck)): + if not ck[i] in data: + return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!')) + return (True, mw.returnJson(True, 'ok')) + + +def getConf(): + path = getServerDir() + '/etc/my.cnf' + return path + + +def getDbPort(): + file = getConf() + content = mw.readFile(file) + rep = r'port\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + +def getDbServerId(): + file = getConf() + content = mw.readFile(file) + rep = r'server-id\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + +def getSocketFile(): + file = getConf() + content = mw.readFile(file) + rep = r'socket\s*=\s*(.*)' + tmp = re.search(rep, content) + + socket = tmp.groups()[0].strip() + return socket + + +def getErrorLogsFile(): + file = getConf() + content = mw.readFile(file) + rep = r'log-error\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + +def getAuthPolicy(): + file = getConf() + content = mw.readFile(file) + rep = r'authentication_policy\s*=\s*(.*)' + tmp = re.search(rep, content) + if tmp: + return tmp.groups()[0].strip() + # caching_sha2_password + return 'mysql_native_password' + +def contentReplace(content): + service_path = mw.getServerDir() + content = content.replace('{$ROOT_PATH}', mw.getFatherDir()) + content = content.replace('{$SERVER_PATH}', service_path) + content = content.replace('{$SERVER_APP_PATH}', + service_path + '/' + getPluginName()) + + server_id = int(time.time()) + content = content.replace('{$SERVER_ID}', str(server_id)) + + return content + + +def pSqliteDb(dbname='databases'): + file = getServerDir() + '/mysql.db' + name = 'mysql' + + import_sql = mw.readFile(getPluginDir() + '/conf/mysql.sql') + md5_sql = mw.md5(import_sql) + + import_sign = False + save_md5_file = getServerDir() + '/import_sql.md5' + if os.path.exists(save_md5_file): + save_md5_sql = mw.readFile(save_md5_file) + if save_md5_sql != md5_sql: + import_sign = True + mw.writeFile(save_md5_file, md5_sql) + else: + mw.writeFile(save_md5_file, md5_sql) + + if not os.path.exists(file) or import_sql: + conn = mw.M(dbname).dbPos(getServerDir(), name) + csql_list = import_sql.split(';') + for index in range(len(csql_list)): + conn.execute(csql_list[index], ()) + + conn = mw.M(dbname).dbPos(getServerDir(), name) + return conn + + +def pMysqlDb(): + # pymysql + db = mw.getMyORM() + # MySQLdb | + # db = mw.getMyORMDb() + + db.setPort(getDbPort()) + db.setSocket(getSocketFile()) + # db.setCharset("utf8") + db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')) + return db + + +def initDreplace(version=''): + + t = getServerDir() + if not os.path.exists(t): + return + + conf_dir = getServerDir() + '/etc' + mode_dir = conf_dir + '/mode' + + conf_list = [ + conf_dir, + mode_dir, + ] + for conf in conf_list: + if not os.path.exists(conf): + os.mkdir(conf) + + tmp_dir = getServerDir() + '/tmp' + if not os.path.exists(tmp_dir): + os.mkdir(tmp_dir) + mw.execShell("chown -R mysql:mysql " + tmp_dir) + mw.execShell("chmod 750 " + tmp_dir) + + my_conf = conf_dir + '/my.cnf' + if not os.path.exists(my_conf): + tpl = getPluginDir() + '/conf/my' + version + '.cnf' + content = mw.readFile(tpl) + content = contentReplace(content) + mw.writeFile(my_conf, content) + + classic_conf = mode_dir + '/classic.cnf' + if not os.path.exists(classic_conf): + tpl = getPluginDir() + '/conf/classic.cnf' + content = mw.readFile(tpl) + content = contentReplace(content) + mw.writeFile(classic_conf, content) + + gtid_conf = mode_dir + '/gtid.cnf' + if not os.path.exists(gtid_conf): + tpl = getPluginDir() + '/conf/gtid.cnf' + content = mw.readFile(tpl) + content = contentReplace(content) + mw.writeFile(gtid_conf, content) + + # systemd + systemDir = mw.systemdCfgDir() + systemService = systemDir + '/mysql-community.service' + systemServiceTpl = getPluginDir() + '/init.d/mysql' + version + '.service.tpl' + if os.path.exists(systemDir) and not os.path.exists(systemService): + service_path = mw.getServerDir() + content = mw.readFile(systemServiceTpl) + content = content.replace('{$SERVER_PATH}', service_path) + mw.writeFile(systemService, content) + mw.execShell('systemctl daemon-reload') + + if mw.getOs() != 'darwin': + mw.execShell('chown -R mysql mysql ' + getServerDir()) + return 'ok' + +def process_status(): + cmd = "ps -ef|grep mysql-community|grep mysql |grep -v grep | grep -v python | awk '{print $2}'" + data = mw.execShell(cmd) + if data[0] == '': + return 'stop' + return 'start' + +def status(version=''): + pid = getPidFile() + if not os.path.exists(pid): + return 'stop' + return 'start' + + +def getDataDir(): + file = getConf() + content = mw.readFile(file) + rep = r'datadir\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + +def getLogBinName(): + file = getConf() + content = mw.readFile(file) + rep = r'log-bin\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + +def getPidFile(): + file = getConf() + content = mw.readFile(file) + rep = r'pid-file\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + + +def binLog(version=''): + args = getArgs() + conf = getConf() + con = mw.readFile(conf) + + if con.find('#log-bin=mysql-bin') != -1: + if 'status' in args: + return mw.returnJson(False, '0') + con = con.replace('#log-bin=mysql-bin', 'log-bin=mysql-bin') + con = con.replace('#binlog_format=mixed', 'binlog_format=mixed') + mw.execShell('sync') + restart(version) + else: + path = getDataDir() + if 'status' in args: + dsize = 0 + for n in os.listdir(path): + if len(n) < 9: + continue + if n[0:9] == 'mysql-bin': + dsize += os.path.getsize(path + '/' + n) + return mw.returnJson(True, dsize) + con = con.replace('log-bin=mysql-bin', '#log-bin=mysql-bin') + con = con.replace('binlog_format=mixed', '#binlog_format=mixed') + mw.execShell('sync') + restart(version) + mw.execShell('rm -f ' + path + '/mysql-bin.*') + + mw.writeFile(conf, con) + return mw.returnJson(True, '设置成功!') + + +def setSkipGrantTables(v): + ''' + 设置是否密码验证 + ''' + conf = getConf() + con = mw.readFile(conf) + if v: + if con.find('#skip-grant-tables') != -1: + con = con.replace('#skip-grant-tables', 'skip-grant-tables') + else: + con = con.replace('skip-grant-tables', '#skip-grant-tables') + mw.writeFile(conf, con) + return True + +def binLogList(): + args = getArgs() + data = checkArgs(args, ['page', 'page_size', 'tojs']) + if not data[0]: + return data[1] + + page = int(args['page']) + page_size = int(args['page_size']) + + data_dir = getDataDir() + log_bin_name = getLogBinName() + + alist = os.listdir(data_dir) + log_bin_l = [] + for x in range(len(alist)): + f = alist[x] + t = {} + if f.startswith(log_bin_name) and not f.endswith('.index'): + abspath = data_dir + '/' + f + t['name'] = f + t['size'] = os.path.getsize(abspath) + t['time'] = mw.getDataFromInt(os.path.getctime(abspath)) + log_bin_l.append(t) + + log_bin_l = sorted(log_bin_l, key=lambda x: x['time'], reverse=True) + + # print(log_bin_l) + # print(data_dir, log_bin_name) + + count = len(log_bin_l) + + page_start = (page - 1) * page_size + page_end = page_start + page_size + if page_end > count: + page_end = count + + data = {} + page_args = {} + page_args['count'] = count + page_args['p'] = page + page_args['row'] = page_size + page_args['tojs'] = args['tojs'] + data['page'] = mw.getPage(page_args) + data['data'] = log_bin_l[page_start:page_end] + + return mw.getJson(data) + +def cleanBinLog(): + db = pMysqlDb() + cleanTime = time.strftime('%Y-%m-%d %H:%i:%s', time.localtime()) + db.execute("PURGE MASTER LOGS BEFORE '" + cleanTime + "';") + return mw.returnJson(True, '清理BINLOG成功!') + +def getErrorLog(): + args = getArgs() + filename = getErrorLogsFile() + if not os.path.exists(filename): + return mw.returnJson(False, '指定文件不存在!') + if 'close' in args: + mw.writeFile(filename, '') + return mw.returnJson(False, '日志已清空') + info = mw.getLastLine(filename, 18) + return mw.returnJson(True, 'OK', info) + + +def getShowLogFile(): + file = getConf() + content = mw.readFile(file) + rep = r'slow-query-log-file\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + +def getMdb8Ver(): + return ['8.0','8.1','8.2','8.3','8.4','9.0','9.1'] + +def pGetDbUser(): + if mw.isAppleSystem(): + user = mw.execShell("who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() + return user + return 'mysql' + + +def initMysql57Data(): + datadir = getDataDir() + if not os.path.exists(datadir + '/mysql'): + serverdir = getServerDir() + myconf = serverdir + "/etc/my.cnf" + user = pGetDbUser() + + cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + \ + datadir + ' --initialize-insecure --explicit_defaults_for_timestamp' + data = mw.execShell(cmd) + if data[1].lower().find('error') != -1: + exit("Init MySQL5.7 Data Error:"+data[1]) + + if not mw.isAppleSystem(): + mw.execShell('chown -R mysql:mysql ' + datadir) + mw.execShell('chmod -R 755 ' + datadir) + return False + return True + + +def initMysql8Data(): + ''' + chmod 644 /www/server/mysql-apt/etc/my.cnf + try: + mysqld --basedir=/usr --datadir=/www/server/mysql-apt/data --initialize-insecure + mysqld --defaults-file=/www/server/mysql-apt/etc/my.cnf --initialize-insecure + mysqld --initialize-insecure + select user, plugin from user; + update user set authentication_string=password("123123"),plugin='mysql_native_password' where user='root'; + ''' + datadir = getDataDir() + if not os.path.exists(datadir + '/mysql'): + serverdir = getServerDir() + user = pGetDbUser() + + cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + datadir + \ + ' --initialize-insecure --lower-case-table-names=1' + data = mw.execShell(cmd) + if data[1].lower().find('error') != -1: + exit("Init MySQL8+ Data Error:"+data[1]) + if data[1].lower().find('not found') != -1: + exit("Init MySQL8+ Data Error:"+data[1]) + + if not mw.isAppleSystem(): + mw.execShell('chown -R mysql:mysql ' + datadir) + mw.execShell('chmod -R 755 ' + datadir) + return False + return True + + +def initMysql8Pwd(): + ''' + /usr/bin/mysql --defaults-file=/www/server/mysql-apt/etc/my.cnf -uroot -e"UPDATE mysql.user SET password=PASSWORD('BhIroUczczNVaKvw') WHERE user='root';flush privileges;" + /usr/bin/mysql --defaults-file=/www/server/mysql-apt/etc/my.cnf -uroot -e"alter user 'root'@'localhost' identified by '123456';" + ''' + time.sleep(5) + + serverdir = getServerDir() + myconf = serverdir + "/etc/my.cnf" + pwd = mw.getRandomString(16) + + cmd_my = serverdir + '/bin/mysql' + + cmd_pass = cmd_my + ' --defaults-file=' + myconf + ' -uroot -e' + cmd_pass = cmd_pass + '"alter user \'root\'@\'localhost\' identified by \'' + pwd + '\';' + cmd_pass = cmd_pass + 'flush privileges;"' + # print(cmd_pass) + data = mw.execShell(cmd_pass) + # print(data) + + # 删除空账户 + drop_empty_user = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + \ + pwd + ' -e "use mysql;delete from user where USER=\'\'"' + mw.execShell(drop_empty_user) + + # 删除测试数据库 + drop_test_db = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + \ + pwd + ' -e "drop database test";' + mw.execShell(drop_test_db) + + pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) + + # 删除冗余账户 + hostname = mw.execShell('hostname')[0].strip() + if hostname != 'localhost': + drop_hostname = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + pwd + ' -e "drop user \'\'@\'' + hostname + '\'";' + mw.execShell(drop_hostname) + + drop_root_hostname = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + pwd + ' -e "drop user \'root\'@\'' + hostname + '\'";' + mw.execShell(drop_root_hostname) + + return True + + +def my8cmd(version, method): + initDreplace(version) + # mysql 8.0 and 5.7 + mdb8 = getMdb8Ver() + try: + isInited = True + if mw.inArray(mdb8, version): + isInited = initMysql8Data() + else: + isInited = initMysql57Data() + + if not isInited: + if not mw.isSupportSystemctl(): + cmd_init_start = init_file + ' start' + subprocess.Popen(cmd_init_start, stdout=subprocess.PIPE, shell=True, + bufsize=4096, stderr=subprocess.PIPE) + + time.sleep(6) + else: + mw.execShell('systemctl start '+getPluginName()) + + for x in range(10): + mydb_status = process_status() + if mydb_status == 'start': + initMysql8Pwd() + break + time.sleep(1) + + if not mw.isSupportSystemctl(): + cmd_init_stop = init_file + ' stop' + subprocess.Popen(cmd_init_stop, stdout=subprocess.PIPE, shell=True, + bufsize=4096, stderr=subprocess.PIPE) + time.sleep(3) + else: + mw.execShell('systemctl stop ' + getPluginName()) + + if not mw.isSupportSystemctl(): + sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, + bufsize=4096, stderr=subprocess.PIPE) + sub.wait(5) + else: + mw.execShell('systemctl ' + method + ' '+getPluginName()) + return 'ok' + except Exception as e: + return str(e) + + +def appCMD(version, action): + return my8cmd(version, action) + + +def start(version=''): + return appCMD(version, 'start') + + +def stop(version=''): + return appCMD(version, 'stop') + + +def restart(version=''): + return appCMD(version, 'restart') + + +def reload(version=''): + return appCMD(version, 'reload') + + +def initdStatus(): + if mw.isAppleSystem(): + return "Apple Computer does not support" + + shell_cmd = 'systemctl status ' + \ + getPluginName() + ' | grep loaded | grep "enabled;"' + data = mw.execShell(shell_cmd) + if data[0] == '': + return 'fail' + return 'ok' + + +def initdInstall(): + if mw.isAppleSystem(): + return "Apple Computer does not support" + + mw.execShell('systemctl enable ' + getPluginName()) + return 'ok' + + +def initdUinstall(): + if mw.isAppleSystem(): + return "Apple Computer does not support" + + mw.execShell('systemctl disable ' + getPluginName()) + return 'ok' + + +def getMyDbPos(): + file = getConf() + content = mw.readFile(file) + rep = r'datadir\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + + +def setMyDbPos(version=''): + args = getArgs() + data = checkArgs(args, ['datadir']) + if not data[0]: + return data[1] + + s_datadir = getMyDbPos() + t_datadir = args['datadir'] + if t_datadir == s_datadir: + return mw.returnJson(False, '与当前存储目录相同,无法迁移文件!') + + if not os.path.exists(t_datadir): + mw.execShell('mkdir -p ' + t_datadir) + + # mw.execShell('/etc/init.d/mysqld stop') + stop(version) + mw.execShell('cp -rf ' + s_datadir + '/* ' + t_datadir + '/') + mw.execShell('chown -R mysql mysql ' + t_datadir) + mw.execShell('chmod -R 755 ' + t_datadir) + mw.execShell('rm -f ' + t_datadir + '/*.pid') + mw.execShell('rm -f ' + t_datadir + '/*.err') + + path = getServerDir() + myfile = path + '/etc/my.cnf' + mycnf = mw.readFile(myfile) + mw.writeFile(path + '/etc/my_backup.cnf', mycnf) + + mycnf = mycnf.replace(s_datadir, t_datadir) + mw.writeFile(myfile, mycnf) + restart(version) + + result = mw.execShell('ps aux|grep mysqld| grep -v grep|grep -v python') + if len(result[0]) > 10: + mw.writeFile('data/datadir.pl', t_datadir) + return mw.returnJson(True, '存储目录迁移成功!') + else: + mw.execShell('pkill -9 mysqld') + mw.writeFile(myfile, mw.readFile(path + '/etc/my_backup.cnf')) + start() + return mw.returnJson(False, '文件迁移失败!') + + +def getMyPort(): + file = getConf() + content = mw.readFile(file) + rep = r'port\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + + +def setMyPort(): + args = getArgs() + data = checkArgs(args, ['port']) + if not data[0]: + return data[1] + + port = args['port'] + file = getConf() + content = mw.readFile(file) + rep = r"port\s*=\s*([0-9]+)\s*\n" + content = re.sub(rep, 'port = ' + port + '\n', content) + mw.writeFile(file, content) + restart() + return mw.returnJson(True, '编辑成功!') + + +def runInfo(version): + + if status(version) == 'stop': + return mw.returnJson(False, 'MySQL未启动', []) + + db = pMysqlDb() + data = db.query('show global status') + isError = isSqlError(data) + if isError != None: + return isError + + gets = ['Max_used_connections', 'Com_commit', 'Com_select', 'Com_rollback', 'Questions', 'Innodb_buffer_pool_reads', 'Innodb_buffer_pool_read_requests', 'Key_reads', 'Key_read_requests', 'Key_writes', + 'Key_write_requests', 'Qcache_hits', 'Qcache_inserts', 'Bytes_received', 'Bytes_sent', 'Aborted_clients', 'Aborted_connects', + 'Created_tmp_disk_tables', 'Created_tmp_tables', 'Innodb_buffer_pool_pages_dirty', 'Opened_files', 'Open_tables', 'Opened_tables', 'Select_full_join', + 'Select_range_check', 'Sort_merge_passes', 'Table_locks_waited', 'Threads_cached', 'Threads_connected', 'Threads_created', 'Threads_running', 'Connections', 'Uptime'] + + result = {} + # print(data) + for d in data: + vname = d["Variable_name"] + for g in gets: + if vname == g: + result[g] = d["Value"] + + # print(result, int(result['Uptime'])) + result['Run'] = int(time.time()) - int(result['Uptime']) + tmp = db.query('show master status') + try: + result['File'] = tmp[0]["File"] + result['Position'] = tmp[0]["Position"] + except: + result['File'] = 'OFF' + result['Position'] = 'OFF' + return mw.getJson(result) + + +def myDbStatus(version): + result = {} + db = pMysqlDb() + data = db.query('show variables') + isError = isSqlError(data) + if isError != None: + return isError + + gets = ['table_open_cache', 'thread_cache_size', 'key_buffer_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', + 'innodb_additional_mem_pool_size', 'innodb_log_buffer_size', 'max_connections', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] + + if version != "8.0": + gets.append('query_cache_size') + + result['mem'] = {} + for d in data: + vname = d['Variable_name'] + for g in gets: + # print(g) + if vname == g: + result['mem'][g] = d["Value"] + return mw.getJson(result) + + +def setDbStatus(version): + gets = ['key_buffer_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', 'innodb_log_buffer_size', 'max_connections', + 'table_open_cache', 'thread_cache_size', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] + + if version != "8.0": + # gets.append('query_cache_size') + gets = ['key_buffer_size', 'query_cache_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', 'innodb_log_buffer_size', 'max_connections', + 'table_open_cache', 'thread_cache_size', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] + + # print(gets) + emptys = ['max_connections', 'thread_cache_size', 'table_open_cache'] + args = getArgs() + conFile = getConf() + content = mw.readFile(conFile) + n = 0 + for g in gets: + s = 'M' + if n > 5: + s = 'K' + if g in emptys: + s = '' + rep = r'\s*' + g + r'\s*=\s*\d+(M|K|k|m|G)?\n' + c = g + ' = ' + args[g] + s + '\n' + if content.find(g) != -1: + content = re.sub(rep, '\n' + c, content, 1) + else: + content = content.replace('[mysqld]\n', '[mysqld]\n' + c) + n += 1 + mw.writeFile(conFile, content) + return mw.returnJson(True, '设置成功!') + + +def isSqlError(mysqlMsg): + # 检测数据库执行错误 + mysqlMsg = str(mysqlMsg) + if "MySQLdb" in mysqlMsg: + return mw.returnJson(False, 'err:' + str(mysqlMsg) + "\n" + 'MySQLdb组件缺失!
进入SSH命令行输入: pip install mysql-python | pip install mysqlclient==2.0.3') + if "2002," in mysqlMsg: + return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') + if "2003," in mysqlMsg: + return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)") + if "using password:" in mysqlMsg: + return mw.returnJson(False, '数据库密码错误,在管理列表-点击【修复】!') + if "1045," in mysqlMsg: + return mw.returnJson(False, '连接错误!') + if "SQL syntax" in mysqlMsg: + return mw.returnJson(False, 'SQL语法错误!') + if "Connection refused" in mysqlMsg: + return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') + if "1133," in mysqlMsg: + return mw.returnJson(False, '数据库用户不存在!') + if "1007," in mysqlMsg: + return mw.returnJson(False, '数据库已经存在!') + return None + + +def __createUser(dbname, username, password, address): + pdb = pMysqlDb() + + if username == 'root': + dbname = '*' + + pdb.execute( + "CREATE USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, password)) + pdb.execute( + "grant all privileges on %s.* to `%s`@`localhost`" % (dbname, username)) + for a in address.split(','): + pdb.execute( + "CREATE USER `%s`@`%s` IDENTIFIED BY '%s'" % (username, a, password)) + pdb.execute( + "grant all privileges on %s.* to `%s`@`%s`" % (dbname, username, a)) + pdb.execute("flush privileges") + + +def getDbBackupListFunc(dbname=''): + + bkDir = getBackupDir() + if not os.path.exists(bkDir): + os.mkdir(bkDir) + + blist = os.listdir(bkDir) + r = [] + + bname = 'db_' + dbname + blen = len(bname) + for x in blist: + fbstr = x[0:blen] + if fbstr == bname: + r.append(x) + return r + + +def setDbBackup(): + args = getArgs() + data = checkArgs(args, ['name']) + if not data[0]: + return data[1] + + scDir = getPluginDir() + '/scripts/backup.py' + cmd = 'python3 ' + scDir + ' database ' + args['name'] + ' 3' + os.system(cmd) + return mw.returnJson(True, 'ok') + + +def rootPwd(): + return pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + + +def importDbExternal(): + args = getArgs() + data = checkArgs(args, ['file', 'name']) + if not data[0]: + return data[1] + + file = args['file'] + name = args['name'] + + import_dir = mw.getBackupDir() + '/import/' + + file_path = import_dir + file + if not os.path.exists(file_path): + return mw.returnJson(False, '文件突然消失?') + + exts = ['sql', 'gz', 'zip'] + ext = mw.getFileSuffix(file) + if ext not in exts: + return mw.returnJson(False, '导入数据库格式不对!') + + tmp = file.split('/') + tmpFile = tmp[len(tmp) - 1] + tmpFile = tmpFile.replace('.sql.' + ext, '.sql') + tmpFile = tmpFile.replace('.' + ext, '.sql') + tmpFile = tmpFile.replace('tar.', '') + + # print(tmpFile) + import_sql = "" + if file.find("sql.gz") > -1: + cmd = 'cd ' + import_dir + ' && gzip -dc ' + \ + file + " > " + import_dir + tmpFile + info = mw.execShell(cmd) + if info[1] == "": + import_sql = import_dir + tmpFile + + if file.find(".zip") > -1: + cmd = 'cd ' + import_dir + ' && unzip -o ' + file + mw.execShell(cmd) + import_sql = import_dir + tmpFile + + if file.find("tar.gz") > -1: + cmd = 'cd ' + import_dir + ' && tar -zxvf ' + file + mw.execShell(cmd) + import_sql = import_dir + tmpFile + + if file.find(".sql") > -1 and file.find(".sql.gz") == -1: + import_sql = import_dir + file + + if import_sql == "": + return mw.returnJson(False, '未找SQL文件') + + pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + sock = getSocketFile() + + os.environ["MYSQL_PWD"] = pwd + mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + \ + pwd + ' ' + name + ' < ' + import_sql + + # print(mysql_cmd) + rdata = mw.execShell(mysql_cmd) + if ext != 'sql': + os.remove(import_sql) + + if rdata[1].lower().find('error') > -1: + return mw.returnJson(False, rdata[1]) + + return mw.returnJson(True, 'ok') + +def importDbExternalProgress(): + args = getArgs() + data = checkArgs(args, ['file', 'name']) + if not data[0]: + return data[1] + + file = args['file'] + name = args['name'] + + cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && ' + cmd += 'python3 '+mw.getServerDir()+'/mdserver-web/plugins/mysql-community/index.py import_db_external_progress_bar {"file":"'+file+'","name":"'+name+'"}' + return mw.returnJson(True, 'ok',cmd) + +def importDbExternalProgressBar(): + args = getArgs() + data = checkArgs(args, ['file', 'name']) + if not data[0]: + return data[1] + + file = args['file'] + name = args['name'] + + import_dir = mw.getFatherDir() + '/backup/import/' + + file_path = import_dir + file + if not os.path.exists(file_path): + return mw.returnJson(False, '文件突然消失?') + + exts = ['sql', 'gz', 'zip'] + ext = mw.getFileSuffix(file) + if ext not in exts: + return mw.returnJson(False, '导入数据库格式不对!') + + tmp = file.split('/') + tmpFile = tmp[len(tmp) - 1] + tmpFile = tmpFile.replace('.sql.' + ext, '.sql') + tmpFile = tmpFile.replace('.' + ext, '.sql') + tmpFile = tmpFile.replace('tar.', '') + + # print(tmpFile) + import_sql = "" + if file.find("sql.gz") > -1: + cmd = 'cd ' + import_dir + ' && gzip -dc ' + \ + file + " > " + import_dir + tmpFile + info = mw.execShell(cmd) + if info[1] == "": + import_sql = import_dir + tmpFile + + if file.find(".zip") > -1: + cmd = 'cd ' + import_dir + ' && unzip -o ' + file + mw.execShell(cmd) + import_sql = import_dir + tmpFile + + if file.find("tar.gz") > -1: + cmd = 'cd ' + import_dir + ' && tar -zxvf ' + file + mw.execShell(cmd) + import_sql = import_dir + tmpFile + + if file.find(".sql") > -1 and file.find(".sql.gz") == -1: + import_sql = import_dir + file + + if import_sql == "": + return mw.returnJson(False, '未找SQL文件') + + pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + sock = getSocketFile() + + # option = '' + # mode = recognizeDbMode() + # if mode == 'gtid': + # option = ' --set-gtid-purged=off ' + + my_cnf = getConf() + mysql_cmd = getServerDir() + '/bin/mysql --defaults-file=' + my_cnf + ' -uroot -p"' + pwd + '" -f ' + name + mysql_cmd_progress_bar = "pv -t -p " + import_sql + '|'+ mysql_cmd + print(mysql_cmd_progress_bar) + rdata = os.system(mysql_cmd_progress_bar) + return "" + +def importDbBackup(): + args = getArgs() + data = checkArgs(args, ['file', 'name']) + if not data[0]: + return data[1] + + file = args['file'] + name = args['name'] + + file_path = mw.getBackupDir() + '/database/' + file + file_path_sql = mw.getBackupDir() + '/database/' + file.replace('.gz', '') + + if not os.path.exists(file_path_sql): + cmd = 'cd ' + mw.getBackupDir() + '/database && gzip -d ' + file + mw.execShell(cmd) + + pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + sock = getSocketFile() + mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ + ' ' + name + ' < ' + file_path_sql + + # print(mysql_cmd) + # os.system(mysql_cmd) + + rdata = mw.execShell(mysql_cmd) + if rdata[1].lower().find('error') > -1: + return mw.returnJson(False, rdata[1]) + + return mw.returnJson(True, 'ok') + + +def deleteDbBackup(): + args = getArgs() + data = checkArgs(args, ['filename', 'path']) + if not data[0]: + return data[1] + + path = args['path'] + full_file = "" + bkDir = getBackupDir() + full_file = bkDir + '/' + args['filename'] + if path != "": + full_file = path + "/" + args['filename'] + os.remove(full_file) + return mw.returnJson(True, 'ok') + + +def getDbBackupList(): + args = getArgs() + data = checkArgs(args, ['name']) + if not data[0]: + return data[1] + + r = getDbBackupListFunc(args['name']) + bkDir = getBackupDir() + rr = [] + for x in range(0, len(r)): + p = bkDir + '/' + r[x] + data = {} + data['name'] = r[x] + + rsize = os.path.getsize(p) + data['size'] = mw.toSize(rsize) + + t = os.path.getctime(p) + t = time.localtime(t) + + data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t) + rr.append(data) + + data['file'] = p + + return mw.returnJson(True, 'ok', rr) + + +def getDbBackupImportList(): + bkImportDir = mw.getBackupDir() + '/import' + if not os.path.exists(bkImportDir): + os.mkdir(bkImportDir) + + blist = os.listdir(bkImportDir) + + rr = [] + for x in range(0, len(blist)): + name = blist[x] + p = bkImportDir + '/' + name + data = {} + data['name'] = name + + rsize = os.path.getsize(p) + data['size'] = mw.toSize(rsize) + + t = os.path.getctime(p) + t = time.localtime(t) + + data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t) + rr.append(data) + + data['file'] = p + + rdata = { + "list": rr, + "upload_dir": bkImportDir, + } + return mw.returnJson(True, 'ok', rdata) + + +def getDbList(): + args = getArgs() + page = 1 + page_size = 10 + search = '' + data = {} + if 'page' in args: + page = int(args['page']) + + if 'page_size' in args: + page_size = int(args['page_size']) + + if 'search' in args: + search = args['search'] + + conn = pSqliteDb('databases') + limit = str((page - 1) * page_size) + ',' + str(page_size) + condition = '' + if not search == '': + condition = "name like '%" + search + "%'" + field = 'id,pid,name,username,password,accept,rw,ps,addtime' + clist = conn.where(condition, ()).field( + field).limit(limit).order('id desc').select() + + for x in range(0, len(clist)): + dbname = clist[x]['name'] + blist = getDbBackupListFunc(dbname) + # print(blist) + clist[x]['is_backup'] = False + if len(blist) > 0: + clist[x]['is_backup'] = True + + count = conn.where(condition, ()).count() + _page = {} + _page['count'] = count + _page['p'] = page + _page['row'] = page_size + _page['tojs'] = 'dbList' + data['page'] = mw.getPage(_page) + data['data'] = clist + + info = {} + info['root_pwd'] = pSqliteDb('config').where( + 'id=?', (1,)).getField('mysql_root') + data['info'] = info + + return mw.getJson(data) + + +def syncGetDatabases(): + pdb = pMysqlDb() + psdb = pSqliteDb('databases') + data = pdb.query('show databases') + isError = isSqlError(data) + if isError != None: + return isError + users = pdb.query( + "select User,Host from mysql.user where User!='root' AND Host!='localhost' AND Host!=''") + nameArr = ['information_schema', 'performance_schema', 'mysql', 'sys'] + n = 0 + + # print(users) + for value in data: + vdb_name = value["Database"] + b = False + for key in nameArr: + if vdb_name == key: + b = True + break + if b: + continue + if psdb.where("name=?", (vdb_name,)).count() > 0: + continue + host = '127.0.0.1' + for user in users: + if vdb_name == user["User"]: + host = user["Host"] + break + + ps = mw.getMsg('INPUT_PS') + if vdb_name == 'test': + ps = mw.getMsg('DATABASE_TEST') + addTime = time.strftime('%Y-%m-%d %X', time.localtime()) + if psdb.add('name,username,password,accept,ps,addtime', (vdb_name, vdb_name, '', host, ps, addTime)): + n += 1 + + msg = mw.getInfo('本次共从服务器获取了{1}个数据库!', (str(n),)) + return mw.returnJson(True, msg) + + +def toDbBase(find): + pdb = pMysqlDb() + psdb = pSqliteDb('databases') + if len(find['password']) < 3: + find['username'] = find['name'] + find['password'] = mw.md5(str(time.time()) + find['name'])[0:10] + psdb.where("id=?", (find['id'],)).save( + 'password,username', (find['password'], find['username'])) + + result = pdb.execute("create database `" + find['name'] + "`") + if "using password:" in str(result): + return -1 + if "Connection refused" in str(result): + return -1 + + password = find['password'] + __createUser(find['name'], find['username'], password, find['accept']) + return 1 + + +def syncToDatabases(): + args = getArgs() + data = checkArgs(args, ['type', 'ids']) + if not data[0]: + return data[1] + + pdb = pMysqlDb() + result = pdb.execute("show databases") + isError = isSqlError(result) + if isError: + return isError + + stype = int(args['type']) + psdb = pSqliteDb('databases') + n = 0 + + if stype == 0: + data = psdb.field('id,name,username,password,accept').select() + for value in data: + result = toDbBase(value) + if result == 1: + n += 1 + else: + data = json.loads(args['ids']) + for value in data: + find = psdb.where("id=?", (value,)).field( + 'id,name,username,password,accept').find() + # print find + result = toDbBase(find) + if result == 1: + n += 1 + msg = mw.getInfo('本次共同步了{1}个数据库!', (str(n),)) + return mw.returnJson(True, msg) + + +def setRootPwd(version=''): + args = getArgs() + data = checkArgs(args, ['password']) + if not data[0]: + return data[1] + + #强制修改 + force = 0 + if 'force' in args and args['force'] == '1': + force = 1 + + password = args['password'] + try: + pdb = pMysqlDb() + result = pdb.query("show databases") + isError = isSqlError(result) + if isError != None: + if force == 1: + pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (password,)) + return mw.returnJson(True, '【强制修改】数据库root密码修改成功(不意为成功连接数据)!') + return isError + + if version.find('5.7') > -1 or version.find('8.0') > -1: + pdb.execute( + "UPDATE mysql.user SET authentication_string='' WHERE user='root'") + pdb.execute( + "ALTER USER 'root'@'localhost' IDENTIFIED BY '%s'" % password) + pdb.execute( + "ALTER USER 'root'@'127.0.0.1' IDENTIFIED BY '%s'" % password) + else: + result = pdb.execute( + "update mysql.user set Password=password('" + password + "') where User='root'") + pdb.execute("flush privileges") + pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (password,)) + + msg = '' + if force == 1: + msg = ',无须强制!' + return mw.returnJson(True, '数据库root密码修改成功!'+msg) + except Exception as ex: + return mw.returnJson(False, '修改错误:' + str(ex)) + +def setUserPwd(version=''): + args = getArgs() + data = checkArgs(args, ['password', 'name']) + if not data[0]: + return data[1] + + newpassword = args['password'] + username = args['name'] + uid = args['id'] + try: + pdb = pMysqlDb() + psdb = pSqliteDb('databases') + name = psdb.where('id=?', (uid,)).getField('name') + + if version.find('5.7') > -1 or version.find('8.0') > -1: + accept = pdb.query( + "select Host from mysql.user where User='" + name + "' AND Host!='localhost'") + t1 = pdb.execute( + "update mysql.user set authentication_string='' where User='" + username + "'") + # print(t1) + result = pdb.execute( + "ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, newpassword)) + # print(result) + for my_host in accept: + t2 = pdb.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ( + username, my_host["Host"], newpassword)) + # print(t2) + else: + result = pdb.execute("update mysql.user set Password=password('" + + newpassword + "') where User='" + username + "'") + + pdb.execute("flush privileges") + psdb.where("id=?", (uid,)).setField('password', newpassword) + return mw.returnJson(True, mw.getInfo('修改数据库[{1}]密码成功!', (name,))) + except Exception as ex: + return mw.returnJson(False, mw.getInfo('修改数据库[{1}]密码失败[{2}]!', (name, str(ex),))) + + +def setDbPs(): + args = getArgs() + data = checkArgs(args, ['id', 'name', 'ps']) + if not data[0]: + return data[1] + + ps = args['ps'] + sid = args['id'] + name = args['name'] + try: + psdb = pSqliteDb('databases') + psdb.where("id=?", (sid,)).setField('ps', ps) + return mw.returnJson(True, mw.getInfo('修改数据库[{1}]备注成功!', (name,))) + except Exception as e: + return mw.returnJson(True, mw.getInfo('修改数据库[{1}]备注失败!', (name,))) + + +def addDb(): + args = getArgs() + data = checkArgs(args, + ['password', 'name', 'codeing', 'db_user', 'dataAccess', 'ps']) + if not data[0]: + return data[1] + + if not 'address' in args: + address = '' + else: + address = args['address'].strip() + + dbname = args['name'].strip() + dbuser = args['db_user'].strip() + codeing = args['codeing'].strip() + password = args['password'].strip() + dataAccess = args['dataAccess'].strip() + ps = args['ps'].strip() + + reg = r"^[\w-]+$" + if not re.match(reg, args['name']): + return mw.returnJson(False, '数据库名称不能带有特殊符号!') + checks = ['root', 'mysql', 'test', 'sys', 'performance_schema','information_schema'] + if dbuser in checks or len(dbuser) < 1: + return mw.returnJson(False, '数据库用户名不合法!') + if dbname in checks or len(dbname) < 1: + return mw.returnJson(False, '数据库名称不合法!') + + if len(password) < 1: + password = mw.md5(time.time())[0:8] + + wheres = { + 'utf8': 'utf8_general_ci', + 'utf8mb4': 'utf8mb4_general_ci', + 'gbk': 'gbk_chinese_ci', + 'big5': 'big5_chinese_ci' + } + codeStr = wheres[codeing] + + pdb = pMysqlDb() + psdb = pSqliteDb('databases') + + if psdb.where("name=? or username=?", (dbname, dbuser)).count(): + return mw.returnJson(False, '数据库已存在!') + + result = pdb.execute("create database `" + dbname + + "` DEFAULT CHARACTER SET " + codeing + " COLLATE " + codeStr) + # print result + isError = isSqlError(result) + if isError != None: + return isError + + pdb.execute("drop user '" + dbuser + "'@'localhost'") + for a in address.split(','): + pdb.execute("drop user '" + dbuser + "'@'" + a + "'") + + __createUser(dbname, dbuser, password, address) + + addTime = time.strftime('%Y-%m-%d %X', time.localtime()) + psdb.add('pid,name,username,password,accept,ps,addtime', + (0, dbname, dbuser, password, address, ps, addTime)) + return mw.returnJson(True, '添加成功!') + + +def delDb(): + args = getArgs() + data = checkArgs(args, ['id', 'name']) + if not data[0]: + return data[1] + try: + sid = args['id'] + name = args['name'] + psdb = pSqliteDb('databases') + pdb = pMysqlDb() + find = psdb.where("id=?", (sid,)).field( + 'id,pid,name,username,password,accept,ps,addtime').find() + accept = find['accept'] + username = find['username'] + + # 删除MYSQL + result = pdb.execute("drop database `" + name + "`") + + users = pdb.query("select Host from mysql.user where User='" + + username + "' AND Host!='localhost'") + pdb.execute("drop user '" + username + "'@'localhost'") + for us in users: + pdb.execute("drop user '" + username + "'@'" + us["Host"] + "'") + pdb.execute("flush privileges") + + # 删除SQLITE + psdb.where("id=?", (sid,)).delete() + return mw.returnJson(True, '删除成功!') + except Exception as ex: + return mw.returnJson(False, '删除失败!' + str(ex)) + + +def getDbAccess(): + args = getArgs() + data = checkArgs(args, ['username']) + if not data[0]: + return data[1] + username = args['username'] + pdb = pMysqlDb() + + users = pdb.query("select Host from mysql.user where User='" + + username + "' AND Host!='localhost'") + + isError = isSqlError(users) + if isError != None: + return isError + + if len(users) < 1: + return mw.returnJson(True, "127.0.0.1") + accs = [] + for c in users: + accs.append(c["Host"]) + userStr = ','.join(accs) + return mw.returnJson(True, userStr) + + +def setDbAccess(): + args = getArgs() + data = checkArgs(args, ['username', 'access']) + if not data[0]: + return data[1] + name = args['username'] + access = args['access'] + pdb = pMysqlDb() + psdb = pSqliteDb('databases') + + dbname = psdb.where('username=?', (name,)).getField('name') + + if name == 'root': + password = pSqliteDb('config').where( + 'id=?', (1,)).getField('mysql_root') + else: + password = psdb.where("username=?", (name,)).getField('password') + + users = pdb.query("select Host from mysql.user where User='" + + name + "' AND Host!='localhost'") + + for us in users: + pdb.execute("drop user '" + name + "'@'" + us["Host"] + "'") + + __createUser(dbname, name, password, access) + + psdb.where('username=?', (name,)).save('accept,rw', (access, 'rw',)) + return mw.returnJson(True, '设置成功!') + + + +def openSkipGrantTables(): + mycnf = getConf() + content = mw.readFile(mycnf) + content = content.replace('#skip-grant-tables','skip-grant-tables') + mw.writeFile(mycnf, content) + return True + +def closeSkipGrantTables(): + mycnf = getConf() + content = mw.readFile(mycnf) + content = content.replace('skip-grant-tables','#skip-grant-tables') + mw.writeFile(mycnf, content) + return True + + +def resetDbRootPwd(version): + serverdir = getServerDir() + myconf = serverdir + "/etc/my.cnf" + pwd = mw.getRandomString(16) + + pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) + mdb8 = getMdb8Ver() + if not mw.inArray(mdb8, version): + cmd_pass = serverdir + '/bin/mysql --defaults-file=' + myconf + ' -uroot -e' + cmd_pass = cmd_pass + '"UPDATE mysql.user SET password=PASSWORD(\'' + pwd + "') WHERE user='root';" + cmd_pass = cmd_pass + 'flush privileges;"' + data = mw.execShell(cmd_pass) + # print(data) + else: + auth_policy = getAuthPolicy() + + reset_pwd = 'flush privileges;' + reset_pwd = reset_pwd + \ + "UPDATE mysql.user SET authentication_string='' WHERE user='root';" + reset_pwd = reset_pwd + "flush privileges;" + reset_pwd = reset_pwd + \ + "alter user 'root'@'localhost' IDENTIFIED by '" + pwd + "';" + reset_pwd = reset_pwd + \ + "alter user 'root'@'localhost' IDENTIFIED WITH "+auth_policy+" by '" + pwd + "';" + reset_pwd = reset_pwd + "flush privileges;" + + tmp_file = "/tmp/mysql_init_tmp.log" + mw.writeFile(tmp_file, reset_pwd) + cmd_pass = serverdir + '/bin/mysql --defaults-file=' + myconf + ' -uroot -proot < ' + tmp_file + + data = mw.execShell(cmd_pass) + # print(data) + os.remove(tmp_file) + return True + +def fixDbAccess2(version): + try: + pdb = pMysqlDb() + data = pdb.query('show databases') + isError = isSqlError(data) + if isError != None: + appCMD(version, 'stop') + mw.execShell("rm -rf " + getServerDir() + "/data") + appCMD(version, 'start') + return mw.returnJson(True, '修复成功!') + return mw.returnJson(True, '正常无需修复!') + except Exception as e: + return mw.returnJson(False, '修复失败请重试!') + +def fixDbAccess(version): + + pdb = pMysqlDb() + mdb_ddir = getDataDir() + if not os.path.exists(mdb_ddir): + return mw.returnJson(False, '数据目录不存在,尝试重启重建!') + + try: + data = pdb.query('show databases') + isError = isSqlError(data) + if isError != None: + + # 重置密码 + appCMD(version, 'stop') + openSkipGrantTables() + appCMD(version, 'start') + time.sleep(3) + resetDbRootPwd(version) + + appCMD(version, 'stop') + closeSkipGrantTables() + appCMD(version, 'start') + + return mw.returnJson(True, '修复成功!') + return mw.returnJson(True, '正常无需修复!') + except Exception as e: + return mw.returnJson(False, '修复失败请重试!') + + + +def setDbRw(version=''): + args = getArgs() + data = checkArgs(args, ['username', 'id', 'rw']) + if not data[0]: + return data[1] + + username = args['username'] + uid = args['id'] + rw = args['rw'] + + pdb = pMysqlDb() + psdb = pSqliteDb('databases') + dbname = psdb.where("id=?", (uid,)).getField('name') + users = pdb.query( + "select Host from mysql.user where User='" + username + "'") + + # show grants for demo@"127.0.0.1"; + for x in users: + # REVOKE ALL PRIVILEGES ON `imail`.* FROM 'imail'@'127.0.0.1'; + + sql = "REVOKE ALL PRIVILEGES ON `" + dbname + \ + "`.* FROM '" + username + "'@'" + x["Host"] + "';" + r = pdb.query(sql) + # print(sql, r) + + if rw == 'rw': + sql = "GRANT SELECT, INSERT, UPDATE, DELETE ON " + dbname + ".* TO " + \ + username + "@'" + x["Host"] + "'" + elif rw == 'r': + sql = "GRANT SELECT ON " + dbname + ".* TO " + \ + username + "@'" + x["Host"] + "'" + else: + sql = "GRANT all privileges ON " + dbname + ".* TO " + \ + username + "@'" + x["Host"] + "'" + pdb.execute(sql) + pdb.execute("flush privileges") + r = psdb.where("id=?", (uid,)).setField('rw', rw) + # print(r) + return mw.returnJson(True, '切换成功!') + + +def getDbInfo(): + args = getArgs() + data = checkArgs(args, ['name']) + if not data[0]: + return data[1] + + db_name = args['name'] + pdb = pMysqlDb() + # print 'show tables from `%s`' % db_name + tables = pdb.query('show tables from `%s`' % db_name) + + ret = {} + sql = "select sum(DATA_LENGTH)+sum(INDEX_LENGTH) as sum_size from information_schema.tables where table_schema='%s'" % db_name + data_sum = pdb.query(sql) + + data = 0 + if data_sum[0]['sum_size'] != None: + data = data_sum[0]['sum_size'] + + ret['data_size'] = mw.toSize(data) + ret['database'] = db_name + + ret3 = [] + table_key = "Tables_in_" + db_name + for i in tables: + tb_sql = "show table status from `%s` where name = '%s'" % (db_name, i[ + table_key]) + table = pdb.query(tb_sql) + + tmp = {} + tmp['type'] = table[0]["Engine"] + tmp['rows_count'] = table[0]["Rows"] + tmp['collation'] = table[0]["Collation"] + + data_size = 0 + if table[0]['Avg_row_length'] != None: + data_size = table[0]['Avg_row_length'] + + if table[0]['Data_length'] != None: + data_size = table[0]['Data_length'] + + tmp['data_byte'] = data_size + tmp['data_size'] = mw.toSize(data_size) + tmp['table_name'] = table[0]["Name"] + ret3.append(tmp) + + ret['tables'] = (ret3) + + return mw.getJson(ret) + + +def repairTable(): + args = getArgs() + data = checkArgs(args, ['db_name', 'tables']) + if not data[0]: + return data[1] + + db_name = args['db_name'] + tables = json.loads(args['tables']) + pdb = pMysqlDb() + mtable = pdb.query('show tables from `%s`' % db_name) + + ret = [] + key = "Tables_in_" + db_name + for i in mtable: + for tn in tables: + if tn == i[key]: + ret.append(tn) + + if len(ret) > 0: + for i in ret: + pdb.execute('REPAIR TABLE `%s`.`%s`' % (db_name, i)) + return mw.returnJson(True, "修复完成!") + return mw.returnJson(False, "修复失败!") + + +def optTable(): + args = getArgs() + data = checkArgs(args, ['db_name', 'tables']) + if not data[0]: + return data[1] + + db_name = args['db_name'] + tables = json.loads(args['tables']) + pdb = pMysqlDb() + mtable = pdb.query('show tables from `%s`' % db_name) + ret = [] + key = "Tables_in_" + db_name + for i in mtable: + for tn in tables: + if tn == i[key]: + ret.append(tn) + + if len(ret) > 0: + for i in ret: + pdb.execute('OPTIMIZE TABLE `%s`.`%s`' % (db_name, i)) + return mw.returnJson(True, "优化成功!") + return mw.returnJson(False, "优化失败或者已经优化过了!") + + +def alterTable(): + args = getArgs() + data = checkArgs(args, ['db_name', 'tables']) + if not data[0]: + return data[1] + + db_name = args['db_name'] + tables = json.loads(args['tables']) + table_type = args['table_type'] + pdb = pMysqlDb() + mtable = pdb.query('show tables from `%s`' % db_name) + + ret = [] + key = "Tables_in_" + db_name + for i in mtable: + for tn in tables: + if tn == i[key]: + ret.append(tn) + + if len(ret) > 0: + for i in ret: + pdb.execute('alter table `%s`.`%s` ENGINE=`%s`' % + (db_name, i, table_type)) + return mw.returnJson(True, "更改成功!") + return mw.returnJson(False, "更改失败!") + + +def getTotalStatistics(): + st = status() + data = {} + + isInstall = os.path.exists(getServerDir() + '/version.pl') + + if st == 'start' and isInstall: + data['status'] = True + data['count'] = pSqliteDb('databases').count() + data['ver'] = mw.readFile(getServerDir() + '/version.pl').strip() + return mw.returnJson(True, 'ok', data) + else: + data['status'] = False + data['count'] = 0 + return mw.returnJson(False, 'fail', data) + + +def recognizeDbMode(): + conf = getConf() + con = mw.readFile(conf) + rep = r"!include %s/(.*)?\.cnf" % (getServerDir() + "/etc/mode",) + mode = 'none' + try: + data = re.findall(rep, con, re.M) + mode = data[0] + except Exception as e: + pass + return mode + + +def getDbrunMode(version=''): + mode = recognizeDbMode() + return mw.returnJson(True, "ok", {'mode': mode}) + + +def setDbrunMode(version=''): + if version == '5.5': + return mw.returnJson(False, "不支持切换") + + args = getArgs() + data = checkArgs(args, ['mode', 'reload']) + if not data[0]: + return data[1] + + mode = args['mode'] + dbreload = args['reload'] + + if not mode in ['classic', 'gtid']: + return mw.returnJson(False, "mode的值无效:" + mode) + + origin_mode = recognizeDbMode() + path = getConf() + con = mw.readFile(path) + rep = r"!include %s/%s\.cnf" % (getServerDir() + "/etc/mode", origin_mode) + rep_after = "!include %s/%s.cnf" % (getServerDir() + "/etc/mode", mode) + con = re.sub(rep, rep_after, con) + mw.writeFile(path, con) + + if version == '5.6': + dbreload = 'yes' + else: + db = pMysqlDb() + # The value of @@GLOBAL.GTID_MODE can only be changed one step at a + # time: OFF <-> OFF_PERMISSIVE <-> ON_PERMISSIVE <-> ON. Also note that + # this value must be stepped up or down simultaneously on all servers. + # See the Manual for instructions. + if mode == 'classic': + db.query('set global enforce_gtid_consistency=off') + db.query('set global gtid_mode=on') + db.query('set global gtid_mode=on_permissive') + db.query('set global gtid_mode=off_permissive') + db.query('set global gtid_mode=off') + elif mode == 'gtid': + db.query('set global enforce_gtid_consistency=on') + db.query('set global gtid_mode=off') + db.query('set global gtid_mode=off_permissive') + db.query('set global gtid_mode=on_permissive') + db.query('set global gtid_mode=on') + + if dbreload == "yes": + restart(version) + + return mw.returnJson(True, "切换成功!") + + +def findBinlogDoDb(): + conf = getConf() + con = mw.readFile(conf) + rep = r"binlog-do-db\s*?=\s*?(.*)" + dodb = re.findall(rep, con, re.M) + return dodb + + +def findBinlogSlaveDoDb(): + conf = getConf() + con = mw.readFile(conf) + rep = r"replicate-do-db\s*?=\s*?(.*)" + dodb = re.findall(rep, con, re.M) + return dodb + + +def setDbMasterAccess(): + args = getArgs() + data = checkArgs(args, ['username', 'access']) + if not data[0]: + return data[1] + username = args['username'] + access = args['access'] + pdb = pMysqlDb() + psdb = pSqliteDb('master_replication_user') + password = psdb.where("username=?", (username,)).getField('password') + users = pdb.query("select Host from mysql.user where User='" + + username + "' AND Host!='localhost'") + for us in users: + pdb.execute("drop user '" + username + "'@'" + us["Host"] + "'") + + dbname = '*' + for a in access.split(','): + pdb.execute( + "CREATE USER `%s`@`%s` IDENTIFIED BY '%s'" % (username, a, password)) + pdb.execute( + "grant all privileges on %s.* to `%s`@`%s`" % (dbname, username, a)) + + pdb.execute("flush privileges") + psdb.where('username=?', (username,)).save('accept', (access,)) + return mw.returnJson(True, '设置成功!') + + +def resetMaster(version=''): + pdb = pMysqlDb() + r = pdb.execute('reset master') + isError = isSqlError(r) + if isError != None: + return isError + return mw.returnJson(True, '重置成功!') + + +def getMasterDbList(version=''): + try: + args = getArgs() + page = 1 + page_size = 10 + search = '' + data = {} + if 'page' in args: + page = int(args['page']) + + if 'page_size' in args: + page_size = int(args['page_size']) + + if 'search' in args: + search = args['search'] + + conn = pSqliteDb('databases') + limit = str((page - 1) * page_size) + ',' + str(page_size) + condition = '' + dodb = findBinlogDoDb() + data['dodb'] = dodb + + slave_dodb = findBinlogSlaveDoDb() + + if not search == '': + condition = "name like '%" + search + "%'" + field = 'id,pid,name,username,password,accept,ps,addtime' + clist = conn.where(condition, ()).field( + field).limit(limit).order('id desc').select() + count = conn.where(condition, ()).count() + + for x in range(0, len(clist)): + if clist[x]['name'] in dodb: + clist[x]['master'] = 1 + else: + clist[x]['master'] = 0 + + if clist[x]['name'] in slave_dodb: + clist[x]['slave'] = 1 + else: + clist[x]['slave'] = 0 + + _page = {} + _page['count'] = count + _page['p'] = page + _page['row'] = page_size + _page['tojs'] = 'dbList' + data['page'] = mw.getPage(_page) + data['data'] = clist + return mw.getJson(data) + except Exception as e: + return mw.returnJson(False, "数据库密码错误,在管理列表-点击【修复】!") + + +def setDbMaster(version): + args = getArgs() + data = checkArgs(args, ['name']) + if not data[0]: + return data[1] + + conf = getConf() + con = mw.readFile(conf) + rep = r"(binlog-do-db\s*?=\s*?(.*))" + dodb = re.findall(rep, con, re.M) + + isHas = False + for x in range(0, len(dodb)): + + if dodb[x][1] == args['name']: + isHas = True + + con = con.replace(dodb[x][0] + "\n", '') + mw.writeFile(conf, con) + + if not isHas: + prefix = '#binlog-do-db' + con = con.replace( + prefix, prefix + "\nbinlog-do-db=" + args['name']) + mw.writeFile(conf, con) + + restart(version) + time.sleep(4) + return mw.returnJson(True, '设置成功', [args, dodb]) + + +def setDbSlave(version): + args = getArgs() + data = checkArgs(args, ['name']) + if not data[0]: + return data[1] + + conf = getConf() + con = mw.readFile(conf) + rep = r"(replicate-do-db\s*?=\s*?(.*))" + dodb = re.findall(rep, con, re.M) + + isHas = False + for x in range(0, len(dodb)): + if dodb[x][1] == args['name']: + isHas = True + + con = con.replace(dodb[x][0] + "\n", '') + mw.writeFile(conf, con) + + if not isHas: + prefix = '#replicate-do-db' + con = con.replace( + prefix, prefix + "\nreplicate-do-db=" + args['name']) + mw.writeFile(conf, con) + + restart(version) + time.sleep(4) + return mw.returnJson(True, '设置成功', [args, dodb]) + + +def getMasterStatus(version=''): + + if status(version) == 'stop': + return mw.returnJson(False, 'MySQL未启动,或正在启动中...!', []) + + query_status_cmd = 'show slave status' + mdb8 = getMdb8Ver() + is_mdb8 = False + if mw.inArray(mdb8, version): + is_mdb8 = True + query_status_cmd = 'show replica status' + + try: + conf = getConf() + content = mw.readFile(conf) + master_status = False + if content.find('#log-bin') == -1 and content.find('log-bin') > 1: + dodb = findBinlogDoDb() + if len(dodb) > 0: + master_status = True + + data = {} + data['mode'] = recognizeDbMode() + data['status'] = master_status + + db = pMysqlDb() + dlist = db.query(query_status_cmd) + + # print(dlist[0]) + if is_mdb8: + if len(dlist) > 0 and (dlist[0]["Replica_IO_Running"] == 'Yes' or dlist[0]["Replica_SQL_Running"] == 'Yes'): + data['slave_status'] = True + else: + if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'): + data['slave_status'] = True + + return mw.returnJson(master_status, '设置成功', data) + except Exception as e: + return mw.returnJson(False, "数据库密码错误,在管理列表-点击【修复】!", 'pwd') + + +def setMasterStatus(version=''): + + conf = getConf() + con = mw.readFile(conf) + + if con.find('#log-bin') != -1: + return mw.returnJson(False, '必须开启二进制日志') + + sign = 'mdserver_ms_open' + + dodb = findBinlogDoDb() + if not sign in dodb: + prefix = '#binlog-do-db' + con = con.replace(prefix, prefix + "\nbinlog-do-db=" + sign) + mw.writeFile(conf, con) + else: + con = con.replace("binlog-do-db=" + sign + "\n", '') + rep = r"(binlog-do-db\s*?=\s*?(.*))" + dodb = re.findall(rep, con, re.M) + for x in range(0, len(dodb)): + con = con.replace(dodb[x][0] + "\n", '') + mw.writeFile(conf, con) + + restart(version) + return mw.returnJson(True, '设置成功') + + +def getMasterRepSlaveList(version=''): + args = getArgs() + page = 1 + page_size = 10 + search = '' + data = {} + if 'page' in args: + page = int(args['page']) + + if 'page_size' in args: + page_size = int(args['page_size']) + + if 'search' in args: + search = args['search'] + + conn = pSqliteDb('master_replication_user') + limit = str((page - 1) * page_size) + ',' + str(page_size) + condition = '' + + if not search == '': + condition = "name like '%" + search + "%'" + field = 'id,username,password,accept,ps,addtime' + clist = conn.where(condition, ()).field( + field).limit(limit).order('id desc').select() + count = conn.where(condition, ()).count() + + _page = {} + _page['count'] = count + _page['p'] = page + _page['row'] = page_size + _page['tojs'] = 'getMasterRepSlaveList' + data['page'] = mw.getPage(_page) + data['data'] = clist + + return mw.getJson(data) + + +def addMasterRepSlaveUser(version=''): + args = getArgs() + data = checkArgs(args, ['username', 'password']) + if not data[0]: + return data[1] + + address = '' + if 'address' in args: + address = args['address'].strip() + + username = args['username'].strip() + password = args['password'].strip() + # ps = args['ps'].strip() + # address = args['address'].strip() + # dataAccess = args['dataAccess'].strip() + + reg = r"^[\w-]+$" + if not re.match(reg, username): + return mw.returnJson(False, '用户名不能带有特殊符号!') + checks = ['root', 'mysql', 'test', 'sys', 'performance_schema','information_schema'] + if username in checks or len(username) < 1: + return mw.returnJson(False, '用户名不合法!') + if password in checks or len(password) < 1: + return mw.returnJson(False, '密码不合法!') + + if len(password) < 1: + password = mw.md5(time.time())[0:8] + + pdb = pMysqlDb() + psdb = pSqliteDb('master_replication_user') + + if psdb.where("username=?", (username)).count() > 0: + return mw.returnJson(False, '用户已存在!') + + mdb8 = ['8.0','8.1','8.2','8.3','8.4'] + if mw.inArray(mdb8,version): + sql = "CREATE USER '" + username + \ + "' IDENTIFIED WITH mysql_native_password BY '" + password + "';" + pdb.execute(sql) + sql = "grant replication slave on *.* to '" + username + "'@'%';" + result = pdb.execute(sql) + isError = isSqlError(result) + if isError != None: + return isError + + else: + sql = "GRANT REPLICATION SLAVE ON *.* TO '" + username + \ + "'@'%' identified by '" + password + "';" + result = pdb.execute(sql) + isError = isSqlError(result) + if isError != None: + return isError + + sql_select = "grant select,reload,REPLICATION CLIENT,PROCESS on *.* to " + username + "@'%';" + pdb.execute(sql_select) + pdb.execute('FLUSH PRIVILEGES;') + + addTime = time.strftime('%Y-%m-%d %X', time.localtime()) + psdb.add('username,password,accept,ps,addtime',(username, password, '%', '', addTime)) + return mw.returnJson(True, '添加成功!') + + +def getMasterRepSlaveUserCmd(version): + + args = getArgs() + data = checkArgs(args, ['username', 'db']) + if not data[0]: + return data[1] + + psdb = pSqliteDb('master_replication_user') + f = 'username,password' + username = args['username'] + if username == '': + count = psdb.count() + if count == 0: + return mw.returnJson(False, '请添加同步账户!') + + clist = psdb.field(f).limit('1').order('id desc').select() + else: + clist = psdb.field(f).where("username=?", (username,)).limit( + '1').order('id desc').select() + + ip = mw.getLocalIp() + port = getMyPort() + db = pMysqlDb() + + mstatus = db.query('show master status') + if len(mstatus) == 0: + return mw.returnJson(False, '未开启!') + + mode = recognizeDbMode() + + sid = getDbServerId() + channel_name = "" + if sid != '': + channel_name = " for channel 'r{}'".format(sid) + + mdb8 = ['8.0','8.1','8.2','8.3','8.4'] + sql = '' + if not mw.inArray(mdb8,version): + base_sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \ + clist[0]['username'] + "', MASTER_PASSWORD='" + clist[0]['password'] + "'" + + sql += base_sql; + sql += "

"; + # sql += base_sql + ", MASTER_AUTO_POSITION=1" + channel_name + sql += base_sql + channel_name + sql += "

"; + + sql += base_sql + ", MASTER_LOG_FILE='" + mstatus[0]["File"] + "',MASTER_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name + else: + base_sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \ + clist[0]['username'] + "', SOURCE_PASSWORD='" + clist[0]['password']+"'" + sql += base_sql; + sql += "

"; + # sql += base_sql + ", MASTER_AUTO_POSITION=1" + channel_name + sql += base_sql + channel_name + sql += "

"; + sql += base_sql + ", SOURCE_LOG_FILE='" + mstatus[0]["File"] + "',SOURCE_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name + + + data = {} + data['cmd'] = sql + data["info"] = clist[0] + data['mode'] = mode + + return mw.returnJson(True, 'ok!', data) + + +def delMasterRepSlaveUser(version=''): + args = getArgs() + data = checkArgs(args, ['username']) + if not data[0]: + return data[1] + + name = args['username'] + + pdb = pMysqlDb() + psdb = pSqliteDb('master_replication_user') + pdb.execute("drop user '" + name + "'@'%'") + pdb.execute("drop user '" + name + "'@'localhost'") + + users = pdb.query("select Host from mysql.user where User='" + + name + "' AND Host!='localhost'") + for us in users: + pdb.execute("drop user '" + name + "'@'" + us["Host"] + "'") + + psdb.where("username=?", (args['username'],)).delete() + + return mw.returnJson(True, '删除成功!') + + +def updateMasterRepSlaveUser(version=''): + args = getArgs() + data = checkArgs(args, ['username', 'password']) + if not data[0]: + return data[1] + + pdb = pMysqlDb() + psdb = pSqliteDb('master_replication_user') + pdb.execute("drop user '" + args['username'] + "'@'%'") + + pdb.execute("GRANT REPLICATION SLAVE ON *.* TO '" + + args['username'] + "'@'%' identified by '" + args['password'] + "'") + + psdb.where("username=?", (args['username'],)).save( + 'password', args['password']) + + return mw.returnJson(True, '更新成功!') + + +def getSlaveSSHList(version=''): + args = getArgs() + data = checkArgs(args, ['page', 'page_size']) + if not data[0]: + return data[1] + + page = int(args['page']) + page_size = int(args['page_size']) + + conn = pSqliteDb('slave_id_rsa') + limit = str((page - 1) * page_size) + ',' + str(page_size) + + field = 'id,ip,port,db_user,id_rsa,ps,addtime' + clist = conn.field(field).limit(limit).order('id desc').select() + count = conn.count() + + data = {} + _page = {} + _page['count'] = count + _page['p'] = page + _page['row'] = page_size + _page['tojs'] = args['tojs'] + data['page'] = mw.getPage(_page) + data['data'] = clist + + return mw.getJson(data) + + +def getSlaveSyncUserByIp(version=''): + args = getArgs() + data = checkArgs(args, ['ip']) + if not data[0]: + return data[1] + + ip = args['ip'] + + conn = pSqliteDb('slave_sync_user') + data = conn.field('ip,port,user,pass,mode,cmd').where( + "ip=?", (ip,)).select() + return mw.returnJson(True, 'ok', data) + + +def addSlaveSyncUser(version=''): + import base64 + + args = getArgs() + data = checkArgs(args, ['ip']) + if not data[0]: + return data[1] + + ip = args['ip'] + if ip == "": + return mw.returnJson(True, 'ok') + + data = checkArgs(args, ['port', 'user', 'pass', 'mode']) + if not data[0]: + return data[1] + + cmd = args['cmd'] + port = args['port'] + user = args['user'] + apass = args['pass'] + mode = args['mode'] + addTime = time.strftime('%Y-%m-%d %X', time.localtime()) + + conn = pSqliteDb('slave_sync_user') + data = conn.field('ip').where("ip=?", (ip,)).select() + if len(data) > 0: + res = conn.where("ip=?", (ip,)).save( + 'port,user,pass,mode,cmd', (port, user, apass, mode, cmd)) + else: + conn.add('ip,port,user,cmd,user,pass,mode,addtime', + (ip, port, user, cmd, user, apass, mode, addTime)) + + return mw.returnJson(True, '设置成功!') + + +def delSlaveSyncUser(version=''): + args = getArgs() + data = checkArgs(args, ['ip']) + if not data[0]: + return data[1] + + ip = args['ip'] + + conn = pSqliteDb('slave_sync_user') + conn.where("ip=?", (ip,)).delete() + return mw.returnJson(True, '删除成功!') + + +def getSlaveSyncUserList(version=''): + args = getArgs() + data = checkArgs(args, ['page', 'page_size']) + if not data[0]: + return data[1] + + page = int(args['page']) + page_size = int(args['page_size']) + + conn = pSqliteDb('slave_sync_user') + limit = str((page - 1) * page_size) + ',' + str(page_size) + + field = 'id,ip,port,user,pass,cmd,addtime' + clist = conn.field(field).limit(limit).order('id desc').select() + count = conn.count() + + data = {} + _page = {} + _page['count'] = count + _page['p'] = page + _page['row'] = page_size + _page['tojs'] = args['tojs'] + data['page'] = mw.getPage(_page) + data['data'] = clist + + return mw.getJson(data) + + +def getSyncModeFile(): + return getServerDir() + "/sync.mode" + + +def getSlaveSyncMode(version): + sync_mode = getSyncModeFile() + if os.path.exists(sync_mode): + mode = mw.readFile(sync_mode).strip() + return mw.returnJson(True, 'ok', mode) + return mw.returnJson(False, 'fail') + + +def setSlaveSyncMode(version): + args = getArgs() + data = checkArgs(args, ['mode']) + if not data[0]: + return data[1] + mode = args['mode'] + sync_mode = getSyncModeFile() + + if mode == 'none': + os.remove(sync_mode) + else: + mw.writeFile(sync_mode, mode) + return mw.returnJson(True, '设置成功', mode) + + +def getSlaveSSHByIp(version=''): + args = getArgs() + data = checkArgs(args, ['ip']) + if not data[0]: + return data[1] + + ip = args['ip'] + + conn = pSqliteDb('slave_id_rsa') + data = conn.field('ip,port,db_user,id_rsa').where("ip=?", (ip,)).select() + return mw.returnJson(True, 'ok', data) + + +def addSlaveSSH(version=''): + import base64 + + args = getArgs() + data = checkArgs(args, ['ip']) + if not data[0]: + return data[1] + + ip = args['ip'] + if ip == "": + return mw.returnJson(True, 'ok') + + data = checkArgs(args, ['port', 'id_rsa', 'db_user']) + if not data[0]: + return data[1] + + id_rsa = args['id_rsa'] + port = args['port'] + db_user = args['db_user'] + user = 'root' + addTime = time.strftime('%Y-%m-%d %X', time.localtime()) + + conn = pSqliteDb('slave_id_rsa') + data = conn.field('ip,id_rsa').where("ip=?", (ip,)).select() + if len(data) > 0: + res = conn.where("ip=?", (ip,)).save( + 'port,id_rsa,db_user', (port, id_rsa, db_user)) + else: + conn.add('ip,port,user,id_rsa,db_user,ps,addtime', + (ip, port, user, id_rsa, db_user, '', addTime)) + + return mw.returnJson(True, '设置成功!') + + +def delSlaveSSH(version=''): + args = getArgs() + data = checkArgs(args, ['ip']) + if not data[0]: + return data[1] + + ip = args['ip'] + + conn = pSqliteDb('slave_id_rsa') + conn.where("ip=?", (ip,)).delete() + return mw.returnJson(True, 'ok') + + +def updateSlaveSSH(version=''): + args = getArgs() + data = checkArgs(args, ['ip', 'id_rsa']) + if not data[0]: + return data[1] + + ip = args['ip'] + id_rsa = args['id_rsa'] + conn = pSqliteDb('slave_id_rsa') + conn.where("ip=?", (ip,)).save('id_rsa', (id_rsa,)) + return mw.returnJson(True, 'ok') + + +def getSlaveList(version=''): + + query_status_cmd = 'show slave status' + mdb8 = getMdb8Ver() + if mw.inArray(mdb8, version): + query_status_cmd = 'show replica status' + + if status(version) == 'stop': + return mw.returnJson(False, 'MySQL未启动', []) + + db = pMysqlDb() + dlist = db.query(query_status_cmd) + + # print(dlist) + data = {} + data['data'] = dlist + return mw.getJson(data) + +def trySlaveSyncBugfix(version=''): + if status(version) == 'stop': + return mw.returnJson(False, 'MySQL未启动', []) + + mode_file = getSyncModeFile() + if not os.path.exists(mode_file): + return mw.returnJson(False, '需要先设置同步配置') + + mode = mw.readFile(mode_file) + if mode != 'sync-user': + return mw.returnJson(False, '仅支持【同步账户】模式') + + conn = pSqliteDb('slave_sync_user') + slave_sync_data = conn.field('ip,port,user,pass,mode,cmd').select() + if len(slave_sync_data) < 1: + return mw.returnJson(False, '需要先添加【同步用户】配置!') + + # print(slave_sync_data) + # 本地从库 + sdb = pMysqlDb() + + gtid_purged = '' + + for i in range(len(slave_sync_data)): + port = slave_sync_data[i]['port'] + password = slave_sync_data[i]['pass'] + host = slave_sync_data[i]['ip'] + user = slave_sync_data[i]['user'] + + # print(port, password, host) + + mdb = mw.getMyORM() + mdb.setHost(host) + mdb.setPort(port) + mdb.setUser(user) + mdb.setPwd(password) + mdb.setSocket('') + + var_gtid = mdb.query('show VARIABLES like "%gtid_purged%"') + if len(var_gtid) > 0: + gtid_purged += var_gtid[0]['Value'] + ',' + + gtid_purged = gtid_purged.strip(',') + sql = "set @@global.gtid_purged='" + gtid_purged + "'" + + sdb.query('stop slave') + # print(sql) + sdb.query(sql) + sdb.query('start slave') + return mw.returnJson(True, '修复成功!') + +def getSlaveSyncCmd(version=''): + + root = mw.getPanelDir() + cmd = 'cd ' + root + ' && python3 ' + root + \ + '/plugins/mysql/index.py do_full_sync {"db":"all","sign":""}' + return mw.returnJson(True, 'ok', cmd) + + +def initSlaveStatus(version=''): + mode_file = getSyncModeFile() + if not os.path.exists(mode_file): + return mw.returnJson(False, '需要先设置同步配置') + + mode = mw.readFile(mode_file) + if mode == 'ssh': + return initSlaveStatusSSH(version) + if mode == 'sync-user': + return initSlaveStatusSyncUser(version) + + +def parseSlaveSyncCmd(cmd): + a = {} + if cmd.lower().find('for') > 0: + cmd_tmp = cmd.split('for') + cmd = cmd_tmp[0].strip() + + pattern_c = r"channel \'(.*)\';" + match_val = re.match(pattern_c, cmd_tmp[1].strip(), re.I) + if match_val: + m_groups = match_val.groups() + a['channel'] = m_groups[0] + vlist = cmd.split(',') + for i in vlist: + tmp = i.strip() + tmp_a = tmp.split(" ") + real_tmp = tmp_a[len(tmp_a) - 1] + kv = real_tmp.split("=") + a[kv[0]] = kv[1].replace("'", '').replace("'", '').replace(";", '') + return a + + +def initSlaveStatusSyncUser(version=''): + conn = pSqliteDb('slave_sync_user') + slave_data = conn.field('ip,port,user,pass,mode,cmd').select() + if len(slave_data) < 1: + return mw.returnJson(False, '需要先添加同步用户配置!') + + # print(data) + pdb = pMysqlDb() + if len(slave_data) == 1: + dlist = pdb.query('show slave status') + if len(dlist) > 0: + return mw.returnJson(False, '已经初始化好了zz...') + + msg = '' + local_mode = recognizeDbMode() + for x in range(len(slave_data)): + slave_t = slave_data[x] + mode_name = 'classic' + base_t = 'IP:' + slave_t['ip'] + ",PORT:" + \ + slave_t['port'] + ",USER:" + slave_t['user'] + + if slave_t['mode'] == '1': + mode_name = 'gtid' + + if local_mode != mode_name: + msg += base_t + '->同步模式不一致' + continue + + cmd_sql = slave_t['cmd'] + if cmd_sql == '': + msg += base_t + '->同步命令不能为空' + continue + + try: + pinfo = parseSlaveSyncCmd(cmd_sql) + except Exception as e: + return mw.returnJson(False, base_t + '->CMD同步命令不合规范!') + t = pdb.query(cmd_sql) + isError = isSqlError(t) + if isError: + return isError + + # pdb.query("start slave user='{}' password='{}';".format( + # u['user'], u['pass'])) + + pdb.query("start slave") + pdb.query("start all slaves") + + if msg == '': + msg = '初始化成功!' + return mw.returnJson(True, msg) + + +def initSlaveStatusSSH(version=''): + db = pMysqlDb() + dlist = db.query('show slave status') + + conn = pSqliteDb('slave_id_rsa') + ssh_list = conn.field('ip,port,id_rsa,db_user').select() + + if len(ssh_list) < 1: + return mw.returnJson(False, '需要先配置【[主]SSH配置】!') + + local_mode = recognizeDbMode() + + import paramiko + paramiko.util.log_to_file('paramiko.log') + ssh = paramiko.SSHClient() + + db.query('stop slave') + db.query('reset slave all') + for data in ssh_list: + ip = data['ip'] + SSH_PRIVATE_KEY = "/tmp/t_ssh_" + ip + ".txt" + master_port = data['port'] + mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n')) + mw.execShell("chmod 600 " + SSH_PRIVATE_KEY) + try: + key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(hostname=ip, port=int(master_port), + username='root', pkey=key) + + db_user = data['db_user'] + cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \ + getSPluginDir() + \ + '/index.py get_master_rep_slave_user_cmd {"username":"' + \ + db_user + '","db":""}' + stdin, stdout, stderr = ssh.exec_command(cmd) + result = stdout.read() + result = result.decode('utf-8') + if result.strip() == "": + return mw.returnJson(False, '[主][' + ip + ']:获取同步命令失败!') + + cmd_data = json.loads(result) + if not cmd_data['status']: + return mw.returnJson(False, '[主][' + ip + ']:' + cmd_data['msg']) + + if local_mode != cmd_data['data']['mode']: + return mw.returnJson(False, '[主][' + ip + ']:【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode)) + + u = cmd_data['data']['info'] + + ps = u['username'] + "|" + u['password'] + print(ps) + conn.where('ip=?', (ip,)).setField('ps', ps) + db.query('stop slave') + + # 保证同步IP一致 + cmd = cmd_data['data']['cmd'] + if cmd.find('SOURCE_HOST') > -1: + cmd = re.sub(r"SOURCE_HOST='(.*?)'", + "SOURCE_HOST='" + ip + "'", cmd, 1) + + if cmd.find('MASTER_HOST') > -1: + cmd = re.sub(r"MASTER_HOST='(.*?)'", + "MASTER_HOST='" + ip + "'", cmd, 1) + db.query(cmd) + ssh.close() + if os.path.exists(SSH_PRIVATE_KEY): + os.system("rm -rf " + SSH_PRIVATE_KEY) + except Exception as e: + return mw.returnJson(False, '[主][' + ip + ']:SSH认证配置连接失败!' + str(e)) + db.query('start slave') + return mw.returnJson(True, '初始化成功!') + + +def setSlaveStatus(version=''): + mode_file = getSyncModeFile() + if not os.path.exists(mode_file): + return mw.returnJson(False, '需要先设置同步配置') + + mode = mw.readFile(mode_file) + pdb = pMysqlDb() + dlist = pdb.query('show slave status') + if len(dlist) == 0: + return mw.returnJson(False, '需要手动添加同步账户或者执行初始化!') + + for v in dlist: + connection_name = '' + cmd = "slave" + if 'Channel_Name' in v: + ch_name = v['Channel_Name'] + cmd = "slave for channel '{}'".format(ch_name) + + if (v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes'): + pdb.query("stop {}".format(cmd)) + else: + pdb.query("start {}".format(cmd)) + + return mw.returnJson(True, '设置成功!') + + +def deleteSlave(version=''): + args = getArgs() + db = pMysqlDb() + if 'sign' in args: + sign = args['sign'] + db.query("stop slave for channel '{}'".format(sign)) + db.query("reset slave all for channel '{}'".format(sign)) + else: + db.query('stop slave') + db.query('reset slave all') + + return mw.returnJson(True, '删除成功!') + + +def dumpMysqlData(version=''): + args = getArgs() + data = checkArgs(args, ['db']) + if not data[0]: + return data[1] + + pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + mysql_dir = getServerDir() + myconf = mysql_dir + "/etc/my.cnf" + + option = '' + mode = recognizeDbMode() + if mode == 'gtid': + option = ' --set-gtid-purged=off ' + + if args['db'].lower() == 'all': + dlist = findBinlogDoDb() + cmd = mysql_dir + "/bin/mysqldump --defaults-file=" + myconf + " " + option + " -uroot -p" + \ + pwd + " --databases " + \ + ' '.join(dlist) + " | gzip > /tmp/dump.sql.gz" + else: + cmd = mysql_dir + "/bin/mysqldump --defaults-file=" + myconf + " " + option + " -uroot -p" + \ + pwd + " --databases " + args['db'] + " | gzip > /tmp/dump.sql.gz" + + ret = mw.execShell(cmd) + if ret[0] == '': + return 'ok' + return 'fail' + +############### --- 重要 数据补足同步 ---- ########### + +def getSyncMysqlDB(dbname,sign = ''): + conn = pSqliteDb('slave_sync_user') + if sign != '': + data = conn.field('ip,port,user,pass,mode,cmd').where('ip=?', (sign,)).find() + else: + data = conn.field('ip,port,user,pass,mode,cmd').find() + user = data['user'] + apass = data['pass'] + port = data['port'] + ip = data['ip'] + # 远程数据 + sync_db = mw.getMyORM() + # MySQLdb | + sync_db.setPort(port) + sync_db.setHost(ip) + sync_db.setUser(user) + sync_db.setPwd(apass) + sync_db.setDbName(dbname) + sync_db.setTimeout(60) + return sync_db + +def syncDatabaseRepairTempFile(): + tmp_log = mw.getMWLogs()+ '/mysql-check.log' + return tmp_log + +def syncDatabaseRepairLog(version=''): + import subprocess + args = getArgs() + data = checkArgs(args, ['db','sign','op']) + if not data[0]: + return data[1] + + sync_args_db = args['db'] + sync_args_sign = args['sign'] + op = args['op'] + tmp_log = syncDatabaseRepairTempFile() + cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && python3 plugins/mysql-community/index.py sync_database_repair {"db":"'+sync_args_db+'","sign":"'+sync_args_sign+'"}' + # print(cmd) + + if op == 'get': + log = mw.getLastLine(tmp_log, 15) + return mw.returnJson(True, log) + + if op == 'cmd': + return mw.returnJson(True, 'ok', cmd) + + if op == 'do': + os.system(' echo "开始执行" > '+ tmp_log) + os.system(cmd +' >> '+ tmp_log +' &') + return mw.returnJson(True, 'ok') + + return mw.returnJson(False, '无效请求!') + + +def syncDatabaseRepair(version=''): + time_stats_s = time.time() + tmp_log = syncDatabaseRepairTempFile() + + from pymysql.converters import escape_string + args = getArgs() + data = checkArgs(args, ['db','sign']) + if not data[0]: + return data[1] + + sync_args_db = args['db'] + sync_args_sign = args['sign'] + + # 本地数据 + local_db = pMysqlDb() + # 远程数据 + sync_db = getSyncMysqlDB(sync_args_db,sync_args_sign) + + tables = local_db.query('show tables from `%s`' % sync_args_db) + table_key = "Tables_in_" + sync_args_db + inconsistent_table = [] + + tmp_dir = '/tmp/sync_db_repair' + mw.execShell('mkdir -p '+tmp_dir) + + for tb in tables: + + table_name = sync_args_db+'.'+tb[table_key] + table_check_file = tmp_dir+'/'+table_name+'.txt' + + if os.path.exists(table_check_file): + # print(table_name+', 已检查OK') + continue + + primary_key_sql = "SHOW INDEX FROM "+table_name+" WHERE Key_name = 'PRIMARY';"; + primary_key_data = local_db.query(primary_key_sql) + # print(primary_key_sql,primary_key_data) + pkey_name = '*' + if len(primary_key_data) == 1: + pkey_name = primary_key_data[0]['Column_name'] + # print(pkey_name) + if pkey_name != '*' : + # 智能校验(由于服务器同步可能会慢,比较总数总是对不上) + cmd_local_newpk_sql = 'select ' + pkey_name + ' from ' + table_name + " order by " + pkey_name + " desc limit 1" + cmd_local_newpk_data = local_db.query(cmd_local_newpk_sql) + # print(cmd_local_newpk_data) + if len(cmd_local_newpk_data) == 1: + # 比较总数 + cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name + ' where '+pkey_name + ' <= '+ str(cmd_local_newpk_data[0][pkey_name]) + local_count_data = local_db.query(cmd_count_sql) + sync_count_data = sync_db.query(cmd_count_sql) + + if local_count_data != sync_count_data: + print(cmd_count_sql) + print("all data compare: ",local_count_data, sync_count_data) + else: + print(table_name+' smart compare check ok.') + mw.writeFile(tmp_log, table_name+' smart compare check ok.\n','a+') + mw.execShell("echo 'ok' > "+table_check_file) + continue + + + + # 比较总数 + cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name + local_count_data = local_db.query(cmd_count_sql) + sync_count_data = sync_db.query(cmd_count_sql) + + if local_count_data != sync_count_data: + print("all data compare: ",local_count_data, sync_count_data) + inconsistent_table.append(table_name) + diff = sync_count_data[0]['num'] - local_count_data[0]['num'] + print(table_name+', need sync. diff,'+str(diff)) + mw.writeFile(tmp_log, table_name+', need sync. diff,'+str(diff)+'\n','a+') + else: + print(table_name+' check ok.') + mw.writeFile(tmp_log, table_name+' check ok.\n','a+') + mw.execShell("echo 'ok' > "+table_check_file) + + + # inconsistent_table = ['xx.xx'] + # 数据对齐 + for table_name in inconsistent_table: + is_break = False + while not is_break: + local_db.ping() + # 远程数据 + sync_db.ping() + + print("check table:"+table_name) + mw.writeFile(tmp_log, "check table:"+table_name+'\n','a+') + table_name_pos = 0 + table_name_pos_file = tmp_dir+'/'+table_name+'.pos.txt' + primary_key_sql = "SHOW INDEX FROM "+table_name+" WHERE Key_name = 'PRIMARY';"; + primary_key_data = local_db.query(primary_key_sql) + pkey_name = primary_key_data[0]['Column_name'] + + if os.path.exists(table_name_pos_file): + table_name_pos = mw.readFile(table_name_pos_file) + + + data_select_sql = 'select * from '+table_name + ' where '+pkey_name+' > '+str(table_name_pos)+' limit 10000' + print(data_select_sql) + local_select_data = local_db.query(data_select_sql) + + time_s = time.time() + sync_select_data = sync_db.query(data_select_sql) + print(f'sync query cos:{time.time() - time_s:.4f}s') + mw.writeFile(tmp_log, f'sync query cos:{time.time() - time_s:.4f}s\n','a+') + + # print(local_select_data) + # print(sync_select_data) + + # print(len(local_select_data)) + # print(len(sync_select_data)) + print('pos:',str(table_name_pos),'local compare sync,',local_select_data == sync_select_data) + + + cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name + local_count_data = local_db.query(cmd_count_sql) + time_s = time.time() + sync_count_data = sync_db.query(cmd_count_sql) + print(f'sync count data cos:{time.time() - time_s:.4f}s') + print(local_count_data,sync_count_data) + # 数据同步有延迟,相等即任务数据补足完成 + if local_count_data[0]['num'] == sync_count_data[0]['num']: + is_break = True + break + + diff = sync_count_data[0]['num'] - local_count_data[0]['num'] + print("diff," + str(diff)+' line data!') + + if local_select_data == sync_select_data: + data_count = len(local_select_data) + if data_count == 0: + # mw.writeFile(table_name_pos_file, '0') + print(table_name+",data is equal ok..") + is_break = True + break + + # print(table_name,data_count) + pos = local_select_data[data_count-1][pkey_name] + print('pos',pos) + progress = pos/sync_count_data[0]['num'] + print('progress,%.2f' % progress+'%') + mw.writeFile(table_name_pos_file, str(pos)) + else: + sync_select_data_len = len(sync_select_data) + skip_idx = 0 + # 主库PK -> 查询本地 | 保证一致 + if sync_select_data_len > 0: + for idx in range(sync_select_data_len): + sync_idx_data = sync_select_data[idx] + local_idx_data = None + if idx in local_select_data: + local_idx_data = local_select_data[idx] + if sync_select_data[idx] == local_idx_data: + skip_idx = idx + pos = local_select_data[idx][pkey_name] + mw.writeFile(table_name_pos_file, str(pos)) + + # print(insert_data) + local_inquery_sql = 'select * from ' + table_name+ ' where ' +pkey_name+' = '+ str(sync_idx_data[pkey_name]) + # print(local_inquery_sql) + ldata = local_db.query(local_inquery_sql) + # print('ldata:',ldata) + if len(ldata) == 0: + print("id:"+ str(sync_idx_data[pkey_name])+ " no exists, insert") + insert_sql = 'insert into ' + table_name + field_str = '' + value_str = '' + for field in sync_idx_data: + field_str += '`'+field+'`,' + value_str += '\''+escape_string(str(sync_idx_data[field]))+'\',' + field_str = '(' +field_str.strip(',')+')' + value_str = '(' +value_str.strip(',')+')' + insert_sql = insert_sql+' '+field_str+' values'+value_str+';' + print(insert_sql) + r = local_db.execute(insert_sql) + print(r) + else: + # print('compare sync->local:',sync_idx_data == ldata[0] ) + if ldata[0] == sync_idx_data: + continue + + print("id:"+ str(sync_idx_data[pkey_name])+ " data is not equal, update") + update_sql = 'update ' + table_name + field_str = '' + value_str = '' + for field in sync_idx_data: + if field == pkey_name: + continue + field_str += '`'+field+'`=\''+escape_string(str(sync_idx_data[field]))+'\',' + field_str = field_str.strip(',') + update_sql = update_sql+' set '+field_str+' where '+pkey_name+'=\''+str(sync_idx_data[pkey_name])+'\';' + print(update_sql) + r = local_db.execute(update_sql) + print(r) + + # 本地PK -> 查询主库 | 保证一致 + # local_select_data_len = len(local_select_data) + # if local_select_data_len > 0: + # for idx in range(local_select_data_len): + # if idx < skip_idx: + # continue + # local_idx_data = local_select_data[idx] + # print('local idx check', idx, skip_idx) + # local_inquery_sql = 'select * from ' + table_name+ ' where ' +pkey_name+' = '+ str(local_idx_data[pkey_name]) + # print(local_inquery_sql) + # sdata = sync_db.query(local_inquery_sql) + # sdata_len = len(sdata) + # print('sdata:',sdata,sdata_len) + # if sdata_len == 0: + # delete_sql = 'delete from ' + table_name + ' where ' +pkey_name+' = '+ str(local_idx_data[pkey_name]) + # print(delete_sql) + # r = local_db.execute(delete_sql) + # print(r) + # break + + + if is_break: + print("break all") + break + time.sleep(3) + print(f'data check cos:{time.time() - time_stats_s:.4f}s') + print("data supplementation completed") + mw.execShell('rm -rf '+tmp_dir) + return 'ok' + +############### --- 重要 同步---- ########### + +def asyncTmpfile(): + path = '/tmp/mysql_community_async_status.txt' + return path + + +def writeDbSyncStatus(data): + path = asyncTmpfile() + mw.writeFile(path, json.dumps(data)) + +def fullSyncCmd(): + time_all_s = time.time() + args = getArgs() + data = checkArgs(args, ['db', 'sign']) + if not data[0]: + return data[1] + + db = args['db'] + sign = args['sign'] + + cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && python3 plugins/mysql-community/index.py do_full_sync {"db":"'+db+'","sign":"'+sign+'"}' + return mw.returnJson(True,'ok',cmd) + +def doFullSync(version=''): + mode_file = getSyncModeFile() + if not os.path.exists(mode_file): + return mw.returnJson(False, '需要先设置同步配置') + + mode = mw.readFile(mode_file) + if mode == 'ssh': + return doFullSyncSSH(version) + if mode == 'sync-user': + return doFullSyncUser(version) + +def isSimpleSyncCmd(sql): + new_sql = sql.lower() + if new_sql.find('master_auto_position') > 0: + return False + return True + +def getChannelNameForCmd(cmd): + cmd = cmd.lower() + cmd_arr = cmd.split('channel') + if len(cmd_arr) == 2: + cmd_channel_info = cmd_arr[1] + channel_name = cmd_channel_info.strip() + channel_name = channel_name.strip(';') + channel_name = channel_name.strip("'") + return channel_name + return '' + +def doFullSyncUserImportContentForChannel(file, channel_name): + # print(file, channel_name) + content = mw.readFile(file) + + content = content.replace('STOP SLAVE;', "STOP SLAVE for channel '{}';".format(channel_name)) + content = content.replace('START SLAVE;', "START SLAVE for channel '{}';".format(channel_name)) + + find_head = "CHANGE MASTER TO " + find_re = find_head+"(.*?);" + find_r = re.search(find_re, content, re.I|re.M) + if find_r: + find_rg = find_r.groups() + if len(find_rg)>0: + find_str = find_head+find_rg[0] + if find_str.lower().find('channel')==-1: + content = content.replace(find_str+';', find_str+" for channel '{}';".format(channel_name)) + + mw.writeFile(file,content) + return True + +def doFullSyncUser(version=''): + which_pv = mw.execShell('which pv') + is_exist_pv = False + if os.path.exists(which_pv[0]): + is_exist_pv = True + + time_all_s = time.time() + + args = getArgs() + data = checkArgs(args, ['db', 'sign']) + if not data[0]: + return data[1] + + sync_db = args['db'] + sync_db_import = args['db'] + + if sync_db.lower() == 'all': + sync_db_import = '' + dbs = findBinlogSlaveDoDb() + dbs_str = '' + for x in dbs: + dbs_str += ' ' + x + sync_db = "--databases " + dbs_str.strip() + + sync_sign = args['sign'] + + db = pMysqlDb() + + conn = pSqliteDb('slave_sync_user') + if sync_sign != '': + data = conn.field('ip,port,user,pass,mode,cmd').where( + 'ip=?', (sync_sign,)).find() + else: + data = conn.field('ip,port,user,pass,mode,cmd').find() + + user = data['user'] + apass = data['pass'] + port = data['port'] + ip = data['ip'] + cmd = data['cmd'] + + channel_name = getChannelNameForCmd(cmd) + sync_mdb = getSyncMysqlDB(sync_db,sync_sign) + + bak_file = '/tmp/tmp.sql' + if os.path.exists(bak_file): + os.system("rm -rf " + bak_file) + + writeDbSyncStatus({'code': 0, 'msg': '开始同步...', 'progress': 0}) + dmp_option = '' + mode = recognizeDbMode() + if mode == 'gtid': + dmp_option = ' --set-gtid-purged=off ' + + time.sleep(1) + writeDbSyncStatus({'code': 1, 'msg': '正在停止从库...', 'progress': 15}) + + mdb8 = getMdb8Ver() + if mw.inArray(mdb8,version): + db.query("stop slave user='{}' password='{}';".format(user, apass)) + else: + db.query("stop slave") + + time.sleep(1) + writeDbSyncStatus({'code': 2, 'msg': '远程导出数据...', 'progress': 20}) + + find_run_dump = mw.execShell('ps -ef | grep mysqldump | grep -v grep') + if find_run_dump[0] != "": + print("正在远程导出数据中,别着急...") + writeDbSyncStatus({'code': 3.1, 'msg': '正在远程导出数据中,别着急...', 'progress': 19}) + return False + + time_s = time.time() + if not os.path.exists(bak_file): + dmp_option += ' ' + if isSimpleSyncCmd(cmd): + if mw.inArray(mdb8,version): + # --compression-algorithms + dmp_option += " --source-data=1 --apply-replica-statements --include-source-host-port " + else: + dmp_option += " --master-data=1 --apply-slave-statements --include-master-host-port --compress " + + + dump_sql_data = getServerDir() + "/bin/mysqldump --single-transaction --default-character-set=utf8mb4 -q " + dmp_option + " -h" + \ + ip + " -P" + port + " -u" + user + ' -p"' + apass + '" --ssl-mode=DISABLED ' + sync_db + " > " + bak_file + print(dump_sql_data) + time_s = time.time() + r = mw.execShell(dump_sql_data) + print(r) + time_e = time.time() + export_cos = time_e - time_s + print("export cos:", export_cos) + + writeDbSyncStatus({'code': 3, 'msg': '导出耗时:'+str(int(export_cos))+'秒,正在到本地导入数据中...', 'progress': 40}) + + find_run_import = mw.execShell('ps -ef | grep mysql| grep '+ bak_file +' | grep -v grep') + if find_run_import[0] != "": + print("正在导入数据中,别着急...") + writeDbSyncStatus({'code': 4.1, 'msg': '正在导入数据中,别着急...', 'progress': 39}) + return False + + + time_s = time.time() + if os.path.exists(bak_file): + + # 重置 + db.execute('reset master') + if channel_name != '': + doFullSyncUserImportContentForChannel(bak_file, channel_name) + + pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + sock = getSocketFile() + + if is_exist_pv: + my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import + my_import_cmd = "pv -t -p " + bak_file + '|' + my_import_cmd + print(my_import_cmd) + os.system(my_import_cmd) + else: + my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import + ' < ' + bak_file + print(my_import_cmd) + mw.execShell(my_import_cmd) + + my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ + ' ' + sync_db_import + ' < ' + bak_file + mw.execShell(my_import_cmd) + + if mw.inArray(mdb8, version): + db.query("start replica user='{}' password='{}';".format(user, apass)) + else: + db.query("start slave") + + db.query("start all slaves") + time_all_e = time.time() + cos = time_all_e - time_all_s + writeDbSyncStatus({'code': 6, 'msg': '总耗时:'+str(int(cos))+'秒,从库重启完成...', 'progress': 100}) + + if os.path.exists(bak_file): + os.system("rm -rf " + bak_file) + + return True + + +def doFullSyncSSH(version=''): + + args = getArgs() + data = checkArgs(args, ['db', 'sign']) + if not data[0]: + return data[1] + + sync_db = args['db'] + sync_sign = args['sign'] + + db = pMysqlDb() + + id_rsa_conn = pSqliteDb('slave_id_rsa') + if sync_sign != '': + data = id_rsa_conn.field('ip,port,db_user,id_rsa').where( + 'ip=?', (sync_sign,)).find() + else: + data = id_rsa_conn.field('ip,port,db_user,id_rsa').find() + + SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt" + id_rsa = data['id_rsa'].replace('\\n', '\n') + mw.writeFile(SSH_PRIVATE_KEY, id_rsa) + + ip = data["ip"] + master_port = data['port'] + db_user = data['db_user'] + print("master ip:", ip) + + writeDbSyncStatus({'code': 0, 'msg': '开始同步...', 'progress': 0}) + + import paramiko + paramiko.util.log_to_file('paramiko.log') + ssh = paramiko.SSHClient() + + print(SSH_PRIVATE_KEY) + if not os.path.exists(SSH_PRIVATE_KEY): + writeDbSyncStatus({'code': 0, 'msg': '需要配置SSH......', 'progress': 0}) + return 'fail' + + try: + # ssh.load_system_host_keys() + mw.execShell("chmod 600 " + SSH_PRIVATE_KEY) + key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + print(ip, master_port) + + # pkey=key + # key_filename=SSH_PRIVATE_KEY + ssh.connect(hostname=ip, port=int(master_port), + username='root', pkey=key) + except Exception as e: + print(str(e)) + writeDbSyncStatus( + {'code': 0, 'msg': 'SSH配置错误:' + str(e), 'progress': 0}) + return 'fail' + + writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5}) + + dbname = args['db'] + cmd = "cd /www/server/mdserver-web && source bin/activate && python3 " + \ + getSPluginDir() + "/index.py dump_mysql_data {\"db\":'" + dbname + "'}" + print(cmd) + stdin, stdout, stderr = ssh.exec_command(cmd) + result = stdout.read() + result = result.decode('utf-8') + if result.strip() == 'ok': + writeDbSyncStatus({'code': 1, 'msg': '主服务器备份完成...', 'progress': 30}) + else: + writeDbSyncStatus( + {'code': 1, 'msg': '主服务器备份失败...:' + str(result), 'progress': 100}) + return 'fail' + + print("同步文件", "start") + # cmd = 'scp -P' + str(master_port) + ' -i ' + SSH_PRIVATE_KEY + \ + # ' root@' + ip + ':/tmp/dump.sql.gz /tmp' + t = ssh.get_transport() + sftp = paramiko.SFTPClient.from_transport(t) + copy_status = sftp.get("/tmp/dump.sql.gz", "/tmp/dump.sql.gz") + print("同步信息:", copy_status) + print("同步文件", "end") + if copy_status == None: + writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40}) + + cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \ + getSPluginDir() + \ + '/index.py get_master_rep_slave_user_cmd {"username":"' + \ + db_user + '","db":""}' + stdin, stdout, stderr = ssh.exec_command(cmd) + result = stdout.read() + result = result.decode('utf-8') + cmd_data = json.loads(result) + + db.query('stop slave') + writeDbSyncStatus({'code': 3, 'msg': '停止从库完成...', 'progress': 45}) + + cmd = cmd_data['data']['cmd'] + # 保证同步IP一致 + if cmd.find('SOURCE_HOST') > -1: + cmd = re.sub(r"SOURCE_HOST='(.*?)'", + "SOURCE_HOST='" + ip + "'", cmd, 1) + + if cmd.find('MASTER_HOST') > -1: + cmd = re.sub(r"MASTER_HOST='(.*?)'", + "MASTER_HOST='" + ip + "'", cmd, 1) + + db.query(cmd) + uinfo = cmd_data['data']['info'] + ps = uinfo['username'] + "|" + uinfo['password'] + id_rsa_conn.where('ip=?', (ip,)).setField('ps', ps) + writeDbSyncStatus({'code': 4, 'msg': '刷新从库同步信息完成...', 'progress': 50}) + + pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + root_dir = getServerDir() + msock = root_dir + "/mysql.sock" + mw.execShell("cd /tmp && gzip -d dump.sql.gz") + cmd = root_dir + "/bin/mysql -S " + msock + \ + " -uroot -p" + pwd + " < /tmp/dump.sql" + + print(cmd) + import_data = mw.execShell(cmd) + if import_data[0] == '': + print(import_data[1]) + writeDbSyncStatus({'code': 5, 'msg': '导入数据完成...', 'progress': 90}) + else: + print(import_data[0]) + writeDbSyncStatus({'code': 5, 'msg': '导入数据失败...', 'progress': 100}) + return 'fail' + + # "start slave user='{}' password='{}';".format(uinfo['username'], uinfo['password']) + + db.query("start slave") + writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100}) + + os.system("rm -rf " + SSH_PRIVATE_KEY) + os.system("rm -rf /tmp/dump.sql") + return True + + +def fullSync(version=''): + args = getArgs() + data = checkArgs(args, ['db', 'begin']) + if not data[0]: + return data[1] + + status_file = asyncTmpfile() + if args['begin'] == '1': + cmd = 'cd ' + mw.getPanelDir() + ' && python3 ' + getPluginDir() + \ + '/index.py do_full_sync {"db":"' + \ + args['db'] + '","sign":"' + sign + '"} &' + # print(cmd) + mw.execShell(cmd) + return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0}) + + if os.path.exists(status_file): + c = mw.readFile(status_file) + tmp = json.loads(c) + if tmp['code'] == 1: + sys_dump_sql = "/tmp/dump.sql" + if os.path.exists(sys_dump_sql): + dump_size = os.path.getsize(sys_dump_sql) + tmp['msg'] = tmp['msg'] + ":" + "同步文件:" + mw.toSize(dump_size) + c = json.dumps(tmp) + + # if tmp['code'] == 6: + # os.remove(status_file) + return c + + return json.dumps({'code': 0, 'msg': '点击开始,开始同步!', 'progress': 0}) + + +def installPreInspection(version): + arch_data = mw.execShell('arch') + if arch_data[0].strip().startswith('aarch'): + return '不支持aarch架构' + + cmd = "cat /etc/*-release | grep PRETTY_NAME |awk -F = '{print $2}' | awk -F '\"' '{print $2}'| awk '{print $1}'" + sys = mw.execShell(cmd) + + if sys[1] != '': + return '不支持改系统' + + cmd = "cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F '\"' '{print $2}'" + sys_id = mw.execShell(cmd) + + sysName = sys[0].strip().lower() + sysId = sys_id[0].strip() + mdb8 = getMdb8Ver() + + if not sysName in ('debian', 'ubuntu'): + return '仅支持debian,ubuntu' + + if (sysName == 'debian' and not sysId in('12', '11', '10')): + return 'debian支持10,11,12' + + if sysName == 'debian' and sysId == '12' and version == '8.0': + return 'debian12,暂时不支持8.0' + + if version == '9.0': + if sysName == 'debian' and sysId != '12': + return '9.0 仅支持debian12' + if sysName == 'ubuntu' and sysId != '24.04': + return '9.0 仅支持ubuntu24.04' + + if (sysName == 'ubuntu' and version == '5.7' and not sysId in ('18.04')): + return "Ubuntu Apt MySQL[" + version + "] 仅支持18.04" + + if (sysName == 'ubuntu' and version == '8.0' and not sysId in ('18.04', '20.04', '22.04','24.04')): + return 'Ubuntu Apt MySQL[' + version + '] 仅支持18.04,20.04,22.04,24.04' + return 'ok' + + +def uninstallPreInspection(version): + + data_dir = getDataDir() + if os.path.exists(data_dir): + stop(version) + + if mw.isDebugMode(): + return 'ok' + + from utils.plugin import plugin as MwPlugin + MwPlugin.instance().removeIndex(getPluginName(), version) + + return "请手动删除MySQL[{}]
rm -rf {}".format(version, getServerDir()) + +if __name__ == "__main__": + func = sys.argv[1] + version = '5.6' + version_pl = getServerDir() + "/version.pl" + if os.path.exists(version_pl): + version = mw.readFile(version_pl).strip() + + if func == 'status': + print(status(version)) + elif func == 'start': + print(start(version)) + elif func == 'stop': + print(stop(version)) + elif func == 'restart': + print(restart(version)) + elif func == 'reload': + print(reload(version)) + elif func == 'initd_status': + print(initdStatus()) + elif func == 'initd_install': + print(initdInstall()) + elif func == 'initd_uninstall': + print(initdUinstall()) + elif func == 'install_pre_inspection': + print(installPreInspection(version)) + elif func == 'uninstall_pre_inspection': + print(uninstallPreInspection(version)) + elif func == 'run_info': + print(runInfo(version)) + elif func == 'db_status': + print(myDbStatus(version)) + elif func == 'set_db_status': + print(setDbStatus(version)) + elif func == 'conf': + print(getConf()) + elif func == 'bin_log': + print(binLog(version)) + elif func == 'binlog_list': + print(binLogList()) + elif func == 'clean_bin_log': + print(cleanBinLog()) + elif func == 'error_log': + print(getErrorLog()) + elif func == 'show_log': + print(getShowLogFile()) + elif func == 'my_db_pos': + print(getMyDbPos()) + elif func == 'set_db_pos': + print(setMyDbPos(version)) + elif func == 'my_port': + print(getMyPort()) + elif func == 'set_my_port': + print(setMyPort()) + elif func == 'init_pwd': + print(initMysqlPwd()) + elif func == 'root_pwd': + print(rootPwd()) + elif func == 'get_db_list': + print(getDbList()) + elif func == 'set_db_backup': + print(setDbBackup()) + elif func == 'import_db_backup': + print(importDbBackup()) + elif func == 'import_db_external': + print(importDbExternal()) + elif func == 'import_db_external_progress': + print(importDbExternalProgress()) + elif func == 'import_db_external_progress_bar': + print(importDbExternalProgressBar()) + elif func == 'delete_db_backup': + print(deleteDbBackup()) + elif func == 'get_db_backup_list': + print(getDbBackupList()) + elif func == 'get_db_backup_import_list': + print(getDbBackupImportList()) + elif func == 'add_db': + print(addDb()) + elif func == 'del_db': + print(delDb()) + elif func == 'sync_get_databases': + print(syncGetDatabases()) + elif func == 'sync_to_databases': + print(syncToDatabases()) + elif func == 'set_root_pwd': + print(setRootPwd(version)) + elif func == 'set_user_pwd': + print(setUserPwd(version)) + elif func == 'get_db_access': + print(getDbAccess()) + elif func == 'set_db_access': + print(setDbAccess()) + elif func == 'fix_db_access': + print(fixDbAccess(version)) + elif func == 'fix_db_access2': + print(fixDbAccess2(version)) + elif func == 'set_db_rw': + print(setDbRw(version)) + elif func == 'set_db_ps': + print(setDbPs()) + elif func == 'get_db_info': + print(getDbInfo()) + elif func == 'repair_table': + print(repairTable()) + elif func == 'opt_table': + print(optTable()) + elif func == 'alter_table': + print(alterTable()) + elif func == 'get_total_statistics': + print(getTotalStatistics()) + elif func == 'get_dbrun_mode': + print(getDbrunMode(version)) + elif func == 'set_dbrun_mode': + print(setDbrunMode(version)) + elif func == 'reset_master': + print(resetMaster(version)) + elif func == 'get_masterdb_list': + print(getMasterDbList(version)) + elif func == 'get_master_status': + print(getMasterStatus(version)) + elif func == 'set_master_status': + print(setMasterStatus(version)) + elif func == 'set_db_master': + print(setDbMaster(version)) + elif func == 'set_db_slave': + print(setDbSlave(version)) + elif func == 'set_dbmaster_access': + print(setDbMasterAccess()) + elif func == 'get_master_rep_slave_list': + print(getMasterRepSlaveList(version)) + elif func == 'add_master_rep_slave_user': + print(addMasterRepSlaveUser(version)) + elif func == 'del_master_rep_slave_user': + print(delMasterRepSlaveUser(version)) + elif func == 'update_master_rep_slave_user': + print(updateMasterRepSlaveUser(version)) + elif func == 'get_master_rep_slave_user_cmd': + print(getMasterRepSlaveUserCmd(version)) + elif func == 'get_slave_list': + print(getSlaveList(version)) + elif func == 'try_slave_sync_bugfix': + print(trySlaveSyncBugfix(version)) + elif func == 'get_slave_sync_cmd': + print(getSlaveSyncCmd(version)) + elif func == 'get_slave_ssh_list': + print(getSlaveSSHList(version)) + elif func == 'get_slave_ssh_by_ip': + print(getSlaveSSHByIp(version)) + elif func == 'add_slave_ssh': + print(addSlaveSSH(version)) + elif func == 'del_slave_ssh': + print(delSlaveSSH(version)) + elif func == 'update_slave_ssh': + print(updateSlaveSSH(version)) + elif func == 'get_slave_sync_user_list': + print(getSlaveSyncUserList(version)) + elif func == 'get_slave_sync_user_by_ip': + print(getSlaveSyncUserByIp(version)) + elif func == 'add_slave_sync_user': + print(addSlaveSyncUser(version)) + elif func == 'del_slave_sync_user': + print(delSlaveSyncUser(version)) + elif func == 'get_slave_sync_mode': + print(getSlaveSyncMode(version)) + elif func == 'set_slave_sync_mode': + print(setSlaveSyncMode(version)) + elif func == 'init_slave_status': + print(initSlaveStatus(version)) + elif func == 'set_slave_status': + print(setSlaveStatus(version)) + elif func == 'delete_slave': + print(deleteSlave(version)) + elif func == 'full_sync': + print(fullSync(version)) + elif func == 'do_full_sync': + print(doFullSync(version)) + elif func == 'full_sync_cmd': + print(fullSyncCmd()) + elif func == 'dump_mysql_data': + print(dumpMysqlData(version)) + elif func == 'sync_database_repair': + print(syncDatabaseRepair()) + elif func == 'sync_database_repair_log': + print(syncDatabaseRepairLog()) + else: + print('error') diff --git a/plugins/mysql-community/index_mysql_community.py b/plugins/mysql-community/index_mysql_community.py new file mode 100644 index 0000000000..0c32680705 --- /dev/null +++ b/plugins/mysql-community/index_mysql_community.py @@ -0,0 +1,189 @@ +# coding:utf-8 + +import sys +import io +import os +import time +import subprocess +import re +import json + +web_dir = os.getcwd() + "/web" +if os.path.exists(web_dir): + sys.path.append(web_dir) + os.chdir(web_dir) + +import core.mw as mw + +# if mw.isAppleSystem(): +# cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\'' +# info = mw.execShell(cmd) +# p = "/usr/local/lib/" + info[0].strip() + "/site-packages" +# sys.path.append(p) + + +app_debug = False +if mw.isAppleSystem(): + app_debug = True + + +def getPluginName(): + return 'mysql-community' + + +def getPluginDir(): + return mw.getPluginDir() + '/' + getPluginName() + + +def getSPluginDir(): + return '/www/server/mdserver-web/plugins/' + getPluginName() + + +def getServerDir(): + return mw.getServerDir() + '/' + getPluginName() + + +def getConf(): + path = getServerDir() + '/etc/my.cnf' + return path + + +def getDataDir(): + file = getConf() + content = mw.readFile(file) + rep = r'datadir\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + + +def getRelayLogName(): + file = getConf() + content = mw.readFile(file) + rep = r'relay-log\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + + +def getLogBinName(): + file = getConf() + content = mw.readFile(file) + rep = r'log-bin\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + + +def binLogListLook(args): + + file = args['file'] + line = args['line'] + + data_dir = getDataDir() + my_bin = getServerDir() + '/bin' + my_binlog_cmd = my_bin + '/mysqlbinlog' + + cmd = my_binlog_cmd + ' --no-defaults ' + \ + data_dir + '/' + file + '|tail -' + str(line) + + data = mw.execShell(cmd) + + rdata = {} + rdata['cmd'] = cmd + rdata['data'] = data[0] + + return rdata + + +def binLogListLookDecode(args): + + file = args['file'] + line = args['line'] + + data_dir = getDataDir() + my_bin = getServerDir() + '/bin' + my_binlog_cmd = my_bin + '/mysqlbinlog' + + cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ + data_dir + '/' + file + '|tail -' + str(line) + + data = mw.execShell(cmd) + + rdata = {} + rdata['cmd'] = cmd + rdata['data'] = data[0] + + return rdata + + +def binLogListTraceRelay(args): + rdata = {} + file = args['file'] + line = args['line'] + + relay_name = getRelayLogName() + data_dir = getDataDir() + alist = os.listdir(data_dir) + relay_list = [] + for x in range(len(alist)): + f = alist[x] + t = {} + if f.startswith(relay_name) and not f.endswith('.index'): + relay_list.append(f) + + relay_list = sorted(relay_list, reverse=True) + if len(relay_list) == 0: + rdata['cmd'] = '' + rdata['data'] = '无Relay日志' + return rdata + + file = relay_list[0] + + my_bin = getServerDir() + '/bin' + my_binlog_cmd = my_bin + '/mysqlbinlog' + + cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ + data_dir + '/' + file + '|tail -' + str(line) + + data = mw.execShell(cmd) + + rdata['cmd'] = cmd + rdata['data'] = data[0] + + return rdata + + +def binLogListTraceBinLog(args): + rdata = {} + file = args['file'] + line = args['line'] + + data_dir = getDataDir() + log_bin_name = getLogBinName() + + alist = os.listdir(data_dir) + log_bin_l = [] + for x in range(len(alist)): + f = alist[x] + t = {} + if f.startswith(log_bin_name) and not f.endswith('.index'): + log_bin_l.append(f) + + if len(log_bin_l) == 0: + rdata['cmd'] = '' + rdata['data'] = '无BINLOG' + return rdata + + log_bin_l = sorted(log_bin_l, reverse=True) + file = log_bin_l[0] + + my_bin = getServerDir() + '/bin' + my_binlog_cmd = my_bin + '/mysqlbinlog' + + cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ + data_dir + '/' + file + '|tail -' + str(line) + + data = mw.execShell(cmd) + + rdata['cmd'] = cmd + rdata['data'] = data[0] + + return rdata diff --git a/plugins/mysql-community/info.json b/plugins/mysql-community/info.json new file mode 100755 index 0000000000..eb8c9c367e --- /dev/null +++ b/plugins/mysql-community/info.json @@ -0,0 +1,19 @@ +{ + "hook":["database"], + "title":"MySQL[Tar]", + "tip":"soft", + "name":"mysql-community", + "type":"运行环境", + "ps":"一种关系数据库管理系统(极速安装)", + "todo_versions":["5.7","8.0"], + "versions":["5.7","8.0","8.2","8.3","8.4","9.0","9.1"], + "shell":"install.sh", + "install_pre_inspection":true, + "uninstall_pre_inspection":true, + "checks":"server/mysql-community", + "path":"server/mysql-community", + "author":"mysql", + "home":"https://dev.mysql.com/downloads/mysql", + "date":"2022-06-29", + "pid": "6" +} \ No newline at end of file diff --git a/plugins/mysql-community/init.d/mysql5.7.service.tpl b/plugins/mysql-community/init.d/mysql5.7.service.tpl new file mode 100644 index 0000000000..dad046923f --- /dev/null +++ b/plugins/mysql-community/init.d/mysql5.7.service.tpl @@ -0,0 +1,43 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +After=network.target + +[Service] +User=mysql +Group=mysql +Type=simple +PermissionsStartOnly=true +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 5000 +Restart=on-failure +RestartPreventExitStatus=1 +RuntimeDirectory=mysqld +RuntimeDirectoryMode=755 + +[Install] +WantedBy=multi-user.target diff --git a/plugins/mysql-community/init.d/mysql8.0.service.tpl b/plugins/mysql-community/init.d/mysql8.0.service.tpl new file mode 100644 index 0000000000..0672790163 --- /dev/null +++ b/plugins/mysql-community/init.d/mysql8.0.service.tpl @@ -0,0 +1,50 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +Documentation=man:mysqld(8) +Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html +After=network.target + +[Install] +WantedBy=multi-user.target + +[Service] +User=mysql +Group=mysql +Type=notify +#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 10000 +Restart=on-failure +RestartPreventExitStatus=1 + +# Always restart when mysqld exits with exit code of 16. This special exit code +# is used by mysqld for RESTART SQL. +RestartForceExitStatus=16 + +# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. +Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-community/init.d/mysql8.1.service.tpl b/plugins/mysql-community/init.d/mysql8.1.service.tpl new file mode 100644 index 0000000000..0672790163 --- /dev/null +++ b/plugins/mysql-community/init.d/mysql8.1.service.tpl @@ -0,0 +1,50 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +Documentation=man:mysqld(8) +Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html +After=network.target + +[Install] +WantedBy=multi-user.target + +[Service] +User=mysql +Group=mysql +Type=notify +#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 10000 +Restart=on-failure +RestartPreventExitStatus=1 + +# Always restart when mysqld exits with exit code of 16. This special exit code +# is used by mysqld for RESTART SQL. +RestartForceExitStatus=16 + +# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. +Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-community/init.d/mysql8.2.service.tpl b/plugins/mysql-community/init.d/mysql8.2.service.tpl new file mode 100644 index 0000000000..0672790163 --- /dev/null +++ b/plugins/mysql-community/init.d/mysql8.2.service.tpl @@ -0,0 +1,50 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +Documentation=man:mysqld(8) +Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html +After=network.target + +[Install] +WantedBy=multi-user.target + +[Service] +User=mysql +Group=mysql +Type=notify +#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 10000 +Restart=on-failure +RestartPreventExitStatus=1 + +# Always restart when mysqld exits with exit code of 16. This special exit code +# is used by mysqld for RESTART SQL. +RestartForceExitStatus=16 + +# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. +Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-community/init.d/mysql8.3.service.tpl b/plugins/mysql-community/init.d/mysql8.3.service.tpl new file mode 100644 index 0000000000..0672790163 --- /dev/null +++ b/plugins/mysql-community/init.d/mysql8.3.service.tpl @@ -0,0 +1,50 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +Documentation=man:mysqld(8) +Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html +After=network.target + +[Install] +WantedBy=multi-user.target + +[Service] +User=mysql +Group=mysql +Type=notify +#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 10000 +Restart=on-failure +RestartPreventExitStatus=1 + +# Always restart when mysqld exits with exit code of 16. This special exit code +# is used by mysqld for RESTART SQL. +RestartForceExitStatus=16 + +# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. +Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-community/init.d/mysql8.4.service.tpl b/plugins/mysql-community/init.d/mysql8.4.service.tpl new file mode 100644 index 0000000000..9de86ce288 --- /dev/null +++ b/plugins/mysql-community/init.d/mysql8.4.service.tpl @@ -0,0 +1,49 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +Documentation=man:mysqld(8) +Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html +After=network.target + +[Install] +WantedBy=multi-user.target + +[Service] +User=mysql +Group=mysql +Type=notify +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 10000 +Restart=on-failure +RestartPreventExitStatus=1 + +# Always restart when mysqld exits with exit code of 16. This special exit code +# is used by mysqld for RESTART SQL. +RestartForceExitStatus=16 + +# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. +Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-community/init.d/mysql9.0.service.tpl b/plugins/mysql-community/init.d/mysql9.0.service.tpl new file mode 100644 index 0000000000..9de86ce288 --- /dev/null +++ b/plugins/mysql-community/init.d/mysql9.0.service.tpl @@ -0,0 +1,49 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +Documentation=man:mysqld(8) +Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html +After=network.target + +[Install] +WantedBy=multi-user.target + +[Service] +User=mysql +Group=mysql +Type=notify +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 10000 +Restart=on-failure +RestartPreventExitStatus=1 + +# Always restart when mysqld exits with exit code of 16. This special exit code +# is used by mysqld for RESTART SQL. +RestartForceExitStatus=16 + +# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. +Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-community/init.d/mysql9.1.service.tpl b/plugins/mysql-community/init.d/mysql9.1.service.tpl new file mode 100644 index 0000000000..9de86ce288 --- /dev/null +++ b/plugins/mysql-community/init.d/mysql9.1.service.tpl @@ -0,0 +1,49 @@ +# Copyright (c) 2015, 2022, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License, version 2.0, +# as published by the Free Software Foundation. +# +# This program is also distributed with certain software (including +# but not limited to OpenSSL) that is licensed under separate terms, +# as designated in a particular file or component or in included license +# documentation. The authors of MySQL hereby grant you an additional +# permission to link the program and your derivative works with the +# separately licensed software that they have included with MySQL. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License, version 2.0, for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# MySQL systemd service file + +[Unit] +Description=MySQL Community Server +Documentation=man:mysqld(8) +Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html +After=network.target + +[Install] +WantedBy=multi-user.target + +[Service] +User=mysql +Group=mysql +Type=notify +ExecStart={$SERVER_PATH}/mysql-community/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-community/etc/my.cnf +TimeoutSec=600 +LimitNOFILE = 10000 +Restart=on-failure +RestartPreventExitStatus=1 + +# Always restart when mysqld exits with exit code of 16. This special exit code +# is used by mysqld for RESTART SQL. +RestartForceExitStatus=16 + +# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. +Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-community/install.sh b/plugins/mysql-community/install.sh new file mode 100755 index 0000000000..16c9ad7d0c --- /dev/null +++ b/plugins/mysql-community/install.sh @@ -0,0 +1,71 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") + +# https://dev.mysql.com/downloads/mysql/ +# https://downloads.mysql.com/archives/community/ + + +# /www/server/mysql-community/bin/mysqld --basedir=/www/server/mysql-community --datadir=/www/server/mysql-community/data --initialize-insecure --explicit_defaults_for_timestamp + + +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 8.0 +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh uninstall 8.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 5.7 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py fix_db_access +# cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql/index.py do_full_sync {"db":"xxx","sign":"","begin":1} + +action=$1 +type=$2 + +if id mysql &> /dev/null ;then + echo "mysql UID is `id -u mysql`" + echo "mysql Shell is `grep "^mysql:" /etc/passwd |cut -d':' -f7 `" +else + groupadd mysql + useradd -g mysql -s /usr/sbin/nologin mysql +fi + + +if [ "${2}" == "" ];then + echo '缺少安装脚本...' + exit 0 +fi + +if [ ! -d $curPath/versions/$2 ];then + echo '缺少安装脚本2...' + exit 0 +fi + +if [ "${action}" == "uninstall" ];then + + cd ${rootPath} && python3 ${rootPath}/plugins/mysql-community/index.py stop ${type} + cd ${rootPath} && python3 ${rootPath}/plugins/mysql-community/index.py initd_uninstall ${type} + cd $curPath + + if [ -f /usr/lib/systemd/system/mysql-community.service ] || [ -f /lib/systemd/system/mysql-community.service ];then + systemctl stop mysql-community + systemctl disable mysql-community + rm -rf /usr/lib/systemd/system/mysql-community.service + rm -rf /lib/systemd/system/mysql-community.service + systemctl daemon-reload + fi +fi + + +sh -x $curPath/versions/$2/install_generic.sh $1 + +if [ "${action}" == "install" ];then + #初始化 + + if [ "$?" != "0" ];then + exit $? + fi + cd ${rootPath} && python3 ${rootPath}/plugins/mysql-community/index.py start ${type} + cd ${rootPath} && python3 ${rootPath}/plugins/mysql-community/index.py initd_install ${type} +fi diff --git a/plugins/mysql-community/js/mysql-community.js b/plugins/mysql-community/js/mysql-community.js new file mode 100755 index 0000000000..3d1fb3169c --- /dev/null +++ b/plugins/mysql-community/js/mysql-community.js @@ -0,0 +1,2968 @@ + +function myPost(method,args,callback, title){ + + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(toArrayObject(args)); + } else { + _args = JSON.stringify(args); + } + + var _title = '正在获取...'; + if (typeof(title) != 'undefined'){ + _title = title; + } + + var loadT = layer.msg(_title, { icon: 16, time: 0, shade: 0.3 }); + $.post('/plugins/run', {name:'mysql-community', func:method, args:_args}, function(data) { + layer.close(loadT); + if (!data.status){ + layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function myPostN(method,args,callback, title){ + + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(toArrayObject(args)); + } else { + _args = JSON.stringify(args); + } + + var _title = '正在获取...'; + if (typeof(title) != 'undefined'){ + _title = title; + } + $.post('/plugins/run', {name:'mysql-community', func:method, args:_args}, function(data) { + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function myAsyncPost(method,args){ + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(toArrayObject(args)); + } else { + _args = JSON.stringify(args); + } + + var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); + return syncPost('/plugins/run', {name:'mysql-community', func:method, args:_args}); +} + + +function myPostCallbak(method, version, args,callback){ + var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); + + var req_data = {}; + req_data['name'] = 'mysql-community'; + req_data['func'] = method; + req_data['script']='index_mysql_community'; + args['version'] = version; + + + if (typeof(args) == 'string' && args == ''){ + req_data['args'] = JSON.stringify(toArrayObject(args)); + } else { + req_data['args'] = JSON.stringify(args); + } + + $.post('/plugins/callback', req_data, function(data) { + layer.close(loadT); + if (!data.status){ + layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function myPostCallbakN(method, version, args,callback){ + + var req_data = {}; + req_data['name'] = 'mysql-community'; + req_data['func'] = method; + req_data['script']='index_mysql_community'; + args['version'] = version; + + + if (typeof(args) == 'string' && args == ''){ + req_data['args'] = JSON.stringify(toArrayObject(args)); + } else { + req_data['args'] = JSON.stringify(args); + } + + $.post('/plugins/callback', req_data, function(data) { + if (!data.status){ + layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function vaildPhpmyadmin(url,username,password){ + // console.log("Authorization: Basic " + btoa(username + ":" + password)); + $.ajax({ + type: "GET", + url: url, + dataType: 'json', + async: false, + username:username, + password:password, + headers: { + "Authorization": "Basic " + btoa(username + ":" + password) + }, + data: 'vaild', + success: function (){ + alert('Thanks for your comment!'); + } + }); +} + +function runInfo(){ + myPost('run_info','',function(data){ + + var rdata = $.parseJSON(data.data); + if (typeof(rdata['status']) != 'undefined'){ + layer.msg(rdata['msg'],{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + // Com_select , Qcache_inserts + var cache_size = ((parseInt(rdata.Qcache_hits) / (parseInt(rdata.Qcache_hits) + parseInt(rdata.Qcache_inserts))) * 100).toFixed(2) + '%'; + if (cache_size == 'NaN%') cache_size = 'OFF'; + var Con = '
\ + \ + \ + \ + \ + \ + \ +
启动时间' + getLocalTime(rdata.Run) + '每秒查询' + parseInt(rdata.Questions / rdata.Uptime) + '
总连接次数' + rdata.Connections + '每秒事务' + parseInt((parseInt(rdata.Com_commit) + parseInt(rdata.Com_rollback)) / rdata.Uptime) + '
发送' + toSize(rdata.Bytes_sent) + 'File' + rdata.File + '
接收' + toSize(rdata.Bytes_received) + 'Position' + rdata.Position + '
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
活动/峰值连接数' + rdata.Threads_running + '/' + rdata.Max_used_connections + '若值过大,增加max_connections
线程缓存命中率' + ((1 - rdata.Threads_created / rdata.Connections) * 100).toFixed(2) + '%若过低,增加thread_cache_size
索引命中率' + ((1 - rdata.Key_reads / rdata.Key_read_requests) * 100).toFixed(2) + '%若过低,增加key_buffer_size
Innodb索引命中率' + (rdata.Innodb_buffer_pool_read_requests / (rdata.Innodb_buffer_pool_read_requests+rdata.Innodb_buffer_pool_reads)).toFixed(2) + '%若过低,增加innodb_buffer_pool_size
查询缓存命中率' + cache_size + '' + lan.soft.mysql_status_ps5 + '
创建临时表到磁盘' + ((rdata.Created_tmp_disk_tables / rdata.Created_tmp_tables) * 100).toFixed(2) + '%若过大,尝试增加tmp_table_size
已打开的表' + rdata.Open_tables + '若过大,增加table_cache_size
没有使用索引的量' + rdata.Select_full_join + '若不为0,请检查数据表的索引是否合理
没有索引的JOIN量' + rdata.Select_range_check + '若不为0,请检查数据表的索引是否合理
排序后的合并次数' + rdata.Sort_merge_passes + '若值过大,增加sort_buffer_size
锁表次数' + rdata.Table_locks_waited + '若值过大,请考虑增加您的数据库性能
'; + $(".soft-man-con").html(Con); + }); +} + + +function myDbPos(){ + myPost('my_db_pos','',function(data){ + var con = '
\ +
\ + \ + \ + \ +
'; + $(".soft-man-con").html(con); + + $('#btn_change_path').click(function(){ + var datadir = $("input[name='datadir']").val(); + myPost('set_db_pos','datadir='+datadir,function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,time:2000,shade: [0.3, '#000']}); + }); + }); + }); +} + +function myPort(){ + myPost('my_port','',function(data){ + var con = '
\ +
\ + \ + \ +
'; + $(".soft-man-con").html(con); + + $('#btn_change_port').click(function(){ + var port = $("input[name='port']").val(); + myPost('set_my_port','port='+port,function(data){ + var rdata = $.parseJSON(data.data); + if (rdata.status){ + layer.msg('修改成功!',{icon:1,time:2000,shade: [0.3, '#000']}); + } else { + layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']}); + } + }); + }); + }); +} + +//数据库配置状态 +function myPerfOpt() { + //获取MySQL配置 + myPost('db_status','',function(data){ + var rdata = $.parseJSON(data.data); + if ( typeof(rdata.status) != 'undefined' && !rdata.status){ + layer.msg(rdata.msg, {icon:2}); + return; + } + + + // console.log(rdata); + var key_buffer_size = toSizeM(rdata.mem.key_buffer_size); + var query_cache_size = toSizeM(rdata.mem.query_cache_size); + var tmp_table_size = toSizeM(rdata.mem.tmp_table_size); + var innodb_buffer_pool_size = toSizeM(rdata.mem.innodb_buffer_pool_size); + var innodb_additional_mem_pool_size = toSizeM(rdata.mem.innodb_additional_mem_pool_size); + var innodb_log_buffer_size = toSizeM(rdata.mem.innodb_log_buffer_size); + + var sort_buffer_size = toSizeM(rdata.mem.sort_buffer_size); + var read_buffer_size = toSizeM(rdata.mem.read_buffer_size); + var read_rnd_buffer_size = toSizeM(rdata.mem.read_rnd_buffer_size); + var join_buffer_size = toSizeM(rdata.mem.join_buffer_size); + var thread_stack = toSizeM(rdata.mem.thread_stack); + var binlog_cache_size = toSizeM(rdata.mem.binlog_cache_size); + + var a = key_buffer_size + query_cache_size + tmp_table_size + innodb_buffer_pool_size + innodb_additional_mem_pool_size + innodb_log_buffer_size; + var b = sort_buffer_size + read_buffer_size + read_rnd_buffer_size + join_buffer_size + thread_stack + binlog_cache_size; + var memSize = a + rdata.mem.max_connections * b; + + + var memCon = '
\ +
最大使用内存: \ + \ + ' + lan.soft.mysql_set_maxmem + ': MB\ +
\ +

key_buffer_sizeMB, ' + lan.soft.mysql_set_key_buffer_size + '

\ +

query_cache_sizeMB, ' + lan.soft.mysql_set_query_cache_size + '

\ +

tmp_table_sizeMB, ' + lan.soft.mysql_set_tmp_table_size + '

\ +

innodb_buffer_pool_sizeMB, ' + lan.soft.mysql_set_innodb_buffer_pool_size + '

\ +

innodb_log_buffer_sizeMB, ' + lan.soft.mysql_set_innodb_log_buffer_size + '

\ +

innodb_additional_mem_pool_sizeMB

\ +

sort_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_sort_buffer_size + '

\ +

read_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_read_buffer_size + '

\ +

read_rnd_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_read_rnd_buffer_size + '

\ +

join_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_join_buffer_size + '

\ +

thread_stackKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_thread_stack + '

\ +

binlog_cache_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_binlog_cache_size + '

\ +

thread_cache_size ' + lan.soft.mysql_set_thread_cache_size + '

\ +

table_open_cache ' + lan.soft.mysql_set_table_open_cache + '

\ +

max_connections ' + lan.soft.mysql_set_max_connections + '

\ +
\ +
' + + $(".soft-man-con").html(memCon); + + $(".conf_p input[name*='size'],.conf_p input[name='max_connections'],.conf_p input[name='thread_stack']").change(function() { + comMySqlMem(); + }); + + $(".conf_p select[name='mysql_set']").change(function() { + mySQLMemOpt($(this).val()); + comMySqlMem(); + }); + }); +} + +function reBootMySqld(){ + pluginOpService('mysql-apt','restart',''); +} + + +//设置MySQL配置参数 +function setMySQLConf() { + $.post('/system/system_total', '', function(memInfo) { + var memSize = memInfo['memTotal']; + var setSize = parseInt($("input[name='memSize']").val()); + + if(memSize < setSize){ + var errMsg = "错误,内存分配过高!

物理内存: {1}MB
最大使用内存: {2}MB
可能造成的后果: 导致数据库不稳定,甚至无法启动MySQLd服务!"; + var msg = errMsg.replace('{1}',memSize).replace('{2}',setSize); + layer.msg(msg,{icon:2,time:5000}); + return; + } + + var query_cache_size = parseInt($("input[name='query_cache_size']").val()); + var query_cache_type = 0; + if (query_cache_size > 0) { + query_cache_type = 1; + } + var data = { + key_buffer_size: parseInt($("input[name='key_buffer_size']").val()), + query_cache_size: query_cache_size, + query_cache_type: query_cache_type, + tmp_table_size: parseInt($("input[name='tmp_table_size']").val()), + max_heap_table_size: parseInt($("input[name='tmp_table_size']").val()), + innodb_buffer_pool_size: parseInt($("input[name='innodb_buffer_pool_size']").val()), + innodb_log_buffer_size: parseInt($("input[name='innodb_log_buffer_size']").val()), + sort_buffer_size: parseInt($("input[name='sort_buffer_size']").val()), + read_buffer_size: parseInt($("input[name='read_buffer_size']").val()), + read_rnd_buffer_size: parseInt($("input[name='read_rnd_buffer_size']").val()), + join_buffer_size: parseInt($("input[name='join_buffer_size']").val()), + thread_stack: parseInt($("input[name='thread_stack']").val()), + binlog_cache_size: parseInt($("input[name='binlog_cache_size']").val()), + thread_cache_size: parseInt($("input[name='thread_cache_size']").val()), + table_open_cache: parseInt($("input[name='table_open_cache']").val()), + max_connections: parseInt($("input[name='max_connections']").val()) + }; + + myPost('set_db_status', data, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + reBootMySqld(); + },{ icon: rdata.status ? 1 : 2 }); + }); + },'json'); +} + + +//MySQL内存优化方案 +function mySQLMemOpt(opt) { + var query_size = parseInt($("input[name='query_cache_size']").val()); + switch (opt) { + case '0': + $("input[name='key_buffer_size']").val(8); + if (query_size) $("input[name='query_cache_size']").val(4); + $("input[name='tmp_table_size']").val(8); + $("input[name='innodb_buffer_pool_size']").val(16); + $("input[name='sort_buffer_size']").val(256); + $("input[name='read_buffer_size']").val(256); + $("input[name='read_rnd_buffer_size']").val(128); + $("input[name='join_buffer_size']").val(128); + $("input[name='thread_stack']").val(256); + $("input[name='binlog_cache_size']").val(32); + $("input[name='thread_cache_size']").val(4); + $("input[name='table_open_cache']").val(32); + $("input[name='max_connections']").val(500); + break; + case '1': + $("input[name='key_buffer_size']").val(128); + if (query_size) $("input[name='query_cache_size']").val(64); + $("input[name='tmp_table_size']").val(64); + $("input[name='innodb_buffer_pool_size']").val(256); + $("input[name='sort_buffer_size']").val(768); + $("input[name='read_buffer_size']").val(768); + $("input[name='read_rnd_buffer_size']").val(512); + $("input[name='join_buffer_size']").val(1024); + $("input[name='thread_stack']").val(256); + $("input[name='binlog_cache_size']").val(64); + $("input[name='thread_cache_size']").val(64); + $("input[name='table_open_cache']").val(128); + $("input[name='max_connections']").val(100); + break; + case '2': + $("input[name='key_buffer_size']").val(256); + if (query_size) $("input[name='query_cache_size']").val(128); + $("input[name='tmp_table_size']").val(384); + $("input[name='innodb_buffer_pool_size']").val(384); + $("input[name='sort_buffer_size']").val(768); + $("input[name='read_buffer_size']").val(768); + $("input[name='read_rnd_buffer_size']").val(512); + $("input[name='join_buffer_size']").val(2048); + $("input[name='thread_stack']").val(256); + $("input[name='binlog_cache_size']").val(64); + $("input[name='thread_cache_size']").val(96); + $("input[name='table_open_cache']").val(192); + $("input[name='max_connections']").val(200); + break; + case '3': + $("input[name='key_buffer_size']").val(384); + if (query_size) $("input[name='query_cache_size']").val(192); + $("input[name='tmp_table_size']").val(512); + $("input[name='innodb_buffer_pool_size']").val(512); + $("input[name='sort_buffer_size']").val(1024); + $("input[name='read_buffer_size']").val(1024); + $("input[name='read_rnd_buffer_size']").val(768); + $("input[name='join_buffer_size']").val(2048); + $("input[name='thread_stack']").val(256); + $("input[name='binlog_cache_size']").val(128); + $("input[name='thread_cache_size']").val(128); + $("input[name='table_open_cache']").val(384); + $("input[name='max_connections']").val(300); + break; + case '4': + $("input[name='key_buffer_size']").val(512); + if (query_size) $("input[name='query_cache_size']").val(256); + $("input[name='tmp_table_size']").val(1024); + $("input[name='innodb_buffer_pool_size']").val(1024); + $("input[name='sort_buffer_size']").val(2048); + $("input[name='read_buffer_size']").val(2048); + $("input[name='read_rnd_buffer_size']").val(1024); + $("input[name='join_buffer_size']").val(4096); + $("input[name='thread_stack']").val(384); + $("input[name='binlog_cache_size']").val(192); + $("input[name='thread_cache_size']").val(192); + $("input[name='table_open_cache']").val(1024); + $("input[name='max_connections']").val(400); + break; + case '5': + $("input[name='key_buffer_size']").val(1024); + if (query_size) $("input[name='query_cache_size']").val(384); + $("input[name='tmp_table_size']").val(2048); + $("input[name='innodb_buffer_pool_size']").val(4096); + $("input[name='sort_buffer_size']").val(4096); + $("input[name='read_buffer_size']").val(4096); + $("input[name='read_rnd_buffer_size']").val(2048); + $("input[name='join_buffer_size']").val(8192); + $("input[name='thread_stack']").val(512); + $("input[name='binlog_cache_size']").val(256); + $("input[name='thread_cache_size']").val(256); + $("input[name='table_open_cache']").val(2048); + $("input[name='max_connections']").val(500); + break; + } +} + +//计算MySQL内存开销 +function comMySqlMem() { + var key_buffer_size = parseInt($("input[name='key_buffer_size']").val()); + var query_cache_size = parseInt($("input[name='query_cache_size']").val()); + var tmp_table_size = parseInt($("input[name='tmp_table_size']").val()); + var innodb_buffer_pool_size = parseInt($("input[name='innodb_buffer_pool_size']").val()); + var innodb_additional_mem_pool_size = parseInt($("input[name='innodb_additional_mem_pool_size']").val()); + var innodb_log_buffer_size = parseInt($("input[name='innodb_log_buffer_size']").val()); + + var sort_buffer_size = $("input[name='sort_buffer_size']").val() / 1024; + var read_buffer_size = $("input[name='read_buffer_size']").val() / 1024; + var read_rnd_buffer_size = $("input[name='read_rnd_buffer_size']").val() / 1024; + var join_buffer_size = $("input[name='join_buffer_size']").val() / 1024; + var thread_stack = $("input[name='thread_stack']").val() / 1024; + var binlog_cache_size = $("input[name='binlog_cache_size']").val() / 1024; + var max_connections = $("input[name='max_connections']").val(); + + var a = key_buffer_size + query_cache_size + tmp_table_size + innodb_buffer_pool_size + innodb_additional_mem_pool_size + innodb_log_buffer_size + var b = sort_buffer_size + read_buffer_size + read_rnd_buffer_size + join_buffer_size + thread_stack + binlog_cache_size + var memSize = a + max_connections * b + $("input[name='memSize']").val(memSize.toFixed(2)); +} + +function syncGetDatabase(){ + myPost('sync_get_databases', null, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + dbList(); + },{ icon: rdata.status ? 1 : 2 }); + }); +} + +function syncToDatabase(type){ + var data = []; + $('input[type="checkbox"].check:checked').each(function () { + if (!isNaN($(this).val())) data.push($(this).val()); + }); + var postData = 'type='+type+'&ids='+JSON.stringify(data); + myPost('sync_to_databases', postData, function(data){ + var rdata = $.parseJSON(data.data); + // console.log(rdata); + showMsg(rdata.msg,function(){ + dbList(); + },{ icon: rdata.status ? 1 : 2 }); + }); +} + +function setRootPwd(type, pwd){ + if (type==1){ + var password = $("#MyPassword").val(); + myPost('set_root_pwd', {password:password}, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + dbList(); + },{icon: rdata.status ? 1 : 2}); + }); + return; + } + + var index = layer.open({ + type: 1, + area: '500px', + title: '修改数据库密码', + closeBtn: 1, + shift: 5, + btn:["提交", "关闭", "复制ROOT密码", "强制修改"], + shadeClose: true, + content: "

\ +
\ + root密码\ +
\ + \ +
\ +
\ +
", + yes:function(layerIndex){ + var password = $("#MyPassword").val(); + myPost('set_root_pwd', {password:password}, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + layer.close(layerIndex); + dbList(); + },{icon: rdata.status ? 1 : 2}); + }); + }, + btn3:function(){ + var password = $("#MyPassword").val(); + copyText(password); + return false; + }, + btn4:function(layerIndex){ + layer.confirm('强制修改,是为了在重建时使用,确定强制?', { + btn: ['确定', '取消'] + }, function(index, layero){ + layer.close(index); + var password = $("#MyPassword").val(); + myPost('set_root_pwd', {password:password,force:'1'}, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + layer.close(layerIndex); + dbList(); + },{icon: rdata.status ? 1 : 2}); + }); + }); + return false; + } + }); +} + +function showHidePass(obj){ + var a = "glyphicon-eye-open"; + var b = "glyphicon-eye-close"; + + if($(obj).hasClass(a)){ + $(obj).removeClass(a).addClass(b); + $(obj).prev().text($(obj).prev().attr('data-pw')) + } + else{ + $(obj).removeClass(b).addClass(a); + $(obj).prev().text('***'); + } +} + +function checkSelect(){ + setTimeout(function () { + var num = $('input[type="checkbox"].check:checked').length; + // console.log(num); + if (num == 1) { + $('button[batch="true"]').hide(); + $('button[batch="false"]').show(); + }else if (num>1){ + $('button[batch="true"]').show(); + $('button[batch="false"]').show(); + }else{ + $('button[batch="true"]').hide(); + $('button[batch="false"]').hide(); + } + },5) +} + +function setDbRw(id,username,val){ + myPost('set_db_rw',{id:id,username:username,rw:val}, function(data){ + var rdata = $.parseJSON(data.data); + // layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']}); + showMsg(rdata.msg, function(){ + dbList(); + },{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']}, 2000); + + }); +} + +function setDbAccess(username){ + myPost('get_db_access','username='+username, function(data){ + var rdata = $.parseJSON(data.data); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); + return; + } + + var index = layer.open({ + type: 1, + area: '500px', + title: '设置数据库权限', + closeBtn: 1, + shift: 5, + btn:["提交","取消"], + shadeClose: true, + content: "
\ +
\ + 访问权限\ +
\ + \ +
\ +
\ +
", + success:function(){ + if (rdata.msg == '127.0.0.1'){ + $('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true); + } else if (rdata.msg == '%'){ + $('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true); + } else if ( rdata.msg == 'ip' ){ + $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); + $('select[name="dataAccess"]').after(""); + } else { + $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); + $('select[name="dataAccess"]').after(""); + } + + $('select[name="dataAccess"]').change(function(){ + var v = $(this).val(); + if (v == 'ip'){ + $(this).after(""); + } else { + $('#dataAccess_subid').remove(); + } + }); + }, + yes:function(index){ + var data = $("#set_db_access").serialize(); + data = decodeURIComponent(data); + var dataObj = toArrayObject(data); + if(!dataObj['access']){ + dataObj['access'] = dataObj['dataAccess']; + if ( dataObj['dataAccess'] == 'ip'){ + if (dataObj['address']==''){ + layer.msg('IP地址不能空!',{icon:2,shade: [0.3, '#000']}); + return; + } + dataObj['access'] = dataObj['address']; + } + } + dataObj['username'] = username; + myPost('set_db_access', dataObj, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + layer.close(index); + dbList(); + },{icon: rdata.status ? 1 : 2}); + }); + } + }); + + }); +} + +function fixDbAccess(username){ + myPost('fix_db_access', '', function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg,function(){ + dbList(); + },{icon: rdata.status ? 1 : 2}); + }); +} + +function setDbPass(id, username, password){ + layer.open({ + type: 1, + area: '500px', + title: '修改数据库密码', + closeBtn: 1, + shift: 5, + shadeClose: true, + btn:["提交","关闭"], + content: "
\ +
\ + 用户名\ +
\ +
\ +
\ + 密码\ +
\ + \ +
\ +
\ + \ +
", + yes:function(index){ + // var data = $("#mod_pwd").serialize(); + var data = {}; + data['name'] = $('input[name=name]').val(); + data['password'] = $('#MyPassword').val(); + data['id'] = $('input[name=id]').val(); + myPost('set_user_pwd', data, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + layer.close(index); + dbList(); + },{icon: rdata.status ? 1 : 2}); + }); + } + }); +} + +function addDatabase(type){ + layer.open({ + type: 1, + area: '500px', + title: '添加数据库', + closeBtn: 1, + shift: 5, + shadeClose: true, + btn:["提交","关闭"], + content: "
\ +
\ + 数据库名\ +
\ + \ +
\ +
\ +
用户名
\ +
\ + 密码\ +
\ +
\ +
\ + 访问权限\ +
\ + \ +
\ +
\ + \ +
", + success:function(){ + $("input[name='name']").keyup(function(){ + var v = $(this).val(); + $("input[name='db_user']").val(v); + $("input[name='ps']").val(v); + }); + + $('select[name="dataAccess"]').change(function(){ + var v = $(this).val(); + if (v == 'ip'){ + $(this).after(""); + } else { + $('#dataAccess_subid').remove(); + } + }); + }, + yes:function(index) { + var data = $("#add_db").serialize(); + data = decodeURIComponent(data); + var dataObj = toArrayObject(data); + if(!dataObj['address']){ + dataObj['address'] = dataObj['dataAccess']; + } + myPost('add_db', dataObj, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + layer.close(index); + dbList(); + } + },{icon: rdata.status ? 1 : 2}, 2000); + }); + } + }); +} + +function delDb(id, name){ + safeMessage('删除['+name+']','您真的要删除['+name+']吗?',function(){ + var data='id='+id+'&name='+name; + myPost('del_db', data, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + dbList(); + },{icon: rdata.status ? 1 : 2}, 600); + }); + }); +} + +function delDbBatch(){ + var arr = []; + $('input[type="checkbox"].check:checked').each(function () { + var _val = $(this).val(); + var _name = $(this).parent().next().text(); + if (!isNaN(_val)) { + arr.push({'id':_val,'name':_name}); + } + }); + + safeMessage('批量删除数据库','您共选择了[2]个数据库,删除后将无法恢复,真的要删除吗?',function(){ + var i = 0; + $(arr).each(function(){ + var data = myAsyncPost('del_db', this); + var rdata = $.parseJSON(data.data); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:2,time:2000,shade: [0.3, '#000']}); + } + i++; + }); + + var msg = '成功删除['+i+']个数据库!'; + showMsg(msg,function(){ + dbList(); + },{icon: 1}, 600); + }); +} + + +function setDbPs(id, name, obj) { + var _span = $(obj); + var _input = $(""); + _span.hide().after(_input); + _input.focus(); + _input.blur(function(){ + $(this).remove(); + var ps = _input.val(); + _span.text(ps).show(); + var data = {name:name,id:id,ps:ps}; + myPost('set_db_ps', data, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + }); + }); + _input.keyup(function(){ + if(event.keyCode == 13){ + _input.trigger('blur'); + } + }); +} + +function openPhpmyadmin(name,username,password){ + $.post('/plugins/run', {'name':'phpmyadmin','func':'plugins_db_support'}, function(data){ + var rdata = $.parseJSON(data.data); + + if (rdata.data['installed'] != 'ok'){ + layer.msg('phpMyAdmin未安装!',{icon:2,shade: [0.3, '#000']}); + return; + } + + if (rdata.data['status'] != 'start'){ + layer.msg('phpMyAdmin未启动',{icon:2,shade: [0.3, '#000']}); + return; + } + + if (rdata.data['cfg']['choose'] != 'mysql-apt'){ + layer.msg('当前为['+rdata.data['cfg']['choose'] + ']模式,若要使用请修改phpMyAdmin访问切换.',{icon:2,shade: [0.3, '#000']}); + return; + } + var home_page = rdata.data['home_page']; + $("#toPHPMyAdmin").attr('action',home_page); + if($("#toPHPMyAdmin").attr('action').indexOf('phpmyadmin') == -1){ + layer.msg('请先安装phpMyAdmin',{icon:2,shade: [0.3, '#000']}); + setTimeout(function(){ window.location.href = '/soft'; },3000); + return; + } + //检查版本 + bigVer = rdata.data['version']; + if (bigVer>=4.5){ + + setTimeout(function(){ + $("#toPHPMyAdmin").submit(); + },2000); + layer.msg('phpMyAdmin['+data.data+']需要手动登录😭',{icon:16,shade: [0.3, '#000'],time:4000}); + + } else{ + var murl = $("#toPHPMyAdmin").attr('action'); + $("#pma_username").val(username); + $("#pma_password").val(password); + $("#db").val(name); + + layer.msg('正在打开phpMyAdmin',{icon:16,shade: [0.3, '#000'],time:2000}); + + setTimeout(function(){ + $("#toPHPMyAdmin").submit(); + },2000); + } + + },'json'); +} + +function delBackup(filename, name, path){ + if(typeof(path) == "undefined"){ + path = ""; + } + myPost('delete_db_backup',{filename:filename,path:path},function(){ + layer.msg('执行成功!'); + setTimeout(function(){ + setBackupReq(name); + },2000); + }); +} + +function downloadBackup(file){ + window.open('/files/download?filename='+encodeURIComponent(file)); +} + +function importBackup(file,name){ + myPost('import_db_backup',{file:file,name:name}, function(data){ + // console.log(data); + layer.msg('执行成功!'); + }); +} + +function importBackupProgress(file,name){ + myPost('import_db_backup_progress',{file:file,name:name}, function(data){ + var rdata = $.parseJSON(data.data); + layer.open({ + title: "手动导入命令CMD【显示进度】", + area: ['600px', '180px'], + type:1, + closeBtn: 1, + shadeClose: false, + btn:["复制","取消"], + content: '
\ +
\ +
'+rdata.data+'
\ +
\ +
', + success:function(){ + copyText(rdata.data); + }, + yes:function(){ + copyText(rdata.data); + } + }); + }); +} + + +function importDbExternal(file,name){ + myPost('import_db_external',{file:file,name:name}, function(data){ + layer.msg('执行成功!'); + }); +} + +function importDbExternalProgress(file,name){ + myPost('import_db_external_progress',{file:file,name:name}, function(data){ + var rdata = $.parseJSON(data.data); + layer.open({ + title: "手动导入命令CMD【显示进度】", + area: ['600px', '180px'], + type:1, + closeBtn: 1, + shadeClose: false, + btn:["复制","取消"], + content: '
\ +
\ +
'+rdata.data+'
\ +
\ +
', + success:function(){ + copyText(rdata.data); + }, + yes:function(){ + copyText(rdata.data); + } + }); + }); +} + +function setLocalImport(db_name){ + + //上传文件 + function uploadDbFiles(upload_dir){ + var up_db = layer.open({ + type:1, + closeBtn: 1, + title:"上传导入文件["+upload_dir+']', + area: ['500px','300px'], + shadeClose:false, + content:'
\ + \ + \ + \ + \ + \ + \ + 文件编码:\ + \ + \ + \ +
    \ +
    ', + success:function(){ + $('#filesClose').click(function(){ + layer.close(up_db); + }); + } + + }); + uploadStart(function(){ + getList(); + layer.close(up_db); + }); + } + + function getList(){ + myPost('get_db_backup_import_list',{}, function(data){ + var rdata = $.parseJSON(data.data); + + var file_list = rdata.data.list; + var upload_dir = rdata.data.upload_dir; + + var tbody = ''; + for (var i = 0; i < file_list.length; i++) { + tbody += '\ + ' + file_list[i]['name'] + '\ + ' + file_list[i]['size'] + '\ + ' + file_list[i]['time'] + '\ + \ + 导入 | \ + 导入进度 | \ + 删除\ + \ + '; + } + + $('#import_db_file_list').html(tbody); + $('input[name="upload_dir"]').val(upload_dir); + + $("#import_db_file_list .del").on('click',function(){ + var index = $(this).attr('index'); + var filename = file_list[index]["name"]; + myPost('delete_db_backup',{filename:filename,path:upload_dir},function(){ + showMsg('执行成功!', function(){ + getList(); + },{icon:1},2000); + }); + }); + }); + } + + var layerIndex = layer.open({ + type: 1, + title: "从文件导入数据", + area: ['700px', '380px'], + closeBtn: 1, + shadeClose: false, + content: '
    \ +
    \ + \ +
    \ +
    \ + \ +
    \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
    文件名称文件大小备份时间操作
    \ +
    \ +
      \ +
    • 仅支持sql、zip、sql.gz、(tar.gz|gz|tgz)
    • \ +
    • zip、tar.gz压缩包结构:test.zip或test.tar.gz压缩包内,必需包含test.sql
    • \ +
    • 若文件过大,您还可以使用SFTP工具,将数据库文件上传到/www/backup/import
    • \ +
    \ +
    \ +
    ', + success:function(index){ + $('#btn_file_upload').click(function(){ + var upload_dir = $('input[name="upload_dir"]').val(); + uploadDbFiles(upload_dir); + }); + + getList(); + }, + }); + + +} + +function setBackup(db_name){ + var layerIndex = layer.open({ + type: 1, + title: "数据库备份详情", + area: ['700px', '280px'], + closeBtn: 1, + shadeClose: false, + content: '
    \ +
    \ + \ + \ +
    \ +
    \ +
    \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
    文件名称文件大小备份时间操作
    \ +
    \ +
    \ +
    ', + success:function(index){ + $('#btn_backup').click(function(){ + myPost('set_db_backup',{name:db_name}, function(data){ + showMsg('执行成功!', function(){ + setBackupReq(db_name); + }, {icon:1}, 2000); + }); + }); + + $('#btn_local_import').click(function(){ + setLocalImport(db_name); + }); + + setBackupReq(db_name); + }, + }); +} + + +function setBackupReq(db_name, obj){ + myPost('get_db_backup_list', {name:db_name}, function(data){ + var rdata = $.parseJSON(data.data); + var tbody = ''; + for (var i = 0; i < rdata.data.length; i++) { + tbody += '\ + ' + rdata.data[i]['name'] + '\ + ' + rdata.data[i]['size'] + '\ + ' + rdata.data[i]['time'] + '\ + \ + 导入 | \ + 导入进度 | \ + 下载 | \ + 删除\ + \ + '; + } + $('#database_table tbody').html(tbody); + }); +} + +function dbList(page, search){ + var _data = {}; + if (typeof(page) =='undefined'){ + var page = 1; + } + + _data['page'] = page; + _data['page_size'] = 10; + if(typeof(search) != 'undefined'){ + _data['search'] = search; + } + myPost('get_db_list', _data, function(data){ + var rdata = $.parseJSON(data.data); + var list = ''; + for(i in rdata.data){ + list += ''; + list +=''; + list += '' + rdata.data[i]['name'] +''; + list += '' + rdata.data[i]['username'] +''; + list += '' + + '***' + + ''+ + ''+ + ''; + + + list += ''+rdata.data[i]['ps']+''; + list += ''; + + list += ''+(rdata.data[i]['is_backup']?'已备份':'未备份') +' | '; + + var rw = ''; + var rw_change = 'all'; + if (typeof(rdata.data[i]['rw'])!='undefined'){ + var rw_val = '读写'; + if (rdata.data[i]['rw'] == 'all'){ + rw_val = "所有"; + rw_change = 'rw'; + } else if (rdata.data[i]['rw'] == 'rw'){ + rw_val = "读写"; + rw_change = 'r'; + } else if (rdata.data[i]['rw'] == 'r'){ + rw_val = "只读"; + rw_change = 'all'; + } + rw = ''+rw_val+' | '; + } + + + list += '管理 | ' + + '工具 | ' + + '权限 | ' + + rw + + '改密 | ' + + '删除' + + ''; + list += ''; + } + + // + var con = '
    \ + \ + \ + \ + \ + \ + \ + \ + \ +
    \ +
    \ + \ + \ + \ + \ + \ + '+ + // ''+ + '\ + \ + \ + '+ list +'\ +
    数据库名用户名密码备份备注操作
    \ +
    \ +
    \ +
    \ + 同步选中\ + 同步所有\ + 从服务器获取\ +
    \ +
    \ +
    '; + + con += ''; + + $(".soft-man-con").html(con); + $('#databasePage').html(rdata.page); + + readerTableChecked(); + }); +} + + +function myBinRollingLogs(_name, func, _args, line){ + + var file_line = 100; + if ( typeof(line) != 'undefined' ){ + file_line = line; + } + + var reqTimer = null; + + function requestLogs(func,file,line){ + myPostCallbakN(func,'',{'file':file,"line":line}, function(rdata){ + var data = rdata.data.data; + var cmd = rdata.data.cmd; + if(data == '') { + data = '当前没有日志!'; + } + + $('#my_rolling_cmd').html(cmd); + + $('#my_rolling_copy').click(function(){ + copyText(cmd); + }); + + var ebody = ''; + $("#my_rolling_logs").html(ebody); + var ob = document.getElementById('roll_info_log'); + ob.scrollTop = ob.scrollHeight; + }); + } + + + layer.open({ + type: 1, + title: _name + '日志', + area: ['800px','700px'], + end: function(){ + if (reqTimer){ + clearInterval(reqTimer); + } + }, + content:'
    \ +
    \ + \ + \ + \ + \ +
    cmd
    \ +
    \ +
    \ +
    \ + \ +
    ', + success:function(){ + var fileName = _args['file']; + requestLogs(func,fileName,file_line); + reqTimer = setInterval(function(){ + requestLogs(func,fileName,file_line); + },1000); + } + }); +} + +function myBinLogsRender(page){ + var _data = {}; + if (typeof(page) =='undefined'){ + var page = 1; + } + + _data['page'] = page; + _data['page_size'] = 10; + _data['tojs'] = 'myBinLogsRender'; + myPost('binlog_list', _data, function(data){ + var rdata = $.parseJSON(data.data); + // console.log(rdata); + var list = ''; + for(i in rdata.data){ + list += ''; + + list += '' + rdata.data[i]['name'] +''; + list += '' + toSize(rdata.data[i]['size'])+''; + list += '' + rdata.data[i]['time'] +''; + + + list += ''; + list += '查看 | '; + list += '解码查看'; + list += ''; + } + + if (rdata.data.length ==0){ + list = '无数据'; + } + + $("#binlog_list tbody").html(list); + $('#binlog_page').html(rdata.page); + + + $('#binlog_list .look').click(function(){ + var i = $(this).data('index'); + var file = rdata.data[i]['name']; + myBinRollingLogs('查看BINLOG','binLogListLook',{'file':file },100); + }); + + $('#binlog_list .look_decode').click(function(){ + var i = $(this).data('index'); + var file = rdata.data[i]['name']; + myBinRollingLogs('查看解码BINLOG','binLogListLookDecode',{'file':file },100); + }); + }); +} + +function myBinLogs(){ + var con = '
    \ + \ + \ +
    \ +
    \ + \ + \ + \ + \ + \ + \ + \ +
    文件名称大小时间操作
    \ +
    \ +
    \ +
    \ +
    '; + $(".soft-man-con").html(con); + myBinLogsRender(1); + + $('.soft-man-con .relay_trace').click(function(){ + myBinRollingLogs('中继日志跟踪','binLogListTraceRelay',{'file':''},100); + }); + + $('.soft-man-con .binlog_trace').click(function(){ + myBinRollingLogs('最新BINLOG日志跟踪','binLogListTraceBinLog',{'file':''},100); + }); +} + +function myLogs(){ + + myPost('bin_log', {status:1}, function(data){ + var rdata = $.parseJSON(data.data); + + var line_status = "" + if (rdata.status){ + line_status = '\ + '; + } else { + line_status = ''; + } + + var limitCon = '

    \ + 二进制日志 ' + toSize(rdata.msg) + '\ + '+line_status+'\ +

    错误日志

    \ + \ +

    '; + $(".soft-man-con").html(limitCon); + + //设置二进制日志 + $(".btn-bin").click(function () { + myPost('bin_log', 'close=change', function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + setTimeout(function(){myLogs();}, 2000); + }); + }); + + $(".clean-btn-bin").click(function () { + myPost('clean_bin_log', '', function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + setTimeout(function(){myLogs();}, 2000); + }); + }); + + //清空日志 + $(".btn-clear").click(function () { + myPost('error_log', 'close=1', function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + setTimeout(function(){myLogs();}, 2000); + }); + }) + + myPost('error_log', 'p=1', function(data){ + var rdata = $.parseJSON(data.data); + var error_body = ''; + if (rdata.status){ + error_body = rdata.data; + } else { + error_body = rdata.msg; + } + $("#error_log").html(error_body); + var ob = document.getElementById('error_log'); + ob.scrollTop = ob.scrollHeight; + }); + }); +} + + +function repCheckeds(tables) { + var dbs = [] + if (tables) { + dbs.push(tables) + } else { + var db_tools = $("input[value^='dbtools_']"); + for (var i = 0; i < db_tools.length; i++) { + if (db_tools[i].checked) dbs.push(db_tools[i].value.replace('dbtools_', '')); + } + } + + if (dbs.length < 1) { + layer.msg('请至少选择一张表!', { icon: 2 }); + return false; + } + return dbs; +} + +function repDatabase(db_name, tables) { + dbs = repCheckeds(tables); + + myPost('repair_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + repTools(db_name, true); + },'已送修复指令,请稍候...'); +} + + +function optDatabase(db_name, tables) { + dbs = repCheckeds(tables); + + myPost('opt_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + repTools(db_name, true); + },'已送优化指令,请稍候...'); +} + +function toDatabaseType(db_name, tables, type){ + dbs = repCheckeds(tables); + myPost('alter_table', { db_name: db_name, tables: JSON.stringify(dbs),table_type: type }, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + repTools(db_name, true); + }, '已送引擎转换指令,请稍候...'); +} + + +function selectedTools(my_obj, db_name) { + var is_checked = false + + if (my_obj) is_checked = my_obj.checked; + var db_tools = $("input[value^='dbtools_']"); + var n = 0; + for (var i = 0; i < db_tools.length; i++) { + if (my_obj) db_tools[i].checked = is_checked; + if (db_tools[i].checked) n++; + } + if (n > 0) { + var my_btns = '\ + \ + \ + ' + $("#db_tools").html(my_btns); + } else { + $("#db_tools").html(''); + } +} + +function repTools(db_name, res){ + myPost('get_db_info', {name:db_name}, function(data){ + var rdata = $.parseJSON(data.data); + var types = { InnoDB: "MyISAM", MyISAM: "InnoDB" }; + var tbody = ''; + for (var i = 0; i < rdata.tables.length; i++) { + if (!types[rdata.tables[i].type]) continue; + tbody += '\ + \ + ' + rdata.tables[i].table_name + '\ + ' + rdata.tables[i].type + '\ + ' + rdata.tables[i].collation + '\ + ' + rdata.tables[i].rows_count + '\ + ' + rdata.tables[i].data_size + '\ + \ + 修复 |\ + 优化 |\ + 转为' + types[rdata.tables[i].type] + '\ + \ + ' + } + + if (res) { + $(".gztr").html(tbody); + $("#db_tools").html(''); + $("input[type='checkbox']").attr("checked", false); + $(".tools_size").html('大小:' + rdata.data_size); + return; + } + + layer.open({ + type: 1, + title: "MySQL工具箱【" + db_name + "】", + area: ['780px', '580px'], + closeBtn: 1, + shadeClose: false, + content: '
    \ + \ +
    \ +
    \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + ' + tbody + '\ +
    表名引擎字符集行数大小操作
    \ +
    \ +
    \ +
      \ +
    • 【修复】尝试使用REPAIR命令修复损坏的表,仅能做简单修复,若修复不成功请考虑使用myisamchk工具
    • \ +
    • 【优化】执行OPTIMIZE命令,可回收未释放的磁盘空间,建议每月执行一次
    • \ +
    • 【转为InnoDB/MyISAM】转换数据表引擎,建议将所有表转为InnoDB
    • \ +
    ' + }); + tableFixed('database_fix'); + }); +} + + +function setDbMaster(name){ + myPost('set_db_master', {name:name}, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + setTimeout(function(){ + masterOrSlaveConf(); + }, 2000); + }); +} + + +function setDbSlave(name){ + myPost('set_db_slave', {name:name}, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + setTimeout(function(){ + masterOrSlaveConf(); + }, 2000); + }); +} + + +function addMasterRepSlaveUser(){ + layer.open({ + type: 1, + area: '500px', + title: '添加同步账户', + closeBtn: 1, + shift: 5, + shadeClose: true, + btn:["提交","取消"], + content: "
    \ +
    用户名
    \ +
    \ + 密码\ +
    \ +
    \ + \ +
    ", + success:function(){ + $("input[name='name']").keyup(function(){ + var v = $(this).val(); + $("input[name='db_user']").val(v); + $("input[name='ps']").val(v); + }); + + $('select[name="dataAccess"]').change(function(){ + var v = $(this).val(); + if (v == 'ip'){ + $(this).after(""); + } else { + $('#dataAccess_subid').remove(); + } + }); + }, + yes:function(index){ + var data = $("#add_master").serialize(); + data = decodeURIComponent(data); + var dataObj = toArrayObject(data); + if(!dataObj['address']){ + dataObj['address'] = dataObj['dataAccess']; + } + + myPost('add_master_rep_slave_user', dataObj, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + layer.close(index); + if (rdata.status){ + getMasterRepSlaveList(); + } + },{icon: rdata.status ? 1 : 2},600); + }); + } + }); +} + + + +function updateMasterRepSlaveUser(username, password){ + + var index = layer.open({ + type: 1, + area: '500px', + title: '更新账户', + closeBtn: 1, + shift: 5, + shadeClose: true, + content: "
    \ +
    用户名
    \ +
    \ + 密码\ +
    \ +
    \ + \ +
    \ + \ +
    \ +
    ", + }); + + $('#submit_update_master').click(function(){ + var data = $("#update_master").serialize(); + data = decodeURIComponent(data); + var dataObj = toArrayObject(data); + myPost('update_master_rep_slave_user', data, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + getMasterRepSlaveList(); + } + $('.layui-layer-close1').click(); + },{icon: rdata.status ? 1 : 2},600); + }); + }); +} + +function getMasterRepSlaveUserCmd(username, db=''){ + myPost('get_master_rep_slave_user_cmd', {username:username,db:db}, function(data){ + var rdata = $.parseJSON(data.data); + + if (!rdata['status']){ + layer.msg(rdata['msg']); + return; + } + + var cmd = rdata.data['cmd']; + + var loadOpen = layer.open({ + type: 1, + title: '同步命令', + area: '500px', + content:"
    \ +
    "+cmd+"
    \ +
    \ + \ +
    \ +
    ", + }); + }); +} + +function delMasterRepSlaveUser(username){ + myPost('del_master_rep_slave_user', {username:username}, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg, function(){ + getMasterRepSlaveList(); + },{icon: rdata.status ? 1 : 2},1000) + }); +} + + +function setDbMasterAccess(username){ + myPost('get_db_access','username='+username, function(data){ + var rdata = $.parseJSON(data.data); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); + return; + } + + var index = layer.open({ + type: 1, + area: '500px', + title: '设置数据库权限', + closeBtn: 1, + shift: 5, + btn:["提交","取消"], + shadeClose: true, + content: "
    \ +
    \ + 访问权限\ +
    \ + \ +
    \ +
    \ +
    ", + success:function(){ + if (rdata.msg == '127.0.0.1'){ + $('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true); + } else if (rdata.msg == '%'){ + $('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true); + } else if ( rdata.msg == 'ip' ){ + $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); + $('select[name="dataAccess"]').after(""); + } else { + $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); + $('select[name="dataAccess"]').after(""); + } + + $('select[name="dataAccess"]').change(function(){ + var v = $(this).val(); + if (v == 'ip'){ + $(this).after(""); + } else { + $('#dataAccess_subid').remove(); + } + }); + }, + yes:function(index){ + var data = $("#set_db_access").serialize(); + data = decodeURIComponent(data); + var dataObj = toArrayObject(data); + if(!dataObj['access']){ + dataObj['access'] = dataObj['dataAccess']; + if ( dataObj['dataAccess'] == 'ip'){ + if (dataObj['address']==''){ + layer.msg('IP地址不能空!',{icon:2,shade: [0.3, '#000']}); + return; + } + dataObj['access'] = dataObj['address']; + } + } + dataObj['username'] = username; + myPost('set_dbmaster_access', dataObj, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + layer.close(index); + },{icon: rdata.status ? 1 : 2}); + }); + } + }); + + }); +} + + +function resetMaster(){ + myPost('reset_master', '', function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + },{icon: rdata.status ? 1 : 2}); + },'正在执行重置master命令[reset master]'); +} + +function getMasterRepSlaveList(){ + var _data = {}; + if (typeof(page) =='undefined'){ + var page = 1; + } + + _data['page'] = page; + _data['page_size'] = 10; + myPost('get_master_rep_slave_list', _data, function(data){ + // console.log(data); + var rdata = []; + try { + rdata = $.parseJSON(data.data); + } catch(e){ + console.log(e); + } + var list = ''; + // console.log(rdata['data']); + var user_list = rdata['data']; + for (i in user_list) { + // console.log(i); + var name = user_list[i]['username']; + var password = user_list[i]['password']; + list += ''+name+'\ + '+password+'\ + \ + 修改 | \ + 删除 | \ + 权限 | \ + 从库同步命令\ + \ + '; + } + + $('#get_master_rep_slave_list_page tbody').html(list); + $('.dataTables_paginate_4').html(rdata['page']); + }); +} + +function getMasterRepSlaveListPage(){ + var page = '
    '; + page += '
    添加同步账户
    '; + + var loadOpen = layer.open({ + type: 1, + title: '同步账户列表', + area: '500px', + content:"
    \ +
    \ +
    \ + \ + \ +
    用户名密码操作
    \ + "+page +"\ +
    \ +
    ", + success:function(){ + getMasterRepSlaveList(); + } + }); +} + + +function deleteSlave(sign){ + myPost('delete_slave', {sign:sign}, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata['msg'], function(){ + masterOrSlaveConf(); + },{icon:rdata.status?1:2,time:3000},3000); + }); +} + + +function getFullSyncStatus(db){ + var timeId = null; + + myPost('get_slave_list', {page:1,page_size:100}, function(data){ + var rdata = $.parseJSON(data.data); + var rsource = rdata.data; + + if (db == 'ALL' && rsource.length>1){ + layer.msg("多主不支持该模式!",{icon:2}); + return; + } + + var dataSource = ''; + if (rsource.length>1){ + var sourceList = ''; + for (var i = 0; i < rsource.length; i++) { + if ('Channel_Name' in rsource[i]){ + sourceList += ''; + } + } + + dataSource = "

    \ + 同步数据源:\ + \ +

    "; + } + + layer.open({ + type: 1, + title: '全量同步['+db+']', + area: '500px', + content:"
    \ +
    \ + "+dataSource+"\ + \ +
    \ +
    0%
    \ +
    \ +
    \ +
    \ + 开始\ + 手动命令\ +
    \ +
    ", + cancel: function(){ + clearInterval(timeId); + }, + success:function(){ + $('#begin_full_sync').click(function(){ + var val = $(this).data('status'); + var sign = ''; + if (dataSource !=''){ + sign = $('select[name="data_source"]').val(); + } + if (val == 'init'){ + fullSync(db, sign, 1); + timeId = setInterval(function(){ + fullSync(db,sign,0); + }, 1000); + $(this).data('status','starting'); + $('#begin_full_sync').text("同步中"); + } else { + layer.msg("正在同步中..",{icon:0}); + } + }); + + $('#full_sync_cmd').click(function(){ + myPostN('full_sync_cmd', {'db':db,'sign':''}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + layer.open({ + title: "手动执行命令CMD", + area: ['600px', '180px'], + type:1, + closeBtn: 1, + shadeClose: false, + btn:["复制","取消"], + content: '
    \ +
    \ +
    '+rdata.data+'
    \ +
    \ +
    ', + success:function(){ + copyText(rdata.data); + }, + yes:function(){ + copyText(rdata.data); + } + }); + }); + }); + } + }); + }); + + function fullSync(db,sign,begin){ + + myPostN('full_sync', {db:db,sign:sign,begin:begin}, function(data){ + var rdata = $.parseJSON(data.data); + $('#full_msg').text(rdata['msg']); + $('.progress-bar').css('width',rdata['progress']+'%'); + $('.progress-bar').text(rdata['progress']+'%'); + + if (rdata['code']==6 ||rdata['code']<0){ + layer.msg(rdata['msg']); + clearInterval(timeId); + $('#begin_full_sync').text("同步结束,再次同步?"); + $("#begin_full_sync").attr('data-status','init'); + } + }); + } +} + +function dataSyncVerify(db){ + var reqTimer = null; + + function requestLogs(layerIndex){ + myPostN('sync_database_repair_log', {db:db, sign:'',op:'get'}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + + if(!rdata.status) { + layer.close(layerIndex); + layer.msg(rdata.msg,{icon:2, time:2000}); + clearInterval(reqTimer); + return; + }; + + if (rdata.msg == ''){ + rdata.msg = '暂无数据!'; + } + + $("#data_verify_log").html(rdata.msg); + //滚动到最低 + var ob = document.getElementById('data_verify_log'); + ob.scrollTop = ob.scrollHeight; + }); + } + + layer.open({ + type: 1, + title: '同步数据库['+db+']数据校验', + area: '500px', + btn:[ "开始","取消","手动"], + content:"
    \ + "+'
    '+"\
    +            
    ", + cancel: function(){ + if (reqTimer){ + clearInterval(reqTimer); + } + }, + yes:function(index,layer_index){ + myPostN('sync_database_repair_log', {db:db, sign:'',op:'do'}, function(data){}); + layer.msg("执行成功"); + + requestLogs(layer_index); + reqTimer = setInterval(function(){ + requestLogs(layer_index); + },3000); + }, + success:function(){ + }, + btn3: function(){ + myPostN('sync_database_repair_log', {db:db, sign:'',op:'cmd'}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + layer.open({ + title: "手动执行命令CMD", + area: ['600px', '180px'], + type:1, + closeBtn: 1, + shadeClose: false, + btn:["复制","取消"], + content: '
    \ +
    \ +
    '+rdata.data+'
    \ +
    \ +
    ', + success:function(){ + copyText(rdata.data); + }, + yes:function(){ + copyText(rdata.data); + } + }); + }); + return false; + } + + }); +} + +function addSlaveSSH(ip=''){ + + myPost('get_slave_ssh_by_ip', {ip:ip}, function(rdata){ + + var rdata = $.parseJSON(rdata.data); + + var ip = '127.0.0.1'; + var port = "22"; + var id_rsa = ''; + var db_user =''; + + if (rdata.data.length>0){ + ip = rdata.data[0]['ip']; + port = rdata.data[0]['port']; + id_rsa = rdata.data[0]['id_rsa']; + db_user = rdata.data[0]['db_user']; + } + + var index = layer.open({ + type: 1, + area: ['500px','480px'], + title: '添加SSH', + closeBtn: 1, + shift: 5, + shadeClose: true, + btn:["确认","取消"], + content: "
    \ +
    IP
    \ +
    端口
    \ +
    同步账户[DB]
    \ +
    \ + ID_RSA\ +
    \ +
    \ + \ +
    ", + success:function(){ + $('textarea[name="id_rsa"]').html(id_rsa); + }, + yes:function(index){ + var ip = $('input[name="ip"]').val(); + var port = $('input[name="port"]').val(); + var db_user = $('input[name="db_user"]').val(); + var id_rsa = $('textarea[name="id_rsa"]').val(); + + var data = {ip:ip,port:port,id_rsa:id_rsa,db_user:db_user}; + myPost('add_slave_ssh', data, function(data){ + layer.close(index); + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + getSlaveSSHPage(); + } + },{icon: rdata.status ? 1 : 2},600); + }); + } + }); + }); +} + + +function delSlaveSSH(ip){ + myPost('del_slave_ssh', {ip:ip}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + getSlaveSSHPage(); + } + },{icon: rdata.status ? 1 : 2}, 600); + }); +} + + +function delSlaveSyncUser(ip){ + myPost('del_slave_sync_user', {ip:ip}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + getSlaveSyncUserPage(); + } + },{icon: rdata.status ? 1 : 2}, 600); + }); +} + +function getSlaveSSHPage(page=1){ + var _data = {}; + _data['page'] = page; + _data['page_size'] = 5; + _data['tojs'] ='getSlaveSSHPage'; + myPost('get_slave_ssh_list', _data, function(data){ + var layerId = null; + var rdata = []; + try { + rdata = $.parseJSON(data.data); + } catch(e) { + console.log(e); + } + var list = ''; + var ssh_list = rdata['data']; + for (i in ssh_list) { + var ip = ssh_list[i]['ip']; + var port = ssh_list[i]['port']; + + var id_rsa = '未设置'; + if ( ssh_list[i]['port'] != ''){ + id_rsa = '已设置'; + } + + var db_user = '未设置'; + if ( ssh_list[i]['db_user'] != ''){ + db_user = ssh_list[i]['db_user']; + } + + list += ''+ip+'\ + '+port+'\ + '+db_user+'\ + '+id_rsa+'\ + \ + 修改 | \ + 删除\ + \ + '; + } + + $('.get-slave-ssh-list tbody').html(list); + $('.dataTables_paginate_4').html(rdata['page']); + }); +} + + + +function addSlaveSyncUser(ip=''){ + + myPost('get_slave_sync_user_by_ip', {ip:ip}, function(rdata){ + + var rdata = $.parseJSON(rdata.data); + + var ip = '127.0.0.1'; + var port = "22"; + var cmd = ''; + var user = 'input_sync_user'; + var pass = 'input_sync_pwd'; + var mode = '0'; + + if (rdata.data.length>0){ + ip = rdata.data[0]['ip']; + port = rdata.data[0]['port']; + cmd = rdata.data[0]['cmd']; + user = rdata.data[0]['user']; + pass = rdata.data[0]['pass']; + mode = rdata.data[0]['mode']; + } + + var index = layer.open({ + type: 1, + area: ['500px','510px'], + title: '同步账户', + closeBtn: 1, + shift: 5, + shadeClose: true, + btn:["确认","取消"], + content: "
    \ +
    IP
    \ +
    端口
    \ +
    同步账户
    \ +
    同步密码
    \ +
    \ + 同步模式\ +
    \ + \ +
    \ +
    \ +
    \ + CMD[必填]\ +
    \ +
    \ + \ +
    ", + success:function(){ + $('textarea[name="cmd"]').html(cmd); + $('textarea[name="cmd"]').change(function(){ + var val = $(this).val(); + val = val.replace(';',''); + var a = {}; + if (val.toLowerCase().indexOf('for')>0){ + cmd_tmp = val.split('for'); + val = cmd_tmp[0].trim(); + + const channel_str = cmd_tmp[1].trim(); + const ch_reg = /channel \'(.*)\';/; + var match_val = channel_str.match(ch_reg); + if (match_val.length>1){ + a['channel'] = match_val[1]; + } + } + + var vlist = val.split(','); + for (var i in vlist) { + var tmp = toTrim(vlist[i]); + var tmp_a = tmp.split(" "); + var real_tmp = tmp_a[tmp_a.length-1]; + var kv = real_tmp.split("="); + a[kv[0]] = kv[1].replace("'",'').replace("'",''); + } + + if ('MASTER_HOST' in a){ + $('input[name="ip"]').val(a['MASTER_HOST']); + $('input[name="port"]').val(a['MASTER_PORT']); + $('input[name="user"]').val(a['MASTER_USER']); + $('input[name="pass"]').val(a['MASTER_PASSWORD']); + } else { + $('input[name="ip"]').val(a['SOURCE_HOST']); + $('input[name="port"]').val(a['SOURCE_PORT']); + $('input[name="user"]').val(a['SOURCE_USER']); + $('input[name="pass"]').val(a['SOURCE_PASSWORD']); + } + + }); + }, + yes:function(index){ + var ip = $('input[name="ip"]').val(); + var port = $('input[name="port"]').val(); + var user = $('input[name="user"]').val(); + var pass = $('input[name="pass"]').val(); + var cmd = $('textarea[name="cmd"]').val(); + var mode = $('select[name="mode"]').val(); + + var data = {ip:ip,port:port,cmd:cmd,user:user,pass:pass,mode:mode}; + myPost('add_slave_sync_user', data, function(ret_data){ + layer.close(index); + var rdata = $.parseJSON(ret_data.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + getSlaveSyncUserPage(); + } + },{icon: rdata.status ? 1 : 2},600); + }); + } + }); + }); +} + +function getSlaveSyncUserPage(page=1){ + var _data = {}; + _data['page'] = page; + _data['page_size'] = 5; + _data['tojs'] ='getSlaveSyncUserPage'; + myPost('get_slave_sync_user_list', _data, function(data){ + var layerId = null; + var rdata = []; + try { + rdata = $.parseJSON(data.data); + } catch(e) { + console.log(e); + } + + var list = ''; + var user_list = rdata['data']; + for (i in user_list) { + var ip = user_list[i]['ip']; + var port = user_list[i]['port']; + var user = user_list[i]['user']; + var apass = user_list[i]['pass']; + + var cmd = '未设置'; + if (user_list[i]['cmd']!=''){ + cmd = '已设置'; + } + + list += ''+ip+'\ + '+port+'\ + '+user+'\ + '+apass+'\ + '+cmd+'\ + \ + 修改 | \ + 删除\ + \ + '; + } + + $('.get-slave-ssh-list tbody').html(list); + $('.dataTables_paginate_4').html(rdata['page']); + }); +} + +function getSlaveCfg(){ + + myPost('get_slave_sync_mode', '', function(data){ + var rdata = $.parseJSON(data.data); + var mode_none = 'success'; + var mode_ssh = 'danger'; + var mode_sync_user = 'danger'; + if(rdata.status){ + var mode_none = 'danger'; + if (rdata.data == 'ssh'){ + var mode_ssh = 'success'; + var mode_sync_user = 'danger'; + } else { + var mode_ssh = 'danger'; + var mode_sync_user = 'success'; + } + } + + layerId = layer.open({ + type: 1, + title: '同步配置', + area: ['400px','180px'], + content:"
    \ +

    \ + 当前从库同步模式\ + \ + \ + \ + \ +

    \ +
    \ +

    \ + 配置设置\ + \ + \ + \ +

    \ +
    ", + success:function(){ + $('.btn-slave-ssh').click(function(){ + getSlaveSSHList(); + }); + + $('.btn-slave-user').click(function(){ + getSlaveUserList(); + }); + + $('.slave-db-mode').click(function(){ + var _this = this; + var mode = 'none'; + if ($(this).hasClass('btn-ssh')){ + mode = 'ssh'; + } + if ($(this).hasClass('btn-sync-user')){ + mode = 'sync-user'; + } + + myPost('set_slave_sync_mode', {mode:mode}, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + $('.slave-db-mode').remove('btn-success').addClass('btn-danger'); + $(_this).removeClass('btn-danger').addClass('btn-success'); + },{icon:rdata.status?1:2},2000); + }); + + }); + } + }); + }); +} + + +function getSlaveUserList(){ + + var page = '
    '; + page += '
    添加同步账户
    '; + + layerId = layer.open({ + type: 1, + title: '同步账户列表', + area: '600px', + content:"
    \ +
    \ +
    \ + \ + \ +
    IPPORT同步账户同步密码CMD操作
    \ + "+page +"\ +
    \ +
    ", + success:function(){ + getSlaveSyncUserPage(1); + } + }); +} + +function getSlaveSSHList(page=1){ + + var page = '
    '; + page += '
    添加SSH
    '; + + layerId = layer.open({ + type: 1, + title: 'SSH列表', + area: '600px', + content:"
    \ +
    \ +
    \ + \ + \ +
    IPPORT同步账户SSH操作
    \ + "+page +"\ +
    \ +
    ", + success:function(){ + getSlaveSSHPage(1); + } + }); +} + +function handlerRun(){ + myPostN('get_slave_sync_cmd', {}, function(data){ + var rdata = $.parseJSON(data.data); + var cmd = rdata['data']; + var loadOpen = layer.open({ + type: 1, + title: '手动执行', + area: '500px', + content:"
    \ +
    "+cmd+"
    \ +
    \ + \ +
    \ +
    ", + }); + copyPass(cmd); + $('.class-copy-cmd').click(function(){ + copyPass(cmd); + }); + }); +} + +function initSlaveStatus(){ + myPost('init_slave_status', '', function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + masterOrSlaveConf(); + } + },{icon:rdata.status?1:2},2000); + }); +} + +function masterOrSlaveConf(version=''){ + + function getMasterDbList(){ + var _data = {}; + if (typeof(page) =='undefined'){ + var page = 1; + } + + _data['page'] = page; + _data['page_size'] = 10; + + myPost('get_masterdb_list', _data, function(data){ + var rdata = $.parseJSON(data.data); + var list = ''; + for(i in rdata.data){ + list += ''; + list += '' + rdata.data[i]['name'] +''; + list += '' + (rdata.data[i]['master']?'是':'否') +''; + list += '' + + ''+(rdata.data[i]['master']?'退出':'加入')+' | ' + + '同步命令' + + ''; + list += ''; + } + + var con = '
    \ +
    \ + \ + \ + \ + \ + \ + \ + '+ list +'\ +
    数据库名同步操作
    \ +
    \ +
    \ +
    \ + 同步账户列表\ +
    \ +
    '; + + $(".table_master_list").html(con); + $('#databasePage').html(rdata.page); + }); + } + + function getAsyncMasterDbList(){ + var _data = {}; + if (typeof(page) =='undefined'){ + var page = 1; + } + + _data['page'] = page; + _data['page_size'] = 10; + + var mdb_ver = $('.plugin_version').attr('version'); + + myPost('get_slave_list', _data, function(data){ + var rdata = $.parseJSON(data.data); + var list = ''; + + var isHasSign = false; + for(i in rdata.data){ + + var v = rdata.data[i]; + if ('Channel_Name' in v && v['Channel_Name'] !=''){ + isHasSign = true; + } + + var status = "异常"; + if (mdb_ver >= 8){ + + if (v['Replica_SQL_Running'] == 'Yes' && v['Replica_IO_Running'] == 'Yes'){ + status = "正常"; + } + + list += ''; + list += '' + rdata.data[i]['Source_Host'] +''; + list += '' + rdata.data[i]['Source_Port'] +''; + list += '' + rdata.data[i]['Source_User'] +''; + list += '' + rdata.data[i]['Relay_Source_Log_File'] +''; + list += '' + rdata.data[i]['Replica_IO_Running'] +''; + list += '' + rdata.data[i]['Replica_SQL_Running'] +''; + + } else { + if (v['Slave_SQL_Running'] == 'Yes' && v['Slave_IO_Running'] == 'Yes'){ + status = "正常"; + } + + list += ''; + list += '' + rdata.data[i]['Master_Host'] +''; + list += '' + rdata.data[i]['Master_Port'] +''; + list += '' + rdata.data[i]['Master_User'] +''; + list += '' + rdata.data[i]['Master_Log_File'] +''; + list += '' + rdata.data[i]['Slave_IO_Running'] +''; + list += '' + rdata.data[i]['Slave_SQL_Running'] +''; + } + + + if (isHasSign){ + list += '' + v['Channel_Name'] +''; + } + + list += '' + status +''; + list += '' + + '删除' + + ''; + list += ''; + } + + var signThead_th = ''; + if (isHasSign){ + var signThead_th = '标识'; + } + + var con = '
    \ +
    \ + \ + \ + \ + \ + \ + \ + \ + \ + '+signThead_th+'\ + \ + \ + \ + '+ list +'\ +
    主[服务]端口用户日志IOSQL状态操作
    \ +
    \ +
    '; + + //
    \ + //
    \ + // 添加\ + //
    + $(".table_slave_status_list").html(con); + + $(".btn_delete_slave").click(function(){ + var id = $(this).data('id'); + var v = rdata.data[id]; + if ('Channel_Name' in v){ + deleteSlave(v['Channel_Name']); + } else{ + deleteSlave(); + } + }); + + $('.db_error').click(function(){ + var id = $(this).data('id'); + var info = rdata.data[id]; + + var err_line = ""; + err_line +="\ + IO错误\ + "+ (info['Last_IO_Error'] == '' ? '无':info['Last_IO_Error'])+"\ + "; + err_line +="\ + SQL错误\ + "+(info['Last_SQL_Error'] == '' ? '无':info['Last_SQL_Error'])+"\ + "; + + err_line +="\ + 状态\ + "+(info['Slave_SQL_Running_State'] == '' ? '无':info['Slave_SQL_Running_State']) +"\ + "; + + + var btn_list = ['复制错误',"取消"]; + if (info['Last_IO_Error'].search(/1236/i)>0){ + btn_list = ['复制错误',"取消","尝试修复"]; + } + layer.open({ + type: 1, + title: '同步异常信息', + area: ['600px','300px'], + btn:btn_list, + content:"
    \ +
    \ +
    \ + \ + \ + \ + \ + \ + "+ err_line +"\ +
    类型内容
    \ +
    \ +
    \ +
    ", + success:function(){ + if (info['Last_IO_Error'] != ''){ + copyText(info['Last_IO_Error']); + return; + } + + if (info['Last_SQL_Error'] != ''){ + copyText(info['Last_SQL_Error']); + return; + } + + if (info['Slave_SQL_Running_State'] != ''){ + copyText(info['Slave_SQL_Running_State']); + return; + } + }, + yes:function(){ + if (info['Last_IO_Error'] != ''){ + copyText(info['Last_IO_Error']); + return; + } + + if (info['Last_SQL_Error'] != ''){ + copyText(info['Last_SQL_Error']); + return; + } + + if (info['Slave_SQL_Running_State'] != ''){ + copyText(info['Slave_SQL_Running_State']); + return; + } + }, + btn3:function(){ + myPost('try_slave_sync_bugfix', {}, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg, function(){ + masterOrSlaveConf(); + },{ icon: rdata.status ? 1 : 5 },2000); + }); + } + }); + }); + }); + } + + function getAsyncDataList(){ + var _data = {}; + if (typeof(page) =='undefined'){ + var page = 1; + } + + _data['page'] = page; + _data['page_size'] = 10; + myPost('get_masterdb_list', _data, function(data){ + var rdata = $.parseJSON(data.data); + var list = ''; + for(i in rdata.data){ + list += ''; + list += '' + rdata.data[i]['name'] +''; + list += '' + + ''+(rdata.data[i]['slave']?'退出':'加入')+' | ' + + '同步 | ' + + '数据校验' + + ''; + list += ''; + } + + var con = '
    \ +
    \ + \ + \ + \ + \ + \ + '+ list +'\ +
    本地库名操作
    \ +
    \ +
    \ +
    \ + 手动命令\ + 全量同步\ +
    \ +
    '; + + $(".table_slave_list").html(con); + $('#databasePage').html(rdata.page); + }); + } + + + function getMasterStatus(){ + myPost('get_master_status', '', function(rdata){ + var rdata = $.parseJSON(rdata.data); + // console.log('mode:',rdata.data); + if ( typeof(rdata.status) != 'undefined' && !rdata.status && rdata.data == 'pwd'){ + layer.msg(rdata.msg, {icon:2}); + return; + } + + var rdata = rdata.data; + var limitCon = '\ +

    \ + 主从同步模式\ + \ + \ +

    \ +
    \ +

    \ + Master[主]配置\ + \ + \ +

    \ +
    \ + \ +
    \ +
    \ + \ +

    \ + Slave[从]配置\ + \ + \ + \ +

    \ +
    \ + \ +
    \ + \ +
    \ + '; + $(".soft-man-con").html(limitCon); + + //设置主服务器配置 + $(".btn-master").click(function () { + myPost('set_master_status', 'close=change', function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + setTimeout(function(){ + getMasterStatus(); + }, 3000); + }); + }); + + $(".btn-slave").click(function () { + myPost('set_slave_status', 'close=change', function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + setTimeout(function(){ + getMasterStatus(); + }, 3000); + }); + }); + + $('.db-mode').click(function(){ + if ($(this).hasClass('btn-success')){ + //no action + return; + } + + var mode = 'classic'; + if ($(this).hasClass('btn-gtid')){ + mode = 'gtid'; + } + + layer.open({ + type:1, + title:"MySQL主从模式切换", + shadeClose:false, + btnAlign: 'c', + btn: ['切换并重启', '切换不重启'], + yes: function(index, layero){ + this.change(index,mode,"yes"); + + }, + btn2: function(index, layero){ + this.change(index,mode,"no"); + return false; + }, + change:function(index,mode,reload){ + console.log(index,mode,reload); + myPost('set_dbrun_mode',{'mode':mode,'reload':reload},function(data){ + layer.close(index); + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg ,function(){ + getMasterStatus(); + },{ icon: rdata.status ? 1 : 5 }); + }); + } + }); + }); + + if (rdata.status){ + getMasterDbList(); + } + + // if (rdata.slave_status){ + getAsyncMasterDbList(); + getAsyncDataList() + // } + }); + } + getMasterStatus(); +} diff --git a/plugins/mysql-community/scripts/backup.py b/plugins/mysql-community/scripts/backup.py new file mode 100755 index 0000000000..a8073aa00f --- /dev/null +++ b/plugins/mysql-community/scripts/backup.py @@ -0,0 +1,116 @@ +# coding: utf-8 +#----------------------------- +# 网站备份工具 +#----------------------------- + +import sys +import os +import time +import re + +if sys.platform != 'darwin': + os.chdir('/www/server/mdserver-web') + +web_dir = os.getcwd() + "/web" +if os.path.exists(web_dir): + sys.path.append(web_dir) + os.chdir(web_dir) + +import core.mw as mw +import core.db as db + +''' +DEBUG: +python3 /www/server/mdserver-web/plugins/mysql-community/scripts/backup.py database admin 3 +''' +class backupTools: + + def backupDatabase(self, name, count): + db_path = mw.getServerDir() + '/mysql-community' + db_name = 'mysql' + find_name = mw.M('databases').dbPos(db_path, 'mysql').where( + 'name=?', (name,)).getField('name') + startTime = time.time() + if not find_name: + endDate = time.strftime('%Y/%m/%d %X', time.localtime()) + log = "数据库[" + name + "]不存在!" + print("★[" + endDate + "] " + log) + print( + "----------------------------------------------------------------------------") + return + + backup_path = mw.getFatherDir() + '/backup/database/mysql-community' + if not os.path.exists(backup_path): + mw.execShell("mkdir -p " + backup_path) + + filename = backup_path + "/db_" + name + "_" + \ + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + ".sql.gz" + + mysql_root = mw.M('config').dbPos(db_path, db_name).where( + "id=?", (1,)).getField('mysql_root') + + my_conf_path = db_path + '/etc/my.cnf' + mycnf = mw.readFile(my_conf_path) + rep = r"\[mysqldump\]\nuser=root" + sea = "[mysqldump]\n" + subStr = sea + "user=root\npassword=" + mysql_root + "\n" + mycnf = mycnf.replace(sea, subStr) + if len(mycnf) > 100: + mw.writeFile(db_path + '/etc/my.cnf', mycnf) + + cmd = db_path + "/bin/usr/bin/mysqldump --defaults-file=" + my_conf_path + " --single-transaction -q --default-character-set=utf8mb4 " + name + " | gzip > " + filename + mw.execShell(cmd) + + if not os.path.exists(filename): + endDate = time.strftime('%Y/%m/%d %X', time.localtime()) + log = "数据库[" + name + "]备份失败!" + print("★[" + endDate + "] " + log) + print( + "----------------------------------------------------------------------------") + return + + mycnf = mw.readFile(db_path + '/etc/my.cnf') + mycnf = mycnf.replace(subStr, sea) + if len(mycnf) > 100: + mw.writeFile(db_path + '/etc/my.cnf', mycnf) + + endDate = time.strftime('%Y/%m/%d %X', time.localtime()) + outTime = time.time() - startTime + pid = mw.M('databases').dbPos(db_path, db_name).where('name=?', (name,)).getField('id') + + mw.M('backup').add('type,name,pid,filename,add_time,size', (1, os.path.basename(filename), pid, filename, endDate, os.path.getsize(filename))) + log = "数据库[" + name + "]备份成功,用时[" + str(round(outTime, 2)) + "]秒" + mw.writeLog('计划任务', log) + print("★[" + endDate + "] " + log) + print("|---保留最新的[" + count + "]份备份") + print("|---文件名:" + filename) + + # 清理多余备份 + backups = mw.M('backup').where('type=? and pid=?', ('1', pid)).field('id,filename').select() + + num = len(backups) - int(count) + if num > 0: + for backup in backups: + mw.execShell("rm -f " + backup['filename']) + mw.M('backup').where('id=?', (backup['id'],)).delete() + num -= 1 + print("|---已清理过期备份文件:" + backup['filename']) + if num < 1: + break + + def backupDatabaseAll(self, save): + db_path = mw.getServerDir() + '/mysql-community' + db_name = 'mysql' + databases = mw.M('databases').dbPos(db_path, db_name).field('name').select() + for database in databases: + self.backupDatabase(database['name'], save) + + +if __name__ == "__main__": + backup = backupTools() + type = sys.argv[1] + if type == 'database': + if sys.argv[2] == 'ALL': + backup.backupDatabaseAll(sys.argv[3]) + else: + backup.backupDatabase(sys.argv[2], sys.argv[3]) diff --git a/plugins/mysql-community/versions/5.7/install.sh b/plugins/mysql-community/versions/5.7/install.sh new file mode 100755 index 0000000000..1d2a70c432 --- /dev/null +++ b/plugins/mysql-community/versions/5.7/install.sh @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +# debug +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 +# /www/server/mysql-apt/bin/usr/sbin/mysqld --defaults-file=/www/server/mysql-apt/etc/my.cnf --daemonize +# /www/server/mysql-apt/bin/usr/bin/mysql -S /www/server/mysql-apt/mysql.sock -uroot -p + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + +MYSQL_VER=5.7.39 +if [ "$OSNAME" == "debian" ];then + # mysql5.7现在仅有10的编译版 + VERSION_ID="10" +fi + +if [ "$OSNAME" == "ubuntu" ];then + # mysql5.7现在仅有18.04的编译版 + VERSION_ID="18.04" +fi + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 0 +fi + +SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} + +APT_INSTALL() +{ +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt/bin + +wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-5.7/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +apt update -y +apt install -y libnuma1 libaio1 libmecab2 + +# 安装 +dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + + +dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +# 测试时可关闭 +rm -rf $myDir +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '5.7' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/5.7/install_generic.sh b/plugins/mysql-community/versions/5.7/install_generic.sh new file mode 100755 index 0000000000..cd2f003db8 --- /dev/null +++ b/plugins/mysql-community/versions/5.7/install_generic.sh @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=5.7.44 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.12-${OS_ARCH} + +if [ "$OS_ARCH" == "x86_64" ] || [ "$OS_ARCH" == "i686" ];then + echo "ok" +else + echo "暂时不支持该${OS_ARCH}" + exit 0 +fi + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.gz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.gz https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.tar.gz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -zvxf ${myDir}/mysql-${SUFFIX_NAME}.tar.gz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '5.7' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '5.7' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.0/install.sh b/plugins/mysql-community/versions/8.0/install.sh new file mode 100755 index 0000000000..082460a6e7 --- /dev/null +++ b/plugins/mysql-community/versions/8.0/install.sh @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.0 + +# 暂时debian12没有标准版,先用11使用 +# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then +# echo "暂时不支持该${OSNAME}${VERSION_ID}" +# exit 1 +# fi + + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=8.0.39 +SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} + + +# /lib/systemd/system/mysql.service +# /etc/mysql/my.cnf + +APT_INSTALL() +{ +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt/bin + + +mkdir -p /var/run/mysqld +chown mysql -R /var/run/mysqld + +wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +apt update -y +apt install -y libnuma1 libaio1 libmecab2 + +# 安装 +dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + + + +dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +# 测试时可关闭 +rm -rf $myDir +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.0' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.0' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.0/install_generic.sh b/plugins/mysql-community/versions/8.0/install_generic.sh new file mode 100755 index 0000000000..5a080cd694 --- /dev/null +++ b/plugins/mysql-community/versions/8.0/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=8.0.39 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.0 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.0/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.0' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.0' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.2/install.sh b/plugins/mysql-community/versions/8.2/install.sh new file mode 100755 index 0000000000..81cade8267 --- /dev/null +++ b/plugins/mysql-community/versions/8.2/install.sh @@ -0,0 +1,137 @@ + +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 +# cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql-apt/index.py start + +# 暂时debian12没有标准版,先用11使用 +# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then +# echo "暂时不支持该${OSNAME}${VERSION_ID}" +# exit 1 +# fi + + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=8.2.0 +SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} + + +# /lib/systemd/system/mysql.service +# /etc/mysql/my.cnf + +APT_INSTALL() +{ +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt/bin + +mkdir -p /var/run/mysqld +chown mysql -R /var/run/mysqld + +wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.2/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +apt update -y +apt install -y libnuma1 libaio1 libmecab2 + +# 安装 +dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + + + +dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +# 测试时可关闭 +rm -rf $myDir +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.2' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.2' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.2/install_generic.sh b/plugins/mysql-community/versions/8.2/install_generic.sh new file mode 100755 index 0000000000..769c583981 --- /dev/null +++ b/plugins/mysql-community/versions/8.2/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=8.2.0 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.2 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.2 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.2/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.2' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.2' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.3/install.sh b/plugins/mysql-community/versions/8.3/install.sh new file mode 100755 index 0000000000..316ae77edf --- /dev/null +++ b/plugins/mysql-community/versions/8.3/install.sh @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 + +# 暂时debian12没有标准版,先用11使用 +# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then +# echo "暂时不支持该${OSNAME}${VERSION_ID}" +# exit 1 +# fi + + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=8.3.0 +SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} + + +# /lib/systemd/system/mysql.service +# /etc/mysql/my.cnf + +APT_INSTALL() +{ +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt/bin + +mkdir -p /var/run/mysqld +chown mysql -R /var/run/mysqld + +wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.3/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +apt update -y +apt install -y libnuma1 libaio1 libmecab2 + +# 安装 +dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + + + +dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +# 测试时可关闭 +rm -rf $myDir +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.3' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.3' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.3/install_generic.sh b/plugins/mysql-community/versions/8.3/install_generic.sh new file mode 100755 index 0000000000..c451fbd36d --- /dev/null +++ b/plugins/mysql-community/versions/8.3/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=8.3.0 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.3 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.3 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.3/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.3' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.3' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.4/install.sh b/plugins/mysql-community/versions/8.4/install.sh new file mode 100755 index 0000000000..dfcd789980 --- /dev/null +++ b/plugins/mysql-community/versions/8.4/install.sh @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 + +if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then + VERSION_ID="12" +fi + + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=8.4.2 +SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} + + +# /lib/systemd/system/mysql.service +# /etc/mysql/my.cnf + +APT_INSTALL() +{ +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt/bin + +mkdir -p /var/run/mysqld +chown mysql -R /var/run/mysqld + +# https://cdn.mysql.com/archives/mysql-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +# https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +apt update -y +apt install -y libnuma1 libaio1 libmecab2 + +# 安装 +dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + + + +dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +# 测试时可关闭 +rm -rf $myDir +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.4' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.4' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/8.4/install_generic.sh b/plugins/mysql-community/versions/8.4/install_generic.sh new file mode 100755 index 0000000000..5932cb0fa3 --- /dev/null +++ b/plugins/mysql-community/versions/8.4/install_generic.sh @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=8.4.2 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 +APT_INSTALL() +{ + + + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +# https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '8.4' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '8.4' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/9.0/install.sh b/plugins/mysql-community/versions/9.0/install.sh new file mode 100755 index 0000000000..874522d9d4 --- /dev/null +++ b/plugins/mysql-community/versions/9.0/install.sh @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 + +# 暂时debian12没有标准版,先用11使用 +if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then + VERSION_ID="12" +fi + + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=9.0.1 +SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} + + +# /lib/systemd/system/mysql.service +# /etc/mysql/my.cnf + +APT_INSTALL() +{ +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt/bin + +mkdir -p /var/run/mysqld +chown mysql -R /var/run/mysqld + +# https://dev.mysql.com/get/Downloads/MySQL-9.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +# https://cdn.mysql.com/archives/mysql-9.0/mysql-server_9.0.1-1debian12_amd64.deb-bundle.tar + +wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-9.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +# wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +apt update -y +apt install -y libnuma1 libaio1 libmecab2 + +# 安装 +dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + + + +dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +# 测试时可关闭 +rm -rf $myDir +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '9.0' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '9.0' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/9.0/install_generic.sh b/plugins/mysql-community/versions/9.0/install_generic.sh new file mode 100755 index 0000000000..2a8cf58683 --- /dev/null +++ b/plugins/mysql-community/versions/9.0/install_generic.sh @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=9.0.1 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.0 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +# https://cdn.mysql.com/archives/mysql-9.0/mysql-9.0.1-linux-glibc2.28-x86_64.tar.xz +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-9.0/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '9.0' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '9.0' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/9.1/install.sh b/plugins/mysql-community/versions/9.1/install.sh new file mode 100755 index 0000000000..27d3460981 --- /dev/null +++ b/plugins/mysql-community/versions/9.1/install.sh @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.1 +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.1 + +#x-faq +# strings /lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIB + +# debian12 +if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then + VERSION_ID="12" +fi + + +ARCH="amd64" +TMP_ARCH=`arch` +if [ "$TMP_ARCH" == "x86_64" ];then + ARCH="amd64" +elif [ "$TMP_ARCH" == "aarch64" ];then + ARCH="arm64" +else + ARCH="amd64" +fi + +if [ "$ARCH" != "amd64" ];then + echo "暂时不支持该${ARCH}" + exit 1 +fi + + +MYSQL_VER=9.1.0 +SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} + + +# /lib/systemd/system/mysql.service +# /etc/mysql/my.cnf + +APT_INSTALL() +{ + +cd ${rootPath}/plugins/php/lib && /bin/bash openssl_30.sh + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt/bin + +mkdir -p /var/run/mysqld +chown mysql -R /var/run/mysqld + +# https://cdn.mysql.com/archives/mysql-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +# https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar +cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar + +apt update -y +apt install -y libnuma1 libaio1 libmecab2 + +# 安装 +dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + + + +dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin +dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin + +# 测试时可关闭 +rm -rf $myDir +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '9.1' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '9.1' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi diff --git a/plugins/mysql-community/versions/9.1/install_generic.sh b/plugins/mysql-community/versions/9.1/install_generic.sh new file mode 100755 index 0000000000..0c0ea4bb53 --- /dev/null +++ b/plugins/mysql-community/versions/9.1/install_generic.sh @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +#!/bin/bash + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +export DEBIAN_FRONTEND=noninteractive + +# https://downloads.mysql.com/archives/community/ + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +myDir=${serverPath}/source/mysql-apt + +OS_ARCH=`arch` +MYSQL_VER=9.1.0 +SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} + +# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.1 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.1 +APT_INSTALL() +{ + +######## +mkdir -p $myDir +mkdir -p $serverPath/mysql-apt + +# Linux - Generic +# https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz +# https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-${SUFFIX_NAME}.tar.xz +if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then + wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-${SUFFIX_NAME}.tar.xz +fi + +if [ -d ${myDir} ];then + cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt +fi + +# 测试时可关闭 +rm -rf $myDir/mysql-${SUFFIX_NAME} +####### +} + +APT_UNINSTALL() +{ +### +rm -rf $myDir/mysql-${SUFFIX_NAME} +# apt remove -y mysql-server +### +} + + +Install_mysql() +{ + echo '正在安装脚本文件...' + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_INSTALL + fi + + if [ "$?" == "0" ];then + mkdir -p $serverPath/mysql-apt + echo '9.1' > $serverPath/mysql-apt/version.pl + echo '安装完成' + else + echo '9.1' > $serverPath/mysql-apt/version.pl + echo "暂时不支持该系统" + fi +} + +Uninstall_mysql() +{ + + isApt=`which apt` + if [ "$isApt" != "" ];then + APT_UNINSTALL + fi + + rm -rf $serverPath/mysql-apt + echo '卸载完成' +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_mysql +else + Uninstall_mysql +fi From 65c7eeb9c9b748def9d0b7b6a7b5e580d6ec0ecf Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 20:58:26 +0800 Subject: [PATCH 19/40] update --- .../versions/5.7/install_generic.sh | 34 ++++++---------- .../versions/8.0/install_generic.sh | 33 +++++++--------- .../versions/8.2/install_generic.sh | 35 +++++++---------- .../versions/8.3/install_generic.sh | 35 +++++++---------- .../versions/8.4/install_generic.sh | 39 +++++++------------ .../versions/9.0/install_generic.sh | 36 +++++++---------- .../versions/9.1/install_generic.sh | 36 +++++++---------- 7 files changed, 90 insertions(+), 158 deletions(-) diff --git a/plugins/mysql-community/versions/5.7/install_generic.sh b/plugins/mysql-community/versions/5.7/install_generic.sh index cd2f003db8..1dc79f8c1a 100755 --- a/plugins/mysql-community/versions/5.7/install_generic.sh +++ b/plugins/mysql-community/versions/5.7/install_generic.sh @@ -13,7 +13,7 @@ rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") sysName=`uname` -myDir=${serverPath}/source/mysql-apt +myDir=${serverPath}/source/mysql-community OS_ARCH=`arch` MYSQL_VER=5.7.44 @@ -26,14 +26,14 @@ else exit 0 fi -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 -APT_INSTALL() +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 5.7 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 5.7 +COMMUNITY_INSTALL() { ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt +mkdir -p $serverPath/mysql-community # Linux - Generic if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.gz ];then @@ -50,7 +50,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } -APT_UNINSTALL() +COMMUNITY_UNINSTALL() { ### rm -rf $myDir/mysql-${SUFFIX_NAME} @@ -61,31 +61,21 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} Install_mysql() { echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - + COMMUNITY_INSTALL if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '5.7' > $serverPath/mysql-apt/version.pl + mkdir -p $serverPath/mysql-community + echo '5.7' > $serverPath/mysql-community/version.pl echo '安装完成' else - echo '5.7' > $serverPath/mysql-apt/version.pl + echo '5.7' > $serverPath/mysql-community/version.pl echo "暂时不支持该系统" fi } Uninstall_mysql() { - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt + COMMUNITY_UNINSTALL + rm -rf $serverPath/mysql-community echo '卸载完成' } diff --git a/plugins/mysql-community/versions/8.0/install_generic.sh b/plugins/mysql-community/versions/8.0/install_generic.sh index 5a080cd694..f0debfa91b 100755 --- a/plugins/mysql-community/versions/8.0/install_generic.sh +++ b/plugins/mysql-community/versions/8.0/install_generic.sh @@ -13,20 +13,20 @@ rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") sysName=`uname` -myDir=${serverPath}/source/mysql-apt +myDir=${serverPath}/source/mysql-community OS_ARCH=`arch` MYSQL_VER=8.0.39 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.0 -APT_INSTALL() +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 8.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 8.0 +COMMUNITY_INSTALL() { ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt +mkdir -p $serverPath/mysql-community # Linux - Generic if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then @@ -35,7 +35,7 @@ fi if [ -d ${myDir} ];then cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-community fi # 测试时可关闭 @@ -43,7 +43,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } -APT_UNINSTALL() +COMMUNITY_UNINSTALL() { ### rm -rf $myDir/mysql-${SUFFIX_NAME} @@ -55,30 +55,23 @@ Install_mysql() { echo '正在安装脚本文件...' - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi + COMMUNITY_INSTALL if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.0' > $serverPath/mysql-apt/version.pl + mkdir -p $serverPath/mysql-community + echo '8.0' > $serverPath/mysql-community/version.pl echo '安装完成' else - echo '8.0' > $serverPath/mysql-apt/version.pl + echo '8.0' > $serverPath/mysql-community/version.pl echo "暂时不支持该系统" fi } Uninstall_mysql() { + COMMUNITY_UNINSTALL - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt + rm -rf $serverPath/mysql-community echo '卸载完成' } diff --git a/plugins/mysql-community/versions/8.2/install_generic.sh b/plugins/mysql-community/versions/8.2/install_generic.sh index 769c583981..d2cb381d3a 100755 --- a/plugins/mysql-community/versions/8.2/install_generic.sh +++ b/plugins/mysql-community/versions/8.2/install_generic.sh @@ -13,20 +13,20 @@ rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") sysName=`uname` -myDir=${serverPath}/source/mysql-apt +myDir=${serverPath}/source/mysql-community OS_ARCH=`arch` MYSQL_VER=8.2.0 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.2 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.2 -APT_INSTALL() +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 8.2 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 8.2 +COMMUNITY_INSTALL() { ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt +mkdir -p $serverPath/mysql-community # Linux - Generic if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then @@ -35,7 +35,7 @@ fi if [ -d ${myDir} ];then cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-community fi # 测试时可关闭 @@ -43,7 +43,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } -APT_UNINSTALL() +COMMUNITY_UNINSTALL() { ### rm -rf $myDir/mysql-${SUFFIX_NAME} @@ -54,31 +54,22 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} Install_mysql() { echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi + COMMUNITY_INSTALL if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.2' > $serverPath/mysql-apt/version.pl + mkdir -p $serverPath/mysql-community + echo '8.2' > $serverPath/mysql-community/version.pl echo '安装完成' else - echo '8.2' > $serverPath/mysql-apt/version.pl + echo '8.2' > $serverPath/mysql-community/version.pl echo "暂时不支持该系统" fi } Uninstall_mysql() { - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt + COMMUNITY_UNINSTALL + rm -rf $serverPath/mysql-community echo '卸载完成' } diff --git a/plugins/mysql-community/versions/8.3/install_generic.sh b/plugins/mysql-community/versions/8.3/install_generic.sh index c451fbd36d..67debcca46 100755 --- a/plugins/mysql-community/versions/8.3/install_generic.sh +++ b/plugins/mysql-community/versions/8.3/install_generic.sh @@ -13,20 +13,20 @@ rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") sysName=`uname` -myDir=${serverPath}/source/mysql-apt +myDir=${serverPath}/source/mysql-community OS_ARCH=`arch` MYSQL_VER=8.3.0 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.3 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.3 -APT_INSTALL() +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 8.3 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 8.3 +COMMUNITY_INSTALL() { ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt +mkdir -p $serverPath/mysql-community # Linux - Generic if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then @@ -35,7 +35,7 @@ fi if [ -d ${myDir} ];then cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-community fi # 测试时可关闭 @@ -43,7 +43,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } -APT_UNINSTALL() +COMMUNITY_UNINSTALL() { ### rm -rf $myDir/mysql-${SUFFIX_NAME} @@ -54,18 +54,13 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} Install_mysql() { echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - + COMMUNITY_INSTALL if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.3' > $serverPath/mysql-apt/version.pl + mkdir -p $serverPath/mysql-community + echo '8.3' > $serverPath/mysql-community/version.pl echo '安装完成' else - echo '8.3' > $serverPath/mysql-apt/version.pl + echo '8.3' > $serverPath/mysql-community/version.pl echo "暂时不支持该系统" fi } @@ -73,12 +68,8 @@ Install_mysql() Uninstall_mysql() { - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt + COMMUNITY_UNINSTALL + rm -rf $serverPath/mysql-APT_INSTALL echo '卸载完成' } diff --git a/plugins/mysql-community/versions/8.4/install_generic.sh b/plugins/mysql-community/versions/8.4/install_generic.sh index 5932cb0fa3..261e19a58e 100755 --- a/plugins/mysql-community/versions/8.4/install_generic.sh +++ b/plugins/mysql-community/versions/8.4/install_generic.sh @@ -13,22 +13,19 @@ rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") sysName=`uname` -myDir=${serverPath}/source/mysql-apt +myDir=${serverPath}/source/mysql-community OS_ARCH=`arch` MYSQL_VER=8.4.2 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 -APT_INSTALL() +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 8.4 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 8.4 +COMMUNITY_INSTALL() { - - - ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt +mkdir -p $serverPath/mysql-community # Linux - Generic # https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz @@ -38,7 +35,7 @@ fi if [ -d ${myDir} ];then cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-community fi # 测试时可关闭 @@ -46,7 +43,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } -APT_UNINSTALL() +COMMUNITY_UNINSTALL() { ### rm -rf $myDir/mysql-${SUFFIX_NAME} @@ -57,31 +54,21 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} Install_mysql() { echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - + COMMUNITY_INSTALL if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.4' > $serverPath/mysql-apt/version.pl + mkdir -p $serverPath/mysql-community + echo '8.4' > $serverPath/mysql-community/version.pl echo '安装完成' else - echo '8.4' > $serverPath/mysql-apt/version.pl + echo '8.4' > $serverPath/mysql-community/version.pl echo "暂时不支持该系统" fi } Uninstall_mysql() { - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt + COMMUNITY_UNINSTALL + rm -rf $serverPath/mysql-community echo '卸载完成' } diff --git a/plugins/mysql-community/versions/9.0/install_generic.sh b/plugins/mysql-community/versions/9.0/install_generic.sh index 2a8cf58683..cdf5c915e4 100755 --- a/plugins/mysql-community/versions/9.0/install_generic.sh +++ b/plugins/mysql-community/versions/9.0/install_generic.sh @@ -12,20 +12,20 @@ rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") sysName=`uname` -myDir=${serverPath}/source/mysql-apt +myDir=${serverPath}/source/mysql-community OS_ARCH=`arch` MYSQL_VER=9.0.1 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.0 -APT_INSTALL() +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 9.0 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 9.0 +COMMUNITY_INSTALL() { ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt +mkdir -p $serverPath/mysql-community # Linux - Generic # https://cdn.mysql.com/archives/mysql-9.0/mysql-9.0.1-linux-glibc2.28-x86_64.tar.xz @@ -35,7 +35,7 @@ fi if [ -d ${myDir} ];then cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-community fi # 测试时可关闭 @@ -43,7 +43,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } -APT_UNINSTALL() +COMMUNITY_UNINSTALL() { ### rm -rf $myDir/mysql-${SUFFIX_NAME} @@ -54,31 +54,21 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} Install_mysql() { echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - + COMMUNITY_INSTALL if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.0' > $serverPath/mysql-apt/version.pl + mkdir -p $serverPath/mysql-community + echo '9.0' > $serverPath/mysql-community/version.pl echo '安装完成' else - echo '9.0' > $serverPath/mysql-apt/version.pl + echo '9.0' > $serverPath/mysql-community/version.pl echo "暂时不支持该系统" fi } Uninstall_mysql() { - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt + COMMUNITY_UNINSTALL + rm -rf $serverPath/mysql-community echo '卸载完成' } diff --git a/plugins/mysql-community/versions/9.1/install_generic.sh b/plugins/mysql-community/versions/9.1/install_generic.sh index 0c0ea4bb53..382e39040b 100755 --- a/plugins/mysql-community/versions/9.1/install_generic.sh +++ b/plugins/mysql-community/versions/9.1/install_generic.sh @@ -13,20 +13,20 @@ rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") sysName=`uname` -myDir=${serverPath}/source/mysql-apt +myDir=${serverPath}/source/mysql-community OS_ARCH=`arch` MYSQL_VER=9.1.0 SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.1 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.1 -APT_INSTALL() +# cd /www/server/mdserver-web/plugins/mysql-community && bash install.sh install 9.1 +# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-community/index.py start 9.1 +COMMUNITY_INSTALL() { ######## mkdir -p $myDir -mkdir -p $serverPath/mysql-apt +mkdir -p $serverPath/mysql-community # Linux - Generic # https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz @@ -37,7 +37,7 @@ fi if [ -d ${myDir} ];then cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-community fi # 测试时可关闭 @@ -45,7 +45,7 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} ####### } -APT_UNINSTALL() +COMMUNITY_UNINSTALL() { ### rm -rf $myDir/mysql-${SUFFIX_NAME} @@ -57,31 +57,21 @@ rm -rf $myDir/mysql-${SUFFIX_NAME} Install_mysql() { echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - + COMMUNITY_INSTALL if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.1' > $serverPath/mysql-apt/version.pl + mkdir -p $serverPath/mysql-community + echo '9.1' > $serverPath/mysql-community/version.pl echo '安装完成' else - echo '9.1' > $serverPath/mysql-apt/version.pl + echo '9.1' > $serverPath/mysql-community/version.pl echo "暂时不支持该系统" fi } Uninstall_mysql() { - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt + COMMUNITY_UNINSTALL + rm -rf $serverPath/mysql-community echo '卸载完成' } From a109b148f64f564e7b97163b007f09e5d221c1f2 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:03:11 +0800 Subject: [PATCH 20/40] Update install_generic.sh --- plugins/mysql-community/versions/5.7/install_generic.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/mysql-community/versions/5.7/install_generic.sh b/plugins/mysql-community/versions/5.7/install_generic.sh index 1dc79f8c1a..9cb55ed5c5 100755 --- a/plugins/mysql-community/versions/5.7/install_generic.sh +++ b/plugins/mysql-community/versions/5.7/install_generic.sh @@ -42,7 +42,7 @@ fi if [ -d ${myDir} ];then cd ${myDir} && tar -zvxf ${myDir}/mysql-${SUFFIX_NAME}.tar.gz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt + cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-community fi # 测试时可关闭 From 34ed4b2f25e574e86cfa2d998e8d580c68eb81fc Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:20:32 +0800 Subject: [PATCH 21/40] Update public.js --- web/static/app/public.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/web/static/app/public.js b/web/static/app/public.js index 85b9073952..a4d52c2dce 100755 --- a/web/static/app/public.js +++ b/web/static/app/public.js @@ -2100,7 +2100,11 @@ function pluginOpService(a, b, v, _suffix_name='') { _ver = '【' + v + '】'; } - layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,_ver]), {icon:3,closeBtn: 1}, function() { + layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,_ver]), { + area: ['300px'] + icon: 3, + closeBtn: 1 + }, function() { var e = layer.msg(msgTpl('正在{1}{2}{3}服务,请稍候...',[d,a,_ver]), {icon: 16,time: 0}); $.post("/plugins/run", c, function(g) { layer.close(e); From d10c0a2fb96798efd31c6309fae89b3ae8864e36 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:22:40 +0800 Subject: [PATCH 22/40] update --- plugins/mysql-community/index.py | 2 +- web/static/app/public.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/mysql-community/index.py b/plugins/mysql-community/index.py index 79bd47afa4..6aa8ca8475 100755 --- a/plugins/mysql-community/index.py +++ b/plugins/mysql-community/index.py @@ -3480,7 +3480,7 @@ def installPreInspection(version): sys = mw.execShell(cmd) if sys[1] != '': - return '不支持改系统' + return '不支持该系统' cmd = "cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F '\"' '{print $2}'" sys_id = mw.execShell(cmd) diff --git a/web/static/app/public.js b/web/static/app/public.js index a4d52c2dce..a90fe79c17 100755 --- a/web/static/app/public.js +++ b/web/static/app/public.js @@ -2101,7 +2101,7 @@ function pluginOpService(a, b, v, _suffix_name='') { } layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,_ver]), { - area: ['300px'] + area: ['300px'], icon: 3, closeBtn: 1 }, function() { From da8881dd1ec43a1643d881319c1e6782983953ee Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:25:47 +0800 Subject: [PATCH 23/40] Update version.py --- web/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/version.py b/web/version.py index e78644ee3f..2a4f38a05a 100644 --- a/web/version.py +++ b/web/version.py @@ -13,7 +13,7 @@ # 应用程序版本号组件 APP_RELEASE = 0 APP_REVISION = 18 -APP_SMALL_VERSION = 0 +APP_SMALL_VERSION = 0.1 # 应用程序版本后缀,例如“beta1”、“dev”。通常为空字符串GA发布 APP_SUFFIX = '' From 0c8e69c25206abce87e21433ce35ebe7e2c75e83 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:36:54 +0800 Subject: [PATCH 24/40] Update public.js --- web/static/app/public.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/static/app/public.js b/web/static/app/public.js index a90fe79c17..2555af3629 100755 --- a/web/static/app/public.js +++ b/web/static/app/public.js @@ -2101,7 +2101,7 @@ function pluginOpService(a, b, v, _suffix_name='') { } layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,_ver]), { - area: ['300px'], + area: ['400px','auto'], icon: 3, closeBtn: 1 }, function() { From 7e81da67411f2cad43d080ed0b1f6b99db6c8ffb Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:37:25 +0800 Subject: [PATCH 25/40] Update version.py --- web/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/version.py b/web/version.py index 2a4f38a05a..3b3c05e26e 100644 --- a/web/version.py +++ b/web/version.py @@ -13,7 +13,7 @@ # 应用程序版本号组件 APP_RELEASE = 0 APP_REVISION = 18 -APP_SMALL_VERSION = 0.1 +APP_SMALL_VERSION = 0.2 # 应用程序版本后缀,例如“beta1”、“dev”。通常为空字符串GA发布 APP_SUFFIX = '' From f63e7df28d4d15931bfcb88cbdaec5c89439529d Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:41:58 +0800 Subject: [PATCH 26/40] Update public.js --- web/static/app/public.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/static/app/public.js b/web/static/app/public.js index 2555af3629..b503fd9055 100755 --- a/web/static/app/public.js +++ b/web/static/app/public.js @@ -2105,7 +2105,7 @@ function pluginOpService(a, b, v, _suffix_name='') { icon: 3, closeBtn: 1 }, function() { - var e = layer.msg(msgTpl('正在{1}{2}{3}服务,请稍候...',[d,a,_ver]), {icon: 16,time: 0}); + var e = layer.msg(msgTpl('正在{1}{2}{3}服务,请稍候...',[d,a,_ver]), {area: ['400px','auto'],icon: 16,time: 0}); $.post("/plugins/run", c, function(g) { layer.close(e); From a8af7bed62dea58c9b5a22323028ef254e795260 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:42:55 +0800 Subject: [PATCH 27/40] Update public.js --- web/static/app/public.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/static/app/public.js b/web/static/app/public.js index b503fd9055..8221d763aa 100755 --- a/web/static/app/public.js +++ b/web/static/app/public.js @@ -2109,7 +2109,7 @@ function pluginOpService(a, b, v, _suffix_name='') { $.post("/plugins/run", c, function(g) { layer.close(e); - var f = g.data == 'ok' ? msgTpl('{1}{2}服务已{3}',[a,_ver,d]) : msgTpl('{1}{2}服务{3}失败!',[a,_ver,d]); + var f = g.data == 'ok' ? msgTpl('{1}{2}服务已{3}',[a,_ver,d],{area: ['400px','auto'],time: 0}) : msgTpl('{1}{2}服务{3}失败!',[a,_ver,d],{area: ['400px','auto'],time: 0}); layer.msg(f, {icon: g.data == 'ok' ? 1 : 2}); if( b != "reload" && g.data == 'ok' ) { From 485424b5c939935313526de285c67c2e942f2048 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 21:43:17 +0800 Subject: [PATCH 28/40] Update version.py --- web/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/version.py b/web/version.py index 3b3c05e26e..425437ab74 100644 --- a/web/version.py +++ b/web/version.py @@ -13,7 +13,7 @@ # 应用程序版本号组件 APP_RELEASE = 0 APP_REVISION = 18 -APP_SMALL_VERSION = 0.2 +APP_SMALL_VERSION = 0.3 # 应用程序版本后缀,例如“beta1”、“dev”。通常为空字符串GA发布 APP_SUFFIX = '' From 19d94893cbdffbd5c4b5d7e7c4e93da14882fac6 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:10:45 +0800 Subject: [PATCH 29/40] Update index.py --- plugins/mysql-community/index.py | 37 -------------------------------- 1 file changed, 37 deletions(-) diff --git a/plugins/mysql-community/index.py b/plugins/mysql-community/index.py index 6aa8ca8475..901f6b8649 100755 --- a/plugins/mysql-community/index.py +++ b/plugins/mysql-community/index.py @@ -3472,43 +3472,6 @@ def fullSync(version=''): def installPreInspection(version): - arch_data = mw.execShell('arch') - if arch_data[0].strip().startswith('aarch'): - return '不支持aarch架构' - - cmd = "cat /etc/*-release | grep PRETTY_NAME |awk -F = '{print $2}' | awk -F '\"' '{print $2}'| awk '{print $1}'" - sys = mw.execShell(cmd) - - if sys[1] != '': - return '不支持该系统' - - cmd = "cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F '\"' '{print $2}'" - sys_id = mw.execShell(cmd) - - sysName = sys[0].strip().lower() - sysId = sys_id[0].strip() - mdb8 = getMdb8Ver() - - if not sysName in ('debian', 'ubuntu'): - return '仅支持debian,ubuntu' - - if (sysName == 'debian' and not sysId in('12', '11', '10')): - return 'debian支持10,11,12' - - if sysName == 'debian' and sysId == '12' and version == '8.0': - return 'debian12,暂时不支持8.0' - - if version == '9.0': - if sysName == 'debian' and sysId != '12': - return '9.0 仅支持debian12' - if sysName == 'ubuntu' and sysId != '24.04': - return '9.0 仅支持ubuntu24.04' - - if (sysName == 'ubuntu' and version == '5.7' and not sysId in ('18.04')): - return "Ubuntu Apt MySQL[" + version + "] 仅支持18.04" - - if (sysName == 'ubuntu' and version == '8.0' and not sysId in ('18.04', '20.04', '22.04','24.04')): - return 'Ubuntu Apt MySQL[' + version + '] 仅支持18.04,20.04,22.04,24.04' return 'ok' From 5304abcd00b9a99835b08f9c59a0c5c8a645caaa Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:25:00 +0800 Subject: [PATCH 30/40] Update my5.7.cnf --- plugins/mysql-community/conf/my5.7.cnf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/mysql-community/conf/my5.7.cnf b/plugins/mysql-community/conf/my5.7.cnf index d04b185ad8..f97a2bfb71 100644 --- a/plugins/mysql-community/conf/my5.7.cnf +++ b/plugins/mysql-community/conf/my5.7.cnf @@ -18,7 +18,7 @@ server-id = {$SERVER_ID} sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES default_storage_engine = InnoDB -language={$SERVER_APP_PATH}/bin/usr/share/mysql/english +language={$SERVER_APP_PATH}/share/english key_buffer_size = 8M table_open_cache = 32 From 7e3c36cd27639b45ee3833fac376778aa5cbb264 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:25:48 +0800 Subject: [PATCH 31/40] Update version.py --- web/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/version.py b/web/version.py index 425437ab74..e78644ee3f 100644 --- a/web/version.py +++ b/web/version.py @@ -13,7 +13,7 @@ # 应用程序版本号组件 APP_RELEASE = 0 APP_REVISION = 18 -APP_SMALL_VERSION = 0.3 +APP_SMALL_VERSION = 0 # 应用程序版本后缀,例如“beta1”、“dev”。通常为空字符串GA发布 APP_SUFFIX = '' From 60a7e7f8857b5acd6a0daeb3283b1b30e8dead9c Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:30:50 +0800 Subject: [PATCH 32/40] Update mw.tpl --- scripts/init.d/mw.tpl | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/scripts/init.d/mw.tpl b/scripts/init.d/mw.tpl index 242fae1b38..e1e1c89567 100755 --- a/scripts/init.d/mw.tpl +++ b/scripts/init.d/mw.tpl @@ -398,6 +398,10 @@ mw_connect_mysql(){ DB_TYPE["mysql-yum"]="mysql-yum" fi + if [ -d "${ROOT_PATH}/mysql-community" ];then + DB_TYPE["mysql-community"]="mysql-community" + fi + SOURCE_LIST_KEY_SORT_TMP=$(echo ${!DB_TYPE[@]} | tr ' ' '\n' | sort -n) SOURCE_LIST_KEY=(${SOURCE_LIST_KEY_SORT_TMP//'\n'/}) SOURCE_LIST_LEN=${#DB_TYPE[*]} @@ -450,6 +454,10 @@ mw_connect_mysql(){ if [ "$CHOICE_DB" == "mysql-yum" ];then ${ROOT_PATH}/mysql-yum/bin/usr/bin/mysql -S ${ROOT_PATH}/mysql-yum/mysql.sock -uroot -p"${pwd}" fi + + if [ "$CHOICE_DB" == "mysql-community" ];then + ${ROOT_PATH}/mysql-community/bin/mysql -S ${ROOT_PATH}/mysql-community/mysql.sock -uroot -p"${pwd}" + fi } From c4f6db44318c3c4cd4be442ad27f37dc76681b13 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:32:12 +0800 Subject: [PATCH 33/40] update --- .../mysql-community/versions/5.7/install.sh | 132 ---------------- .../mysql-community/versions/8.0/install.sh | 137 ----------------- .../mysql-community/versions/8.2/install.sh | 137 ----------------- .../mysql-community/versions/8.3/install.sh | 135 ---------------- .../mysql-community/versions/8.4/install.sh | 137 ----------------- .../mysql-community/versions/9.0/install.sh | 138 ----------------- .../mysql-community/versions/9.1/install.sh | 144 ------------------ 7 files changed, 960 deletions(-) delete mode 100755 plugins/mysql-community/versions/5.7/install.sh delete mode 100755 plugins/mysql-community/versions/8.0/install.sh delete mode 100755 plugins/mysql-community/versions/8.2/install.sh delete mode 100755 plugins/mysql-community/versions/8.3/install.sh delete mode 100755 plugins/mysql-community/versions/8.4/install.sh delete mode 100755 plugins/mysql-community/versions/9.0/install.sh delete mode 100755 plugins/mysql-community/versions/9.1/install.sh diff --git a/plugins/mysql-community/versions/5.7/install.sh b/plugins/mysql-community/versions/5.7/install.sh deleted file mode 100755 index 1d2a70c432..0000000000 --- a/plugins/mysql-community/versions/5.7/install.sh +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -# debug -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 -# /www/server/mysql-apt/bin/usr/sbin/mysqld --defaults-file=/www/server/mysql-apt/etc/my.cnf --daemonize -# /www/server/mysql-apt/bin/usr/bin/mysql -S /www/server/mysql-apt/mysql.sock -uroot -p - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -MYSQL_VER=5.7.39 -if [ "$OSNAME" == "debian" ];then - # mysql5.7现在仅有10的编译版 - VERSION_ID="10" -fi - -if [ "$OSNAME" == "ubuntu" ];then - # mysql5.7现在仅有18.04的编译版 - VERSION_ID="18.04" -fi - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 0 -fi - -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-5.7/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '5.7' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-community/versions/8.0/install.sh b/plugins/mysql-community/versions/8.0/install.sh deleted file mode 100755 index 082460a6e7..0000000000 --- a/plugins/mysql-community/versions/8.0/install.sh +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.0 - -# 暂时debian12没有标准版,先用11使用 -# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then -# echo "暂时不支持该${OSNAME}${VERSION_ID}" -# exit 1 -# fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.0.39 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.0' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.0' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-community/versions/8.2/install.sh b/plugins/mysql-community/versions/8.2/install.sh deleted file mode 100755 index 81cade8267..0000000000 --- a/plugins/mysql-community/versions/8.2/install.sh +++ /dev/null @@ -1,137 +0,0 @@ - -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 -# cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql-apt/index.py start - -# 暂时debian12没有标准版,先用11使用 -# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then -# echo "暂时不支持该${OSNAME}${VERSION_ID}" -# exit 1 -# fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.2.0 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.2/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.2' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.2' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-community/versions/8.3/install.sh b/plugins/mysql-community/versions/8.3/install.sh deleted file mode 100755 index 316ae77edf..0000000000 --- a/plugins/mysql-community/versions/8.3/install.sh +++ /dev/null @@ -1,135 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 - -# 暂时debian12没有标准版,先用11使用 -# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then -# echo "暂时不支持该${OSNAME}${VERSION_ID}" -# exit 1 -# fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.3.0 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.3/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.3' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.3' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-community/versions/8.4/install.sh b/plugins/mysql-community/versions/8.4/install.sh deleted file mode 100755 index dfcd789980..0000000000 --- a/plugins/mysql-community/versions/8.4/install.sh +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 - -if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then - VERSION_ID="12" -fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.4.2 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -# https://cdn.mysql.com/archives/mysql-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.4' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.4' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-community/versions/9.0/install.sh b/plugins/mysql-community/versions/9.0/install.sh deleted file mode 100755 index 874522d9d4..0000000000 --- a/plugins/mysql-community/versions/9.0/install.sh +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 - -# 暂时debian12没有标准版,先用11使用 -if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then - VERSION_ID="12" -fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=9.0.1 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -# https://dev.mysql.com/get/Downloads/MySQL-9.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# https://cdn.mysql.com/archives/mysql-9.0/mysql-server_9.0.1-1debian12_amd64.deb-bundle.tar - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-9.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.0' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '9.0' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-community/versions/9.1/install.sh b/plugins/mysql-community/versions/9.1/install.sh deleted file mode 100755 index 27d3460981..0000000000 --- a/plugins/mysql-community/versions/9.1/install.sh +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.1 -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.1 - -#x-faq -# strings /lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIB - -# debian12 -if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then - VERSION_ID="12" -fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=9.1.0 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ - -cd ${rootPath}/plugins/php/lib && /bin/bash openssl_30.sh - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -# https://cdn.mysql.com/archives/mysql-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.1' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '9.1' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi From 8ef84763c61fa1ee64b91c435fe2fb0540a93dc7 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:34:35 +0800 Subject: [PATCH 34/40] Update index.py --- plugins/mysql-community/index.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/plugins/mysql-community/index.py b/plugins/mysql-community/index.py index 901f6b8649..7536650bf9 100755 --- a/plugins/mysql-community/index.py +++ b/plugins/mysql-community/index.py @@ -137,12 +137,10 @@ def contentReplace(content): service_path = mw.getServerDir() content = content.replace('{$ROOT_PATH}', mw.getFatherDir()) content = content.replace('{$SERVER_PATH}', service_path) - content = content.replace('{$SERVER_APP_PATH}', - service_path + '/' + getPluginName()) + content = content.replace('{$SERVER_APP_PATH}',service_path + '/' + getPluginName()) server_id = int(time.time()) content = content.replace('{$SERVER_ID}', str(server_id)) - return content @@ -418,7 +416,9 @@ def initMysql57Data(): cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + \ datadir + ' --initialize-insecure --explicit_defaults_for_timestamp' + # print(cmd) data = mw.execShell(cmd) + # print(data) if data[1].lower().find('error') != -1: exit("Init MySQL5.7 Data Error:"+data[1]) @@ -446,7 +446,9 @@ def initMysql8Data(): cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + datadir + \ ' --initialize-insecure --lower-case-table-names=1' + # print(cmd) data = mw.execShell(cmd) + # print(data) if data[1].lower().find('error') != -1: exit("Init MySQL8+ Data Error:"+data[1]) if data[1].lower().find('not found') != -1: From d9d9721249f9a478b536bf6be0ec38cbbf05703e Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:38:37 +0800 Subject: [PATCH 35/40] Update index.py --- plugins/mysql-community/index.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/mysql-community/index.py b/plugins/mysql-community/index.py index 7536650bf9..b9283a12d4 100755 --- a/plugins/mysql-community/index.py +++ b/plugins/mysql-community/index.py @@ -431,10 +431,10 @@ def initMysql57Data(): def initMysql8Data(): ''' - chmod 644 /www/server/mysql-apt/etc/my.cnf + chmod 644 /www/server/mysql-community/etc/my.cnf try: - mysqld --basedir=/usr --datadir=/www/server/mysql-apt/data --initialize-insecure - mysqld --defaults-file=/www/server/mysql-apt/etc/my.cnf --initialize-insecure + mysqld --basedir=/usr --datadir=/www/server/mysql-community/data --initialize-insecure + mysqld --defaults-file=/www/server/mysql-community/etc/my.cnf --initialize-insecure mysqld --initialize-insecure select user, plugin from user; update user set authentication_string=password("123123"),plugin='mysql_native_password' where user='root'; From f82ff2d482af9a81f2cfde2e29853ea3adcd5d39 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:46:00 +0800 Subject: [PATCH 36/40] Update rhel.sh --- scripts/install/rhel.sh | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/install/rhel.sh b/scripts/install/rhel.sh index 259f2ed1d7..6149c2d1ac 100644 --- a/scripts/install/rhel.sh +++ b/scripts/install/rhel.sh @@ -195,9 +195,10 @@ if [ "$VERSION_ID" -ge "8" ];then libpng libpng-devel libstdc++.so.6 libtirpc libtirpc-devel libtool libtool-libs libwebp libwebp-devel \ libxml2 libxml2-devel libxslt libxslt-devel libarchive make mysql-devel ncurses ncurses-devel net-tools \ oniguruma oniguruma-devel patch pcre pcre-devel perl perl-Data-Dumper perl-devel procps psmisc python3-devel \ - openssl openssl-devel patchelf libargon2-devel\ + openssl openssl-devel patchelf libargon2-devel \ ImageMagick ImageMagick-devel libyaml-devel \ - pv bc\ + pv bc \ + ncurses-compat-libs \ readline-devel rpcgen sqlite-devel rar unrar tar unzip vim-minimal wget zip zlib zlib-devel; do # dnf --enablerepo=remi,appstream,baseos,epel,extras,powertools install -y oniguruma5php-devel @@ -218,6 +219,7 @@ else make mysql-devel ncurses ncurses-devel net-tools oniguruma oniguruma-devel openldap openldap-devel \ openssl openssl-devel patch pcre pcre-devel perl perl-Data-Dumper perl-devel psmisc python-devel \ pv bc\ + ncurses-compat-libs \ python3-devel python3-pip re2c readline-devel rpcgen sqlite-devel tar unzip rar unrar vim-minimal vixie-cron \ wget zip zlib zlib-devel ImageMagick ImageMagick-devel libyaml-devel patchelf libargon2-devel; do From aee405f9e261ab127b798f609c1637e9ec7db832 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 22:49:01 +0800 Subject: [PATCH 37/40] update --- scripts/install/centos.sh | 1 + scripts/install/euler.sh | 1 + scripts/install/fedora.sh | 1 + scripts/install/rocky.sh | 1 + 4 files changed, 4 insertions(+) diff --git a/scripts/install/centos.sh b/scripts/install/centos.sh index 57a8aa90b5..e60145a49d 100755 --- a/scripts/install/centos.sh +++ b/scripts/install/centos.sh @@ -35,6 +35,7 @@ yum install -y pv yum install -y bc yum install -y bzip2 yum install -y bzip2-devel +yum install -y ncurses-compat-libs # if [ -f /usr/sbin/iptables ];then diff --git a/scripts/install/euler.sh b/scripts/install/euler.sh index a1b997e22d..674f9dc5b7 100755 --- a/scripts/install/euler.sh +++ b/scripts/install/euler.sh @@ -35,6 +35,7 @@ yum install -y pv yum install -y bc yum install -y bzip2 yum install -y bzip2-devel +yum install -y ncurses-compat-libs # if [ -f /usr/sbin/iptables ];then diff --git a/scripts/install/fedora.sh b/scripts/install/fedora.sh index 3ed2a102e7..2e1af655b6 100644 --- a/scripts/install/fedora.sh +++ b/scripts/install/fedora.sh @@ -15,6 +15,7 @@ sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config yum install -y wget curl lsof unzip yum install -y expect +yum install -y ncurses-compat-libs dnf install crontabs -y SSH_PORT=`netstat -ntpl|grep sshd|grep -v grep | sed -n "1,1p" | awk '{print $4}' | awk -F : '{print $2}'` diff --git a/scripts/install/rocky.sh b/scripts/install/rocky.sh index d30c6042cc..c74c18e11b 100644 --- a/scripts/install/rocky.sh +++ b/scripts/install/rocky.sh @@ -25,6 +25,7 @@ yum install -y bzip2 yum install -y bzip2-devel yum install -y libzip-devel yum install -y re2c +yum install -y ncurses-compat-libs if [ -f /usr/sbin/iptables ];then From 798c52f23def1359187d38e7ac7d92a42e181a40 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 23:18:56 +0800 Subject: [PATCH 38/40] Update sql_mysql.py --- plugins/data_query/sql_mysql.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/data_query/sql_mysql.py b/plugins/data_query/sql_mysql.py index 93cc6c0ed2..2d1e8217b9 100755 --- a/plugins/data_query/sql_mysql.py +++ b/plugins/data_query/sql_mysql.py @@ -84,7 +84,7 @@ def get_options(self, sid=None): result['host'] = '127.0.0.1' result['username'] = 'root' - if sid in ['mysql', 'mysql-apt', 'mysql-yum']: + if sid in ['mysql', 'mysql-apt', 'mysql-yum', 'mysql-community']: my_cnf_path = "{}/{}/etc/my.cnf".format(mw.getServerDir(),sid) if not os.path.exists(my_cnf_path): return False From 85e6a678ddc541701505168738d0cc2e65a3afc4 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 23:20:48 +0800 Subject: [PATCH 39/40] Update sql_mysql.py --- plugins/data_query/sql_mysql.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/data_query/sql_mysql.py b/plugins/data_query/sql_mysql.py index 2d1e8217b9..66bd7febc5 100755 --- a/plugins/data_query/sql_mysql.py +++ b/plugins/data_query/sql_mysql.py @@ -132,6 +132,10 @@ def getServerList(self): local_mysql_yum = "{}/mysql-yum/etc/my.cnf".format(mw.getServerDir()) if os.path.exists(local_mysql_yum): data.append({'name':'本地服务器[yum]', 'val':'mysql-yum'}) + + local_mysql_yum = "{}/mysql-community/etc/my.cnf".format(mw.getServerDir()) + if os.path.exists(local_mysql_yum): + data.append({'name':'本地服务器[community]', 'val':'mysql-community'}) return mw.returnData(True, 'ok', data) @singleton From 1973f6a2b03393c7b815d9343f8bd49ff8bac85b Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Tue, 17 Dec 2024 23:33:46 +0800 Subject: [PATCH 40/40] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=86=97=E4=BD=99mysql?= =?UTF-8?q?=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugins/mysql-apt/conf/classic.cnf | 0 plugins/mysql-apt/conf/gtid.cnf | 4 - plugins/mysql-apt/conf/my5.7.cnf | 110 - plugins/mysql-apt/conf/my8.0.cnf | 103 - plugins/mysql-apt/conf/my8.2.cnf | 103 - plugins/mysql-apt/conf/my8.3.cnf | 103 - plugins/mysql-apt/conf/my8.4.cnf | 103 - plugins/mysql-apt/conf/my9.0.cnf | 103 - plugins/mysql-apt/conf/my9.1.cnf | 103 - plugins/mysql-apt/conf/mysql.sql | 58 - plugins/mysql-apt/ico.png | Bin 1135 -> 0 bytes plugins/mysql-apt/index.html | 59 - plugins/mysql-apt/index.py | 3715 ----------------- plugins/mysql-apt/index_mysql_apt.py | 189 - plugins/mysql-apt/info.json | 19 - plugins/mysql-apt/init.d/mysql5.7.service.tpl | 43 - plugins/mysql-apt/init.d/mysql8.0.service.tpl | 50 - plugins/mysql-apt/init.d/mysql8.1.service.tpl | 50 - plugins/mysql-apt/init.d/mysql8.2.service.tpl | 50 - plugins/mysql-apt/init.d/mysql8.3.service.tpl | 50 - plugins/mysql-apt/init.d/mysql8.4.service.tpl | 49 - plugins/mysql-apt/init.d/mysql9.0.service.tpl | 49 - plugins/mysql-apt/init.d/mysql9.1.service.tpl | 49 - plugins/mysql-apt/install.sh | 71 - plugins/mysql-apt/js/mysql-apt.js | 2968 ------------- plugins/mysql-apt/scripts/backup.py | 119 - plugins/mysql-apt/versions/5.7/install.sh | 132 - .../mysql-apt/versions/5.7/install_generic.sh | 97 - plugins/mysql-apt/versions/8.0/install.sh | 137 - .../mysql-apt/versions/8.0/install_generic.sh | 90 - plugins/mysql-apt/versions/8.2/install.sh | 137 - .../mysql-apt/versions/8.2/install_generic.sh | 90 - plugins/mysql-apt/versions/8.3/install.sh | 135 - .../mysql-apt/versions/8.3/install_generic.sh | 90 - plugins/mysql-apt/versions/8.4/install.sh | 137 - .../mysql-apt/versions/8.4/install_generic.sh | 93 - plugins/mysql-apt/versions/9.0/install.sh | 138 - .../mysql-apt/versions/9.0/install_generic.sh | 90 - plugins/mysql-apt/versions/9.1/install.sh | 144 - .../mysql-apt/versions/9.1/install_generic.sh | 93 - plugins/mysql-yum/conf/classic.cnf | 0 plugins/mysql-yum/conf/gtid.cnf | 4 - plugins/mysql-yum/conf/my5.7.cnf | 111 - plugins/mysql-yum/conf/my8.0.cnf | 103 - plugins/mysql-yum/conf/my8.2.cnf | 105 - plugins/mysql-yum/conf/my8.3.cnf | 105 - plugins/mysql-yum/conf/my8.4.cnf | 104 - plugins/mysql-yum/conf/my9.0.cnf | 104 - plugins/mysql-yum/conf/mysql.sql | 58 - plugins/mysql-yum/ico.png | Bin 1135 -> 0 bytes plugins/mysql-yum/index.html | 59 - plugins/mysql-yum/index.py | 3680 ---------------- plugins/mysql-yum/index_mysql_yum.py | 182 - plugins/mysql-yum/info.json | 18 - plugins/mysql-yum/init.d/mysql5.7.service.tpl | 63 - plugins/mysql-yum/init.d/mysql8.0.service.tpl | 63 - plugins/mysql-yum/init.d/mysql8.2.service.tpl | 63 - plugins/mysql-yum/init.d/mysql8.3.service.tpl | 63 - plugins/mysql-yum/init.d/mysql8.4.service.tpl | 63 - plugins/mysql-yum/init.d/mysql9.0.service.tpl | 63 - plugins/mysql-yum/install.sh | 61 - plugins/mysql-yum/js/mysql-yum.js | 2966 ------------- plugins/mysql-yum/scripts/backup.py | 118 - plugins/mysql-yum/versions/5.7/install.sh | 151 - plugins/mysql-yum/versions/8.0/install.sh | 149 - plugins/mysql-yum/versions/8.2/install.sh | 152 - plugins/mysql-yum/versions/8.3/install.sh | 151 - plugins/mysql-yum/versions/8.4/install.sh | 153 - plugins/mysql-yum/versions/9.0/install.sh | 154 - 69 files changed, 18989 deletions(-) delete mode 100644 plugins/mysql-apt/conf/classic.cnf delete mode 100644 plugins/mysql-apt/conf/gtid.cnf delete mode 100644 plugins/mysql-apt/conf/my5.7.cnf delete mode 100644 plugins/mysql-apt/conf/my8.0.cnf delete mode 100644 plugins/mysql-apt/conf/my8.2.cnf delete mode 100644 plugins/mysql-apt/conf/my8.3.cnf delete mode 100644 plugins/mysql-apt/conf/my8.4.cnf delete mode 100644 plugins/mysql-apt/conf/my9.0.cnf delete mode 100644 plugins/mysql-apt/conf/my9.1.cnf delete mode 100755 plugins/mysql-apt/conf/mysql.sql delete mode 100644 plugins/mysql-apt/ico.png delete mode 100755 plugins/mysql-apt/index.html delete mode 100755 plugins/mysql-apt/index.py delete mode 100644 plugins/mysql-apt/index_mysql_apt.py delete mode 100755 plugins/mysql-apt/info.json delete mode 100644 plugins/mysql-apt/init.d/mysql5.7.service.tpl delete mode 100644 plugins/mysql-apt/init.d/mysql8.0.service.tpl delete mode 100644 plugins/mysql-apt/init.d/mysql8.1.service.tpl delete mode 100644 plugins/mysql-apt/init.d/mysql8.2.service.tpl delete mode 100644 plugins/mysql-apt/init.d/mysql8.3.service.tpl delete mode 100644 plugins/mysql-apt/init.d/mysql8.4.service.tpl delete mode 100644 plugins/mysql-apt/init.d/mysql9.0.service.tpl delete mode 100644 plugins/mysql-apt/init.d/mysql9.1.service.tpl delete mode 100755 plugins/mysql-apt/install.sh delete mode 100755 plugins/mysql-apt/js/mysql-apt.js delete mode 100755 plugins/mysql-apt/scripts/backup.py delete mode 100755 plugins/mysql-apt/versions/5.7/install.sh delete mode 100755 plugins/mysql-apt/versions/5.7/install_generic.sh delete mode 100755 plugins/mysql-apt/versions/8.0/install.sh delete mode 100755 plugins/mysql-apt/versions/8.0/install_generic.sh delete mode 100755 plugins/mysql-apt/versions/8.2/install.sh delete mode 100755 plugins/mysql-apt/versions/8.2/install_generic.sh delete mode 100755 plugins/mysql-apt/versions/8.3/install.sh delete mode 100755 plugins/mysql-apt/versions/8.3/install_generic.sh delete mode 100755 plugins/mysql-apt/versions/8.4/install.sh delete mode 100755 plugins/mysql-apt/versions/8.4/install_generic.sh delete mode 100755 plugins/mysql-apt/versions/9.0/install.sh delete mode 100755 plugins/mysql-apt/versions/9.0/install_generic.sh delete mode 100755 plugins/mysql-apt/versions/9.1/install.sh delete mode 100755 plugins/mysql-apt/versions/9.1/install_generic.sh delete mode 100644 plugins/mysql-yum/conf/classic.cnf delete mode 100644 plugins/mysql-yum/conf/gtid.cnf delete mode 100644 plugins/mysql-yum/conf/my5.7.cnf delete mode 100644 plugins/mysql-yum/conf/my8.0.cnf delete mode 100644 plugins/mysql-yum/conf/my8.2.cnf delete mode 100644 plugins/mysql-yum/conf/my8.3.cnf delete mode 100644 plugins/mysql-yum/conf/my8.4.cnf delete mode 100644 plugins/mysql-yum/conf/my9.0.cnf delete mode 100755 plugins/mysql-yum/conf/mysql.sql delete mode 100644 plugins/mysql-yum/ico.png delete mode 100755 plugins/mysql-yum/index.html delete mode 100755 plugins/mysql-yum/index.py delete mode 100644 plugins/mysql-yum/index_mysql_yum.py delete mode 100755 plugins/mysql-yum/info.json delete mode 100644 plugins/mysql-yum/init.d/mysql5.7.service.tpl delete mode 100644 plugins/mysql-yum/init.d/mysql8.0.service.tpl delete mode 100644 plugins/mysql-yum/init.d/mysql8.2.service.tpl delete mode 100644 plugins/mysql-yum/init.d/mysql8.3.service.tpl delete mode 100644 plugins/mysql-yum/init.d/mysql8.4.service.tpl delete mode 100644 plugins/mysql-yum/init.d/mysql9.0.service.tpl delete mode 100755 plugins/mysql-yum/install.sh delete mode 100755 plugins/mysql-yum/js/mysql-yum.js delete mode 100755 plugins/mysql-yum/scripts/backup.py delete mode 100755 plugins/mysql-yum/versions/5.7/install.sh delete mode 100755 plugins/mysql-yum/versions/8.0/install.sh delete mode 100755 plugins/mysql-yum/versions/8.2/install.sh delete mode 100755 plugins/mysql-yum/versions/8.3/install.sh delete mode 100755 plugins/mysql-yum/versions/8.4/install.sh delete mode 100755 plugins/mysql-yum/versions/9.0/install.sh diff --git a/plugins/mysql-apt/conf/classic.cnf b/plugins/mysql-apt/conf/classic.cnf deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/plugins/mysql-apt/conf/gtid.cnf b/plugins/mysql-apt/conf/gtid.cnf deleted file mode 100644 index 5076776a65..0000000000 --- a/plugins/mysql-apt/conf/gtid.cnf +++ /dev/null @@ -1,4 +0,0 @@ -[mysqld] -# SHOW GLOBAL VARIABLES LIKE '%gtid%' -gtid_mode=ON -enforce_gtid_consistency=ON \ No newline at end of file diff --git a/plugins/mysql-apt/conf/my5.7.cnf b/plugins/mysql-apt/conf/my5.7.cnf deleted file mode 100644 index d04b185ad8..0000000000 --- a/plugins/mysql-apt/conf/my5.7.cnf +++ /dev/null @@ -1,110 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} -sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES - -default_storage_engine = InnoDB -language={$SERVER_APP_PATH}/bin/usr/share/mysql/english - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=0 -character-set-server = UTF8MB4 - -query_cache_type = 1 -query_cache_size = 64M - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -skip_name_resolve = 1 -skip-ssl -#skip-networking -#skip-external-locking -#loose-skip-innodb -#skip-grant-tables - -log-bin=mysql-bin -binlog_format=mixed -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -expire_logs_days=30 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log-slave-updates -#replicate-do-db -slave_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -master_info_repository = table -relay_log_info_repository = table - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_log_file_size = 5M -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-apt/conf/my8.0.cnf b/plugins/mysql-apt/conf/my8.0.cnf deleted file mode 100644 index 388b397eb7..0000000000 --- a/plugins/mysql-apt/conf/my8.0.cnf +++ /dev/null @@ -1,103 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=mysql_native_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-apt/conf/my8.2.cnf b/plugins/mysql-apt/conf/my8.2.cnf deleted file mode 100644 index 1b7ff7b943..0000000000 --- a/plugins/mysql-apt/conf/my8.2.cnf +++ /dev/null @@ -1,103 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-apt/conf/my8.3.cnf b/plugins/mysql-apt/conf/my8.3.cnf deleted file mode 100644 index 1b7ff7b943..0000000000 --- a/plugins/mysql-apt/conf/my8.3.cnf +++ /dev/null @@ -1,103 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-apt/conf/my8.4.cnf b/plugins/mysql-apt/conf/my8.4.cnf deleted file mode 100644 index 1b7ff7b943..0000000000 --- a/plugins/mysql-apt/conf/my8.4.cnf +++ /dev/null @@ -1,103 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-apt/conf/my9.0.cnf b/plugins/mysql-apt/conf/my9.0.cnf deleted file mode 100644 index 1b7ff7b943..0000000000 --- a/plugins/mysql-apt/conf/my9.0.cnf +++ /dev/null @@ -1,103 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-apt/conf/my9.1.cnf b/plugins/mysql-apt/conf/my9.1.cnf deleted file mode 100644 index 1b7ff7b943..0000000000 --- a/plugins/mysql-apt/conf/my9.1.cnf +++ /dev/null @@ -1,103 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-apt/conf/mysql.sql b/plugins/mysql-apt/conf/mysql.sql deleted file mode 100755 index f98ddf79b9..0000000000 --- a/plugins/mysql-apt/conf/mysql.sql +++ /dev/null @@ -1,58 +0,0 @@ -CREATE TABLE IF NOT EXISTS `config` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `mysql_root` TEXT -); - -INSERT INTO `config` (`id`, `mysql_root`) VALUES (1, 'admin'); - -CREATE TABLE IF NOT EXISTS `databases` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `pid` INTEGER, - `name` TEXT, - `username` TEXT, - `password` TEXT, - `accept` TEXT, - `rw` TEXT DEFAULT 'rw', - `ps` TEXT, - `addtime` TEXT -); --- ALTER TABLE `databases` ADD COLUMN `rw` TEXT DEFAULT 'rw'; - -CREATE TABLE IF NOT EXISTS `master_replication_user` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `username` TEXT, - `password` TEXT, - `accept` TEXT, - `ps` TEXT, - `addtime` TEXT -); - --- 从库配置主库的[ssh private key] --- drop table `slave_id_rsa`; -CREATE TABLE IF NOT EXISTS `slave_id_rsa` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `ip` TEXT, - `port` TEXT, - `user` TEXT, - `db_user` TEXT, - `id_rsa` TEXT, - `ps` TEXT, - `addtime` TEXT -); - --- 从库配置主库的[user] --- drop table `slave_user`; -CREATE TABLE IF NOT EXISTS `slave_sync_user` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `ip` TEXT, - `port` TEXT, - `user` TEXT, - `pass` TEXT, - `mode` TEXT, - `cmd` TEXT, - `db` TEXT, - `addtime` TEXT -); -ALTER TABLE `slave_sync_user` ADD COLUMN `db` TEXT DEFAULT ''; - - diff --git a/plugins/mysql-apt/ico.png b/plugins/mysql-apt/ico.png deleted file mode 100644 index ead815fc20cc747780967ef2871b83c000e4f82d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1135 zcmV-#1d#iQP)>{3lQ%rYE>EIo|Bc9O8-^_)1agG}q9>-P216(B zK}1dolB(O#w(T^gZ+;f7TTURgp@*LLi%EvgY=cZDhv*1Q%s|VgV~ETx1Bb!tAi=x$ zUWdVBccSOOP0TAdp?2kNQqbh`6_+AM=z=O#FWZiQgf#GjdIS}L4KI9; zf}sTnN>=9>ibj?}Z*{;EbY?5sx1YxBZ7&Kol9MINSyjpHnF1j5xR->al|lgp3yToqeV zi#1Puj`)fuTy=C78)}wr|E;r9Us(3QJIL;u;2qai|6mNCx)=S2ZoTRgD-Cf~i(61M zx(o`X3N_1iVCx${VeI@Pv@i2P$%IaC9>B`SKIRNTVJVXE z2#%m|zDZ4GHL+7*QfNoPf=^*t~;eZXN43`ND z7cv<&LC*S9H$H{xrQ7Jlg9?E+DPi*uMqb|xC2+^ia|lk(@-ihrD=Xzh`OJFMEZYt$ z$xJyfgDMjpD9034i#I2DjNYWkmE7JWBqSsxeg^A1@>H -
    -
    -
    - -

    服务

    -

    自启动

    -

    配置文件

    -

    存储位置

    -

    端口

    -

    当前状态

    -

    性能优化

    -

    日志

    -

    慢日志

    -

    BINLOG

    -

    管理列表

    -

    主从配置

    -
    -
    -
    -
    -
    - - - - - - \ No newline at end of file diff --git a/plugins/mysql-apt/index.py b/plugins/mysql-apt/index.py deleted file mode 100755 index baa342bc1f..0000000000 --- a/plugins/mysql-apt/index.py +++ /dev/null @@ -1,3715 +0,0 @@ -# coding=utf-8 - -import sys -import io -import os -import time -import subprocess -import re -import json - - -web_dir = os.getcwd() + "/web" -if os.path.exists(web_dir): - sys.path.append(web_dir) - os.chdir(web_dir) - -import core.mw as mw - -app_debug = False -if mw.isAppleSystem(): - app_debug = True - - -def getPluginName(): - return 'mysql-apt' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - - -def getSPluginDir(): - return '/www/server/mdserver-web/plugins/' + getPluginName() - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def is_number(s): - try: - float(s) - return True - except ValueError: - pass - - try: - import unicodedata - unicodedata.numeric(s) - return True - except (TypeError, ValueError): - pass - - return False - - -def getArgs(): - args = sys.argv[2:] - tmp = {} - args_len = len(args) - if args_len == 1: - t = args[0].strip('{').strip('}') - if t.strip() == '': - tmp = [] - else: - t = t.split(':', 1) - tmp[t[0]] = t[1] - tmp[t[0]] = t[1] - elif args_len > 1: - for i in range(len(args)): - t = args[i].split(':', 1) - tmp[t[0]] = t[1] - return tmp - - -def getBackupDir(): - bk_path = mw.getBackupDir() + "/database/mysql-apt" - if not os.path.isdir(bk_path): - mw.execShell("mkdir -p {}".format(bk_path)) - return bk_path - - -def checkArgs(data, ck=[]): - for i in range(len(ck)): - if not ck[i] in data: - return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!')) - return (True, mw.returnJson(True, 'ok')) - - -def getConf(): - path = getServerDir() + '/etc/my.cnf' - return path - - -def getDbPort(): - file = getConf() - content = mw.readFile(file) - rep = r'port\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getDbServerId(): - file = getConf() - content = mw.readFile(file) - rep = r'server-id\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getSocketFile(): - file = getConf() - content = mw.readFile(file) - rep = r'socket\s*=\s*(.*)' - tmp = re.search(rep, content) - - socket = tmp.groups()[0].strip() - return socket - - -def getErrorLogsFile(): - file = getConf() - content = mw.readFile(file) - rep = r'log-error\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getAuthPolicy(): - file = getConf() - content = mw.readFile(file) - rep = r'authentication_policy\s*=\s*(.*)' - tmp = re.search(rep, content) - if tmp: - return tmp.groups()[0].strip() - # caching_sha2_password - return 'mysql_native_password' - -def contentReplace(content): - service_path = mw.getServerDir() - content = content.replace('{$ROOT_PATH}', mw.getFatherDir()) - content = content.replace('{$SERVER_PATH}', service_path) - content = content.replace('{$SERVER_APP_PATH}', - service_path + '/' + getPluginName()) - - server_id = int(time.time()) - content = content.replace('{$SERVER_ID}', str(server_id)) - - return content - - -def pSqliteDb(dbname='databases'): - file = getServerDir() + '/mysql.db' - name = 'mysql' - - import_sql = mw.readFile(getPluginDir() + '/conf/mysql.sql') - md5_sql = mw.md5(import_sql) - - import_sign = False - save_md5_file = getServerDir() + '/import_sql.md5' - if os.path.exists(save_md5_file): - save_md5_sql = mw.readFile(save_md5_file) - if save_md5_sql != md5_sql: - import_sign = True - mw.writeFile(save_md5_file, md5_sql) - else: - mw.writeFile(save_md5_file, md5_sql) - - if not os.path.exists(file) or import_sql: - conn = mw.M(dbname).dbPos(getServerDir(), name) - csql_list = import_sql.split(';') - for index in range(len(csql_list)): - conn.execute(csql_list[index], ()) - - conn = mw.M(dbname).dbPos(getServerDir(), name) - return conn - - -def pMysqlDb(): - # pymysql - db = mw.getMyORM() - # MySQLdb | - # db = mw.getMyORMDb() - - db.setPort(getDbPort()) - db.setSocket(getSocketFile()) - # db.setCharset("utf8") - db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')) - return db - - -def initDreplace(version=''): - - t = getServerDir() - if not os.path.exists(t): - return - - conf_dir = getServerDir() + '/etc' - mode_dir = conf_dir + '/mode' - - conf_list = [ - conf_dir, - mode_dir, - ] - for conf in conf_list: - if not os.path.exists(conf): - os.mkdir(conf) - - tmp_dir = getServerDir() + '/tmp' - if not os.path.exists(tmp_dir): - os.mkdir(tmp_dir) - mw.execShell("chown -R mysql:mysql " + tmp_dir) - mw.execShell("chmod 750 " + tmp_dir) - - my_conf = conf_dir + '/my.cnf' - if not os.path.exists(my_conf): - tpl = getPluginDir() + '/conf/my' + version + '.cnf' - content = mw.readFile(tpl) - content = contentReplace(content) - mw.writeFile(my_conf, content) - - classic_conf = mode_dir + '/classic.cnf' - if not os.path.exists(classic_conf): - tpl = getPluginDir() + '/conf/classic.cnf' - content = mw.readFile(tpl) - content = contentReplace(content) - mw.writeFile(classic_conf, content) - - gtid_conf = mode_dir + '/gtid.cnf' - if not os.path.exists(gtid_conf): - tpl = getPluginDir() + '/conf/gtid.cnf' - content = mw.readFile(tpl) - content = contentReplace(content) - mw.writeFile(gtid_conf, content) - - # systemd - systemDir = mw.systemdCfgDir() - systemService = systemDir + '/mysql-apt.service' - systemServiceTpl = getPluginDir() + '/init.d/mysql' + version + '.service.tpl' - if os.path.exists(systemDir) and not os.path.exists(systemService): - service_path = mw.getServerDir() - content = mw.readFile(systemServiceTpl) - content = content.replace('{$SERVER_PATH}', service_path) - mw.writeFile(systemService, content) - mw.execShell('systemctl daemon-reload') - - if mw.getOs() != 'darwin': - mw.execShell('chown -R mysql mysql ' + getServerDir()) - return 'ok' - -def process_status(): - cmd = "ps -ef|grep mysql-apt|grep mysql |grep -v grep | grep -v python | awk '{print $2}'" - data = mw.execShell(cmd) - if data[0] == '': - return 'stop' - return 'start' - -def status(version=''): - pid = getPidFile() - if not os.path.exists(pid): - return 'stop' - return 'start' - - -def getDataDir(): - file = getConf() - content = mw.readFile(file) - rep = r'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getLogBinName(): - file = getConf() - content = mw.readFile(file) - rep = r'log-bin\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getPidFile(): - file = getConf() - content = mw.readFile(file) - rep = r'pid-file\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def binLog(version=''): - args = getArgs() - conf = getConf() - con = mw.readFile(conf) - - if con.find('#log-bin=mysql-bin') != -1: - if 'status' in args: - return mw.returnJson(False, '0') - con = con.replace('#log-bin=mysql-bin', 'log-bin=mysql-bin') - con = con.replace('#binlog_format=mixed', 'binlog_format=mixed') - mw.execShell('sync') - restart(version) - else: - path = getDataDir() - if 'status' in args: - dsize = 0 - for n in os.listdir(path): - if len(n) < 9: - continue - if n[0:9] == 'mysql-bin': - dsize += os.path.getsize(path + '/' + n) - return mw.returnJson(True, dsize) - con = con.replace('log-bin=mysql-bin', '#log-bin=mysql-bin') - con = con.replace('binlog_format=mixed', '#binlog_format=mixed') - mw.execShell('sync') - restart(version) - mw.execShell('rm -f ' + path + '/mysql-bin.*') - - mw.writeFile(conf, con) - return mw.returnJson(True, '设置成功!') - - -def setSkipGrantTables(v): - ''' - 设置是否密码验证 - ''' - conf = getConf() - con = mw.readFile(conf) - if v: - if con.find('#skip-grant-tables') != -1: - con = con.replace('#skip-grant-tables', 'skip-grant-tables') - else: - con = con.replace('skip-grant-tables', '#skip-grant-tables') - mw.writeFile(conf, con) - return True - -def binLogList(): - args = getArgs() - data = checkArgs(args, ['page', 'page_size', 'tojs']) - if not data[0]: - return data[1] - - page = int(args['page']) - page_size = int(args['page_size']) - - data_dir = getDataDir() - log_bin_name = getLogBinName() - - alist = os.listdir(data_dir) - log_bin_l = [] - for x in range(len(alist)): - f = alist[x] - t = {} - if f.startswith(log_bin_name) and not f.endswith('.index'): - abspath = data_dir + '/' + f - t['name'] = f - t['size'] = os.path.getsize(abspath) - t['time'] = mw.getDataFromInt(os.path.getctime(abspath)) - log_bin_l.append(t) - - log_bin_l = sorted(log_bin_l, key=lambda x: x['time'], reverse=True) - - # print(log_bin_l) - # print(data_dir, log_bin_name) - - count = len(log_bin_l) - - page_start = (page - 1) * page_size - page_end = page_start + page_size - if page_end > count: - page_end = count - - data = {} - page_args = {} - page_args['count'] = count - page_args['p'] = page - page_args['row'] = page_size - page_args['tojs'] = args['tojs'] - data['page'] = mw.getPage(page_args) - data['data'] = log_bin_l[page_start:page_end] - - return mw.getJson(data) - -def cleanBinLog(): - db = pMysqlDb() - cleanTime = time.strftime('%Y-%m-%d %H:%i:%s', time.localtime()) - db.execute("PURGE MASTER LOGS BEFORE '" + cleanTime + "';") - return mw.returnJson(True, '清理BINLOG成功!') - -def getErrorLog(): - args = getArgs() - filename = getErrorLogsFile() - if not os.path.exists(filename): - return mw.returnJson(False, '指定文件不存在!') - if 'close' in args: - mw.writeFile(filename, '') - return mw.returnJson(False, '日志已清空') - info = mw.getLastLine(filename, 18) - return mw.returnJson(True, 'OK', info) - - -def getShowLogFile(): - file = getConf() - content = mw.readFile(file) - rep = r'slow-query-log-file\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getMdb8Ver(): - return ['8.0','8.1','8.2','8.3','8.4','9.0','9.1'] - -def pGetDbUser(): - if mw.isAppleSystem(): - user = mw.execShell("who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() - return user - return 'mysql' - - -def initMysql57Data(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - user = pGetDbUser() - - cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + \ - datadir + ' --initialize-insecure --explicit_defaults_for_timestamp' - data = mw.execShell(cmd) - if data[1].lower().find('error') != -1: - exit("Init MySQL5.7 Data Error:"+data[1]) - - if not mw.isAppleSystem(): - mw.execShell('chown -R mysql:mysql ' + datadir) - mw.execShell('chmod -R 755 ' + datadir) - return False - return True - - -def initMysql8Data(): - ''' - chmod 644 /www/server/mysql-apt/etc/my.cnf - try: - mysqld --basedir=/usr --datadir=/www/server/mysql-apt/data --initialize-insecure - mysqld --defaults-file=/www/server/mysql-apt/etc/my.cnf --initialize-insecure - mysqld --initialize-insecure - select user, plugin from user; - update user set authentication_string=password("123123"),plugin='mysql_native_password' where user='root'; - ''' - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - user = pGetDbUser() - - cmd = serverdir + '/bin/mysqld --basedir=' + serverdir + ' --datadir=' + datadir + \ - ' --initialize-insecure --lower-case-table-names=1' - data = mw.execShell(cmd) - if data[1].lower().find('error') != -1: - exit("Init MySQL8+ Data Error:"+data[1]) - if data[1].lower().find('not found') != -1: - exit("Init MySQL8+ Data Error:"+data[1]) - - if not mw.isAppleSystem(): - mw.execShell('chown -R mysql:mysql ' + datadir) - mw.execShell('chmod -R 755 ' + datadir) - return False - return True - - -def initMysql8Pwd(): - ''' - /usr/bin/mysql --defaults-file=/www/server/mysql-apt/etc/my.cnf -uroot -e"UPDATE mysql.user SET password=PASSWORD('BhIroUczczNVaKvw') WHERE user='root';flush privileges;" - /usr/bin/mysql --defaults-file=/www/server/mysql-apt/etc/my.cnf -uroot -e"alter user 'root'@'localhost' identified by '123456';" - ''' - time.sleep(5) - - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - pwd = mw.getRandomString(16) - - cmd_my = serverdir + '/bin/mysql' - - cmd_pass = cmd_my + ' --defaults-file=' + myconf + ' -uroot -e' - cmd_pass = cmd_pass + '"alter user \'root\'@\'localhost\' identified by \'' + pwd + '\';' - cmd_pass = cmd_pass + 'flush privileges;"' - # print(cmd_pass) - data = mw.execShell(cmd_pass) - # print(data) - - # 删除空账户 - drop_empty_user = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + \ - pwd + ' -e "use mysql;delete from user where USER=\'\'"' - mw.execShell(drop_empty_user) - - # 删除测试数据库 - drop_test_db = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + \ - pwd + ' -e "drop database test";' - mw.execShell(drop_test_db) - - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - - # 删除冗余账户 - hostname = mw.execShell('hostname')[0].strip() - if hostname != 'localhost': - drop_hostname = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + pwd + ' -e "drop user \'\'@\'' + hostname + '\'";' - mw.execShell(drop_hostname) - - drop_root_hostname = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + pwd + ' -e "drop user \'root\'@\'' + hostname + '\'";' - mw.execShell(drop_root_hostname) - - return True - - -def my8cmd(version, method): - initDreplace(version) - # mysql 8.0 and 5.7 - mdb8 = getMdb8Ver() - try: - isInited = True - if mw.inArray(mdb8, version): - isInited = initMysql8Data() - else: - isInited = initMysql57Data() - - if not isInited: - if not mw.isSupportSystemctl(): - cmd_init_start = init_file + ' start' - subprocess.Popen(cmd_init_start, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - - time.sleep(6) - else: - mw.execShell('systemctl start '+getPluginName()) - - for x in range(10): - mydb_status = process_status() - if mydb_status == 'start': - initMysql8Pwd() - break - time.sleep(1) - - if not mw.isSupportSystemctl(): - cmd_init_stop = init_file + ' stop' - subprocess.Popen(cmd_init_stop, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - time.sleep(3) - else: - mw.execShell('systemctl stop ' + getPluginName()) - - if not mw.isSupportSystemctl(): - sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - sub.wait(5) - else: - mw.execShell('systemctl ' + method + ' '+getPluginName()) - return 'ok' - except Exception as e: - return str(e) - - -def appCMD(version, action): - return my8cmd(version, action) - - -def start(version=''): - return appCMD(version, 'start') - - -def stop(version=''): - return appCMD(version, 'stop') - - -def restart(version=''): - return appCMD(version, 'restart') - - -def reload(version=''): - return appCMD(version, 'reload') - - -def initdStatus(): - if mw.isAppleSystem(): - return "Apple Computer does not support" - - shell_cmd = 'systemctl status ' + \ - getPluginName() + ' | grep loaded | grep "enabled;"' - data = mw.execShell(shell_cmd) - if data[0] == '': - return 'fail' - return 'ok' - - -def initdInstall(): - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mw.execShell('systemctl enable ' + getPluginName()) - return 'ok' - - -def initdUinstall(): - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mw.execShell('systemctl disable ' + getPluginName()) - return 'ok' - - -def getMyDbPos(): - file = getConf() - content = mw.readFile(file) - rep = r'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def setMyDbPos(version=''): - args = getArgs() - data = checkArgs(args, ['datadir']) - if not data[0]: - return data[1] - - s_datadir = getMyDbPos() - t_datadir = args['datadir'] - if t_datadir == s_datadir: - return mw.returnJson(False, '与当前存储目录相同,无法迁移文件!') - - if not os.path.exists(t_datadir): - mw.execShell('mkdir -p ' + t_datadir) - - # mw.execShell('/etc/init.d/mysqld stop') - stop(version) - mw.execShell('cp -rf ' + s_datadir + '/* ' + t_datadir + '/') - mw.execShell('chown -R mysql mysql ' + t_datadir) - mw.execShell('chmod -R 755 ' + t_datadir) - mw.execShell('rm -f ' + t_datadir + '/*.pid') - mw.execShell('rm -f ' + t_datadir + '/*.err') - - path = getServerDir() - myfile = path + '/etc/my.cnf' - mycnf = mw.readFile(myfile) - mw.writeFile(path + '/etc/my_backup.cnf', mycnf) - - mycnf = mycnf.replace(s_datadir, t_datadir) - mw.writeFile(myfile, mycnf) - restart(version) - - result = mw.execShell( - 'ps aux|grep mysqld| grep -v grep|grep -v python') - if len(result[0]) > 10: - mw.writeFile('data/datadir.pl', t_datadir) - return mw.returnJson(True, '存储目录迁移成功!') - else: - mw.execShell('pkill -9 mysqld') - mw.writeFile(myfile, mw.readFile(path + '/etc/my_backup.cnf')) - start() - return mw.returnJson(False, '文件迁移失败!') - - -def getMyPort(): - file = getConf() - content = mw.readFile(file) - rep = r'port\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def setMyPort(): - args = getArgs() - data = checkArgs(args, ['port']) - if not data[0]: - return data[1] - - port = args['port'] - file = getConf() - content = mw.readFile(file) - rep = r"port\s*=\s*([0-9]+)\s*\n" - content = re.sub(rep, 'port = ' + port + '\n', content) - mw.writeFile(file, content) - restart() - return mw.returnJson(True, '编辑成功!') - - -def runInfo(version): - - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动', []) - - db = pMysqlDb() - data = db.query('show global status') - isError = isSqlError(data) - if isError != None: - return isError - - gets = ['Max_used_connections', 'Com_commit', 'Com_select', 'Com_rollback', 'Questions', 'Innodb_buffer_pool_reads', 'Innodb_buffer_pool_read_requests', 'Key_reads', 'Key_read_requests', 'Key_writes', - 'Key_write_requests', 'Qcache_hits', 'Qcache_inserts', 'Bytes_received', 'Bytes_sent', 'Aborted_clients', 'Aborted_connects', - 'Created_tmp_disk_tables', 'Created_tmp_tables', 'Innodb_buffer_pool_pages_dirty', 'Opened_files', 'Open_tables', 'Opened_tables', 'Select_full_join', - 'Select_range_check', 'Sort_merge_passes', 'Table_locks_waited', 'Threads_cached', 'Threads_connected', 'Threads_created', 'Threads_running', 'Connections', 'Uptime'] - - result = {} - # print(data) - for d in data: - vname = d["Variable_name"] - for g in gets: - if vname == g: - result[g] = d["Value"] - - # print(result, int(result['Uptime'])) - result['Run'] = int(time.time()) - int(result['Uptime']) - tmp = db.query('show master status') - try: - result['File'] = tmp[0]["File"] - result['Position'] = tmp[0]["Position"] - except: - result['File'] = 'OFF' - result['Position'] = 'OFF' - return mw.getJson(result) - - -def myDbStatus(version): - result = {} - db = pMysqlDb() - data = db.query('show variables') - isError = isSqlError(data) - if isError != None: - return isError - - gets = ['table_open_cache', 'thread_cache_size', 'key_buffer_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', - 'innodb_additional_mem_pool_size', 'innodb_log_buffer_size', 'max_connections', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] - - if version != "8.0": - gets.append('query_cache_size') - - result['mem'] = {} - for d in data: - vname = d['Variable_name'] - for g in gets: - # print(g) - if vname == g: - result['mem'][g] = d["Value"] - return mw.getJson(result) - - -def setDbStatus(version): - gets = ['key_buffer_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', 'innodb_log_buffer_size', 'max_connections', - 'table_open_cache', 'thread_cache_size', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] - - if version != "8.0": - # gets.append('query_cache_size') - gets = ['key_buffer_size', 'query_cache_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', 'innodb_log_buffer_size', 'max_connections', - 'table_open_cache', 'thread_cache_size', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] - - # print(gets) - emptys = ['max_connections', 'thread_cache_size', 'table_open_cache'] - args = getArgs() - conFile = getConf() - content = mw.readFile(conFile) - n = 0 - for g in gets: - s = 'M' - if n > 5: - s = 'K' - if g in emptys: - s = '' - rep = r'\s*' + g + r'\s*=\s*\d+(M|K|k|m|G)?\n' - c = g + ' = ' + args[g] + s + '\n' - if content.find(g) != -1: - content = re.sub(rep, '\n' + c, content, 1) - else: - content = content.replace('[mysqld]\n', '[mysqld]\n' + c) - n += 1 - mw.writeFile(conFile, content) - return mw.returnJson(True, '设置成功!') - - -def isSqlError(mysqlMsg): - # 检测数据库执行错误 - mysqlMsg = str(mysqlMsg) - if "MySQLdb" in mysqlMsg: - return mw.returnJson(False, 'err:' + str(mysqlMsg) + "\n" + 'MySQLdb组件缺失!
    进入SSH命令行输入: pip install mysql-python | pip install mysqlclient==2.0.3') - if "2002," in mysqlMsg: - return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') - if "2003," in mysqlMsg: - return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)") - if "using password:" in mysqlMsg: - return mw.returnJson(False, '数据库密码错误,在管理列表-点击【修复】!') - if "1045," in mysqlMsg: - return mw.returnJson(False, '连接错误!') - if "SQL syntax" in mysqlMsg: - return mw.returnJson(False, 'SQL语法错误!') - if "Connection refused" in mysqlMsg: - return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') - if "1133," in mysqlMsg: - return mw.returnJson(False, '数据库用户不存在!') - if "1007," in mysqlMsg: - return mw.returnJson(False, '数据库已经存在!') - return None - - -def __createUser(dbname, username, password, address): - pdb = pMysqlDb() - - if username == 'root': - dbname = '*' - - pdb.execute( - "CREATE USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, password)) - pdb.execute( - "grant all privileges on %s.* to `%s`@`localhost`" % (dbname, username)) - for a in address.split(','): - pdb.execute( - "CREATE USER `%s`@`%s` IDENTIFIED BY '%s'" % (username, a, password)) - pdb.execute( - "grant all privileges on %s.* to `%s`@`%s`" % (dbname, username, a)) - pdb.execute("flush privileges") - - -def getDbBackupListFunc(dbname=''): - - bkDir = getBackupDir() - if not os.path.exists(bkDir): - os.mkdir(bkDir) - - blist = os.listdir(bkDir) - r = [] - - bname = 'db_' + dbname - blen = len(bname) - for x in blist: - fbstr = x[0:blen] - if fbstr == bname: - r.append(x) - return r - - -def setDbBackup(): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - scDir = getPluginDir() + '/scripts/backup.py' - cmd = 'python3 ' + scDir + ' database ' + args['name'] + ' 3' - os.system(cmd) - return mw.returnJson(True, 'ok') - - -def rootPwd(): - return pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - - -def importDbExternal(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - import_dir = mw.getBackupDir() + '/import/' - - file_path = import_dir + file - if not os.path.exists(file_path): - return mw.returnJson(False, '文件突然消失?') - - exts = ['sql', 'gz', 'zip'] - ext = mw.getFileSuffix(file) - if ext not in exts: - return mw.returnJson(False, '导入数据库格式不对!') - - tmp = file.split('/') - tmpFile = tmp[len(tmp) - 1] - tmpFile = tmpFile.replace('.sql.' + ext, '.sql') - tmpFile = tmpFile.replace('.' + ext, '.sql') - tmpFile = tmpFile.replace('tar.', '') - - # print(tmpFile) - import_sql = "" - if file.find("sql.gz") > -1: - cmd = 'cd ' + import_dir + ' && gzip -dc ' + \ - file + " > " + import_dir + tmpFile - info = mw.execShell(cmd) - if info[1] == "": - import_sql = import_dir + tmpFile - - if file.find(".zip") > -1: - cmd = 'cd ' + import_dir + ' && unzip -o ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find("tar.gz") > -1: - cmd = 'cd ' + import_dir + ' && tar -zxvf ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find(".sql") > -1 and file.find(".sql.gz") == -1: - import_sql = import_dir + file - - if import_sql == "": - return mw.returnJson(False, '未找SQL文件') - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - - os.environ["MYSQL_PWD"] = pwd - mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + \ - pwd + ' ' + name + ' < ' + import_sql - - # print(mysql_cmd) - rdata = mw.execShell(mysql_cmd) - if ext != 'sql': - os.remove(import_sql) - - if rdata[1].lower().find('error') > -1: - return mw.returnJson(False, rdata[1]) - - return mw.returnJson(True, 'ok') - -def importDbExternalProgress(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && ' - cmd += 'python3 '+mw.getServerDir()+'/mdserver-web/plugins/mysql-apt/index.py import_db_external_progress_bar {"file":"'+file+'","name":"'+name+'"}' - return mw.returnJson(True, 'ok',cmd) - -def importDbExternalProgressBar(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - import_dir = mw.getFatherDir() + '/backup/import/' - - file_path = import_dir + file - if not os.path.exists(file_path): - return mw.returnJson(False, '文件突然消失?') - - exts = ['sql', 'gz', 'zip'] - ext = mw.getFileSuffix(file) - if ext not in exts: - return mw.returnJson(False, '导入数据库格式不对!') - - tmp = file.split('/') - tmpFile = tmp[len(tmp) - 1] - tmpFile = tmpFile.replace('.sql.' + ext, '.sql') - tmpFile = tmpFile.replace('.' + ext, '.sql') - tmpFile = tmpFile.replace('tar.', '') - - # print(tmpFile) - import_sql = "" - if file.find("sql.gz") > -1: - cmd = 'cd ' + import_dir + ' && gzip -dc ' + \ - file + " > " + import_dir + tmpFile - info = mw.execShell(cmd) - if info[1] == "": - import_sql = import_dir + tmpFile - - if file.find(".zip") > -1: - cmd = 'cd ' + import_dir + ' && unzip -o ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find("tar.gz") > -1: - cmd = 'cd ' + import_dir + ' && tar -zxvf ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find(".sql") > -1 and file.find(".sql.gz") == -1: - import_sql = import_dir + file - - if import_sql == "": - return mw.returnJson(False, '未找SQL文件') - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - - # option = '' - # mode = recognizeDbMode() - # if mode == 'gtid': - # option = ' --set-gtid-purged=off ' - - my_cnf = getConf() - mysql_cmd = getServerDir() + '/bin/mysql --defaults-file=' + my_cnf + \ - ' -uroot -p"' + pwd + '" -f ' + name - mysql_cmd_progress_bar = "pv -t -p " + import_sql + '|'+ mysql_cmd - print(mysql_cmd_progress_bar) - rdata = os.system(mysql_cmd_progress_bar) - return "" - -def importDbBackup(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - file_path = mw.getBackupDir() + '/database/' + file - file_path_sql = mw.getBackupDir() + '/database/' + file.replace('.gz', '') - - if not os.path.exists(file_path_sql): - cmd = 'cd ' + mw.getBackupDir() + '/database && gzip -d ' + file - mw.execShell(cmd) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ - ' ' + name + ' < ' + file_path_sql - - # print(mysql_cmd) - # os.system(mysql_cmd) - - rdata = mw.execShell(mysql_cmd) - if rdata[1].lower().find('error') > -1: - return mw.returnJson(False, rdata[1]) - - return mw.returnJson(True, 'ok') - - -def deleteDbBackup(): - args = getArgs() - data = checkArgs(args, ['filename', 'path']) - if not data[0]: - return data[1] - - path = args['path'] - full_file = "" - bkDir = getBackupDir() - full_file = bkDir + '/' + args['filename'] - if path != "": - full_file = path + "/" + args['filename'] - os.remove(full_file) - return mw.returnJson(True, 'ok') - - -def getDbBackupList(): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - r = getDbBackupListFunc(args['name']) - bkDir = getBackupDir() - rr = [] - for x in range(0, len(r)): - p = bkDir + '/' + r[x] - data = {} - data['name'] = r[x] - - rsize = os.path.getsize(p) - data['size'] = mw.toSize(rsize) - - t = os.path.getctime(p) - t = time.localtime(t) - - data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t) - rr.append(data) - - data['file'] = p - - return mw.returnJson(True, 'ok', rr) - - -def getDbBackupImportList(): - bkImportDir = mw.getBackupDir() + '/import' - if not os.path.exists(bkImportDir): - os.mkdir(bkImportDir) - - blist = os.listdir(bkImportDir) - - rr = [] - for x in range(0, len(blist)): - name = blist[x] - p = bkImportDir + '/' + name - data = {} - data['name'] = name - - rsize = os.path.getsize(p) - data['size'] = mw.toSize(rsize) - - t = os.path.getctime(p) - t = time.localtime(t) - - data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t) - rr.append(data) - - data['file'] = p - - rdata = { - "list": rr, - "upload_dir": bkImportDir, - } - return mw.returnJson(True, 'ok', rdata) - - -def getDbList(): - args = getArgs() - page = 1 - page_size = 10 - search = '' - data = {} - if 'page' in args: - page = int(args['page']) - - if 'page_size' in args: - page_size = int(args['page_size']) - - if 'search' in args: - search = args['search'] - - conn = pSqliteDb('databases') - limit = str((page - 1) * page_size) + ',' + str(page_size) - condition = '' - if not search == '': - condition = "name like '%" + search + "%'" - field = 'id,pid,name,username,password,accept,rw,ps,addtime' - clist = conn.where(condition, ()).field( - field).limit(limit).order('id desc').select() - - for x in range(0, len(clist)): - dbname = clist[x]['name'] - blist = getDbBackupListFunc(dbname) - # print(blist) - clist[x]['is_backup'] = False - if len(blist) > 0: - clist[x]['is_backup'] = True - - count = conn.where(condition, ()).count() - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = 'dbList' - data['page'] = mw.getPage(_page) - data['data'] = clist - - info = {} - info['root_pwd'] = pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root') - data['info'] = info - - return mw.getJson(data) - - -def syncGetDatabases(): - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - data = pdb.query('show databases') - isError = isSqlError(data) - if isError != None: - return isError - users = pdb.query( - "select User,Host from mysql.user where User!='root' AND Host!='localhost' AND Host!=''") - nameArr = ['information_schema', 'performance_schema', 'mysql', 'sys'] - n = 0 - - # print(users) - for value in data: - vdb_name = value["Database"] - b = False - for key in nameArr: - if vdb_name == key: - b = True - break - if b: - continue - if psdb.where("name=?", (vdb_name,)).count() > 0: - continue - host = '127.0.0.1' - for user in users: - if vdb_name == user["User"]: - host = user["Host"] - break - - ps = mw.getMsg('INPUT_PS') - if vdb_name == 'test': - ps = mw.getMsg('DATABASE_TEST') - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - if psdb.add('name,username,password,accept,ps,addtime', (vdb_name, vdb_name, '', host, ps, addTime)): - n += 1 - - msg = mw.getInfo('本次共从服务器获取了{1}个数据库!', (str(n),)) - return mw.returnJson(True, msg) - - -def toDbBase(find): - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - if len(find['password']) < 3: - find['username'] = find['name'] - find['password'] = mw.md5(str(time.time()) + find['name'])[0:10] - psdb.where("id=?", (find['id'],)).save( - 'password,username', (find['password'], find['username'])) - - result = pdb.execute("create database `" + find['name'] + "`") - if "using password:" in str(result): - return -1 - if "Connection refused" in str(result): - return -1 - - password = find['password'] - __createUser(find['name'], find['username'], password, find['accept']) - return 1 - - -def syncToDatabases(): - args = getArgs() - data = checkArgs(args, ['type', 'ids']) - if not data[0]: - return data[1] - - pdb = pMysqlDb() - result = pdb.execute("show databases") - isError = isSqlError(result) - if isError: - return isError - - stype = int(args['type']) - psdb = pSqliteDb('databases') - n = 0 - - if stype == 0: - data = psdb.field('id,name,username,password,accept').select() - for value in data: - result = toDbBase(value) - if result == 1: - n += 1 - else: - data = json.loads(args['ids']) - for value in data: - find = psdb.where("id=?", (value,)).field( - 'id,name,username,password,accept').find() - # print find - result = toDbBase(find) - if result == 1: - n += 1 - msg = mw.getInfo('本次共同步了{1}个数据库!', (str(n),)) - return mw.returnJson(True, msg) - - -def setRootPwd(version=''): - args = getArgs() - data = checkArgs(args, ['password']) - if not data[0]: - return data[1] - - #强制修改 - force = 0 - if 'force' in args and args['force'] == '1': - force = 1 - - password = args['password'] - try: - pdb = pMysqlDb() - result = pdb.query("show databases") - isError = isSqlError(result) - if isError != None: - if force == 1: - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (password,)) - return mw.returnJson(True, '【强制修改】数据库root密码修改成功(不意为成功连接数据)!') - return isError - - if version.find('5.7') > -1 or version.find('8.0') > -1: - pdb.execute( - "UPDATE mysql.user SET authentication_string='' WHERE user='root'") - pdb.execute( - "ALTER USER 'root'@'localhost' IDENTIFIED BY '%s'" % password) - pdb.execute( - "ALTER USER 'root'@'127.0.0.1' IDENTIFIED BY '%s'" % password) - else: - result = pdb.execute( - "update mysql.user set Password=password('" + password + "') where User='root'") - pdb.execute("flush privileges") - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (password,)) - - msg = '' - if force == 1: - msg = ',无须强制!' - return mw.returnJson(True, '数据库root密码修改成功!'+msg) - except Exception as ex: - return mw.returnJson(False, '修改错误:' + str(ex)) - -def setUserPwd(version=''): - args = getArgs() - data = checkArgs(args, ['password', 'name']) - if not data[0]: - return data[1] - - newpassword = args['password'] - username = args['name'] - uid = args['id'] - try: - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - name = psdb.where('id=?', (uid,)).getField('name') - - if version.find('5.7') > -1 or version.find('8.0') > -1: - accept = pdb.query( - "select Host from mysql.user where User='" + name + "' AND Host!='localhost'") - t1 = pdb.execute( - "update mysql.user set authentication_string='' where User='" + username + "'") - # print(t1) - result = pdb.execute( - "ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, newpassword)) - # print(result) - for my_host in accept: - t2 = pdb.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ( - username, my_host["Host"], newpassword)) - # print(t2) - else: - result = pdb.execute("update mysql.user set Password=password('" + - newpassword + "') where User='" + username + "'") - - pdb.execute("flush privileges") - psdb.where("id=?", (uid,)).setField('password', newpassword) - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]密码成功!', (name,))) - except Exception as ex: - return mw.returnJson(False, mw.getInfo('修改数据库[{1}]密码失败[{2}]!', (name, str(ex),))) - - -def setDbPs(): - args = getArgs() - data = checkArgs(args, ['id', 'name', 'ps']) - if not data[0]: - return data[1] - - ps = args['ps'] - sid = args['id'] - name = args['name'] - try: - psdb = pSqliteDb('databases') - psdb.where("id=?", (sid,)).setField('ps', ps) - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]备注成功!', (name,))) - except Exception as e: - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]备注失败!', (name,))) - - -def addDb(): - args = getArgs() - data = checkArgs(args, - ['password', 'name', 'codeing', 'db_user', 'dataAccess', 'ps']) - if not data[0]: - return data[1] - - if not 'address' in args: - address = '' - else: - address = args['address'].strip() - - dbname = args['name'].strip() - dbuser = args['db_user'].strip() - codeing = args['codeing'].strip() - password = args['password'].strip() - dataAccess = args['dataAccess'].strip() - ps = args['ps'].strip() - - reg = r"^[\w-]+$" - if not re.match(reg, args['name']): - return mw.returnJson(False, '数据库名称不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'performance_schema','information_schema'] - if dbuser in checks or len(dbuser) < 1: - return mw.returnJson(False, '数据库用户名不合法!') - if dbname in checks or len(dbname) < 1: - return mw.returnJson(False, '数据库名称不合法!') - - if len(password) < 1: - password = mw.md5(time.time())[0:8] - - wheres = { - 'utf8': 'utf8_general_ci', - 'utf8mb4': 'utf8mb4_general_ci', - 'gbk': 'gbk_chinese_ci', - 'big5': 'big5_chinese_ci' - } - codeStr = wheres[codeing] - - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - - if psdb.where("name=? or username=?", (dbname, dbuser)).count(): - return mw.returnJson(False, '数据库已存在!') - - result = pdb.execute("create database `" + dbname + - "` DEFAULT CHARACTER SET " + codeing + " COLLATE " + codeStr) - # print result - isError = isSqlError(result) - if isError != None: - return isError - - pdb.execute("drop user '" + dbuser + "'@'localhost'") - for a in address.split(','): - pdb.execute("drop user '" + dbuser + "'@'" + a + "'") - - __createUser(dbname, dbuser, password, address) - - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - psdb.add('pid,name,username,password,accept,ps,addtime', - (0, dbname, dbuser, password, address, ps, addTime)) - return mw.returnJson(True, '添加成功!') - - -def delDb(): - args = getArgs() - data = checkArgs(args, ['id', 'name']) - if not data[0]: - return data[1] - try: - sid = args['id'] - name = args['name'] - psdb = pSqliteDb('databases') - pdb = pMysqlDb() - find = psdb.where("id=?", (sid,)).field( - 'id,pid,name,username,password,accept,ps,addtime').find() - accept = find['accept'] - username = find['username'] - - # 删除MYSQL - result = pdb.execute("drop database `" + name + "`") - - users = pdb.query("select Host from mysql.user where User='" + - username + "' AND Host!='localhost'") - pdb.execute("drop user '" + username + "'@'localhost'") - for us in users: - pdb.execute("drop user '" + username + "'@'" + us["Host"] + "'") - pdb.execute("flush privileges") - - # 删除SQLITE - psdb.where("id=?", (sid,)).delete() - return mw.returnJson(True, '删除成功!') - except Exception as ex: - return mw.returnJson(False, '删除失败!' + str(ex)) - - -def getDbAccess(): - args = getArgs() - data = checkArgs(args, ['username']) - if not data[0]: - return data[1] - username = args['username'] - pdb = pMysqlDb() - - users = pdb.query("select Host from mysql.user where User='" + - username + "' AND Host!='localhost'") - - isError = isSqlError(users) - if isError != None: - return isError - - if len(users) < 1: - return mw.returnJson(True, "127.0.0.1") - accs = [] - for c in users: - accs.append(c["Host"]) - userStr = ','.join(accs) - return mw.returnJson(True, userStr) - - -def setDbAccess(): - args = getArgs() - data = checkArgs(args, ['username', 'access']) - if not data[0]: - return data[1] - name = args['username'] - access = args['access'] - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - - dbname = psdb.where('username=?', (name,)).getField('name') - - if name == 'root': - password = pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root') - else: - password = psdb.where("username=?", (name,)).getField('password') - - users = pdb.query("select Host from mysql.user where User='" + - name + "' AND Host!='localhost'") - - for us in users: - pdb.execute("drop user '" + name + "'@'" + us["Host"] + "'") - - __createUser(dbname, name, password, access) - - psdb.where('username=?', (name,)).save('accept,rw', (access, 'rw',)) - return mw.returnJson(True, '设置成功!') - - - -def openSkipGrantTables(): - mycnf = getConf() - content = mw.readFile(mycnf) - content = content.replace('#skip-grant-tables','skip-grant-tables') - mw.writeFile(mycnf, content) - return True - -def closeSkipGrantTables(): - mycnf = getConf() - content = mw.readFile(mycnf) - content = content.replace('skip-grant-tables','#skip-grant-tables') - mw.writeFile(mycnf, content) - return True - - -def resetDbRootPwd(version): - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - pwd = mw.getRandomString(16) - - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - mdb8 = getMdb8Ver() - if not mw.inArray(mdb8, version): - cmd_pass = serverdir + '/bin/mysql --defaults-file=' + myconf + ' -uroot -e' - cmd_pass = cmd_pass + '"UPDATE mysql.user SET password=PASSWORD(\'' + pwd + "') WHERE user='root';" - cmd_pass = cmd_pass + 'flush privileges;"' - data = mw.execShell(cmd_pass) - # print(data) - else: - auth_policy = getAuthPolicy() - - reset_pwd = 'flush privileges;' - reset_pwd = reset_pwd + \ - "UPDATE mysql.user SET authentication_string='' WHERE user='root';" - reset_pwd = reset_pwd + "flush privileges;" - reset_pwd = reset_pwd + \ - "alter user 'root'@'localhost' IDENTIFIED by '" + pwd + "';" - reset_pwd = reset_pwd + \ - "alter user 'root'@'localhost' IDENTIFIED WITH "+auth_policy+" by '" + pwd + "';" - reset_pwd = reset_pwd + "flush privileges;" - - tmp_file = "/tmp/mysql_init_tmp.log" - mw.writeFile(tmp_file, reset_pwd) - cmd_pass = serverdir + '/bin/mysql --defaults-file=' + myconf + ' -uroot -proot < ' + tmp_file - - data = mw.execShell(cmd_pass) - # print(data) - os.remove(tmp_file) - return True - -def fixDbAccess2(version): - try: - pdb = pMysqlDb() - data = pdb.query('show databases') - isError = isSqlError(data) - if isError != None: - appCMD(version, 'stop') - mw.execShell("rm -rf " + getServerDir() + "/data") - appCMD(version, 'start') - return mw.returnJson(True, '修复成功!') - return mw.returnJson(True, '正常无需修复!') - except Exception as e: - return mw.returnJson(False, '修复失败请重试!') - -def fixDbAccess(version): - - pdb = pMysqlDb() - mdb_ddir = getDataDir() - if not os.path.exists(mdb_ddir): - return mw.returnJson(False, '数据目录不存在,尝试重启重建!') - - try: - data = pdb.query('show databases') - isError = isSqlError(data) - if isError != None: - - # 重置密码 - appCMD(version, 'stop') - openSkipGrantTables() - appCMD(version, 'start') - time.sleep(3) - resetDbRootPwd(version) - - appCMD(version, 'stop') - closeSkipGrantTables() - appCMD(version, 'start') - - return mw.returnJson(True, '修复成功!') - return mw.returnJson(True, '正常无需修复!') - except Exception as e: - return mw.returnJson(False, '修复失败请重试!') - - - -def setDbRw(version=''): - args = getArgs() - data = checkArgs(args, ['username', 'id', 'rw']) - if not data[0]: - return data[1] - - username = args['username'] - uid = args['id'] - rw = args['rw'] - - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - dbname = psdb.where("id=?", (uid,)).getField('name') - users = pdb.query( - "select Host from mysql.user where User='" + username + "'") - - # show grants for demo@"127.0.0.1"; - for x in users: - # REVOKE ALL PRIVILEGES ON `imail`.* FROM 'imail'@'127.0.0.1'; - - sql = "REVOKE ALL PRIVILEGES ON `" + dbname + \ - "`.* FROM '" + username + "'@'" + x["Host"] + "';" - r = pdb.query(sql) - # print(sql, r) - - if rw == 'rw': - sql = "GRANT SELECT, INSERT, UPDATE, DELETE ON " + dbname + ".* TO " + \ - username + "@'" + x["Host"] + "'" - elif rw == 'r': - sql = "GRANT SELECT ON " + dbname + ".* TO " + \ - username + "@'" + x["Host"] + "'" - else: - sql = "GRANT all privileges ON " + dbname + ".* TO " + \ - username + "@'" + x["Host"] + "'" - pdb.execute(sql) - pdb.execute("flush privileges") - r = psdb.where("id=?", (uid,)).setField('rw', rw) - # print(r) - return mw.returnJson(True, '切换成功!') - - -def getDbInfo(): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - db_name = args['name'] - pdb = pMysqlDb() - # print 'show tables from `%s`' % db_name - tables = pdb.query('show tables from `%s`' % db_name) - - ret = {} - sql = "select sum(DATA_LENGTH)+sum(INDEX_LENGTH) as sum_size from information_schema.tables where table_schema='%s'" % db_name - data_sum = pdb.query(sql) - - data = 0 - if data_sum[0]['sum_size'] != None: - data = data_sum[0]['sum_size'] - - ret['data_size'] = mw.toSize(data) - ret['database'] = db_name - - ret3 = [] - table_key = "Tables_in_" + db_name - for i in tables: - tb_sql = "show table status from `%s` where name = '%s'" % (db_name, i[ - table_key]) - table = pdb.query(tb_sql) - - tmp = {} - tmp['type'] = table[0]["Engine"] - tmp['rows_count'] = table[0]["Rows"] - tmp['collation'] = table[0]["Collation"] - - data_size = 0 - if table[0]['Avg_row_length'] != None: - data_size = table[0]['Avg_row_length'] - - if table[0]['Data_length'] != None: - data_size = table[0]['Data_length'] - - tmp['data_byte'] = data_size - tmp['data_size'] = mw.toSize(data_size) - tmp['table_name'] = table[0]["Name"] - ret3.append(tmp) - - ret['tables'] = (ret3) - - return mw.getJson(ret) - - -def repairTable(): - args = getArgs() - data = checkArgs(args, ['db_name', 'tables']) - if not data[0]: - return data[1] - - db_name = args['db_name'] - tables = json.loads(args['tables']) - pdb = pMysqlDb() - mtable = pdb.query('show tables from `%s`' % db_name) - - ret = [] - key = "Tables_in_" + db_name - for i in mtable: - for tn in tables: - if tn == i[key]: - ret.append(tn) - - if len(ret) > 0: - for i in ret: - pdb.execute('REPAIR TABLE `%s`.`%s`' % (db_name, i)) - return mw.returnJson(True, "修复完成!") - return mw.returnJson(False, "修复失败!") - - -def optTable(): - args = getArgs() - data = checkArgs(args, ['db_name', 'tables']) - if not data[0]: - return data[1] - - db_name = args['db_name'] - tables = json.loads(args['tables']) - pdb = pMysqlDb() - mtable = pdb.query('show tables from `%s`' % db_name) - ret = [] - key = "Tables_in_" + db_name - for i in mtable: - for tn in tables: - if tn == i[key]: - ret.append(tn) - - if len(ret) > 0: - for i in ret: - pdb.execute('OPTIMIZE TABLE `%s`.`%s`' % (db_name, i)) - return mw.returnJson(True, "优化成功!") - return mw.returnJson(False, "优化失败或者已经优化过了!") - - -def alterTable(): - args = getArgs() - data = checkArgs(args, ['db_name', 'tables']) - if not data[0]: - return data[1] - - db_name = args['db_name'] - tables = json.loads(args['tables']) - table_type = args['table_type'] - pdb = pMysqlDb() - mtable = pdb.query('show tables from `%s`' % db_name) - - ret = [] - key = "Tables_in_" + db_name - for i in mtable: - for tn in tables: - if tn == i[key]: - ret.append(tn) - - if len(ret) > 0: - for i in ret: - pdb.execute('alter table `%s`.`%s` ENGINE=`%s`' % - (db_name, i, table_type)) - return mw.returnJson(True, "更改成功!") - return mw.returnJson(False, "更改失败!") - - -def getTotalStatistics(): - st = status() - data = {} - - isInstall = os.path.exists(getServerDir() + '/version.pl') - - if st == 'start' and isInstall: - data['status'] = True - data['count'] = pSqliteDb('databases').count() - data['ver'] = mw.readFile(getServerDir() + '/version.pl').strip() - return mw.returnJson(True, 'ok', data) - else: - data['status'] = False - data['count'] = 0 - return mw.returnJson(False, 'fail', data) - - -def recognizeDbMode(): - conf = getConf() - con = mw.readFile(conf) - rep = r"!include %s/(.*)?\.cnf" % (getServerDir() + "/etc/mode",) - mode = 'none' - try: - data = re.findall(rep, con, re.M) - mode = data[0] - except Exception as e: - pass - return mode - - -def getDbrunMode(version=''): - mode = recognizeDbMode() - return mw.returnJson(True, "ok", {'mode': mode}) - - -def setDbrunMode(version=''): - if version == '5.5': - return mw.returnJson(False, "不支持切换") - - args = getArgs() - data = checkArgs(args, ['mode', 'reload']) - if not data[0]: - return data[1] - - mode = args['mode'] - dbreload = args['reload'] - - if not mode in ['classic', 'gtid']: - return mw.returnJson(False, "mode的值无效:" + mode) - - origin_mode = recognizeDbMode() - path = getConf() - con = mw.readFile(path) - rep = r"!include %s/%s\.cnf" % (getServerDir() + "/etc/mode", origin_mode) - rep_after = "!include %s/%s.cnf" % (getServerDir() + "/etc/mode", mode) - con = re.sub(rep, rep_after, con) - mw.writeFile(path, con) - - if version == '5.6': - dbreload = 'yes' - else: - db = pMysqlDb() - # The value of @@GLOBAL.GTID_MODE can only be changed one step at a - # time: OFF <-> OFF_PERMISSIVE <-> ON_PERMISSIVE <-> ON. Also note that - # this value must be stepped up or down simultaneously on all servers. - # See the Manual for instructions. - if mode == 'classic': - db.query('set global enforce_gtid_consistency=off') - db.query('set global gtid_mode=on') - db.query('set global gtid_mode=on_permissive') - db.query('set global gtid_mode=off_permissive') - db.query('set global gtid_mode=off') - elif mode == 'gtid': - db.query('set global enforce_gtid_consistency=on') - db.query('set global gtid_mode=off') - db.query('set global gtid_mode=off_permissive') - db.query('set global gtid_mode=on_permissive') - db.query('set global gtid_mode=on') - - if dbreload == "yes": - restart(version) - - return mw.returnJson(True, "切换成功!") - - -def findBinlogDoDb(): - conf = getConf() - con = mw.readFile(conf) - rep = r"binlog-do-db\s*?=\s*?(.*)" - dodb = re.findall(rep, con, re.M) - return dodb - - -def findBinlogSlaveDoDb(): - conf = getConf() - con = mw.readFile(conf) - rep = r"replicate-do-db\s*?=\s*?(.*)" - dodb = re.findall(rep, con, re.M) - return dodb - - -def setDbMasterAccess(): - args = getArgs() - data = checkArgs(args, ['username', 'access']) - if not data[0]: - return data[1] - username = args['username'] - access = args['access'] - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - password = psdb.where("username=?", (username,)).getField('password') - users = pdb.query("select Host from mysql.user where User='" + - username + "' AND Host!='localhost'") - for us in users: - pdb.execute("drop user '" + username + "'@'" + us["Host"] + "'") - - dbname = '*' - for a in access.split(','): - pdb.execute( - "CREATE USER `%s`@`%s` IDENTIFIED BY '%s'" % (username, a, password)) - pdb.execute( - "grant all privileges on %s.* to `%s`@`%s`" % (dbname, username, a)) - - pdb.execute("flush privileges") - psdb.where('username=?', (username,)).save('accept', (access,)) - return mw.returnJson(True, '设置成功!') - - -def resetMaster(version=''): - pdb = pMysqlDb() - r = pdb.execute('reset master') - isError = isSqlError(r) - if isError != None: - return isError - return mw.returnJson(True, '重置成功!') - - -def getMasterDbList(version=''): - try: - args = getArgs() - page = 1 - page_size = 10 - search = '' - data = {} - if 'page' in args: - page = int(args['page']) - - if 'page_size' in args: - page_size = int(args['page_size']) - - if 'search' in args: - search = args['search'] - - conn = pSqliteDb('databases') - limit = str((page - 1) * page_size) + ',' + str(page_size) - condition = '' - dodb = findBinlogDoDb() - data['dodb'] = dodb - - slave_dodb = findBinlogSlaveDoDb() - - if not search == '': - condition = "name like '%" + search + "%'" - field = 'id,pid,name,username,password,accept,ps,addtime' - clist = conn.where(condition, ()).field( - field).limit(limit).order('id desc').select() - count = conn.where(condition, ()).count() - - for x in range(0, len(clist)): - if clist[x]['name'] in dodb: - clist[x]['master'] = 1 - else: - clist[x]['master'] = 0 - - if clist[x]['name'] in slave_dodb: - clist[x]['slave'] = 1 - else: - clist[x]['slave'] = 0 - - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = 'dbList' - data['page'] = mw.getPage(_page) - data['data'] = clist - return mw.getJson(data) - except Exception as e: - return mw.returnJson(False, "数据库密码错误,在管理列表-点击【修复】!") - - -def setDbMaster(version): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - conf = getConf() - con = mw.readFile(conf) - rep = r"(binlog-do-db\s*?=\s*?(.*))" - dodb = re.findall(rep, con, re.M) - - isHas = False - for x in range(0, len(dodb)): - - if dodb[x][1] == args['name']: - isHas = True - - con = con.replace(dodb[x][0] + "\n", '') - mw.writeFile(conf, con) - - if not isHas: - prefix = '#binlog-do-db' - con = con.replace( - prefix, prefix + "\nbinlog-do-db=" + args['name']) - mw.writeFile(conf, con) - - restart(version) - time.sleep(4) - return mw.returnJson(True, '设置成功', [args, dodb]) - - -def setDbSlave(version): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - conf = getConf() - con = mw.readFile(conf) - rep = r"(replicate-do-db\s*?=\s*?(.*))" - dodb = re.findall(rep, con, re.M) - - isHas = False - for x in range(0, len(dodb)): - if dodb[x][1] == args['name']: - isHas = True - - con = con.replace(dodb[x][0] + "\n", '') - mw.writeFile(conf, con) - - if not isHas: - prefix = '#replicate-do-db' - con = con.replace( - prefix, prefix + "\nreplicate-do-db=" + args['name']) - mw.writeFile(conf, con) - - restart(version) - time.sleep(4) - return mw.returnJson(True, '设置成功', [args, dodb]) - - -def getMasterStatus(version=''): - - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动,或正在启动中...!', []) - - query_status_cmd = 'show slave status' - mdb8 = getMdb8Ver() - is_mdb8 = False - if mw.inArray(mdb8, version): - is_mdb8 = True - query_status_cmd = 'show replica status' - - try: - conf = getConf() - content = mw.readFile(conf) - master_status = False - if content.find('#log-bin') == -1 and content.find('log-bin') > 1: - dodb = findBinlogDoDb() - if len(dodb) > 0: - master_status = True - - data = {} - data['mode'] = recognizeDbMode() - data['status'] = master_status - - db = pMysqlDb() - dlist = db.query(query_status_cmd) - - # print(dlist[0]) - if is_mdb8: - if len(dlist) > 0 and (dlist[0]["Replica_IO_Running"] == 'Yes' or dlist[0]["Replica_SQL_Running"] == 'Yes'): - data['slave_status'] = True - else: - if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'): - data['slave_status'] = True - - return mw.returnJson(master_status, '设置成功', data) - except Exception as e: - return mw.returnJson(False, "数据库密码错误,在管理列表-点击【修复】!", 'pwd') - - -def setMasterStatus(version=''): - - conf = getConf() - con = mw.readFile(conf) - - if con.find('#log-bin') != -1: - return mw.returnJson(False, '必须开启二进制日志') - - sign = 'mdserver_ms_open' - - dodb = findBinlogDoDb() - if not sign in dodb: - prefix = '#binlog-do-db' - con = con.replace(prefix, prefix + "\nbinlog-do-db=" + sign) - mw.writeFile(conf, con) - else: - con = con.replace("binlog-do-db=" + sign + "\n", '') - rep = r"(binlog-do-db\s*?=\s*?(.*))" - dodb = re.findall(rep, con, re.M) - for x in range(0, len(dodb)): - con = con.replace(dodb[x][0] + "\n", '') - mw.writeFile(conf, con) - - restart(version) - return mw.returnJson(True, '设置成功') - - -def getMasterRepSlaveList(version=''): - args = getArgs() - page = 1 - page_size = 10 - search = '' - data = {} - if 'page' in args: - page = int(args['page']) - - if 'page_size' in args: - page_size = int(args['page_size']) - - if 'search' in args: - search = args['search'] - - conn = pSqliteDb('master_replication_user') - limit = str((page - 1) * page_size) + ',' + str(page_size) - condition = '' - - if not search == '': - condition = "name like '%" + search + "%'" - field = 'id,username,password,accept,ps,addtime' - clist = conn.where(condition, ()).field( - field).limit(limit).order('id desc').select() - count = conn.where(condition, ()).count() - - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = 'getMasterRepSlaveList' - data['page'] = mw.getPage(_page) - data['data'] = clist - - return mw.getJson(data) - - -def addMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username', 'password']) - if not data[0]: - return data[1] - - address = '' - if 'address' in args: - address = args['address'].strip() - - username = args['username'].strip() - password = args['password'].strip() - # ps = args['ps'].strip() - # address = args['address'].strip() - # dataAccess = args['dataAccess'].strip() - - reg = r"^[\w-]+$" - if not re.match(reg, username): - return mw.returnJson(False, '用户名不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'performance_schema','information_schema'] - if username in checks or len(username) < 1: - return mw.returnJson(False, '用户名不合法!') - if password in checks or len(password) < 1: - return mw.returnJson(False, '密码不合法!') - - if len(password) < 1: - password = mw.md5(time.time())[0:8] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - - if psdb.where("username=?", (username)).count() > 0: - return mw.returnJson(False, '用户已存在!') - - mdb8 = ['8.0','8.1','8.2','8.3','8.4'] - if mw.inArray(mdb8,version): - sql = "CREATE USER '" + username + \ - "' IDENTIFIED WITH mysql_native_password BY '" + password + "';" - pdb.execute(sql) - sql = "grant replication slave on *.* to '" + username + "'@'%';" - result = pdb.execute(sql) - isError = isSqlError(result) - if isError != None: - return isError - - else: - sql = "GRANT REPLICATION SLAVE ON *.* TO '" + username + \ - "'@'%' identified by '" + password + "';" - result = pdb.execute(sql) - isError = isSqlError(result) - if isError != None: - return isError - - sql_select = "grant select,reload,REPLICATION CLIENT,PROCESS on *.* to " + username + "@'%';" - pdb.execute(sql_select) - pdb.execute('FLUSH PRIVILEGES;') - - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - psdb.add('username,password,accept,ps,addtime',(username, password, '%', '', addTime)) - return mw.returnJson(True, '添加成功!') - - -def getMasterRepSlaveUserCmd(version): - - args = getArgs() - data = checkArgs(args, ['username', 'db']) - if not data[0]: - return data[1] - - psdb = pSqliteDb('master_replication_user') - f = 'username,password' - username = args['username'] - if username == '': - count = psdb.count() - if count == 0: - return mw.returnJson(False, '请添加同步账户!') - - clist = psdb.field(f).limit('1').order('id desc').select() - else: - clist = psdb.field(f).where("username=?", (username,)).limit( - '1').order('id desc').select() - - ip = mw.getLocalIp() - port = getMyPort() - db = pMysqlDb() - - mstatus = db.query('show master status') - if len(mstatus) == 0: - return mw.returnJson(False, '未开启!') - - mode = recognizeDbMode() - - sid = getDbServerId() - channel_name = "" - if sid != '': - channel_name = " for channel 'r{}'".format(sid) - - mdb8 = ['8.0','8.1','8.2','8.3','8.4'] - sql = '' - if not mw.inArray(mdb8,version): - base_sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \ - clist[0]['username'] + "', MASTER_PASSWORD='" + clist[0]['password'] + "'" - - sql += base_sql; - sql += "

    "; - # sql += base_sql + ", MASTER_AUTO_POSITION=1" + channel_name - sql += base_sql + channel_name - sql += "

    "; - - sql += base_sql + ", MASTER_LOG_FILE='" + mstatus[0]["File"] + "',MASTER_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name - else: - base_sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \ - clist[0]['username'] + "', SOURCE_PASSWORD='" + clist[0]['password']+"'" - sql += base_sql; - sql += "

    "; - # sql += base_sql + ", MASTER_AUTO_POSITION=1" + channel_name - sql += base_sql + channel_name - sql += "

    "; - sql += base_sql + ", SOURCE_LOG_FILE='" + mstatus[0]["File"] + "',SOURCE_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name - - - data = {} - data['cmd'] = sql - data["info"] = clist[0] - data['mode'] = mode - - return mw.returnJson(True, 'ok!', data) - - -def delMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username']) - if not data[0]: - return data[1] - - name = args['username'] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - pdb.execute("drop user '" + name + "'@'%'") - pdb.execute("drop user '" + name + "'@'localhost'") - - users = pdb.query("select Host from mysql.user where User='" + - name + "' AND Host!='localhost'") - for us in users: - pdb.execute("drop user '" + name + "'@'" + us["Host"] + "'") - - psdb.where("username=?", (args['username'],)).delete() - - return mw.returnJson(True, '删除成功!') - - -def updateMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username', 'password']) - if not data[0]: - return data[1] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - pdb.execute("drop user '" + args['username'] + "'@'%'") - - pdb.execute("GRANT REPLICATION SLAVE ON *.* TO '" + - args['username'] + "'@'%' identified by '" + args['password'] + "'") - - psdb.where("username=?", (args['username'],)).save( - 'password', args['password']) - - return mw.returnJson(True, '更新成功!') - - -def getSlaveSSHList(version=''): - args = getArgs() - data = checkArgs(args, ['page', 'page_size']) - if not data[0]: - return data[1] - - page = int(args['page']) - page_size = int(args['page_size']) - - conn = pSqliteDb('slave_id_rsa') - limit = str((page - 1) * page_size) + ',' + str(page_size) - - field = 'id,ip,port,db_user,id_rsa,ps,addtime' - clist = conn.field(field).limit(limit).order('id desc').select() - count = conn.count() - - data = {} - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = args['tojs'] - data['page'] = mw.getPage(_page) - data['data'] = clist - - return mw.getJson(data) - - -def getSlaveSyncUserByIp(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_sync_user') - data = conn.field('ip,port,user,pass,mode,cmd').where( - "ip=?", (ip,)).select() - return mw.returnJson(True, 'ok', data) - - -def addSlaveSyncUser(version=''): - import base64 - - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - if ip == "": - return mw.returnJson(True, 'ok') - - data = checkArgs(args, ['port', 'user', 'pass', 'mode']) - if not data[0]: - return data[1] - - cmd = args['cmd'] - port = args['port'] - user = args['user'] - apass = args['pass'] - mode = args['mode'] - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - - conn = pSqliteDb('slave_sync_user') - data = conn.field('ip').where("ip=?", (ip,)).select() - if len(data) > 0: - res = conn.where("ip=?", (ip,)).save( - 'port,user,pass,mode,cmd', (port, user, apass, mode, cmd)) - else: - conn.add('ip,port,user,cmd,user,pass,mode,addtime', - (ip, port, user, cmd, user, apass, mode, addTime)) - - return mw.returnJson(True, '设置成功!') - - -def delSlaveSyncUser(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_sync_user') - conn.where("ip=?", (ip,)).delete() - return mw.returnJson(True, '删除成功!') - - -def getSlaveSyncUserList(version=''): - args = getArgs() - data = checkArgs(args, ['page', 'page_size']) - if not data[0]: - return data[1] - - page = int(args['page']) - page_size = int(args['page_size']) - - conn = pSqliteDb('slave_sync_user') - limit = str((page - 1) * page_size) + ',' + str(page_size) - - field = 'id,ip,port,user,pass,cmd,addtime' - clist = conn.field(field).limit(limit).order('id desc').select() - count = conn.count() - - data = {} - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = args['tojs'] - data['page'] = mw.getPage(_page) - data['data'] = clist - - return mw.getJson(data) - - -def getSyncModeFile(): - return getServerDir() + "/sync.mode" - - -def getSlaveSyncMode(version): - sync_mode = getSyncModeFile() - if os.path.exists(sync_mode): - mode = mw.readFile(sync_mode).strip() - return mw.returnJson(True, 'ok', mode) - return mw.returnJson(False, 'fail') - - -def setSlaveSyncMode(version): - args = getArgs() - data = checkArgs(args, ['mode']) - if not data[0]: - return data[1] - mode = args['mode'] - sync_mode = getSyncModeFile() - - if mode == 'none': - os.remove(sync_mode) - else: - mw.writeFile(sync_mode, mode) - return mw.returnJson(True, '设置成功', mode) - - -def getSlaveSSHByIp(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_id_rsa') - data = conn.field('ip,port,db_user,id_rsa').where("ip=?", (ip,)).select() - return mw.returnJson(True, 'ok', data) - - -def addSlaveSSH(version=''): - import base64 - - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - if ip == "": - return mw.returnJson(True, 'ok') - - data = checkArgs(args, ['port', 'id_rsa', 'db_user']) - if not data[0]: - return data[1] - - id_rsa = args['id_rsa'] - port = args['port'] - db_user = args['db_user'] - user = 'root' - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - - conn = pSqliteDb('slave_id_rsa') - data = conn.field('ip,id_rsa').where("ip=?", (ip,)).select() - if len(data) > 0: - res = conn.where("ip=?", (ip,)).save( - 'port,id_rsa,db_user', (port, id_rsa, db_user)) - else: - conn.add('ip,port,user,id_rsa,db_user,ps,addtime', - (ip, port, user, id_rsa, db_user, '', addTime)) - - return mw.returnJson(True, '设置成功!') - - -def delSlaveSSH(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_id_rsa') - conn.where("ip=?", (ip,)).delete() - return mw.returnJson(True, 'ok') - - -def updateSlaveSSH(version=''): - args = getArgs() - data = checkArgs(args, ['ip', 'id_rsa']) - if not data[0]: - return data[1] - - ip = args['ip'] - id_rsa = args['id_rsa'] - conn = pSqliteDb('slave_id_rsa') - conn.where("ip=?", (ip,)).save('id_rsa', (id_rsa,)) - return mw.returnJson(True, 'ok') - - -def getSlaveList(version=''): - - query_status_cmd = 'show slave status' - mdb8 = getMdb8Ver() - if mw.inArray(mdb8, version): - query_status_cmd = 'show replica status' - - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动', []) - - db = pMysqlDb() - dlist = db.query(query_status_cmd) - - # print(dlist) - data = {} - data['data'] = dlist - return mw.getJson(data) - -def trySlaveSyncBugfix(version=''): - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动', []) - - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - if mode != 'sync-user': - return mw.returnJson(False, '仅支持【同步账户】模式') - - conn = pSqliteDb('slave_sync_user') - slave_sync_data = conn.field('ip,port,user,pass,mode,cmd').select() - if len(slave_sync_data) < 1: - return mw.returnJson(False, '需要先添加【同步用户】配置!') - - # print(slave_sync_data) - # 本地从库 - sdb = pMysqlDb() - - gtid_purged = '' - - for i in range(len(slave_sync_data)): - port = slave_sync_data[i]['port'] - password = slave_sync_data[i]['pass'] - host = slave_sync_data[i]['ip'] - user = slave_sync_data[i]['user'] - - # print(port, password, host) - - mdb = mw.getMyORM() - mdb.setHost(host) - mdb.setPort(port) - mdb.setUser(user) - mdb.setPwd(password) - mdb.setSocket('') - - var_gtid = mdb.query('show VARIABLES like "%gtid_purged%"') - if len(var_gtid) > 0: - gtid_purged += var_gtid[0]['Value'] + ',' - - gtid_purged = gtid_purged.strip(',') - sql = "set @@global.gtid_purged='" + gtid_purged + "'" - - sdb.query('stop slave') - # print(sql) - sdb.query(sql) - sdb.query('start slave') - return mw.returnJson(True, '修复成功!') - -def getSlaveSyncCmd(version=''): - - root = mw.getPanelDir() - cmd = 'cd ' + root + ' && python3 ' + root + \ - '/plugins/mysql/index.py do_full_sync {"db":"all","sign":""}' - return mw.returnJson(True, 'ok', cmd) - - -def initSlaveStatus(version=''): - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - if mode == 'ssh': - return initSlaveStatusSSH(version) - if mode == 'sync-user': - return initSlaveStatusSyncUser(version) - - -def parseSlaveSyncCmd(cmd): - a = {} - if cmd.lower().find('for') > 0: - cmd_tmp = cmd.split('for') - cmd = cmd_tmp[0].strip() - - pattern_c = r"channel \'(.*)\';" - match_val = re.match(pattern_c, cmd_tmp[1].strip(), re.I) - if match_val: - m_groups = match_val.groups() - a['channel'] = m_groups[0] - vlist = cmd.split(',') - for i in vlist: - tmp = i.strip() - tmp_a = tmp.split(" ") - real_tmp = tmp_a[len(tmp_a) - 1] - kv = real_tmp.split("=") - a[kv[0]] = kv[1].replace("'", '').replace("'", '').replace(";", '') - return a - - -def initSlaveStatusSyncUser(version=''): - conn = pSqliteDb('slave_sync_user') - slave_data = conn.field('ip,port,user,pass,mode,cmd').select() - if len(slave_data) < 1: - return mw.returnJson(False, '需要先添加同步用户配置!') - - # print(data) - pdb = pMysqlDb() - if len(slave_data) == 1: - dlist = pdb.query('show slave status') - if len(dlist) > 0: - return mw.returnJson(False, '已经初始化好了zz...') - - msg = '' - local_mode = recognizeDbMode() - for x in range(len(slave_data)): - slave_t = slave_data[x] - mode_name = 'classic' - base_t = 'IP:' + slave_t['ip'] + ",PORT:" + \ - slave_t['port'] + ",USER:" + slave_t['user'] - - if slave_t['mode'] == '1': - mode_name = 'gtid' - - if local_mode != mode_name: - msg += base_t + '->同步模式不一致' - continue - - cmd_sql = slave_t['cmd'] - if cmd_sql == '': - msg += base_t + '->同步命令不能为空' - continue - - try: - pinfo = parseSlaveSyncCmd(cmd_sql) - except Exception as e: - return mw.returnJson(False, base_t + '->CMD同步命令不合规范!') - t = pdb.query(cmd_sql) - isError = isSqlError(t) - if isError: - return isError - - # pdb.query("start slave user='{}' password='{}';".format( - # u['user'], u['pass'])) - - pdb.query("start slave") - pdb.query("start all slaves") - - if msg == '': - msg = '初始化成功!' - return mw.returnJson(True, msg) - - -def initSlaveStatusSSH(version=''): - db = pMysqlDb() - dlist = db.query('show slave status') - - conn = pSqliteDb('slave_id_rsa') - ssh_list = conn.field('ip,port,id_rsa,db_user').select() - - if len(ssh_list) < 1: - return mw.returnJson(False, '需要先配置【[主]SSH配置】!') - - local_mode = recognizeDbMode() - - import paramiko - paramiko.util.log_to_file('paramiko.log') - ssh = paramiko.SSHClient() - - db.query('stop slave') - db.query('reset slave all') - for data in ssh_list: - ip = data['ip'] - SSH_PRIVATE_KEY = "/tmp/t_ssh_" + ip + ".txt" - master_port = data['port'] - mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n')) - mw.execShell("chmod 600 " + SSH_PRIVATE_KEY) - try: - key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - ssh.connect(hostname=ip, port=int(master_port), - username='root', pkey=key) - - db_user = data['db_user'] - cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \ - getSPluginDir() + \ - '/index.py get_master_rep_slave_user_cmd {"username":"' + \ - db_user + '","db":""}' - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result = result.decode('utf-8') - if result.strip() == "": - return mw.returnJson(False, '[主][' + ip + ']:获取同步命令失败!') - - cmd_data = json.loads(result) - if not cmd_data['status']: - return mw.returnJson(False, '[主][' + ip + ']:' + cmd_data['msg']) - - if local_mode != cmd_data['data']['mode']: - return mw.returnJson(False, '[主][' + ip + ']:【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode)) - - u = cmd_data['data']['info'] - - ps = u['username'] + "|" + u['password'] - print(ps) - conn.where('ip=?', (ip,)).setField('ps', ps) - db.query('stop slave') - - # 保证同步IP一致 - cmd = cmd_data['data']['cmd'] - if cmd.find('SOURCE_HOST') > -1: - cmd = re.sub(r"SOURCE_HOST='(.*?)'", - "SOURCE_HOST='" + ip + "'", cmd, 1) - - if cmd.find('MASTER_HOST') > -1: - cmd = re.sub(r"MASTER_HOST='(.*?)'", - "MASTER_HOST='" + ip + "'", cmd, 1) - db.query(cmd) - ssh.close() - if os.path.exists(SSH_PRIVATE_KEY): - os.system("rm -rf " + SSH_PRIVATE_KEY) - except Exception as e: - return mw.returnJson(False, '[主][' + ip + ']:SSH认证配置连接失败!' + str(e)) - db.query('start slave') - return mw.returnJson(True, '初始化成功!') - - -def setSlaveStatus(version=''): - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - pdb = pMysqlDb() - dlist = pdb.query('show slave status') - if len(dlist) == 0: - return mw.returnJson(False, '需要手动添加同步账户或者执行初始化!') - - for v in dlist: - connection_name = '' - cmd = "slave" - if 'Channel_Name' in v: - ch_name = v['Channel_Name'] - cmd = "slave for channel '{}'".format(ch_name) - - if (v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes'): - pdb.query("stop {}".format(cmd)) - else: - pdb.query("start {}".format(cmd)) - - return mw.returnJson(True, '设置成功!') - - -def deleteSlave(version=''): - args = getArgs() - db = pMysqlDb() - if 'sign' in args: - sign = args['sign'] - db.query("stop slave for channel '{}'".format(sign)) - db.query("reset slave all for channel '{}'".format(sign)) - else: - db.query('stop slave') - db.query('reset slave all') - - return mw.returnJson(True, '删除成功!') - - -def dumpMysqlData(version=''): - args = getArgs() - data = checkArgs(args, ['db']) - if not data[0]: - return data[1] - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - mysql_dir = getServerDir() - myconf = mysql_dir + "/etc/my.cnf" - - option = '' - mode = recognizeDbMode() - if mode == 'gtid': - option = ' --set-gtid-purged=off ' - - if args['db'].lower() == 'all': - dlist = findBinlogDoDb() - cmd = mysql_dir + "/bin/mysqldump --defaults-file=" + myconf + " " + option + " -uroot -p" + \ - pwd + " --databases " + \ - ' '.join(dlist) + " | gzip > /tmp/dump.sql.gz" - else: - cmd = mysql_dir + "/bin/mysqldump --defaults-file=" + myconf + " " + option + " -uroot -p" + \ - pwd + " --databases " + args['db'] + " | gzip > /tmp/dump.sql.gz" - - ret = mw.execShell(cmd) - if ret[0] == '': - return 'ok' - return 'fail' - -############### --- 重要 数据补足同步 ---- ########### - -def getSyncMysqlDB(dbname,sign = ''): - conn = pSqliteDb('slave_sync_user') - if sign != '': - data = conn.field('ip,port,user,pass,mode,cmd').where('ip=?', (sign,)).find() - else: - data = conn.field('ip,port,user,pass,mode,cmd').find() - user = data['user'] - apass = data['pass'] - port = data['port'] - ip = data['ip'] - # 远程数据 - sync_db = mw.getMyORM() - # MySQLdb | - sync_db.setPort(port) - sync_db.setHost(ip) - sync_db.setUser(user) - sync_db.setPwd(apass) - sync_db.setDbName(dbname) - sync_db.setTimeout(60) - return sync_db - -def syncDatabaseRepairTempFile(): - tmp_log = mw.getMWLogs()+ '/mysql-check.log' - return tmp_log - -def syncDatabaseRepairLog(version=''): - import subprocess - args = getArgs() - data = checkArgs(args, ['db','sign','op']) - if not data[0]: - return data[1] - - sync_args_db = args['db'] - sync_args_sign = args['sign'] - op = args['op'] - tmp_log = syncDatabaseRepairTempFile() - cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && python3 plugins/mysql-apt/index.py sync_database_repair {"db":"'+sync_args_db+'","sign":"'+sync_args_sign+'"}' - # print(cmd) - - if op == 'get': - log = mw.getLastLine(tmp_log, 15) - return mw.returnJson(True, log) - - if op == 'cmd': - return mw.returnJson(True, 'ok', cmd) - - if op == 'do': - os.system(' echo "开始执行" > '+ tmp_log) - os.system(cmd +' >> '+ tmp_log +' &') - return mw.returnJson(True, 'ok') - - return mw.returnJson(False, '无效请求!') - - -def syncDatabaseRepair(version=''): - time_stats_s = time.time() - tmp_log = syncDatabaseRepairTempFile() - - from pymysql.converters import escape_string - args = getArgs() - data = checkArgs(args, ['db','sign']) - if not data[0]: - return data[1] - - sync_args_db = args['db'] - sync_args_sign = args['sign'] - - # 本地数据 - local_db = pMysqlDb() - # 远程数据 - sync_db = getSyncMysqlDB(sync_args_db,sync_args_sign) - - tables = local_db.query('show tables from `%s`' % sync_args_db) - table_key = "Tables_in_" + sync_args_db - inconsistent_table = [] - - tmp_dir = '/tmp/sync_db_repair' - mw.execShell('mkdir -p '+tmp_dir) - - for tb in tables: - - table_name = sync_args_db+'.'+tb[table_key] - table_check_file = tmp_dir+'/'+table_name+'.txt' - - if os.path.exists(table_check_file): - # print(table_name+', 已检查OK') - continue - - primary_key_sql = "SHOW INDEX FROM "+table_name+" WHERE Key_name = 'PRIMARY';"; - primary_key_data = local_db.query(primary_key_sql) - # print(primary_key_sql,primary_key_data) - pkey_name = '*' - if len(primary_key_data) == 1: - pkey_name = primary_key_data[0]['Column_name'] - # print(pkey_name) - if pkey_name != '*' : - # 智能校验(由于服务器同步可能会慢,比较总数总是对不上) - cmd_local_newpk_sql = 'select ' + pkey_name + ' from ' + table_name + " order by " + pkey_name + " desc limit 1" - cmd_local_newpk_data = local_db.query(cmd_local_newpk_sql) - # print(cmd_local_newpk_data) - if len(cmd_local_newpk_data) == 1: - # 比较总数 - cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name + ' where '+pkey_name + ' <= '+ str(cmd_local_newpk_data[0][pkey_name]) - local_count_data = local_db.query(cmd_count_sql) - sync_count_data = sync_db.query(cmd_count_sql) - - if local_count_data != sync_count_data: - print(cmd_count_sql) - print("all data compare: ",local_count_data, sync_count_data) - else: - print(table_name+' smart compare check ok.') - mw.writeFile(tmp_log, table_name+' smart compare check ok.\n','a+') - mw.execShell("echo 'ok' > "+table_check_file) - continue - - - - # 比较总数 - cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name - local_count_data = local_db.query(cmd_count_sql) - sync_count_data = sync_db.query(cmd_count_sql) - - if local_count_data != sync_count_data: - print("all data compare: ",local_count_data, sync_count_data) - inconsistent_table.append(table_name) - diff = sync_count_data[0]['num'] - local_count_data[0]['num'] - print(table_name+', need sync. diff,'+str(diff)) - mw.writeFile(tmp_log, table_name+', need sync. diff,'+str(diff)+'\n','a+') - else: - print(table_name+' check ok.') - mw.writeFile(tmp_log, table_name+' check ok.\n','a+') - mw.execShell("echo 'ok' > "+table_check_file) - - - # inconsistent_table = ['xx.xx'] - # 数据对齐 - for table_name in inconsistent_table: - is_break = False - while not is_break: - local_db.ping() - # 远程数据 - sync_db.ping() - - print("check table:"+table_name) - mw.writeFile(tmp_log, "check table:"+table_name+'\n','a+') - table_name_pos = 0 - table_name_pos_file = tmp_dir+'/'+table_name+'.pos.txt' - primary_key_sql = "SHOW INDEX FROM "+table_name+" WHERE Key_name = 'PRIMARY';"; - primary_key_data = local_db.query(primary_key_sql) - pkey_name = primary_key_data[0]['Column_name'] - - if os.path.exists(table_name_pos_file): - table_name_pos = mw.readFile(table_name_pos_file) - - - data_select_sql = 'select * from '+table_name + ' where '+pkey_name+' > '+str(table_name_pos)+' limit 10000' - print(data_select_sql) - local_select_data = local_db.query(data_select_sql) - - time_s = time.time() - sync_select_data = sync_db.query(data_select_sql) - print(f'sync query cos:{time.time() - time_s:.4f}s') - mw.writeFile(tmp_log, f'sync query cos:{time.time() - time_s:.4f}s\n','a+') - - # print(local_select_data) - # print(sync_select_data) - - # print(len(local_select_data)) - # print(len(sync_select_data)) - print('pos:',str(table_name_pos),'local compare sync,',local_select_data == sync_select_data) - - - cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name - local_count_data = local_db.query(cmd_count_sql) - time_s = time.time() - sync_count_data = sync_db.query(cmd_count_sql) - print(f'sync count data cos:{time.time() - time_s:.4f}s') - print(local_count_data,sync_count_data) - # 数据同步有延迟,相等即任务数据补足完成 - if local_count_data[0]['num'] == sync_count_data[0]['num']: - is_break = True - break - - diff = sync_count_data[0]['num'] - local_count_data[0]['num'] - print("diff," + str(diff)+' line data!') - - if local_select_data == sync_select_data: - data_count = len(local_select_data) - if data_count == 0: - # mw.writeFile(table_name_pos_file, '0') - print(table_name+",data is equal ok..") - is_break = True - break - - # print(table_name,data_count) - pos = local_select_data[data_count-1][pkey_name] - print('pos',pos) - progress = pos/sync_count_data[0]['num'] - print('progress,%.2f' % progress+'%') - mw.writeFile(table_name_pos_file, str(pos)) - else: - sync_select_data_len = len(sync_select_data) - skip_idx = 0 - # 主库PK -> 查询本地 | 保证一致 - if sync_select_data_len > 0: - for idx in range(sync_select_data_len): - sync_idx_data = sync_select_data[idx] - local_idx_data = None - if idx in local_select_data: - local_idx_data = local_select_data[idx] - if sync_select_data[idx] == local_idx_data: - skip_idx = idx - pos = local_select_data[idx][pkey_name] - mw.writeFile(table_name_pos_file, str(pos)) - - # print(insert_data) - local_inquery_sql = 'select * from ' + table_name+ ' where ' +pkey_name+' = '+ str(sync_idx_data[pkey_name]) - # print(local_inquery_sql) - ldata = local_db.query(local_inquery_sql) - # print('ldata:',ldata) - if len(ldata) == 0: - print("id:"+ str(sync_idx_data[pkey_name])+ " no exists, insert") - insert_sql = 'insert into ' + table_name - field_str = '' - value_str = '' - for field in sync_idx_data: - field_str += '`'+field+'`,' - value_str += '\''+escape_string(str(sync_idx_data[field]))+'\',' - field_str = '(' +field_str.strip(',')+')' - value_str = '(' +value_str.strip(',')+')' - insert_sql = insert_sql+' '+field_str+' values'+value_str+';' - print(insert_sql) - r = local_db.execute(insert_sql) - print(r) - else: - # print('compare sync->local:',sync_idx_data == ldata[0] ) - if ldata[0] == sync_idx_data: - continue - - print("id:"+ str(sync_idx_data[pkey_name])+ " data is not equal, update") - update_sql = 'update ' + table_name - field_str = '' - value_str = '' - for field in sync_idx_data: - if field == pkey_name: - continue - field_str += '`'+field+'`=\''+escape_string(str(sync_idx_data[field]))+'\',' - field_str = field_str.strip(',') - update_sql = update_sql+' set '+field_str+' where '+pkey_name+'=\''+str(sync_idx_data[pkey_name])+'\';' - print(update_sql) - r = local_db.execute(update_sql) - print(r) - - # 本地PK -> 查询主库 | 保证一致 - # local_select_data_len = len(local_select_data) - # if local_select_data_len > 0: - # for idx in range(local_select_data_len): - # if idx < skip_idx: - # continue - # local_idx_data = local_select_data[idx] - # print('local idx check', idx, skip_idx) - # local_inquery_sql = 'select * from ' + table_name+ ' where ' +pkey_name+' = '+ str(local_idx_data[pkey_name]) - # print(local_inquery_sql) - # sdata = sync_db.query(local_inquery_sql) - # sdata_len = len(sdata) - # print('sdata:',sdata,sdata_len) - # if sdata_len == 0: - # delete_sql = 'delete from ' + table_name + ' where ' +pkey_name+' = '+ str(local_idx_data[pkey_name]) - # print(delete_sql) - # r = local_db.execute(delete_sql) - # print(r) - # break - - - if is_break: - print("break all") - break - time.sleep(3) - print(f'data check cos:{time.time() - time_stats_s:.4f}s') - print("data supplementation completed") - mw.execShell('rm -rf '+tmp_dir) - return 'ok' - -############### --- 重要 同步---- ########### - -def asyncTmpfile(): - path = '/tmp/mysql_apt_async_status.txt' - return path - - -def writeDbSyncStatus(data): - path = asyncTmpfile() - mw.writeFile(path, json.dumps(data)) - -def fullSyncCmd(): - time_all_s = time.time() - args = getArgs() - data = checkArgs(args, ['db', 'sign']) - if not data[0]: - return data[1] - - db = args['db'] - sign = args['sign'] - - cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && python3 plugins/mysql-apt/index.py do_full_sync {"db":"'+db+'","sign":"'+sign+'"}' - return mw.returnJson(True,'ok',cmd) - -def doFullSync(version=''): - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - if mode == 'ssh': - return doFullSyncSSH(version) - if mode == 'sync-user': - return doFullSyncUser(version) - -def isSimpleSyncCmd(sql): - new_sql = sql.lower() - if new_sql.find('master_auto_position') > 0: - return False - return True - -def getChannelNameForCmd(cmd): - cmd = cmd.lower() - cmd_arr = cmd.split('channel') - if len(cmd_arr) == 2: - cmd_channel_info = cmd_arr[1] - channel_name = cmd_channel_info.strip() - channel_name = channel_name.strip(';') - channel_name = channel_name.strip("'") - return channel_name - return '' - -def doFullSyncUserImportContentForChannel(file, channel_name): - # print(file, channel_name) - content = mw.readFile(file) - - content = content.replace('STOP SLAVE;', "STOP SLAVE for channel '{}';".format(channel_name)) - content = content.replace('START SLAVE;', "START SLAVE for channel '{}';".format(channel_name)) - - find_head = "CHANGE MASTER TO " - find_re = find_head+"(.*?);" - find_r = re.search(find_re, content, re.I|re.M) - if find_r: - find_rg = find_r.groups() - if len(find_rg)>0: - find_str = find_head+find_rg[0] - if find_str.lower().find('channel')==-1: - content = content.replace(find_str+';', find_str+" for channel '{}';".format(channel_name)) - - mw.writeFile(file,content) - return True - -def doFullSyncUser(version=''): - which_pv = mw.execShell('which pv') - is_exist_pv = False - if os.path.exists(which_pv[0]): - is_exist_pv = True - - time_all_s = time.time() - - args = getArgs() - data = checkArgs(args, ['db', 'sign']) - if not data[0]: - return data[1] - - sync_db = args['db'] - sync_db_import = args['db'] - - if sync_db.lower() == 'all': - sync_db_import = '' - dbs = findBinlogSlaveDoDb() - dbs_str = '' - for x in dbs: - dbs_str += ' ' + x - sync_db = "--databases " + dbs_str.strip() - - sync_sign = args['sign'] - - db = pMysqlDb() - - conn = pSqliteDb('slave_sync_user') - if sync_sign != '': - data = conn.field('ip,port,user,pass,mode,cmd').where( - 'ip=?', (sync_sign,)).find() - else: - data = conn.field('ip,port,user,pass,mode,cmd').find() - - user = data['user'] - apass = data['pass'] - port = data['port'] - ip = data['ip'] - cmd = data['cmd'] - - channel_name = getChannelNameForCmd(cmd) - sync_mdb = getSyncMysqlDB(sync_db,sync_sign) - - bak_file = '/tmp/tmp.sql' - if os.path.exists(bak_file): - os.system("rm -rf " + bak_file) - - writeDbSyncStatus({'code': 0, 'msg': '开始同步...', 'progress': 0}) - dmp_option = '' - mode = recognizeDbMode() - if mode == 'gtid': - dmp_option = ' --set-gtid-purged=off ' - - time.sleep(1) - writeDbSyncStatus({'code': 1, 'msg': '正在停止从库...', 'progress': 15}) - - mdb8 = getMdb8Ver() - if mw.inArray(mdb8,version): - db.query("stop slave user='{}' password='{}';".format(user, apass)) - else: - db.query("stop slave") - - time.sleep(1) - writeDbSyncStatus({'code': 2, 'msg': '远程导出数据...', 'progress': 20}) - - find_run_dump = mw.execShell('ps -ef | grep mysqldump | grep -v grep') - if find_run_dump[0] != "": - print("正在远程导出数据中,别着急...") - writeDbSyncStatus({'code': 3.1, 'msg': '正在远程导出数据中,别着急...', 'progress': 19}) - return False - - time_s = time.time() - if not os.path.exists(bak_file): - dmp_option += ' ' - if isSimpleSyncCmd(cmd): - if mw.inArray(mdb8,version): - # --compression-algorithms - dmp_option += " --source-data=1 --apply-replica-statements --include-source-host-port " - else: - dmp_option += " --master-data=1 --apply-slave-statements --include-master-host-port --compress " - - - dump_sql_data = getServerDir() + "/bin/mysqldump --single-transaction --default-character-set=utf8mb4 -q " + dmp_option + " -h" + \ - ip + " -P" + port + " -u" + user + ' -p"' + apass + '" --ssl-mode=DISABLED ' + sync_db + " > " + bak_file - print(dump_sql_data) - time_s = time.time() - r = mw.execShell(dump_sql_data) - print(r) - time_e = time.time() - export_cos = time_e - time_s - print("export cos:", export_cos) - - writeDbSyncStatus({'code': 3, 'msg': '导出耗时:'+str(int(export_cos))+'秒,正在到本地导入数据中...', 'progress': 40}) - - find_run_import = mw.execShell('ps -ef | grep mysql| grep '+ bak_file +' | grep -v grep') - if find_run_import[0] != "": - print("正在导入数据中,别着急...") - writeDbSyncStatus({'code': 4.1, 'msg': '正在导入数据中,别着急...', 'progress': 39}) - return False - - - time_s = time.time() - if os.path.exists(bak_file): - - # 重置 - db.execute('reset master') - if channel_name != '': - doFullSyncUserImportContentForChannel(bak_file, channel_name) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - - if is_exist_pv: - my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import - my_import_cmd = "pv -t -p " + bak_file + '|' + my_import_cmd - print(my_import_cmd) - os.system(my_import_cmd) - else: - my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import + ' < ' + bak_file - print(my_import_cmd) - mw.execShell(my_import_cmd) - - my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ - ' ' + sync_db_import + ' < ' + bak_file - mw.execShell(my_import_cmd) - - if mw.inArray(mdb8, version): - db.query("start replica user='{}' password='{}';".format(user, apass)) - else: - db.query("start slave") - - db.query("start all slaves") - time_all_e = time.time() - cos = time_all_e - time_all_s - writeDbSyncStatus({'code': 6, 'msg': '总耗时:'+str(int(cos))+'秒,从库重启完成...', 'progress': 100}) - - if os.path.exists(bak_file): - os.system("rm -rf " + bak_file) - - return True - - -def doFullSyncSSH(version=''): - - args = getArgs() - data = checkArgs(args, ['db', 'sign']) - if not data[0]: - return data[1] - - sync_db = args['db'] - sync_sign = args['sign'] - - db = pMysqlDb() - - id_rsa_conn = pSqliteDb('slave_id_rsa') - if sync_sign != '': - data = id_rsa_conn.field('ip,port,db_user,id_rsa').where( - 'ip=?', (sync_sign,)).find() - else: - data = id_rsa_conn.field('ip,port,db_user,id_rsa').find() - - SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt" - id_rsa = data['id_rsa'].replace('\\n', '\n') - mw.writeFile(SSH_PRIVATE_KEY, id_rsa) - - ip = data["ip"] - master_port = data['port'] - db_user = data['db_user'] - print("master ip:", ip) - - writeDbSyncStatus({'code': 0, 'msg': '开始同步...', 'progress': 0}) - - import paramiko - paramiko.util.log_to_file('paramiko.log') - ssh = paramiko.SSHClient() - - print(SSH_PRIVATE_KEY) - if not os.path.exists(SSH_PRIVATE_KEY): - writeDbSyncStatus({'code': 0, 'msg': '需要配置SSH......', 'progress': 0}) - return 'fail' - - try: - # ssh.load_system_host_keys() - mw.execShell("chmod 600 " + SSH_PRIVATE_KEY) - key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - print(ip, master_port) - - # pkey=key - # key_filename=SSH_PRIVATE_KEY - ssh.connect(hostname=ip, port=int(master_port), - username='root', pkey=key) - except Exception as e: - print(str(e)) - writeDbSyncStatus( - {'code': 0, 'msg': 'SSH配置错误:' + str(e), 'progress': 0}) - return 'fail' - - writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5}) - - dbname = args['db'] - cmd = "cd /www/server/mdserver-web && source bin/activate && python3 " + \ - getSPluginDir() + "/index.py dump_mysql_data {\"db\":'" + dbname + "'}" - print(cmd) - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result = result.decode('utf-8') - if result.strip() == 'ok': - writeDbSyncStatus({'code': 1, 'msg': '主服务器备份完成...', 'progress': 30}) - else: - writeDbSyncStatus( - {'code': 1, 'msg': '主服务器备份失败...:' + str(result), 'progress': 100}) - return 'fail' - - print("同步文件", "start") - # cmd = 'scp -P' + str(master_port) + ' -i ' + SSH_PRIVATE_KEY + \ - # ' root@' + ip + ':/tmp/dump.sql.gz /tmp' - t = ssh.get_transport() - sftp = paramiko.SFTPClient.from_transport(t) - copy_status = sftp.get("/tmp/dump.sql.gz", "/tmp/dump.sql.gz") - print("同步信息:", copy_status) - print("同步文件", "end") - if copy_status == None: - writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40}) - - cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \ - getSPluginDir() + \ - '/index.py get_master_rep_slave_user_cmd {"username":"' + \ - db_user + '","db":""}' - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result = result.decode('utf-8') - cmd_data = json.loads(result) - - db.query('stop slave') - writeDbSyncStatus({'code': 3, 'msg': '停止从库完成...', 'progress': 45}) - - cmd = cmd_data['data']['cmd'] - # 保证同步IP一致 - if cmd.find('SOURCE_HOST') > -1: - cmd = re.sub(r"SOURCE_HOST='(.*?)'", - "SOURCE_HOST='" + ip + "'", cmd, 1) - - if cmd.find('MASTER_HOST') > -1: - cmd = re.sub(r"MASTER_HOST='(.*?)'", - "MASTER_HOST='" + ip + "'", cmd, 1) - - db.query(cmd) - uinfo = cmd_data['data']['info'] - ps = uinfo['username'] + "|" + uinfo['password'] - id_rsa_conn.where('ip=?', (ip,)).setField('ps', ps) - writeDbSyncStatus({'code': 4, 'msg': '刷新从库同步信息完成...', 'progress': 50}) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - root_dir = getServerDir() - msock = root_dir + "/mysql.sock" - mw.execShell("cd /tmp && gzip -d dump.sql.gz") - cmd = root_dir + "/bin/mysql -S " + msock + \ - " -uroot -p" + pwd + " < /tmp/dump.sql" - - print(cmd) - import_data = mw.execShell(cmd) - if import_data[0] == '': - print(import_data[1]) - writeDbSyncStatus({'code': 5, 'msg': '导入数据完成...', 'progress': 90}) - else: - print(import_data[0]) - writeDbSyncStatus({'code': 5, 'msg': '导入数据失败...', 'progress': 100}) - return 'fail' - - # "start slave user='{}' password='{}';".format(uinfo['username'], uinfo['password']) - - db.query("start slave") - writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100}) - - os.system("rm -rf " + SSH_PRIVATE_KEY) - os.system("rm -rf /tmp/dump.sql") - return True - - -def fullSync(version=''): - args = getArgs() - data = checkArgs(args, ['db', 'begin']) - if not data[0]: - return data[1] - - status_file = asyncTmpfile() - if args['begin'] == '1': - cmd = 'cd ' + mw.getPanelDir() + ' && python3 ' + getPluginDir() + \ - '/index.py do_full_sync {"db":"' + \ - args['db'] + '","sign":"' + sign + '"} &' - # print(cmd) - mw.execShell(cmd) - return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0}) - - if os.path.exists(status_file): - c = mw.readFile(status_file) - tmp = json.loads(c) - if tmp['code'] == 1: - sys_dump_sql = "/tmp/dump.sql" - if os.path.exists(sys_dump_sql): - dump_size = os.path.getsize(sys_dump_sql) - tmp['msg'] = tmp['msg'] + ":" + "同步文件:" + mw.toSize(dump_size) - c = json.dumps(tmp) - - # if tmp['code'] == 6: - # os.remove(status_file) - return c - - return json.dumps({'code': 0, 'msg': '点击开始,开始同步!', 'progress': 0}) - - -def installPreInspection(version): - arch_data = mw.execShell('arch') - if arch_data[0].strip().startswith('aarch'): - return '不支持aarch架构' - - cmd = "cat /etc/*-release | grep PRETTY_NAME |awk -F = '{print $2}' | awk -F '\"' '{print $2}'| awk '{print $1}'" - sys = mw.execShell(cmd) - - if sys[1] != '': - return '不支持改系统' - - cmd = "cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F '\"' '{print $2}'" - sys_id = mw.execShell(cmd) - - sysName = sys[0].strip().lower() - sysId = sys_id[0].strip() - mdb8 = getMdb8Ver() - - if not sysName in ('debian', 'ubuntu'): - return '仅支持debian,ubuntu' - - if (sysName == 'debian' and not sysId in('12', '11', '10')): - return 'debian支持10,11,12' - - if sysName == 'debian' and sysId == '12' and version == '8.0': - return 'debian12,暂时不支持8.0' - - if version == '9.0': - if sysName == 'debian' and sysId != '12': - return '9.0 仅支持debian12' - if sysName == 'ubuntu' and sysId != '24.04': - return '9.0 仅支持ubuntu24.04' - - if (sysName == 'ubuntu' and version == '5.7' and not sysId in ('18.04')): - return "Ubuntu Apt MySQL[" + version + "] 仅支持18.04" - - if (sysName == 'ubuntu' and version == '8.0' and not sysId in ('18.04', '20.04', '22.04','24.04')): - return 'Ubuntu Apt MySQL[' + version + '] 仅支持18.04,20.04,22.04,24.04' - return 'ok' - - -def uninstallPreInspection(version): - - data_dir = getDataDir() - if os.path.exists(data_dir): - stop(version) - - if mw.isDebugMode(): - return 'ok' - - from utils.plugin import plugin as MwPlugin - MwPlugin.instance().removeIndex(getPluginName(), version) - - return "请手动删除MySQL[{}]
    rm -rf {}".format(version, getServerDir()) - -if __name__ == "__main__": - func = sys.argv[1] - version = '5.6' - version_pl = getServerDir() + "/version.pl" - if os.path.exists(version_pl): - version = mw.readFile(version_pl).strip() - - if func == 'status': - print(status(version)) - elif func == 'start': - print(start(version)) - elif func == 'stop': - print(stop(version)) - elif func == 'restart': - print(restart(version)) - elif func == 'reload': - print(reload(version)) - elif func == 'initd_status': - print(initdStatus()) - elif func == 'initd_install': - print(initdInstall()) - elif func == 'initd_uninstall': - print(initdUinstall()) - elif func == 'install_pre_inspection': - print(installPreInspection(version)) - elif func == 'uninstall_pre_inspection': - print(uninstallPreInspection(version)) - elif func == 'run_info': - print(runInfo(version)) - elif func == 'db_status': - print(myDbStatus(version)) - elif func == 'set_db_status': - print(setDbStatus(version)) - elif func == 'conf': - print(getConf()) - elif func == 'bin_log': - print(binLog(version)) - elif func == 'binlog_list': - print(binLogList()) - elif func == 'clean_bin_log': - print(cleanBinLog()) - elif func == 'error_log': - print(getErrorLog()) - elif func == 'show_log': - print(getShowLogFile()) - elif func == 'my_db_pos': - print(getMyDbPos()) - elif func == 'set_db_pos': - print(setMyDbPos(version)) - elif func == 'my_port': - print(getMyPort()) - elif func == 'set_my_port': - print(setMyPort()) - elif func == 'init_pwd': - print(initMysqlPwd()) - elif func == 'root_pwd': - print(rootPwd()) - elif func == 'get_db_list': - print(getDbList()) - elif func == 'set_db_backup': - print(setDbBackup()) - elif func == 'import_db_backup': - print(importDbBackup()) - elif func == 'import_db_external': - print(importDbExternal()) - elif func == 'import_db_external_progress': - print(importDbExternalProgress()) - elif func == 'import_db_external_progress_bar': - print(importDbExternalProgressBar()) - elif func == 'delete_db_backup': - print(deleteDbBackup()) - elif func == 'get_db_backup_list': - print(getDbBackupList()) - elif func == 'get_db_backup_import_list': - print(getDbBackupImportList()) - elif func == 'add_db': - print(addDb()) - elif func == 'del_db': - print(delDb()) - elif func == 'sync_get_databases': - print(syncGetDatabases()) - elif func == 'sync_to_databases': - print(syncToDatabases()) - elif func == 'set_root_pwd': - print(setRootPwd(version)) - elif func == 'set_user_pwd': - print(setUserPwd(version)) - elif func == 'get_db_access': - print(getDbAccess()) - elif func == 'set_db_access': - print(setDbAccess()) - elif func == 'fix_db_access': - print(fixDbAccess(version)) - elif func == 'fix_db_access2': - print(fixDbAccess2(version)) - elif func == 'set_db_rw': - print(setDbRw(version)) - elif func == 'set_db_ps': - print(setDbPs()) - elif func == 'get_db_info': - print(getDbInfo()) - elif func == 'repair_table': - print(repairTable()) - elif func == 'opt_table': - print(optTable()) - elif func == 'alter_table': - print(alterTable()) - elif func == 'get_total_statistics': - print(getTotalStatistics()) - elif func == 'get_dbrun_mode': - print(getDbrunMode(version)) - elif func == 'set_dbrun_mode': - print(setDbrunMode(version)) - elif func == 'reset_master': - print(resetMaster(version)) - elif func == 'get_masterdb_list': - print(getMasterDbList(version)) - elif func == 'get_master_status': - print(getMasterStatus(version)) - elif func == 'set_master_status': - print(setMasterStatus(version)) - elif func == 'set_db_master': - print(setDbMaster(version)) - elif func == 'set_db_slave': - print(setDbSlave(version)) - elif func == 'set_dbmaster_access': - print(setDbMasterAccess()) - elif func == 'get_master_rep_slave_list': - print(getMasterRepSlaveList(version)) - elif func == 'add_master_rep_slave_user': - print(addMasterRepSlaveUser(version)) - elif func == 'del_master_rep_slave_user': - print(delMasterRepSlaveUser(version)) - elif func == 'update_master_rep_slave_user': - print(updateMasterRepSlaveUser(version)) - elif func == 'get_master_rep_slave_user_cmd': - print(getMasterRepSlaveUserCmd(version)) - elif func == 'get_slave_list': - print(getSlaveList(version)) - elif func == 'try_slave_sync_bugfix': - print(trySlaveSyncBugfix(version)) - elif func == 'get_slave_sync_cmd': - print(getSlaveSyncCmd(version)) - elif func == 'get_slave_ssh_list': - print(getSlaveSSHList(version)) - elif func == 'get_slave_ssh_by_ip': - print(getSlaveSSHByIp(version)) - elif func == 'add_slave_ssh': - print(addSlaveSSH(version)) - elif func == 'del_slave_ssh': - print(delSlaveSSH(version)) - elif func == 'update_slave_ssh': - print(updateSlaveSSH(version)) - elif func == 'get_slave_sync_user_list': - print(getSlaveSyncUserList(version)) - elif func == 'get_slave_sync_user_by_ip': - print(getSlaveSyncUserByIp(version)) - elif func == 'add_slave_sync_user': - print(addSlaveSyncUser(version)) - elif func == 'del_slave_sync_user': - print(delSlaveSyncUser(version)) - elif func == 'get_slave_sync_mode': - print(getSlaveSyncMode(version)) - elif func == 'set_slave_sync_mode': - print(setSlaveSyncMode(version)) - elif func == 'init_slave_status': - print(initSlaveStatus(version)) - elif func == 'set_slave_status': - print(setSlaveStatus(version)) - elif func == 'delete_slave': - print(deleteSlave(version)) - elif func == 'full_sync': - print(fullSync(version)) - elif func == 'do_full_sync': - print(doFullSync(version)) - elif func == 'full_sync_cmd': - print(fullSyncCmd()) - elif func == 'dump_mysql_data': - print(dumpMysqlData(version)) - elif func == 'sync_database_repair': - print(syncDatabaseRepair()) - elif func == 'sync_database_repair_log': - print(syncDatabaseRepairLog()) - else: - print('error') diff --git a/plugins/mysql-apt/index_mysql_apt.py b/plugins/mysql-apt/index_mysql_apt.py deleted file mode 100644 index 5292151111..0000000000 --- a/plugins/mysql-apt/index_mysql_apt.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding:utf-8 - -import sys -import io -import os -import time -import subprocess -import re -import json - -web_dir = os.getcwd() + "/web" -if os.path.exists(web_dir): - sys.path.append(web_dir) - os.chdir(web_dir) - -import core.mw as mw - -# if mw.isAppleSystem(): -# cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\'' -# info = mw.execShell(cmd) -# p = "/usr/local/lib/" + info[0].strip() + "/site-packages" -# sys.path.append(p) - - -app_debug = False -if mw.isAppleSystem(): - app_debug = True - - -def getPluginName(): - return 'mysql-apt' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - - -def getSPluginDir(): - return '/www/server/mdserver-web/plugins/' + getPluginName() - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def getConf(): - path = getServerDir() + '/etc/my.cnf' - return path - - -def getDataDir(): - file = getConf() - content = mw.readFile(file) - rep = r'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getRelayLogName(): - file = getConf() - content = mw.readFile(file) - rep = r'relay-log\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getLogBinName(): - file = getConf() - content = mw.readFile(file) - rep = r'log-bin\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def binLogListLook(args): - - file = args['file'] - line = args['line'] - - data_dir = getDataDir() - my_bin = getServerDir() + '/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata = {} - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata - - -def binLogListLookDecode(args): - - file = args['file'] - line = args['line'] - - data_dir = getDataDir() - my_bin = getServerDir() + '/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata = {} - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata - - -def binLogListTraceRelay(args): - rdata = {} - file = args['file'] - line = args['line'] - - relay_name = getRelayLogName() - data_dir = getDataDir() - alist = os.listdir(data_dir) - relay_list = [] - for x in range(len(alist)): - f = alist[x] - t = {} - if f.startswith(relay_name) and not f.endswith('.index'): - relay_list.append(f) - - relay_list = sorted(relay_list, reverse=True) - if len(relay_list) == 0: - rdata['cmd'] = '' - rdata['data'] = '无Relay日志' - return rdata - - file = relay_list[0] - - my_bin = getServerDir() + '/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata - - -def binLogListTraceBinLog(args): - rdata = {} - file = args['file'] - line = args['line'] - - data_dir = getDataDir() - log_bin_name = getLogBinName() - - alist = os.listdir(data_dir) - log_bin_l = [] - for x in range(len(alist)): - f = alist[x] - t = {} - if f.startswith(log_bin_name) and not f.endswith('.index'): - log_bin_l.append(f) - - if len(log_bin_l) == 0: - rdata['cmd'] = '' - rdata['data'] = '无BINLOG' - return rdata - - log_bin_l = sorted(log_bin_l, reverse=True) - file = log_bin_l[0] - - my_bin = getServerDir() + '/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata diff --git a/plugins/mysql-apt/info.json b/plugins/mysql-apt/info.json deleted file mode 100755 index ea19db4d49..0000000000 --- a/plugins/mysql-apt/info.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "hook":["database"], - "title":"MySQL[APT]", - "tip":"soft", - "name":"mysql-apt", - "type":"运行环境", - "ps":"一种关系数据库管理系统[debian,ubuntu](极速安装)", - "todo_versions":["5.7","8.0"], - "versions":["5.7","8.0","8.2","8.3","8.4","9.0","9.1"], - "shell":"install.sh", - "install_pre_inspection":true, - "uninstall_pre_inspection":true, - "checks":"server/mysql-apt", - "path":"server/mysql-apt", - "author":"mysql", - "home":"https://dev.mysql.com/downloads/mysql", - "date":"2022-06-29", - "pid": "6" -} \ No newline at end of file diff --git a/plugins/mysql-apt/init.d/mysql5.7.service.tpl b/plugins/mysql-apt/init.d/mysql5.7.service.tpl deleted file mode 100644 index bd43bd9d51..0000000000 --- a/plugins/mysql-apt/init.d/mysql5.7.service.tpl +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -After=network.target - -[Service] -User=mysql -Group=mysql -Type=simple -PermissionsStartOnly=true -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 5000 -Restart=on-failure -RestartPreventExitStatus=1 -RuntimeDirectory=mysqld -RuntimeDirectoryMode=755 - -[Install] -WantedBy=multi-user.target diff --git a/plugins/mysql-apt/init.d/mysql8.0.service.tpl b/plugins/mysql-apt/init.d/mysql8.0.service.tpl deleted file mode 100644 index e9eb04dbe2..0000000000 --- a/plugins/mysql-apt/init.d/mysql8.0.service.tpl +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -Documentation=man:mysqld(8) -Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html -After=network.target - -[Install] -WantedBy=multi-user.target - -[Service] -User=mysql -Group=mysql -Type=notify -#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 10000 -Restart=on-failure -RestartPreventExitStatus=1 - -# Always restart when mysqld exits with exit code of 16. This special exit code -# is used by mysqld for RESTART SQL. -RestartForceExitStatus=16 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. -Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-apt/init.d/mysql8.1.service.tpl b/plugins/mysql-apt/init.d/mysql8.1.service.tpl deleted file mode 100644 index e9eb04dbe2..0000000000 --- a/plugins/mysql-apt/init.d/mysql8.1.service.tpl +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -Documentation=man:mysqld(8) -Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html -After=network.target - -[Install] -WantedBy=multi-user.target - -[Service] -User=mysql -Group=mysql -Type=notify -#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 10000 -Restart=on-failure -RestartPreventExitStatus=1 - -# Always restart when mysqld exits with exit code of 16. This special exit code -# is used by mysqld for RESTART SQL. -RestartForceExitStatus=16 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. -Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-apt/init.d/mysql8.2.service.tpl b/plugins/mysql-apt/init.d/mysql8.2.service.tpl deleted file mode 100644 index e9eb04dbe2..0000000000 --- a/plugins/mysql-apt/init.d/mysql8.2.service.tpl +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -Documentation=man:mysqld(8) -Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html -After=network.target - -[Install] -WantedBy=multi-user.target - -[Service] -User=mysql -Group=mysql -Type=notify -#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 10000 -Restart=on-failure -RestartPreventExitStatus=1 - -# Always restart when mysqld exits with exit code of 16. This special exit code -# is used by mysqld for RESTART SQL. -RestartForceExitStatus=16 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. -Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-apt/init.d/mysql8.3.service.tpl b/plugins/mysql-apt/init.d/mysql8.3.service.tpl deleted file mode 100644 index e9eb04dbe2..0000000000 --- a/plugins/mysql-apt/init.d/mysql8.3.service.tpl +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -Documentation=man:mysqld(8) -Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html -After=network.target - -[Install] -WantedBy=multi-user.target - -[Service] -User=mysql -Group=mysql -Type=notify -#ExecStartPre=+/usr/share/mysql-8.0/mysql-systemd-start pre -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 10000 -Restart=on-failure -RestartPreventExitStatus=1 - -# Always restart when mysqld exits with exit code of 16. This special exit code -# is used by mysqld for RESTART SQL. -RestartForceExitStatus=16 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. -Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-apt/init.d/mysql8.4.service.tpl b/plugins/mysql-apt/init.d/mysql8.4.service.tpl deleted file mode 100644 index 8c4e39fdc2..0000000000 --- a/plugins/mysql-apt/init.d/mysql8.4.service.tpl +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -Documentation=man:mysqld(8) -Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html -After=network.target - -[Install] -WantedBy=multi-user.target - -[Service] -User=mysql -Group=mysql -Type=notify -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 10000 -Restart=on-failure -RestartPreventExitStatus=1 - -# Always restart when mysqld exits with exit code of 16. This special exit code -# is used by mysqld for RESTART SQL. -RestartForceExitStatus=16 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. -Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-apt/init.d/mysql9.0.service.tpl b/plugins/mysql-apt/init.d/mysql9.0.service.tpl deleted file mode 100644 index 8c4e39fdc2..0000000000 --- a/plugins/mysql-apt/init.d/mysql9.0.service.tpl +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -Documentation=man:mysqld(8) -Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html -After=network.target - -[Install] -WantedBy=multi-user.target - -[Service] -User=mysql -Group=mysql -Type=notify -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 10000 -Restart=on-failure -RestartPreventExitStatus=1 - -# Always restart when mysqld exits with exit code of 16. This special exit code -# is used by mysqld for RESTART SQL. -RestartForceExitStatus=16 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. -Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-apt/init.d/mysql9.1.service.tpl b/plugins/mysql-apt/init.d/mysql9.1.service.tpl deleted file mode 100644 index 8c4e39fdc2..0000000000 --- a/plugins/mysql-apt/init.d/mysql9.1.service.tpl +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) 2015, 2022, Oracle and/or its affiliates. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License, version 2.0, -# as published by the Free Software Foundation. -# -# This program is also distributed with certain software (including -# but not limited to OpenSSL) that is licensed under separate terms, -# as designated in a particular file or component or in included license -# documentation. The authors of MySQL hereby grant you an additional -# permission to link the program and your derivative works with the -# separately licensed software that they have included with MySQL. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License, version 2.0, for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# MySQL systemd service file - -[Unit] -Description=MySQL Community Server -Documentation=man:mysqld(8) -Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html -After=network.target - -[Install] -WantedBy=multi-user.target - -[Service] -User=mysql -Group=mysql -Type=notify -ExecStart={$SERVER_PATH}/mysql-apt/bin/mysqld --defaults-file={$SERVER_PATH}/mysql-apt/etc/my.cnf -TimeoutSec=600 -LimitNOFILE = 10000 -Restart=on-failure -RestartPreventExitStatus=1 - -# Always restart when mysqld exits with exit code of 16. This special exit code -# is used by mysqld for RESTART SQL. -RestartForceExitStatus=16 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for restart. -Environment=MYSQLD_PARENT_PID=1 diff --git a/plugins/mysql-apt/install.sh b/plugins/mysql-apt/install.sh deleted file mode 100755 index f1c494d019..0000000000 --- a/plugins/mysql-apt/install.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/bin/bash -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") - -# https://dev.mysql.com/downloads/mysql/ -# https://downloads.mysql.com/archives/community/ - - -# /www/server/mysql-apt/bin/mysqld --basedir=/www/server/mysql-apt --datadir=/www/server/mysql-apt/data --initialize-insecure --explicit_defaults_for_timestamp - - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh uninstall 8.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py fix_db_access -# cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql/index.py do_full_sync {"db":"xxx","sign":"","begin":1} - -action=$1 -type=$2 - -if id mysql &> /dev/null ;then - echo "mysql UID is `id -u mysql`" - echo "mysql Shell is `grep "^mysql:" /etc/passwd |cut -d':' -f7 `" -else - groupadd mysql - useradd -g mysql -s /usr/sbin/nologin mysql -fi - - -if [ "${2}" == "" ];then - echo '缺少安装脚本...' - exit 0 -fi - -if [ ! -d $curPath/versions/$2 ];then - echo '缺少安装脚本2...' - exit 0 -fi - -if [ "${action}" == "uninstall" ];then - - cd ${rootPath} && python3 ${rootPath}/plugins/mysql-apt/index.py stop ${type} - cd ${rootPath} && python3 ${rootPath}/plugins/mysql-apt/index.py initd_uninstall ${type} - cd $curPath - - if [ -f /usr/lib/systemd/system/mysql-apt.service ] || [ -f /lib/systemd/system/mysql-apt.service ];then - systemctl stop mysql-apt - systemctl disable mysql-apt - rm -rf /usr/lib/systemd/system/mysql-apt.service - rm -rf /lib/systemd/system/mysql-apt.service - systemctl daemon-reload - fi -fi - - -sh -x $curPath/versions/$2/install_generic.sh $1 - -if [ "${action}" == "install" ];then - #初始化 - - if [ "$?" != "0" ];then - exit $? - fi - cd ${rootPath} && python3 ${rootPath}/plugins/mysql-apt/index.py start ${type} - cd ${rootPath} && python3 ${rootPath}/plugins/mysql-apt/index.py initd_install ${type} -fi diff --git a/plugins/mysql-apt/js/mysql-apt.js b/plugins/mysql-apt/js/mysql-apt.js deleted file mode 100755 index e583af795b..0000000000 --- a/plugins/mysql-apt/js/mysql-apt.js +++ /dev/null @@ -1,2968 +0,0 @@ - -function myPost(method,args,callback, title){ - - var _args = null; - if (typeof(args) == 'string'){ - _args = JSON.stringify(toArrayObject(args)); - } else { - _args = JSON.stringify(args); - } - - var _title = '正在获取...'; - if (typeof(title) != 'undefined'){ - _title = title; - } - - var loadT = layer.msg(_title, { icon: 16, time: 0, shade: 0.3 }); - $.post('/plugins/run', {name:'mysql-apt', func:method, args:_args}, function(data) { - layer.close(loadT); - if (!data.status){ - layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function myPostN(method,args,callback, title){ - - var _args = null; - if (typeof(args) == 'string'){ - _args = JSON.stringify(toArrayObject(args)); - } else { - _args = JSON.stringify(args); - } - - var _title = '正在获取...'; - if (typeof(title) != 'undefined'){ - _title = title; - } - $.post('/plugins/run', {name:'mysql-apt', func:method, args:_args}, function(data) { - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function myAsyncPost(method,args){ - var _args = null; - if (typeof(args) == 'string'){ - _args = JSON.stringify(toArrayObject(args)); - } else { - _args = JSON.stringify(args); - } - - var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); - return syncPost('/plugins/run', {name:'mysql-apt', func:method, args:_args}); -} - - -function myPostCallbak(method, version, args,callback){ - var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); - - var req_data = {}; - req_data['name'] = 'mysql-apt'; - req_data['func'] = method; - req_data['script']='index_mysql_apt'; - args['version'] = version; - - - if (typeof(args) == 'string' && args == ''){ - req_data['args'] = JSON.stringify(toArrayObject(args)); - } else { - req_data['args'] = JSON.stringify(args); - } - - $.post('/plugins/callback', req_data, function(data) { - layer.close(loadT); - if (!data.status){ - layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function myPostCallbakN(method, version, args,callback){ - - var req_data = {}; - req_data['name'] = 'mysql-apt'; - req_data['func'] = method; - req_data['script']='index_mysql_apt'; - args['version'] = version; - - - if (typeof(args) == 'string' && args == ''){ - req_data['args'] = JSON.stringify(toArrayObject(args)); - } else { - req_data['args'] = JSON.stringify(args); - } - - $.post('/plugins/callback', req_data, function(data) { - if (!data.status){ - layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function vaildPhpmyadmin(url,username,password){ - // console.log("Authorization: Basic " + btoa(username + ":" + password)); - $.ajax({ - type: "GET", - url: url, - dataType: 'json', - async: false, - username:username, - password:password, - headers: { - "Authorization": "Basic " + btoa(username + ":" + password) - }, - data: 'vaild', - success: function (){ - alert('Thanks for your comment!'); - } - }); -} - -function runInfo(){ - myPost('run_info','',function(data){ - - var rdata = $.parseJSON(data.data); - if (typeof(rdata['status']) != 'undefined'){ - layer.msg(rdata['msg'],{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - // Com_select , Qcache_inserts - var cache_size = ((parseInt(rdata.Qcache_hits) / (parseInt(rdata.Qcache_hits) + parseInt(rdata.Qcache_inserts))) * 100).toFixed(2) + '%'; - if (cache_size == 'NaN%') cache_size = 'OFF'; - var Con = '
    \ - \ - \ - \ - \ - \ - \ -
    启动时间' + getLocalTime(rdata.Run) + '每秒查询' + parseInt(rdata.Questions / rdata.Uptime) + '
    总连接次数' + rdata.Connections + '每秒事务' + parseInt((parseInt(rdata.Com_commit) + parseInt(rdata.Com_rollback)) / rdata.Uptime) + '
    发送' + toSize(rdata.Bytes_sent) + 'File' + rdata.File + '
    接收' + toSize(rdata.Bytes_received) + 'Position' + rdata.Position + '
    \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
    活动/峰值连接数' + rdata.Threads_running + '/' + rdata.Max_used_connections + '若值过大,增加max_connections
    线程缓存命中率' + ((1 - rdata.Threads_created / rdata.Connections) * 100).toFixed(2) + '%若过低,增加thread_cache_size
    索引命中率' + ((1 - rdata.Key_reads / rdata.Key_read_requests) * 100).toFixed(2) + '%若过低,增加key_buffer_size
    Innodb索引命中率' + (rdata.Innodb_buffer_pool_read_requests / (rdata.Innodb_buffer_pool_read_requests+rdata.Innodb_buffer_pool_reads)).toFixed(2) + '%若过低,增加innodb_buffer_pool_size
    查询缓存命中率' + cache_size + '' + lan.soft.mysql_status_ps5 + '
    创建临时表到磁盘' + ((rdata.Created_tmp_disk_tables / rdata.Created_tmp_tables) * 100).toFixed(2) + '%若过大,尝试增加tmp_table_size
    已打开的表' + rdata.Open_tables + '若过大,增加table_cache_size
    没有使用索引的量' + rdata.Select_full_join + '若不为0,请检查数据表的索引是否合理
    没有索引的JOIN量' + rdata.Select_range_check + '若不为0,请检查数据表的索引是否合理
    排序后的合并次数' + rdata.Sort_merge_passes + '若值过大,增加sort_buffer_size
    锁表次数' + rdata.Table_locks_waited + '若值过大,请考虑增加您的数据库性能
    '; - $(".soft-man-con").html(Con); - }); -} - - -function myDbPos(){ - myPost('my_db_pos','',function(data){ - var con = '
    \ -
    \ - \ - \ - \ -
    '; - $(".soft-man-con").html(con); - - $('#btn_change_path').click(function(){ - var datadir = $("input[name='datadir']").val(); - myPost('set_db_pos','datadir='+datadir,function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,time:2000,shade: [0.3, '#000']}); - }); - }); - }); -} - -function myPort(){ - myPost('my_port','',function(data){ - var con = '
    \ -
    \ - \ - \ -
    '; - $(".soft-man-con").html(con); - - $('#btn_change_port').click(function(){ - var port = $("input[name='port']").val(); - myPost('set_my_port','port='+port,function(data){ - var rdata = $.parseJSON(data.data); - if (rdata.status){ - layer.msg('修改成功!',{icon:1,time:2000,shade: [0.3, '#000']}); - } else { - layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']}); - } - }); - }); - }); -} - -//数据库配置状态 -function myPerfOpt() { - //获取MySQL配置 - myPost('db_status','',function(data){ - var rdata = $.parseJSON(data.data); - if ( typeof(rdata.status) != 'undefined' && !rdata.status){ - layer.msg(rdata.msg, {icon:2}); - return; - } - - - // console.log(rdata); - var key_buffer_size = toSizeM(rdata.mem.key_buffer_size); - var query_cache_size = toSizeM(rdata.mem.query_cache_size); - var tmp_table_size = toSizeM(rdata.mem.tmp_table_size); - var innodb_buffer_pool_size = toSizeM(rdata.mem.innodb_buffer_pool_size); - var innodb_additional_mem_pool_size = toSizeM(rdata.mem.innodb_additional_mem_pool_size); - var innodb_log_buffer_size = toSizeM(rdata.mem.innodb_log_buffer_size); - - var sort_buffer_size = toSizeM(rdata.mem.sort_buffer_size); - var read_buffer_size = toSizeM(rdata.mem.read_buffer_size); - var read_rnd_buffer_size = toSizeM(rdata.mem.read_rnd_buffer_size); - var join_buffer_size = toSizeM(rdata.mem.join_buffer_size); - var thread_stack = toSizeM(rdata.mem.thread_stack); - var binlog_cache_size = toSizeM(rdata.mem.binlog_cache_size); - - var a = key_buffer_size + query_cache_size + tmp_table_size + innodb_buffer_pool_size + innodb_additional_mem_pool_size + innodb_log_buffer_size; - var b = sort_buffer_size + read_buffer_size + read_rnd_buffer_size + join_buffer_size + thread_stack + binlog_cache_size; - var memSize = a + rdata.mem.max_connections * b; - - - var memCon = '
    \ -
    最大使用内存: \ - \ - ' + lan.soft.mysql_set_maxmem + ': MB\ -
    \ -

    key_buffer_sizeMB, ' + lan.soft.mysql_set_key_buffer_size + '

    \ -

    query_cache_sizeMB, ' + lan.soft.mysql_set_query_cache_size + '

    \ -

    tmp_table_sizeMB, ' + lan.soft.mysql_set_tmp_table_size + '

    \ -

    innodb_buffer_pool_sizeMB, ' + lan.soft.mysql_set_innodb_buffer_pool_size + '

    \ -

    innodb_log_buffer_sizeMB, ' + lan.soft.mysql_set_innodb_log_buffer_size + '

    \ -

    innodb_additional_mem_pool_sizeMB

    \ -

    sort_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_sort_buffer_size + '

    \ -

    read_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_read_buffer_size + '

    \ -

    read_rnd_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_read_rnd_buffer_size + '

    \ -

    join_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_join_buffer_size + '

    \ -

    thread_stackKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_thread_stack + '

    \ -

    binlog_cache_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_binlog_cache_size + '

    \ -

    thread_cache_size ' + lan.soft.mysql_set_thread_cache_size + '

    \ -

    table_open_cache ' + lan.soft.mysql_set_table_open_cache + '

    \ -

    max_connections ' + lan.soft.mysql_set_max_connections + '

    \ -
    \ -
    ' - - $(".soft-man-con").html(memCon); - - $(".conf_p input[name*='size'],.conf_p input[name='max_connections'],.conf_p input[name='thread_stack']").change(function() { - comMySqlMem(); - }); - - $(".conf_p select[name='mysql_set']").change(function() { - mySQLMemOpt($(this).val()); - comMySqlMem(); - }); - }); -} - -function reBootMySqld(){ - pluginOpService('mysql-apt','restart',''); -} - - -//设置MySQL配置参数 -function setMySQLConf() { - $.post('/system/system_total', '', function(memInfo) { - var memSize = memInfo['memTotal']; - var setSize = parseInt($("input[name='memSize']").val()); - - if(memSize < setSize){ - var errMsg = "错误,内存分配过高!

    物理内存: {1}MB
    最大使用内存: {2}MB
    可能造成的后果: 导致数据库不稳定,甚至无法启动MySQLd服务!"; - var msg = errMsg.replace('{1}',memSize).replace('{2}',setSize); - layer.msg(msg,{icon:2,time:5000}); - return; - } - - var query_cache_size = parseInt($("input[name='query_cache_size']").val()); - var query_cache_type = 0; - if (query_cache_size > 0) { - query_cache_type = 1; - } - var data = { - key_buffer_size: parseInt($("input[name='key_buffer_size']").val()), - query_cache_size: query_cache_size, - query_cache_type: query_cache_type, - tmp_table_size: parseInt($("input[name='tmp_table_size']").val()), - max_heap_table_size: parseInt($("input[name='tmp_table_size']").val()), - innodb_buffer_pool_size: parseInt($("input[name='innodb_buffer_pool_size']").val()), - innodb_log_buffer_size: parseInt($("input[name='innodb_log_buffer_size']").val()), - sort_buffer_size: parseInt($("input[name='sort_buffer_size']").val()), - read_buffer_size: parseInt($("input[name='read_buffer_size']").val()), - read_rnd_buffer_size: parseInt($("input[name='read_rnd_buffer_size']").val()), - join_buffer_size: parseInt($("input[name='join_buffer_size']").val()), - thread_stack: parseInt($("input[name='thread_stack']").val()), - binlog_cache_size: parseInt($("input[name='binlog_cache_size']").val()), - thread_cache_size: parseInt($("input[name='thread_cache_size']").val()), - table_open_cache: parseInt($("input[name='table_open_cache']").val()), - max_connections: parseInt($("input[name='max_connections']").val()) - }; - - myPost('set_db_status', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - reBootMySqld(); - },{ icon: rdata.status ? 1 : 2 }); - }); - },'json'); -} - - -//MySQL内存优化方案 -function mySQLMemOpt(opt) { - var query_size = parseInt($("input[name='query_cache_size']").val()); - switch (opt) { - case '0': - $("input[name='key_buffer_size']").val(8); - if (query_size) $("input[name='query_cache_size']").val(4); - $("input[name='tmp_table_size']").val(8); - $("input[name='innodb_buffer_pool_size']").val(16); - $("input[name='sort_buffer_size']").val(256); - $("input[name='read_buffer_size']").val(256); - $("input[name='read_rnd_buffer_size']").val(128); - $("input[name='join_buffer_size']").val(128); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(32); - $("input[name='thread_cache_size']").val(4); - $("input[name='table_open_cache']").val(32); - $("input[name='max_connections']").val(500); - break; - case '1': - $("input[name='key_buffer_size']").val(128); - if (query_size) $("input[name='query_cache_size']").val(64); - $("input[name='tmp_table_size']").val(64); - $("input[name='innodb_buffer_pool_size']").val(256); - $("input[name='sort_buffer_size']").val(768); - $("input[name='read_buffer_size']").val(768); - $("input[name='read_rnd_buffer_size']").val(512); - $("input[name='join_buffer_size']").val(1024); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(64); - $("input[name='thread_cache_size']").val(64); - $("input[name='table_open_cache']").val(128); - $("input[name='max_connections']").val(100); - break; - case '2': - $("input[name='key_buffer_size']").val(256); - if (query_size) $("input[name='query_cache_size']").val(128); - $("input[name='tmp_table_size']").val(384); - $("input[name='innodb_buffer_pool_size']").val(384); - $("input[name='sort_buffer_size']").val(768); - $("input[name='read_buffer_size']").val(768); - $("input[name='read_rnd_buffer_size']").val(512); - $("input[name='join_buffer_size']").val(2048); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(64); - $("input[name='thread_cache_size']").val(96); - $("input[name='table_open_cache']").val(192); - $("input[name='max_connections']").val(200); - break; - case '3': - $("input[name='key_buffer_size']").val(384); - if (query_size) $("input[name='query_cache_size']").val(192); - $("input[name='tmp_table_size']").val(512); - $("input[name='innodb_buffer_pool_size']").val(512); - $("input[name='sort_buffer_size']").val(1024); - $("input[name='read_buffer_size']").val(1024); - $("input[name='read_rnd_buffer_size']").val(768); - $("input[name='join_buffer_size']").val(2048); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(128); - $("input[name='thread_cache_size']").val(128); - $("input[name='table_open_cache']").val(384); - $("input[name='max_connections']").val(300); - break; - case '4': - $("input[name='key_buffer_size']").val(512); - if (query_size) $("input[name='query_cache_size']").val(256); - $("input[name='tmp_table_size']").val(1024); - $("input[name='innodb_buffer_pool_size']").val(1024); - $("input[name='sort_buffer_size']").val(2048); - $("input[name='read_buffer_size']").val(2048); - $("input[name='read_rnd_buffer_size']").val(1024); - $("input[name='join_buffer_size']").val(4096); - $("input[name='thread_stack']").val(384); - $("input[name='binlog_cache_size']").val(192); - $("input[name='thread_cache_size']").val(192); - $("input[name='table_open_cache']").val(1024); - $("input[name='max_connections']").val(400); - break; - case '5': - $("input[name='key_buffer_size']").val(1024); - if (query_size) $("input[name='query_cache_size']").val(384); - $("input[name='tmp_table_size']").val(2048); - $("input[name='innodb_buffer_pool_size']").val(4096); - $("input[name='sort_buffer_size']").val(4096); - $("input[name='read_buffer_size']").val(4096); - $("input[name='read_rnd_buffer_size']").val(2048); - $("input[name='join_buffer_size']").val(8192); - $("input[name='thread_stack']").val(512); - $("input[name='binlog_cache_size']").val(256); - $("input[name='thread_cache_size']").val(256); - $("input[name='table_open_cache']").val(2048); - $("input[name='max_connections']").val(500); - break; - } -} - -//计算MySQL内存开销 -function comMySqlMem() { - var key_buffer_size = parseInt($("input[name='key_buffer_size']").val()); - var query_cache_size = parseInt($("input[name='query_cache_size']").val()); - var tmp_table_size = parseInt($("input[name='tmp_table_size']").val()); - var innodb_buffer_pool_size = parseInt($("input[name='innodb_buffer_pool_size']").val()); - var innodb_additional_mem_pool_size = parseInt($("input[name='innodb_additional_mem_pool_size']").val()); - var innodb_log_buffer_size = parseInt($("input[name='innodb_log_buffer_size']").val()); - - var sort_buffer_size = $("input[name='sort_buffer_size']").val() / 1024; - var read_buffer_size = $("input[name='read_buffer_size']").val() / 1024; - var read_rnd_buffer_size = $("input[name='read_rnd_buffer_size']").val() / 1024; - var join_buffer_size = $("input[name='join_buffer_size']").val() / 1024; - var thread_stack = $("input[name='thread_stack']").val() / 1024; - var binlog_cache_size = $("input[name='binlog_cache_size']").val() / 1024; - var max_connections = $("input[name='max_connections']").val(); - - var a = key_buffer_size + query_cache_size + tmp_table_size + innodb_buffer_pool_size + innodb_additional_mem_pool_size + innodb_log_buffer_size - var b = sort_buffer_size + read_buffer_size + read_rnd_buffer_size + join_buffer_size + thread_stack + binlog_cache_size - var memSize = a + max_connections * b - $("input[name='memSize']").val(memSize.toFixed(2)); -} - -function syncGetDatabase(){ - myPost('sync_get_databases', null, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - dbList(); - },{ icon: rdata.status ? 1 : 2 }); - }); -} - -function syncToDatabase(type){ - var data = []; - $('input[type="checkbox"].check:checked').each(function () { - if (!isNaN($(this).val())) data.push($(this).val()); - }); - var postData = 'type='+type+'&ids='+JSON.stringify(data); - myPost('sync_to_databases', postData, function(data){ - var rdata = $.parseJSON(data.data); - // console.log(rdata); - showMsg(rdata.msg,function(){ - dbList(); - },{ icon: rdata.status ? 1 : 2 }); - }); -} - -function setRootPwd(type, pwd){ - if (type==1){ - var password = $("#MyPassword").val(); - myPost('set_root_pwd', {password:password}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - return; - } - - var index = layer.open({ - type: 1, - area: '500px', - title: '修改数据库密码', - closeBtn: 1, - shift: 5, - btn:["提交", "关闭", "复制ROOT密码", "强制修改"], - shadeClose: true, - content: "

    \ -
    \ - root密码\ -
    \ - \ -
    \ -
    \ -
    ", - yes:function(layerIndex){ - var password = $("#MyPassword").val(); - myPost('set_root_pwd', {password:password}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(layerIndex); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - }, - btn3:function(){ - var password = $("#MyPassword").val(); - copyText(password); - return false; - }, - btn4:function(layerIndex){ - layer.confirm('强制修改,是为了在重建时使用,确定强制?', { - btn: ['确定', '取消'] - }, function(index, layero){ - layer.close(index); - var password = $("#MyPassword").val(); - myPost('set_root_pwd', {password:password,force:'1'}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(layerIndex); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - }); - return false; - } - }); -} - -function showHidePass(obj){ - var a = "glyphicon-eye-open"; - var b = "glyphicon-eye-close"; - - if($(obj).hasClass(a)){ - $(obj).removeClass(a).addClass(b); - $(obj).prev().text($(obj).prev().attr('data-pw')) - } - else{ - $(obj).removeClass(b).addClass(a); - $(obj).prev().text('***'); - } -} - -function checkSelect(){ - setTimeout(function () { - var num = $('input[type="checkbox"].check:checked').length; - // console.log(num); - if (num == 1) { - $('button[batch="true"]').hide(); - $('button[batch="false"]').show(); - }else if (num>1){ - $('button[batch="true"]').show(); - $('button[batch="false"]').show(); - }else{ - $('button[batch="true"]').hide(); - $('button[batch="false"]').hide(); - } - },5) -} - -function setDbRw(id,username,val){ - myPost('set_db_rw',{id:id,username:username,rw:val}, function(data){ - var rdata = $.parseJSON(data.data); - // layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']}); - showMsg(rdata.msg, function(){ - dbList(); - },{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']}, 2000); - - }); -} - -function setDbAccess(username){ - myPost('get_db_access','username='+username, function(data){ - var rdata = $.parseJSON(data.data); - if (!rdata.status){ - layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); - return; - } - - var index = layer.open({ - type: 1, - area: '500px', - title: '设置数据库权限', - closeBtn: 1, - shift: 5, - btn:["提交","取消"], - shadeClose: true, - content: "
    \ -
    \ - 访问权限\ -
    \ - \ -
    \ -
    \ -
    ", - success:function(){ - if (rdata.msg == '127.0.0.1'){ - $('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true); - } else if (rdata.msg == '%'){ - $('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true); - } else if ( rdata.msg == 'ip' ){ - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } else { - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index){ - var data = $("#set_db_access").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['access']){ - dataObj['access'] = dataObj['dataAccess']; - if ( dataObj['dataAccess'] == 'ip'){ - if (dataObj['address']==''){ - layer.msg('IP地址不能空!',{icon:2,shade: [0.3, '#000']}); - return; - } - dataObj['access'] = dataObj['address']; - } - } - dataObj['username'] = username; - myPost('set_db_access', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - } - }); - - }); -} - -function fixDbAccess(username){ - myPost('fix_db_access', '', function(rdata){ - var rdata = $.parseJSON(rdata.data); - showMsg(rdata.msg,function(){ - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); -} - -function setDbPass(id, username, password){ - layer.open({ - type: 1, - area: '500px', - title: '修改数据库密码', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["提交","关闭"], - content: "
    \ -
    \ - 用户名\ -
    \ -
    \ -
    \ - 密码\ -
    \ - \ -
    \ -
    \ - \ -
    ", - yes:function(index){ - // var data = $("#mod_pwd").serialize(); - var data = {}; - data['name'] = $('input[name=name]').val(); - data['password'] = $('#MyPassword').val(); - data['id'] = $('input[name=id]').val(); - myPost('set_user_pwd', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - } - }); -} - -function addDatabase(type){ - layer.open({ - type: 1, - area: '500px', - title: '添加数据库', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["提交","关闭"], - content: "
    \ -
    \ - 数据库名\ -
    \ - \ -
    \ -
    \ -
    用户名
    \ -
    \ - 密码\ -
    \ -
    \ -
    \ - 访问权限\ -
    \ - \ -
    \ -
    \ - \ -
    ", - success:function(){ - $("input[name='name']").keyup(function(){ - var v = $(this).val(); - $("input[name='db_user']").val(v); - $("input[name='ps']").val(v); - }); - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index) { - var data = $("#add_db").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['address']){ - dataObj['address'] = dataObj['dataAccess']; - } - myPost('add_db', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - layer.close(index); - dbList(); - } - },{icon: rdata.status ? 1 : 2}, 2000); - }); - } - }); -} - -function delDb(id, name){ - safeMessage('删除['+name+']','您真的要删除['+name+']吗?',function(){ - var data='id='+id+'&name='+name; - myPost('del_db', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - dbList(); - },{icon: rdata.status ? 1 : 2}, 600); - }); - }); -} - -function delDbBatch(){ - var arr = []; - $('input[type="checkbox"].check:checked').each(function () { - var _val = $(this).val(); - var _name = $(this).parent().next().text(); - if (!isNaN(_val)) { - arr.push({'id':_val,'name':_name}); - } - }); - - safeMessage('批量删除数据库','您共选择了[2]个数据库,删除后将无法恢复,真的要删除吗?',function(){ - var i = 0; - $(arr).each(function(){ - var data = myAsyncPost('del_db', this); - var rdata = $.parseJSON(data.data); - if (!rdata.status){ - layer.msg(rdata.msg,{icon:2,time:2000,shade: [0.3, '#000']}); - } - i++; - }); - - var msg = '成功删除['+i+']个数据库!'; - showMsg(msg,function(){ - dbList(); - },{icon: 1}, 600); - }); -} - - -function setDbPs(id, name, obj) { - var _span = $(obj); - var _input = $(""); - _span.hide().after(_input); - _input.focus(); - _input.blur(function(){ - $(this).remove(); - var ps = _input.val(); - _span.text(ps).show(); - var data = {name:name,id:id,ps:ps}; - myPost('set_db_ps', data, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - }); - }); - _input.keyup(function(){ - if(event.keyCode == 13){ - _input.trigger('blur'); - } - }); -} - -function openPhpmyadmin(name,username,password){ - $.post('/plugins/run', {'name':'phpmyadmin','func':'plugins_db_support'}, function(data){ - var rdata = $.parseJSON(data.data); - - if (rdata.data['installed'] != 'ok'){ - layer.msg('phpMyAdmin未安装!',{icon:2,shade: [0.3, '#000']}); - return; - } - - if (rdata.data['status'] != 'start'){ - layer.msg('phpMyAdmin未启动',{icon:2,shade: [0.3, '#000']}); - return; - } - - if (rdata.data['cfg']['choose'] != 'mysql-apt'){ - layer.msg('当前为['+rdata.data['cfg']['choose'] + ']模式,若要使用请修改phpMyAdmin访问切换.',{icon:2,shade: [0.3, '#000']}); - return; - } - var home_page = rdata.data['home_page']; - $("#toPHPMyAdmin").attr('action',home_page); - if($("#toPHPMyAdmin").attr('action').indexOf('phpmyadmin') == -1){ - layer.msg('请先安装phpMyAdmin',{icon:2,shade: [0.3, '#000']}); - setTimeout(function(){ window.location.href = '/soft'; },3000); - return; - } - //检查版本 - bigVer = rdata.data['version']; - if (bigVer>=4.5){ - - setTimeout(function(){ - $("#toPHPMyAdmin").submit(); - },2000); - layer.msg('phpMyAdmin['+data.data+']需要手动登录😭',{icon:16,shade: [0.3, '#000'],time:4000}); - - } else{ - var murl = $("#toPHPMyAdmin").attr('action'); - $("#pma_username").val(username); - $("#pma_password").val(password); - $("#db").val(name); - - layer.msg('正在打开phpMyAdmin',{icon:16,shade: [0.3, '#000'],time:2000}); - - setTimeout(function(){ - $("#toPHPMyAdmin").submit(); - },2000); - } - - },'json'); -} - -function delBackup(filename, name, path){ - if(typeof(path) == "undefined"){ - path = ""; - } - myPost('delete_db_backup',{filename:filename,path:path},function(){ - layer.msg('执行成功!'); - setTimeout(function(){ - setBackupReq(name); - },2000); - }); -} - -function downloadBackup(file){ - window.open('/files/download?filename='+encodeURIComponent(file)); -} - -function importBackup(file,name){ - myPost('import_db_backup',{file:file,name:name}, function(data){ - // console.log(data); - layer.msg('执行成功!'); - }); -} - -function importBackupProgress(file,name){ - myPost('import_db_backup_progress',{file:file,name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.open({ - title: "手动导入命令CMD【显示进度】", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
    \ -
    \ -
    '+rdata.data+'
    \ -
    \ -
    ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); -} - - -function importDbExternal(file,name){ - myPost('import_db_external',{file:file,name:name}, function(data){ - layer.msg('执行成功!'); - }); -} - -function importDbExternalProgress(file,name){ - myPost('import_db_external_progress',{file:file,name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.open({ - title: "手动导入命令CMD【显示进度】", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
    \ -
    \ -
    '+rdata.data+'
    \ -
    \ -
    ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); -} - -function setLocalImport(db_name){ - - //上传文件 - function uploadDbFiles(upload_dir){ - var up_db = layer.open({ - type:1, - closeBtn: 1, - title:"上传导入文件["+upload_dir+']', - area: ['500px','300px'], - shadeClose:false, - content:'
    \ - \ - \ - \ - \ - \ - \ - 文件编码:\ - \ - \ - \ -
      \ -
      ', - success:function(){ - $('#filesClose').click(function(){ - layer.close(up_db); - }); - } - - }); - uploadStart(function(){ - getList(); - layer.close(up_db); - }); - } - - function getList(){ - myPost('get_db_backup_import_list',{}, function(data){ - var rdata = $.parseJSON(data.data); - - var file_list = rdata.data.list; - var upload_dir = rdata.data.upload_dir; - - var tbody = ''; - for (var i = 0; i < file_list.length; i++) { - tbody += '\ - ' + file_list[i]['name'] + '\ - ' + file_list[i]['size'] + '\ - ' + file_list[i]['time'] + '\ - \ - 导入 | \ - 导入进度 | \ - 删除\ - \ - '; - } - - $('#import_db_file_list').html(tbody); - $('input[name="upload_dir"]').val(upload_dir); - - $("#import_db_file_list .del").on('click',function(){ - var index = $(this).attr('index'); - var filename = file_list[index]["name"]; - myPost('delete_db_backup',{filename:filename,path:upload_dir},function(){ - showMsg('执行成功!', function(){ - getList(); - },{icon:1},2000); - }); - }); - }); - } - - var layerIndex = layer.open({ - type: 1, - title: "从文件导入数据", - area: ['700px', '380px'], - closeBtn: 1, - shadeClose: false, - content: '
      \ -
      \ - \ -
      \ -
      \ - \ -
      \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
      文件名称文件大小备份时间操作
      \ -
      \ -
        \ -
      • 仅支持sql、zip、sql.gz、(tar.gz|gz|tgz)
      • \ -
      • zip、tar.gz压缩包结构:test.zip或test.tar.gz压缩包内,必需包含test.sql
      • \ -
      • 若文件过大,您还可以使用SFTP工具,将数据库文件上传到/www/backup/import
      • \ -
      \ -
      \ -
      ', - success:function(index){ - $('#btn_file_upload').click(function(){ - var upload_dir = $('input[name="upload_dir"]').val(); - uploadDbFiles(upload_dir); - }); - - getList(); - }, - }); - - -} - -function setBackup(db_name){ - var layerIndex = layer.open({ - type: 1, - title: "数据库备份详情", - area: ['700px', '280px'], - closeBtn: 1, - shadeClose: false, - content: '
      \ -
      \ - \ - \ -
      \ -
      \ -
      \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
      文件名称文件大小备份时间操作
      \ -
      \ -
      \ -
      ', - success:function(index){ - $('#btn_backup').click(function(){ - myPost('set_db_backup',{name:db_name}, function(data){ - showMsg('执行成功!', function(){ - setBackupReq(db_name); - }, {icon:1}, 2000); - }); - }); - - $('#btn_local_import').click(function(){ - setLocalImport(db_name); - }); - - setBackupReq(db_name); - }, - }); -} - - -function setBackupReq(db_name, obj){ - myPost('get_db_backup_list', {name:db_name}, function(data){ - var rdata = $.parseJSON(data.data); - var tbody = ''; - for (var i = 0; i < rdata.data.length; i++) { - tbody += '\ - ' + rdata.data[i]['name'] + '\ - ' + rdata.data[i]['size'] + '\ - ' + rdata.data[i]['time'] + '\ - \ - 导入 | \ - 导入进度 | \ - 下载 | \ - 删除\ - \ - '; - } - $('#database_table tbody').html(tbody); - }); -} - -function dbList(page, search){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - if(typeof(search) != 'undefined'){ - _data['search'] = search; - } - myPost('get_db_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - for(i in rdata.data){ - list += ''; - list +=''; - list += '' + rdata.data[i]['name'] +''; - list += '' + rdata.data[i]['username'] +''; - list += '' + - '***' + - ''+ - ''+ - ''; - - - list += ''+rdata.data[i]['ps']+''; - list += ''; - - list += ''+(rdata.data[i]['is_backup']?'已备份':'未备份') +' | '; - - var rw = ''; - var rw_change = 'all'; - if (typeof(rdata.data[i]['rw'])!='undefined'){ - var rw_val = '读写'; - if (rdata.data[i]['rw'] == 'all'){ - rw_val = "所有"; - rw_change = 'rw'; - } else if (rdata.data[i]['rw'] == 'rw'){ - rw_val = "读写"; - rw_change = 'r'; - } else if (rdata.data[i]['rw'] == 'r'){ - rw_val = "只读"; - rw_change = 'all'; - } - rw = ''+rw_val+' | '; - } - - - list += '管理 | ' + - '工具 | ' + - '权限 | ' + - rw + - '改密 | ' + - '删除' + - ''; - list += ''; - } - - // - var con = '
      \ - \ - \ - \ - \ - \ - \ - \ - \ -
      \ -
      \ - \ - \ - \ - \ - \ - '+ - // ''+ - '\ - \ - \ - '+ list +'\ -
      数据库名用户名密码备份备注操作
      \ -
      \ -
      \ -
      \ - 同步选中\ - 同步所有\ - 从服务器获取\ -
      \ -
      \ -
      '; - - con += ''; - - $(".soft-man-con").html(con); - $('#databasePage').html(rdata.page); - - readerTableChecked(); - }); -} - - -function myBinRollingLogs(_name, func, _args, line){ - - var file_line = 100; - if ( typeof(line) != 'undefined' ){ - file_line = line; - } - - var reqTimer = null; - - function requestLogs(func,file,line){ - myPostCallbakN(func,'',{'file':file,"line":line}, function(rdata){ - var data = rdata.data.data; - var cmd = rdata.data.cmd; - if(data == '') { - data = '当前没有日志!'; - } - - $('#my_rolling_cmd').html(cmd); - - $('#my_rolling_copy').click(function(){ - copyText(cmd); - }); - - var ebody = ''; - $("#my_rolling_logs").html(ebody); - var ob = document.getElementById('roll_info_log'); - ob.scrollTop = ob.scrollHeight; - }); - } - - - layer.open({ - type: 1, - title: _name + '日志', - area: ['800px','700px'], - end: function(){ - if (reqTimer){ - clearInterval(reqTimer); - } - }, - content:'
      \ -
      \ - \ - \ - \ - \ -
      cmd
      \ -
      \ -
      \ -
      \ - \ -
      ', - success:function(){ - var fileName = _args['file']; - requestLogs(func,fileName,file_line); - reqTimer = setInterval(function(){ - requestLogs(func,fileName,file_line); - },1000); - } - }); -} - -function myBinLogsRender(page){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - _data['tojs'] = 'myBinLogsRender'; - myPost('binlog_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - // console.log(rdata); - var list = ''; - for(i in rdata.data){ - list += ''; - - list += '' + rdata.data[i]['name'] +''; - list += '' + toSize(rdata.data[i]['size'])+''; - list += '' + rdata.data[i]['time'] +''; - - - list += ''; - list += '查看 | '; - list += '解码查看'; - list += ''; - } - - if (rdata.data.length ==0){ - list = '无数据'; - } - - $("#binlog_list tbody").html(list); - $('#binlog_page').html(rdata.page); - - - $('#binlog_list .look').click(function(){ - var i = $(this).data('index'); - var file = rdata.data[i]['name']; - myBinRollingLogs('查看BINLOG','binLogListLook',{'file':file },100); - }); - - $('#binlog_list .look_decode').click(function(){ - var i = $(this).data('index'); - var file = rdata.data[i]['name']; - myBinRollingLogs('查看解码BINLOG','binLogListLookDecode',{'file':file },100); - }); - }); -} - -function myBinLogs(){ - var con = '
      \ - \ - \ -
      \ -
      \ - \ - \ - \ - \ - \ - \ - \ -
      文件名称大小时间操作
      \ -
      \ -
      \ -
      \ -
      '; - $(".soft-man-con").html(con); - myBinLogsRender(1); - - $('.soft-man-con .relay_trace').click(function(){ - myBinRollingLogs('中继日志跟踪','binLogListTraceRelay',{'file':''},100); - }); - - $('.soft-man-con .binlog_trace').click(function(){ - myBinRollingLogs('最新BINLOG日志跟踪','binLogListTraceBinLog',{'file':''},100); - }); -} - -function myLogs(){ - - myPost('bin_log', {status:1}, function(data){ - var rdata = $.parseJSON(data.data); - - var line_status = "" - if (rdata.status){ - line_status = '\ - '; - } else { - line_status = ''; - } - - var limitCon = '

      \ - 二进制日志 ' + toSize(rdata.msg) + '\ - '+line_status+'\ -

      错误日志

      \ - \ -

      '; - $(".soft-man-con").html(limitCon); - - //设置二进制日志 - $(".btn-bin").click(function () { - myPost('bin_log', 'close=change', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){myLogs();}, 2000); - }); - }); - - $(".clean-btn-bin").click(function () { - myPost('clean_bin_log', '', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){myLogs();}, 2000); - }); - }); - - //清空日志 - $(".btn-clear").click(function () { - myPost('error_log', 'close=1', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){myLogs();}, 2000); - }); - }) - - myPost('error_log', 'p=1', function(data){ - var rdata = $.parseJSON(data.data); - var error_body = ''; - if (rdata.status){ - error_body = rdata.data; - } else { - error_body = rdata.msg; - } - $("#error_log").html(error_body); - var ob = document.getElementById('error_log'); - ob.scrollTop = ob.scrollHeight; - }); - }); -} - - -function repCheckeds(tables) { - var dbs = [] - if (tables) { - dbs.push(tables) - } else { - var db_tools = $("input[value^='dbtools_']"); - for (var i = 0; i < db_tools.length; i++) { - if (db_tools[i].checked) dbs.push(db_tools[i].value.replace('dbtools_', '')); - } - } - - if (dbs.length < 1) { - layer.msg('请至少选择一张表!', { icon: 2 }); - return false; - } - return dbs; -} - -function repDatabase(db_name, tables) { - dbs = repCheckeds(tables); - - myPost('repair_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - repTools(db_name, true); - },'已送修复指令,请稍候...'); -} - - -function optDatabase(db_name, tables) { - dbs = repCheckeds(tables); - - myPost('opt_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - repTools(db_name, true); - },'已送优化指令,请稍候...'); -} - -function toDatabaseType(db_name, tables, type){ - dbs = repCheckeds(tables); - myPost('alter_table', { db_name: db_name, tables: JSON.stringify(dbs),table_type: type }, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - repTools(db_name, true); - }, '已送引擎转换指令,请稍候...'); -} - - -function selectedTools(my_obj, db_name) { - var is_checked = false - - if (my_obj) is_checked = my_obj.checked; - var db_tools = $("input[value^='dbtools_']"); - var n = 0; - for (var i = 0; i < db_tools.length; i++) { - if (my_obj) db_tools[i].checked = is_checked; - if (db_tools[i].checked) n++; - } - if (n > 0) { - var my_btns = '\ - \ - \ - ' - $("#db_tools").html(my_btns); - } else { - $("#db_tools").html(''); - } -} - -function repTools(db_name, res){ - myPost('get_db_info', {name:db_name}, function(data){ - var rdata = $.parseJSON(data.data); - var types = { InnoDB: "MyISAM", MyISAM: "InnoDB" }; - var tbody = ''; - for (var i = 0; i < rdata.tables.length; i++) { - if (!types[rdata.tables[i].type]) continue; - tbody += '\ - \ - ' + rdata.tables[i].table_name + '\ - ' + rdata.tables[i].type + '\ - ' + rdata.tables[i].collation + '\ - ' + rdata.tables[i].rows_count + '\ - ' + rdata.tables[i].data_size + '\ - \ - 修复 |\ - 优化 |\ - 转为' + types[rdata.tables[i].type] + '\ - \ - ' - } - - if (res) { - $(".gztr").html(tbody); - $("#db_tools").html(''); - $("input[type='checkbox']").attr("checked", false); - $(".tools_size").html('大小:' + rdata.data_size); - return; - } - - layer.open({ - type: 1, - title: "MySQL工具箱【" + db_name + "】", - area: ['780px', '580px'], - closeBtn: 1, - shadeClose: false, - content: '
      \ - \ -
      \ -
      \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - ' + tbody + '\ -
      表名引擎字符集行数大小操作
      \ -
      \ -
      \ -
        \ -
      • 【修复】尝试使用REPAIR命令修复损坏的表,仅能做简单修复,若修复不成功请考虑使用myisamchk工具
      • \ -
      • 【优化】执行OPTIMIZE命令,可回收未释放的磁盘空间,建议每月执行一次
      • \ -
      • 【转为InnoDB/MyISAM】转换数据表引擎,建议将所有表转为InnoDB
      • \ -
      ' - }); - tableFixed('database_fix'); - }); -} - - -function setDbMaster(name){ - myPost('set_db_master', {name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - masterOrSlaveConf(); - }, 2000); - }); -} - - -function setDbSlave(name){ - myPost('set_db_slave', {name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - masterOrSlaveConf(); - }, 2000); - }); -} - - -function addMasterRepSlaveUser(){ - layer.open({ - type: 1, - area: '500px', - title: '添加同步账户', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["提交","取消"], - content: "
      \ -
      用户名
      \ -
      \ - 密码\ -
      \ -
      \ - \ -
      ", - success:function(){ - $("input[name='name']").keyup(function(){ - var v = $(this).val(); - $("input[name='db_user']").val(v); - $("input[name='ps']").val(v); - }); - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index){ - var data = $("#add_master").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['address']){ - dataObj['address'] = dataObj['dataAccess']; - } - - myPost('add_master_rep_slave_user', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - if (rdata.status){ - getMasterRepSlaveList(); - } - },{icon: rdata.status ? 1 : 2},600); - }); - } - }); -} - - - -function updateMasterRepSlaveUser(username, password){ - - var index = layer.open({ - type: 1, - area: '500px', - title: '更新账户', - closeBtn: 1, - shift: 5, - shadeClose: true, - content: "
      \ -
      用户名
      \ -
      \ - 密码\ -
      \ -
      \ - \ -
      \ - \ -
      \ -
      ", - }); - - $('#submit_update_master').click(function(){ - var data = $("#update_master").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - myPost('update_master_rep_slave_user', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getMasterRepSlaveList(); - } - $('.layui-layer-close1').click(); - },{icon: rdata.status ? 1 : 2},600); - }); - }); -} - -function getMasterRepSlaveUserCmd(username, db=''){ - myPost('get_master_rep_slave_user_cmd', {username:username,db:db}, function(data){ - var rdata = $.parseJSON(data.data); - - if (!rdata['status']){ - layer.msg(rdata['msg']); - return; - } - - var cmd = rdata.data['cmd']; - - var loadOpen = layer.open({ - type: 1, - title: '同步命令', - area: '500px', - content:"
      \ -
      "+cmd+"
      \ -
      \ - \ -
      \ -
      ", - }); - }); -} - -function delMasterRepSlaveUser(username){ - myPost('del_master_rep_slave_user', {username:username}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg, function(){ - getMasterRepSlaveList(); - },{icon: rdata.status ? 1 : 2},1000) - }); -} - - -function setDbMasterAccess(username){ - myPost('get_db_access','username='+username, function(data){ - var rdata = $.parseJSON(data.data); - if (!rdata.status){ - layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); - return; - } - - var index = layer.open({ - type: 1, - area: '500px', - title: '设置数据库权限', - closeBtn: 1, - shift: 5, - btn:["提交","取消"], - shadeClose: true, - content: "
      \ -
      \ - 访问权限\ -
      \ - \ -
      \ -
      \ -
      ", - success:function(){ - if (rdata.msg == '127.0.0.1'){ - $('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true); - } else if (rdata.msg == '%'){ - $('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true); - } else if ( rdata.msg == 'ip' ){ - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } else { - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index){ - var data = $("#set_db_access").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['access']){ - dataObj['access'] = dataObj['dataAccess']; - if ( dataObj['dataAccess'] == 'ip'){ - if (dataObj['address']==''){ - layer.msg('IP地址不能空!',{icon:2,shade: [0.3, '#000']}); - return; - } - dataObj['access'] = dataObj['address']; - } - } - dataObj['username'] = username; - myPost('set_dbmaster_access', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - },{icon: rdata.status ? 1 : 2}); - }); - } - }); - - }); -} - - -function resetMaster(){ - myPost('reset_master', '', function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - },{icon: rdata.status ? 1 : 2}); - },'正在执行重置master命令[reset master]'); -} - -function getMasterRepSlaveList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - myPost('get_master_rep_slave_list', _data, function(data){ - // console.log(data); - var rdata = []; - try { - rdata = $.parseJSON(data.data); - } catch(e){ - console.log(e); - } - var list = ''; - // console.log(rdata['data']); - var user_list = rdata['data']; - for (i in user_list) { - // console.log(i); - var name = user_list[i]['username']; - var password = user_list[i]['password']; - list += ''+name+'\ - '+password+'\ - \ - 修改 | \ - 删除 | \ - 权限 | \ - 从库同步命令\ - \ - '; - } - - $('#get_master_rep_slave_list_page tbody').html(list); - $('.dataTables_paginate_4').html(rdata['page']); - }); -} - -function getMasterRepSlaveListPage(){ - var page = '
      '; - page += '
      添加同步账户
      '; - - var loadOpen = layer.open({ - type: 1, - title: '同步账户列表', - area: '500px', - content:"
      \ -
      \ -
      \ - \ - \ -
      用户名密码操作
      \ - "+page +"\ -
      \ -
      ", - success:function(){ - getMasterRepSlaveList(); - } - }); -} - - -function deleteSlave(sign){ - myPost('delete_slave', {sign:sign}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata['msg'], function(){ - masterOrSlaveConf(); - },{icon:rdata.status?1:2,time:3000},3000); - }); -} - - -function getFullSyncStatus(db){ - var timeId = null; - - myPost('get_slave_list', {page:1,page_size:100}, function(data){ - var rdata = $.parseJSON(data.data); - var rsource = rdata.data; - - if (db == 'ALL' && rsource.length>1){ - layer.msg("多主不支持该模式!",{icon:2}); - return; - } - - var dataSource = ''; - if (rsource.length>1){ - var sourceList = ''; - for (var i = 0; i < rsource.length; i++) { - if ('Channel_Name' in rsource[i]){ - sourceList += ''; - } - } - - dataSource = "

      \ - 同步数据源:\ - \ -

      "; - } - - layer.open({ - type: 1, - title: '全量同步['+db+']', - area: '500px', - content:"
      \ -
      \ - "+dataSource+"\ - \ -
      \ -
      0%
      \ -
      \ -
      \ -
      \ - 开始\ - 手动命令\ -
      \ -
      ", - cancel: function(){ - clearInterval(timeId); - }, - success:function(){ - $('#begin_full_sync').click(function(){ - var val = $(this).data('status'); - var sign = ''; - if (dataSource !=''){ - sign = $('select[name="data_source"]').val(); - } - if (val == 'init'){ - fullSync(db, sign, 1); - timeId = setInterval(function(){ - fullSync(db,sign,0); - }, 1000); - $(this).data('status','starting'); - $('#begin_full_sync').text("同步中"); - } else { - layer.msg("正在同步中..",{icon:0}); - } - }); - - $('#full_sync_cmd').click(function(){ - myPostN('full_sync_cmd', {'db':db,'sign':''}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - layer.open({ - title: "手动执行命令CMD", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
      \ -
      \ -
      '+rdata.data+'
      \ -
      \ -
      ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); - }); - } - }); - }); - - function fullSync(db,sign,begin){ - - myPostN('full_sync', {db:db,sign:sign,begin:begin}, function(data){ - var rdata = $.parseJSON(data.data); - $('#full_msg').text(rdata['msg']); - $('.progress-bar').css('width',rdata['progress']+'%'); - $('.progress-bar').text(rdata['progress']+'%'); - - if (rdata['code']==6 ||rdata['code']<0){ - layer.msg(rdata['msg']); - clearInterval(timeId); - $('#begin_full_sync').text("同步结束,再次同步?"); - $("#begin_full_sync").attr('data-status','init'); - } - }); - } -} - -function dataSyncVerify(db){ - var reqTimer = null; - - function requestLogs(layerIndex){ - myPostN('sync_database_repair_log', {db:db, sign:'',op:'get'}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - - if(!rdata.status) { - layer.close(layerIndex); - layer.msg(rdata.msg,{icon:2, time:2000}); - clearInterval(reqTimer); - return; - }; - - if (rdata.msg == ''){ - rdata.msg = '暂无数据!'; - } - - $("#data_verify_log").html(rdata.msg); - //滚动到最低 - var ob = document.getElementById('data_verify_log'); - ob.scrollTop = ob.scrollHeight; - }); - } - - layer.open({ - type: 1, - title: '同步数据库['+db+']数据校验', - area: '500px', - btn:[ "开始","取消","手动"], - content:"
      \ - "+'
      '+"\
      -            
      ", - cancel: function(){ - if (reqTimer){ - clearInterval(reqTimer); - } - }, - yes:function(index,layer_index){ - myPostN('sync_database_repair_log', {db:db, sign:'',op:'do'}, function(data){}); - layer.msg("执行成功"); - - requestLogs(layer_index); - reqTimer = setInterval(function(){ - requestLogs(layer_index); - },3000); - }, - success:function(){ - }, - btn3: function(){ - myPostN('sync_database_repair_log', {db:db, sign:'',op:'cmd'}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - layer.open({ - title: "手动执行命令CMD", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
      \ -
      \ -
      '+rdata.data+'
      \ -
      \ -
      ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); - return false; - } - - }); -} - -function addSlaveSSH(ip=''){ - - myPost('get_slave_ssh_by_ip', {ip:ip}, function(rdata){ - - var rdata = $.parseJSON(rdata.data); - - var ip = '127.0.0.1'; - var port = "22"; - var id_rsa = ''; - var db_user =''; - - if (rdata.data.length>0){ - ip = rdata.data[0]['ip']; - port = rdata.data[0]['port']; - id_rsa = rdata.data[0]['id_rsa']; - db_user = rdata.data[0]['db_user']; - } - - var index = layer.open({ - type: 1, - area: ['500px','480px'], - title: '添加SSH', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["确认","取消"], - content: "
      \ -
      IP
      \ -
      端口
      \ -
      同步账户[DB]
      \ -
      \ - ID_RSA\ -
      \ -
      \ - \ -
      ", - success:function(){ - $('textarea[name="id_rsa"]').html(id_rsa); - }, - yes:function(index){ - var ip = $('input[name="ip"]').val(); - var port = $('input[name="port"]').val(); - var db_user = $('input[name="db_user"]').val(); - var id_rsa = $('textarea[name="id_rsa"]').val(); - - var data = {ip:ip,port:port,id_rsa:id_rsa,db_user:db_user}; - myPost('add_slave_ssh', data, function(data){ - layer.close(index); - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSSHPage(); - } - },{icon: rdata.status ? 1 : 2},600); - }); - } - }); - }); -} - - -function delSlaveSSH(ip){ - myPost('del_slave_ssh', {ip:ip}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSSHPage(); - } - },{icon: rdata.status ? 1 : 2}, 600); - }); -} - - -function delSlaveSyncUser(ip){ - myPost('del_slave_sync_user', {ip:ip}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSyncUserPage(); - } - },{icon: rdata.status ? 1 : 2}, 600); - }); -} - -function getSlaveSSHPage(page=1){ - var _data = {}; - _data['page'] = page; - _data['page_size'] = 5; - _data['tojs'] ='getSlaveSSHPage'; - myPost('get_slave_ssh_list', _data, function(data){ - var layerId = null; - var rdata = []; - try { - rdata = $.parseJSON(data.data); - } catch(e) { - console.log(e); - } - var list = ''; - var ssh_list = rdata['data']; - for (i in ssh_list) { - var ip = ssh_list[i]['ip']; - var port = ssh_list[i]['port']; - - var id_rsa = '未设置'; - if ( ssh_list[i]['port'] != ''){ - id_rsa = '已设置'; - } - - var db_user = '未设置'; - if ( ssh_list[i]['db_user'] != ''){ - db_user = ssh_list[i]['db_user']; - } - - list += ''+ip+'\ - '+port+'\ - '+db_user+'\ - '+id_rsa+'\ - \ - 修改 | \ - 删除\ - \ - '; - } - - $('.get-slave-ssh-list tbody').html(list); - $('.dataTables_paginate_4').html(rdata['page']); - }); -} - - - -function addSlaveSyncUser(ip=''){ - - myPost('get_slave_sync_user_by_ip', {ip:ip}, function(rdata){ - - var rdata = $.parseJSON(rdata.data); - - var ip = '127.0.0.1'; - var port = "22"; - var cmd = ''; - var user = 'input_sync_user'; - var pass = 'input_sync_pwd'; - var mode = '0'; - - if (rdata.data.length>0){ - ip = rdata.data[0]['ip']; - port = rdata.data[0]['port']; - cmd = rdata.data[0]['cmd']; - user = rdata.data[0]['user']; - pass = rdata.data[0]['pass']; - mode = rdata.data[0]['mode']; - } - - var index = layer.open({ - type: 1, - area: ['500px','510px'], - title: '同步账户', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["确认","取消"], - content: "
      \ -
      IP
      \ -
      端口
      \ -
      同步账户
      \ -
      同步密码
      \ -
      \ - 同步模式\ -
      \ - \ -
      \ -
      \ -
      \ - CMD[必填]\ -
      \ -
      \ - \ -
      ", - success:function(){ - $('textarea[name="cmd"]').html(cmd); - $('textarea[name="cmd"]').change(function(){ - var val = $(this).val(); - val = val.replace(';',''); - var a = {}; - if (val.toLowerCase().indexOf('for')>0){ - cmd_tmp = val.split('for'); - val = cmd_tmp[0].trim(); - - const channel_str = cmd_tmp[1].trim(); - const ch_reg = /channel \'(.*)\';/; - var match_val = channel_str.match(ch_reg); - if (match_val.length>1){ - a['channel'] = match_val[1]; - } - } - - var vlist = val.split(','); - for (var i in vlist) { - var tmp = toTrim(vlist[i]); - var tmp_a = tmp.split(" "); - var real_tmp = tmp_a[tmp_a.length-1]; - var kv = real_tmp.split("="); - a[kv[0]] = kv[1].replace("'",'').replace("'",''); - } - - if ('MASTER_HOST' in a){ - $('input[name="ip"]').val(a['MASTER_HOST']); - $('input[name="port"]').val(a['MASTER_PORT']); - $('input[name="user"]').val(a['MASTER_USER']); - $('input[name="pass"]').val(a['MASTER_PASSWORD']); - } else { - $('input[name="ip"]').val(a['SOURCE_HOST']); - $('input[name="port"]').val(a['SOURCE_PORT']); - $('input[name="user"]').val(a['SOURCE_USER']); - $('input[name="pass"]').val(a['SOURCE_PASSWORD']); - } - - }); - }, - yes:function(index){ - var ip = $('input[name="ip"]').val(); - var port = $('input[name="port"]').val(); - var user = $('input[name="user"]').val(); - var pass = $('input[name="pass"]').val(); - var cmd = $('textarea[name="cmd"]').val(); - var mode = $('select[name="mode"]').val(); - - var data = {ip:ip,port:port,cmd:cmd,user:user,pass:pass,mode:mode}; - myPost('add_slave_sync_user', data, function(ret_data){ - layer.close(index); - var rdata = $.parseJSON(ret_data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSyncUserPage(); - } - },{icon: rdata.status ? 1 : 2},600); - }); - } - }); - }); -} - -function getSlaveSyncUserPage(page=1){ - var _data = {}; - _data['page'] = page; - _data['page_size'] = 5; - _data['tojs'] ='getSlaveSyncUserPage'; - myPost('get_slave_sync_user_list', _data, function(data){ - var layerId = null; - var rdata = []; - try { - rdata = $.parseJSON(data.data); - } catch(e) { - console.log(e); - } - - var list = ''; - var user_list = rdata['data']; - for (i in user_list) { - var ip = user_list[i]['ip']; - var port = user_list[i]['port']; - var user = user_list[i]['user']; - var apass = user_list[i]['pass']; - - var cmd = '未设置'; - if (user_list[i]['cmd']!=''){ - cmd = '已设置'; - } - - list += ''+ip+'\ - '+port+'\ - '+user+'\ - '+apass+'\ - '+cmd+'\ - \ - 修改 | \ - 删除\ - \ - '; - } - - $('.get-slave-ssh-list tbody').html(list); - $('.dataTables_paginate_4').html(rdata['page']); - }); -} - -function getSlaveCfg(){ - - myPost('get_slave_sync_mode', '', function(data){ - var rdata = $.parseJSON(data.data); - var mode_none = 'success'; - var mode_ssh = 'danger'; - var mode_sync_user = 'danger'; - if(rdata.status){ - var mode_none = 'danger'; - if (rdata.data == 'ssh'){ - var mode_ssh = 'success'; - var mode_sync_user = 'danger'; - } else { - var mode_ssh = 'danger'; - var mode_sync_user = 'success'; - } - } - - layerId = layer.open({ - type: 1, - title: '同步配置', - area: ['400px','180px'], - content:"
      \ -

      \ - 当前从库同步模式\ - \ - \ - \ - \ -

      \ -
      \ -

      \ - 配置设置\ - \ - \ - \ -

      \ -
      ", - success:function(){ - $('.btn-slave-ssh').click(function(){ - getSlaveSSHList(); - }); - - $('.btn-slave-user').click(function(){ - getSlaveUserList(); - }); - - $('.slave-db-mode').click(function(){ - var _this = this; - var mode = 'none'; - if ($(this).hasClass('btn-ssh')){ - mode = 'ssh'; - } - if ($(this).hasClass('btn-sync-user')){ - mode = 'sync-user'; - } - - myPost('set_slave_sync_mode', {mode:mode}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - $('.slave-db-mode').remove('btn-success').addClass('btn-danger'); - $(_this).removeClass('btn-danger').addClass('btn-success'); - },{icon:rdata.status?1:2},2000); - }); - - }); - } - }); - }); -} - - -function getSlaveUserList(){ - - var page = '
      '; - page += '
      添加同步账户
      '; - - layerId = layer.open({ - type: 1, - title: '同步账户列表', - area: '600px', - content:"
      \ -
      \ -
      \ - \ - \ -
      IPPORT同步账户同步密码CMD操作
      \ - "+page +"\ -
      \ -
      ", - success:function(){ - getSlaveSyncUserPage(1); - } - }); -} - -function getSlaveSSHList(page=1){ - - var page = '
      '; - page += '
      添加SSH
      '; - - layerId = layer.open({ - type: 1, - title: 'SSH列表', - area: '600px', - content:"
      \ -
      \ -
      \ - \ - \ -
      IPPORT同步账户SSH操作
      \ - "+page +"\ -
      \ -
      ", - success:function(){ - getSlaveSSHPage(1); - } - }); -} - -function handlerRun(){ - myPostN('get_slave_sync_cmd', {}, function(data){ - var rdata = $.parseJSON(data.data); - var cmd = rdata['data']; - var loadOpen = layer.open({ - type: 1, - title: '手动执行', - area: '500px', - content:"
      \ -
      "+cmd+"
      \ -
      \ - \ -
      \ -
      ", - }); - copyPass(cmd); - $('.class-copy-cmd').click(function(){ - copyPass(cmd); - }); - }); -} - -function initSlaveStatus(){ - myPost('init_slave_status', '', function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - masterOrSlaveConf(); - } - },{icon:rdata.status?1:2},2000); - }); -} - -function masterOrSlaveConf(version=''){ - - function getMasterDbList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - - myPost('get_masterdb_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - for(i in rdata.data){ - list += ''; - list += '' + rdata.data[i]['name'] +''; - list += '' + (rdata.data[i]['master']?'是':'否') +''; - list += '' + - ''+(rdata.data[i]['master']?'退出':'加入')+' | ' + - '同步命令' + - ''; - list += ''; - } - - var con = '
      \ -
      \ - \ - \ - \ - \ - \ - \ - '+ list +'\ -
      数据库名同步操作
      \ -
      \ -
      \ -
      \ - 同步账户列表\ -
      \ -
      '; - - $(".table_master_list").html(con); - $('#databasePage').html(rdata.page); - }); - } - - function getAsyncMasterDbList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - - var mdb_ver = $('.plugin_version').attr('version'); - - myPost('get_slave_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - - var isHasSign = false; - for(i in rdata.data){ - - var v = rdata.data[i]; - if ('Channel_Name' in v && v['Channel_Name'] !=''){ - isHasSign = true; - } - - var status = "异常"; - if (mdb_ver >= 8){ - - if (v['Replica_SQL_Running'] == 'Yes' && v['Replica_IO_Running'] == 'Yes'){ - status = "正常"; - } - - list += ''; - list += '' + rdata.data[i]['Source_Host'] +''; - list += '' + rdata.data[i]['Source_Port'] +''; - list += '' + rdata.data[i]['Source_User'] +''; - list += '' + rdata.data[i]['Relay_Source_Log_File'] +''; - list += '' + rdata.data[i]['Replica_IO_Running'] +''; - list += '' + rdata.data[i]['Replica_SQL_Running'] +''; - - } else { - if (v['Slave_SQL_Running'] == 'Yes' && v['Slave_IO_Running'] == 'Yes'){ - status = "正常"; - } - - list += ''; - list += '' + rdata.data[i]['Master_Host'] +''; - list += '' + rdata.data[i]['Master_Port'] +''; - list += '' + rdata.data[i]['Master_User'] +''; - list += '' + rdata.data[i]['Master_Log_File'] +''; - list += '' + rdata.data[i]['Slave_IO_Running'] +''; - list += '' + rdata.data[i]['Slave_SQL_Running'] +''; - } - - - if (isHasSign){ - list += '' + v['Channel_Name'] +''; - } - - list += '' + status +''; - list += '' + - '删除' + - ''; - list += ''; - } - - var signThead_th = ''; - if (isHasSign){ - var signThead_th = '标识'; - } - - var con = '
      \ -
      \ - \ - \ - \ - \ - \ - \ - \ - \ - '+signThead_th+'\ - \ - \ - \ - '+ list +'\ -
      主[服务]端口用户日志IOSQL状态操作
      \ -
      \ -
      '; - - //
      \ - //
      \ - // 添加\ - //
      - $(".table_slave_status_list").html(con); - - $(".btn_delete_slave").click(function(){ - var id = $(this).data('id'); - var v = rdata.data[id]; - if ('Channel_Name' in v){ - deleteSlave(v['Channel_Name']); - } else{ - deleteSlave(); - } - }); - - $('.db_error').click(function(){ - var id = $(this).data('id'); - var info = rdata.data[id]; - - var err_line = ""; - err_line +="\ - IO错误\ - "+ (info['Last_IO_Error'] == '' ? '无':info['Last_IO_Error'])+"\ - "; - err_line +="\ - SQL错误\ - "+(info['Last_SQL_Error'] == '' ? '无':info['Last_SQL_Error'])+"\ - "; - - err_line +="\ - 状态\ - "+(info['Slave_SQL_Running_State'] == '' ? '无':info['Slave_SQL_Running_State']) +"\ - "; - - - var btn_list = ['复制错误',"取消"]; - if (info['Last_IO_Error'].search(/1236/i)>0){ - btn_list = ['复制错误',"取消","尝试修复"]; - } - layer.open({ - type: 1, - title: '同步异常信息', - area: ['600px','300px'], - btn:btn_list, - content:"
      \ -
      \ -
      \ - \ - \ - \ - \ - \ - "+ err_line +"\ -
      类型内容
      \ -
      \ -
      \ -
      ", - success:function(){ - if (info['Last_IO_Error'] != ''){ - copyText(info['Last_IO_Error']); - return; - } - - if (info['Last_SQL_Error'] != ''){ - copyText(info['Last_SQL_Error']); - return; - } - - if (info['Slave_SQL_Running_State'] != ''){ - copyText(info['Slave_SQL_Running_State']); - return; - } - }, - yes:function(){ - if (info['Last_IO_Error'] != ''){ - copyText(info['Last_IO_Error']); - return; - } - - if (info['Last_SQL_Error'] != ''){ - copyText(info['Last_SQL_Error']); - return; - } - - if (info['Slave_SQL_Running_State'] != ''){ - copyText(info['Slave_SQL_Running_State']); - return; - } - }, - btn3:function(){ - myPost('try_slave_sync_bugfix', {}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg, function(){ - masterOrSlaveConf(); - },{ icon: rdata.status ? 1 : 5 },2000); - }); - } - }); - }); - }); - } - - function getAsyncDataList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - myPost('get_masterdb_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - for(i in rdata.data){ - list += ''; - list += '' + rdata.data[i]['name'] +''; - list += '' + - ''+(rdata.data[i]['slave']?'退出':'加入')+' | ' + - '同步 | ' + - '数据校验' + - ''; - list += ''; - } - - var con = '
      \ -
      \ - \ - \ - \ - \ - \ - '+ list +'\ -
      本地库名操作
      \ -
      \ -
      \ -
      \ - 手动命令\ - 全量同步\ -
      \ -
      '; - - $(".table_slave_list").html(con); - $('#databasePage').html(rdata.page); - }); - } - - - function getMasterStatus(){ - myPost('get_master_status', '', function(rdata){ - var rdata = $.parseJSON(rdata.data); - // console.log('mode:',rdata.data); - if ( typeof(rdata.status) != 'undefined' && !rdata.status && rdata.data == 'pwd'){ - layer.msg(rdata.msg, {icon:2}); - return; - } - - var rdata = rdata.data; - var limitCon = '\ -

      \ - 主从同步模式\ - \ - \ -

      \ -
      \ -

      \ - Master[主]配置\ - \ - \ -

      \ -
      \ - \ -
      \ -
      \ - \ -

      \ - Slave[从]配置\ - \ - \ - \ -

      \ -
      \ - \ -
      \ - \ -
      \ - '; - $(".soft-man-con").html(limitCon); - - //设置主服务器配置 - $(".btn-master").click(function () { - myPost('set_master_status', 'close=change', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - getMasterStatus(); - }, 3000); - }); - }); - - $(".btn-slave").click(function () { - myPost('set_slave_status', 'close=change', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - getMasterStatus(); - }, 3000); - }); - }); - - $('.db-mode').click(function(){ - if ($(this).hasClass('btn-success')){ - //no action - return; - } - - var mode = 'classic'; - if ($(this).hasClass('btn-gtid')){ - mode = 'gtid'; - } - - layer.open({ - type:1, - title:"MySQL主从模式切换", - shadeClose:false, - btnAlign: 'c', - btn: ['切换并重启', '切换不重启'], - yes: function(index, layero){ - this.change(index,mode,"yes"); - - }, - btn2: function(index, layero){ - this.change(index,mode,"no"); - return false; - }, - change:function(index,mode,reload){ - console.log(index,mode,reload); - myPost('set_dbrun_mode',{'mode':mode,'reload':reload},function(data){ - layer.close(index); - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg ,function(){ - getMasterStatus(); - },{ icon: rdata.status ? 1 : 5 }); - }); - } - }); - }); - - if (rdata.status){ - getMasterDbList(); - } - - // if (rdata.slave_status){ - getAsyncMasterDbList(); - getAsyncDataList() - // } - }); - } - getMasterStatus(); -} diff --git a/plugins/mysql-apt/scripts/backup.py b/plugins/mysql-apt/scripts/backup.py deleted file mode 100755 index a058e5d235..0000000000 --- a/plugins/mysql-apt/scripts/backup.py +++ /dev/null @@ -1,119 +0,0 @@ -# coding: utf-8 -#----------------------------- -# 网站备份工具 -#----------------------------- - -import sys -import os -import time -import re - -if sys.platform != 'darwin': - os.chdir('/www/server/mdserver-web') - -web_dir = os.getcwd() + "/web" -if os.path.exists(web_dir): - sys.path.append(web_dir) - os.chdir(web_dir) - -import core.mw as mw -import core.db as db - -''' -DEBUG: -python3 /www/server/mdserver-web/plugins/mysql-apt/scripts/backup.py database admin 3 -''' - - -class backupTools: - - def backupDatabase(self, name, count): - db_path = mw.getServerDir() + '/mysql-apt' - db_name = 'mysql' - find_name = mw.M('databases').dbPos(db_path, 'mysql').where( - 'name=?', (name,)).getField('name') - startTime = time.time() - if not find_name: - endDate = time.strftime('%Y/%m/%d %X', time.localtime()) - log = "数据库[" + name + "]不存在!" - print("★[" + endDate + "] " + log) - print( - "----------------------------------------------------------------------------") - return - - backup_path = mw.getFatherDir() + '/backup/database/mysql-apt' - if not os.path.exists(backup_path): - mw.execShell("mkdir -p " + backup_path) - - filename = backup_path + "/db_" + name + "_" + \ - time.strftime('%Y%m%d_%H%M%S', time.localtime()) + ".sql.gz" - - mysql_root = mw.M('config').dbPos(db_path, db_name).where( - "id=?", (1,)).getField('mysql_root') - - my_conf_path = db_path + '/etc/my.cnf' - mycnf = mw.readFile(my_conf_path) - rep = r"\[mysqldump\]\nuser=root" - sea = "[mysqldump]\n" - subStr = sea + "user=root\npassword=" + mysql_root + "\n" - mycnf = mycnf.replace(sea, subStr) - if len(mycnf) > 100: - mw.writeFile(db_path + '/etc/my.cnf', mycnf) - - cmd = db_path + "/bin/usr/bin/mysqldump --defaults-file=" + my_conf_path + " --single-transaction -q --default-character-set=utf8mb4 " + \ - name + " | gzip > " + filename - mw.execShell(cmd) - - if not os.path.exists(filename): - endDate = time.strftime('%Y/%m/%d %X', time.localtime()) - log = "数据库[" + name + "]备份失败!" - print("★[" + endDate + "] " + log) - print( - "----------------------------------------------------------------------------") - return - - mycnf = mw.readFile(db_path + '/etc/my.cnf') - mycnf = mycnf.replace(subStr, sea) - if len(mycnf) > 100: - mw.writeFile(db_path + '/etc/my.cnf', mycnf) - - endDate = time.strftime('%Y/%m/%d %X', time.localtime()) - outTime = time.time() - startTime - pid = mw.M('databases').dbPos(db_path, db_name).where('name=?', (name,)).getField('id') - - mw.M('backup').add('type,name,pid,filename,add_time,size', (1, os.path.basename(filename), pid, filename, endDate, os.path.getsize(filename))) - log = "数据库[" + name + "]备份成功,用时[" + str(round(outTime, 2)) + "]秒" - mw.writeLog('计划任务', log) - print("★[" + endDate + "] " + log) - print("|---保留最新的[" + count + "]份备份") - print("|---文件名:" + filename) - - # 清理多余备份 - backups = mw.M('backup').where('type=? and pid=?', ('1', pid)).field('id,filename').select() - - num = len(backups) - int(count) - if num > 0: - for backup in backups: - mw.execShell("rm -f " + backup['filename']) - mw.M('backup').where('id=?', (backup['id'],)).delete() - num -= 1 - print("|---已清理过期备份文件:" + backup['filename']) - if num < 1: - break - - def backupDatabaseAll(self, save): - db_path = mw.getServerDir() + '/mysql-apt' - db_name = 'mysql' - databases = mw.M('databases').dbPos(db_path, db_name).field('name').select() - for database in databases: - self.backupDatabase(database['name'], save) - - -if __name__ == "__main__": - backup = backupTools() - type = sys.argv[1] - if type == 'database': - if sys.argv[2] == 'ALL': - backup.backupDatabaseAll(sys.argv[3]) - else: - backup.backupDatabase(sys.argv[2], sys.argv[3]) diff --git a/plugins/mysql-apt/versions/5.7/install.sh b/plugins/mysql-apt/versions/5.7/install.sh deleted file mode 100755 index 1d2a70c432..0000000000 --- a/plugins/mysql-apt/versions/5.7/install.sh +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -# debug -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 -# /www/server/mysql-apt/bin/usr/sbin/mysqld --defaults-file=/www/server/mysql-apt/etc/my.cnf --daemonize -# /www/server/mysql-apt/bin/usr/bin/mysql -S /www/server/mysql-apt/mysql.sock -uroot -p - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -MYSQL_VER=5.7.39 -if [ "$OSNAME" == "debian" ];then - # mysql5.7现在仅有10的编译版 - VERSION_ID="10" -fi - -if [ "$OSNAME" == "ubuntu" ];then - # mysql5.7现在仅有18.04的编译版 - VERSION_ID="18.04" -fi - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 0 -fi - -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-5.7/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '5.7' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/5.7/install_generic.sh b/plugins/mysql-apt/versions/5.7/install_generic.sh deleted file mode 100755 index cd2f003db8..0000000000 --- a/plugins/mysql-apt/versions/5.7/install_generic.sh +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -OS_ARCH=`arch` -MYSQL_VER=5.7.44 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.12-${OS_ARCH} - -if [ "$OS_ARCH" == "x86_64" ] || [ "$OS_ARCH" == "i686" ];then - echo "ok" -else - echo "暂时不支持该${OS_ARCH}" - exit 0 -fi - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 5.7 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 5.7 -APT_INSTALL() -{ - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt - -# Linux - Generic -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.gz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.gz https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.tar.gz -fi - -if [ -d ${myDir} ];then - cd ${myDir} && tar -zvxf ${myDir}/mysql-${SUFFIX_NAME}.tar.gz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt -fi - -# 测试时可关闭 -rm -rf $myDir/mysql-${SUFFIX_NAME} -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir/mysql-${SUFFIX_NAME} -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '5.7' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '5.7' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.0/install.sh b/plugins/mysql-apt/versions/8.0/install.sh deleted file mode 100755 index 082460a6e7..0000000000 --- a/plugins/mysql-apt/versions/8.0/install.sh +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.0 - -# 暂时debian12没有标准版,先用11使用 -# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then -# echo "暂时不支持该${OSNAME}${VERSION_ID}" -# exit 1 -# fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.0.39 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.0' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.0' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.0/install_generic.sh b/plugins/mysql-apt/versions/8.0/install_generic.sh deleted file mode 100755 index 5a080cd694..0000000000 --- a/plugins/mysql-apt/versions/8.0/install_generic.sh +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -OS_ARCH=`arch` -MYSQL_VER=8.0.39 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.0 -APT_INSTALL() -{ - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt - -# Linux - Generic -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.0/mysql-${SUFFIX_NAME}.tar.xz -fi - -if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt -fi - -# 测试时可关闭 -rm -rf $myDir/mysql-${SUFFIX_NAME} -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir/mysql-${SUFFIX_NAME} -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.0' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.0' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.2/install.sh b/plugins/mysql-apt/versions/8.2/install.sh deleted file mode 100755 index 81cade8267..0000000000 --- a/plugins/mysql-apt/versions/8.2/install.sh +++ /dev/null @@ -1,137 +0,0 @@ - -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 -# cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql-apt/index.py start - -# 暂时debian12没有标准版,先用11使用 -# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then -# echo "暂时不支持该${OSNAME}${VERSION_ID}" -# exit 1 -# fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.2.0 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.2/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.2' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.2' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.2/install_generic.sh b/plugins/mysql-apt/versions/8.2/install_generic.sh deleted file mode 100755 index 769c583981..0000000000 --- a/plugins/mysql-apt/versions/8.2/install_generic.sh +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -OS_ARCH=`arch` -MYSQL_VER=8.2.0 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.2 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.2 -APT_INSTALL() -{ - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt - -# Linux - Generic -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.2/mysql-${SUFFIX_NAME}.tar.xz -fi - -if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt -fi - -# 测试时可关闭 -rm -rf $myDir/mysql-${SUFFIX_NAME} -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir/mysql-${SUFFIX_NAME} -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.2' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.2' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.3/install.sh b/plugins/mysql-apt/versions/8.3/install.sh deleted file mode 100755 index 316ae77edf..0000000000 --- a/plugins/mysql-apt/versions/8.3/install.sh +++ /dev/null @@ -1,135 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0 - -# 暂时debian12没有标准版,先用11使用 -# if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" == '12' ] ;then -# echo "暂时不支持该${OSNAME}${VERSION_ID}" -# exit 1 -# fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.3.0 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-8.3/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.3' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.3' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.3/install_generic.sh b/plugins/mysql-apt/versions/8.3/install_generic.sh deleted file mode 100755 index c451fbd36d..0000000000 --- a/plugins/mysql-apt/versions/8.3/install_generic.sh +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -OS_ARCH=`arch` -MYSQL_VER=8.3.0 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.3 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.3 -APT_INSTALL() -{ - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt - -# Linux - Generic -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.3/mysql-${SUFFIX_NAME}.tar.xz -fi - -if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt -fi - -# 测试时可关闭 -rm -rf $myDir/mysql-${SUFFIX_NAME} -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir/mysql-${SUFFIX_NAME} -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.3' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.3' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.4/install.sh b/plugins/mysql-apt/versions/8.4/install.sh deleted file mode 100755 index dfcd789980..0000000000 --- a/plugins/mysql-apt/versions/8.4/install.sh +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 - -if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then - VERSION_ID="12" -fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=8.4.2 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -# https://cdn.mysql.com/archives/mysql-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.4' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.4' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/8.4/install_generic.sh b/plugins/mysql-apt/versions/8.4/install_generic.sh deleted file mode 100755 index 5932cb0fa3..0000000000 --- a/plugins/mysql-apt/versions/8.4/install_generic.sh +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -OS_ARCH=`arch` -MYSQL_VER=8.4.2 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.4 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 8.4 -APT_INSTALL() -{ - - - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt - -# Linux - Generic -# https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.tar.xz -fi - -if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt -fi - -# 测试时可关闭 -rm -rf $myDir/mysql-${SUFFIX_NAME} -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir/mysql-${SUFFIX_NAME} -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '8.4' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '8.4' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/9.0/install.sh b/plugins/mysql-apt/versions/9.0/install.sh deleted file mode 100755 index 874522d9d4..0000000000 --- a/plugins/mysql-apt/versions/9.0/install.sh +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 - -# 暂时debian12没有标准版,先用11使用 -if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then - VERSION_ID="12" -fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=9.0.1 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -# https://dev.mysql.com/get/Downloads/MySQL-9.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# https://cdn.mysql.com/archives/mysql-9.0/mysql-server_9.0.1-1debian12_amd64.deb-bundle.tar - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://cdn.mysql.com/archives/mysql-9.0/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.0' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '9.0' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/9.0/install_generic.sh b/plugins/mysql-apt/versions/9.0/install_generic.sh deleted file mode 100755 index 2a8cf58683..0000000000 --- a/plugins/mysql-apt/versions/9.0/install_generic.sh +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -OS_ARCH=`arch` -MYSQL_VER=9.0.1 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.0 -APT_INSTALL() -{ - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt - -# Linux - Generic -# https://cdn.mysql.com/archives/mysql-9.0/mysql-9.0.1-linux-glibc2.28-x86_64.tar.xz -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/archives/mysql-9.0/mysql-${SUFFIX_NAME}.tar.xz -fi - -if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt -fi - -# 测试时可关闭 -rm -rf $myDir/mysql-${SUFFIX_NAME} -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir/mysql-${SUFFIX_NAME} -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.0' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '9.0' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/9.1/install.sh b/plugins/mysql-apt/versions/9.1/install.sh deleted file mode 100755 index 27d3460981..0000000000 --- a/plugins/mysql-apt/versions/9.1/install.sh +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.1 -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.1 - -#x-faq -# strings /lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIB - -# debian12 -if [ "$OSNAME" == 'debian' ] && [ "$VERSION_ID" -lt '12' ] ;then - VERSION_ID="12" -fi - - -ARCH="amd64" -TMP_ARCH=`arch` -if [ "$TMP_ARCH" == "x86_64" ];then - ARCH="amd64" -elif [ "$TMP_ARCH" == "aarch64" ];then - ARCH="arm64" -else - ARCH="amd64" -fi - -if [ "$ARCH" != "amd64" ];then - echo "暂时不支持该${ARCH}" - exit 1 -fi - - -MYSQL_VER=9.1.0 -SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH} - - -# /lib/systemd/system/mysql.service -# /etc/mysql/my.cnf - -APT_INSTALL() -{ - -cd ${rootPath}/plugins/php/lib && /bin/bash openssl_30.sh - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt/bin - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -# https://cdn.mysql.com/archives/mysql-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -# https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -wget --no-check-certificate -O ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-9.1/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -chmod +x ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar -cd ${myDir} && tar vxf ${myDir}/mysql-server_${SUFFIX_NAME}.deb-bundle.tar - -apt update -y -apt install -y libnuma1 libaio1 libmecab2 - -# 安装 -dpkg -X mysql-common_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - - - -dpkg -X mysql-community-client-plugins_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-community-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-client_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server-core_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -dpkg -X mysql-community-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin -dpkg -X mysql-server_${SUFFIX_NAME}.deb $serverPath/mysql-apt/bin - -# 测试时可关闭 -rm -rf $myDir -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.1' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '9.1' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-apt/versions/9.1/install_generic.sh b/plugins/mysql-apt/versions/9.1/install_generic.sh deleted file mode 100755 index 0c0ea4bb53..0000000000 --- a/plugins/mysql-apt/versions/9.1/install_generic.sh +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH -export DEBIAN_FRONTEND=noninteractive - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-apt - -OS_ARCH=`arch` -MYSQL_VER=9.1.0 -SUFFIX_NAME=${MYSQL_VER}-linux-glibc2.28-${OS_ARCH} - -# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 9.1 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-apt/index.py start 9.1 -APT_INSTALL() -{ - -######## -mkdir -p $myDir -mkdir -p $serverPath/mysql-apt - -# Linux - Generic -# https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.2-linux-glibc2.28-x86_64.tar.xz -# https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-${SUFFIX_NAME}.tar.xz -if [ ! -f ${myDir}/mysql-${SUFFIX_NAME}.tar.xz ];then - wget --no-check-certificate -O ${myDir}/mysql-${SUFFIX_NAME}.tar.xz https://cdn.mysql.com/Downloads/MySQL-9.1/mysql-${SUFFIX_NAME}.tar.xz -fi - -if [ -d ${myDir} ];then - cd ${myDir} && tar -Jxf ${myDir}/mysql-${SUFFIX_NAME}.tar.xz - cp -rf ${myDir}/mysql-${SUFFIX_NAME}/* $serverPath/mysql-apt -fi - -# 测试时可关闭 -rm -rf $myDir/mysql-${SUFFIX_NAME} -####### -} - -APT_UNINSTALL() -{ -### -rm -rf $myDir/mysql-${SUFFIX_NAME} -# apt remove -y mysql-server -### -} - - -Install_mysql() -{ - echo '正在安装脚本文件...' - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_INSTALL - fi - - if [ "$?" == "0" ];then - mkdir -p $serverPath/mysql-apt - echo '9.1' > $serverPath/mysql-apt/version.pl - echo '安装完成' - else - echo '9.1' > $serverPath/mysql-apt/version.pl - echo "暂时不支持该系统" - fi -} - -Uninstall_mysql() -{ - - isApt=`which apt` - if [ "$isApt" != "" ];then - APT_UNINSTALL - fi - - rm -rf $serverPath/mysql-apt - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-yum/conf/classic.cnf b/plugins/mysql-yum/conf/classic.cnf deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/plugins/mysql-yum/conf/gtid.cnf b/plugins/mysql-yum/conf/gtid.cnf deleted file mode 100644 index 5076776a65..0000000000 --- a/plugins/mysql-yum/conf/gtid.cnf +++ /dev/null @@ -1,4 +0,0 @@ -[mysqld] -# SHOW GLOBAL VARIABLES LIKE '%gtid%' -gtid_mode=ON -enforce_gtid_consistency=ON \ No newline at end of file diff --git a/plugins/mysql-yum/conf/my5.7.cnf b/plugins/mysql-yum/conf/my5.7.cnf deleted file mode 100644 index 72c7b0587b..0000000000 --- a/plugins/mysql-yum/conf/my5.7.cnf +++ /dev/null @@ -1,111 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} -sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES - -default_storage_engine = InnoDB -language={$SERVER_APP_PATH}/bin/usr/share/mysql/english - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=0 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -query_cache_type = 1 -query_cache_size = 64M - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -skip_name_resolve = 1 -skip-ssl -#skip-networking -#skip-external-locking -#loose-skip-innodb -#skip-grant-tables - -log-bin=mysql-bin -binlog_format=mixed -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -expire_logs_days=30 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#sync_binlog=1 - -#binlog-do-db -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log-slave-updates -#replicate-do-db -slave_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -master_info_repository = table -relay_log_info_repository = table - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_log_file_size = 5M -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-yum/conf/my8.0.cnf b/plugins/mysql-yum/conf/my8.0.cnf deleted file mode 100644 index 92d6ac93d3..0000000000 --- a/plugins/mysql-yum/conf/my8.0.cnf +++ /dev/null @@ -1,103 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=mysql_native_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#binlog-do-db -#sync_binlog=1 - -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-yum/conf/my8.2.cnf b/plugins/mysql-yum/conf/my8.2.cnf deleted file mode 100644 index 58cca49b94..0000000000 --- a/plugins/mysql-yum/conf/my8.2.cnf +++ /dev/null @@ -1,105 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} -sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#binlog-do-db -#sync_binlog=1 - -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-yum/conf/my8.3.cnf b/plugins/mysql-yum/conf/my8.3.cnf deleted file mode 100644 index 58cca49b94..0000000000 --- a/plugins/mysql-yum/conf/my8.3.cnf +++ /dev/null @@ -1,105 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf - -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} -sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#binlog-do-db -#sync_binlog=1 - -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-yum/conf/my8.4.cnf b/plugins/mysql-yum/conf/my8.4.cnf deleted file mode 100644 index fe2adacbcc..0000000000 --- a/plugins/mysql-yum/conf/my8.4.cnf +++ /dev/null @@ -1,104 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf -#mysql_native_password=ON -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -#mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#binlog-do-db -#sync_binlog=1 - -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-yum/conf/my9.0.cnf b/plugins/mysql-yum/conf/my9.0.cnf deleted file mode 100644 index fe2adacbcc..0000000000 --- a/plugins/mysql-yum/conf/my9.0.cnf +++ /dev/null @@ -1,104 +0,0 @@ -[client] -user = root -#password = your_password -port = 33206 -socket = {$SERVER_APP_PATH}/mysql.sock -default-character-set = UTF8MB4 - -[mysqld] -!include {$SERVER_APP_PATH}/etc/mode/classic.cnf -#mysql_native_password=ON -authentication_policy=caching_sha2_password -pid-file = {$SERVER_APP_PATH}/data/mysql.pid -user = mysql -port = 33206 -#mysqlx_port = 33260 -socket = {$SERVER_APP_PATH}/mysql.sock -datadir = {$SERVER_APP_PATH}/data -log-error = {$SERVER_APP_PATH}/data/error.log -server-id = {$SERVER_ID} - -default_storage_engine = InnoDB - -key_buffer_size = 8M -table_open_cache = 32 -sort_buffer_size = 256K -net_buffer_length = 4K -read_buffer_size = 128K -read_rnd_buffer_size = 256K -myisam_sort_buffer_size = 4M -thread_cache_size = 4 -lower_case_table_names=1 -tmp_table_size = 8M -character-set-server = UTF8MB4 - -max_connections = 500 -max_connect_errors = 100 -open_files_limit = 2560 -max_allowed_packet = 128M - -#skip-external-locking -#skip-grant-tables -#loose-skip-innodb -#skip-networking -#skip-name-resolve - -log-bin=mysql-bin -slow_query_log=1 -slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log -long_query_time=3 -#log_queries_not_using_indexes=on - -relay-log=mdserver -relay-log-index=mdserver - -#master -#binlog-do-db -#sync_binlog=1 - -binlog-ignore-db = test -binlog-ignore-db = mysql -binlog-ignore-db = information_schema -binlog-ignore-db = performance_schema - -#slave -log_replica_updates -#replicate-do-db -replica_skip_errors=1062,1396 -replicate-ignore-db = information_schema -replicate-ignore-db = performance_schema -replicate-ignore-db = mysql -replicate-ignore-db = test - - -default_storage_engine = InnoDB -innodb_data_home_dir = {$SERVER_APP_PATH}/data -innodb_data_file_path = ibdata1:10M:autoextend -innodb_log_group_home_dir = {$SERVER_APP_PATH}/data -innodb_buffer_pool_size = 16M -innodb_redo_log_capacity=10485760 -innodb_log_buffer_size = 8M -innodb_flush_log_at_trx_commit = 1 -innodb_lock_wait_timeout = 120 -innodb_max_dirty_pages_pct = 90 -innodb_read_io_threads = 1 -innodb_write_io_threads = 1 -innodb_file_per_table=1 -binlog_expire_logs_seconds=2592000 - -secure-file-priv={$SERVER_APP_PATH}/tmp - -[mysqldump] -quick - -[mysql] -no-auto-rehash - -[myisamchk] -key_buffer_size = 20M -sort_buffer_size = 20M -read_buffer = 2M -write_buffer = 2M - -[mysqlhotcopy] -interactive-timeout \ No newline at end of file diff --git a/plugins/mysql-yum/conf/mysql.sql b/plugins/mysql-yum/conf/mysql.sql deleted file mode 100755 index f98ddf79b9..0000000000 --- a/plugins/mysql-yum/conf/mysql.sql +++ /dev/null @@ -1,58 +0,0 @@ -CREATE TABLE IF NOT EXISTS `config` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `mysql_root` TEXT -); - -INSERT INTO `config` (`id`, `mysql_root`) VALUES (1, 'admin'); - -CREATE TABLE IF NOT EXISTS `databases` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `pid` INTEGER, - `name` TEXT, - `username` TEXT, - `password` TEXT, - `accept` TEXT, - `rw` TEXT DEFAULT 'rw', - `ps` TEXT, - `addtime` TEXT -); --- ALTER TABLE `databases` ADD COLUMN `rw` TEXT DEFAULT 'rw'; - -CREATE TABLE IF NOT EXISTS `master_replication_user` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `username` TEXT, - `password` TEXT, - `accept` TEXT, - `ps` TEXT, - `addtime` TEXT -); - --- 从库配置主库的[ssh private key] --- drop table `slave_id_rsa`; -CREATE TABLE IF NOT EXISTS `slave_id_rsa` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `ip` TEXT, - `port` TEXT, - `user` TEXT, - `db_user` TEXT, - `id_rsa` TEXT, - `ps` TEXT, - `addtime` TEXT -); - --- 从库配置主库的[user] --- drop table `slave_user`; -CREATE TABLE IF NOT EXISTS `slave_sync_user` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `ip` TEXT, - `port` TEXT, - `user` TEXT, - `pass` TEXT, - `mode` TEXT, - `cmd` TEXT, - `db` TEXT, - `addtime` TEXT -); -ALTER TABLE `slave_sync_user` ADD COLUMN `db` TEXT DEFAULT ''; - - diff --git a/plugins/mysql-yum/ico.png b/plugins/mysql-yum/ico.png deleted file mode 100644 index ead815fc20cc747780967ef2871b83c000e4f82d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1135 zcmV-#1d#iQP)>{3lQ%rYE>EIo|Bc9O8-^_)1agG}q9>-P216(B zK}1dolB(O#w(T^gZ+;f7TTURgp@*LLi%EvgY=cZDhv*1Q%s|VgV~ETx1Bb!tAi=x$ zUWdVBccSOOP0TAdp?2kNQqbh`6_+AM=z=O#FWZiQgf#GjdIS}L4KI9; zf}sTnN>=9>ibj?}Z*{;EbY?5sx1YxBZ7&Kol9MINSyjpHnF1j5xR->al|lgp3yToqeV zi#1Puj`)fuTy=C78)}wr|E;r9Us(3QJIL;u;2qai|6mNCx)=S2ZoTRgD-Cf~i(61M zx(o`X3N_1iVCx${VeI@Pv@i2P$%IaC9>B`SKIRNTVJVXE z2#%m|zDZ4GHL+7*QfNoPf=^*t~;eZXN43`ND z7cv<&LC*S9H$H{xrQ7Jlg9?E+DPi*uMqb|xC2+^ia|lk(@-ihrD=Xzh`OJFMEZYt$ z$xJyfgDMjpD9034i#I2DjNYWkmE7JWBqSsxeg^A1@>H -
      -
      -
      - -

      服务

      -

      自启动

      -

      配置文件

      -

      存储位置

      -

      端口

      -

      当前状态

      -

      性能优化

      -

      日志

      -

      慢日志

      -

      BINLOG

      -

      管理列表

      -

      主从配置

      -
      -
      -
      -
      -
      - - - - - - \ No newline at end of file diff --git a/plugins/mysql-yum/index.py b/plugins/mysql-yum/index.py deleted file mode 100755 index 4581ebd866..0000000000 --- a/plugins/mysql-yum/index.py +++ /dev/null @@ -1,3680 +0,0 @@ -# coding:utf-8 - -import sys -import io -import os -import time -import subprocess -import re -import json - - -web_dir = os.getcwd() + "/web" -if os.path.exists(web_dir): - sys.path.append(web_dir) - os.chdir(web_dir) - -import core.mw as mw - -# if mw.isAppleSystem(): -# cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\'' -# info = mw.execShell(cmd) -# p = "/usr/local/lib/" + info[0].strip() + "/site-packages" -# sys.path.append(p) - - -app_debug = False -if mw.isAppleSystem(): - app_debug = True - - -def getPluginName(): - return 'mysql-yum' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - - -def getSPluginDir(): - return '/www/server/mdserver-web/plugins/' + getPluginName() - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def getArgs(): - args = sys.argv[2:] - tmp = {} - args_len = len(args) - if args_len == 1: - t = args[0].strip('{').strip('}') - if t.strip() == '': - tmp = [] - else: - t = t.split(':', 1) - tmp[t[0]] = t[1] - tmp[t[0]] = t[1] - elif args_len > 1: - for i in range(len(args)): - t = args[i].split(':', 1) - tmp[t[0]] = t[1] - return tmp - - -def checkArgs(data, ck=[]): - for i in range(len(ck)): - if not ck[i] in data: - return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!')) - return (True, mw.returnJson(True, 'ok')) - - -def getBackupDir(): - bk_path = mw.getBackupDir() + "/database/mysql-yum" - if not os.path.isdir(bk_path): - mw.execShell("mkdir -p {}".format(bk_path)) - return bk_path - - -def getConf(): - path = getServerDir() + '/etc/my.cnf' - return path - - -def getDataDir(): - file = getConf() - content = mw.readFile(file) - rep = r'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getLogBinName(): - file = getConf() - content = mw.readFile(file) - rep = r'log-bin\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getPidFile(): - file = getConf() - content = mw.readFile(file) - rep = r'pid-file\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getDbPort(): - file = getConf() - content = mw.readFile(file) - rep = r'port\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getDbServerId(): - file = getConf() - content = mw.readFile(file) - rep = r'server-id\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getSocketFile(): - file = getConf() - content = mw.readFile(file) - rep = r'socket\s*=\s*(.*)' - tmp = re.search(rep, content) - socket = tmp.groups()[0].strip() - - _socket = socket+'.sock' - if os.path.exists(_socket): - return _socket - return socket - - -def getErrorLogsFile(): - file = getConf() - content = mw.readFile(file) - rep = r'log-error\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getAuthPolicy(): - file = getConf() - content = mw.readFile(file) - rep = r'authentication_policy\s*=\s*(.*)' - tmp = re.search(rep, content) - if tmp: - return tmp.groups()[0].strip() - # caching_sha2_password - return 'mysql_native_password' - -def contentReplace(content): - service_path = mw.getServerDir() - content = content.replace('{$ROOT_PATH}', mw.getFatherDir()) - content = content.replace('{$SERVER_PATH}', service_path) - content = content.replace('{$SERVER_APP_PATH}',service_path + '/' + getPluginName()) - - server_id = int(time.time()) - content = content.replace('{$SERVER_ID}', str(server_id)) - return content - - -def pSqliteDb(dbname='databases'): - file = getServerDir() + '/mysql.db' - name = 'mysql' - - import_sql = mw.readFile(getPluginDir() + '/conf/mysql.sql') - md5_sql = mw.md5(import_sql) - - import_sign = False - save_md5_file = getServerDir() + '/import_sql.md5' - if os.path.exists(save_md5_file): - save_md5_sql = mw.readFile(save_md5_file) - if save_md5_sql != md5_sql: - import_sign = True - mw.writeFile(save_md5_file, md5_sql) - else: - mw.writeFile(save_md5_file, md5_sql) - - if not os.path.exists(file) or import_sql: - conn = mw.M(dbname).dbPos(getServerDir(), name) - csql_list = import_sql.split(';') - for index in range(len(csql_list)): - conn.execute(csql_list[index], ()) - - conn = mw.M(dbname).dbPos(getServerDir(), name) - return conn - - -def pMysqlDb(): - # mysql.connector - db = mw.getMyORM() - # MySQLdb | - # db = mw.getMyORMDb() - - db.__DB_CNF = getConf() - db.setPort(getDbPort()) - db.setSocket(getSocketFile()) - db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')) - return db - - -def initDreplace(version=''): - - conf_dir = getServerDir() + '/etc' - mode_dir = conf_dir + '/mode' - - conf_list = [ - conf_dir, - mode_dir, - ] - for conf in conf_list: - if not os.path.exists(conf): - os.mkdir(conf) - - tmp_dir = getServerDir() + '/tmp' - if not os.path.exists(tmp_dir): - os.mkdir(tmp_dir) - mw.execShell("chown -R mysql:mysql " + tmp_dir) - mw.execShell("chmod 750 " + tmp_dir) - - my_conf = conf_dir + '/my.cnf' - if not os.path.exists(my_conf): - tpl = getPluginDir() + '/conf/my' + version + '.cnf' - content = mw.readFile(tpl) - content = contentReplace(content) - mw.writeFile(my_conf, content) - - classic_conf = mode_dir + '/classic.cnf' - if not os.path.exists(classic_conf): - tpl = getPluginDir() + '/conf/classic.cnf' - content = mw.readFile(tpl) - content = contentReplace(content) - mw.writeFile(classic_conf, content) - - gtid_conf = mode_dir + '/gtid.cnf' - if not os.path.exists(gtid_conf): - tpl = getPluginDir() + '/conf/gtid.cnf' - content = mw.readFile(tpl) - content = contentReplace(content) - mw.writeFile(gtid_conf, content) - - # systemd - systemDir = mw.systemdCfgDir() - systemService = systemDir + '/mysql-yum.service' - systemServiceTpl = getPluginDir() + '/init.d/mysql' + version + '.service.tpl' - # if os.path.exists(systemDir) and not os.path.exists(systemService): - service_path = mw.getServerDir() - content = mw.readFile(systemServiceTpl) - content = content.replace('{$SERVER_PATH}', service_path) - mw.writeFile(systemService, content) - mw.execShell('systemctl daemon-reload') - - if mw.getOs() != 'darwin': - mw.execShell('chown -R mysql mysql ' + getServerDir()) - return 'ok' - -def process_status(): - cmd = "ps -ef|grep mysql-yum | grep mysql |grep -v grep | grep -v python | awk '{print $2}'" - data = mw.execShell(cmd) - if data[0] == '': - return 'stop' - return 'start' - -def status(version=''): - pid = getPidFile() - if not os.path.exists(pid): - return 'stop' - return 'start' - - -def binLog(version=''): - args = getArgs() - conf = getConf() - con = mw.readFile(conf) - - if con.find('#log-bin=mysql-bin') != -1: - if 'status' in args: - return mw.returnJson(False, '0') - con = con.replace('#log-bin=mysql-bin', 'log-bin=mysql-bin') - con = con.replace('#binlog_format=mixed', 'binlog_format=mixed') - mw.execShell('sync') - restart(version) - else: - path = getDataDir() - if 'status' in args: - dsize = 0 - for n in os.listdir(path): - if len(n) < 9: - continue - if n[0:9] == 'mysql-bin': - dsize += os.path.getsize(path + '/' + n) - return mw.returnJson(True, dsize) - con = con.replace('log-bin=mysql-bin', '#log-bin=mysql-bin') - con = con.replace('binlog_format=mixed', '#binlog_format=mixed') - mw.execShell('sync') - restart(version) - mw.execShell('rm -f ' + path + '/mysql-bin.*') - - mw.writeFile(conf, con) - return mw.returnJson(True, '设置成功!') - -def binLogList(): - args = getArgs() - data = checkArgs(args, ['page', 'page_size', 'tojs']) - if not data[0]: - return data[1] - - page = int(args['page']) - page_size = int(args['page_size']) - - data_dir = getDataDir() - log_bin_name = getLogBinName() - - alist = os.listdir(data_dir) - log_bin_l = [] - for x in range(len(alist)): - f = alist[x] - t = {} - if f.startswith(log_bin_name) and not f.endswith('.index'): - abspath = data_dir + '/' + f - t['name'] = f - t['size'] = os.path.getsize(abspath) - t['time'] = mw.getDataFromInt(os.path.getctime(abspath)) - log_bin_l.append(t) - - log_bin_l = sorted(log_bin_l, key=lambda x: x['time'], reverse=True) - - # print(log_bin_l) - # print(data_dir, log_bin_name) - - count = len(log_bin_l) - - page_start = (page - 1) * page_size - page_end = page_start + page_size - if page_end > count: - page_end = count - - data = {} - page_args = {} - page_args['count'] = count - page_args['p'] = page - page_args['row'] = page_size - page_args['tojs'] = args['tojs'] - data['page'] = mw.getPage(page_args) - data['data'] = log_bin_l[page_start:page_end] - - return mw.getJson(data) - -def cleanBinLog(): - db = pMysqlDb() - cleanTime = time.strftime('%Y-%m-%d %H:%i:%s', time.localtime()) - db.execute("PURGE MASTER LOGS BEFORE '" + cleanTime + "';") - return mw.returnJson(True, '清理BINLOG成功!') - - -def setSkipGrantTables(v): - ''' - 设置是否密码验证 - ''' - conf = getConf() - con = mw.readFile(conf) - if v: - if con.find('#skip-grant-tables') != -1: - con = con.replace('#skip-grant-tables', 'skip-grant-tables') - else: - con = con.replace('skip-grant-tables', '#skip-grant-tables') - mw.writeFile(conf, con) - return True - - -def getErrorLog(): - args = getArgs() - filename = getErrorLogsFile() - if not os.path.exists(filename): - return mw.returnJson(False, '指定文件不存在!') - if 'close' in args: - mw.writeFile(filename, '') - return mw.returnJson(False, '日志已清空') - info = mw.getLastLine(filename, 18) - return mw.returnJson(True, 'OK', info) - - -def getShowLogFile(): - file = getConf() - content = mw.readFile(file) - rep = r'slow-query-log-file\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - -def getMdb8Ver(): - return ['8.0','8.1','8.2','8.3','8.4','9.0'] - -def pGetDbUser(): - if mw.isAppleSystem(): - user = mw.execShell( - "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() - return user - return 'mysql' - - -def initMysql57Data(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - user = pGetDbUser() - cmd = serverdir + '/bin/usr/sbin/mysqld --basedir=' + serverdir + '/bin/usr --datadir=' + \ - datadir + ' --initialize-insecure --explicit_defaults_for_timestamp' - data = mw.execShell(cmd) - # print(cmd) - # print(data) - if not mw.isAppleSystem(): - mw.execShell('chown -R mysql:mysql ' + datadir) - mw.execShell('chmod -R 755 ' + datadir) - return False - return True - - -def initMysql8Data(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - user = pGetDbUser() - cmd = serverdir + '/bin/usr/sbin/mysqld --basedir=' + serverdir + '/bin/usr --datadir=' + \ - datadir + ' --initialize-insecure --lower-case-table-names=1' - data = mw.execShell(cmd) - # print(data) - - if not mw.isAppleSystem(): - mw.execShell('chown -R mysql:mysql ' + datadir) - mw.execShell('chmod -R 755 ' + datadir) - return False - return True - -def getLib64Pos(name=''): - cmd = "ls /usr/lib64 | grep "+name+".so | cut -d \\ -f 1 | awk 'END {print}'" - d = mw.execShell(cmd) - return '/usr/lib64/'+d[0] - -def makeLib64SoftLink(name=''): - pos = getLib64Pos(name) - dst_file = '/usr/lib64/'+name+'.so.5' - if os.path.exists(dst_file): - return True - - if os.path.exists(pos): - cmd = 'ln -s '+pos+' '+dst_file - mw.execShell(cmd) - return True - -def yumLibFix(): - makeLib64SoftLink('libncurses') - makeLib64SoftLink('libtinfo') - -def initMysql8Pwd(): - ''' - /usr/bin/mysql --defaults-file=/www/server/mysql-apt/etc/my.cnf -uroot -e"UPDATE mysql.user SET password=PASSWORD('BhIroUczczNVaKvw') WHERE user='root';flush privileges;" - /usr/bin/mysql --defaults-file=/www/server/mysql-apt/etc/my.cnf -uroot -e"alter user 'root'@'localhost' identified by '123456';" - ''' - time.sleep(5) - - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - pwd = mw.getRandomString(16) - auth_policy = getAuthPolicy() - - cmd_my = serverdir + '/bin/usr/bin/mysql' - - cmd_pass = cmd_my + ' --defaults-file=' + myconf + ' -uroot -e' - cmd_pass = cmd_pass + \ - '"alter user \'root\'@\'localhost\' identified by \'' + pwd + '\';' - cmd_pass = cmd_pass + \ - "alter user 'root'@'localhost' IDENTIFIED WITH "+auth_policy+" by '" + pwd + "';" - cmd_pass = cmd_pass + 'flush privileges;"' - # print(cmd_pass) - data = mw.execShell(cmd_pass) - if data[1] != '': - print(data[1]) - exit(-1) - - # 删除空账户 - # drop_empty_user = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + \ - # pwd + ' -e "use mysql;delete from user where USER=\'\'"' - # mw.execShell(drop_empty_user) - - # 删除测试数据库 - drop_test_db = cmd_my + ' --defaults-file=' + myconf + ' -uroot -p' + \ - pwd + ' -e "drop database test";' - mw.execShell(drop_test_db) - - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - - # 删除冗余账户 - # hostname = mw.execShell('hostname')[0].strip() - # if hostname != 'localhost': - # drop_hostname = cmd_my + ' --defaults-file=' + \ - # myconf + ' -uroot -p' + pwd + ' -e "drop user \'\'@\'' + hostname + '\'";' - # mw.execShell(drop_hostname) - - # drop_root_hostname = cmd_my + ' --defaults-file=' + \ - # myconf + ' -uroot -p' + pwd + ' -e "drop user \'root\'@\'' + hostname + '\'";' - # mw.execShell(drop_root_hostname) - return True - - -def my8cmd(version, method): - initDreplace(version) - # mysql 8.0 and 5.7 - - mdb8 = getMdb8Ver() - try: - isInited = True - if mw.inArray(mdb8, version): - isInited = initMysql8Data() - else: - isInited = initMysql57Data() - - if not isInited: - if not mw.isSupportSystemctl(): - cmd_init_start = init_file + ' start' - subprocess.Popen(cmd_init_start, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - - time.sleep(6) - else: - mw.execShell('systemctl start '+getPluginName()) - - for x in range(10): - mydb_status = process_status() - if mydb_status == 'start': - initMysql8Pwd() - break - time.sleep(1) - - if not mw.isSupportSystemctl(): - cmd_init_stop = init_file + ' stop' - subprocess.Popen(cmd_init_stop, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - time.sleep(3) - else: - mw.execShell('systemctl stop ' + getPluginName()) - - if not mw.isSupportSystemctl(): - sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - sub.wait(5) - else: - mw.execShell('systemctl ' + method + ' ' + getPluginName()) - return 'ok' - except Exception as e: - return str(e) - - -def appCMD(version, action): - return my8cmd(version, action) - - -def start(version=''): - return appCMD(version, 'start') - - -def stop(version=''): - return appCMD(version, 'stop') - - -def restart(version=''): - return appCMD(version, 'restart') - - -def reload(version=''): - return appCMD(version, 'reload') - - -def initdStatus(): - if mw.isAppleSystem(): - return "Apple Computer does not support" - - shell_cmd = 'systemctl status ' + \ - getPluginName() + ' | grep loaded | grep "enabled;"' - data = mw.execShell(shell_cmd) - if data[0] == '': - return 'fail' - return 'ok' - - -def initdInstall(): - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mw.execShell('systemctl enable ' + getPluginName()) - return 'ok' - - -def initdUinstall(): - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mw.execShell('systemctl disable ' + getPluginName()) - return 'ok' - - -def getMyDbPos(): - file = getConf() - content = mw.readFile(file) - rep = r'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def setMyDbPos(version=''): - args = getArgs() - data = checkArgs(args, ['datadir']) - if not data[0]: - return data[1] - - s_datadir = getMyDbPos() - t_datadir = args['datadir'] - if t_datadir == s_datadir: - return mw.returnJson(False, '与当前存储目录相同,无法迁移文件!') - - if not os.path.exists(t_datadir): - mw.execShell('mkdir -p ' + t_datadir) - - # mw.execShell('/etc/init.d/mysqld stop') - stop(version) - mw.execShell('cp -rf ' + s_datadir + '/* ' + t_datadir + '/') - mw.execShell('chown -R mysql mysql ' + t_datadir) - mw.execShell('chmod -R 755 ' + t_datadir) - mw.execShell('rm -f ' + t_datadir + '/*.pid') - mw.execShell('rm -f ' + t_datadir + '/*.err') - - path = getServerDir() - myfile = path + '/etc/my.cnf' - mycnf = mw.readFile(myfile) - mw.writeFile(path + '/etc/my_backup.cnf', mycnf) - - mycnf = mycnf.replace(s_datadir, t_datadir) - mw.writeFile(myfile, mycnf) - restart(version) - - cmd = 'ps aux|grep "mysql-yum/bin/usr/sbin/mysqld"| grep -v grep|grep -v python' - result = mw.execShell(cmd) - if len(result[0]) > 10: - mw.writeFile('data/datadir.pl', t_datadir) - return mw.returnJson(True, '存储目录迁移成功!') - else: - mw.execShell('pkill -9 mysqld') - mw.writeFile(myfile, mw.readFile(path + '/etc/my_backup.cnf')) - start(version) - return mw.returnJson(False, '文件迁移失败!') - - -def getMyPort(): - file = getConf() - content = mw.readFile(file) - rep = r'port\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def setMyPort(): - args = getArgs() - data = checkArgs(args, ['port']) - if not data[0]: - return data[1] - - port = args['port'] - file = getConf() - content = mw.readFile(file) - rep = r"port\s*=\s*([0-9]+)\s*\n" - content = re.sub(rep, 'port = ' + port + '\n', content) - mw.writeFile(file, content) - restart() - return mw.returnJson(True, '编辑成功!') - - -def runInfo(version): - - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动', []) - - db = pMysqlDb() - data = db.query('show global status') - isError = isSqlError(data) - if isError != None: - return isError - - gets = ['Max_used_connections', 'Com_commit', 'Com_select', 'Com_rollback', 'Questions', 'Innodb_buffer_pool_reads', 'Innodb_buffer_pool_read_requests', 'Key_reads', 'Key_read_requests', 'Key_writes', - 'Key_write_requests', 'Qcache_hits', 'Qcache_inserts', 'Bytes_received', 'Bytes_sent', 'Aborted_clients', 'Aborted_connects', - 'Created_tmp_disk_tables', 'Created_tmp_tables', 'Innodb_buffer_pool_pages_dirty', 'Opened_files', 'Open_tables', 'Opened_tables', 'Select_full_join', - 'Select_range_check', 'Sort_merge_passes', 'Table_locks_waited', 'Threads_cached', 'Threads_connected', 'Threads_created', 'Threads_running', 'Connections', 'Uptime'] - - result = {} - # print(data) - for d in data: - vname = d["Variable_name"] - for g in gets: - if vname == g: - result[g] = d["Value"] - - # print(result, int(result['Uptime'])) - result['Run'] = int(time.time()) - int(result['Uptime']) - tmp = db.query('show master status') - try: - result['File'] = tmp[0]["File"] - result['Position'] = tmp[0]["Position"] - except: - result['File'] = 'OFF' - result['Position'] = 'OFF' - return mw.getJson(result) - - -def myDbStatus(version): - result = {} - db = pMysqlDb() - data = db.query('show variables') - isError = isSqlError(data) - if isError != None: - return isError - - gets = ['table_open_cache', 'thread_cache_size', 'key_buffer_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', - 'innodb_additional_mem_pool_size', 'innodb_log_buffer_size', 'max_connections', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] - - if version != "8.0": - gets.append('query_cache_size') - - result['mem'] = {} - for d in data: - vname = d['Variable_name'] - for g in gets: - # print(g) - if vname == g: - result['mem'][g] = d["Value"] - return mw.getJson(result) - - -def setDbStatus(version): - gets = ['key_buffer_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', 'innodb_log_buffer_size', 'max_connections', - 'table_open_cache', 'thread_cache_size', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] - - if version != "8.0": - # gets.append('query_cache_size') - gets = ['key_buffer_size', 'query_cache_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', 'innodb_log_buffer_size', 'max_connections', - 'table_open_cache', 'thread_cache_size', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] - - # print(gets) - emptys = ['max_connections', 'thread_cache_size', 'table_open_cache'] - args = getArgs() - conFile = getConf() - content = mw.readFile(conFile) - n = 0 - for g in gets: - s = 'M' - if n > 5: - s = 'K' - if g in emptys: - s = '' - rep = r'\s*' + g + r'\s*=\s*\d+(M|K|k|m|G)?\n' - c = g + ' = ' + args[g] + s + '\n' - if content.find(g) != -1: - content = re.sub(rep, '\n' + c, content, 1) - else: - content = content.replace('[mysqld]\n', '[mysqld]\n' + c) - n += 1 - mw.writeFile(conFile, content) - return mw.returnJson(True, '设置成功!') - - -def isSqlError(mysqlMsg): - # 检测数据库执行错误 - mysqlMsg = str(mysqlMsg) - if "MySQLdb" in mysqlMsg: - return mw.returnJson(False, 'err:' + str(mysqlMsg) + "\n" + 'MySQLdb组件缺失!
      进入SSH命令行输入: pip install mysql-python | pip install mysqlclient==2.0.3') - if "2002," in mysqlMsg: - return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') - if "2003," in mysqlMsg: - return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)") - if "using password:" in mysqlMsg: - return mw.returnJson(False, '数据库密码错误,在管理列表-点击【修复】!') - if "1045," in mysqlMsg: - return mw.returnJson(False, '连接错误!') - if "SQL syntax" in mysqlMsg: - return mw.returnJson(False, 'SQL语法错误!') - if "Connection refused" in mysqlMsg: - return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') - if "1133," in mysqlMsg: - return mw.returnJson(False, '数据库用户不存在!') - if "1007," in mysqlMsg: - return mw.returnJson(False, '数据库已经存在!') - return None - - -def __createUser(dbname, username, password, address): - pdb = pMysqlDb() - - if username == 'root': - dbname = '*' - - pdb.execute( - "CREATE USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, password)) - pdb.execute( - "grant all privileges on %s.* to `%s`@`localhost`" % (dbname, username)) - for a in address.split(','): - pdb.execute( - "CREATE USER `%s`@`%s` IDENTIFIED BY '%s'" % (username, a, password)) - pdb.execute( - "grant all privileges on %s.* to `%s`@`%s`" % (dbname, username, a)) - pdb.execute("flush privileges") - - -def getDbBackupListFunc(dbname=''): - bkDir = getBackupDir() - blist = os.listdir(bkDir) - r = [] - - bname = 'db_' + dbname - blen = len(bname) - for x in blist: - fbstr = x[0:blen] - if fbstr == bname: - r.append(x) - return r - - -def setDbBackup(): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - scDir = getPluginDir() + '/scripts/backup.py' - cmd = 'python3 ' + scDir + ' database ' + args['name'] + ' 3' - os.system(cmd) - return mw.returnJson(True, 'ok') - - -def rootPwd(): - return pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root') - - -def importDbExternal(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - import_dir = mw.getBackupDir() + '/import/' - - file_path = import_dir + file - if not os.path.exists(file_path): - return mw.returnJson(False, '文件突然消失?') - - exts = ['sql', 'gz', 'zip'] - ext = mw.getFileSuffix(file) - if ext not in exts: - return mw.returnJson(False, '导入数据库格式不对!') - - tmp = file.split('/') - tmpFile = tmp[len(tmp) - 1] - tmpFile = tmpFile.replace('.sql.' + ext, '.sql') - tmpFile = tmpFile.replace('.' + ext, '.sql') - tmpFile = tmpFile.replace('tar.', '') - - # print(tmpFile) - import_sql = "" - if file.find("sql.gz") > -1: - cmd = 'cd ' + import_dir + ' && gzip -dc ' + \ - file + " > " + import_dir + tmpFile - info = mw.execShell(cmd) - if info[1] == "": - import_sql = import_dir + tmpFile - - if file.find(".zip") > -1: - cmd = 'cd ' + import_dir + ' && unzip -o ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find("tar.gz") > -1: - cmd = 'cd ' + import_dir + ' && tar -zxvf ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find(".sql") > -1 and file.find(".sql.gz") == -1: - import_sql = import_dir + file - - if import_sql == "": - return mw.returnJson(False, '未找SQL文件') - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - - os.environ["MYSQL_PWD"] = pwd - mysql_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + \ - pwd + ' ' + name + ' < ' + import_sql - - rdata = mw.execShell(mysql_cmd) - if ext != 'sql': - os.remove(import_sql) - - if rdata[1].lower().find('error') > -1: - return mw.returnJson(False, rdata[1]) - - return mw.returnJson(True, 'ok') - -def importDbExternalProgress(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && ' - cmd += 'python3 '+mw.getServerDir()+'/mdserver-web/plugins/mysql-yum/index.py import_db_external_progress_bar {"file":"'+file+'","name":"'+name+'"}' - return mw.returnJson(True, 'ok',cmd) - -def importDbExternalProgressBar(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - import_dir = mw.getFatherDir() + '/backup/import/' - - file_path = import_dir + file - if not os.path.exists(file_path): - return mw.returnJson(False, '文件突然消失?') - - exts = ['sql', 'gz', 'zip'] - ext = mw.getFileSuffix(file) - if ext not in exts: - return mw.returnJson(False, '导入数据库格式不对!') - - tmp = file.split('/') - tmpFile = tmp[len(tmp) - 1] - tmpFile = tmpFile.replace('.sql.' + ext, '.sql') - tmpFile = tmpFile.replace('.' + ext, '.sql') - tmpFile = tmpFile.replace('tar.', '') - - # print(tmpFile) - import_sql = "" - if file.find("sql.gz") > -1: - cmd = 'cd ' + import_dir + ' && gzip -dc ' + \ - file + " > " + import_dir + tmpFile - info = mw.execShell(cmd) - if info[1] == "": - import_sql = import_dir + tmpFile - - if file.find(".zip") > -1: - cmd = 'cd ' + import_dir + ' && unzip -o ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find("tar.gz") > -1: - cmd = 'cd ' + import_dir + ' && tar -zxvf ' + file - mw.execShell(cmd) - import_sql = import_dir + tmpFile - - if file.find(".sql") > -1 and file.find(".sql.gz") == -1: - import_sql = import_dir + file - - if import_sql == "": - return mw.returnJson(False, '未找SQL文件') - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - - my_cnf = getConf() - mysql_cmd = getServerDir() + '/bin/usr/bin/mysql --defaults-file=' + my_cnf + \ - ' -uroot -p"' + pwd + '" -f ' + name - mysql_cmd_progress_bar = "pv -t -p " + import_sql + '|'+ mysql_cmd - print(mysql_cmd_progress_bar) - rdata = os.system(mysql_cmd_progress_bar) - return "" - -def importDbBackup(): - args = getArgs() - data = checkArgs(args, ['file', 'name']) - if not data[0]: - return data[1] - - file = args['file'] - name = args['name'] - - file_path = getBackupDir() + '/' + file - file_path_sql = getBackupDir() + '/' + file.replace('.gz', '') - - if not os.path.exists(file_path_sql): - cmd = 'cd ' + mw.getBackupDir() + '/database && gzip -d ' + file - mw.execShell(cmd) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - mysql_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ - ' ' + name + ' < ' + file_path_sql - - rdata = mw.execShell(mysql_cmd) - if rdata[1].lower().find('error') > -1: - return mw.returnJson(False, rdata[1]) - - return mw.returnJson(True, 'ok') - - -def deleteDbBackup(): - args = getArgs() - data = checkArgs(args, ['filename', 'path']) - if not data[0]: - return data[1] - - path = args['path'] - full_file = "" - bkDir = getBackupDir() - full_file = bkDir + '/' + args['filename'] - if path != "": - full_file = path + "/" + args['filename'] - os.remove(full_file) - return mw.returnJson(True, 'ok') - - -def getDbBackupList(): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - r = getDbBackupListFunc(args['name']) - bkDir = getBackupDir() - rr = [] - for x in range(0, len(r)): - p = bkDir + '/' + r[x] - data = {} - data['name'] = r[x] - - rsize = os.path.getsize(p) - data['size'] = mw.toSize(rsize) - - t = os.path.getctime(p) - t = time.localtime(t) - - data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t) - rr.append(data) - - data['file'] = p - - return mw.returnJson(True, 'ok', rr) - - -def getDbBackupImportList(): - bkImportDir = mw.getBackupDir() + '/import' - if not os.path.exists(bkImportDir): - os.mkdir(bkImportDir) - - blist = os.listdir(bkImportDir) - - rr = [] - for x in range(0, len(blist)): - name = blist[x] - p = bkImportDir + '/' + name - data = {} - data['name'] = name - - rsize = os.path.getsize(p) - data['size'] = mw.toSize(rsize) - - t = os.path.getctime(p) - t = time.localtime(t) - - data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t) - rr.append(data) - - data['file'] = p - - rdata = { - "list": rr, - "upload_dir": bkImportDir, - } - return mw.returnJson(True, 'ok', rdata) - - -def getDbList(): - args = getArgs() - page = 1 - page_size = 10 - search = '' - data = {} - if 'page' in args: - page = int(args['page']) - - if 'page_size' in args: - page_size = int(args['page_size']) - - if 'search' in args: - search = args['search'] - - conn = pSqliteDb('databases') - limit = str((page - 1) * page_size) + ',' + str(page_size) - condition = '' - if not search == '': - condition = "name like '%" + search + "%'" - field = 'id,pid,name,username,password,accept,rw,ps,addtime' - clist = conn.where(condition, ()).field( - field).limit(limit).order('id desc').select() - - for x in range(0, len(clist)): - dbname = clist[x]['name'] - blist = getDbBackupListFunc(dbname) - # print(blist) - clist[x]['is_backup'] = False - if len(blist) > 0: - clist[x]['is_backup'] = True - - count = conn.where(condition, ()).count() - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = 'dbList' - data['page'] = mw.getPage(_page) - data['data'] = clist - - info = {} - info['root_pwd'] = pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root') - data['info'] = info - - return mw.getJson(data) - - -def syncGetDatabases(): - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - data = pdb.query('show databases') - isError = isSqlError(data) - if isError != None: - return isError - users = pdb.query( - "select User,Host from mysql.user where User!='root' AND Host!='localhost' AND Host!=''") - nameArr = ['information_schema', 'performance_schema', 'mysql', 'sys'] - n = 0 - - # print(users) - for value in data: - vdb_name = value["Database"] - b = False - for key in nameArr: - if vdb_name == key: - b = True - break - if b: - continue - if psdb.where("name=?", (vdb_name,)).count() > 0: - continue - host = '127.0.0.1' - for user in users: - if vdb_name == user["User"]: - host = user["Host"] - break - - ps = mw.getMsg('INPUT_PS') - if vdb_name == 'test': - ps = mw.getMsg('DATABASE_TEST') - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - if psdb.add('name,username,password,accept,ps,addtime', (vdb_name, vdb_name, '', host, ps, addTime)): - n += 1 - - msg = mw.getInfo('本次共从服务器获取了{1}个数据库!', (str(n),)) - return mw.returnJson(True, msg) - - -def toDbBase(find): - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - if len(find['password']) < 3: - find['username'] = find['name'] - find['password'] = mw.md5(str(time.time()) + find['name'])[0:10] - psdb.where("id=?", (find['id'],)).save( - 'password,username', (find['password'], find['username'])) - - result = pdb.execute("create database `" + find['name'] + "`") - if "using password:" in str(result): - return -1 - if "Connection refused" in str(result): - return -1 - - password = find['password'] - __createUser(find['name'], find['username'], password, find['accept']) - return 1 - - -def syncToDatabases(): - args = getArgs() - data = checkArgs(args, ['type', 'ids']) - if not data[0]: - return data[1] - - pdb = pMysqlDb() - result = pdb.execute("show databases") - isError = isSqlError(result) - if isError: - return isError - - stype = int(args['type']) - psdb = pSqliteDb('databases') - n = 0 - - if stype == 0: - data = psdb.field('id,name,username,password,accept').select() - for value in data: - result = toDbBase(value) - if result == 1: - n += 1 - else: - data = json.loads(args['ids']) - for value in data: - find = psdb.where("id=?", (value,)).field( - 'id,name,username,password,accept').find() - # print find - result = toDbBase(find) - if result == 1: - n += 1 - msg = mw.getInfo('本次共同步了{1}个数据库!', (str(n),)) - return mw.returnJson(True, msg) - - -def setRootPwd(version=''): - args = getArgs() - data = checkArgs(args, ['password']) - if not data[0]: - return data[1] - - #强制修改 - force = 0 - if 'force' in args and args['force'] == '1': - force = 1 - - password = args['password'] - try: - pdb = pMysqlDb() - result = pdb.query("show databases") - isError = isSqlError(result) - if isError != None: - if force == 1: - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (password,)) - return mw.returnJson(True, '【强制修改】数据库root密码修改成功(不意为成功连接数据)!') - return isError - - if version.find('5.7') > -1 or version.find('8.0') > -1: - pdb.execute( - "UPDATE mysql.user SET authentication_string='' WHERE user='root'") - pdb.execute( - "ALTER USER 'root'@'localhost' IDENTIFIED BY '%s'" % password) - pdb.execute( - "ALTER USER 'root'@'127.0.0.1' IDENTIFIED BY '%s'" % password) - else: - result = pdb.execute( - "update mysql.user set Password=password('" + password + "') where User='root'") - pdb.execute("flush privileges") - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (password,)) - - msg = '' - if force == 1: - msg = ',无须强制!' - return mw.returnJson(True, '数据库root密码修改成功!'+msg) - except Exception as ex: - return mw.returnJson(False, '修改错误:' + str(ex)) - - -def setUserPwd(version=''): - args = getArgs() - data = checkArgs(args, ['password', 'name']) - if not data[0]: - return data[1] - - newpassword = args['password'] - username = args['name'] - uid = args['id'] - try: - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - name = psdb.where('id=?', (uid,)).getField('name') - - if version.find('5.7') > -1 or version.find('8.0') > -1: - accept = pdb.query( - "select Host from mysql.user where User='" + name + "' AND Host!='localhost'") - t1 = pdb.execute( - "update mysql.user set authentication_string='' where User='" + username + "'") - # print(t1) - result = pdb.execute( - "ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, newpassword)) - # print(result) - for my_host in accept: - t2 = pdb.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ( - username, my_host["Host"], newpassword)) - # print(t2) - else: - result = pdb.execute("update mysql.user set Password=password('" + - newpassword + "') where User='" + username + "'") - - pdb.execute("flush privileges") - psdb.where("id=?", (uid,)).setField('password', newpassword) - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]密码成功!', (name,))) - except Exception as ex: - return mw.returnJson(False, mw.getInfo('修改数据库[{1}]密码失败[{2}]!', (name, str(ex),))) - - -def setDbPs(): - args = getArgs() - data = checkArgs(args, ['id', 'name', 'ps']) - if not data[0]: - return data[1] - - ps = args['ps'] - sid = args['id'] - name = args['name'] - try: - psdb = pSqliteDb('databases') - psdb.where("id=?", (sid,)).setField('ps', ps) - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]备注成功!', (name,))) - except Exception as e: - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]备注失败!', (name,))) - - -def addDb(): - args = getArgs() - data = checkArgs(args, - ['password', 'name', 'codeing', 'db_user', 'dataAccess', 'ps']) - if not data[0]: - return data[1] - - if not 'address' in args: - address = '' - else: - address = args['address'].strip() - - dbname = args['name'].strip() - dbuser = args['db_user'].strip() - codeing = args['codeing'].strip() - password = args['password'].strip() - dataAccess = args['dataAccess'].strip() - ps = args['ps'].strip() - - reg = r"^[\w-]+$" - if not re.match(reg, args['name']): - return mw.returnJson(False, '数据库名称不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'performance_schema','information_schema'] - if dbuser in checks or len(dbuser) < 1: - return mw.returnJson(False, '数据库用户名不合法!') - if dbname in checks or len(dbname) < 1: - return mw.returnJson(False, '数据库名称不合法!') - - if len(password) < 1: - password = mw.md5(time.time())[0:8] - - wheres = { - 'utf8': 'utf8_general_ci', - 'utf8mb4': 'utf8mb4_general_ci', - 'gbk': 'gbk_chinese_ci', - 'big5': 'big5_chinese_ci' - } - codeStr = wheres[codeing] - - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - - if psdb.where("name=? or username=?", (dbname, dbuser)).count(): - return mw.returnJson(False, '数据库已存在!') - - result = pdb.execute("create database `" + dbname + - "` DEFAULT CHARACTER SET " + codeing + " COLLATE " + codeStr) - # print result - isError = isSqlError(result) - if isError != None: - return isError - - pdb.execute("drop user '" + dbuser + "'@'localhost'") - for a in address.split(','): - pdb.execute("drop user '" + dbuser + "'@'" + a + "'") - - __createUser(dbname, dbuser, password, address) - - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - psdb.add('pid,name,username,password,accept,ps,addtime', - (0, dbname, dbuser, password, address, ps, addTime)) - return mw.returnJson(True, '添加成功!') - - -def delDb(): - args = getArgs() - data = checkArgs(args, ['id', 'name']) - if not data[0]: - return data[1] - try: - sid = args['id'] - name = args['name'] - psdb = pSqliteDb('databases') - pdb = pMysqlDb() - find = psdb.where("id=?", (sid,)).field( - 'id,pid,name,username,password,accept,ps,addtime').find() - accept = find['accept'] - username = find['username'] - - # 删除MYSQL - result = pdb.execute("drop database `" + name + "`") - - users = pdb.query("select Host from mysql.user where User='" + - username + "' AND Host!='localhost'") - pdb.execute("drop user '" + username + "'@'localhost'") - for us in users: - pdb.execute("drop user '" + username + "'@'" + us["Host"] + "'") - pdb.execute("flush privileges") - - # 删除SQLITE - psdb.where("id=?", (sid,)).delete() - return mw.returnJson(True, '删除成功!') - except Exception as ex: - return mw.returnJson(False, '删除失败!' + str(ex)) - - -def getDbAccess(): - args = getArgs() - data = checkArgs(args, ['username']) - if not data[0]: - return data[1] - username = args['username'] - pdb = pMysqlDb() - - users = pdb.query("select Host from mysql.user where User='" + - username + "' AND Host!='localhost'") - - isError = isSqlError(users) - if isError != None: - return isError - - if len(users) < 1: - return mw.returnJson(True, "127.0.0.1") - accs = [] - for c in users: - accs.append(c["Host"]) - userStr = ','.join(accs) - return mw.returnJson(True, userStr) - - -def setDbAccess(): - args = getArgs() - data = checkArgs(args, ['username', 'access']) - if not data[0]: - return data[1] - name = args['username'] - access = args['access'] - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - - dbname = psdb.where('username=?', (name,)).getField('name') - - if name == 'root': - password = pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root') - else: - password = psdb.where("username=?", (name,)).getField('password') - - users = pdb.query("select Host from mysql.user where User='" + - name + "' AND Host!='localhost'") - - for us in users: - pdb.execute("drop user '" + name + "'@'" + us["Host"] + "'") - - __createUser(dbname, name, password, access) - - psdb.where('username=?', (name,)).save('accept,rw', (access, 'rw',)) - return mw.returnJson(True, '设置成功!') - -def openSkipGrantTables(): - mycnf = getConf() - content = mw.readFile(mycnf) - content = content.replace('#skip-grant-tables','skip-grant-tables') - mw.writeFile(mycnf, content) - return True - -def closeSkipGrantTables(): - mycnf = getConf() - content = mw.readFile(mycnf) - content = content.replace('skip-grant-tables','#skip-grant-tables') - mw.writeFile(mycnf, content) - return True - - -def resetDbRootPwd(version): - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - pwd = mw.getRandomString(16) - - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - - mdb8 = getMdb8Ver() - if not mw.inArray(mdb8, version): - cmd_pass = serverdir + '/bin/usr/bin/mysql --defaults-file=' + myconf + ' -uroot -e' - cmd_pass = cmd_pass + '"UPDATE mysql.user SET password=PASSWORD(\'' + pwd + "') WHERE user='root';" - cmd_pass = cmd_pass + 'flush privileges;"' - data = mw.execShell(cmd_pass) - # print(data) - else: - auth_policy = getAuthPolicy() - - reset_pwd = 'flush privileges;' - reset_pwd = reset_pwd + "UPDATE mysql.user SET authentication_string='' WHERE user='root';" - reset_pwd = reset_pwd + "flush privileges;" - reset_pwd = reset_pwd + "alter user 'root'@'localhost' IDENTIFIED by '" + pwd + "';" - reset_pwd = reset_pwd + "alter user 'root'@'localhost' IDENTIFIED WITH "+auth_policy+" by '" + pwd + "';" - reset_pwd = reset_pwd + "flush privileges;" - - tmp_file = "/tmp/mysql_init_tmp.log" - mw.writeFile(tmp_file, reset_pwd) - cmd_pass = serverdir + '/bin/usr/bin/mysql --defaults-file=' + myconf + ' -uroot -proot < ' + tmp_file - - data = mw.execShell(cmd_pass) - # print(data) - os.remove(tmp_file) - return True - -def fixDbAccess2(version): - try: - pdb = pMysqlDb() - data = pdb.query('show databases') - isError = isSqlError(data) - if isError != None: - appCMD(version, 'stop') - mw.execShell("rm -rf " + getServerDir() + "/data") - appCMD(version, 'start') - return mw.returnJson(True, '修复成功!') - return mw.returnJson(True, '正常无需修复!') - except Exception as e: - return mw.returnJson(False, '修复失败请重试!') - -def fixDbAccess(version): - - pdb = pMysqlDb() - mdb_ddir = getDataDir() - if not os.path.exists(mdb_ddir): - return mw.returnJson(False, '数据目录不存在,尝试重启重建!') - - try: - data = pdb.query('show databases') - isError = isSqlError(data) - if isError != None: - - # 重置密码 - appCMD(version, 'stop') - openSkipGrantTables() - appCMD(version, 'start') - time.sleep(3) - resetDbRootPwd(version) - - appCMD(version, 'stop') - closeSkipGrantTables() - appCMD(version, 'start') - - return mw.returnJson(True, '修复成功!') - return mw.returnJson(True, '正常无需修复!') - except Exception as e: - return mw.returnJson(False, '修复失败请重试!') - - -def setDbRw(version=''): - args = getArgs() - data = checkArgs(args, ['username', 'id', 'rw']) - if not data[0]: - return data[1] - - username = args['username'] - uid = args['id'] - rw = args['rw'] - - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - dbname = psdb.where("id=?", (uid,)).getField('name') - users = pdb.query( - "select Host from mysql.user where User='" + username + "'") - - # show grants for demo@"127.0.0.1"; - for x in users: - # REVOKE ALL PRIVILEGES ON `imail`.* FROM 'imail'@'127.0.0.1'; - - sql = "REVOKE ALL PRIVILEGES ON `" + dbname + \ - "`.* FROM '" + username + "'@'" + x["Host"] + "';" - r = pdb.query(sql) - # print(sql, r) - - if rw == 'rw': - sql = "GRANT SELECT, INSERT, UPDATE, DELETE ON " + dbname + ".* TO " + \ - username + "@'" + x["Host"] + "'" - elif rw == 'r': - sql = "GRANT SELECT ON " + dbname + ".* TO " + \ - username + "@'" + x["Host"] + "'" - else: - sql = "GRANT all privileges ON " + dbname + ".* TO " + \ - username + "@'" + x["Host"] + "'" - pdb.execute(sql) - pdb.execute("flush privileges") - r = psdb.where("id=?", (uid,)).setField('rw', rw) - # print(r) - return mw.returnJson(True, '切换成功!') - - -def getDbInfo(): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - db_name = args['name'] - pdb = pMysqlDb() - # print 'show tables from `%s`' % db_name - tables = pdb.query('show tables from `%s`' % db_name) - - ret = {} - sql = "select sum(DATA_LENGTH)+sum(INDEX_LENGTH) as sum_size from information_schema.tables where table_schema='%s'" % db_name - data_sum = pdb.query(sql) - - data = 0 - if data_sum[0]['sum_size'] != None: - data = data_sum[0]['sum_size'] - - ret['data_size'] = mw.toSize(data) - ret['database'] = db_name - - ret3 = [] - table_key = "Tables_in_" + db_name - for i in tables: - tb_sql = "show table status from `%s` where name = '%s'" % (db_name, i[ - table_key]) - table = pdb.query(tb_sql) - - tmp = {} - tmp['type'] = table[0]["Engine"] - tmp['rows_count'] = table[0]["Rows"] - tmp['collation'] = table[0]["Collation"] - - data_size = 0 - if table[0]['Avg_row_length'] != None: - data_size = table[0]['Avg_row_length'] - - if table[0]['Data_length'] != None: - data_size = table[0]['Data_length'] - - tmp['data_byte'] = data_size - tmp['data_size'] = mw.toSize(data_size) - tmp['table_name'] = table[0]["Name"] - ret3.append(tmp) - - ret['tables'] = (ret3) - - return mw.getJson(ret) - - -def repairTable(): - args = getArgs() - data = checkArgs(args, ['db_name', 'tables']) - if not data[0]: - return data[1] - - db_name = args['db_name'] - tables = json.loads(args['tables']) - pdb = pMysqlDb() - mtable = pdb.query('show tables from `%s`' % db_name) - - ret = [] - key = "Tables_in_" + db_name - for i in mtable: - for tn in tables: - if tn == i[key]: - ret.append(tn) - - if len(ret) > 0: - for i in ret: - pdb.execute('REPAIR TABLE `%s`.`%s`' % (db_name, i)) - return mw.returnJson(True, "修复完成!") - return mw.returnJson(False, "修复失败!") - - -def optTable(): - args = getArgs() - data = checkArgs(args, ['db_name', 'tables']) - if not data[0]: - return data[1] - - db_name = args['db_name'] - tables = json.loads(args['tables']) - pdb = pMysqlDb() - mtable = pdb.query('show tables from `%s`' % db_name) - ret = [] - key = "Tables_in_" + db_name - for i in mtable: - for tn in tables: - if tn == i[key]: - ret.append(tn) - - if len(ret) > 0: - for i in ret: - pdb.execute('OPTIMIZE TABLE `%s`.`%s`' % (db_name, i)) - return mw.returnJson(True, "优化成功!") - return mw.returnJson(False, "优化失败或者已经优化过了!") - - -def alterTable(): - args = getArgs() - data = checkArgs(args, ['db_name', 'tables']) - if not data[0]: - return data[1] - - db_name = args['db_name'] - tables = json.loads(args['tables']) - table_type = args['table_type'] - pdb = pMysqlDb() - mtable = pdb.query('show tables from `%s`' % db_name) - - ret = [] - key = "Tables_in_" + db_name - for i in mtable: - for tn in tables: - if tn == i[key]: - ret.append(tn) - - if len(ret) > 0: - for i in ret: - pdb.execute('alter table `%s`.`%s` ENGINE=`%s`' % - (db_name, i, table_type)) - return mw.returnJson(True, "更改成功!") - return mw.returnJson(False, "更改失败!") - - -def getTotalStatistics(): - st = status() - data = {} - - isInstall = os.path.exists(getServerDir() + '/version.pl') - - if st == 'start' and isInstall: - data['status'] = True - data['count'] = pSqliteDb('databases').count() - data['ver'] = mw.readFile(getServerDir() + '/version.pl').strip() - return mw.returnJson(True, 'ok', data) - else: - data['status'] = False - data['count'] = 0 - return mw.returnJson(False, 'fail', data) - - -def recognizeDbMode(): - conf = getConf() - con = mw.readFile(conf) - rep = r"!include %s/(.*)?\.cnf" % (getServerDir() + "/etc/mode",) - mode = 'none' - try: - data = re.findall(rep, con, re.M) - mode = data[0] - except Exception as e: - pass - return mode - - -def getDbrunMode(version=''): - mode = recognizeDbMode() - return mw.returnJson(True, "ok", {'mode': mode}) - - -def setDbrunMode(version=''): - if version == '5.5': - return mw.returnJson(False, "不支持切换") - - args = getArgs() - data = checkArgs(args, ['mode', 'reload']) - if not data[0]: - return data[1] - - mode = args['mode'] - dbreload = args['reload'] - - if not mode in ['classic', 'gtid']: - return mw.returnJson(False, "mode的值无效:" + mode) - - origin_mode = recognizeDbMode() - path = getConf() - con = mw.readFile(path) - rep = r"!include %s/%s\.cnf" % (getServerDir() + "/etc/mode", origin_mode) - rep_after = "!include %s/%s.cnf" % (getServerDir() + "/etc/mode", mode) - con = re.sub(rep, rep_after, con) - mw.writeFile(path, con) - - if version == '5.6': - dbreload = 'yes' - else: - db = pMysqlDb() - # The value of @@GLOBAL.GTID_MODE can only be changed one step at a - # time: OFF <-> OFF_PERMISSIVE <-> ON_PERMISSIVE <-> ON. Also note that - # this value must be stepped up or down simultaneously on all servers. - # See the Manual for instructions. - if mode == 'classic': - db.query('set global enforce_gtid_consistency=off') - db.query('set global gtid_mode=on') - db.query('set global gtid_mode=on_permissive') - db.query('set global gtid_mode=off_permissive') - db.query('set global gtid_mode=off') - elif mode == 'gtid': - db.query('set global enforce_gtid_consistency=on') - db.query('set global gtid_mode=off') - db.query('set global gtid_mode=off_permissive') - db.query('set global gtid_mode=on_permissive') - db.query('set global gtid_mode=on') - - if dbreload == "yes": - restart(version) - - return mw.returnJson(True, "切换成功!") - - -def findBinlogDoDb(): - conf = getConf() - con = mw.readFile(conf) - rep = r"binlog-do-db\s*?=\s*?(.*)" - dodb = re.findall(rep, con, re.M) - return dodb - - -def findBinlogSlaveDoDb(): - conf = getConf() - con = mw.readFile(conf) - rep = r"replicate-do-db\s*?=\s*?(.*)" - dodb = re.findall(rep, con, re.M) - return dodb - - -def setDbMasterAccess(): - args = getArgs() - data = checkArgs(args, ['username', 'access']) - if not data[0]: - return data[1] - username = args['username'] - access = args['access'] - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - password = psdb.where("username=?", (username,)).getField('password') - users = pdb.query("select Host from mysql.user where User='" + - username + "' AND Host!='localhost'") - for us in users: - pdb.execute("drop user '" + username + "'@'" + us["Host"] + "'") - - dbname = '*' - for a in access.split(','): - pdb.execute( - "CREATE USER `%s`@`%s` IDENTIFIED BY '%s'" % (username, a, password)) - pdb.execute( - "grant all privileges on %s.* to `%s`@`%s`" % (dbname, username, a)) - - pdb.execute("flush privileges") - psdb.where('username=?', (username,)).save('accept', (access,)) - return mw.returnJson(True, '设置成功!') - - -def resetMaster(version=''): - pdb = pMysqlDb() - r = pdb.execute('reset master') - isError = isSqlError(r) - if isError != None: - return isError - return mw.returnJson(True, '重置成功!') - - -def getMasterDbList(version=''): - try: - args = getArgs() - page = 1 - page_size = 10 - search = '' - data = {} - if 'page' in args: - page = int(args['page']) - - if 'page_size' in args: - page_size = int(args['page_size']) - - if 'search' in args: - search = args['search'] - - conn = pSqliteDb('databases') - limit = str((page - 1) * page_size) + ',' + str(page_size) - condition = '' - dodb = findBinlogDoDb() - data['dodb'] = dodb - - slave_dodb = findBinlogSlaveDoDb() - - if not search == '': - condition = "name like '%" + search + "%'" - field = 'id,pid,name,username,password,accept,ps,addtime' - clist = conn.where(condition, ()).field( - field).limit(limit).order('id desc').select() - count = conn.where(condition, ()).count() - - for x in range(0, len(clist)): - if clist[x]['name'] in dodb: - clist[x]['master'] = 1 - else: - clist[x]['master'] = 0 - - if clist[x]['name'] in slave_dodb: - clist[x]['slave'] = 1 - else: - clist[x]['slave'] = 0 - - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = 'dbList' - data['page'] = mw.getPage(_page) - data['data'] = clist - return mw.getJson(data) - except Exception as e: - return mw.returnJson(False, "数据库密码错误,在管理列表-点击【修复】!") - - -def setDbMaster(version): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - conf = getConf() - con = mw.readFile(conf) - rep = r"(binlog-do-db\s*?=\s*?(.*))" - dodb = re.findall(rep, con, re.M) - - isHas = False - for x in range(0, len(dodb)): - - if dodb[x][1] == args['name']: - isHas = True - - con = con.replace(dodb[x][0] + "\n", '') - mw.writeFile(conf, con) - - if not isHas: - prefix = '#binlog-do-db' - con = con.replace( - prefix, prefix + "\nbinlog-do-db=" + args['name']) - mw.writeFile(conf, con) - - restart(version) - time.sleep(4) - return mw.returnJson(True, '设置成功', [args, dodb]) - - -def setDbSlave(version): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - conf = getConf() - con = mw.readFile(conf) - rep = r"(replicate-do-db\s*?=\s*?(.*))" - dodb = re.findall(rep, con, re.M) - - isHas = False - for x in range(0, len(dodb)): - if dodb[x][1] == args['name']: - isHas = True - - con = con.replace(dodb[x][0] + "\n", '') - mw.writeFile(conf, con) - - if not isHas: - prefix = '#replicate-do-db' - con = con.replace( - prefix, prefix + "\nreplicate-do-db=" + args['name']) - mw.writeFile(conf, con) - - restart(version) - time.sleep(4) - return mw.returnJson(True, '设置成功', [args, dodb]) - - -def getMasterStatus(version=''): - - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动,或正在启动中...!', []) - - query_status_cmd = 'show slave status' - mdb8 = getMdb8Ver() - is_mdb8 = False - if mw.inArray(mdb8, version): - is_mdb8 = True - query_status_cmd = 'show replica status' - - try: - - conf = getConf() - content = mw.readFile(conf) - master_status = False - if content.find('#log-bin') == -1 and content.find('log-bin') > 1: - dodb = findBinlogDoDb() - if len(dodb) > 0: - master_status = True - - data = {} - data['mode'] = recognizeDbMode() - data['status'] = master_status - - db = pMysqlDb() - dlist = db.query(query_status_cmd) - - # print(dlist[0]) - if is_mdb8: - if len(dlist) > 0 and (dlist[0]["Replica_IO_Running"] == 'Yes' or dlist[0]["Replica_SQL_Running"] == 'Yes'): - data['slave_status'] = True - else: - if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'): - data['slave_status'] = True - - return mw.returnJson(master_status, '设置成功', data) - except Exception as e: - mw.getTracebackInfo() - return mw.returnJson(False, "数据库密码错误,在管理列表-点击【修复】,"+str(e), 'pwd') - - -def setMasterStatus(version=''): - - conf = getConf() - con = mw.readFile(conf) - - if con.find('#log-bin') != -1: - return mw.returnJson(False, '必须开启二进制日志') - - sign = 'mdserver_ms_open' - - dodb = findBinlogDoDb() - if not sign in dodb: - prefix = '#binlog-do-db' - con = con.replace(prefix, prefix + "\nbinlog-do-db=" + sign) - mw.writeFile(conf, con) - else: - con = con.replace("binlog-do-db=" + sign + "\n", '') - rep = r"(binlog-do-db\s*?=\s*?(.*))" - dodb = re.findall(rep, con, re.M) - for x in range(0, len(dodb)): - con = con.replace(dodb[x][0] + "\n", '') - mw.writeFile(conf, con) - - restart(version) - return mw.returnJson(True, '设置成功') - - -def getMasterRepSlaveList(version=''): - args = getArgs() - page = 1 - page_size = 10 - search = '' - data = {} - if 'page' in args: - page = int(args['page']) - - if 'page_size' in args: - page_size = int(args['page_size']) - - if 'search' in args: - search = args['search'] - - conn = pSqliteDb('master_replication_user') - limit = str((page - 1) * page_size) + ',' + str(page_size) - condition = '' - - if not search == '': - condition = "name like '%" + search + "%'" - field = 'id,username,password,accept,ps,addtime' - clist = conn.where(condition, ()).field( - field).limit(limit).order('id desc').select() - count = conn.where(condition, ()).count() - - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = 'getMasterRepSlaveList' - data['page'] = mw.getPage(_page) - data['data'] = clist - - return mw.getJson(data) - - -def addMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username', 'password']) - if not data[0]: - return data[1] - - address = '' - if 'address' in args: - address = args['address'].strip() - - username = args['username'].strip() - password = args['password'].strip() - - reg = r"^[\w-]+$" - if not re.match(reg, username): - return mw.returnJson(False, '用户名不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'performance_schema','information_schema'] - if username in checks or len(username) < 1: - return mw.returnJson(False, '用户名不合法!') - if password in checks or len(password) < 1: - return mw.returnJson(False, '密码不合法!') - - if len(password) < 1: - password = mw.md5(time.time())[0:8] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - - if psdb.where("username=?", (username)).count() > 0: - return mw.returnJson(False, '用户已存在!') - - mdb8 = ['8.0','8.1','8.2','8.3','8.4'] - if mw.inArray(mdb8,version): - sql = "CREATE USER '" + username + \ - "' IDENTIFIED WITH mysql_native_password BY '" + password + "';" - pdb.execute(sql) - sql = "grant replication slave on *.* to '" + username + "'@'%';" - result = pdb.execute(sql) - isError = isSqlError(result) - if isError != None: - return isError - - else: - sql = "GRANT REPLICATION SLAVE ON *.* TO '" + username + \ - "'@'%' identified by '" + password + "';" - result = pdb.execute(sql) - isError = isSqlError(result) - if isError != None: - return isError - - sql_select = "grant select,reload,REPLICATION CLIENT,PROCESS on *.* to " + username + "@'%';" - pdb.execute(sql_select) - pdb.execute('FLUSH PRIVILEGES;') - - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - psdb.add('username,password,accept,ps,addtime',(username, password, '%', '', addTime)) - return mw.returnJson(True, '添加成功!') - - -def getMasterRepSlaveUserCmd(version): - - args = getArgs() - data = checkArgs(args, ['username', 'db']) - if not data[0]: - return data[1] - - psdb = pSqliteDb('master_replication_user') - f = 'username,password' - username = args['username'] - if username == '': - count = psdb.count() - if count == 0: - return mw.returnJson(False, '请添加同步账户!') - - clist = psdb.field(f).limit('1').order('id desc').select() - else: - clist = psdb.field(f).where("username=?", (username,)).limit( - '1').order('id desc').select() - - ip = mw.getLocalIp() - port = getMyPort() - db = pMysqlDb() - - mstatus = db.query('show master status') - if len(mstatus) == 0: - return mw.returnJson(False, '未开启!') - - mode = recognizeDbMode() - - sid = getDbServerId() - channel_name = "" - if sid != '': - channel_name = " for channel 'r{}'".format(sid) - - mdb8 = getMdb8Ver() - sql = '' - if not mw.inArray(mdb8,version): - base_sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \ - clist[0]['username'] + "', MASTER_PASSWORD='" + clist[0]['password'] + "'" - - sql += base_sql; - sql += "

      "; - # sql += base_sql + ", MASTER_AUTO_POSITION=1" + channel_name - sql += base_sql + channel_name - sql += "

      "; - - sql += base_sql + ", MASTER_LOG_FILE='" + mstatus[0]["File"] + "',MASTER_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name - else: - base_sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \ - clist[0]['username'] + "', SOURCE_PASSWORD='" + clist[0]['password']+"'" - sql += base_sql; - sql += "

      "; - # sql += base_sql + ", MASTER_AUTO_POSITION=1" + channel_name - sql += base_sql + channel_name - sql += "

      "; - sql += base_sql + ", SOURCE_LOG_FILE='" + mstatus[0]["File"] + "',SOURCE_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name - - - data = {} - data['cmd'] = sql - data["info"] = clist[0] - data['mode'] = mode - - return mw.returnJson(True, 'ok!', data) - - -def delMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username']) - if not data[0]: - return data[1] - - name = args['username'] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - pdb.execute("drop user '" + name + "'@'%'") - pdb.execute("drop user '" + name + "'@'localhost'") - - users = pdb.query("select Host from mysql.user where User='" + - name + "' AND Host!='localhost'") - for us in users: - pdb.execute("drop user '" + name + "'@'" + us["Host"] + "'") - - psdb.where("username=?", (args['username'],)).delete() - - return mw.returnJson(True, '删除成功!') - - -def updateMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username', 'password']) - if not data[0]: - return data[1] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - pdb.execute("drop user '" + args['username'] + "'@'%'") - - pdb.execute("GRANT REPLICATION SLAVE ON *.* TO '" + - args['username'] + "'@'%' identified by '" + args['password'] + "'") - - psdb.where("username=?", (args['username'],)).save( - 'password', args['password']) - - return mw.returnJson(True, '更新成功!') - - -def getSlaveSSHList(version=''): - args = getArgs() - data = checkArgs(args, ['page', 'page_size']) - if not data[0]: - return data[1] - - page = int(args['page']) - page_size = int(args['page_size']) - - conn = pSqliteDb('slave_id_rsa') - limit = str((page - 1) * page_size) + ',' + str(page_size) - - field = 'id,ip,port,db_user,id_rsa,ps,addtime' - clist = conn.field(field).limit(limit).order('id desc').select() - count = conn.count() - - data = {} - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = args['tojs'] - data['page'] = mw.getPage(_page) - data['data'] = clist - - return mw.getJson(data) - - -def getSlaveSyncUserByIp(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_sync_user') - data = conn.field('ip,port,user,pass,mode,cmd').where( - "ip=?", (ip,)).select() - return mw.returnJson(True, 'ok', data) - - -def addSlaveSyncUser(version=''): - import base64 - - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - if ip == "": - return mw.returnJson(True, 'ok') - - data = checkArgs(args, ['port', 'user', 'pass', 'mode']) - if not data[0]: - return data[1] - - cmd = args['cmd'] - port = args['port'] - user = args['user'] - apass = args['pass'] - mode = args['mode'] - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - - conn = pSqliteDb('slave_sync_user') - data = conn.field('ip').where("ip=?", (ip,)).select() - if len(data) > 0: - res = conn.where("ip=?", (ip,)).save( - 'port,user,pass,mode,cmd', (port, user, apass, mode, cmd)) - else: - conn.add('ip,port,user,cmd,user,pass,mode,addtime', - (ip, port, user, cmd, user, apass, mode, addTime)) - - return mw.returnJson(True, '设置成功!') - - -def delSlaveSyncUser(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_sync_user') - conn.where("ip=?", (ip,)).delete() - return mw.returnJson(True, '删除成功!') - - -def getSlaveSyncUserList(version=''): - args = getArgs() - data = checkArgs(args, ['page', 'page_size']) - if not data[0]: - return data[1] - - page = int(args['page']) - page_size = int(args['page_size']) - - conn = pSqliteDb('slave_sync_user') - limit = str((page - 1) * page_size) + ',' + str(page_size) - - field = 'id,ip,port,user,pass,cmd,addtime' - clist = conn.field(field).limit(limit).order('id desc').select() - count = conn.count() - - data = {} - _page = {} - _page['count'] = count - _page['p'] = page - _page['row'] = page_size - _page['tojs'] = args['tojs'] - data['page'] = mw.getPage(_page) - data['data'] = clist - - return mw.getJson(data) - - -def getSyncModeFile(): - return getServerDir() + "/sync.mode" - - -def getSlaveSyncMode(version): - sync_mode = getSyncModeFile() - if os.path.exists(sync_mode): - mode = mw.readFile(sync_mode).strip() - return mw.returnJson(True, 'ok', mode) - return mw.returnJson(False, 'fail') - - -def setSlaveSyncMode(version): - args = getArgs() - data = checkArgs(args, ['mode']) - if not data[0]: - return data[1] - mode = args['mode'] - sync_mode = getSyncModeFile() - - if mode == 'none': - os.remove(sync_mode) - else: - mw.writeFile(sync_mode, mode) - return mw.returnJson(True, '设置成功', mode) - - -def getSlaveSSHByIp(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_id_rsa') - data = conn.field('ip,port,db_user,id_rsa').where("ip=?", (ip,)).select() - return mw.returnJson(True, 'ok', data) - - -def addSlaveSSH(version=''): - import base64 - - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - if ip == "": - return mw.returnJson(True, 'ok') - - data = checkArgs(args, ['port', 'id_rsa', 'db_user']) - if not data[0]: - return data[1] - - id_rsa = args['id_rsa'] - port = args['port'] - db_user = args['db_user'] - user = 'root' - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - - conn = pSqliteDb('slave_id_rsa') - data = conn.field('ip,id_rsa').where("ip=?", (ip,)).select() - if len(data) > 0: - res = conn.where("ip=?", (ip,)).save( - 'port,id_rsa,db_user', (port, id_rsa, db_user)) - else: - conn.add('ip,port,user,id_rsa,db_user,ps,addtime', - (ip, port, user, id_rsa, db_user, '', addTime)) - - return mw.returnJson(True, '设置成功!') - - -def delSlaveSSH(version=''): - args = getArgs() - data = checkArgs(args, ['ip']) - if not data[0]: - return data[1] - - ip = args['ip'] - - conn = pSqliteDb('slave_id_rsa') - conn.where("ip=?", (ip,)).delete() - return mw.returnJson(True, 'ok') - - -def updateSlaveSSH(version=''): - args = getArgs() - data = checkArgs(args, ['ip', 'id_rsa']) - if not data[0]: - return data[1] - - ip = args['ip'] - id_rsa = args['id_rsa'] - conn = pSqliteDb('slave_id_rsa') - conn.where("ip=?", (ip,)).save('id_rsa', (id_rsa,)) - return mw.returnJson(True, 'ok') - - -def getSlaveList(version=''): - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动', []) - - query_status_cmd = 'show slave status' - mdb8 = getMdb8Ver() - if mw.inArray(mdb8, version): - query_status_cmd = 'show replica status' - - db = pMysqlDb() - dlist = db.query(query_status_cmd) - data = {} - data['data'] = dlist - return mw.getJson(data) - -def trySlaveSyncBugfix(version=''): - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动', []) - - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - if mode != 'sync-user': - return mw.returnJson(False, '仅支持【同步账户】模式') - - conn = pSqliteDb('slave_sync_user') - slave_sync_data = conn.field('ip,port,user,pass,mode,cmd').select() - if len(slave_sync_data) < 1: - return mw.returnJson(False, '需要先添加【同步用户】配置!') - - # print(slave_sync_data) - # 本地从库 - sdb = pMysqlDb() - - gtid_purged = '' - - for i in range(len(slave_sync_data)): - port = slave_sync_data[i]['port'] - password = slave_sync_data[i]['pass'] - host = slave_sync_data[i]['ip'] - user = slave_sync_data[i]['user'] - - # print(port, password, host) - - mdb = mw.getMyORM() - mdb.setHost(host) - mdb.setPort(port) - mdb.setUser(user) - mdb.setPwd(password) - mdb.setSocket('') - - var_gtid = mdb.query('show VARIABLES like "%gtid_purged%"') - if len(var_gtid) > 0: - gtid_purged += var_gtid[0]['Value'] + ',' - - gtid_purged = gtid_purged.strip(',') - sql = "set @@global.gtid_purged='" + gtid_purged + "'" - - sdb.query('stop slave') - # print(sql) - sdb.query(sql) - sdb.query('start slave') - return mw.returnJson(True, '修复成功!') - -def getSlaveSyncCmd(version=''): - - root = mw.getPanelDir() - cmd = 'cd ' + root + ' && python3 ' + root + \ - '/plugins/mysql/index.py do_full_sync {"db":"all"}' - return mw.returnJson(True, 'ok', cmd) - - -def initSlaveStatus(version=''): - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - if mode == 'ssh': - return initSlaveStatusSSH(version) - if mode == 'sync-user': - return initSlaveStatusSyncUser(version) - - -def parseSlaveSyncCmd(cmd): - a = {} - if cmd.lower().find('for') > 0: - cmd_tmp = cmd.split('for') - cmd = cmd_tmp[0].strip() - - pattern_c = r"channel \'(.*)\';" - match_val = re.match(pattern_c, cmd_tmp[1].strip(), re.I) - if match_val: - m_groups = match_val.groups() - a['channel'] = m_groups[0] - vlist = cmd.split(',') - for i in vlist: - tmp = i.strip() - tmp_a = tmp.split(" ") - real_tmp = tmp_a[len(tmp_a) - 1] - kv = real_tmp.split("=") - a[kv[0]] = kv[1].replace("'", '').replace("'", '').replace(";", '') - return a - - -def initSlaveStatusSyncUser(version=''): - conn = pSqliteDb('slave_sync_user') - slave_data = conn.field('ip,port,user,pass,mode,cmd').select() - if len(slave_data) < 1: - return mw.returnJson(False, '需要先添加同步用户配置!') - - # print(data) - pdb = pMysqlDb() - if len(slave_data) == 1: - dlist = pdb.query('show slave status') - if len(dlist) > 0: - return mw.returnJson(False, '已经初始化好了zz...') - - msg = '' - local_mode = recognizeDbMode() - for x in range(len(slave_data)): - slave_t = slave_data[x] - mode_name = 'classic' - base_t = 'IP:' + slave_t['ip'] + ",PORT:" + \ - slave_t['port'] + ",USER:" + slave_t['user'] - - if slave_t['mode'] == '1': - mode_name = 'gtid' - - if local_mode != mode_name: - msg += base_t + '->同步模式不一致' - continue - - cmd_sql = slave_t['cmd'] - if cmd_sql == '': - msg += base_t + '->同步命令不能为空' - continue - - try: - pinfo = parseSlaveSyncCmd(cmd_sql) - except Exception as e: - return mw.returnJson(False, base_t + '->CMD同步命令不合规范!') - # print(u['cmd']) - t = pdb.query(cmd_sql) - isError = isSqlError(t) - if isError: - return isError - - # pdb.query("start slave user='{}' password='{}';".format( - # u['user'], u['pass'])) - - pdb.query("start slave") - pdb.query("start all slaves") - - if msg == '': - msg = '初始化成功!' - return mw.returnJson(True, msg) - - -def initSlaveStatusSSH(version=''): - db = pMysqlDb() - dlist = db.query('show slave status') - - conn = pSqliteDb('slave_id_rsa') - ssh_list = conn.field('ip,port,id_rsa,db_user').select() - - if len(ssh_list) < 1: - return mw.returnJson(False, '需要先配置【[主]SSH配置】!') - - local_mode = recognizeDbMode() - - import paramiko - paramiko.util.log_to_file('paramiko.log') - ssh = paramiko.SSHClient() - - db.query('stop slave') - db.query('reset slave all') - for data in ssh_list: - ip = data['ip'] - SSH_PRIVATE_KEY = "/tmp/t_ssh_" + ip + ".txt" - master_port = data['port'] - mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n')) - mw.execShell("chmod 600 " + SSH_PRIVATE_KEY) - try: - key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - ssh.connect(hostname=ip, port=int(master_port), - username='root', pkey=key) - - db_user = data['db_user'] - cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql-yum/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}' - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result = result.decode('utf-8') - if result.strip() == "": - return mw.returnJson(False, '[主][' + ip + ']:获取同步命令失败!') - - cmd_data = json.loads(result) - if not cmd_data['status']: - return mw.returnJson(False, '[主][' + ip + ']:' + cmd_data['msg']) - - if local_mode != cmd_data['data']['mode']: - return mw.returnJson(False, '[主][' + ip + ']:【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode)) - - u = cmd_data['data']['info'] - - ps = u['username'] + "|" + u['password'] - print(ps) - conn.where('ip=?', (ip,)).setField('ps', ps) - db.query('stop slave') - - # 保证同步IP一致 - cmd = cmd_data['data']['cmd'] - if cmd.find('SOURCE_HOST') > -1: - cmd = re.sub(r"SOURCE_HOST='(.*?)'", - "SOURCE_HOST='" + ip + "'", cmd, 1) - - if cmd.find('MASTER_HOST') > -1: - cmd = re.sub(r"MASTER_HOST='(.*?)'", - "MASTER_HOST='" + ip + "'", cmd, 1) - db.query(cmd) - ssh.close() - if os.path.exists(SSH_PRIVATE_KEY): - os.system("rm -rf " + SSH_PRIVATE_KEY) - except Exception as e: - return mw.returnJson(False, '[主][' + ip + ']:SSH认证配置连接失败!' + str(e)) - db.query('start slave') - return mw.returnJson(True, '初始化成功!') - - -def setSlaveStatus(version=''): - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - pdb = pMysqlDb() - dlist = pdb.query('show slave status') - if len(dlist) == 0: - return mw.returnJson(False, '需要手动添加同步账户或者执行初始化!') - - for v in dlist: - connection_name = '' - cmd = "slave" - if 'Channel_Name' in v: - ch_name = v['Channel_Name'] - cmd = "slave for channel '{}'".format(ch_name) - - if (v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes'): - pdb.query("stop {}".format(cmd)) - else: - pdb.query("start {}".format(cmd)) - - return mw.returnJson(True, '设置成功!') - - -def deleteSlave(version=''): - args = getArgs() - db = pMysqlDb() - if 'sign' in args: - sign = args['sign'] - db.query("stop slave for channel '{}'".format(sign)) - db.query("reset slave all for channel '{}'".format(sign)) - else: - db.query('stop slave') - db.query('reset slave all') - - return mw.returnJson(True, '删除成功!') - - -def dumpMysqlData(version=''): - args = getArgs() - data = checkArgs(args, ['db']) - if not data[0]: - return data[1] - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - mysql_dir = getServerDir() - myconf = mysql_dir + "/etc/my.cnf" - - option = '' - mode = recognizeDbMode() - if mode == 'gtid': - option = ' --set-gtid-purged=off ' - - if args['db'].lower() == 'all': - dlist = findBinlogDoDb() - cmd = mysql_dir + "/bin/mysqldump --defaults-file=" + myconf + " " + option + " -uroot -p" + \ - pwd + " --databases " + \ - ' '.join(dlist) + " | gzip > /tmp/dump.sql.gz" - else: - cmd = mysql_dir + "/bin/mysqldump --defaults-file=" + myconf + " " + option + " -uroot -p" + \ - pwd + " --databases " + args['db'] + " | gzip > /tmp/dump.sql.gz" - - ret = mw.execShell(cmd) - if ret[0] == '': - return 'ok' - return 'fail' - - -############### --- 重要 数据补足同步 ---- ########### - -def getSyncMysqlDB(dbname,sign = ''): - conn = pSqliteDb('slave_sync_user') - if sign != '': - data = conn.field('ip,port,user,pass,mode,cmd').where('ip=?', (sign,)).find() - else: - data = conn.field('ip,port,user,pass,mode,cmd').find() - user = data['user'] - apass = data['pass'] - port = data['port'] - ip = data['ip'] - # 远程数据 - sync_db = mw.getMyORM() - # MySQLdb | - sync_db.setPort(port) - sync_db.setHost(ip) - sync_db.setUser(user) - sync_db.setPwd(apass) - sync_db.setDbName(dbname) - sync_db.setTimeout(60) - return sync_db - -def syncDatabaseRepairTempFile(): - tmp_log = mw.getMWLogs()+ '/mysql-check.log' - return tmp_log - -def syncDatabaseRepairLog(version=''): - import subprocess - args = getArgs() - data = checkArgs(args, ['db','sign','op']) - if not data[0]: - return data[1] - - sync_args_db = args['db'] - sync_args_sign = args['sign'] - op = args['op'] - tmp_log = syncDatabaseRepairTempFile() - cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && python3 plugins/mysql-yum/index.py sync_database_repair {"db":"'+sync_args_db+'","sign":"'+sync_args_sign+'"}' - # print(cmd) - - if op == 'get': - log = mw.getLastLine(tmp_log, 15) - return mw.returnJson(True, log) - - if op == 'cmd': - return mw.returnJson(True, 'ok', cmd) - - if op == 'do': - os.system(' echo "开始执行" > '+ tmp_log) - os.system(cmd +' >> '+ tmp_log +' &') - return mw.returnJson(True, 'ok') - - return mw.returnJson(False, '无效请求!') - - -def syncDatabaseRepair(version=''): - time_stats_s = time.time() - tmp_log = syncDatabaseRepairTempFile() - - from pymysql.converters import escape_string - args = getArgs() - data = checkArgs(args, ['db','sign']) - if not data[0]: - return data[1] - - sync_args_db = args['db'] - sync_args_sign = args['sign'] - - # 本地数据 - local_db = pMysqlDb() - # 远程数据 - sync_db = getSyncMysqlDB(sync_args_db,sync_args_sign) - - tables = local_db.query('show tables from `%s`' % sync_args_db) - table_key = "Tables_in_" + sync_args_db - inconsistent_table = [] - - tmp_dir = '/tmp/sync_db_repair' - mw.execShell('mkdir -p '+tmp_dir) - - for tb in tables: - - table_name = sync_args_db+'.'+tb[table_key] - table_check_file = tmp_dir+'/'+table_name+'.txt' - - if os.path.exists(table_check_file): - # print(table_name+', 已检查OK') - continue - - primary_key_sql = "SHOW INDEX FROM "+table_name+" WHERE Key_name = 'PRIMARY';"; - primary_key_data = local_db.query(primary_key_sql) - # print(primary_key_sql,primary_key_data) - pkey_name = '*' - if len(primary_key_data) == 1: - pkey_name = primary_key_data[0]['Column_name'] - # print(pkey_name) - if pkey_name != '*' : - # 智能校验(由于服务器同步可能会慢,比较总数总是对不上) - cmd_local_newpk_sql = 'select ' + pkey_name + ' from ' + table_name + " order by " + pkey_name + " desc limit 1" - cmd_local_newpk_data = local_db.query(cmd_local_newpk_sql) - # print(cmd_local_newpk_data) - if len(cmd_local_newpk_data) == 1: - # 比较总数 - cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name + ' where '+pkey_name + ' <= '+ str(cmd_local_newpk_data[0][pkey_name]) - local_count_data = local_db.query(cmd_count_sql) - sync_count_data = sync_db.query(cmd_count_sql) - - if local_count_data != sync_count_data: - print(cmd_count_sql) - print("all data compare: ",local_count_data, sync_count_data) - else: - print(table_name+' smart compare check ok.') - mw.writeFile(tmp_log, table_name+' smart compare check ok.\n','a+') - mw.execShell("echo 'ok' > "+table_check_file) - continue - - - - # 比较总数 - cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name - local_count_data = local_db.query(cmd_count_sql) - sync_count_data = sync_db.query(cmd_count_sql) - - if local_count_data != sync_count_data: - print("all data compare: ",local_count_data, sync_count_data) - inconsistent_table.append(table_name) - diff = sync_count_data[0]['num'] - local_count_data[0]['num'] - print(table_name+', need sync. diff,'+str(diff)) - mw.writeFile(tmp_log, table_name+', need sync. diff,'+str(diff)+'\n','a+') - else: - print(table_name+' check ok.') - mw.writeFile(tmp_log, table_name+' check ok.\n','a+') - mw.execShell("echo 'ok' > "+table_check_file) - - - # inconsistent_table = ['xx.xx'] - # 数据对齐 - for table_name in inconsistent_table: - is_break = False - while not is_break: - local_db.ping() - # 远程数据 - sync_db.ping() - - print("check table:"+table_name) - mw.writeFile(tmp_log, "check table:"+table_name+'\n','a+') - table_name_pos = 0 - table_name_pos_file = tmp_dir+'/'+table_name+'.pos.txt' - primary_key_sql = "SHOW INDEX FROM "+table_name+" WHERE Key_name = 'PRIMARY';"; - primary_key_data = local_db.query(primary_key_sql) - pkey_name = primary_key_data[0]['Column_name'] - - if os.path.exists(table_name_pos_file): - table_name_pos = mw.readFile(table_name_pos_file) - - - data_select_sql = 'select * from '+table_name + ' where '+pkey_name+' > '+str(table_name_pos)+' limit 10000' - print(data_select_sql) - local_select_data = local_db.query(data_select_sql) - - time_s = time.time() - sync_select_data = sync_db.query(data_select_sql) - print(f'sync query cos:{time.time() - time_s:.4f}s') - mw.writeFile(tmp_log, f'sync query cos:{time.time() - time_s:.4f}s\n','a+') - - # print(local_select_data) - # print(sync_select_data) - - # print(len(local_select_data)) - # print(len(sync_select_data)) - print('pos:',str(table_name_pos),'local compare sync,',local_select_data == sync_select_data) - - - cmd_count_sql = 'select count('+pkey_name+') as num from '+table_name - local_count_data = local_db.query(cmd_count_sql) - time_s = time.time() - sync_count_data = sync_db.query(cmd_count_sql) - print(f'sync count data cos:{time.time() - time_s:.4f}s') - print(local_count_data,sync_count_data) - # 数据同步有延迟,相等即任务数据补足完成 - if local_count_data[0]['num'] == sync_count_data[0]['num']: - is_break = True - break - - diff = sync_count_data[0]['num'] - local_count_data[0]['num'] - print("diff," + str(diff)+' line data!') - - if local_select_data == sync_select_data: - data_count = len(local_select_data) - if data_count == 0: - # mw.writeFile(table_name_pos_file, '0') - print(table_name+",data is equal ok..") - is_break = True - break - - # print(table_name,data_count) - pos = local_select_data[data_count-1][pkey_name] - print('pos',pos) - progress = pos/sync_count_data[0]['num'] - print('progress,%.2f' % progress+'%') - mw.writeFile(table_name_pos_file, str(pos)) - else: - sync_select_data_len = len(sync_select_data) - skip_idx = 0 - # 主库PK -> 查询本地 | 保证一致 - if sync_select_data_len > 0: - for idx in range(sync_select_data_len): - sync_idx_data = sync_select_data[idx] - local_idx_data = None - if idx in local_select_data: - local_idx_data = local_select_data[idx] - if sync_select_data[idx] == local_idx_data: - skip_idx = idx - pos = local_select_data[idx][pkey_name] - mw.writeFile(table_name_pos_file, str(pos)) - - # print(insert_data) - local_inquery_sql = 'select * from ' + table_name+ ' where ' +pkey_name+' = '+ str(sync_idx_data[pkey_name]) - # print(local_inquery_sql) - ldata = local_db.query(local_inquery_sql) - # print('ldata:',ldata) - if len(ldata) == 0: - print("id:"+ str(sync_idx_data[pkey_name])+ " no exists, insert") - insert_sql = 'insert into ' + table_name - field_str = '' - value_str = '' - for field in sync_idx_data: - field_str += '`'+field+'`,' - value_str += '\''+escape_string(str(sync_idx_data[field]))+'\',' - field_str = '(' +field_str.strip(',')+')' - value_str = '(' +value_str.strip(',')+')' - insert_sql = insert_sql+' '+field_str+' values'+value_str+';' - print(insert_sql) - r = local_db.execute(insert_sql) - print(r) - else: - # print('compare sync->local:',sync_idx_data == ldata[0] ) - if ldata[0] == sync_idx_data: - continue - - print("id:"+ str(sync_idx_data[pkey_name])+ " data is not equal, update") - update_sql = 'update ' + table_name - field_str = '' - value_str = '' - for field in sync_idx_data: - if field == pkey_name: - continue - field_str += '`'+field+'`=\''+escape_string(str(sync_idx_data[field]))+'\',' - field_str = field_str.strip(',') - update_sql = update_sql+' set '+field_str+' where '+pkey_name+'=\''+str(sync_idx_data[pkey_name])+'\';' - print(update_sql) - r = local_db.execute(update_sql) - print(r) - - # 本地PK -> 查询主库 | 保证一致 - # local_select_data_len = len(local_select_data) - # if local_select_data_len > 0: - # for idx in range(local_select_data_len): - # if idx < skip_idx: - # continue - # local_idx_data = local_select_data[idx] - # print('local idx check', idx, skip_idx) - # local_inquery_sql = 'select * from ' + table_name+ ' where ' +pkey_name+' = '+ str(local_idx_data[pkey_name]) - # print(local_inquery_sql) - # sdata = sync_db.query(local_inquery_sql) - # sdata_len = len(sdata) - # print('sdata:',sdata,sdata_len) - # if sdata_len == 0: - # delete_sql = 'delete from ' + table_name + ' where ' +pkey_name+' = '+ str(local_idx_data[pkey_name]) - # print(delete_sql) - # r = local_db.execute(delete_sql) - # print(r) - # break - - - if is_break: - print("break all") - break - time.sleep(3) - print(f'data check cos:{time.time() - time_stats_s:.4f}s') - print("data supplementation completed") - mw.execShell('rm -rf '+tmp_dir) - return 'ok' - -############### --- 重要 同步---- ########### - -def asyncTmpfile(): - path = '/tmp/mysql_async_status.txt' - return path - - -def writeDbSyncStatus(data): - path = asyncTmpfile() - mw.writeFile(path, json.dumps(data)) - return True - -def fullSyncCmd(): - args = getArgs() - data = checkArgs(args, ['db', 'sign']) - if not data[0]: - return data[1] - - db = args['db'] - sign = args['sign'] - - cmd = 'cd '+mw.getServerDir()+'/mdserver-web && source bin/activate && python3 plugins/mysql-yum/index.py do_full_sync {"db":"'+db+'","sign":"'+sign+'"}' - return mw.returnJson(True,'ok',cmd) - -def doFullSync(version=''): - mode_file = getSyncModeFile() - if not os.path.exists(mode_file): - return mw.returnJson(False, '需要先设置同步配置') - - mode = mw.readFile(mode_file) - if mode == 'ssh': - return doFullSyncSSH(version) - if mode == 'sync-user': - return doFullSyncUser(version) - - -def isSimpleSyncCmd(sql): - new_sql = sql.lower() - if new_sql.find('master_auto_position') > 0: - return False - return True - -def getChannelNameForCmd(cmd): - cmd = cmd.lower() - cmd_arr = cmd.split('channel') - if len(cmd_arr) == 2: - cmd_channel_info = cmd_arr[1] - channel_name = cmd_channel_info.strip() - channel_name = channel_name.strip(';') - channel_name = channel_name.strip("'") - return channel_name - return '' - -def doFullSyncUserImportContentForChannel(file, channel_name): - # print(file, channel_name) - content = mw.readFile(file) - - content = content.replace('STOP SLAVE;', "STOP SLAVE for channel '{}';".format(channel_name)) - content = content.replace('START SLAVE;', "START SLAVE for channel '{}';".format(channel_name)) - - find_head = "CHANGE MASTER TO " - find_re = find_head+"(.*?);" - find_r = re.search(find_re, content, re.I|re.M) - if find_r: - find_rg = find_r.groups() - if len(find_rg)>0: - find_str = find_head+find_rg[0] - if find_str.lower().find('channel')==-1: - content = content.replace(find_str+';', find_str+" for channel '{}';".format(channel_name)) - - mw.writeFile(file,content) - return True - - -def doFullSyncUser(version=''): - which_pv = mw.execShell('which pv') - is_exist_pv = False - if os.path.exists(which_pv[0]): - is_exist_pv = True - - time_all_s = time.time() - args = getArgs() - data = checkArgs(args, ['db', 'sign']) - if not data[0]: - return data[1] - - sync_db = args['db'] - sync_db_import = args['db'] - - if sync_db.lower() == 'all': - sync_db_import = '' - dbs = findBinlogSlaveDoDb() - dbs_str = '' - for x in dbs: - dbs_str += ' ' + x - sync_db = "--databases " + dbs_str.strip() - - sync_sign = args['sign'] - - db = pMysqlDb() - - conn = pSqliteDb('slave_sync_user') - if sync_sign != '': - data = conn.field('ip,port,user,pass,mode,cmd').where( - 'ip=?', (sync_sign,)).find() - else: - data = conn.field('ip,port,user,pass,mode,cmd').find() - - user = data['user'] - apass = data['pass'] - port = data['port'] - ip = data['ip'] - cmd = data['cmd'] - - channel_name = getChannelNameForCmd(cmd) - sync_mdb = getSyncMysqlDB(sync_db,sync_sign) - - bak_file = '/tmp/tmp.sql' - if os.path.exists(bak_file): - os.system("rm -rf " + bak_file) - - writeDbSyncStatus({'code': 0, 'msg': '开始同步...', 'progress': 0}) - dmp_option = '' - mode = recognizeDbMode() - if mode == 'gtid': - dmp_option = ' --set-gtid-purged=off ' - - writeDbSyncStatus({'code': 1, 'msg': '远程导出数据...', 'progress': 15}) - - mdb8 = getMdb8Ver() - if mw.inArray(mdb8,version): - db.query("stop slave user='{}' password='{}';".format(user, apass)) - else: - db.query("stop slave") - - time.sleep(1) - writeDbSyncStatus({'code': 2, 'msg': '远程导出数据...', 'progress': 20}) - - find_run_dump = mw.execShell('ps -ef | grep mysqldump | grep -v grep') - if find_run_dump[0] != "": - print("正在远程导出数据中,别着急...") - writeDbSyncStatus({'code': 3.1, 'msg': '正在远程导出数据中,别着急...', 'progress': 19}) - return False - - if not os.path.exists(bak_file): - dmp_option += ' ' - if isSimpleSyncCmd(cmd): - if mw.inArray(mdb8,version): - # --compression-algorithms - dmp_option += " --source-data=1 --apply-replica-statements --include-source-host-port " - else: - dmp_option += " --master-data=1 --apply-slave-statements --include-master-host-port --compress " - - - dump_sql_data = getServerDir() + "/bin/usr/bin/mysqldump --single-transaction --default-character-set=utf8mb4 -q " + dmp_option + " -h" + \ - ip + " -P" + port + " -u" + user + ' -p"' + apass + '" --ssl-mode=DISABLED ' + sync_db + " > " + bak_file - print(dump_sql_data) - time_s = time.time() - r = mw.execShell(dump_sql_data) - print(r) - time_e = time.time() - export_cos = time_e - time_s - print("export cos:", export_cos) - - writeDbSyncStatus({'code': 3, 'msg': '导出耗时:'+str(int(export_cos))+'秒,正在到本地导入数据中...', 'progress': 40}) - - find_run_import = mw.execShell('ps -ef | grep mysql| grep '+ bak_file +' | grep -v grep') - if find_run_import[0] != "": - print("正在导入数据中,别着急...") - writeDbSyncStatus({'code': 4.1, 'msg': '正在导入数据中,别着急...', 'progress': 39}) - return False - - writeDbSyncStatus({'code': 2, 'msg': '本地导入数据...', 'progress': 40}) - time_s = time.time() - if os.path.exists(bak_file): - # 重置 - db.execute('reset master') - if channel_name != '': - doFullSyncUserImportContentForChannel(bak_file, channel_name) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - sock = getSocketFile() - - if is_exist_pv: - my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import - my_import_cmd = "pv -t -p " + bak_file + '|' + my_import_cmd - print(my_import_cmd) - os.system(my_import_cmd) - else: - my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + " -uroot -p'" + pwd + "' " + sync_db_import + ' < ' + bak_file - print(my_import_cmd) - mw.execShell(my_import_cmd) - - my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \ - ' ' + sync_db_import + ' < ' + bak_file - mw.execShell(my_import_cmd) - - - if mw.inArray(mdb8, version): - db.query("start replica user='{}' password='{}';".format(user, apass)) - else: - db.query("start slave") - - db.query("start all slaves") - time_all_e = time.time() - cos = time_all_e - time_all_s - writeDbSyncStatus({'code': 6, 'msg': '总耗时:'+str(int(cos))+'秒,从库重启完成...', 'progress': 100}) - - if os.path.exists(bak_file): - os.system("rm -rf " + bak_file) - return True - - -def doFullSyncSSH(version=''): - - args = getArgs() - data = checkArgs(args, ['db', 'sign']) - if not data[0]: - return data[1] - - sync_db = args['db'] - sync_sign = args['sign'] - - db = pMysqlDb() - - id_rsa_conn = pSqliteDb('slave_id_rsa') - if sync_sign != '': - data = id_rsa_conn.field('ip,port,db_user,id_rsa').where( - 'ip=?', (sync_sign,)).find() - else: - data = id_rsa_conn.field('ip,port,db_user,id_rsa').find() - - SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt" - id_rsa = data['id_rsa'].replace('\\n', '\n') - mw.writeFile(SSH_PRIVATE_KEY, id_rsa) - - ip = data["ip"] - master_port = data['port'] - db_user = data['db_user'] - print("master ip:", ip) - - writeDbSyncStatus({'code': 0, 'msg': '开始同步...', 'progress': 0}) - - import paramiko - paramiko.util.log_to_file('paramiko.log') - ssh = paramiko.SSHClient() - - print(SSH_PRIVATE_KEY) - if not os.path.exists(SSH_PRIVATE_KEY): - writeDbSyncStatus({'code': 0, 'msg': '需要配置SSH......', 'progress': 0}) - return 'fail' - - try: - # ssh.load_system_host_keys() - mw.execShell("chmod 600 " + SSH_PRIVATE_KEY) - key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - print(ip, master_port) - - # pkey=key - # key_filename=SSH_PRIVATE_KEY - ssh.connect(hostname=ip, port=int(master_port), - username='root', pkey=key) - except Exception as e: - print(str(e)) - writeDbSyncStatus( - {'code': 0, 'msg': 'SSH配置错误:' + str(e), 'progress': 0}) - return 'fail' - - writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5}) - - dbname = args['db'] - cmd = "cd /www/server/mdserver-web && source bin/activate && python3 " + \ - getSPluginDir() + "/index.py dump_mysql_data {\"db\":'" + dbname + "'}" - print(cmd) - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result = result.decode('utf-8') - if result.strip() == 'ok': - writeDbSyncStatus({'code': 1, 'msg': '主服务器备份完成...', 'progress': 30}) - else: - writeDbSyncStatus( - {'code': 1, 'msg': '主服务器备份失败...:' + str(result), 'progress': 100}) - return 'fail' - - print("同步文件", "start") - # cmd = 'scp -P' + str(master_port) + ' -i ' + SSH_PRIVATE_KEY + \ - # ' root@' + ip + ':/tmp/dump.sql.gz /tmp' - t = ssh.get_transport() - sftp = paramiko.SFTPClient.from_transport(t) - copy_status = sftp.get("/tmp/dump.sql.gz", "/tmp/dump.sql.gz") - print("同步信息:", copy_status) - print("同步文件", "end") - if copy_status == None: - writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40}) - - cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \ - getSPluginDir() + \ - '/index.py get_master_rep_slave_user_cmd {"username":"' + \ - db_user + '","db":""}' - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result = result.decode('utf-8') - cmd_data = json.loads(result) - - db.query('stop slave') - writeDbSyncStatus({'code': 3, 'msg': '停止从库完成...', 'progress': 45}) - - cmd = cmd_data['data']['cmd'] - # 保证同步IP一致 - if cmd.find('SOURCE_HOST') > -1: - cmd = re.sub(r"SOURCE_HOST='(.*?)'", - "SOURCE_HOST='" + ip + "'", cmd, 1) - - if cmd.find('MASTER_HOST') > -1: - cmd = re.sub(r"MASTER_HOST='(.*?)'", - "MASTER_HOST='" + ip + "'", cmd, 1) - - db.query(cmd) - uinfo = cmd_data['data']['info'] - ps = uinfo['username'] + "|" + uinfo['password'] - id_rsa_conn.where('ip=?', (ip,)).setField('ps', ps) - writeDbSyncStatus({'code': 4, 'msg': '刷新从库同步信息完成...', 'progress': 50}) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - root_dir = getServerDir() - msock = root_dir + "/mysql.sock" - mw.execShell("cd /tmp && gzip -d dump.sql.gz") - cmd = root_dir + "/bin/usr/bin/mysql -S " + msock + \ - " -uroot -p" + pwd + " < /tmp/dump.sql" - - print(cmd) - import_data = mw.execShell(cmd) - if import_data[0] == '': - print(import_data[1]) - writeDbSyncStatus({'code': 5, 'msg': '导入数据完成...', 'progress': 90}) - else: - print(import_data[0]) - writeDbSyncStatus({'code': 5, 'msg': '导入数据失败...', 'progress': 100}) - return 'fail' - - # "start slave user='{}' password='{}';".format(uinfo['username'], uinfo['password']) - - db.query("start slave") - writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100}) - - os.system("rm -rf " + SSH_PRIVATE_KEY) - os.system("rm -rf /tmp/dump.sql") - return True - - -def fullSync(version=''): - args = getArgs() - data = checkArgs(args, ['db', 'begin']) - if not data[0]: - return data[1] - - sign = '' - if 'sign' in args: - sign = args['sign'] - - status_file = asyncTmpfile() - if args['begin'] == '1': - cmd = 'cd ' + mw.getPanelDir() + ' && python3 ' + getPluginDir() + \ - '/index.py do_full_sync {"db":"' + \ - args['db'] + '","sign":"' + sign + '"} &' - # print(cmd) - mw.execShell(cmd) - return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0}) - - if os.path.exists(status_file): - c = mw.readFile(status_file) - tmp = json.loads(c) - if tmp['code'] == 1: - sys_dump_sql = "/tmp/dump.sql" - if os.path.exists(sys_dump_sql): - dump_size = os.path.getsize(sys_dump_sql) - tmp['msg'] = tmp['msg'] + ":" + "同步文件:" + mw.toSize(dump_size) - c = json.dumps(tmp) - - # if tmp['code'] == 6: - # os.remove(status_file) - return c - - return json.dumps({'code': 0, 'msg': '点击开始,开始同步!', 'progress': 0}) - - -def installPreInspection(version): - cmd = "cat /etc/*-release | grep PRETTY_NAME |awk -F = '{print $2}' | awk -F '\"' '{print $2}'| awk '{print $1}'" - sys = mw.execShell(cmd) - - cmd = "cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F '\"' '{print $2}'" - sys_id = mw.execShell(cmd) - - sysName = sys[0].strip().lower() - sysId = sys_id[0].strip() - - if not sysName in ['centos','almalinux','rocky','opensuse']: - return '仅支持centos,almalinux,rocky,opensuse' - - if (sysName == 'centos' and version == '5.7' and not sysId in('7',)): - return 'mysql5.7 仅支持centos7' - - mdb8 = getMdb8Ver() - if (sysName == 'centos' and mw.inArray(mdb8, version) and not sysId in ('7', '8', '9',)): - return 'mysql8.0 仅支持centos7,8,9' - return 'ok' - - -def uninstallPreInspection(version): - try: - stop(version) - except Exception as e: - pass - if mw.isDebugMode(): - return 'ok' - - from utils.plugin import plugin as MwPlugin - MwPlugin.instance().removeIndex(getPluginName(), version) - - return "请手动删除MySQL[{}]
      rm -rf {}".format(version, getServerDir()) - -if __name__ == "__main__": - func = sys.argv[1] - - version = '5.6' - version_pl = getServerDir() + "/version.pl" - if os.path.exists(version_pl): - version = mw.readFile(version_pl).strip() - - if func == 'status': - print(status(version)) - elif func == 'start': - print(start(version)) - elif func == 'stop': - print(stop(version)) - elif func == 'restart': - print(restart(version)) - elif func == 'reload': - print(reload(version)) - elif func == 'initd_status': - print(initdStatus()) - elif func == 'initd_install': - print(initdInstall()) - elif func == 'initd_uninstall': - print(initdUinstall()) - elif func == 'install_pre_inspection': - print(installPreInspection(version)) - elif func == 'uninstall_pre_inspection': - print(uninstallPreInspection(version)) - elif func == 'run_info': - print(runInfo(version)) - elif func == 'db_status': - print(myDbStatus(version)) - elif func == 'set_db_status': - print(setDbStatus(version)) - elif func == 'conf': - print(getConf()) - elif func == 'bin_log': - print(binLog(version)) - elif func == 'binlog_list': - print(binLogList()) - elif func == 'clean_bin_log': - print(cleanBinLog()) - elif func == 'error_log': - print(getErrorLog()) - elif func == 'show_log': - print(getShowLogFile()) - elif func == 'my_db_pos': - print(getMyDbPos()) - elif func == 'set_db_pos': - print(setMyDbPos(version)) - elif func == 'my_port': - print(getMyPort()) - elif func == 'set_my_port': - print(setMyPort()) - elif func == 'init_pwd': - print(initMysqlPwd()) - elif func == 'root_pwd': - print(rootPwd()) - elif func == 'get_db_list': - print(getDbList()) - elif func == 'set_db_backup': - print(setDbBackup()) - elif func == 'import_db_backup': - print(importDbBackup()) - elif func == 'import_db_external': - print(importDbExternal()) - elif func == 'import_db_external_progress': - print(importDbExternalProgress()) - elif func == 'import_db_external_progress_bar': - print(importDbExternalProgressBar()) - elif func == 'delete_db_backup': - print(deleteDbBackup()) - elif func == 'get_db_backup_list': - print(getDbBackupList()) - elif func == 'get_db_backup_import_list': - print(getDbBackupImportList()) - elif func == 'add_db': - print(addDb()) - elif func == 'del_db': - print(delDb()) - elif func == 'sync_get_databases': - print(syncGetDatabases()) - elif func == 'sync_to_databases': - print(syncToDatabases()) - elif func == 'set_root_pwd': - print(setRootPwd(version)) - elif func == 'set_user_pwd': - print(setUserPwd(version)) - elif func == 'get_db_access': - print(getDbAccess()) - elif func == 'set_db_access': - print(setDbAccess()) - elif func == 'fix_db_access': - print(fixDbAccess(version)) - elif func == 'fix_db_access2': - print(fixDbAccess2(version)) - elif func == 'set_db_rw': - print(setDbRw(version)) - elif func == 'set_db_ps': - print(setDbPs()) - elif func == 'get_db_info': - print(getDbInfo()) - elif func == 'repair_table': - print(repairTable()) - elif func == 'opt_table': - print(optTable()) - elif func == 'alter_table': - print(alterTable()) - elif func == 'get_total_statistics': - print(getTotalStatistics()) - elif func == 'get_dbrun_mode': - print(getDbrunMode(version)) - elif func == 'set_dbrun_mode': - print(setDbrunMode(version)) - elif func == 'reset_master': - print(resetMaster(version)) - elif func == 'get_masterdb_list': - print(getMasterDbList(version)) - elif func == 'get_master_status': - print(getMasterStatus(version)) - elif func == 'set_master_status': - print(setMasterStatus(version)) - elif func == 'set_db_master': - print(setDbMaster(version)) - elif func == 'set_db_slave': - print(setDbSlave(version)) - elif func == 'set_dbmaster_access': - print(setDbMasterAccess()) - elif func == 'get_master_rep_slave_list': - print(getMasterRepSlaveList(version)) - elif func == 'add_master_rep_slave_user': - print(addMasterRepSlaveUser(version)) - elif func == 'del_master_rep_slave_user': - print(delMasterRepSlaveUser(version)) - elif func == 'update_master_rep_slave_user': - print(updateMasterRepSlaveUser(version)) - elif func == 'get_master_rep_slave_user_cmd': - print(getMasterRepSlaveUserCmd(version)) - elif func == 'get_slave_list': - print(getSlaveList(version)) - elif func == 'try_slave_sync_bugfix': - print(trySlaveSyncBugfix(version)) - elif func == 'get_slave_sync_cmd': - print(getSlaveSyncCmd(version)) - elif func == 'get_slave_ssh_list': - print(getSlaveSSHList(version)) - elif func == 'get_slave_ssh_by_ip': - print(getSlaveSSHByIp(version)) - elif func == 'add_slave_ssh': - print(addSlaveSSH(version)) - elif func == 'del_slave_ssh': - print(delSlaveSSH(version)) - elif func == 'update_slave_ssh': - print(updateSlaveSSH(version)) - elif func == 'get_slave_sync_user_list': - print(getSlaveSyncUserList(version)) - elif func == 'get_slave_sync_user_by_ip': - print(getSlaveSyncUserByIp(version)) - elif func == 'add_slave_sync_user': - print(addSlaveSyncUser(version)) - elif func == 'del_slave_sync_user': - print(delSlaveSyncUser(version)) - elif func == 'get_slave_sync_mode': - print(getSlaveSyncMode(version)) - elif func == 'set_slave_sync_mode': - print(setSlaveSyncMode(version)) - elif func == 'init_slave_status': - print(initSlaveStatus(version)) - elif func == 'set_slave_status': - print(setSlaveStatus(version)) - elif func == 'delete_slave': - print(deleteSlave(version)) - elif func == 'full_sync': - print(fullSync(version)) - elif func == 'do_full_sync': - print(doFullSync(version)) - elif func == 'full_sync_cmd': - print(fullSyncCmd()) - elif func == 'dump_mysql_data': - print(dumpMysqlData(version)) - elif func == 'sync_database_repair': - print(syncDatabaseRepair()) - elif func == 'sync_database_repair_log': - print(syncDatabaseRepairLog()) - else: - print('error') diff --git a/plugins/mysql-yum/index_mysql_yum.py b/plugins/mysql-yum/index_mysql_yum.py deleted file mode 100644 index 6c10d29f0f..0000000000 --- a/plugins/mysql-yum/index_mysql_yum.py +++ /dev/null @@ -1,182 +0,0 @@ -# coding:utf-8 - -import sys -import io -import os -import time -import subprocess -import re -import json - -web_dir = os.getcwd() + "/web" -if os.path.exists(web_dir): - sys.path.append(web_dir) - os.chdir(web_dir) - -import core.mw as mw - -app_debug = False -if mw.isAppleSystem(): - app_debug = True - - -def getPluginName(): - return 'mysql-yum' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - - -def getSPluginDir(): - return '/www/server/mdserver-web/plugins/' + getPluginName() - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def getConf(): - path = getServerDir() + '/etc/my.cnf' - return path - - -def getDataDir(): - file = getConf() - content = mw.readFile(file) - rep = r'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getRelayLogName(): - file = getConf() - content = mw.readFile(file) - rep = r'relay-log\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getLogBinName(): - file = getConf() - content = mw.readFile(file) - rep = r'log-bin\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def binLogListLook(args): - - file = args['file'] - line = args['line'] - - data_dir = getDataDir() - my_bin = getServerDir() + '/bin/usr/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata = {} - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata - - -def binLogListLookDecode(args): - - file = args['file'] - line = args['line'] - - data_dir = getDataDir() - my_bin = getServerDir() + '/bin/usr/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata = {} - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata - - -def binLogListTraceRelay(args): - rdata = {} - file = args['file'] - line = args['line'] - - relay_name = getRelayLogName() - data_dir = getDataDir() - alist = os.listdir(data_dir) - relay_list = [] - for x in range(len(alist)): - f = alist[x] - t = {} - if f.startswith(relay_name) and not f.endswith('.index'): - relay_list.append(f) - - relay_list = sorted(relay_list, reverse=True) - if len(relay_list) == 0: - rdata['cmd'] = '' - rdata['data'] = '无Relay日志' - return rdata - - file = relay_list[0] - - my_bin = getServerDir() + '/bin/usr/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata - - -def binLogListTraceBinLog(args): - rdata = {} - file = args['file'] - line = args['line'] - - data_dir = getDataDir() - log_bin_name = getLogBinName() - - alist = os.listdir(data_dir) - log_bin_l = [] - for x in range(len(alist)): - f = alist[x] - t = {} - if f.startswith(log_bin_name) and not f.endswith('.index'): - log_bin_l.append(f) - - if len(log_bin_l) == 0: - rdata['cmd'] = '' - rdata['data'] = '无BINLOG' - return rdata - - log_bin_l = sorted(log_bin_l, reverse=True) - file = log_bin_l[0] - - my_bin = getServerDir() + '/bin/usr/bin' - my_binlog_cmd = my_bin + '/mysqlbinlog' - - cmd = my_binlog_cmd + ' --no-defaults --base64-output=decode-rows -vvvv ' + \ - data_dir + '/' + file + '|tail -' + str(line) - - data = mw.execShell(cmd) - - rdata['cmd'] = cmd - rdata['data'] = data[0] - - return rdata diff --git a/plugins/mysql-yum/info.json b/plugins/mysql-yum/info.json deleted file mode 100755 index 7730019a3c..0000000000 --- a/plugins/mysql-yum/info.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "hook":["database"], - "title":"MySQL[YUM]", - "tip":"soft", - "name":"mysql-yum", - "type":"运行环境", - "ps":"一种关系数据库管理系统[centos](极速安装)", - "versions":["5.7","8.0","8.2","8.3", "8.4", "9.0"], - "shell":"install.sh", - "install_pre_inspection":true, - "uninstall_pre_inspection":true, - "checks":"server/mysql-yum", - "path":"server/mysql-yum", - "author":"mysql", - "home":"https://dev.mysql.com/downloads/mysql", - "date":"2022-06-29", - "pid": "6" -} \ No newline at end of file diff --git a/plugins/mysql-yum/init.d/mysql5.7.service.tpl b/plugins/mysql-yum/init.d/mysql5.7.service.tpl deleted file mode 100644 index 54e8036b84..0000000000 --- a/plugins/mysql-yum/init.d/mysql5.7.service.tpl +++ /dev/null @@ -1,63 +0,0 @@ -# It's not recommended to modify this file in-place, because it will be -# overwritten during package upgrades. If you want to customize, the -# best way is to use systemctl edit: -# -# $ systemctl edit mysqld.service -# -# this will create file -# -# /etc/systemd/system/mysqld.service.d/override.conf -# -# which be parsed after the file mysqld.service itself is parsed. -# -# For example, if you want to increase mysql's open-files-limit to 20000 -# add following when editing with command above: -# -# [Service] -# LimitNOFILE=20000 -# -# Or if you require to execute pre and post scripts in the unit file as root, set -# PermissionsStartOnly=true -# -# For more info about custom unit files, see systemd.unit(5) or -# http://fedoraproject.org/wiki/Systemd#How_do_I_customize_a_unit_file.2F_add_a_custom_unit_file.3F -# -# Don't forget to reload systemd daemon after you change unit configuration: -# root> systemctl --system daemon-reload - -[Unit] -Description=MySQL 5.7 database server -After=syslog.target -After=network.target - -[Service] -Type=forking -User=mysql -Group=mysql - -#ExecStartPre=/usr/libexec/mysql-check-socket -#ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n -# Note: we set --basedir to prevent probes that might trigger SELinux alarms, -# per bug #547485 -ExecStart={$SERVER_PATH}/mysql-yum/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-yum/etc/my.cnf --basedir={$SERVER_PATH}/mysql-yum/bin/usr --daemonize -#ExecStartPost=/usr/libexec/mysql-check-upgrade -#ExecStopPost=/usr/libexec/mysql-wait-stop - -# Give a reasonable amount of time for the server to start up/shut down -TimeoutSec=300 - -# Place temp files in a secure directory, not /tmp -PrivateTmp=false - -Restart=on-failure - -RestartPreventExitStatus=1 - -# Sets open_files_limit -LimitNOFILE = 10000 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for SQL restart command. -Environment=MYSQLD_PARENT_PID=1 - -[Install] -WantedBy=multi-user.target diff --git a/plugins/mysql-yum/init.d/mysql8.0.service.tpl b/plugins/mysql-yum/init.d/mysql8.0.service.tpl deleted file mode 100644 index a1a05ecf25..0000000000 --- a/plugins/mysql-yum/init.d/mysql8.0.service.tpl +++ /dev/null @@ -1,63 +0,0 @@ -# It's not recommended to modify this file in-place, because it will be -# overwritten during package upgrades. If you want to customize, the -# best way is to use systemctl edit: -# -# $ systemctl edit mysqld.service -# -# this will create file -# -# /etc/systemd/system/mysqld.service.d/override.conf -# -# which be parsed after the file mysqld.service itself is parsed. -# -# For example, if you want to increase mysql's open-files-limit to 20000 -# add following when editing with command above: -# -# [Service] -# LimitNOFILE=20000 -# -# Or if you require to execute pre and post scripts in the unit file as root, set -# PermissionsStartOnly=true -# -# For more info about custom unit files, see systemd.unit(5) or -# http://fedoraproject.org/wiki/Systemd#How_do_I_customize_a_unit_file.2F_add_a_custom_unit_file.3F -# -# Don't forget to reload systemd daemon after you change unit configuration: -# root> systemctl --system daemon-reload - -[Unit] -Description=MySQL 8.0 database server -After=syslog.target -After=network.target - -[Service] -Type=notify -User=mysql -Group=mysql - -#ExecStartPre=/usr/libexec/mysql-check-socket -#ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n -# Note: we set --basedir to prevent probes that might trigger SELinux alarms, -# per bug #547485 -ExecStart={$SERVER_PATH}/mysql-yum/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-yum/etc/my.cnf --basedir={$SERVER_PATH}/mysql-yum/bin/usr --user=mysql -#ExecStartPost=/usr/libexec/mysql-check-upgrade -#ExecStopPost=/usr/libexec/mysql-wait-stop - -# Give a reasonable amount of time for the server to start up/shut down -TimeoutSec=300 - -# Place temp files in a secure directory, not /tmp -PrivateTmp=false - -Restart=on-failure - -RestartPreventExitStatus=1 - -# Sets open_files_limit -LimitNOFILE = 10000 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for SQL restart command. -Environment=MYSQLD_PARENT_PID=1 - -[Install] -WantedBy=multi-user.target diff --git a/plugins/mysql-yum/init.d/mysql8.2.service.tpl b/plugins/mysql-yum/init.d/mysql8.2.service.tpl deleted file mode 100644 index a1a05ecf25..0000000000 --- a/plugins/mysql-yum/init.d/mysql8.2.service.tpl +++ /dev/null @@ -1,63 +0,0 @@ -# It's not recommended to modify this file in-place, because it will be -# overwritten during package upgrades. If you want to customize, the -# best way is to use systemctl edit: -# -# $ systemctl edit mysqld.service -# -# this will create file -# -# /etc/systemd/system/mysqld.service.d/override.conf -# -# which be parsed after the file mysqld.service itself is parsed. -# -# For example, if you want to increase mysql's open-files-limit to 20000 -# add following when editing with command above: -# -# [Service] -# LimitNOFILE=20000 -# -# Or if you require to execute pre and post scripts in the unit file as root, set -# PermissionsStartOnly=true -# -# For more info about custom unit files, see systemd.unit(5) or -# http://fedoraproject.org/wiki/Systemd#How_do_I_customize_a_unit_file.2F_add_a_custom_unit_file.3F -# -# Don't forget to reload systemd daemon after you change unit configuration: -# root> systemctl --system daemon-reload - -[Unit] -Description=MySQL 8.0 database server -After=syslog.target -After=network.target - -[Service] -Type=notify -User=mysql -Group=mysql - -#ExecStartPre=/usr/libexec/mysql-check-socket -#ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n -# Note: we set --basedir to prevent probes that might trigger SELinux alarms, -# per bug #547485 -ExecStart={$SERVER_PATH}/mysql-yum/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-yum/etc/my.cnf --basedir={$SERVER_PATH}/mysql-yum/bin/usr --user=mysql -#ExecStartPost=/usr/libexec/mysql-check-upgrade -#ExecStopPost=/usr/libexec/mysql-wait-stop - -# Give a reasonable amount of time for the server to start up/shut down -TimeoutSec=300 - -# Place temp files in a secure directory, not /tmp -PrivateTmp=false - -Restart=on-failure - -RestartPreventExitStatus=1 - -# Sets open_files_limit -LimitNOFILE = 10000 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for SQL restart command. -Environment=MYSQLD_PARENT_PID=1 - -[Install] -WantedBy=multi-user.target diff --git a/plugins/mysql-yum/init.d/mysql8.3.service.tpl b/plugins/mysql-yum/init.d/mysql8.3.service.tpl deleted file mode 100644 index a1a05ecf25..0000000000 --- a/plugins/mysql-yum/init.d/mysql8.3.service.tpl +++ /dev/null @@ -1,63 +0,0 @@ -# It's not recommended to modify this file in-place, because it will be -# overwritten during package upgrades. If you want to customize, the -# best way is to use systemctl edit: -# -# $ systemctl edit mysqld.service -# -# this will create file -# -# /etc/systemd/system/mysqld.service.d/override.conf -# -# which be parsed after the file mysqld.service itself is parsed. -# -# For example, if you want to increase mysql's open-files-limit to 20000 -# add following when editing with command above: -# -# [Service] -# LimitNOFILE=20000 -# -# Or if you require to execute pre and post scripts in the unit file as root, set -# PermissionsStartOnly=true -# -# For more info about custom unit files, see systemd.unit(5) or -# http://fedoraproject.org/wiki/Systemd#How_do_I_customize_a_unit_file.2F_add_a_custom_unit_file.3F -# -# Don't forget to reload systemd daemon after you change unit configuration: -# root> systemctl --system daemon-reload - -[Unit] -Description=MySQL 8.0 database server -After=syslog.target -After=network.target - -[Service] -Type=notify -User=mysql -Group=mysql - -#ExecStartPre=/usr/libexec/mysql-check-socket -#ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n -# Note: we set --basedir to prevent probes that might trigger SELinux alarms, -# per bug #547485 -ExecStart={$SERVER_PATH}/mysql-yum/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-yum/etc/my.cnf --basedir={$SERVER_PATH}/mysql-yum/bin/usr --user=mysql -#ExecStartPost=/usr/libexec/mysql-check-upgrade -#ExecStopPost=/usr/libexec/mysql-wait-stop - -# Give a reasonable amount of time for the server to start up/shut down -TimeoutSec=300 - -# Place temp files in a secure directory, not /tmp -PrivateTmp=false - -Restart=on-failure - -RestartPreventExitStatus=1 - -# Sets open_files_limit -LimitNOFILE = 10000 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for SQL restart command. -Environment=MYSQLD_PARENT_PID=1 - -[Install] -WantedBy=multi-user.target diff --git a/plugins/mysql-yum/init.d/mysql8.4.service.tpl b/plugins/mysql-yum/init.d/mysql8.4.service.tpl deleted file mode 100644 index a1a05ecf25..0000000000 --- a/plugins/mysql-yum/init.d/mysql8.4.service.tpl +++ /dev/null @@ -1,63 +0,0 @@ -# It's not recommended to modify this file in-place, because it will be -# overwritten during package upgrades. If you want to customize, the -# best way is to use systemctl edit: -# -# $ systemctl edit mysqld.service -# -# this will create file -# -# /etc/systemd/system/mysqld.service.d/override.conf -# -# which be parsed after the file mysqld.service itself is parsed. -# -# For example, if you want to increase mysql's open-files-limit to 20000 -# add following when editing with command above: -# -# [Service] -# LimitNOFILE=20000 -# -# Or if you require to execute pre and post scripts in the unit file as root, set -# PermissionsStartOnly=true -# -# For more info about custom unit files, see systemd.unit(5) or -# http://fedoraproject.org/wiki/Systemd#How_do_I_customize_a_unit_file.2F_add_a_custom_unit_file.3F -# -# Don't forget to reload systemd daemon after you change unit configuration: -# root> systemctl --system daemon-reload - -[Unit] -Description=MySQL 8.0 database server -After=syslog.target -After=network.target - -[Service] -Type=notify -User=mysql -Group=mysql - -#ExecStartPre=/usr/libexec/mysql-check-socket -#ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n -# Note: we set --basedir to prevent probes that might trigger SELinux alarms, -# per bug #547485 -ExecStart={$SERVER_PATH}/mysql-yum/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-yum/etc/my.cnf --basedir={$SERVER_PATH}/mysql-yum/bin/usr --user=mysql -#ExecStartPost=/usr/libexec/mysql-check-upgrade -#ExecStopPost=/usr/libexec/mysql-wait-stop - -# Give a reasonable amount of time for the server to start up/shut down -TimeoutSec=300 - -# Place temp files in a secure directory, not /tmp -PrivateTmp=false - -Restart=on-failure - -RestartPreventExitStatus=1 - -# Sets open_files_limit -LimitNOFILE = 10000 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for SQL restart command. -Environment=MYSQLD_PARENT_PID=1 - -[Install] -WantedBy=multi-user.target diff --git a/plugins/mysql-yum/init.d/mysql9.0.service.tpl b/plugins/mysql-yum/init.d/mysql9.0.service.tpl deleted file mode 100644 index a1a05ecf25..0000000000 --- a/plugins/mysql-yum/init.d/mysql9.0.service.tpl +++ /dev/null @@ -1,63 +0,0 @@ -# It's not recommended to modify this file in-place, because it will be -# overwritten during package upgrades. If you want to customize, the -# best way is to use systemctl edit: -# -# $ systemctl edit mysqld.service -# -# this will create file -# -# /etc/systemd/system/mysqld.service.d/override.conf -# -# which be parsed after the file mysqld.service itself is parsed. -# -# For example, if you want to increase mysql's open-files-limit to 20000 -# add following when editing with command above: -# -# [Service] -# LimitNOFILE=20000 -# -# Or if you require to execute pre and post scripts in the unit file as root, set -# PermissionsStartOnly=true -# -# For more info about custom unit files, see systemd.unit(5) or -# http://fedoraproject.org/wiki/Systemd#How_do_I_customize_a_unit_file.2F_add_a_custom_unit_file.3F -# -# Don't forget to reload systemd daemon after you change unit configuration: -# root> systemctl --system daemon-reload - -[Unit] -Description=MySQL 8.0 database server -After=syslog.target -After=network.target - -[Service] -Type=notify -User=mysql -Group=mysql - -#ExecStartPre=/usr/libexec/mysql-check-socket -#ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n -# Note: we set --basedir to prevent probes that might trigger SELinux alarms, -# per bug #547485 -ExecStart={$SERVER_PATH}/mysql-yum/bin/usr/sbin/mysqld --defaults-file={$SERVER_PATH}/mysql-yum/etc/my.cnf --basedir={$SERVER_PATH}/mysql-yum/bin/usr --user=mysql -#ExecStartPost=/usr/libexec/mysql-check-upgrade -#ExecStopPost=/usr/libexec/mysql-wait-stop - -# Give a reasonable amount of time for the server to start up/shut down -TimeoutSec=300 - -# Place temp files in a secure directory, not /tmp -PrivateTmp=false - -Restart=on-failure - -RestartPreventExitStatus=1 - -# Sets open_files_limit -LimitNOFILE = 10000 - -# Set enviroment variable MYSQLD_PARENT_PID. This is required for SQL restart command. -Environment=MYSQLD_PARENT_PID=1 - -[Install] -WantedBy=multi-user.target diff --git a/plugins/mysql-yum/install.sh b/plugins/mysql-yum/install.sh deleted file mode 100755 index 3fb1a908f4..0000000000 --- a/plugins/mysql-yum/install.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/bash -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") - - -# cd /www/server/mdserver-web/plugins/mysql-yum && bash install.sh install 8.0 -# cd /www/server/mdserver-web/plugins/mysql-yum && bash install.sh uninstall 8.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-yum/index.py start 8.0 -# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/mysql-yum/index.py get_master_status 8.4 - - -action=$1 -type=$2 - -if id mysql &> /dev/null ;then - echo "mysql UID is `id -u mysql`" - echo "mysql Shell is `grep "^mysql:" /etc/passwd |cut -d':' -f7 `" -else - groupadd mysql - useradd -g mysql -s /usr/sbin/nologin mysql -fi - - - -if [ "${2}" == "" ];then - echo '缺少安装脚本...' - exit 0 -fi - -if [ ! -d $curPath/versions/$2 ];then - echo '缺少安装脚本2...' - exit 0 -fi - -if [ "${action}" == "uninstall" ];then - - cd ${rootPath} && python3 plugins/mysql-yum/index.py stop ${type} - cd ${rootPath} && python3 plugins/mysql-yum/index.py initd_uninstall ${type} - cd $curPath - - if [ -f /usr/lib/systemd/system/mysql-yum.service ] || [ -f /lib/systemd/system/mysql-yum.service ];then - systemctl stop mysql-yum - systemctl disable mysql-yum - rm -rf /usr/lib/systemd/system/mysql-yum.service - rm -rf /lib/systemd/system/mysql-yum.service - systemctl daemon-reload - fi -fi - -sh -x $curPath/versions/$2/install.sh $1 - -if [ "${action}" == "install" ];then -# #初始化 - cd ${rootPath} && python3 plugins/mysql-yum/index.py start ${type} - cd ${rootPath} && python3 plugins/mysql-yum/index.py initd_install ${type} -fi diff --git a/plugins/mysql-yum/js/mysql-yum.js b/plugins/mysql-yum/js/mysql-yum.js deleted file mode 100755 index 66836f384b..0000000000 --- a/plugins/mysql-yum/js/mysql-yum.js +++ /dev/null @@ -1,2966 +0,0 @@ - -function myPost(method,args,callback, title){ - - var _args = null; - if (typeof(args) == 'string'){ - _args = JSON.stringify(toArrayObject(args)); - } else { - _args = JSON.stringify(args); - } - - var _title = '正在获取...'; - if (typeof(title) != 'undefined'){ - _title = title; - } - - var loadT = layer.msg(_title, { icon: 16, time: 0, shade: 0.3 }); - $.post('/plugins/run', {name:'mysql-yum', func:method, args:_args}, function(data) { - layer.close(loadT); - if (!data.status){ - layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function myPostN(method,args,callback, title){ - - var _args = null; - if (typeof(args) == 'string'){ - _args = JSON.stringify(toArrayObject(args)); - } else { - _args = JSON.stringify(args); - } - - var _title = '正在获取...'; - if (typeof(title) != 'undefined'){ - _title = title; - } - $.post('/plugins/run', {name:'mysql-yum', func:method, args:_args}, function(data) { - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function myAsyncPost(method,args){ - var _args = null; - if (typeof(args) == 'string'){ - _args = JSON.stringify(toArrayObject(args)); - } else { - _args = JSON.stringify(args); - } - - var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); - return syncPost('/plugins/run', {name:'mysql', func:method, args:_args}); -} - - -function myPostCallbak(method, version, args,callback){ - var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); - - var req_data = {}; - req_data['name'] = 'mysql-yum'; - req_data['func'] = method; - req_data['script']='index_mysql_yum'; - args['version'] = version; - - - if (typeof(args) == 'string' && args == ''){ - req_data['args'] = JSON.stringify(toArrayObject(args)); - } else { - req_data['args'] = JSON.stringify(args); - } - - $.post('/plugins/callback', req_data, function(data) { - layer.close(loadT); - if (!data.status){ - layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function myPostCallbakN(method, version, args,callback){ - - var req_data = {}; - req_data['name'] = 'mysql-yum'; - req_data['func'] = method; - req_data['script']='index_mysql_yum'; - args['version'] = version; - - - if (typeof(args) == 'string' && args == ''){ - req_data['args'] = JSON.stringify(toArrayObject(args)); - } else { - req_data['args'] = JSON.stringify(args); - } - - $.post('/plugins/callback', req_data, function(data) { - if (!data.status){ - layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - if(typeof(callback) == 'function'){ - callback(data); - } - },'json'); -} - -function vaildPhpmyadmin(url,username,password){ - // console.log("Authorization: Basic " + btoa(username + ":" + password)); - $.ajax({ - type: "GET", - url: url, - dataType: 'json', - async: false, - username:username, - password:password, - headers: { - "Authorization": "Basic " + btoa(username + ":" + password) - }, - data: 'vaild', - success: function (){ - alert('Thanks for your comment!'); - } - }); -} - -function runInfo(){ - myPost('run_info','',function(data){ - - var rdata = $.parseJSON(data.data); - if (typeof(rdata['status']) != 'undefined'){ - layer.msg(rdata['msg'],{icon:0,time:2000,shade: [0.3, '#000']}); - return; - } - - // Com_select , Qcache_inserts - var cache_size = ((parseInt(rdata.Qcache_hits) / (parseInt(rdata.Qcache_hits) + parseInt(rdata.Qcache_inserts))) * 100).toFixed(2) + '%'; - if (cache_size == 'NaN%') cache_size = 'OFF'; - var Con = '
      \ - \ - \ - \ - \ - \ - \ -
      启动时间' + getLocalTime(rdata.Run) + '每秒查询' + parseInt(rdata.Questions / rdata.Uptime) + '
      总连接次数' + rdata.Connections + '每秒事务' + parseInt((parseInt(rdata.Com_commit) + parseInt(rdata.Com_rollback)) / rdata.Uptime) + '
      发送' + toSize(rdata.Bytes_sent) + 'File' + rdata.File + '
      接收' + toSize(rdata.Bytes_received) + 'Position' + rdata.Position + '
      \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
      活动/峰值连接数' + rdata.Threads_running + '/' + rdata.Max_used_connections + '若值过大,增加max_connections
      线程缓存命中率' + ((1 - rdata.Threads_created / rdata.Connections) * 100).toFixed(2) + '%若过低,增加thread_cache_size
      索引命中率' + ((1 - rdata.Key_reads / rdata.Key_read_requests) * 100).toFixed(2) + '%若过低,增加key_buffer_size
      Innodb索引命中率' + (rdata.Innodb_buffer_pool_read_requests / (rdata.Innodb_buffer_pool_read_requests+rdata.Innodb_buffer_pool_reads)).toFixed(2) + '%若过低,增加innodb_buffer_pool_size
      查询缓存命中率' + cache_size + '' + lan.soft.mysql_status_ps5 + '
      创建临时表到磁盘' + ((rdata.Created_tmp_disk_tables / rdata.Created_tmp_tables) * 100).toFixed(2) + '%若过大,尝试增加tmp_table_size
      已打开的表' + rdata.Open_tables + '若过大,增加table_cache_size
      没有使用索引的量' + rdata.Select_full_join + '若不为0,请检查数据表的索引是否合理
      没有索引的JOIN量' + rdata.Select_range_check + '若不为0,请检查数据表的索引是否合理
      排序后的合并次数' + rdata.Sort_merge_passes + '若值过大,增加sort_buffer_size
      锁表次数' + rdata.Table_locks_waited + '若值过大,请考虑增加您的数据库性能
      '; - $(".soft-man-con").html(Con); - }); -} - - -function myDbPos(){ - myPost('my_db_pos','',function(data){ - var con = '
      \ -
      \ - \ - \ - \ -
      '; - $(".soft-man-con").html(con); - - $('#btn_change_path').click(function(){ - var datadir = $("input[name='datadir']").val(); - myPost('set_db_pos','datadir='+datadir,function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,time:2000,shade: [0.3, '#000']}); - }); - }); - }); -} - -function myPort(){ - myPost('my_port','',function(data){ - var con = '
      \ -
      \ - \ - \ -
      '; - $(".soft-man-con").html(con); - - $('#btn_change_port').click(function(){ - var port = $("input[name='port']").val(); - myPost('set_my_port','port='+port,function(data){ - var rdata = $.parseJSON(data.data); - if (rdata.status){ - layer.msg('修改成功!',{icon:1,time:2000,shade: [0.3, '#000']}); - } else { - layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']}); - } - }); - }); - }); -} - -//数据库配置状态 -function myPerfOpt() { - //获取MySQL配置 - myPost('db_status','',function(data){ - var rdata = $.parseJSON(data.data); - if ( typeof(rdata.status) != 'undefined' && !rdata.status){ - layer.msg(rdata.msg, {icon:2}); - return; - } - - - // console.log(rdata); - var key_buffer_size = toSizeM(rdata.mem.key_buffer_size); - var query_cache_size = toSizeM(rdata.mem.query_cache_size); - var tmp_table_size = toSizeM(rdata.mem.tmp_table_size); - var innodb_buffer_pool_size = toSizeM(rdata.mem.innodb_buffer_pool_size); - var innodb_additional_mem_pool_size = toSizeM(rdata.mem.innodb_additional_mem_pool_size); - var innodb_log_buffer_size = toSizeM(rdata.mem.innodb_log_buffer_size); - - var sort_buffer_size = toSizeM(rdata.mem.sort_buffer_size); - var read_buffer_size = toSizeM(rdata.mem.read_buffer_size); - var read_rnd_buffer_size = toSizeM(rdata.mem.read_rnd_buffer_size); - var join_buffer_size = toSizeM(rdata.mem.join_buffer_size); - var thread_stack = toSizeM(rdata.mem.thread_stack); - var binlog_cache_size = toSizeM(rdata.mem.binlog_cache_size); - - var a = key_buffer_size + query_cache_size + tmp_table_size + innodb_buffer_pool_size + innodb_additional_mem_pool_size + innodb_log_buffer_size; - var b = sort_buffer_size + read_buffer_size + read_rnd_buffer_size + join_buffer_size + thread_stack + binlog_cache_size; - var memSize = a + rdata.mem.max_connections * b; - - - var memCon = '
      \ -
      最大使用内存: \ - \ - ' + lan.soft.mysql_set_maxmem + ': MB\ -
      \ -

      key_buffer_sizeMB, ' + lan.soft.mysql_set_key_buffer_size + '

      \ -

      query_cache_sizeMB, ' + lan.soft.mysql_set_query_cache_size + '

      \ -

      tmp_table_sizeMB, ' + lan.soft.mysql_set_tmp_table_size + '

      \ -

      innodb_buffer_pool_sizeMB, ' + lan.soft.mysql_set_innodb_buffer_pool_size + '

      \ -

      innodb_log_buffer_sizeMB, ' + lan.soft.mysql_set_innodb_log_buffer_size + '

      \ -

      innodb_additional_mem_pool_sizeMB

      \ -

      sort_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_sort_buffer_size + '

      \ -

      read_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_read_buffer_size + '

      \ -

      read_rnd_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_read_rnd_buffer_size + '

      \ -

      join_buffer_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_join_buffer_size + '

      \ -

      thread_stackKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_thread_stack + '

      \ -

      binlog_cache_sizeKB * ' + lan.soft.mysql_set_conn + ', ' + lan.soft.mysql_set_binlog_cache_size + '

      \ -

      thread_cache_size ' + lan.soft.mysql_set_thread_cache_size + '

      \ -

      table_open_cache ' + lan.soft.mysql_set_table_open_cache + '

      \ -

      max_connections ' + lan.soft.mysql_set_max_connections + '

      \ -
      \ -
      ' - - $(".soft-man-con").html(memCon); - - $(".conf_p input[name*='size'],.conf_p input[name='max_connections'],.conf_p input[name='thread_stack']").change(function() { - comMySqlMem(); - }); - - $(".conf_p select[name='mysql_set']").change(function() { - mySQLMemOpt($(this).val()); - comMySqlMem(); - }); - }); -} - -function reBootMySqld(){ - pluginOpService('mysql-yum','restart',''); -} - - -//设置MySQL配置参数 -function setMySQLConf() { - $.post('/system/system_total', '', function(memInfo) { - var memSize = memInfo['memTotal']; - var setSize = parseInt($("input[name='memSize']").val()); - - if(memSize < setSize){ - var errMsg = "错误,内存分配过高!

      物理内存: {1}MB
      最大使用内存: {2}MB
      可能造成的后果: 导致数据库不稳定,甚至无法启动MySQLd服务!"; - var msg = errMsg.replace('{1}',memSize).replace('{2}',setSize); - layer.msg(msg,{icon:2,time:5000}); - return; - } - - var query_cache_size = parseInt($("input[name='query_cache_size']").val()); - var query_cache_type = 0; - if (query_cache_size > 0) { - query_cache_type = 1; - } - var data = { - key_buffer_size: parseInt($("input[name='key_buffer_size']").val()), - query_cache_size: query_cache_size, - query_cache_type: query_cache_type, - tmp_table_size: parseInt($("input[name='tmp_table_size']").val()), - max_heap_table_size: parseInt($("input[name='tmp_table_size']").val()), - innodb_buffer_pool_size: parseInt($("input[name='innodb_buffer_pool_size']").val()), - innodb_log_buffer_size: parseInt($("input[name='innodb_log_buffer_size']").val()), - sort_buffer_size: parseInt($("input[name='sort_buffer_size']").val()), - read_buffer_size: parseInt($("input[name='read_buffer_size']").val()), - read_rnd_buffer_size: parseInt($("input[name='read_rnd_buffer_size']").val()), - join_buffer_size: parseInt($("input[name='join_buffer_size']").val()), - thread_stack: parseInt($("input[name='thread_stack']").val()), - binlog_cache_size: parseInt($("input[name='binlog_cache_size']").val()), - thread_cache_size: parseInt($("input[name='thread_cache_size']").val()), - table_open_cache: parseInt($("input[name='table_open_cache']").val()), - max_connections: parseInt($("input[name='max_connections']").val()) - }; - - myPost('set_db_status', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - reBootMySqld(); - },{ icon: rdata.status ? 1 : 2 }); - }); - },'json'); -} - - -//MySQL内存优化方案 -function mySQLMemOpt(opt) { - var query_size = parseInt($("input[name='query_cache_size']").val()); - switch (opt) { - case '0': - $("input[name='key_buffer_size']").val(8); - if (query_size) $("input[name='query_cache_size']").val(4); - $("input[name='tmp_table_size']").val(8); - $("input[name='innodb_buffer_pool_size']").val(16); - $("input[name='sort_buffer_size']").val(256); - $("input[name='read_buffer_size']").val(256); - $("input[name='read_rnd_buffer_size']").val(128); - $("input[name='join_buffer_size']").val(128); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(32); - $("input[name='thread_cache_size']").val(4); - $("input[name='table_open_cache']").val(32); - $("input[name='max_connections']").val(500); - break; - case '1': - $("input[name='key_buffer_size']").val(128); - if (query_size) $("input[name='query_cache_size']").val(64); - $("input[name='tmp_table_size']").val(64); - $("input[name='innodb_buffer_pool_size']").val(256); - $("input[name='sort_buffer_size']").val(768); - $("input[name='read_buffer_size']").val(768); - $("input[name='read_rnd_buffer_size']").val(512); - $("input[name='join_buffer_size']").val(1024); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(64); - $("input[name='thread_cache_size']").val(64); - $("input[name='table_open_cache']").val(128); - $("input[name='max_connections']").val(100); - break; - case '2': - $("input[name='key_buffer_size']").val(256); - if (query_size) $("input[name='query_cache_size']").val(128); - $("input[name='tmp_table_size']").val(384); - $("input[name='innodb_buffer_pool_size']").val(384); - $("input[name='sort_buffer_size']").val(768); - $("input[name='read_buffer_size']").val(768); - $("input[name='read_rnd_buffer_size']").val(512); - $("input[name='join_buffer_size']").val(2048); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(64); - $("input[name='thread_cache_size']").val(96); - $("input[name='table_open_cache']").val(192); - $("input[name='max_connections']").val(200); - break; - case '3': - $("input[name='key_buffer_size']").val(384); - if (query_size) $("input[name='query_cache_size']").val(192); - $("input[name='tmp_table_size']").val(512); - $("input[name='innodb_buffer_pool_size']").val(512); - $("input[name='sort_buffer_size']").val(1024); - $("input[name='read_buffer_size']").val(1024); - $("input[name='read_rnd_buffer_size']").val(768); - $("input[name='join_buffer_size']").val(2048); - $("input[name='thread_stack']").val(256); - $("input[name='binlog_cache_size']").val(128); - $("input[name='thread_cache_size']").val(128); - $("input[name='table_open_cache']").val(384); - $("input[name='max_connections']").val(300); - break; - case '4': - $("input[name='key_buffer_size']").val(512); - if (query_size) $("input[name='query_cache_size']").val(256); - $("input[name='tmp_table_size']").val(1024); - $("input[name='innodb_buffer_pool_size']").val(1024); - $("input[name='sort_buffer_size']").val(2048); - $("input[name='read_buffer_size']").val(2048); - $("input[name='read_rnd_buffer_size']").val(1024); - $("input[name='join_buffer_size']").val(4096); - $("input[name='thread_stack']").val(384); - $("input[name='binlog_cache_size']").val(192); - $("input[name='thread_cache_size']").val(192); - $("input[name='table_open_cache']").val(1024); - $("input[name='max_connections']").val(400); - break; - case '5': - $("input[name='key_buffer_size']").val(1024); - if (query_size) $("input[name='query_cache_size']").val(384); - $("input[name='tmp_table_size']").val(2048); - $("input[name='innodb_buffer_pool_size']").val(4096); - $("input[name='sort_buffer_size']").val(4096); - $("input[name='read_buffer_size']").val(4096); - $("input[name='read_rnd_buffer_size']").val(2048); - $("input[name='join_buffer_size']").val(8192); - $("input[name='thread_stack']").val(512); - $("input[name='binlog_cache_size']").val(256); - $("input[name='thread_cache_size']").val(256); - $("input[name='table_open_cache']").val(2048); - $("input[name='max_connections']").val(500); - break; - } -} - -//计算MySQL内存开销 -function comMySqlMem() { - var key_buffer_size = parseInt($("input[name='key_buffer_size']").val()); - var query_cache_size = parseInt($("input[name='query_cache_size']").val()); - var tmp_table_size = parseInt($("input[name='tmp_table_size']").val()); - var innodb_buffer_pool_size = parseInt($("input[name='innodb_buffer_pool_size']").val()); - var innodb_additional_mem_pool_size = parseInt($("input[name='innodb_additional_mem_pool_size']").val()); - var innodb_log_buffer_size = parseInt($("input[name='innodb_log_buffer_size']").val()); - - var sort_buffer_size = $("input[name='sort_buffer_size']").val() / 1024; - var read_buffer_size = $("input[name='read_buffer_size']").val() / 1024; - var read_rnd_buffer_size = $("input[name='read_rnd_buffer_size']").val() / 1024; - var join_buffer_size = $("input[name='join_buffer_size']").val() / 1024; - var thread_stack = $("input[name='thread_stack']").val() / 1024; - var binlog_cache_size = $("input[name='binlog_cache_size']").val() / 1024; - var max_connections = $("input[name='max_connections']").val(); - - var a = key_buffer_size + query_cache_size + tmp_table_size + innodb_buffer_pool_size + innodb_additional_mem_pool_size + innodb_log_buffer_size - var b = sort_buffer_size + read_buffer_size + read_rnd_buffer_size + join_buffer_size + thread_stack + binlog_cache_size - var memSize = a + max_connections * b - $("input[name='memSize']").val(memSize.toFixed(2)); -} - -function syncGetDatabase(){ - myPost('sync_get_databases', null, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - dbList(); - },{ icon: rdata.status ? 1 : 2 }); - }); -} - -function syncToDatabase(type){ - var data = []; - $('input[type="checkbox"].check:checked').each(function () { - if (!isNaN($(this).val())) data.push($(this).val()); - }); - var postData = 'type='+type+'&ids='+JSON.stringify(data); - myPost('sync_to_databases', postData, function(data){ - var rdata = $.parseJSON(data.data); - // console.log(rdata); - showMsg(rdata.msg,function(){ - dbList(); - },{ icon: rdata.status ? 1 : 2 }); - }); -} - -function setRootPwd(type, pwd){ - if (type==1){ - var password = $("#MyPassword").val(); - myPost('set_root_pwd', {password:password}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - return; - } - - var index = layer.open({ - type: 1, - area: '500px', - title: '修改数据库密码', - closeBtn: 1, - shift: 5, - btn:["提交", "关闭", "复制ROOT密码", "强制修改"], - shadeClose: true, - content: "

      \ -
      \ - root密码\ -
      \ - \ -
      \ -
      \ -
      ", - yes:function(layerIndex){ - var password = $("#MyPassword").val(); - myPost('set_root_pwd', {password:password}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(layerIndex); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - }, - btn3:function(){ - var password = $("#MyPassword").val(); - copyText(password); - return false; - }, - btn4:function(layerIndex){ - layer.confirm('强制修改,是为了在重建时使用,确定强制?', { - btn: ['确定', '取消'] - }, function(index, layero){ - layer.close(index); - var password = $("#MyPassword").val(); - myPost('set_root_pwd', {password:password,force:'1'}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(layerIndex); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - }); - return false; - } - }); -} - -function showHidePass(obj){ - var a = "glyphicon-eye-open"; - var b = "glyphicon-eye-close"; - - if($(obj).hasClass(a)){ - $(obj).removeClass(a).addClass(b); - $(obj).prev().text($(obj).prev().attr('data-pw')) - } - else{ - $(obj).removeClass(b).addClass(a); - $(obj).prev().text('***'); - } -} - -function checkSelect(){ - setTimeout(function () { - var num = $('input[type="checkbox"].check:checked').length; - // console.log(num); - if (num == 1) { - $('button[batch="true"]').hide(); - $('button[batch="false"]').show(); - }else if (num>1){ - $('button[batch="true"]').show(); - $('button[batch="false"]').show(); - }else{ - $('button[batch="true"]').hide(); - $('button[batch="false"]').hide(); - } - },5) -} - -function setDbRw(id,username,val){ - myPost('set_db_rw',{id:id,username:username,rw:val}, function(data){ - var rdata = $.parseJSON(data.data); - // layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']}); - showMsg(rdata.msg, function(){ - dbList(); - },{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']}, 2000); - - }); -} - -function setDbAccess(username){ - myPost('get_db_access','username='+username, function(data){ - var rdata = $.parseJSON(data.data); - if (!rdata.status){ - layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); - return; - } - - var index = layer.open({ - type: 1, - area: '500px', - title: '设置数据库权限', - closeBtn: 1, - shift: 5, - btn:["提交","取消"], - shadeClose: true, - content: "
      \ -
      \ - 访问权限\ -
      \ - \ -
      \ -
      \ -
      ", - success:function(){ - if (rdata.msg == '127.0.0.1'){ - $('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true); - } else if (rdata.msg == '%'){ - $('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true); - } else if ( rdata.msg == 'ip' ){ - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } else { - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index){ - var data = $("#set_db_access").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['access']){ - dataObj['access'] = dataObj['dataAccess']; - if ( dataObj['dataAccess'] == 'ip'){ - if (dataObj['address']==''){ - layer.msg('IP地址不能空!',{icon:2,shade: [0.3, '#000']}); - return; - } - dataObj['access'] = dataObj['address']; - } - } - dataObj['username'] = username; - myPost('set_db_access', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - } - }); - - }); -} - -function fixDbAccess(username){ - myPost('fix_db_access', '', function(rdata){ - var rdata = $.parseJSON(rdata.data); - showMsg(rdata.msg,function(){ - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); -} - -function setDbPass(id, username, password){ - layer.open({ - type: 1, - area: '500px', - title: '修改数据库密码', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["提交","关闭"], - content: "
      \ -
      \ - 用户名\ -
      \ -
      \ -
      \ - 密码\ -
      \ - \ -
      \ -
      \ - \ -
      ", - yes:function(index){ - // var data = $("#mod_pwd").serialize(); - var data = {}; - data['name'] = $('input[name=name]').val(); - data['password'] = $('#MyPassword').val(); - data['id'] = $('input[name=id]').val(); - myPost('set_user_pwd', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - dbList(); - },{icon: rdata.status ? 1 : 2}); - }); - } - }); -} - -function addDatabase(type){ - layer.open({ - type: 1, - area: '500px', - title: '添加数据库', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["提交","关闭"], - content: "
      \ -
      \ - 数据库名\ -
      \ - \ -
      \ -
      \ -
      用户名
      \ -
      \ - 密码\ -
      \ -
      \ -
      \ - 访问权限\ -
      \ - \ -
      \ -
      \ - \ -
      ", - success:function(){ - $("input[name='name']").keyup(function(){ - var v = $(this).val(); - $("input[name='db_user']").val(v); - $("input[name='ps']").val(v); - }); - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index) { - var data = $("#add_db").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['address']){ - dataObj['address'] = dataObj['dataAccess']; - } - myPost('add_db', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - layer.close(index); - dbList(); - } - },{icon: rdata.status ? 1 : 2}, 2000); - }); - } - }); -} - -function delDb(id, name){ - safeMessage('删除['+name+']','您真的要删除['+name+']吗?',function(){ - var data='id='+id+'&name='+name; - myPost('del_db', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - dbList(); - },{icon: rdata.status ? 1 : 2}, 600); - }); - }); -} - -function delDbBatch(){ - var arr = []; - $('input[type="checkbox"].check:checked').each(function () { - var _val = $(this).val(); - var _name = $(this).parent().next().text(); - if (!isNaN(_val)) { - arr.push({'id':_val,'name':_name}); - } - }); - - safeMessage('批量删除数据库','您共选择了[2]个数据库,删除后将无法恢复,真的要删除吗?',function(){ - var i = 0; - $(arr).each(function(){ - var data = myAsyncPost('del_db', this); - var rdata = $.parseJSON(data.data); - if (!rdata.status){ - layer.msg(rdata.msg,{icon:2,time:2000,shade: [0.3, '#000']}); - } - i++; - }); - - var msg = '成功删除['+i+']个数据库!'; - showMsg(msg,function(){ - dbList(); - },{icon: 1}, 600); - }); -} - - -function setDbPs(id, name, obj) { - var _span = $(obj); - var _input = $(""); - _span.hide().after(_input); - _input.focus(); - _input.blur(function(){ - $(this).remove(); - var ps = _input.val(); - _span.text(ps).show(); - var data = {name:name,id:id,ps:ps}; - myPost('set_db_ps', data, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - }); - }); - _input.keyup(function(){ - if(event.keyCode == 13){ - _input.trigger('blur'); - } - }); -} - -function openPhpmyadmin(name,username,password){ - $.post('/plugins/run', {'name':'phpmyadmin','func':'plugins_db_support'}, function(data){ - var rdata = $.parseJSON(data.data); - - if (rdata.data['installed'] != 'ok'){ - layer.msg('phpMyAdmin未安装!',{icon:2,shade: [0.3, '#000']}); - return; - } - - if (rdata.data['status'] != 'start'){ - layer.msg('phpMyAdmin未启动',{icon:2,shade: [0.3, '#000']}); - return; - } - - if (rdata.data['cfg']['choose'] != 'mysql-yum'){ - layer.msg('当前为['+rdata.data['cfg']['choose'] + ']模式,若要使用请修改phpMyAdmin访问切换.',{icon:2,shade: [0.3, '#000']}); - return; - } - var home_page = rdata.data['home_page']; - $("#toPHPMyAdmin").attr('action',home_page); - if($("#toPHPMyAdmin").attr('action').indexOf('phpmyadmin') == -1){ - layer.msg('请先安装phpMyAdmin',{icon:2,shade: [0.3, '#000']}); - setTimeout(function(){ window.location.href = '/soft'; },3000); - return; - } - //检查版本 - bigVer = rdata.data['version']; - if (bigVer>=4.5){ - - setTimeout(function(){ - $("#toPHPMyAdmin").submit(); - },2000); - layer.msg('phpMyAdmin['+data.data+']需要手动登录😭',{icon:16,shade: [0.3, '#000'],time:4000}); - - } else{ - var murl = $("#toPHPMyAdmin").attr('action'); - $("#pma_username").val(username); - $("#pma_password").val(password); - $("#db").val(name); - - layer.msg('正在打开phpMyAdmin',{icon:16,shade: [0.3, '#000'],time:2000}); - - setTimeout(function(){ - $("#toPHPMyAdmin").submit(); - },2000); - } - - },'json'); -} - -function delBackup(filename, name, path){ - if(typeof(path) == "undefined"){ - path = ""; - } - myPost('delete_db_backup',{filename:filename,path:path},function(){ - layer.msg('执行成功!'); - setTimeout(function(){ - setBackupReq(name); - },2000); - }); -} - -function downloadBackup(file){ - window.open('/files/download?filename='+encodeURIComponent(file)); -} - -function importBackup(file,name){ - myPost('import_db_backup',{file:file,name:name}, function(data){ - // console.log(data); - layer.msg('执行成功!'); - }); -} - -function importBackupProgress(file,name){ - myPost('import_db_backup_progress',{file:file,name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.open({ - title: "手动导入命令CMD【显示进度】", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
      \ -
      \ -
      '+rdata.data+'
      \ -
      \ -
      ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); -} - - -function importDbExternal(file,name){ - myPost('import_db_external',{file:file,name:name}, function(data){ - layer.msg('执行成功!'); - }); -} - -function importDbExternalProgress(file,name){ - myPost('import_db_external_progress',{file:file,name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.open({ - title: "手动导入命令CMD【显示进度】", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
      \ -
      \ -
      '+rdata.data+'
      \ -
      \ -
      ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); -} - -function setLocalImport(db_name){ - - //上传文件 - function uploadDbFiles(upload_dir){ - var up_db = layer.open({ - type:1, - closeBtn: 1, - title:"上传导入文件["+upload_dir+']', - area: ['500px','300px'], - shadeClose:false, - content:'
      \ - \ - \ - \ - \ - \ - \ - 文件编码:\ - \ - \ - \ -
        \ -
        ', - success:function(){ - $('#filesClose').click(function(){ - layer.close(up_db); - }); - } - - }); - uploadStart(function(){ - getList(); - layer.close(up_db); - }); - } - - function getList(){ - myPost('get_db_backup_import_list',{}, function(data){ - var rdata = $.parseJSON(data.data); - - var file_list = rdata.data.list; - var upload_dir = rdata.data.upload_dir; - - var tbody = ''; - for (var i = 0; i < file_list.length; i++) { - tbody += '\ - ' + file_list[i]['name'] + '\ - ' + file_list[i]['size'] + '\ - ' + file_list[i]['time'] + '\ - \ - 导入 | \ - 导入进度 | \ - 删除\ - \ - '; - } - - $('#import_db_file_list').html(tbody); - $('input[name="upload_dir"]').val(upload_dir); - - $("#import_db_file_list .del").on('click',function(){ - var index = $(this).attr('index'); - var filename = file_list[index]["name"]; - myPost('delete_db_backup',{filename:filename,path:upload_dir},function(){ - showMsg('执行成功!', function(){ - getList(); - },{icon:1},2000); - }); - }); - }); - } - - var layerIndex = layer.open({ - type: 1, - title: "从文件导入数据", - area: ['700px', '380px'], - closeBtn: 1, - shadeClose: false, - content: '
        \ -
        \ - \ -
        \ -
        \ - \ -
        \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
        文件名称文件大小备份时间操作
        \ -
        \ -
          \ -
        • 仅支持sql、zip、sql.gz、(tar.gz|gz|tgz)
        • \ -
        • zip、tar.gz压缩包结构:test.zip或test.tar.gz压缩包内,必需包含test.sql
        • \ -
        • 若文件过大,您还可以使用SFTP工具,将数据库文件上传到/www/backup/import
        • \ -
        \ -
        \ -
        ', - success:function(index){ - $('#btn_file_upload').click(function(){ - var upload_dir = $('input[name="upload_dir"]').val(); - uploadDbFiles(upload_dir); - }); - - getList(); - }, - }); - - -} - -function setBackup(db_name){ - var layerIndex = layer.open({ - type: 1, - title: "数据库备份详情", - area: ['700px', '280px'], - closeBtn: 1, - shadeClose: false, - content: '
        \ -
        \ - \ - \ -
        \ -
        \ -
        \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
        文件名称文件大小备份时间操作
        \ -
        \ -
        \ -
        ', - success:function(index){ - $('#btn_backup').click(function(){ - myPost('set_db_backup',{name:db_name}, function(data){ - showMsg('执行成功!', function(){ - setBackupReq(db_name); - }, {icon:1}, 2000); - }); - }); - - $('#btn_local_import').click(function(){ - setLocalImport(db_name); - }); - - setBackupReq(db_name); - }, - }); -} - - -function setBackupReq(db_name, obj){ - myPost('get_db_backup_list', {name:db_name}, function(data){ - var rdata = $.parseJSON(data.data); - var tbody = ''; - for (var i = 0; i < rdata.data.length; i++) { - tbody += '\ - ' + rdata.data[i]['name'] + '\ - ' + rdata.data[i]['size'] + '\ - ' + rdata.data[i]['time'] + '\ - \ - 导入 | \ - 导入进度 | \ - 下载 | \ - 删除\ - \ - '; - } - $('#database_table tbody').html(tbody); - }); -} - -function dbList(page, search){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - if(typeof(search) != 'undefined'){ - _data['search'] = search; - } - myPost('get_db_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - for(i in rdata.data){ - list += ''; - list +=''; - list += '' + rdata.data[i]['name'] +''; - list += '' + rdata.data[i]['username'] +''; - list += '' + - '***' + - ''+ - ''+ - ''; - - - list += ''+rdata.data[i]['ps']+''; - list += ''; - - list += ''+(rdata.data[i]['is_backup']?'已备份':'未备份') +' | '; - - var rw = ''; - var rw_change = 'all'; - if (typeof(rdata.data[i]['rw'])!='undefined'){ - var rw_val = '读写'; - if (rdata.data[i]['rw'] == 'all'){ - rw_val = "所有"; - rw_change = 'rw'; - } else if (rdata.data[i]['rw'] == 'rw'){ - rw_val = "读写"; - rw_change = 'r'; - } else if (rdata.data[i]['rw'] == 'r'){ - rw_val = "只读"; - rw_change = 'all'; - } - rw = ''+rw_val+' | '; - } - - - list += '管理 | ' + - '工具 | ' + - '权限 | ' + - rw + - '改密 | ' + - '删除' + - ''; - list += ''; - } - - // - var con = '
        \ - \ - \ - \ - \ - \ - \ - \ - \ -
        \ -
        \ - \ - \ - \ - \ - \ - '+ - // ''+ - '\ - \ - \ - '+ list +'\ -
        数据库名用户名密码备份备注操作
        \ -
        \ -
        \ -
        \ - 同步选中\ - 同步所有\ - 从服务器获取\ -
        \ -
        \ -
        '; - - con += ''; - - $(".soft-man-con").html(con); - $('#databasePage').html(rdata.page); - - readerTableChecked(); - }); -} - - -function myBinRollingLogs(_name, func, _args, line){ - - var file_line = 100; - if ( typeof(line) != 'undefined' ){ - file_line = line; - } - - var reqTimer = null; - - function requestLogs(func,file,line){ - myPostCallbakN(func,'',{'file':file,"line":line}, function(rdata){ - var data = rdata.data.data; - var cmd = rdata.data.cmd; - if(data == '') { - data = '当前没有日志!'; - } - - $('#my_rolling_cmd').html(cmd); - - $('#my_rolling_copy').click(function(){ - copyText(cmd); - }); - - var ebody = ''; - $("#my_rolling_logs").html(ebody); - var ob = document.getElementById('roll_info_log'); - ob.scrollTop = ob.scrollHeight; - }); - } - - - layer.open({ - type: 1, - title: _name + '日志', - area: ['800px','700px'], - end: function(){ - if (reqTimer){ - clearInterval(reqTimer); - } - }, - content:'
        \ -
        \ - \ - \ - \ - \ -
        cmd
        \ -
        \ -
        \ -
        \ - \ -
        ', - success:function(){ - var fileName = _args['file']; - requestLogs(func,fileName,file_line); - reqTimer = setInterval(function(){ - requestLogs(func,fileName,file_line); - },1000); - } - }); -} - -function myBinLogsRender(page){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - _data['tojs'] = 'myBinLogsRender'; - myPost('binlog_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - // console.log(rdata); - var list = ''; - for(i in rdata.data){ - list += ''; - - list += '' + rdata.data[i]['name'] +''; - list += '' + toSize(rdata.data[i]['size'])+''; - list += '' + rdata.data[i]['time'] +''; - - - list += ''; - list += '查看 | '; - list += '解码查看'; - list += ''; - } - - if (rdata.data.length ==0){ - list = '无数据'; - } - - $("#binlog_list tbody").html(list); - $('#binlog_page').html(rdata.page); - - - $('#binlog_list .look').click(function(){ - var i = $(this).data('index'); - var file = rdata.data[i]['name']; - myBinRollingLogs('查看BINLOG','binLogListLook',{'file':file },100); - }); - - $('#binlog_list .look_decode').click(function(){ - var i = $(this).data('index'); - var file = rdata.data[i]['name']; - myBinRollingLogs('查看解码BINLOG','binLogListLookDecode',{'file':file },100); - }); - }); -} - -function myBinLogs(){ - var con = '
        \ - \ - \ -
        \ -
        \ - \ - \ - \ - \ - \ - \ - \ -
        文件名称大小时间操作
        \ -
        \ -
        \ -
        \ -
        '; - $(".soft-man-con").html(con); - myBinLogsRender(1); - - $('.soft-man-con .relay_trace').click(function(){ - myBinRollingLogs('中继日志跟踪','binLogListTraceRelay',{'file':''},100); - }); - - $('.soft-man-con .binlog_trace').click(function(){ - myBinRollingLogs('最新BINLOG日志跟踪','binLogListTraceBinLog',{'file':''},100); - }); -} - -function myLogs(){ - - myPost('bin_log', {status:1}, function(data){ - var rdata = $.parseJSON(data.data); - - var line_status = "" - if (rdata.status){ - line_status = '\ - '; - } else { - line_status = ''; - } - - var limitCon = '

        \ - 二进制日志 ' + toSize(rdata.msg) + '\ - '+line_status+'\ -

        错误日志

        \ - \ -

        '; - $(".soft-man-con").html(limitCon); - - //设置二进制日志 - $(".btn-bin").click(function () { - myPost('bin_log', 'close=change', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){myLogs();}, 2000); - }); - }); - - $(".clean-btn-bin").click(function () { - myPost('clean_bin_log', '', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){myLogs();}, 2000); - }); - }); - - //清空日志 - $(".btn-clear").click(function () { - myPost('error_log', 'close=1', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){myLogs();}, 2000); - }); - }) - - myPost('error_log', 'p=1', function(data){ - var rdata = $.parseJSON(data.data); - var error_body = ''; - if (rdata.status){ - error_body = rdata.data; - } else { - error_body = rdata.msg; - } - $("#error_log").html(error_body); - var ob = document.getElementById('error_log'); - ob.scrollTop = ob.scrollHeight; - }); - }); -} - - -function repCheckeds(tables) { - var dbs = [] - if (tables) { - dbs.push(tables) - } else { - var db_tools = $("input[value^='dbtools_']"); - for (var i = 0; i < db_tools.length; i++) { - if (db_tools[i].checked) dbs.push(db_tools[i].value.replace('dbtools_', '')); - } - } - - if (dbs.length < 1) { - layer.msg('请至少选择一张表!', { icon: 2 }); - return false; - } - return dbs; -} - -function repDatabase(db_name, tables) { - dbs = repCheckeds(tables); - - myPost('repair_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - repTools(db_name, true); - },'已送修复指令,请稍候...'); -} - - -function optDatabase(db_name, tables) { - dbs = repCheckeds(tables); - - myPost('opt_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - repTools(db_name, true); - },'已送优化指令,请稍候...'); -} - -function toDatabaseType(db_name, tables, type){ - dbs = repCheckeds(tables); - myPost('alter_table', { db_name: db_name, tables: JSON.stringify(dbs),table_type: type }, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); - repTools(db_name, true); - }, '已送引擎转换指令,请稍候...'); -} - - -function selectedTools(my_obj, db_name) { - var is_checked = false - - if (my_obj) is_checked = my_obj.checked; - var db_tools = $("input[value^='dbtools_']"); - var n = 0; - for (var i = 0; i < db_tools.length; i++) { - if (my_obj) db_tools[i].checked = is_checked; - if (db_tools[i].checked) n++; - } - if (n > 0) { - var my_btns = '\ - \ - \ - ' - $("#db_tools").html(my_btns); - } else { - $("#db_tools").html(''); - } -} - -function repTools(db_name, res){ - myPost('get_db_info', {name:db_name}, function(data){ - var rdata = $.parseJSON(data.data); - var types = { InnoDB: "MyISAM", MyISAM: "InnoDB" }; - var tbody = ''; - for (var i = 0; i < rdata.tables.length; i++) { - if (!types[rdata.tables[i].type]) continue; - tbody += '\ - \ - ' + rdata.tables[i].table_name + '\ - ' + rdata.tables[i].type + '\ - ' + rdata.tables[i].collation + '\ - ' + rdata.tables[i].rows_count + '\ - ' + rdata.tables[i].data_size + '\ - \ - 修复 |\ - 优化 |\ - 转为' + types[rdata.tables[i].type] + '\ - \ - ' - } - - if (res) { - $(".gztr").html(tbody); - $("#db_tools").html(''); - $("input[type='checkbox']").attr("checked", false); - $(".tools_size").html('大小:' + rdata.data_size); - return; - } - - layer.open({ - type: 1, - title: "MySQL工具箱【" + db_name + "】", - area: ['780px', '580px'], - closeBtn: 1, - shadeClose: false, - content: '
        \ - \ -
        \ -
        \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - ' + tbody + '\ -
        表名引擎字符集行数大小操作
        \ -
        \ -
        \ -
          \ -
        • 【修复】尝试使用REPAIR命令修复损坏的表,仅能做简单修复,若修复不成功请考虑使用myisamchk工具
        • \ -
        • 【优化】执行OPTIMIZE命令,可回收未释放的磁盘空间,建议每月执行一次
        • \ -
        • 【转为InnoDB/MyISAM】转换数据表引擎,建议将所有表转为InnoDB
        • \ -
        ' - }); - tableFixed('database_fix'); - }); -} - - -function setDbMaster(name){ - myPost('set_db_master', {name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - masterOrSlaveConf(); - }, 2000); - }); -} - - -function setDbSlave(name){ - myPost('set_db_slave', {name:name}, function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - masterOrSlaveConf(); - }, 2000); - }); -} - - -function addMasterRepSlaveUser(){ - layer.open({ - type: 1, - area: '500px', - title: '添加同步账户', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["提交","取消"], - content: "
        \ -
        用户名
        \ -
        \ - 密码\ -
        \ -
        \ - \ -
        ", - success:function(){ - $("input[name='name']").keyup(function(){ - var v = $(this).val(); - $("input[name='db_user']").val(v); - $("input[name='ps']").val(v); - }); - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index){ - var data = $("#add_master").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['address']){ - dataObj['address'] = dataObj['dataAccess']; - } - - myPost('add_master_rep_slave_user', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - if (rdata.status){ - getMasterRepSlaveList(); - } - },{icon: rdata.status ? 1 : 2},600); - }); - } - }); -} - - - -function updateMasterRepSlaveUser(username, password){ - - var index = layer.open({ - type: 1, - area: '500px', - title: '更新账户', - closeBtn: 1, - shift: 5, - shadeClose: true, - content: "
        \ -
        用户名
        \ -
        \ - 密码\ -
        \ -
        \ - \ -
        \ - \ -
        \ -
        ", - }); - - $('#submit_update_master').click(function(){ - var data = $("#update_master").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - myPost('update_master_rep_slave_user', data, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getMasterRepSlaveList(); - } - $('.layui-layer-close1').click(); - },{icon: rdata.status ? 1 : 2},600); - }); - }); -} - -function getMasterRepSlaveUserCmd(username, db=''){ - myPost('get_master_rep_slave_user_cmd', {username:username,db:db}, function(data){ - var rdata = $.parseJSON(data.data); - - if (!rdata['status']){ - layer.msg(rdata['msg']); - return; - } - - var cmd = rdata.data['cmd']; - - var loadOpen = layer.open({ - type: 1, - title: '同步命令', - area: '500px', - content:"
        \ -
        "+cmd+"
        \ -
        \ - \ -
        \ -
        ", - }); - }); -} - -function delMasterRepSlaveUser(username){ - myPost('del_master_rep_slave_user', {username:username}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg, function(){ - getMasterRepSlaveList(); - },{icon: rdata.status ? 1 : 2},1000) - }); -} - - -function setDbMasterAccess(username){ - myPost('get_db_access','username='+username, function(data){ - var rdata = $.parseJSON(data.data); - if (!rdata.status){ - layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); - return; - } - - var index = layer.open({ - type: 1, - area: '500px', - title: '设置数据库权限', - closeBtn: 1, - shift: 5, - btn:["提交","取消"], - shadeClose: true, - content: "
        \ -
        \ - 访问权限\ -
        \ - \ -
        \ -
        \ -
        ", - success:function(){ - if (rdata.msg == '127.0.0.1'){ - $('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true); - } else if (rdata.msg == '%'){ - $('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true); - } else if ( rdata.msg == 'ip' ){ - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } else { - $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); - $('select[name="dataAccess"]').after(""); - } - - $('select[name="dataAccess"]').change(function(){ - var v = $(this).val(); - if (v == 'ip'){ - $(this).after(""); - } else { - $('#dataAccess_subid').remove(); - } - }); - }, - yes:function(index){ - var data = $("#set_db_access").serialize(); - data = decodeURIComponent(data); - var dataObj = toArrayObject(data); - if(!dataObj['access']){ - dataObj['access'] = dataObj['dataAccess']; - if ( dataObj['dataAccess'] == 'ip'){ - if (dataObj['address']==''){ - layer.msg('IP地址不能空!',{icon:2,shade: [0.3, '#000']}); - return; - } - dataObj['access'] = dataObj['address']; - } - } - dataObj['username'] = username; - myPost('set_dbmaster_access', dataObj, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - layer.close(index); - },{icon: rdata.status ? 1 : 2}); - }); - } - }); - - }); -} - - -function resetMaster(){ - myPost('reset_master', '', function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - },{icon: rdata.status ? 1 : 2}); - },'正在执行重置master命令[reset master]'); -} - -function getMasterRepSlaveList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - myPost('get_master_rep_slave_list', _data, function(data){ - // console.log(data); - var rdata = []; - try { - rdata = $.parseJSON(data.data); - } catch(e){ - console.log(e); - } - var list = ''; - // console.log(rdata['data']); - var user_list = rdata['data']; - for (i in user_list) { - // console.log(i); - var name = user_list[i]['username']; - var password = user_list[i]['password']; - list += ''+name+'\ - '+password+'\ - \ - 修改 | \ - 删除 | \ - 权限 | \ - 从库同步命令\ - \ - '; - } - - $('#get_master_rep_slave_list_page tbody').html(list); - $('.dataTables_paginate_4').html(rdata['page']); - }); -} - -function getMasterRepSlaveListPage(){ - var page = '
        '; - page += '
        添加同步账户
        '; - - var loadOpen = layer.open({ - type: 1, - title: '同步账户列表', - area: '500px', - content:"
        \ -
        \ -
        \ - \ - \ -
        用户名密码操作
        \ - "+page +"\ -
        \ -
        ", - success:function(){ - getMasterRepSlaveList(); - } - }); -} - - -function deleteSlave(sign){ - myPost('delete_slave', {sign:sign}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata['msg'], function(){ - masterOrSlaveConf(); - },{icon:rdata.status?1:2,time:3000},3000); - }); -} - - -function getFullSyncStatus(db){ - var timeId = null; - - myPost('get_slave_list', {page:1,page_size:100}, function(data){ - var rdata = $.parseJSON(data.data); - var rsource = rdata.data; - - if (db == 'ALL' && rsource.length>1){ - layer.msg("多主不支持该模式!",{icon:2}); - return; - } - - var dataSource = ''; - if (rsource.length>1){ - var sourceList = ''; - for (var i = 0; i < rsource.length; i++) { - if ('Channel_Name' in rsource[i]){ - sourceList += ''; - } - } - - dataSource = "

        \ - 同步数据源:\ - \ -

        "; - } - - layer.open({ - type: 1, - title: '全量同步['+db+']', - area: '500px', - content:"
        \ -
        \ - "+dataSource+"\ - \ -
        \ -
        0%
        \ -
        \ -
        \ -
        \ - 开始\ - 手动命令\ -
        \ -
        ", - cancel: function(){ - clearInterval(timeId); - }, - success:function(){ - $('#begin_full_sync').click(function(){ - var val = $(this).data('status'); - var sign = ''; - if (dataSource !=''){ - sign = $('select[name="data_source"]').val(); - } - if (val == 'init'){ - fullSync(db, sign, 1); - timeId = setInterval(function(){ - fullSync(db,sign,0); - }, 1000); - $(this).data('status','starting'); - $('#begin_full_sync').text("同步中"); - } else { - layer.msg("正在同步中..",{icon:0}); - } - }); - - $('#full_sync_cmd').click(function(){ - myPostN('full_sync_cmd', {'db':db,'sign':''}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - layer.open({ - title: "手动执行命令CMD", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
        \ -
        \ -
        '+rdata.data+'
        \ -
        \ -
        ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); - }); - } - }); - }); - - function fullSync(db,sign,begin){ - - myPostN('full_sync', {db:db,sign:sign,begin:begin}, function(data){ - var rdata = $.parseJSON(data.data); - $('#full_msg').text(rdata['msg']); - $('.progress-bar').css('width',rdata['progress']+'%'); - $('.progress-bar').text(rdata['progress']+'%'); - - if (rdata['code']==6 ||rdata['code']<0){ - layer.msg(rdata['msg']); - clearInterval(timeId); - $('#begin_full_sync').text("同步结束,再次同步?"); - $("#begin_full_sync").attr('data-status','init'); - } - }); - } -} - -function dataSyncVerify(db){ - var reqTimer = null; - - function requestLogs(layerIndex){ - myPostN('sync_database_repair_log', {db:db, sign:'',op:'get'}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - - if(!rdata.status) { - layer.close(layerIndex); - layer.msg(rdata.msg,{icon:2, time:2000}); - clearInterval(reqTimer); - return; - }; - - if (rdata.msg == ''){ - rdata.msg = '暂无数据!'; - } - - $("#data_verify_log").html(rdata.msg); - //滚动到最低 - var ob = document.getElementById('data_verify_log'); - ob.scrollTop = ob.scrollHeight; - }); - } - - layer.open({ - type: 1, - title: '同步数据库['+db+']数据校验', - area: '500px', - btn:[ "开始","取消","手动"], - content:"
        \ - "+'
        '+"\
        -            
        ", - cancel: function(){ - if (reqTimer){ - clearInterval(reqTimer); - } - }, - yes:function(index,layer_index){ - myPostN('sync_database_repair_log', {db:db, sign:'',op:'do'}, function(data){}); - layer.msg("执行成功"); - - requestLogs(layer_index); - reqTimer = setInterval(function(){ - requestLogs(layer_index); - },3000); - }, - success:function(){ - }, - btn3: function(){ - myPostN('sync_database_repair_log', {db:db, sign:'',op:'cmd'}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - layer.open({ - title: "手动执行命令CMD", - area: ['600px', '180px'], - type:1, - closeBtn: 1, - shadeClose: false, - btn:["复制","取消"], - content: '
        \ -
        \ -
        '+rdata.data+'
        \ -
        \ -
        ', - success:function(){ - copyText(rdata.data); - }, - yes:function(){ - copyText(rdata.data); - } - }); - }); - return false; - } - - }); -} - -function addSlaveSSH(ip=''){ - - myPost('get_slave_ssh_by_ip', {ip:ip}, function(rdata){ - - var rdata = $.parseJSON(rdata.data); - - var ip = '127.0.0.1'; - var port = "22"; - var id_rsa = ''; - var db_user =''; - - if (rdata.data.length>0){ - ip = rdata.data[0]['ip']; - port = rdata.data[0]['port']; - id_rsa = rdata.data[0]['id_rsa']; - db_user = rdata.data[0]['db_user']; - } - - var index = layer.open({ - type: 1, - area: ['500px','480px'], - title: '添加SSH', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["确认","取消"], - content: "
        \ -
        IP
        \ -
        端口
        \ -
        同步账户[DB]
        \ -
        \ - ID_RSA\ -
        \ -
        \ - \ -
        ", - success:function(){ - $('textarea[name="id_rsa"]').html(id_rsa); - }, - yes:function(index){ - var ip = $('input[name="ip"]').val(); - var port = $('input[name="port"]').val(); - var db_user = $('input[name="db_user"]').val(); - var id_rsa = $('textarea[name="id_rsa"]').val(); - - var data = {ip:ip,port:port,id_rsa:id_rsa,db_user:db_user}; - myPost('add_slave_ssh', data, function(data){ - layer.close(index); - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSSHPage(); - } - },{icon: rdata.status ? 1 : 2},600); - }); - } - }); - }); -} - - -function delSlaveSSH(ip){ - myPost('del_slave_ssh', {ip:ip}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSSHPage(); - } - },{icon: rdata.status ? 1 : 2}, 600); - }); -} - - -function delSlaveSyncUser(ip){ - myPost('del_slave_sync_user', {ip:ip}, function(rdata){ - var rdata = $.parseJSON(rdata.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSyncUserPage(); - } - },{icon: rdata.status ? 1 : 2}, 600); - }); -} - -function getSlaveSSHPage(page=1){ - var _data = {}; - _data['page'] = page; - _data['page_size'] = 5; - _data['tojs'] ='getSlaveSSHPage'; - myPost('get_slave_ssh_list', _data, function(data){ - var layerId = null; - var rdata = []; - try { - rdata = $.parseJSON(data.data); - } catch(e) { - console.log(e); - } - var list = ''; - var ssh_list = rdata['data']; - for (i in ssh_list) { - var ip = ssh_list[i]['ip']; - var port = ssh_list[i]['port']; - - var id_rsa = '未设置'; - if ( ssh_list[i]['port'] != ''){ - id_rsa = '已设置'; - } - - var db_user = '未设置'; - if ( ssh_list[i]['db_user'] != ''){ - db_user = ssh_list[i]['db_user']; - } - - list += ''+ip+'\ - '+port+'\ - '+db_user+'\ - '+id_rsa+'\ - \ - 修改 | \ - 删除\ - \ - '; - } - - $('.get-slave-ssh-list tbody').html(list); - $('.dataTables_paginate_4').html(rdata['page']); - }); -} - - - -function addSlaveSyncUser(ip=''){ - - myPost('get_slave_sync_user_by_ip', {ip:ip}, function(rdata){ - - var rdata = $.parseJSON(rdata.data); - - var ip = '127.0.0.1'; - var port = "22"; - var cmd = ''; - var user = 'input_sync_user'; - var pass = 'input_sync_pwd'; - var mode = '0'; - - if (rdata.data.length>0){ - ip = rdata.data[0]['ip']; - port = rdata.data[0]['port']; - cmd = rdata.data[0]['cmd']; - user = rdata.data[0]['user']; - pass = rdata.data[0]['pass']; - mode = rdata.data[0]['mode']; - } - - var index = layer.open({ - type: 1, - area: ['500px','510px'], - title: '同步账户', - closeBtn: 1, - shift: 5, - shadeClose: true, - btn:["确认","取消"], - content: "
        \ -
        IP
        \ -
        端口
        \ -
        同步账户
        \ -
        同步密码
        \ -
        \ - 同步模式\ -
        \ - \ -
        \ -
        \ -
        \ - CMD[必填]\ -
        \ -
        \ - \ -
        ", - success:function(){ - $('textarea[name="cmd"]').html(cmd); - $('textarea[name="cmd"]').change(function(){ - var val = $(this).val(); - val = val.replace(';',''); - var a = {}; - if (val.toLowerCase().indexOf('for')>0){ - cmd_tmp = val.split('for'); - val = cmd_tmp[0].trim(); - - const channel_str = cmd_tmp[1].trim(); - const ch_reg = /channel \'(.*)\';/; - var match_val = channel_str.match(ch_reg); - if (match_val.length>1){ - a['channel'] = match_val[1]; - } - } - - var vlist = val.split(','); - for (var i in vlist) { - var tmp = toTrim(vlist[i]); - var tmp_a = tmp.split(" "); - var real_tmp = tmp_a[tmp_a.length-1]; - var kv = real_tmp.split("="); - a[kv[0]] = kv[1].replace("'",'').replace("'",''); - } - - if ('MASTER_HOST' in a){ - $('input[name="ip"]').val(a['MASTER_HOST']); - $('input[name="port"]').val(a['MASTER_PORT']); - $('input[name="user"]').val(a['MASTER_USER']); - $('input[name="pass"]').val(a['MASTER_PASSWORD']); - } else { - $('input[name="ip"]').val(a['SOURCE_HOST']); - $('input[name="port"]').val(a['SOURCE_PORT']); - $('input[name="user"]').val(a['SOURCE_USER']); - $('input[name="pass"]').val(a['SOURCE_PASSWORD']); - } - }); - }, - yes:function(index){ - var ip = $('input[name="ip"]').val(); - var port = $('input[name="port"]').val(); - var user = $('input[name="user"]').val(); - var pass = $('input[name="pass"]').val(); - var cmd = $('textarea[name="cmd"]').val(); - var mode = $('select[name="mode"]').val(); - - var data = {ip:ip,port:port,cmd:cmd,user:user,pass:pass,mode:mode}; - myPost('add_slave_sync_user', data, function(ret_data){ - layer.close(index); - var rdata = $.parseJSON(ret_data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - getSlaveSyncUserPage(); - } - },{icon: rdata.status ? 1 : 2},600); - }); - } - }); - }); -} - -function getSlaveSyncUserPage(page=1){ - var _data = {}; - _data['page'] = page; - _data['page_size'] = 5; - _data['tojs'] ='getSlaveSyncUserPage'; - myPost('get_slave_sync_user_list', _data, function(data){ - var layerId = null; - var rdata = []; - try { - rdata = $.parseJSON(data.data); - } catch(e) { - console.log(e); - } - - var list = ''; - var user_list = rdata['data']; - for (i in user_list) { - var ip = user_list[i]['ip']; - var port = user_list[i]['port']; - var user = user_list[i]['user']; - var apass = user_list[i]['pass']; - - var cmd = '未设置'; - if (user_list[i]['cmd']!=''){ - cmd = '已设置'; - } - - list += ''+ip+'\ - '+port+'\ - '+user+'\ - '+apass+'\ - '+cmd+'\ - \ - 修改 | \ - 删除\ - \ - '; - } - - $('.get-slave-ssh-list tbody').html(list); - $('.dataTables_paginate_4').html(rdata['page']); - }); -} - -function getSlaveCfg(){ - - myPost('get_slave_sync_mode', '', function(data){ - var rdata = $.parseJSON(data.data); - var mode_none = 'success'; - var mode_ssh = 'danger'; - var mode_sync_user = 'danger'; - if(rdata.status){ - var mode_none = 'danger'; - if (rdata.data == 'ssh'){ - var mode_ssh = 'success'; - var mode_sync_user = 'danger'; - } else { - var mode_ssh = 'danger'; - var mode_sync_user = 'success'; - } - } - - layerId = layer.open({ - type: 1, - title: '同步配置', - area: ['400px','180px'], - content:"
        \ -

        \ - 当前从库同步模式\ - \ - \ - \ - \ -

        \ -
        \ -

        \ - 配置设置\ - \ - \ - \ -

        \ -
        ", - success:function(){ - $('.btn-slave-ssh').click(function(){ - getSlaveSSHList(); - }); - - $('.btn-slave-user').click(function(){ - getSlaveUserList(); - }); - - $('.slave-db-mode').click(function(){ - var _this = this; - var mode = 'none'; - if ($(this).hasClass('btn-ssh')){ - mode = 'ssh'; - } - if ($(this).hasClass('btn-sync-user')){ - mode = 'sync-user'; - } - - myPost('set_slave_sync_mode', {mode:mode}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - $('.slave-db-mode').remove('btn-success').addClass('btn-danger'); - $(_this).removeClass('btn-danger').addClass('btn-success'); - },{icon:rdata.status?1:2},2000); - }); - - }); - } - }); - }); -} - - -function getSlaveUserList(){ - - var page = '
        '; - page += '
        添加同步账户
        '; - - layerId = layer.open({ - type: 1, - title: '同步账户列表', - area: '600px', - content:"
        \ -
        \ -
        \ - \ - \ -
        IPPORT同步账户同步密码CMD操作
        \ - "+page +"\ -
        \ -
        ", - success:function(){ - getSlaveSyncUserPage(1); - } - }); -} - -function getSlaveSSHList(page=1){ - - var page = '
        '; - page += '
        添加SSH
        '; - - layerId = layer.open({ - type: 1, - title: 'SSH列表', - area: '600px', - content:"
        \ -
        \ -
        \ - \ - \ -
        IPPORT同步账户SSH操作
        \ - "+page +"\ -
        \ -
        ", - success:function(){ - getSlaveSSHPage(1); - } - }); -} - -function handlerRun(){ - myPostN('get_slave_sync_cmd', {}, function(data){ - var rdata = $.parseJSON(data.data); - var cmd = rdata['data']; - var loadOpen = layer.open({ - type: 1, - title: '手动执行', - area: '500px', - content:"
        \ -
        "+cmd+"
        \ -
        \ - \ -
        \ -
        ", - }); - copyPass(cmd); - $('.class-copy-cmd').click(function(){ - copyPass(cmd); - }); - }); -} - -function initSlaveStatus(){ - myPost('init_slave_status', '', function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg,function(){ - if (rdata.status){ - masterOrSlaveConf(); - } - },{icon:rdata.status?1:2},2000); - }); -} - -function masterOrSlaveConf(version=''){ - - function getMasterDbList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - - myPost('get_masterdb_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - for(i in rdata.data){ - list += ''; - list += '' + rdata.data[i]['name'] +''; - list += '' + (rdata.data[i]['master']?'是':'否') +''; - list += '' + - ''+(rdata.data[i]['master']?'退出':'加入')+' | ' + - '同步命令' + - ''; - list += ''; - } - - var con = '
        \ -
        \ - \ - \ - \ - \ - \ - \ - '+ list +'\ -
        数据库名同步操作
        \ -
        \ -
        \ -
        \ - 同步账户列表\ -
        \ -
        '; - - $(".table_master_list").html(con); - $('#databasePage').html(rdata.page); - }); - } - - function getAsyncMasterDbList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - - var mdb_ver = $('.plugin_version').attr('version'); - - myPost('get_slave_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - - var isHasSign = false; - for(i in rdata.data){ - - var v = rdata.data[i]; - if ('Channel_Name' in v && v['Channel_Name'] !=''){ - isHasSign = true; - } - - var status = "异常"; - if (mdb_ver >= 8){ - if (v['Replica_SQL_Running'] == 'Yes' && v['Replica_IO_Running'] == 'Yes'){ - status = "正常"; - } - - list += ''; - list += '' + rdata.data[i]['Source_Host'] +''; - list += '' + rdata.data[i]['Source_Port'] +''; - list += '' + rdata.data[i]['Source_User'] +''; - list += '' + rdata.data[i]['Relay_Source_Log_File'] +''; - list += '' + rdata.data[i]['Replica_IO_Running'] +''; - list += '' + rdata.data[i]['Replica_SQL_Running'] +''; - - } else { - if (v['Slave_SQL_Running'] == 'Yes' && v['Slave_IO_Running'] == 'Yes'){ - status = "正常"; - } - - list += ''; - list += '' + rdata.data[i]['Master_Host'] +''; - list += '' + rdata.data[i]['Master_Port'] +''; - list += '' + rdata.data[i]['Master_User'] +''; - list += '' + rdata.data[i]['Master_Log_File'] +''; - list += '' + rdata.data[i]['Slave_IO_Running'] +''; - list += '' + rdata.data[i]['Slave_SQL_Running'] +''; - } - - - if (isHasSign){ - list += '' + v['Channel_Name'] +''; - } - - list += '' + status +''; - list += '' + - '删除' + - ''; - list += ''; - } - - var signThead_th = ''; - if (isHasSign){ - var signThead_th = '标识'; - } - - var con = '
        \ -
        \ - \ - \ - \ - \ - \ - \ - \ - \ - '+signThead_th+'\ - \ - \ - \ - '+ list +'\ -
        主[服务]端口用户日志IOSQL状态操作
        \ -
        \ -
        '; - - //
        \ - //
        \ - // 添加\ - //
        - $(".table_slave_status_list").html(con); - - $(".btn_delete_slave").click(function(){ - var id = $(this).data('id'); - var v = rdata.data[id]; - if ('Channel_Name' in v){ - deleteSlave(v['Channel_Name']); - } else{ - deleteSlave(); - } - }); - - $('.db_error').click(function(){ - var id = $(this).data('id'); - var info = rdata.data[id]; - - var err_line = ""; - err_line +="\ - IO错误\ - "+ (info['Last_IO_Error'] == '' ? '无':info['Last_IO_Error'])+"\ - "; - err_line +="\ - SQL错误\ - "+(info['Last_SQL_Error'] == '' ? '无':info['Last_SQL_Error'])+"\ - "; - - err_line +="\ - 状态\ - "+(info['Slave_SQL_Running_State'] == '' ? '无':info['Slave_SQL_Running_State']) +"\ - "; - - - var btn_list = ['复制错误',"取消"]; - if (info['Last_IO_Error'].search(/1236/i)>0){ - btn_list = ['复制错误',"取消","尝试修复"]; - } - layer.open({ - type: 1, - title: '同步异常信息', - area: ['600px','300px'], - btn:btn_list, - content:"
        \ -
        \ -
        \ - \ - \ - \ - \ - \ - "+ err_line +"\ -
        类型内容
        \ -
        \ -
        \ -
        ", - success:function(){ - if (info['Last_IO_Error'] != ''){ - copyText(info['Last_IO_Error']); - return; - } - - if (info['Last_SQL_Error'] != ''){ - copyText(info['Last_SQL_Error']); - return; - } - - if (info['Slave_SQL_Running_State'] != ''){ - copyText(info['Slave_SQL_Running_State']); - return; - } - }, - yes:function(){ - if (info['Last_IO_Error'] != ''){ - copyText(info['Last_IO_Error']); - return; - } - - if (info['Last_SQL_Error'] != ''){ - copyText(info['Last_SQL_Error']); - return; - } - - if (info['Slave_SQL_Running_State'] != ''){ - copyText(info['Slave_SQL_Running_State']); - return; - } - }, - btn3:function(){ - myPost('try_slave_sync_bugfix', {}, function(data){ - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg, function(){ - masterOrSlaveConf(); - },{ icon: rdata.status ? 1 : 5 },2000); - }); - } - }); - }); - }); - } - - function getAsyncDataList(){ - var _data = {}; - if (typeof(page) =='undefined'){ - var page = 1; - } - - _data['page'] = page; - _data['page_size'] = 10; - myPost('get_masterdb_list', _data, function(data){ - var rdata = $.parseJSON(data.data); - var list = ''; - for(i in rdata.data){ - list += ''; - list += '' + rdata.data[i]['name'] +''; - list += '' + - ''+(rdata.data[i]['slave']?'退出':'加入')+' | ' + - '同步 | ' + - '数据校验' + - ''; - list += ''; - } - - var con = '
        \ -
        \ - \ - \ - \ - \ - \ - '+ list +'\ -
        本地库名操作
        \ -
        \ -
        \ -
        \ - 手动命令\ - 全量同步\ -
        \ -
        '; - - $(".table_slave_list").html(con); - $('#databasePage').html(rdata.page); - }); - } - - - function getMasterStatus(){ - myPost('get_master_status', '', function(rdata){ - var rdata = $.parseJSON(rdata.data); - // console.log('mode:',rdata.data); - if ( typeof(rdata.status) != 'undefined' && !rdata.status && rdata.data == 'pwd'){ - layer.msg(rdata.msg, {icon:2}); - return; - } - - var rdata = rdata.data; - var limitCon = '\ -

        \ - 主从同步模式\ - \ - \ -

        \ -
        \ -

        \ - Master[主]配置\ - \ - \ -

        \ -
        \ - \ -
        \ -
        \ - \ -

        \ - Slave[从]配置\ - \ - \ - \ -

        \ -
        \ - \ -
        \ - \ -
        \ - '; - $(".soft-man-con").html(limitCon); - - //设置主服务器配置 - $(".btn-master").click(function () { - myPost('set_master_status', 'close=change', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - getMasterStatus(); - }, 3000); - }); - }); - - $(".btn-slave").click(function () { - myPost('set_slave_status', 'close=change', function(data){ - var rdata = $.parseJSON(data.data); - layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); - setTimeout(function(){ - getMasterStatus(); - }, 3000); - }); - }); - - $('.db-mode').click(function(){ - if ($(this).hasClass('btn-success')){ - //no action - return; - } - - var mode = 'classic'; - if ($(this).hasClass('btn-gtid')){ - mode = 'gtid'; - } - - layer.open({ - type:1, - title:"MySQL主从模式切换", - shadeClose:false, - btnAlign: 'c', - btn: ['切换并重启', '切换不重启'], - yes: function(index, layero){ - this.change(index,mode,"yes"); - - }, - btn2: function(index, layero){ - this.change(index,mode,"no"); - return false; - }, - change:function(index,mode,reload){ - console.log(index,mode,reload); - myPost('set_dbrun_mode',{'mode':mode,'reload':reload},function(data){ - layer.close(index); - var rdata = $.parseJSON(data.data); - showMsg(rdata.msg ,function(){ - getMasterStatus(); - },{ icon: rdata.status ? 1 : 5 }); - }); - } - }); - }); - - if (rdata.status){ - getMasterDbList(); - } - - // if (rdata.slave_status){ - getAsyncMasterDbList(); - getAsyncDataList() - // } - }); - } - getMasterStatus(); -} diff --git a/plugins/mysql-yum/scripts/backup.py b/plugins/mysql-yum/scripts/backup.py deleted file mode 100755 index d18caf8e6b..0000000000 --- a/plugins/mysql-yum/scripts/backup.py +++ /dev/null @@ -1,118 +0,0 @@ -# coding: utf-8 -#----------------------------- -# 网站备份工具 -#----------------------------- - -import sys -import os -import time -import re - -if sys.platform != 'darwin': - os.chdir('/www/server/mdserver-web') - - -web_dir = os.getcwd() + "/web" -if os.path.exists(web_dir): - sys.path.append(web_dir) - os.chdir(web_dir) - -import core.mw as mw -import core.db as db - -''' -DEBUG: -python3 /www/server/mdserver-web/plugins/mysql-yum/scripts/backup.py database admin 3 -''' - - -class backupTools: - - def backupDatabase(self, name, count): - db_path = mw.getServerDir() + '/mysql-yum' - db_name = 'mysql' - find_name = mw.M('databases').dbPos(db_path, 'mysql').where( - 'name=?', (name,)).getField('name') - startTime = time.time() - if not find_name: - endDate = time.strftime('%Y/%m/%d %X', time.localtime()) - log = "数据库[" + name + "]不存在!" - print("★[" + endDate + "] " + log) - print( - "----------------------------------------------------------------------------") - return - - backup_path = mw.getFatherDir() + '/backup/database/mysql-yum' - if not os.path.exists(backup_path): - mw.execShell("mkdir -p " + backup_path) - - filename = backup_path + "/db_" + name + "_" + \ - time.strftime('%Y%m%d_%H%M%S', time.localtime()) + ".sql.gz" - - mysql_root = mw.M('config').dbPos(db_path, db_name).where( - "id=?", (1,)).getField('mysql_root') - - my_cnf = db_path + '/etc/my.cnf' - - mw.backFile(my_cnf) - content = mw.readFile(my_cnf) - rep = r"\[mysqldump\]\nuser=root" - sea = "[mysqldump]\n" - subStr = sea + "user=root\npassword=" + mysql_root + "\n" - content = content.replace(sea, subStr) - if len(content) > 100: - mw.writeFile(my_cnf, content) - - cmd = db_path + "/bin/usr/bin/mysqldump --defaults-file=" + my_cnf + " --single-transaction -q --default-character-set=utf8mb4 " + \ - name + " | gzip > " + filename - mw.execShell(cmd) - - mw.restoreFile(my_cnf) - if not os.path.exists(filename): - endDate = time.strftime('%Y/%m/%d %X', time.localtime()) - log = "数据库[" + name + "]备份失败!" - print("★[" + endDate + "] " + log) - print( - "----------------------------------------------------------------------------") - return - - endDate = time.strftime('%Y/%m/%d %X', time.localtime()) - outTime = time.time() - startTime - pid = mw.M('databases').dbPos(db_path, db_name).where('name=?', (name,)).getField('id') - - mw.M('backup').add('type,name,pid,filename,add_time,size', (1, os.path.basename(filename), pid, filename, endDate, os.path.getsize(filename))) - log = "数据库[" + name + "]备份成功,用时[" + str(round(outTime, 2)) + "]秒" - mw.writeLog('计划任务', log) - print("★[" + endDate + "] " + log) - print("|---保留最新的[" + count + "]份备份") - print("|---文件名:" + filename) - - # 清理多余备份 - backups = mw.M('backup').where('type=? and pid=?', ('1', pid)).field('id,filename').select() - num = len(backups) - int(count) - if num > 0: - for backup in backups: - mw.execShell("rm -f " + backup['filename']) - mw.M('backup').where('id=?', (backup['id'],)).delete() - num -= 1 - print("|---已清理过期备份文件:" + backup['filename']) - if num < 1: - break - - def backupDatabaseAll(self, save): - db_path = mw.getServerDir() + '/mysql-yum' - db_name = 'mysql' - databases = mw.M('databases').dbPos( - db_path, db_name).field('name').select() - for database in databases: - self.backupDatabase(database['name'], save) - - -if __name__ == "__main__": - backup = backupTools() - stype = sys.argv[1] - if stype == 'database': - if sys.argv[2] == 'ALL': - backup.backupDatabaseAll(sys.argv[3]) - else: - backup.backupDatabase(sys.argv[2], sys.argv[3]) diff --git a/plugins/mysql-yum/versions/5.7/install.sh b/plugins/mysql-yum/versions/5.7/install.sh deleted file mode 100755 index e94ac9b890..0000000000 --- a/plugins/mysql-yum/versions/5.7/install.sh +++ /dev/null @@ -1,151 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - - -myDir=${serverPath}/source/mysql-yum - -ARCH=`uname -m` -ARCH_NAME='' -case $(uname -m) in - i386) ARCH_NAME="386" ;; - i686) ARCH_NAME="386" ;; - x86_64) ARCH_NAME="amd64" ;; - arm) ARCH_NAME="arm64" ;; -esac - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` -echo "VERSION_ID:${VERSION_ID}" - -if [ "$OSNAME" == "centos" ] && [ "$VERSION_ID" -gt "7" ]; then - VERSION_ID=7 -fi - -OS_SIGN=1.el9 -if [ "$OSNAME" == "centos" ];then - OS_SIGN=1.el${VERSION_ID} -elif [ "$OSNAME" == "fedora" ]; then - OS_SIGN=10.fc${VERSION_ID} -elif [ "$OSNAME" == "opensuse" ]; then - OS_SIGN=1.sl${VERSION_ID:0:2} -fi - -MYSQL_VER=5.7.44 -SUFFIX_NAME=${MYSQL_VER}-${OS_SIGN}.${ARCH} - -YUM_INSTALL() -{ - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.rpm-bundle.tar -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -ZYPPER_INSTALL() -{ -zypper install -y libstdc++6 - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.rpm-bundle.tar -echo "wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-5.7/mysql-${SUFFIX_NAME}.rpm-bundle.tar" - -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -YUM_UNINSTALL() -{ -### YUM卸载 START ######## -# yum -y remove mysql-server -rm -rf ${myDir} -### YUM卸载 END ######## -} - - -Install_mysql() -{ - - echo '正在安装脚本文件...' - - mkdir -p $serverPath/mysql-yum - - isYum=`which yum` - if [ "$isYum" != "" ];then - YUM_INSTALL - fi - - isZypper=`which zypper` - if [ "$isZypper" != "" ];then - ZYPPER_INSTALL - fi - - rm -rf $myDir - echo '5.7' > $serverPath/mysql-yum/version.pl - echo '安装完成' -} - -Uninstall_mysql() -{ - YUM_UNINSTALL - rm -rf $serverPath/mysql-yum - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-yum/versions/8.0/install.sh b/plugins/mysql-yum/versions/8.0/install.sh deleted file mode 100755 index 27e72cbc4c..0000000000 --- a/plugins/mysql-yum/versions/8.0/install.sh +++ /dev/null @@ -1,149 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-yum - -ARCH=`uname -m` -ARCH_NAME='' -case $(uname -m) in - i386) ARCH_NAME="386" ;; - i686) ARCH_NAME="386" ;; - x86_64) ARCH_NAME="amd64" ;; - arm) ARCH_NAME="arm64" ;; -esac - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` -echo "VERSION_ID:${VERSION_ID}" - -OS_SIGN=1.el9 -if [ "$OSNAME" == "centos" ];then - OS_SIGN=1.el${VERSION_ID} -elif [ "$OSNAME" == "fedora" ]; then - OS_SIGN=10.fc${VERSION_ID} -elif [ "$OSNAME" == "opensuse" ]; then - OS_SIGN=1.sl${VERSION_ID:0:2} -fi - -MYSQL_VER=8.0.37 -SUFFIX_NAME=${MYSQL_VER}-${OS_SIGN}.${ARCH} - -YUM_INSTALL() -{ - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.0/mysql-${SUFFIX_NAME}.rpm-bundle.tar -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -ZYPPER_INSTALL() -{ -zypper install -y libstdc++6 - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.0/mysql-${SUFFIX_NAME}.rpm-bundle.tar -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar -echo "wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.0/mysql-${SUFFIX_NAME}.rpm-bundle.tar" - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -YUM_UNINSTALL() -{ -### YUM卸载 START ######## -# yum -y remove mysql-server -rm -rf ${myDir} -### YUM卸载 END ######## -} - - -Install_mysql() -{ - - echo '正在安装脚本文件...' - - mkdir -p $serverPath/mysql-yum - mkdir -p /var/run/mysqld - chown mysql -R /var/run/mysqld - - isYum=`which yum` - if [ "$isYum" != "" ];then - YUM_INSTALL - fi - - isZypper=`which zypper` - if [ "$isZypper" != "" ];then - ZYPPER_INSTALL - fi - - rm -rf $myDir - - echo '8.0' > $serverPath/mysql-yum/version.pl - echo '安装完成' -} - -Uninstall_mysql() -{ - YUM_UNINSTALL - rm -rf $serverPath/mysql-yum - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-yum/versions/8.2/install.sh b/plugins/mysql-yum/versions/8.2/install.sh deleted file mode 100755 index 08cb36d1e9..0000000000 --- a/plugins/mysql-yum/versions/8.2/install.sh +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - - -myDir=${serverPath}/source/mysql-yum - -ARCH=`uname -m` -ARCH_NAME='' -case $(uname -m) in - i386) ARCH_NAME="386" ;; - i686) ARCH_NAME="386" ;; - x86_64) ARCH_NAME="amd64" ;; - arm) ARCH_NAME="arm64" ;; -esac - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` -echo "VERSION_ID:${VERSION_ID}" - -OS_SIGN=1.el9 -if [ "$OSNAME" == "centos" ];then - OS_SIGN=1.el${VERSION_ID} -elif [ "$OSNAME" == "fedora" ]; then - OS_SIGN=10.fc${VERSION_ID} -elif [ "$OSNAME" == "opensuse" ]; then - OS_SIGN=1.sl${VERSION_ID:0:2} -fi - -MYSQL_VER=8.2.0 -SUFFIX_NAME=${MYSQL_VER}-${OS_SIGN}.${ARCH} - -YUM_INSTALL() -{ - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.2/mysql-${SUFFIX_NAME}.rpm-bundle.tar -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -ZYPPER_INSTALL() -{ -zypper install -y libstdc++6 - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.2/mysql-${SUFFIX_NAME}.rpm-bundle.tar -echo "wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.2/mysql-${SUFFIX_NAME}.rpm-bundle.tar" -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -YUM_UNINSTALL() -{ -### YUM卸载 START ######## -# yum -y remove mysql-server -rm -rf ${myDir} -### YUM卸载 END ######## -} - - -Install_mysql() -{ - - echo '正在安装脚本文件...' - - mkdir -p $serverPath/mysql-yum - - mkdir -p /var/lib/mysql - chown mysql -R /var/lib/mysql - - isYum=`which yum` - if [ "$isYum" != "" ];then - YUM_INSTALL - fi - - isZypper=`which zypper` - if [ "$isZypper" != "" ];then - ZYPPER_INSTALL - fi - - rm -rf $myDir - - echo '8.2' > $serverPath/mysql-yum/version.pl - echo '安装完成' -} - -Uninstall_mysql() -{ - YUM_UNINSTALL - rm -rf $serverPath/mysql-yum - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-yum/versions/8.3/install.sh b/plugins/mysql-yum/versions/8.3/install.sh deleted file mode 100755 index f7630ad861..0000000000 --- a/plugins/mysql-yum/versions/8.3/install.sh +++ /dev/null @@ -1,151 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-yum - -ARCH=`uname -m` -ARCH_NAME='' -case $(uname -m) in - i386) ARCH_NAME="386" ;; - i686) ARCH_NAME="386" ;; - x86_64) ARCH_NAME="amd64" ;; - arm) ARCH_NAME="arm64" ;; -esac - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` -echo "VERSION_ID:${VERSION_ID}" - -OS_SIGN=1.el9 -if [ "$OSNAME" == "centos" ];then - OS_SIGN=1.el${VERSION_ID} -elif [ "$OSNAME" == "fedora" ]; then - OS_SIGN=10.fc${VERSION_ID} -elif [ "$OSNAME" == "opensuse" ]; then - OS_SIGN=1.sl${VERSION_ID:0:2} -fi - -MYSQL_VER=8.3.0 -SUFFIX_NAME=${MYSQL_VER}-${OS_SIGN}.${ARCH} - -YUM_INSTALL() -{ - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.3/mysql-${SUFFIX_NAME}.rpm-bundle.tar -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -ZYPPER_INSTALL() -{ -zypper install -y libstdc++6 - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.3/mysql-${SUFFIX_NAME}.rpm-bundle.tar -echo "wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.3/mysql-${SUFFIX_NAME}.rpm-bundle.tar" -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -YUM_UNINSTALL() -{ -### YUM卸载 START ######## -# yum -y remove mysql-server -rm -rf ${myDir} -### YUM卸载 END ######## -} - - -Install_mysql() -{ - - echo '正在安装脚本文件...' - - mkdir -p $serverPath/mysql-yum - - mkdir -p /var/lib/mysql - chown mysql -R /var/lib/mysql - - isYum=`which yum` - if [ "$isYum" != "" ];then - YUM_INSTALL - fi - - isZypper=`which zypper` - if [ "$isZypper" != "" ];then - ZYPPER_INSTALL - fi - - rm -rf $myDir - - echo '8.3' > $serverPath/mysql-yum/version.pl - echo '安装完成' -} - -Uninstall_mysql() -{ - YUM_UNINSTALL - rm -rf $serverPath/mysql-yum - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-yum/versions/8.4/install.sh b/plugins/mysql-yum/versions/8.4/install.sh deleted file mode 100755 index 02bf03981d..0000000000 --- a/plugins/mysql-yum/versions/8.4/install.sh +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-yum - -ARCH=`uname -m` -ARCH_NAME='' -case $(uname -m) in - i386) ARCH_NAME="386" ;; - i686) ARCH_NAME="386" ;; - x86_64) ARCH_NAME="amd64" ;; - arm) ARCH_NAME="arm64" ;; -esac - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` -echo "VERSION_ID:${VERSION_ID}" - -OS_SIGN=1.el9 -if [ "$OSNAME" == "centos" ];then - OS_SIGN=1.el${VERSION_ID} -elif [ "$OSNAME" == "fedora" ]; then - OS_SIGN=10.fc${VERSION_ID} -elif [ "$OSNAME" == "opensuse" ]; then - OS_SIGN=1.sl${VERSION_ID:0:2} -fi - -MYSQL_VER=8.4.0 -SUFFIX_NAME=${MYSQL_VER}-${OS_SIGN}.${ARCH} - -YUM_INSTALL() -{ - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -####### -mkdir -p $myDir - -# https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-${SUFFIX_NAME}.rpm-bundle.tar -# https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.rpm-bundle.tar - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-${SUFFIX_NAME}.rpm-bundle.tar -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -ZYPPER_INSTALL() -{ -zypper install -y libstdc++6 - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld -####### -mkdir -p $myDir - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.rpm-bundle.tar -echo "wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.rpm-bundle.tar" -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -YUM_UNINSTALL() -{ -### YUM卸载 START ######## -# yum -y remove mysql-server -rm -rf ${myDir} -### YUM卸载 END ######## -} - - -Install_mysql() -{ - - echo '正在安装脚本文件...' - mkdir -p $serverPath/mysql-yum - - mkdir -p /var/lib/mysql - chown mysql -R /var/lib/mysql/ - - isYum=`which yum` - if [ "$isYum" != "" ];then - YUM_INSTALL - fi - - isZypper=`which zypper` - if [ "$isZypper" != "" ];then - ZYPPER_INSTALL - fi - - rm -rf $myDir - - echo '8.4' > $serverPath/mysql-yum/version.pl - echo '安装完成' -} - -Uninstall_mysql() -{ - YUM_UNINSTALL - rm -rf $serverPath/mysql-yum - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi diff --git a/plugins/mysql-yum/versions/9.0/install.sh b/plugins/mysql-yum/versions/9.0/install.sh deleted file mode 100755 index 821b6c4885..0000000000 --- a/plugins/mysql-yum/versions/9.0/install.sh +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -#!/bin/bash - -PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin -export PATH - -# https://downloads.mysql.com/archives/community/ - -curPath=`pwd` -rootPath=$(dirname "$curPath") -rootPath=$(dirname "$rootPath") -serverPath=$(dirname "$rootPath") -sysName=`uname` - -myDir=${serverPath}/source/mysql-yum - -ARCH=`uname -m` -ARCH_NAME='' -case $(uname -m) in - i386) ARCH_NAME="386" ;; - i686) ARCH_NAME="386" ;; - x86_64) ARCH_NAME="amd64" ;; - arm) ARCH_NAME="arm64" ;; -esac - -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` -echo "VERSION_ID:${VERSION_ID}" - -OS_SIGN=1.el9 -if [ "$OSNAME" == "centos" ];then - OS_SIGN=1.el${VERSION_ID} -elif [ "$OSNAME" == "fedora" ]; then - OS_SIGN=10.fc${VERSION_ID} -elif [ "$OSNAME" == "opensuse" ]; then - OS_SIGN=1.sl${VERSION_ID:0:2} -fi - -MYSQL_VER=9.0.1 -SUFFIX_NAME=${MYSQL_VER}-${OS_SIGN}.${ARCH} - -YUM_INSTALL() -{ - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld - -####### -mkdir -p $myDir - -# https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-${SUFFIX_NAME}.rpm-bundle.tar -# https://cdn.mysql.com/archives/mysql-8.4/mysql-${SUFFIX_NAME}.rpm-bundle.tar - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://dev.mysql.com/get/Downloads/MySQL-9.0/mysql-${SUFFIX_NAME}.rpm-bundle.tar -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -ZYPPER_INSTALL() -{ -zypper install -y libstdc++6 - -mkdir -p /var/run/mysqld -chown mysql -R /var/run/mysqld -####### -mkdir -p $myDir - - -wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/Downloads/MySQL-9.0/mysql-${SUFFIX_NAME}.rpm-bundle.tar -echo "wget --no-check-certificate -O $myDir/mysql-${SUFFIX_NAME}.rpm-bundle.tar https://cdn.mysql.com/Downloads/MySQL-9.0/mysql-${SUFFIX_NAME}.rpm-bundle.tar" -cd ${myDir} && tar vxf mysql-${SUFFIX_NAME}.rpm-bundle.tar - -mkdir -p ${serverPath}/mysql-yum/bin && cd ${serverPath}/mysql-yum/bin - -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-client-${SUFFIX_NAME}.x86_64.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-common-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-debuginfo-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-devel-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-embedded-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-icu-data-files-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-libs-compat-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-server-debug-${SUFFIX_NAME}.rpm | cpio -div -rpm2cpio ${myDir}/mysql-community-test-${SUFFIX_NAME}.rpm | cpio -div - -####### -} - -YUM_UNINSTALL() -{ -### YUM卸载 START ######## -# yum -y remove mysql-server -rm -rf ${myDir} -### YUM卸载 END ######## -} - - -Install_mysql() -{ - - echo '正在安装脚本文件...' - mkdir -p $serverPath/mysql-yum - - mkdir -p /var/lib/mysql - chown mysql -R /var/lib/mysql/ - - isYum=`which yum` - if [ "$isYum" != "" ];then - YUM_INSTALL - fi - - isZypper=`which zypper` - if [ "$isZypper" != "" ];then - ZYPPER_INSTALL - fi - - rm -rf $myDir - - echo '9.0' > $serverPath/mysql-yum/version.pl - echo '安装完成' -} - -Uninstall_mysql() -{ - YUM_UNINSTALL - rm -rf $serverPath/mysql-yum - echo '卸载完成' -} - -action=$1 -if [ "${1}" == 'install' ];then - Install_mysql -else - Uninstall_mysql -fi