diff --git a/README.md b/README.md index ab0187235d..22f45d10b9 100644 --- a/README.md +++ b/README.md @@ -90,14 +90,15 @@ docker run -itd --name mw-server --privileged=true -p 7200:7200 -p 80:80 -p 443: ``` -### 版本更新 0.9.11 - -* 大文件解压优化。 -* 防火墙api优化。 -* mysql|mariadb安装删除冗余账户。 -* imail插件添加。 -* 安装面板初始化安装时不再固定端口[7200],优化为随机端口。 -* redis添加性能调整功能。 +### 版本更新 0.9.12 + +* 日志清理插件优化。 +* 计划任务显示完整。 +* 加入gitea插件。 +* 融合mw-cli命令。 +* 加快php编译速度。 +* swap加上调整功能。 +* 其他细节优化。 ### JSDelivr安装地址 diff --git a/class/core/config_api.py b/class/core/config_api.py index 1eb48f58a8..c3b4c6a42b 100755 --- a/class/core/config_api.py +++ b/class/core/config_api.py @@ -15,7 +15,7 @@ class config_api: - __version = '0.9.11' + __version = '0.9.12' def __init__(self): pass diff --git a/class/core/crontab_api.py b/class/core/crontab_api.py index 66362cf8f4..326b8f2597 100755 --- a/class/core/crontab_api.py +++ b/class/core/crontab_api.py @@ -414,10 +414,10 @@ def getShell(self, param): script_dir = mw.getServerDir() + "/mdserver-web/scripts" wheres = { - 'path': head + "python " + script_dir + "/backup.py path " + param['sname'] + " " + str(param['save']), - 'site': head + "python " + script_dir + "/backup.py site " + param['sname'] + " " + str(param['save']), - 'database': head + "python " + script_dir + "/backup.py database " + param['sname'] + " " + str(param['save']), - 'logs': head + "python " + script_dir + "/logs_backup.py " + param['sname'] + log + " " + str(param['save']), + 'path': head + "python3 " + script_dir + "/backup.py path " + param['sname'] + " " + str(param['save']), + 'site': head + "python3 " + script_dir + "/backup.py site " + param['sname'] + " " + str(param['save']), + 'database': head + "python3 " + script_dir + "/backup.py database " + param['sname'] + " " + str(param['save']), + 'logs': head + "python3 " + script_dir + "/logs_backup.py " + param['sname'] + log + " " + str(param['save']), 'rememory': head + "/bin/bash " + script_dir + '/rememory.sh' } if param['backup_to'] != 'localhost': diff --git a/class/core/mw.py b/class/core/mw.py index 81d892da7f..c53f897bc7 100755 --- a/class/core/mw.py +++ b/class/core/mw.py @@ -552,7 +552,7 @@ def getSpeed(): return json.loads(data) -def getLastLine(inputfile, lineNum): +def getLastLineBk(inputfile, lineNum): # 读文件指定倒数行数 try: fp = open(inputfile, 'rb') @@ -585,7 +585,7 @@ def getLastLine(inputfile, lineNum): # return getMsg('TASK_SLEEP') -def getNumLines(path, num, p=1): +def getLastLine(path, num, p=1): pyVersion = sys.version_info[0] try: import html @@ -624,7 +624,7 @@ def getNumLines(path, num, p=1): t_buf = fp.read(to_read) if pyVersion == 3: if type(t_buf) == bytes: - t_buf = t_buf.decode('utf-8') + t_buf = t_buf.decode("utf-8", "ignore").strip() buf = t_buf + buf fp.seek(-to_read, 1) if pos - to_read == 0: diff --git a/mw-cli b/mw-cli deleted file mode 100755 index 8d2b919f43..0000000000 --- a/mw-cli +++ /dev/null @@ -1,86 +0,0 @@ -#!/www/server/mdserver-web/bin/python -# description: mdserver-web cli tools -# ln -s /www/server/mdserver-web/mw-cli /usr/bin/mw-cli -import os -import sys - - -def mw_start(): - """ - Start mdserver-web - """ - os.system('systemctl start mw') - print("服务已启动") - - -def mw_stop(): - """ - stop mdserver-web - """ - os.system('systemctl stop mw') - print("服务已停止") - - -def mw_restart(): - """ - restart mdserver-web - """ - os.system('systemctl restart mw') - print("服务已重启") - - -def mw_reset_username(): - """ - reset mdserver-web username - """ - from tools import set_panel_username - user_name = input("请输入新的用户名: ") - set_panel_username(user_name) - - -def mw_reset_pwd(): - """ - reset mdserver-web password - """ - from tools import set_panel_pwd - pwd = input("请输入新的密码: ") - set_panel_pwd(pwd, True) - - -if __name__ == '__main__': - - if os.geteuid() != 0: - print("请使用root账户执行该命令.") - sys.exit(1) - - os.chdir("/www/server/mdserver-web") - sys.path.append(os.getcwd() + "/class/core") - - try: - str = ''' - ==== mdserver-web cli tools ==== - 1. 启动服务 2. 停止服务 - 3. 重启服务 4. 修改用户名 - 5. 修改密码 - ================================= - ''' - if len(sys.argv) == 2: - sw = sys.argv[1] - else: - print(str) - sw = input("请输入您要进行的操作: ") - - if sw == '1': - mw_start() - elif sw == '2': - mw_stop() - elif sw == '3': - mw_restart() - elif sw == '4': - mw_reset_username() - elif sw == '5': - mw_reset_pwd() - else: - print("操作不存在") - except KeyboardInterrupt: - print("\n操作已终止") diff --git a/plugins/clean/index.html b/plugins/clean/index.html index 23cc972a73..0a67006105 100755 --- a/plugins/clean/index.html +++ b/plugins/clean/index.html @@ -3,6 +3,7 @@

服务

配置修改

+

运行日志

说明

@@ -16,7 +17,10 @@ function pRead(){ var readme = ''; $('.soft-man-con').html(readme); diff --git a/plugins/clean/index.py b/plugins/clean/index.py index 4d993f6b74..3d2f0e8a66 100755 --- a/plugins/clean/index.py +++ b/plugins/clean/index.py @@ -53,34 +53,94 @@ def getArgs(): return tmp +def getLockFile(): + return getServerDir() + "/installed_lock.pl" + + +def runLog(): + return getServerDir() + "/clean.log" + + def status(): - if os.path.exists(getConf()): + initConf() + if os.path.exists(getLockFile()): return "start" return 'stop' +def initConf(): + conf = getConf() + if not os.path.exists(conf): + content = "" + + clog = [ + "/var/log/cron-*", + "/var/log/maillog-*", + "/var/log/secure-*", + "/var/log/spooler-*", + "/var/log/yum.log-*", + "/var/log/messages-*", + "/var/log/btmp-*", + "/var/log/audit/audit.log.*", + "/var/log/rhsm/rhsm.log-*", + "/var/log/rhsm/rhsmcertd.log-*", + "/tmp/yum_save_*", + "/tmp/tmp.*", + ] + for i in clog: + content += i + "\n" + + # 常用日志 + clogcom = [ + "/var/log/messages", + "/var/log/btmp", + "/var/log/wtmp", + "/var/log/secure", + "/var/log/lastlog", + "/var/log/cron", + ] + for i in clogcom: + if os.path.exists(i): + content += i + "\n" + + # 清理日志 + rootDir = "/var/log" + + l = os.listdir(rootDir) + for x in range(len(l)): + abspath = rootDir + "/" + l[x] + content += abspath + "\n" + mw.writeFile(conf, content) + + def start(): - file = initDreplace() - data = mw.execShell(file + ' start') - if data[1] == '': + initConf() + + lock_file = getLockFile() + if not os.path.exists(lock_file): + mw.writeFile(lock_file, "") + + import tool_task + tool_task.createBgTask() return 'ok' + return 'fail' def stop(): - file = initDreplace() - data = mw.execShell(file + ' stop') - if data[1] == '': + initConf() + lock_file = getLockFile() + if os.path.exists(lock_file): + os.remove(lock_file) + import tool_task + tool_task.removeBgTask() return 'ok' + return 'fail' def reload(): - file = initDreplace() - data = mw.execShell(file + ' reload') - if data[1] == '': - return 'ok' - return 'fail' + return 'ok' def get_filePath_fileName_fileExt(filename): @@ -93,15 +153,20 @@ def cleanFileLog(path): filepath, shotname, extension = get_filePath_fileName_fileExt(path) if extension == ".log": cmd = "echo \"\" > " + path + tmp = mw.execShell(cmd) + if tmp[1] != "": + cmd += " | error:" + tmp[1].strip() print(cmd) - print(mw.execShell(cmd)) def cleanSelfFileLog(path): filepath, shotname, extension = get_filePath_fileName_fileExt(path) - cmd = "echo \"\" > " + path - print(cmd) - print(mw.execShell(cmd)) + if extension == ".log": + cmd = "echo \"\" > " + path + tmp = mw.execShell(cmd) + if tmp[1] != "": + cmd += " | error:" + tmp[1].strip() + print(cmd) def cleanDirLog(path): @@ -115,70 +180,28 @@ def cleanDirLog(path): def cleanLog(): - # 清理日志 - rootDir = "/var/log" - print("clean start") - - clog = [ - "rm -rf /var/log/cron-*", - "rm -rf /var/log/maillog-*", - "rm -rf /var/log/secure-*", - "rm -rf /var/log/spooler-*", - "rm -rf /var/log/yum.log-*", - "rm -rf /var/log/messages-*", - "rm -rf /var/log/btmp-*", - "rm -rf /var/log/audit/audit.log.*", - "rm -rf /var/log/rhsm/rhsm.log-*", - "rm -rf /var/log/rhsm/rhsmcertd.log-*", - "rm -rf /tmp/yum_save_*", - "rm -rf /tmp/tmp.*", - ] - - for i in clog: - print(i) - mw.execShell(i) - - # 常用日志 - clogcom = [ - "/var/log/messages", - "/var/log/btmp", - "/var/log/wtmp", - "/var/log/secure", - "/var/log/lastlog", - "/var/log/cron", - ] - for i in clogcom: - if os.path.exists(i): - mw.execShell("echo \"\" > " + i) - - l = os.listdir(rootDir) - for x in range(len(l)): - abspath = rootDir + "/" + l[x] - if os.path.isfile(abspath): - cleanFileLog(abspath) - - if os.path.isdir(abspath): - cleanDirLog(abspath) - - print("conf clean") - - confFile = getServerDir() - # mw.readFile() - confFile = confFile + "/clean.conf" - clist = mw.readFile(confFile).strip() + conf = getConf() + clist = mw.readFile(conf).strip() clist = clist.split("\n") for x in clist: abspath = x.strip() + + if abspath.find('*') > 1: + cmd = 'rm -rf ' + abspath + print(cmd) + data = mw.execShell(cmd) + # print(data) + continue + if os.path.exists(abspath): if os.path.isfile(abspath): cleanSelfFileLog(abspath) + continue if os.path.isdir(abspath): cleanDirLog(abspath) - print("conf clean end") - - print("clean end") + continue if __name__ == "__main__": func = sys.argv[1] @@ -194,6 +217,8 @@ def cleanLog(): print(reload()) elif func == 'conf': print(getConf()) + elif func == 'run_log': + print(runLog()) elif func == 'clean': cleanLog() else: diff --git a/plugins/clean/install.sh b/plugins/clean/install.sh index 7d82a8f56b..25c89387b8 100755 --- a/plugins/clean/install.sh +++ b/plugins/clean/install.sh @@ -13,6 +13,10 @@ serverPath=$(dirname "$rootPath") install_tmp=${rootPath}/tmp/mw_install.pl VERSION=$2 +if [ -f ${rootPath}/bin/activate ];then + source ${rootPath}/bin/activate +fi + Install_app() { @@ -21,12 +25,14 @@ Install_app() echo "" > $serverPath/clean/clean.conf + cd ${rootPath} && python3 ${rootPath}/plugins/clean/index.py start echo "${VERSION}" > $serverPath/clean/version.pl echo '安装完成' > $install_tmp } Uninstall_app() { + cd ${rootPath} && python3 ${rootPath}/plugins/clean/index.py stop rm -rf $serverPath/clean echo "Uninstall_clean" > $install_tmp } diff --git a/plugins/clean/tool_task.py b/plugins/clean/tool_task.py new file mode 100644 index 0000000000..be7868365d --- /dev/null +++ b/plugins/clean/tool_task.py @@ -0,0 +1,154 @@ +# coding:utf-8 + +import sys +import io +import os +import time +import json + +sys.path.append(os.getcwd() + "/class/core") +import mw + + +app_debug = False +if mw.isAppleSystem(): + app_debug = True + + +def getPluginName(): + return 'clean' + + +def getPluginDir(): + return mw.getPluginDir() + '/' + getPluginName() + + +def getServerDir(): + return mw.getServerDir() + '/' + getPluginName() + + +def getTaskConf(): + conf = getServerDir() + "/task_config.json" + return conf + + +def getConfigData(): + try: + return json.loads(mw.readFile(getTaskConf())) + except: + pass + return [] + + +def getConfigTpl(): + tpl = { + "name": "", + "task_id": -1, + } + return tpl + + +def createBgTask(): + removeBgTask() + args = { + "period": "day", + "hour": "2", + "minute": "30", + } + createBgTaskByName(getPluginName(), args) + + +def createBgTaskByName(name, args): + cfg = getConfigTpl() + _name = "[勿删]日志清理[" + name + "]" + res = mw.M("crontab").field("id, name").where("name=?", (_name,)).find() + if res: + return True + + if "task_id" in cfg.keys() and cfg["task_id"] > 0: + res = mw.M("crontab").field("id, name").where( + "id=?", (cfg["task_id"],)).find() + if res and res["id"] == cfg["task_id"]: + print("计划任务已经存在!") + return True + import crontab_api + api = crontab_api.crontab_api() + + period = args['period'] + _hour = '' + _minute = '' + _where1 = '' + _type_day = "day" + if period == 'day': + _type_day = 'day' + _hour = args['hour'] + _minute = args['minute'] + elif period == 'minute-n': + _type_day = 'minute-n' + _where1 = args['minute-n'] + _minute = '' + + cmd = ''' +rname=%s +plugin_path=%s +script_path=%s +logs_file=$plugin_path/${rname}.log +''' % (name, getServerDir(), getPluginDir()) + cmd += 'echo "★【`date +"%Y-%m-%d %H:%M:%S"`】 STSRT★" >> $logs_file' + "\n" + cmd += 'echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" >> $logs_file' + "\n" + cmd += 'echo "python3 $script_path/index.py clean >> $logs_file 2>&1"' + "\n" + cmd += 'python3 $script_path/index.py clean >> $logs_file 2>&1' + "\n" + cmd += 'echo "【`date +"%Y-%m-%d %H:%M:%S"`】 END★" >> $logs_file' + "\n" + cmd += 'echo "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" >> $logs_file' + "\n" + + params = { + 'name': _name, + 'type': _type_day, + 'week': "", + 'where1': _where1, + 'hour': _hour, + 'minute': _minute, + 'save': "", + 'backup_to': "", + 'stype': "toShell", + 'sname': '', + 'sbody': cmd, + 'urladdress': '', + } + + task_id = api.add(params) + if task_id > 0: + cfg["task_id"] = task_id + cfg["name"] = name + + _dd = getConfigData() + _dd.append(cfg) + mw.writeFile(getTaskConf(), json.dumps(_dd)) + + +def removeBgTask(): + cfg_list = getConfigData() + for x in range(len(cfg_list)): + cfg = cfg_list[x] + if "task_id" in cfg.keys() and cfg["task_id"] > 0: + res = mw.M("crontab").field("id, name").where( + "id=?", (cfg["task_id"],)).find() + if res and res["id"] == cfg["task_id"]: + import crontab_api + api = crontab_api.crontab_api() + data = api.delete(cfg["task_id"]) + if data[0]: + cfg["task_id"] = -1 + cfg_list[x] = cfg + mw.writeFile(getTaskConf(), '[]') + return True + return False + + +if __name__ == "__main__": + if len(sys.argv) > 1: + action = sys.argv[1] + if action == "remove": + removeBgTask() + elif action == "add": + createBgTask() diff --git a/plugins/gitea/hook/commit.tpl b/plugins/gitea/hook/commit.tpl new file mode 100755 index 0000000000..7070accf54 --- /dev/null +++ b/plugins/gitea/hook/commit.tpl @@ -0,0 +1,39 @@ +#!/bin/bash + +echo `date` + +GITADDR="{$GITROOTURL}/{$USERNAME}/{$PROJECT}.git" +GIT_SDIR="{$CODE_DIR}" + +GIT_USER_DIR="${GIT_SDIR}/{$USERNAME}" +GIT_PROJECT_DIR="${GIT_USER_DIR}/{$PROJECT}" + + +git config --global credential.helper store + +# echo $GIT_PROJECT_DIR +if [ ! -d $GIT_PROJECT_DIR ];then + mkdir -p $GIT_USER_DIR && cd $GIT_USER_DIR + git clone $GITADDR +fi + +unset GIT_DIR +cd $GIT_PROJECT_DIR && git pull + +# func 2 +# cd $GIT_PROJECT_DIR && env -i git pull origin master + + +#更新的目的地址 +WEB_PATH={$WEB_ROOT}/{$USERNAME}/{$PROJECT} +mkdir -p $WEB_PATH + +rsync -vauP --delete --exclude=".*" $GIT_PROJECT_DIR/ $WEB_PATH + +sysName=`uname` +if [ $sysName == 'Darwin' ]; then + USER=$(who | sed -n "2,1p" |awk '{print $1}') + chown -R $USER:staff $WEB_PATH +else + chown -R www:www $WEB_PATH +fi \ No newline at end of file diff --git a/plugins/gitea/hook/commit.tpl.ssh b/plugins/gitea/hook/commit.tpl.ssh new file mode 100755 index 0000000000..6aac78ca85 --- /dev/null +++ b/plugins/gitea/hook/commit.tpl.ssh @@ -0,0 +1,36 @@ +#!/bin/bash + +echo `date` + +GITADDR="{$GITROOTURL}/{$USERNAME}/{$PROJECT}" +GIT_SDIR="{$CODE_DIR}" + +GIT_USER_DIR="${GIT_SDIR}/{$USERNAME}" +GIT_PROJECT_DIR="${GIT_USER_DIR}/{$PROJECT}" + +# echo $GIT_PROJECT_DIR +if [ ! -d $GIT_PROJECT_DIR ];then + mkdir -p $GIT_USER_DIR && cd $GIT_USER_DIR + git clone $GITADDR +fi + +unset GIT_DIR +cd $GIT_PROJECT_DIR && git pull + +# func 2 +# cd $GIT_PROJECT_DIR && env -i git pull origin master + + + +WEB_PATH={$WEB_ROOT}/{$USERNAME}/{$PROJECT} +mkdir -p $WEB_PATH + +rsync -vauP --delete --exclude=".*" $GIT_PROJECT_DIR/ $WEB_PATH + +sysName=`uname` +if [ $sysName == 'Darwin' ]; then + USER=$(who | sed -n "2,1p" |awk '{print $1}') + chown -R $USER:staff $WEB_PATH +else + chown -R www:www $WEB_PATH +fi \ No newline at end of file diff --git a/plugins/gitea/hook/post-receive.tpl b/plugins/gitea/hook/post-receive.tpl new file mode 100755 index 0000000000..0c747ce2f3 --- /dev/null +++ b/plugins/gitea/hook/post-receive.tpl @@ -0,0 +1,3 @@ +#!/bin/bash + +sh -x {$PATH}/commit 2>{$PATH}/sh.log \ No newline at end of file diff --git a/plugins/gitea/ico.png b/plugins/gitea/ico.png new file mode 100644 index 0000000000..5dacd7735d Binary files /dev/null and b/plugins/gitea/ico.png differ diff --git a/plugins/gitea/index.html b/plugins/gitea/index.html new file mode 100755 index 0000000000..8d9fe51d42 --- /dev/null +++ b/plugins/gitea/index.html @@ -0,0 +1,24 @@ +
+
+
+

服务

+

自启动

+ +

手动编辑

+

配置文件

+

配置修改

+

用户列表

+

运行日志

+

提交日志

+

使用说明

+
+
+
+
+
+
+ \ No newline at end of file diff --git a/plugins/gogs/bak/index_2022_6_19.py b/plugins/gitea/index.py similarity index 74% rename from plugins/gogs/bak/index_2022_6_19.py rename to plugins/gitea/index.py index 9bfc0b2a71..2c8d401ce1 100755 --- a/plugins/gogs/bak/index_2022_6_19.py +++ b/plugins/gitea/index.py @@ -11,11 +11,10 @@ import mw -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) -import psutil +# 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 @@ -24,15 +23,12 @@ def getPluginName(): - return 'gogs' + return 'gitea' def getPluginDir(): return mw.getPluginDir() + '/' + getPluginName() -sys.path.append(getPluginDir() + "/class") -import mysqlDb - def getServerDir(): return mw.getServerDir() + '/' + getPluginName() @@ -61,18 +57,28 @@ def getArgs(): 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 getInitdConfTpl(): - path = getPluginDir() + "/init.d/gogs.tpl" + path = getPluginDir() + "/init.d/gitea.tpl" return path def getInitdConf(): - path = getServerDir() + "/init.d/gogs" + path = getServerDir() + "/init.d/gitea" return path def getConf(): path = getServerDir() + "/custom/conf/app.ini" + + if not os.path.exists(path): + return mw.returnJson(False, "请先安装初始化!
默认地址:http://" + mw.getLocalIp() + ":3000") return path @@ -95,7 +101,7 @@ def getHomeDir(): "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() return '/Users/' + user else: - return '/root' + return 'git' def getRunUser(): @@ -104,7 +110,7 @@ def getRunUser(): "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() return user else: - return 'root' + return 'git' __SR = '''#!/bin/bash PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin @@ -140,13 +146,16 @@ def initDreplace(): mw.writeFile(file_bin, content) mw.execShell('chmod +x ' + file_bin) - conf_bin = getConf() - if not os.path.exists(conf_bin): - mw.execShell('mkdir -p ' + getServerDir() + '/custom/conf') - conf_tpl = getConfTpl() - content = mw.readFile(conf_tpl) - content = contentReplace(content) - mw.writeFile(conf_bin, content) + # systemd + systemDir = mw.systemdCfgDir() + systemService = systemDir + '/gitea.service' + systemServiceTpl = getPluginDir() + '/init.d/gitea.service.tpl' + if os.path.exists(systemDir) and not os.path.exists(systemService): + service_path = mw.getServerDir() + se_content = mw.readFile(systemServiceTpl) + se_content = se_content.replace('{$SERVER_PATH}', service_path) + mw.writeFile(systemService, se_content) + mw.execShell('systemctl daemon-reload') log_path = getServerDir() + '/log' if not os.path.exists(log_path): @@ -159,9 +168,14 @@ def getRootUrl(): content = mw.readFile(getConf()) rep = 'ROOT_URL\s*=\s*(.*)' tmp = re.search(rep, content) - if not tmp: - return '' - return tmp.groups()[0] + if tmp: + return tmp.groups()[0] + + rep = 'EXTERNAL_URL\s*=\s*(.*)' + tmp = re.search(rep, content) + if tmp: + return tmp.groups()[0] + return '' def getSshPort(): @@ -192,8 +206,11 @@ def getRootPath(): def getDbConfValue(): - content = mw.readFile(getConf()) + conf = getConf() + if not os.path.exists(conf): + return {} + content = mw.readFile(conf) rep_scope = "\[database\](.*?)\[" tmp = re.findall(rep_scope, content, re.S) @@ -207,18 +224,72 @@ def getDbConfValue(): return r -def pMysqlDb(): - conf = getDbConfValue() - +def pMysqlDb(conf): host = conf['HOST'].split(':') - conn = mysqlDb.mysqlDb() + # pymysql + db = mw.getMyORM() + # MySQLdb | + # db = mw.getMyORMDb() + + db.setPort(int(host[1])) + db.setUser(conf['USER']) + + if 'PASSWD' in conf: + db.setPwd(conf['PASSWD']) + else: + db.setPwd(conf['PASSWORD']) + + db.setDbName(conf['NAME']) + # db.setSocket(getSocketFile()) + db.setCharset("utf8") + return db + + +def pSqliteDb(conf): + # print(conf) + import db + psDb = db.Sql() + + # 默认 + gsdir = getServerDir() + '/data' + dbname = 'gitea' + if conf['PATH'][0] == '/': + # 绝对路径 + pass + else: + path = conf['PATH'].split('/') + gsdir = getServerDir() + '/' + path[0] + dbname = path[1].split('.')[0] - conn.setHost(host[0]) - conn.setUser(conf['USER']) - conn.setPwd(conf['PASSWD']) - conn.setPort(int(host[1])) - conn.setDb(conf['NAME']) - return conn + # print(gsdir, dbname) + psDb.dbPos(gsdir, dbname) + return psDb + + +def getGiteaDbType(conf): + + if 'DB_TYPE' in conf: + return conf['DB_TYPE'] + + if 'TYPE' in conf: + return conf['TYPE'] + + return 'NONE' + + +def pQuery(sql): + conf = getDbConfValue() + gtype = getGiteaDbType(conf) + if gtype == 'sqlite3': + db = pSqliteDb(conf) + data = db.query(sql, []).fetchall() + return data + elif gtype == 'mysql': + db = pMysqlDb(conf) + return db.query(sql) + + print("仅支持mysql|sqlite3配置") + exit(0) def isSqlError(mysqlMsg): @@ -244,93 +315,66 @@ def isSqlError(mysqlMsg): return mw.returnData(True, 'OK') -def start(): - - is_frist = True - conf_bin = getConf() - if os.path.exists(conf_bin): - is_frist = False - +def appOp(method): file = initDreplace() - if is_frist: - return "第一次启动Gogs,默认使用MySQL连接!
可以在配置文件中重新设置,再启动!" - - conn = pMysqlDb() - list_table = conn.query('show tables') - data = isSqlError(list_table) - if not data['status']: - return data['msg'] + if not mw.isAppleSystem(): + data = mw.execShell('systemctl ' + method + ' ' + getPluginName()) + if data[1] == '': + return 'ok' + return 'fail' - data = mw.execShell(__SR + file + ' start') + data = mw.execShell(__SR + file + ' ' + method) if data[1] == '': return 'ok' return data[0] +def start(): + return appOp('start') + + def stop(): - file = initDreplace() - data = mw.execShell(__SR + file + ' stop') - if data[1] == '': - return 'ok' - return data[1] + return appOp('stop') def restart(): - file = initDreplace() - data = mw.execShell(__SR + file + ' restart') - if data[1] == '': - return 'ok' - return data[1] + return appOp('restart') def reload(): - file = initDreplace() - data = mw.execShell(__SR + file + ' reload') - if data[1] == '': - return 'ok' - return data[1] + return appOp('reload') def initdStatus(): - if not app_debug: - os_name = mw.getOs() - if os_name == 'darwin': - return "Apple Computer does not support" - initd_bin = getInitDFile() - if os.path.exists(initd_bin): - return 'ok' - return 'fail' + if mw.isAppleSystem(): + return "Apple Computer does not support" + + shell_cmd = 'systemctl status gitea | grep loaded | grep "enabled;"' + data = mw.execShell(shell_cmd) + if data[0] == '': + return 'fail' + return 'ok' def initdInstall(): - import shutil - if not app_debug: - os_name = mw.getOs() - if os_name == 'darwin': - return "Apple Computer does not support" - - mem_bin = initDreplace() - initd_bin = getInitDFile() - shutil.copyfile(mem_bin, initd_bin) - mw.execShell('chmod +x ' + initd_bin) - mw.execShell('chkconfig --add ' + getPluginName()) + if mw.isAppleSystem(): + return "Apple Computer does not support" + + mw.execShell('systemctl enable gitea') return 'ok' def initdUinstall(): - if not app_debug: - os_name = mw.getOs() - if os_name == 'darwin': - return "Apple Computer does not support" - initd_bin = getInitDFile() - os.remove(initd_bin) - mw.execShell('chkconfig --del ' + getPluginName()) + if mw.isAppleSystem(): + return "Apple Computer does not support" + + mw.execShell('systemctl disable gitea') return 'ok' def runLog(): - log_path = getServerDir() + '/log/gogs.log' + log_path = getServerDir() + '/log/gitea.log' return log_path @@ -340,6 +384,10 @@ def postReceiveLog(): def getGogsConf(): + conf = getConf() + if not os.path.exists(conf): + return mw.returnJson(False, "请先安装初始化!
默认地址:http://" + mw.getLocalIp() + ":3000") + gets = [ {'name': 'DOMAIN', 'type': -1, 'ps': '服务器域名'}, {'name': 'ROOT_URL', 'type': -1, 'ps': '公开的完整URL路径'}, @@ -360,7 +408,7 @@ def getGogsConf(): {'name': 'SHOW_FOOTER_VERSION', 'type': 2, 'ps': 'Gogs版本信息'}, {'name': 'SHOW_FOOTER_TEMPLATE_LOAD_TIME', 'type': 2, 'ps': 'Gogs模板加载时间'}, ] - conf = mw.readFile(getConf()) + conf = mw.readFile(conf) result = [] for g in gets: @@ -370,7 +418,7 @@ def getGogsConf(): continue g['value'] = tmp.groups()[0] result.append(g) - return mw.getJson(result) + return mw.returnJson(True, 'OK', result) def submitGogsConf(): @@ -402,18 +450,27 @@ def submitGogsConf(): def userList(): + + conf = getConf() + if not os.path.exists(conf): + return mw.returnJson(False, "请先安装初始化!
默认地址:http://" + mw.getLocalIp() + ":3000") + + conf = getDbConfValue() + gtype = getGiteaDbType(conf) + if gtype != 'mysql': + return mw.returnJson(False, "仅支持mysql数据操作!") + import math args = getArgs() - page = 1 - page_size = 10 - search = '' - if 'page' in args: - page = int(args['page']) - - if 'page_size' in args: - page_size = int(args['page_size']) + data = checkArgs(args, ['page', 'page_size']) + if not data[0]: + return data[1] + page = int(args['page']) + page_size = int(args['page_size']) + tojs = args['tojs'] + search = '' if 'search' in args: search = args['search'] @@ -421,17 +478,14 @@ def userList(): data['root_url'] = getRootUrl() - pm = pMysqlDb() start = (page - 1) * page_size - list_count = pm.query('select count(id) as num from user') - count = list_count[0][0] + list_count = pQuery('select count(id) as num from user') - list_data = pm.query( + count = list_count[0]["num"] + list_data = pQuery( 'select id,name,email from user order by id desc limit ' + str(start) + ',' + str(page_size)) - - page_info = {'count': count, 'p': page, - 'row': page_size, 'tojs': 'gogsUserList'} - data['list'] = mw.getPage(page_info) + data['list'] = mw.getPage( + {'count': count, 'p': page, 'row': page_size, 'tojs': tojs}) data['page'] = page data['page_size'] = page_size data['page_count'] = int(math.ceil(count / page_size)) @@ -556,8 +610,8 @@ def projectScriptLoad(): cc_content = mw.readFile(commit_tpl) - sshUrl = 'http://127.0.0.1:' + getHttpPort() - cc_content = cc_content.replace('{$GITROOTURL}', sshUrl) + gitPath = getRootPath() + cc_content = cc_content.replace('{$GITROOTURL}', gitPath) cc_content = cc_content.replace('{$CODE_DIR}', codeDir) cc_content = cc_content.replace('{$USERNAME}', user) cc_content = cc_content.replace('{$PROJECT}', args['name']) @@ -570,11 +624,9 @@ def projectScriptLoad(): def projectScriptUnload(): args = getArgs() - if not 'user' in args: - return mw.returnJson(True, 'username missing') - - if not 'name' in args: - return mw.returnJson(True, 'project name missing') + data = checkArgs(args, ['user', 'name']) + if not data[0]: + return data[1] user = args['user'] name = args['name'] + '.git' @@ -591,11 +643,10 @@ def projectScriptUnload(): def projectScriptDebug(): args = getArgs() - if not 'user' in args: - return mw.returnJson(True, 'username missing') + data = checkArgs(args, ['user', 'name']) + if not data[0]: + return data[1] - if not 'name' in args: - return mw.returnJson(True, 'project name missing') user = args['user'] name = args['name'] + '.git' commit_log = getRootPath() + '/' + user + '/' + name + \ @@ -634,14 +685,8 @@ def getTotalStatistics(): st = status() data = {} if st.strip() == 'start': - pm = pMysqlDb() - list_count = pm.query('select count(id) as num from repository') - - if list_count.find("error") > -1: - data['status'] = False - data['count'] = 0 - return mw.returnJson(False, 'fail', data) - + list_count = pQuery('select count(id) as num from repository') + count = list_count[0]["num"] data['status'] = True data['count'] = count data['ver'] = mw.readFile(getServerDir() + '/version.pl').strip() diff --git a/plugins/gitea/info.json b/plugins/gitea/info.json new file mode 100755 index 0000000000..2eac70638f --- /dev/null +++ b/plugins/gitea/info.json @@ -0,0 +1,16 @@ +{ + "ps": "Gitea 是一个开源社区驱动的轻量级代码托管解决方案。", + "name": "gitea", + "title": "Gitea", + "versions": ["1.17.2"], + "tip": "soft", + "checks": "server/gitea", + "path":"server/gitea", + "author": "gitea", + "date": "2022-10-03", + "home": "https://dl.gitea.io/", + "type": "Git服务器", + "shell": "install.sh", + "pid": "3", + "sort": 7 +} \ No newline at end of file diff --git a/plugins/gitea/init.d/gitea.service.tpl b/plugins/gitea/init.d/gitea.service.tpl new file mode 100644 index 0000000000..31c93873d7 --- /dev/null +++ b/plugins/gitea/init.d/gitea.service.tpl @@ -0,0 +1,20 @@ +[Unit] +Description=Gitea (Git with a cup of tea) +After=syslog.target +After=network.target + +[Service] +RestartSec=2s +Type=simple +User=git +Group=git +WorkingDirectory={$SERVER_PATH}/gitea +ExecStart={$SERVER_PATH}/gitea/gitea web +Restart=always +Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea +RemainAfterExit=yes +#AmbientCapabilities=CAP_NET_BIND_SERVICE +#CapabilityBoundingSet=CAP_NET_BIND_SERVICE + +[Install] +WantedBy=multi-user.target diff --git a/plugins/gitea/init.d/gitea.tpl b/plugins/gitea/init.d/gitea.tpl new file mode 100644 index 0000000000..b00abdf6f9 --- /dev/null +++ b/plugins/gitea/init.d/gitea.tpl @@ -0,0 +1,110 @@ +#!/bin/sh +# +# /etc/rc.d/init.d/Gitea +# +# Runs the Gogs +# +# +# chkconfig: - 85 15 +# + +### BEGIN INIT INFO +# Provides: Gitea +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Should-Start: mysql postgresql +# Should-Stop: mysql postgresql +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Start Gitea at boot time. +# Description: Control Gitea. +### END INIT INFO + +# Source function library. +if [ -f /etc/init.d/functions ];then + . /etc/init.d/functions +fi + +if [ -f /etc/rc.d/init.d/functions ];then + . /etc/rc.d/init.d/functions +fi + +# Default values +export HOME={$HOME_DIR} +export USER={$RUN_USER} +NAME=gitea +GOGS_HOME={$SERVER_PATH}/gitea +GOGS_PATH=${GOGS_HOME}/$NAME +GOGS_USER={$RUN_USER} +SERVICENAME="gitea" +LOCKFILE=/tmp/gitea.lock +LOGPATH=${GOGS_HOME}/log +LOGFILE=${LOGPATH}/gitea.log +RETVAL=0 + + +[ -r /etc/sysconfig/$NAME ] && . /etc/sysconfig/$NAME +DAEMON_OPTS="--check $NAME" +[ ! -z "$GOGS_USER" ] && DAEMON_OPTS="$DAEMON_OPTS --user=${GOGS_USER}" + + +status(){ + isStart=`ps -ef|grep 'gitea web' |grep -v grep|awk '{print $2}'` + if [ "$isStart" == '' ];then + echo -e "${SERVICENAME} not running" + else + echo -e "${SERVICENAME}(pid $(echo $isStart)) already running" + fi +} + +start() { + isStart=`ps -ef|grep 'gitea web' |grep -v grep|awk '{print $2}'` + if [ "$isStart" != '' ];then + echo "${SERVICENAME}(pid $(echo $isStart)) already running" + return $RETVAL + fi + + cd ${GOGS_HOME} + echo -e "Starting ${SERVICENAME}: \c" + ${GOGS_PATH} web > ${LOGFILE} 2>&1 & + RETVAL=$? + [ $RETVAL = 0 ] && touch ${LOCKFILE} && echo -e "\033[32mdone\033[0m" + return $RETVAL +} + +stop() { + + pids=`ps -ef|grep 'gitea web' |grep -v grep|awk '{print $2}'` + arr=($pids) + echo -e "Stopping gitea... \c" + for p in ${arr[@]} + do + kill -9 $p + done + echo -e "\033[32mdone\033[0m" +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + status) + status + ;; + restart) + stop + start + ;; + reload) + stop + start + ;; + *) + echo "Usage: ${NAME} {start|stop|status|restart}" + exit 1 + ;; +esac +exit $RETVAL diff --git a/plugins/gitea/install.sh b/plugins/gitea/install.sh new file mode 100755 index 0000000000..d9dbd926da --- /dev/null +++ b/plugins/gitea/install.sh @@ -0,0 +1,111 @@ +#!/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") + + +install_tmp=${rootPath}/tmp/mw_install.pl +if [ -f ${rootPath}/bin/activate ];then + source ${rootPath}/bin/activate +fi + + +URL_DOWNLOAD=https://dl.gitea.io/ + +getOs(){ + os=`uname` + if [ "Darwin" == "$os" ];then + echo 'darwin' + else + echo 'linux' + fi + return 0 +} + +getBit(){ + echo `getconf LONG_BIT` +} + + +Install_App() +{ + mkdir -p $serverPath/source/gitea + + + if id git &> /dev/null ;then + echo "git UID is `id -u git`" + echo "git Shell is `grep "^git:" /etc/passwd |cut -d':' -f7 `" + else + groupadd git + useradd -g git git + fi + + + echo '正在安装脚本文件...' > $install_tmp + version=$1 + os=`getOs` + + git config --global push.default simple + + if [ "darwin" == "$os" ];then + file=gitea-${version}-darwin-10.12-amd64 + else + file=gitea-${version}-linux-amd64 + fi + + file_xz="${file}.xz" + echo "wget -O $serverPath/source/gitea/$file_xz ${URL_DOWNLOAD}/gitea/${version}/${file_xz}" + if [ ! -f $serverPath/source/gitea/$file_xz ];then + wget -O $serverPath/source/gitea/$file_xz ${URL_DOWNLOAD}/gitea/${version}/${file_xz} + fi + + cd $serverPath/source/gitea && xz -k -d $file_xz + if [ -f $file ];then + mkdir -p $serverPath/gitea + mv $serverPath/source/gitea/$file $serverPath/gitea/gitea + chmod +x $serverPath/gitea/gitea + + chown -R git:git $serverPath/gitea + fi + + + if [ -d $serverPath/gitea ];then + echo $version > $serverPath/gitea/version.pl + + cd ${rootPath} && python3 plugins/gitea/index.py start + cd ${rootPath} && python3 plugins/gitea/index.py initd_install + fi + + echo 'install success' > $install_tmp +} + +Uninstall_App() +{ + + if [ -f /usr/lib/systemd/system/gitea.service ];then + systemctl stop gitea + systemctl disable gitea + rm -rf /usr/lib/systemd/system/gitea.service + systemctl daemon-reload + fi + + if [ -f $serverPath/gitea/initd/gitea ];then + $serverPath/gitea/initd/gitea stop + fi + + rm -rf $serverPath/gitea + echo 'uninstall success' > $install_tmp +} + + +action=$1 +version=$2 +if [ "${1}" == 'install' ];then + Install_App $version +else + Uninstall_App $version +fi diff --git a/plugins/gitea/js/gitea.js b/plugins/gitea/js/gitea.js new file mode 100755 index 0000000000..8f0a6071ab --- /dev/null +++ b/plugins/gitea/js/gitea.js @@ -0,0 +1,353 @@ + +function str2Obj(str){ + var data = {}; + kv = str.split('&'); + for(i in kv){ + v = kv[i].split('='); + data[v[0]] = v[1]; + } + return data; +} + +function gogsPost(method,args,callback, title){ + + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(str2Obj(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:'gitea', 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 gogsSetConfig(){ + gogsPost('get_gogs_conf', '', function(data){ + var rrdata = $.parseJSON(data.data); + if (!rrdata.status){ + layer.msg(rrdata.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + var rdata = rrdata.data; + var mlist = ''; + for (var i = 0; i < rdata.length; i++) { + var w = '140'; + if (rdata[i].name == 'error_reporting') w = '250'; + var ibody = ''; + switch (rdata[i].type) { + case 0: + var selected_1 = (rdata[i].value == 1) ? 'selected' : ''; + var selected_0 = (rdata[i].value == 0) ? 'selected' : ''; + ibody = ''; + break; + case 1: + var selected_1 = (rdata[i].value == 'On') ? 'selected' : ''; + var selected_0 = (rdata[i].value == 'Off') ? 'selected' : ''; + ibody = '' + break; + case 2: + var selected_1 = (rdata[i].value == 'true') ? 'selected' : ''; + var selected_0 = (rdata[i].value == 'false') ? 'selected' : ''; + ibody = '' + break; + } + mlist += '

' + rdata[i].name + '' + ibody + ', ' + rdata[i].ps + '

' + } + var html = '
\ + ' + mlist + '\ +
\ + \ +
\ +
'; + $(".soft-man-con").html(html); + }); +} + + +//提交PHP配置 +function submitGogsConf() { + var data = { + DOMAIN: $("input[name='DOMAIN']").val(), + ROOT_URL: $("input[name='ROOT_URL']").val(), + HTTP_ADDR: $("select[name='HTTP_ADDR']").val(), + HTTP_PORT: $("input[name='HTTP_PORT']").val(), + START_SSH_SERVER: $("select[name='START_SSH_SERVER']").val() || 'false', + SSH_PORT: $("input[name='SSH_PORT']").val(), + REQUIRE_SIGNIN_VIEW: $("select[name='REQUIRE_SIGNIN_VIEW']").val() || 'false', + ENABLE_CAPTCHA: $("select[name='ENABLE_CAPTCHA']").val() || 'true', + DISABLE_REGISTRATION: $("select[name='DISABLE_REGISTRATION']").val() || 'false', + ENABLE_NOTIFY_MAIL: $("select[name='ENABLE_NOTIFY_MAIL']").val() || 'false', + FORCE_PRIVATE: $("select[name='FORCE_PRIVATE']").val() || 'false', + SHOW_FOOTER_BRANDING: $("select[name='SHOW_FOOTER_BRANDING']").val() || 'false', + SHOW_FOOTER_VERSION: $("select[name='SHOW_FOOTER_VERSION']").val() || 'false', + SHOW_FOOTER_TEMPLATE_LOAD_TIME: $("select[name='SHOW_FOOTER_TEMPLATE_LOAD_TIME']").val() || 'false', + }; + + gogsPost('submit_gogs_conf', data, function(ret_data){ + var rdata = $.parseJSON(ret_data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + gogsSetConfig(); + }); +} + +function gogsEdit(){ + + gogsPost('gogs_edit',{} , function(data){ + // console.log(data); + var rdata = $.parseJSON(data.data); + var edit = '

通用的手动编辑:

'; + edit +='
\ + \ + \ +
'; + $(".soft-man-con").html(edit); + }); + +} + +function giteaUserList(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; + } + _data['tojs'] = 'giteaUserList'; + + gogsPost('user_list', _data, function(data){ + + var rdata = $.parseJSON(data.data); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + content = '
'; + content += '
'; + + content += '
'; + content += ''; + content += ''; + content += ''; + content += ''; + content += ''; + content += ''; + + content += ''; + + ulist = rdata['data']['data']; + for (i in ulist){ + email = ulist[i]["email"] == '' ? '无' : ulist[i]["email"]; + content += ''+ + ''+ + ''+ + ''+ + ''; + } + + content += ''; + content += '
序号用户或组织邮件地址操作(WEB管理)
'+ulist[i]["id"]+''+ulist[i]["name"]+''+email+'项目管理
'; + + var page = ''; + + content += page; + + $(".soft-man-con").html(content); + }); +} + +function userProjectList(user, search){ + var req = {}; + if (!isNaN(user)){ + req['page'] = user; + req['name'] = user = getCookie('gogsUserSelected'); + } else { + req['page'] = 1; + req['name'] = user; + setCookie('gogsUserSelected', user); + } + + req['page_size'] = 5; + req['search'] = ''; + if(typeof(search) != 'undefined'){ + req['search'] = search; + } + + $('.layui-layer-close1').click(); + gogsPost('user_project_list', req, function(data){ + var rdata = []; + try { + rdata = $.parseJSON(data.data); + } catch(e){} + + if (!rdata['status']){ + layer.msg(rdata['msg'], { icon: 2 }); + return; + } + + var list = ''; + // console.log(rdata); + var project_list = rdata['data']['data']; + for (i in project_list) { + var name = project_list[i]['name']; + list += ''+name+'\ + \ + 源码 | \ + 脚本\ + \ + '; + } + + var page = ''; + + var loadOpen = layer.open({ + type: 1, + title: '用户('+user+')项目列表', + area: '500px', + content:"
\ +
\ +
\ + \ + \ + " + list + "\ +
项目操作
" + + page + + "
" + }); + }); +} + + +function projectScript(user, name,has_hook){ + // console.log(user,name,has_hook); + var html = ''; + if (has_hook){ + html += ''; + html += ''; + html += ''; + html += ''; + } else { + html += ''; + } + + var loadOpen = layer.open({ + type: 1, + title: '['+user+']['+name+']脚本设置', + area: '240px', + content:'
'+html+'
' + }); +} + +function projectScriptEdit(user,name){ + gogsPost('project_script_edit', {'user':user,'name':name}, function(data){ + var rdata = $.parseJSON(data.data); + if (rdata['status']){ + onlineEditFile(0, rdata['data']['path']); + } else { + layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']}); + } + }); +} + +function projectScriptLoad(user,name){ + gogsPost('project_script_load', {'user':user,'name':name}, function(data){ + if (data.data != 'ok'){ + layer.msg(data.data,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + layer.msg('加载成功!',{icon:1,time:2000,shade: [0.3, '#000']}); + setTimeout(function(){ + userProjectList(1); + }, 2000); + }); +} + +function projectScriptUnload(user,name){ + gogsPost('project_script_unload', {'user':user,'name':name}, function(data){ + if (data.data != 'ok'){ + layer.msg(data.data,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + layer.msg('卸载成功!',{icon:1,time:2000,shade: [0.3, '#000']}); + setTimeout(function(){ + userProjectList(1); + }, 2000); + }); +} + +function projectScriptDebug(user,name){ + gogsPost('project_script_debug', {'user':user,'name':name}, function(data){ + var rdata = $.parseJSON(data.data); + if (rdata['status']){ + onlineEditFile(0, rdata['path']); + } else { + layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']}); + } + }); +} + +function getRsaPublic(){ + gogsPost('get_rsa_public', {}, function(data){ + var rdata = $.parseJSON(data.data); + var con = '
\ +
\ + \ +
\ + \ +
' + layer.open({ + type: 1, + area: "600px", + title: '本机公钥', + closeBtn: 2, + shift: 5, + shadeClose: false, + content:con + }); + }); +} + +function giteaRead(){ + + var readme = ''; + + $('.soft-man-con').html(readme); +} \ No newline at end of file diff --git a/plugins/gogs/index.py b/plugins/gogs/index.py index 4193d04c36..08ce6a69a6 100755 --- a/plugins/gogs/index.py +++ b/plugins/gogs/index.py @@ -462,6 +462,11 @@ def userList(): if not os.path.exists(conf): return mw.returnJson(False, "请先安装初始化!
默认地址:http://" + mw.getLocalIp() + ":3000") + conf = getDbConfValue() + gtype = getGogsDbType(conf) + if gtype != 'mysql': + return mw.returnJson(False, "仅支持mysql数据操作!") + import math args = getArgs() diff --git a/plugins/gogs/install.sh b/plugins/gogs/install.sh index 73c8eeb8de..47a264866b 100755 --- a/plugins/gogs/install.sh +++ b/plugins/gogs/install.sh @@ -29,7 +29,6 @@ getBit(){ Install_gogs() { - pip3 install mysqlclient mkdir -p $serverPath/source/gogs diff --git a/plugins/mysql/bak/index_2022_6_18.py b/plugins/mysql/bak/index_2022_6_18.py deleted file mode 100755 index 5651a04062..0000000000 --- a/plugins/mysql/bak/index_2022_6_18.py +++ /dev/null @@ -1,2030 +0,0 @@ -# coding:utf-8 - -import sys -import io -import os -import time -import subprocess -import re -import json - - -# reload(sys) -# sys.setdefaultencoding('utf-8') - -sys.path.append(os.getcwd() + "/class/core") -import 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' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - -sys.path.append(getPluginDir() + "/class") -import mysqlDb - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def getInitDFile(): - if app_debug: - return '/tmp/' + getPluginName() - return '/etc/init.d/' + 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:] - - # print(args) - - # if is_number(args): - # args = sys.argv[3:] - - tmp = {} - args_len = len(args) - - if args_len == 1: - t = args[0].strip('{').strip('}') - t = t.split(':') - tmp[t[0]] = t[1] - elif args_len > 1: - for i in range(len(args)): - t = args[i].split(':') - 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 getConf(): - path = getServerDir() + '/etc/my.cnf' - return path - - -def getInitdTpl(version=''): - path = getPluginDir() + '/init.d/mysql' + version + '.tpl' - return path - - -def contentReplace(content): - service_path = mw.getServerDir() - content = content.replace('{$ROOT_PATH}', mw.getRootDir()) - content = content.replace('{$SERVER_PATH}', service_path) - content = content.replace('{$SERVER_APP_PATH}', service_path + '/mysql') - return content - - -def pSqliteDb(dbname='databases'): - file = getServerDir() + '/mysql.db' - name = 'mysql' - if not os.path.exists(file): - conn = mw.M(dbname).dbPos(getServerDir(), name) - csql = mw.readFile(getPluginDir() + '/conf/mysql.sql') - csql_list = csql.split(';') - for index in range(len(csql_list)): - conn.execute(csql_list[index], ()) - else: - # 现有run - # conn = mw.M(dbname).dbPos(getServerDir(), name) - # csql = mw.readFile(getPluginDir() + '/conf/mysql.sql') - # csql_list = csql.split(';') - # for index in range(len(csql_list)): - # conn.execute(csql_list[index], ()) - conn = mw.M(dbname).dbPos(getServerDir(), name) - return conn - - -def pMysqlDb(): - db = mysqlDb.mysqlDb() - db.__DB_CNF = getConf() - db.setDbConf(getConf()) - db.setPwd(pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root')) - return db - - -def initDreplace(version=''): - initd_tpl = getInitdTpl(version) - - initD_path = getServerDir() + '/init.d' - if not os.path.exists(initD_path): - os.mkdir(initD_path) - - file_bin = initD_path + '/' + getPluginName() - if not os.path.exists(file_bin): - content = mw.readFile(initd_tpl) - content = contentReplace(content) - mw.writeFile(file_bin, content) - mw.execShell('chmod +x ' + file_bin) - - mysql_conf_dir = getServerDir() + '/etc' - if not os.path.exists(mysql_conf_dir): - os.mkdir(mysql_conf_dir) - - mysql_conf = mysql_conf_dir + '/my.cnf' - if not os.path.exists(mysql_conf): - mysql_conf_tpl = getPluginDir() + '/conf/my' + version + '.cnf' - content = mw.readFile(mysql_conf_tpl) - content = contentReplace(content) - mw.writeFile(mysql_conf, content) - - if mw.getOs() != 'darwin': - mw.execShell('chown -R mysql mysql ' + getServerDir()) - return file_bin - - -def status(version=''): - data = mw.execShell( - "ps -ef|grep mysqld |grep -v grep | grep -v python | awk '{print $2}'") - if data[0] == '': - return 'stop' - return 'start' - - -def getDataDir(): - file = getConf() - content = mw.readFile(file) - rep = 'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def binLog(): - 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() - 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() - 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 getErrorLog(): - args = getArgs() - path = getDataDir() - filename = '' - for n in os.listdir(path): - if len(n) < 5: - continue - if n == 'error.log': - filename = path + '/' + n - break - # print filename - if not os.path.exists(filename): - return mw.returnJson(False, '指定文件不存在!') - if 'close' in args: - mw.writeFile(filename, '') - return mw.returnJson(False, '日志已清空') - info = mw.getNumLines(filename, 18) - return mw.returnJson(True, 'OK', info) - - -def getShowLogFile(): - file = getConf() - content = mw.readFile(file) - rep = 'slow-query-log-file\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def pGetDbUser(): - if mw.isAppleSystem(): - user = mw.execShell( - "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() - return user - return 'mysql' - - -def initMysqlData(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - user = pGetDbUser() - cmd = 'cd ' + serverdir + ' && ./scripts/mysql_install_db --user=' + \ - user + ' --basedir=' + serverdir + ' --ldata=' + datadir - mw.execShell(cmd) - return 0 - return 1 - - -def initMysql57Data(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - user = pGetDbUser() - cmd = 'cd ' + serverdir + ' && ./bin/mysqld --defaults-file=' + myconf + \ - ' --initialize --explicit_defaults_for_timestamp' - mw.execShell(cmd) - return 0 - return 1 - - -def initMysql8Data(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - user = pGetDbUser() - cmd = 'cd ' + serverdir + ' && ./bin/mysqld --basedir=' + serverdir + ' --datadir=' + \ - datadir + ' --initialize' - # print(cmd) - mw.execShell(cmd) - return 0 - return 1 - - -def initMysqlPwd(): - time.sleep(5) - - serverdir = getServerDir() - - pwd = mw.getRandomString(16) - cmd_pass = serverdir + '/bin/mysqladmin -uroot password ' + pwd - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - mw.execShell(cmd_pass) - return True - - -def mysql8IsInitedPasswd(): - - serverdir = getServerDir() - pass_cmd = "cat " + serverdir + \ - "/data/error.log | grep root@localhost | awk -F 'root@localhost:' '{print $2}'" - passdata = mw.execShell(pass_cmd) - password = passdata[0].strip() - - if len(password) == 0: - return True - return False - - -def initMysql8Pwd(): - is_start = False - for x in range(60): - data = mw.execShell( - "ps -ef|grep mysql|grep -v grep|grep -v py|grep -v init.d|awk '{print $2}'") - if data[0] != "": - # print("mysql start ok!") - is_start = True - break - time.sleep(0.5) - - if not is_start: - # print("mysql start fail!") - return False - - serverdir = getServerDir() - pwd = mw.getRandomString(16) - - pass_cmd = "cat " + serverdir + \ - "/data/error.log | grep root@localhost | awk -F 'root@localhost:' '{print $2}'" - passdata = mw.execShell(pass_cmd) - password = passdata[0].strip() - - if len(password) == 0: - return True - - # print('localhost', 3306, 'root', password, - # "/www/server/mysql/mysql.sock") - - # import MySQLdb as mdb - # dbconn = mdb.connect(host='localhost', port=3306, user='root', - # passwd=password, unix_socket="/www/server/mysql/mysql.sock") - # dbconn.autocommit(True) - # dbcurr = dbconn.cursor() - # dbcurr.execute('SET NAMES UTF8MB4') - - # # with mysql_native_password - alter_root_pwd = 'flush privileges;' - alter_root_pwd = alter_root_pwd + \ - "alter user 'root'@'localhost' IDENTIFIED by '" + pwd + "';" - alter_root_pwd = alter_root_pwd + \ - "alter user 'root'@'localhost' IDENTIFIED WITH mysql_native_password by '" + pwd + "';" - alter_root_pwd = alter_root_pwd + "flush privileges;" - # dbcurr.execute(alter_root_pwd) - - tmp_file = "/tmp/mysql_init_tmp.log" - mw.writeFile(tmp_file, alter_root_pwd) - cmd_pass = serverdir + '/bin/mysql --connect-expired-password -uroot -p"' + \ - password + '" < ' + tmp_file - # print(cmd_pass) - data = mw.execShell(cmd_pass) - if data[1].find("ERROR") != -1: - # print(data[1]) - pass - else: - mw.writeFile(serverdir + "/data/error.log", "") - os.remove(tmp_file) - - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - - return True - - -def myOp(version, method): - # import commands - init_file = initDreplace() - cmd = init_file + ' ' + method - try: - initData = initMysqlData() - subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - if initData == 0: - initMysqlPwd() - return 'ok' - except Exception as e: - return str(e) - - -def my8cmd(version, method): - # mysql 8.0 and 5.7 ok - init_file = initDreplace(version) - cmd = init_file + ' ' + method - - if version == '5.7': - initMysql57Data() - elif version == '8.0': - initMysql8Data() - try: - - if not mysql8IsInitedPasswd(): - setSkipGrantTables(True) - cmd_init_start = init_file + ' start' - subprocess.Popen(cmd_init_start, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - - time.sleep(6) - initMysql8Pwd() - - cmd_init_stop = init_file + ' stop' - subprocess.Popen(cmd_init_stop, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - setSkipGrantTables(False) - - time.sleep(3) - my8cmd(version, method) - else: - if method == "stop": - mw.execShell(cmd) - mw.execShell( - "ps -ef|grep mysql|grep -v grep|grep -v py|awk '{print $2}'|xargs kill") - return "ok" - - sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - sub.wait(5) - return 'ok' - except Exception as e: - return str(e) - - return 'fail' - - -def appCMD(version, action): - if version == '8.0' or version == '5.7': - return my8cmd(version, action) - return myOp(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 not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - - initd_bin = getInitDFile() - if os.path.exists(initd_bin): - return 'ok' - return 'fail' - - -def initdInstall(): - import shutil - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mysql_bin = initDreplace() - initd_bin = getInitDFile() - shutil.copyfile(mysql_bin, initd_bin) - mw.execShell('chmod +x ' + initd_bin) - mw.execShell('chkconfig --add ' + getPluginName()) - return 'ok' - - -def initdUinstall(): - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - mw.execShell('chkconfig --del ' + getPluginName()) - initd_bin = getInitDFile() - os.remove(initd_bin) - return 'ok' - - -def getMyDbPos(): - file = getConf() - content = mw.readFile(file) - rep = 'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def setMyDbPos(): - 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() - 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) - start() - - 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 = '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 = "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(): - - if status(version) == 'stop': - return mw.returnJson(false, 'MySQL未启动', []) - - db = pMysqlDb() - data = db.query('show global status') - gets = ['Max_used_connections', 'Com_commit', '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'] - - try: - # print data - if data[0] == 1045 or data[0] == 2003: - pwd = db.getPwd() - return mw.returnJson(False, 'mysql password error:' + pwd + '!') - except Exception as e: - pass - - result = {} - - # print(data) - - for d in data: - for g in gets: - if d[0] == g: - result[g] = d[1] - - # print(result, int(result['Uptime'])) - result['Run'] = int(time.time()) - int(result['Uptime']) - tmp = db.query('show master status') - try: - result['File'] = tmp[0][0] - result['Position'] = tmp[0][1] - except: - result['File'] = 'OFF' - result['Position'] = 'OFF' - return mw.getJson(result) - - -def myDbStatus(): - 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'] - result['mem'] = {} - for d in data: - for g in gets: - if d[0] == g: - result['mem'][g] = d[1] - # if result['mem']['query_cache_type'] != 'ON': - # result['mem']['query_cache_size'] = '0' - return mw.getJson(result) - - -def setDbStatus(): - 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'] - 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 = '\s*' + g + '\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, 'MySQLdb组件缺失!
进入SSH命令行输入: pip install mysql-python') - 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 "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 mapToList(map_obj): - # map to list - try: - if type(map_obj) != list and type(map_obj) != str: - map_obj = list(map_obj) - return map_obj - except: - return [] - - -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 = mw.getRootDir() + '/backup/database' - 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 = mw.getRunDir() + '/scripts/backup.py' - - cmd = 'python ' + scDir + ' database ' + args['name'] + ' 3' - os.system(cmd) - return mw.returnJson(True, 'ok') - - -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.getRootDir() + '/backup/database/' + file - file_path_sql = mw.getRootDir() + '/backup/database/' + file.replace('.gz', '') - - if not os.path.exists(file_path_sql): - cmd = 'cd ' + mw.getRootDir() + '/backup/database && gzip -d ' + file - mw.execShell(cmd) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - - mysql_cmd = mw.getRootDir() + '/server/mysql/bin/mysql -uroot -p' + pwd + \ - ' ' + name + ' < ' + file_path_sql - - # print(mysql_cmd) - os.system(mysql_cmd) - return mw.returnJson(True, 'ok') - - -def deleteDbBackup(): - args = getArgs() - data = checkArgs(args, ['filename']) - if not data[0]: - return data[1] - - bkDir = mw.getRootDir() + '/backup/database' - - os.remove(bkDir + '/' + args['filename']) - 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 = mw.getRootDir() + '/backup/database' - 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 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,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 - for value in data: - b = False - for key in nameArr: - if value[0] == key: - b = True - break - if b: - continue - if psdb.where("name=?", (value[0],)).count(): - continue - host = '127.0.0.1' - for user in users: - if value[0] == user[0]: - host = user[1] - break - - ps = mw.getMsg('INPUT_PS') - if value[0] == 'test': - ps = mw.getMsg('DATABASE_TEST') - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - if psdb.add('name,username,password,accept,ps,addtime', (value[0], value[0], '', 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(): - args = getArgs() - data = checkArgs(args, ['password']) - if not data[0]: - return data[1] - - password = args['password'] - try: - pdb = pMysqlDb() - result = pdb.query("show databases") - isError = isSqlError(result) - if isError != None: - return isError - - m_version = mw.readFile(getServerDir() + '/version.pl') - if m_version.find('5.7') == 0 or m_version.find('8.0') == 0: - 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,)) - return mw.returnJson(True, '数据库root密码修改成功!') - except Exception as ex: - return mw.returnJson(False, '修改错误:' + str(ex)) - - -def setUserPwd(): - args = getArgs() - data = checkArgs(args, ['password', 'name']) - if not data[0]: - return data[1] - - newpassword = args['password'] - username = args['name'] - id = args['id'] - try: - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - name = psdb.where('id=?', (id,)).getField('name') - - m_version = mw.readFile(getServerDir() + '/version.pl') - if m_version.find('5.7') == 0 or m_version.find('8.0') == 0: - tmp = pdb.query( - "select Host from mysql.user where User='" + name + "' AND Host!='localhost'") - accept = mapToList(tmp) - pdb.execute( - "update mysql.user set authentication_string='' where User='" + username + "'") - result = pdb.execute( - "ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, newpassword)) - for my_host in accept: - pdb.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ( - username, my_host[0], newpassword)) - else: - result = pdb.execute("update mysql.user set Password=password('" + - newpassword + "') where User='" + username + "'") - isError = isSqlError(result) - if isError != None: - return isError - pdb.execute("flush privileges") - psdb.where("id=?", (id,)).setField('password', newpassword) - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]密码成功!', (name,))) - except Exception as ex: - # print str(ex) - return mw.returnJson(False, mw.getInfo('修改数据库[{1}]密码失败!', (name,))) - - -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 = "^[\w\.-]+$" - if not re.match(reg, args['name']): - return mw.returnJson(False, '数据库名称不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'panel_logs'] - 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: - id = args['id'] - name = args['name'] - psdb = pSqliteDb('databases') - pdb = pMysqlDb() - find = psdb.where("id=?", (id,)).field( - 'id,pid,name,username,password,accept,ps,addtime').find() - accept = find['accept'] - username = find['username'] - - # 删除MYSQL - result = pdb.execute("drop database `" + name + "`") - isError = isSqlError(result) - if isError != None: - return isError - - 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[0] + "'") - pdb.execute("flush privileges") - - # 删除SQLITE - psdb.where("id=?", (id,)).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 - - users = mapToList(users) - if len(users) < 1: - return mw.returnJson(True, "127.0.0.1") - accs = [] - for c in users: - accs.append(c[0]) - userStr = ','.join(accs) - return mw.returnJson(True, userStr) - - -def toSize(size): - d = ('b', 'KB', 'MB', 'GB', 'TB') - s = d[0] - for b in d: - if size < 1024: - return str(size) + ' ' + b - size = size / 1024 - s = b - _size = round(size, 2) - # print(size, _size) - return str(size) + ' ' + b - - -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[0] + "'") - - __createUser(dbname, name, password, access) - - psdb.where('username=?', (name,)).save('accept', (access,)) - 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 - table_res = pdb.query('show tables from `%s`' % db_name) - isError = isSqlError(table_res) - if isError != None: - return isError - - tables = mapToList(table_res) - - ret = {} - if type(tables) == list: - try: - data = mapToList(pdb.query( - "select sum(DATA_LENGTH)+sum(INDEX_LENGTH) from information_schema.tables where table_schema='%s'" % db_name))[0][0] - except: - data = 0 - - if not data: - data = 0 - ret['data_size'] = mw.toSize(data) - # print ret - ret['database'] = db_name - - ret3 = [] - - for i in tables: - if i == 1049: - return mw.returnJson(False, '指定数据库不存在!') - table = mapToList( - pdb.query("show table status from `%s` where name = '%s'" % (db_name, i[0]))) - if not table: - continue - try: - ret2 = {} - ret2['type'] = table[0][1] - ret2['rows_count'] = table[0][4] - ret2['collation'] = table[0][14] - data_size = table[0][6] + table[0][8] - ret2['data_byte'] = data_size - ret2['data_size'] = mw.toSize(data_size) - ret2['table_name'] = i[0] - ret3.append(ret2) - except: - continue - 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() - mysql_table = mapToList(pdb.query('show tables from `%s`' % db_name)) - ret = [] - if type(mysql_table) == list: - if len(mysql_table) > 0: - for i in mysql_table: - for i2 in tables: - if i2 == i[0]: - ret.append(i2) - 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() - mysql_table = mapToList(pdb.query('show tables from `%s`' % db_name)) - ret = [] - if type(mysql_table) == list: - if len(mysql_table) > 0: - for i in mysql_table: - for i2 in tables: - if i2 == i[0]: - ret.append(i2) - 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() - mysql_table = mapToList(pdb.query('show tables from `%s`' % db_name)) - ret = [] - if type(mysql_table) == list: - if len(mysql_table) > 0: - for i in mysql_table: - for i2 in tables: - if i2 == i[0]: - ret.append(i2) - 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 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 getMasterDbList(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('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) - - -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未启动,或正在启动中...!', []) - - conf = getConf() - con = mw.readFile(conf) - master_status = False - if con.find('#log-bin') == -1 and con.find('log-bin') > 1: - dodb = findBinlogDoDb() - if len(dodb) > 0: - master_status = True - data = {} - data['status'] = master_status - - db = pMysqlDb() - dlist = db.query('show slave status') - # print(dlist, len(dlist)) - if len(dlist) > 0 and (dlist[0][10] == 'Yes' or dlist[0][11] == 'Yes'): - data['slave_status'] = True - - return mw.returnJson(master_status, '设置成功', data) - - -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] - - if not 'address' in args: - address = '' - else: - 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 = "^[\w\.-]+$" - if not re.match(reg, username): - return mw.returnJson(False, '用户名不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'panel_logs'] - 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(): - return mw.returnJson(False, '用户已存在!') - - result = pdb.execute("GRANT REPLICATION SLAVE ON *.* TO '" + - username + "'@'%' identified by '" + password + "';FLUSH PRIVILEGES;") - # print result - isError = isSqlError(result) - if isError != None: - return isError - - 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' - if args['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=?", (args['username'],)).limit( - '1').order('id desc').select() - - ip = mw.getLocalIp() - port = getMyPort() - - db = pMysqlDb() - tmp = db.query('show master status') - - if len(tmp) == 0: - return mw.returnJson(False, '未开启!') - - sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \ - clist[0]['username'] + "', MASTER_PASSWORD='" + \ - clist[0]['password'] + \ - "', MASTER_LOG_FILE='" + tmp[0][0] + \ - "',MASTER_LOG_POS=" + str(tmp[0][1]) + "" - - # if args['db'] != '': - # replicate-do-table - - return mw.returnJson(True, 'OK!', sql) - - -def delMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username']) - if not data[0]: - return data[1] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - pdb.execute("drop user '" + args['username'] + "'@'%'") - 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 getSlaveList(version=''): - - db = pMysqlDb() - dlist = db.query('show slave status') - - # print(dlist) - ret = [] - for x in range(0, len(dlist)): - tmp = {} - tmp['Master_User'] = dlist[x][2] - tmp['Master_Host'] = dlist[x][1] - tmp['Master_Port'] = dlist[x][3] - tmp['Master_Log_File'] = dlist[x][5] - tmp['Slave_IO_Running'] = dlist[x][10] - tmp['Slave_SQL_Running'] = dlist[x][11] - ret.append(tmp) - data = {} - data['data'] = ret - - return mw.getJson(data) - - -def setSlaveStatus(version=''): - db = pMysqlDb() - dlist = db.query('show slave status') - - if len(dlist) == 0: - return mw.returnJson(False, '需要手动添加主服务同步命令!') - - if len(dlist) > 0 and (dlist[0][10] == 'Yes' or dlist[0][11] == 'Yes'): - db.query('stop slave') - else: - db.query('start slave') - - return mw.returnJson(True, '设置成功!') - - -def deleteSlave(version=''): - db = pMysqlDb() - dlist = db.query('stop slave;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') - if args['db'] == 'all' or args['db'] == 'ALL': - dlist = findBinlogDoDb() - cmd = getServerDir() + "/bin/mysqldump -uroot -p" + \ - pwd + " --databases " + ' '.join(dlist) + \ - " > /tmp/dump.sql" - else: - cmd = getServerDir() + "/bin/mysqldump -uroot -p" + pwd + \ - " --databases " + args['db'] + " > /tmp/dump.sql" - - ret = mw.execShell(cmd) - - if ret[0] == '': - return 'ok' - return 'fail' - - -from threading import Thread -from time import sleep - - -def mw_async(f): - def wrapper(*args, **kwargs): - thr = Thread(target=f, args=args, kwargs=kwargs) - thr.start() - return wrapper - - -def doFullSync(): - - args = getArgs() - data = checkArgs(args, ['db']) - if not data[0]: - return data[1] - - status_data = {} - status_data['progress'] = 5 - - db = pMysqlDb() - - dlist = db.query('show slave status') - if len(dlist) == 0: - status_data['code'] = -1 - status_data['msg'] = '没有启动...' - - ip = dlist[0][1] - print(ip) - - status_file = '/tmp/db_async_status.txt' - - status_data['code'] = 0 - status_data['msg'] = '运行中...' - mw.writeFile(status_file, json.dumps(status_data)) - - import paramiko - paramiko.util.log_to_file('paramiko.log') - ssh = paramiko.SSHClient() - - SSH_PRIVATE_KEY = '/root/.ssh/id_rsa' - - if mw.getOs() == 'darwin': - user = mw.execShell( - "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() - SSH_PRIVATE_KEY = '/Users/' + user + '/.ssh/id_rsa' - - print(SSH_PRIVATE_KEY) - if not os.path.exists(SSH_PRIVATE_KEY): - status_data['code'] = 0 - status_data['msg'] = '需要配置免登录...' - mw.writeFile(status_file, json.dumps(status_data)) - return - - try: - key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) - # ssh.load_system_host_keys() - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - ssh.connect(hostname=ip, port=22, username='root', pkey=key) - except Exception as e: - status_data['code'] = 0 - status_data['msg'] = '需要配置免登录....' - mw.writeFile(status_file, json.dumps(status_data)) - return - - cmd = "cd /www/server/mdserver-web && python /www/server/mdserver-web/plugins/mysql/index.py dump_mysql_data {\"db\":'" + args[ - 'db'] + "'}" - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result_err = stderr.read() - - if result == 'ok': - status_data['code'] = 1 - status_data['msg'] = '主服务器备份完成...' - status_data['progress'] = 30 - mw.writeFile(status_file, json.dumps(status_data)) - - r = mw.execShell('scp root@' + ip + ':/tmp/dump.sql /tmp') - if r[0] == '': - status_data['code'] = 2 - status_data['msg'] = '数据同步本地完成...' - status_data['progress'] = 40 - mw.writeFile(status_file, json.dumps(status_data)) - - cmd = 'cd /www/server/mdserver-web && python /www/server/mdserver-web/plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"","db":""}' - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result_err = stderr.read() - cmd_data = json.loads(result) - - db.query('stop slave') - status_data['code'] = 3 - status_data['msg'] = '停止从库完成...' - status_data['progress'] = 45 - mw.writeFile(status_file, json.dumps(status_data)) - - dlist = db.query(cmd_data['data']) - status_data['code'] = 4 - status_data['msg'] = '刷新库信息完成...' - status_data['progress'] = 50 - mw.writeFile(status_file, json.dumps(status_data)) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - cmd = getServerDir() + "/bin/mysql -uroot -p" + pwd + " < /tmp/dump.sql" - print(mw.execShell(cmd)) - status_data['code'] = 5 - status_data['msg'] = '同步数据完成...' - status_data['progress'] = 90 - mw.writeFile(status_file, json.dumps(status_data)) - - db.query('start slave') - status_data['code'] = 6 - status_data['msg'] = '从库重启完成...' - status_data['progress'] = 100 - mw.writeFile(status_file, json.dumps(status_data)) - - return True - - -def fullSync(version=''): - args = getArgs() - data = checkArgs(args, ['db', 'begin']) - if not data[0]: - return data[1] - - status_file = '/tmp/db_async_status.txt' - if args['begin'] == '1': - cmd = 'cd ' + mw.getRunDir() + ' && python ' + \ - getPluginDir() + \ - '/index.py do_full_sync {"db":"' + args['db'] + '"} &' - mw.execShell(cmd) - return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0}) - - if os.path.exists(status_file): - c = mw.readFile(status_file) - d = json.loads(c) - - if d['code'] == 6: - os.remove(status_file) - return c - - return json.dumps({'code': 0, 'msg': '点击开始,开始同步!', 'progress': 0}) - -if __name__ == "__main__": - func = sys.argv[1] - - version = "5.6" - if (len(sys.argv) > 2): - version = sys.argv[2] - - 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 == 'run_info': - print(runInfo()) - elif func == 'db_status': - print(myDbStatus()) - elif func == 'set_db_status': - print(setDbStatus()) - elif func == 'conf': - print(getConf()) - elif func == 'bin_log': - print(binLog()) - 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()) - elif func == 'my_port': - print(getMyPort()) - elif func == 'set_my_port': - print(setMyPort()) - elif func == 'init_pwd': - print(initMysqlPwd()) - elif func == 'get_db_list': - print(getDbList()) - elif func == 'set_db_backup': - print(setDbBackup()) - elif func == 'import_db_backup': - print(importDbBackup()) - elif func == 'delete_db_backup': - print(deleteDbBackup()) - elif func == 'get_db_backup_list': - print(getDbBackupList()) - 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()) - elif func == 'set_user_pwd': - print(setUserPwd()) - elif func == 'get_db_access': - print(getDbAccess()) - elif func == 'set_db_access': - print(setDbAccess()) - 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_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 == '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 == '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()) - elif func == 'dump_mysql_data': - print(dumpMysqlData(version)) - else: - print('error') diff --git a/plugins/mysql/bak/index_2022_8_02.py b/plugins/mysql/bak/index_2022_8_02.py deleted file mode 100755 index ccb036bf72..0000000000 --- a/plugins/mysql/bak/index_2022_8_02.py +++ /dev/null @@ -1,2229 +0,0 @@ -# coding:utf-8 - -import sys -import io -import os -import time -import subprocess -import re -import json - - -# reload(sys) -# sys.setdefaultencoding('utf-8') - -sys.path.append(os.getcwd() + "/class/core") -import 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' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def getInitDFile(): - if app_debug: - return '/tmp/' + getPluginName() - return '/etc/init.d/' + getPluginName() - - -def getArgs(): - args = sys.argv[2:] - - tmp = {} - args_len = len(args) - - if args_len == 1: - t = args[0].strip('{').strip('}') - t = t.split(':') - tmp[t[0]] = t[1] - elif args_len > 1: - for i in range(len(args)): - t = args[i].split(':') - 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 getConf(): - path = getServerDir() + '/etc/my.cnf' - return path - - -def getDbPort(): - file = getConf() - content = mw.readFile(file) - rep = 'port\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getSocketFile(): - file = getConf() - content = mw.readFile(file) - rep = 'socket\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getInitdTpl(version=''): - path = getPluginDir() + '/init.d/mysql' + version + '.tpl' - if not os.path.exists(path): - path = getPluginDir() + '/init.d/mysql.tpl' - return path - - -def contentReplace(content): - service_path = mw.getServerDir() - if content.find('{$ROOT_PATH}') != -1: - content = content.replace('{$ROOT_PATH}', mw.getRootDir()) - - if content.find('{$SERVER_PATH}') != -1: - content = content.replace('{$SERVER_PATH}', service_path) - - if content.find('{$SERVER_APP_PATH}') != -1: - content = content.replace( - '{$SERVER_APP_PATH}', service_path + '/mysql') - return content - - -def pSqliteDb(dbname='databases'): - file = getServerDir() + '/mysql.db' - name = 'mysql' - if not os.path.exists(file): - conn = mw.M(dbname).dbPos(getServerDir(), name) - csql = mw.readFile(getPluginDir() + '/conf/mysql.sql') - csql_list = csql.split(';') - for index in range(len(csql_list)): - conn.execute(csql_list[index], ()) - else: - # 现有run - # conn = mw.M(dbname).dbPos(getServerDir(), name) - # csql = mw.readFile(getPluginDir() + '/conf/mysql.sql') - # csql_list = csql.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.setPort(getDbPort()) - db.setSocket(getSocketFile()) - # db.setCharset("utf8") - db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')) - return db - - -def initDreplace(version=''): - initd_tpl = getInitdTpl(version) - - initD_path = getServerDir() + '/init.d' - if not os.path.exists(initD_path): - os.mkdir(initD_path) - - file_bin = initD_path + '/' + getPluginName() - if not os.path.exists(file_bin): - content = mw.readFile(initd_tpl) - content = contentReplace(content) - mw.writeFile(file_bin, content) - mw.execShell('chmod +x ' + file_bin) - - mysql_conf_dir = getServerDir() + '/etc' - if not os.path.exists(mysql_conf_dir): - os.mkdir(mysql_conf_dir) - - mysql_tmp = getServerDir() + '/tmp' - if not os.path.exists(mysql_tmp): - os.mkdir(mysql_tmp) - mw.execShell("chown -R mysql:mysql " + mysql_tmp) - - mysql_conf = mysql_conf_dir + '/my.cnf' - if not os.path.exists(mysql_conf): - mysql_conf_tpl = getPluginDir() + '/conf/my' + version + '.cnf' - content = mw.readFile(mysql_conf_tpl) - content = contentReplace(content) - mw.writeFile(mysql_conf, content) - - # systemd - systemDir = mw.systemdCfgDir() - systemService = systemDir + '/mysql.service' - systemServiceTpl = getPluginDir() + '/init.d/mysql.service.tpl' - if os.path.exists(systemDir) and not os.path.exists(systemService): - service_path = mw.getServerDir() - se_content = mw.readFile(systemServiceTpl) - se_content = se_content.replace('{$SERVER_PATH}', service_path) - mw.writeFile(systemService, se_content) - mw.execShell('systemctl daemon-reload') - - if mw.getOs() != 'darwin': - mw.execShell('chown -R mysql mysql ' + getServerDir()) - return file_bin - - -def status(version=''): - pid = getPidFile() - if not os.path.exists(pid): - return 'stop' - - return 'start' - - -def getDataDir(): - file = getConf() - content = mw.readFile(file) - rep = 'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def getPidFile(): - file = getConf() - content = mw.readFile(file) - rep = 'pid-file\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def binLog(): - 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() - 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() - mw.execShell('rm -f ' + path + '/mysql-bin.*') - - mw.writeFile(conf, con) - return mw.returnJson(True, '设置成功!') - - -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() - path = getDataDir() - filename = '' - for n in os.listdir(path): - if len(n) < 5: - continue - if n == 'error.log': - filename = path + '/' + n - break - # print filename - if not os.path.exists(filename): - return mw.returnJson(False, '指定文件不存在!') - if 'close' in args: - mw.writeFile(filename, '') - return mw.returnJson(False, '日志已清空') - info = mw.getNumLines(filename, 18) - return mw.returnJson(True, 'OK', info) - - -def getShowLogFile(): - file = getConf() - content = mw.readFile(file) - rep = 'slow-query-log-file\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def pGetDbUser(): - if mw.isAppleSystem(): - user = mw.execShell( - "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() - return user - return 'mysql' - - -def initMysqlData(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - user = pGetDbUser() - cmd = 'cd ' + serverdir + ' && ./scripts/mysql_install_db --defaults-file=' + myconf - mw.execShell(cmd) - return False - return True - - -def initMysql57Data(): - ''' - cd /www/server/mysql && /www/server/mysql/bin/mysqld --defaults-file=/www/server/mysql/etc/my.cnf --initialize-insecure --explicit_defaults_for_timestamp - ''' - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - user = pGetDbUser() - cmd = 'cd ' + serverdir + ' && ./bin/mysqld --defaults-file=' + myconf + \ - ' --initialize-insecure --explicit_defaults_for_timestamp' - data = mw.execShell(cmd) - # print(data) - return False - return True - - -def initMysql8Data(): - datadir = getDataDir() - if not os.path.exists(datadir + '/mysql'): - serverdir = getServerDir() - user = pGetDbUser() - # cmd = 'cd ' + serverdir + ' && ./bin/mysqld --basedir=' + serverdir + ' --datadir=' + \ - # datadir + ' --initialize' - - cmd = 'cd ' + serverdir + ' && ./bin/mysqld --basedir=' + serverdir + ' --datadir=' + \ - datadir + ' --initialize-insecure' - - # print(cmd) - data = mw.execShell(cmd) - # print(data) - return False - return True - - -def initMysqlPwd(): - time.sleep(5) - - serverdir = getServerDir() - pwd = mw.getRandomString(16) - # cmd_pass = serverdir + '/bin/mysqladmin -uroot password ' + pwd - - # cmd_pass = "insert into mysql.user(Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv,Event_priv,Trigger_priv,Create_tablespace_priv,User,Password,host)values('Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','root',password('" + pwd + "'),'127.0.0.1')" - # cmd_pass = cmd_pass + \ - # "insert into mysql.user(Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv,Event_priv,Trigger_priv,Create_tablespace_priv,User,Password,host)values('Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','root',password('" + pwd + "'),'localhost')" - # cmd_pass = cmd_pass + \ - # "UPDATE mysql.user SET password=PASSWORD('" + \ - # pwd + "') WHERE user='root'" - cmd_pass = serverdir + '/bin/mysql -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(cmd_pass) - # print(data) - - # 删除测试数据库 - drop_test_db = serverdir + '/bin/mysql -uroot -p' + \ - pwd + ' -e "drop database test";' - mw.execShell(drop_test_db) - - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - return True - - -def initMysql8Pwd(): - time.sleep(2) - - serverdir = getServerDir() - myconf = serverdir + "/etc/my.cnf" - - pwd = mw.getRandomString(16) - - alter_root_pwd = 'flush privileges;' - - alter_root_pwd = alter_root_pwd + \ - "UPDATE mysql.user SET authentication_string='' WHERE user='root';" - alter_root_pwd = alter_root_pwd + "flush privileges;" - alter_root_pwd = alter_root_pwd + \ - "alter user 'root'@'localhost' IDENTIFIED by '" + pwd + "';" - alter_root_pwd = alter_root_pwd + \ - "alter user 'root'@'localhost' IDENTIFIED WITH mysql_native_password by '" + pwd + "';" - alter_root_pwd = alter_root_pwd + "flush privileges;" - - cmd_pass = serverdir + '/bin/mysqladmin --defaults-file=' + \ - myconf + ' -uroot password root' - data = mw.execShell(cmd_pass) - # print(cmd_pass) - # print(data) - - tmp_file = "/tmp/mysql_init_tmp.log" - mw.writeFile(tmp_file, alter_root_pwd) - cmd_pass = serverdir + '/bin/mysql --defaults-file=' + \ - myconf + ' -uroot -proot < ' + tmp_file - - data = mw.execShell(cmd_pass) - os.remove(tmp_file) - - # 删除测试数据库 - drop_test_db = serverdir + '/bin/mysql --defaults-file=' + \ - myconf + ' -uroot -p' + pwd + ' -e "drop database test";' - mw.execShell(drop_test_db) - - pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) - - return True - - -def myOp(version, method): - # import commands - init_file = initDreplace() - try: - isInited = initMysqlData() - if not isInited: - mw.execShell('systemctl start mysql') - initMysqlPwd() - mw.execShell('systemctl stop mysql') - - mw.execShell('systemctl ' + method + ' mysql') - return 'ok' - except Exception as e: - return str(e) - - -def my8cmd(version, method): - # mysql 8.0 and 5.7 - init_file = initDreplace(version) - cmd = init_file + ' ' + method - try: - if version == '5.7': - isInited = initMysql57Data() - elif version == '8.0': - isInited = initMysql8Data() - - if not isInited: - - if mw.isAppleSystem(): - 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 mysql') - - initMysql8Pwd() - - if mw.isAppleSystem(): - 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 mysql') - - if mw.isAppleSystem(): - sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, - bufsize=4096, stderr=subprocess.PIPE) - sub.wait(5) - else: - mw.execShell('systemctl ' + method + ' mysql') - return 'ok' - except Exception as e: - return str(e) - - -def appCMD(version, action): - if version == '8.0' or version == '5.7': - return my8cmd(version, action) - return myOp(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 mysql | 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 mysql') - return 'ok' - - -def initdUinstall(): - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mw.execShell('systemctl disable mysql') - return 'ok' - - -def getMyDbPos(): - file = getConf() - content = mw.readFile(file) - rep = 'datadir\s*=\s*(.*)' - tmp = re.search(rep, content) - return tmp.groups()[0].strip() - - -def setMyDbPos(): - 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() - 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) - start() - - 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 = '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 = "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(): - - if status(version) == 'stop': - return mw.returnJson(False, 'MySQL未启动', []) - - db = pMysqlDb() - data = db.query('show global status') - gets = ['Max_used_connections', 'Com_commit', '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'] - - try: - # print data - if data[0] == 1045 or data[0] == 2003: - pwd = db.getPwd() - return mw.returnJson(False, 'mysql password error:' + pwd + '!') - except Exception as e: - pass - - result = {} - - # print(data) - - for d in data: - for g in gets: - if d[0] == g: - result[g] = d[1] - - # print(result, int(result['Uptime'])) - result['Run'] = int(time.time()) - int(result['Uptime']) - tmp = db.query('show master status') - try: - result['File'] = tmp[0][0] - result['Position'] = tmp[0][1] - except: - result['File'] = 'OFF' - result['Position'] = 'OFF' - return mw.getJson(result) - - -def myDbStatus(): - 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'] - result['mem'] = {} - for d in data: - for g in gets: - if d[0] == g: - result['mem'][g] = d[1] - # if result['mem']['query_cache_type'] != 'ON': - # result['mem']['query_cache_size'] = '0' - return mw.getJson(result) - - -def setDbStatus(): - 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'] - 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 = '\s*' + g + '\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, '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 mapToList(map_obj): - # map to list - try: - if type(map_obj) != list and type(map_obj) != str: - map_obj = list(map_obj) - return map_obj - except: - return [] - - -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 = mw.getRootDir() + '/backup/database' - 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 = mw.getRunDir() + '/scripts/backup.py' - - cmd = 'python ' + scDir + ' database ' + args['name'] + ' 3' - os.system(cmd) - return mw.returnJson(True, 'ok') - - -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.getRootDir() + '/backup/database/' + file - file_path_sql = mw.getRootDir() + '/backup/database/' + file.replace('.gz', '') - - if not os.path.exists(file_path_sql): - cmd = 'cd ' + mw.getRootDir() + '/backup/database && gzip -d ' + file - mw.execShell(cmd) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - - mysql_cmd = mw.getRootDir() + '/server/mysql/bin/mysql -uroot -p' + pwd + \ - ' ' + name + ' < ' + file_path_sql - - # print(mysql_cmd) - os.system(mysql_cmd) - return mw.returnJson(True, 'ok') - - -def deleteDbBackup(): - args = getArgs() - data = checkArgs(args, ['filename']) - if not data[0]: - return data[1] - - bkDir = mw.getRootDir() + '/backup/database' - - os.remove(bkDir + '/' + args['filename']) - 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 = mw.getRootDir() + '/backup/database' - 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 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,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 - for value in data: - b = False - for key in nameArr: - if value[0] == key: - b = True - break - if b: - continue - if psdb.where("name=?", (value[0],)).count(): - continue - host = '127.0.0.1' - for user in users: - if value[0] == user[0]: - host = user[1] - break - - ps = mw.getMsg('INPUT_PS') - if value[0] == 'test': - ps = mw.getMsg('DATABASE_TEST') - addTime = time.strftime('%Y-%m-%d %X', time.localtime()) - if psdb.add('name,username,password,accept,ps,addtime', (value[0], value[0], '', 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(): - args = getArgs() - data = checkArgs(args, ['password']) - if not data[0]: - return data[1] - - password = args['password'] - try: - pdb = pMysqlDb() - result = pdb.query("show databases") - isError = isSqlError(result) - if isError != None: - return isError - - m_version = mw.readFile(getServerDir() + '/version.pl') - if m_version.find('5.7') == 0 or m_version.find('8.0') == 0: - 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,)) - return mw.returnJson(True, '数据库root密码修改成功!') - except Exception as ex: - return mw.returnJson(False, '修改错误:' + str(ex)) - - -def setUserPwd(): - args = getArgs() - data = checkArgs(args, ['password', 'name']) - if not data[0]: - return data[1] - - newpassword = args['password'] - username = args['name'] - id = args['id'] - try: - pdb = pMysqlDb() - psdb = pSqliteDb('databases') - name = psdb.where('id=?', (id,)).getField('name') - - m_version = mw.readFile(getServerDir() + '/version.pl') - if m_version.find('5.7') == 0 or m_version.find('8.0') == 0: - tmp = pdb.query( - "select Host from mysql.user where User='" + name + "' AND Host!='localhost'") - accept = mapToList(tmp) - pdb.execute( - "update mysql.user set authentication_string='' where User='" + username + "'") - result = pdb.execute( - "ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, newpassword)) - for my_host in accept: - pdb.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ( - username, my_host[0], newpassword)) - else: - result = pdb.execute("update mysql.user set Password=password('" + - newpassword + "') where User='" + username + "'") - isError = isSqlError(result) - if isError != None: - return isError - pdb.execute("flush privileges") - psdb.where("id=?", (id,)).setField('password', newpassword) - return mw.returnJson(True, mw.getInfo('修改数据库[{1}]密码成功!', (name,))) - except Exception as ex: - # print str(ex) - return mw.returnJson(False, mw.getInfo('修改数据库[{1}]密码失败!', (name,))) - - -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 = "^[\w\.-]+$" - if not re.match(reg, args['name']): - return mw.returnJson(False, '数据库名称不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'panel_logs'] - 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: - id = args['id'] - name = args['name'] - psdb = pSqliteDb('databases') - pdb = pMysqlDb() - find = psdb.where("id=?", (id,)).field( - 'id,pid,name,username,password,accept,ps,addtime').find() - accept = find['accept'] - username = find['username'] - - # 删除MYSQL - result = pdb.execute("drop database `" + name + "`") - isError = isSqlError(result) - if isError != None: - return isError - - 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[0] + "'") - pdb.execute("flush privileges") - - # 删除SQLITE - psdb.where("id=?", (id,)).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 - - users = mapToList(users) - if len(users) < 1: - return mw.returnJson(True, "127.0.0.1") - accs = [] - for c in users: - accs.append(c[0]) - userStr = ','.join(accs) - return mw.returnJson(True, userStr) - - -def toSize(size): - d = ('b', 'KB', 'MB', 'GB', 'TB') - s = d[0] - for b in d: - if size < 1024: - return str(size) + ' ' + b - size = size / 1024 - s = b - _size = round(size, 2) - # print(size, _size) - return str(size) + ' ' + b - - -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[0] + "'") - - __createUser(dbname, name, password, access) - - psdb.where('username=?', (name,)).save('accept', (access,)) - 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 - table_res = pdb.query('show tables from `%s`' % db_name) - isError = isSqlError(table_res) - if isError != None: - return isError - - tables = mapToList(table_res) - - ret = {} - if type(tables) == list: - try: - data = mapToList(pdb.query( - "select sum(DATA_LENGTH)+sum(INDEX_LENGTH) from information_schema.tables where table_schema='%s'" % db_name))[0][0] - except: - data = 0 - - if not data: - data = 0 - ret['data_size'] = mw.toSize(data) - # print ret - ret['database'] = db_name - - ret3 = [] - - for i in tables: - if i == 1049: - return mw.returnJson(False, '指定数据库不存在!') - table = mapToList( - pdb.query("show table status from `%s` where name = '%s'" % (db_name, i[0]))) - if not table: - continue - try: - ret2 = {} - ret2['type'] = table[0][1] - ret2['rows_count'] = table[0][4] - ret2['collation'] = table[0][14] - data_size = table[0][6] + table[0][8] - ret2['data_byte'] = data_size - ret2['data_size'] = mw.toSize(data_size) - ret2['table_name'] = i[0] - ret3.append(ret2) - except: - continue - 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() - mysql_table = mapToList(pdb.query('show tables from `%s`' % db_name)) - ret = [] - if type(mysql_table) == list: - if len(mysql_table) > 0: - for i in mysql_table: - for i2 in tables: - if i2 == i[0]: - ret.append(i2) - 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() - mysql_table = mapToList(pdb.query('show tables from `%s`' % db_name)) - ret = [] - if type(mysql_table) == list: - if len(mysql_table) > 0: - for i in mysql_table: - for i2 in tables: - if i2 == i[0]: - ret.append(i2) - 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() - mysql_table = mapToList(pdb.query('show tables from `%s`' % db_name)) - ret = [] - if type(mysql_table) == list: - if len(mysql_table) > 0: - for i in mysql_table: - for i2 in tables: - if i2 == i[0]: - ret.append(i2) - 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 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 getMasterDbList(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('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) - - -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未启动,或正在启动中...!', []) - - conf = getConf() - con = mw.readFile(conf) - master_status = False - if con.find('#log-bin') == -1 and con.find('log-bin') > 1: - dodb = findBinlogDoDb() - if len(dodb) > 0: - master_status = True - data = {} - data['status'] = master_status - - db = pMysqlDb() - dlist = db.query('show slave status') - dlist = list(dlist) - # print(dlist, len(dlist)) - if len(dlist) > 0 and (dlist[0][10] == 'Yes' or dlist[0][11] == 'Yes'): - data['slave_status'] = True - - return mw.returnJson(master_status, '设置成功', data) - - -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=''): - version_pl = getServerDir() + "/version.pl" - if os.path.exists(version_pl): - version = mw.readFile(version_pl).strip() - - args = getArgs() - data = checkArgs(args, ['username', 'password']) - if not data[0]: - return data[1] - - if not 'address' in args: - address = '' - else: - 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 = "^[\w\.-]+$" - if not re.match(reg, username): - return mw.returnJson(False, '用户名不能带有特殊符号!') - checks = ['root', 'mysql', 'test', 'sys', 'panel_logs'] - 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(): - return mw.returnJson(False, '用户已存在!') - - if version == "8.0": - sql = "CREATE USER '" + username + \ - "'@'%' IDENTIFIED WITH mysql_native_password BY '" + password + "';" - sql += "grant replication slave on *.* to '" + username + "'@'%';" - sql += "FLUSH PRIVILEGES;" - result = pdb.execute(sql) - isError = isSqlError(result) - if isError != None: - return isError - else: - sql = "GRANT REPLICATION SLAVE ON *.* TO '" + username + \ - "'@'%' identified by '" + password + "';FLUSH PRIVILEGES;" - result = pdb.execute(sql) - isError = isSqlError(result) - if isError != None: - return isError - - 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): - - version_pl = getServerDir() + "/version.pl" - if os.path.exists(version_pl): - version = mw.readFile(version_pl).strip() - - args = getArgs() - data = checkArgs(args, ['username', 'db']) - if not data[0]: - return data[1] - - psdb = pSqliteDb('master_replication_user') - f = 'username,password' - if args['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=?", (args['username'],)).limit( - '1').order('id desc').select() - - ip = mw.getLocalIp() - port = getMyPort() - - db = pMysqlDb() - mstatus = db.query('show master status') - # print(mstatus) - mstatus = list(mstatus) - if len(mstatus) == 0: - return mw.returnJson(False, '未开启!') - - sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \ - clist[0]['username'] + "', MASTER_PASSWORD='" + \ - clist[0]['password'] + \ - "', MASTER_LOG_FILE='" + mstatus[0][0] + \ - "',MASTER_LOG_POS=" + str(mstatus[0][1]) + "" - - if version == "8.0": - sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \ - clist[0]['username'] + "', SOURCE_PASSWORD='" + \ - clist[0]['password'] + \ - "', SOURCE_LOG_FILE='" + mstatus[0][0] + \ - "',SOURCE_LOG_POS=" + str(mstatus[0][1]) + "" - - return mw.returnJson(True, 'OK!', sql) - - -def delMasterRepSlaveUser(version=''): - args = getArgs() - data = checkArgs(args, ['username']) - if not data[0]: - return data[1] - - pdb = pMysqlDb() - psdb = pSqliteDb('master_replication_user') - pdb.execute("drop user '" + args['username'] + "'@'%'") - 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,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 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,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']) - if not data[0]: - return data[1] - - id_rsa = args['id_rsa'] - port = args['port'] - 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', (port, id_rsa,)) - else: - conn.add('ip,port,user,id_rsa,ps,addtime', - (ip, port, user, id_rsa, '', 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=''): - - db = pMysqlDb() - dlist = db.query('show slave status') - dlist = list(dlist) - # print(dlist) - ret = [] - for x in range(0, len(dlist)): - tmp = {} - tmp['Master_User'] = dlist[x][2] - tmp['Master_Host'] = dlist[x][1] - tmp['Master_Port'] = dlist[x][3] - tmp['Master_Log_File'] = dlist[x][5] - tmp['Slave_IO_Running'] = dlist[x][10] - tmp['Slave_SQL_Running'] = dlist[x][11] - ret.append(tmp) - data = {} - data['data'] = ret - - return mw.getJson(data) - - -def getSlaveSyncCmd(version=''): - - root = mw.getRunDir() - cmd = 'cd ' + root + ' && python ' + root + \ - '/plugins/mysql/index.py do_full_sync {"db":"all"}' - return mw.returnJson(True, 'ok', cmd) - - -def setSlaveStatus(version=''): - db = pMysqlDb() - dlist = db.query('show slave status') - dlist = list(dlist) - if len(dlist) == 0: - return mw.returnJson(False, '需要手动添加主服务同步命令!') - - if len(dlist) > 0 and (dlist[0][10] == 'Yes' or dlist[0][11] == 'Yes'): - db.query('stop slave') - else: - db.query('start slave') - - return mw.returnJson(True, '设置成功!') - - -def deleteSlave(version=''): - db = pMysqlDb() - dlist = db.query('stop slave;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') - if args['db'] == 'all' or args['db'] == 'ALL': - dlist = findBinlogDoDb() - cmd = getServerDir() + "/bin/mysqldump -uroot -p" + \ - pwd + " --databases " + ' '.join(dlist) + \ - " > /tmp/dump.sql" - else: - cmd = getServerDir() + "/bin/mysqldump -uroot -p" + pwd + \ - " --databases " + args['db'] + " > /tmp/dump.sql" - - ret = mw.execShell(cmd) - - if ret[0] == '': - return 'ok' - return 'fail' - - -from threading import Thread -from time import sleep - - -def mw_async(f): - def wrapper(*args, **kwargs): - thr = Thread(target=f, args=args, kwargs=kwargs) - thr.start() - return wrapper - - -############### --- 重要 同步---- ########### - -def writeDbSyncStatus(data): - path = '/tmp/db_async_status.txt' - # status_data['code'] = 1 - # status_data['msg'] = '主服务器备份完成...' - # status_data['progress'] = 30 - mw.writeFile(path, json.dumps(data)) - - -def doFullSync(): - - args = getArgs() - data = checkArgs(args, ['db']) - if not data[0]: - return data[1] - - arg_db_select = args['db'] - - status_data = {} - status_data['progress'] = 5 - - db = pMysqlDb() - - dlist = db.query('show slave status') - dlist = list(dlist) - if len(dlist) == 0: - status_data['code'] = -1 - status_data['msg'] = '没有启动...' - - ip = dlist[0][1] - print("master ip:", ip) - - id_rsa_conn = pSqliteDb('slave_id_rsa') - data = id_rsa_conn.field('ip,port,id_rsa').where("ip=?", (ip,)).select() - - SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt" - id_rsa_key = data[0]['id_rsa'] - id_rsa_key = id_rsa_key.replace('\\n', '\n') - master_port = int(data[0]['port']) - - mw.writeFile(SSH_PRIVATE_KEY, id_rsa_key) - - 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: - key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) - # ssh.load_system_host_keys() - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - ssh.connect(hostname=ip, port=master_port, username='root', pkey=key) - except Exception as e: - writeDbSyncStatus( - {'code': 0, 'msg': 'SSH配置错误:' + str(e), 'progress': 0}) - return 'fail' - - writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5}) - - cmd = "cd /www/server/mdserver-web && python /www/server/mdserver-web/plugins/mysql/index.py dump_mysql_data {\"db\":'" + args[ - 'db'] + "'}" - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result_err = stderr.read() - - result = result.decode('utf-8') - # print(result) - if result.strip() == 'ok': - writeDbSyncStatus({'code': 1, 'msg': '主服务器备份完成...', 'progress': 30}) - else: - writeDbSyncStatus({'code': 1, 'msg': '主服务器备份失败...', 'progress': 30}) - return 'fail' - - r = mw.execShell('scp root@' + ip + ':/tmp/dump.sql /tmp') - if r[0] == '': - writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40}) - - cmd = 'cd /www/server/mdserver-web && python /www/server/mdserver-web/plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"","db":""}' - stdin, stdout, stderr = ssh.exec_command(cmd) - result = stdout.read() - result_err = stderr.read() - cmd_data = json.loads(result) - # print(cmd_data) - - db.query('stop slave') - writeDbSyncStatus({'code': 3, 'msg': '停止从库完成...', 'progress': 45}) - - dlist = db.query(cmd_data['data']) - writeDbSyncStatus({'code': 4, 'msg': '刷新从库同步信息完成...', 'progress': 50}) - - pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') - root_dir = getServerDir() - msock = root_dir + "/mysql.sock" - cmd = root_dir + "/bin/mysql -S " + msock + \ - " -uroot -p" + pwd + " < /tmp/dump.sql" - import_data = mw.execShell(cmd) - print(import_data[0]) - print(import_data[1]) - if import_data[0] == '': - writeDbSyncStatus({'code': 5, 'msg': '导入数据完成...', 'progress': 90}) - else: - writeDbSyncStatus({'code': 5, 'msg': '导入数据失败...', 'progress': 90}) - return 'fail' - - 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 = '/tmp/db_async_status.txt' - if args['begin'] == '1': - cmd = 'cd ' + mw.getRunDir() + ' && python ' + \ - getPluginDir() + \ - '/index.py do_full_sync {"db":"' + args['db'] + '"} &' - # 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: - dump_size = os.path.getsize("/tmp/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): - swap_path = mw.getServerDir() + "/swap" - if not os.path.exists(swap_path): - return "为了稳定安装MySQL,先安装swap插件!" - return 'ok' - - -def uninstallPreInspection(version): - # return "请手动删除MySQL[{}]".format(version) - return 'ok' - -if __name__ == "__main__": - func = sys.argv[1] - - version = "5.6" - if (len(sys.argv) > 2): - version = sys.argv[2] - - 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()) - elif func == 'db_status': - print(myDbStatus()) - elif func == 'set_db_status': - print(setDbStatus()) - elif func == 'conf': - print(getConf()) - elif func == 'bin_log': - print(binLog()) - 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()) - elif func == 'my_port': - print(getMyPort()) - elif func == 'set_my_port': - print(setMyPort()) - elif func == 'init_pwd': - print(initMysqlPwd()) - elif func == 'get_db_list': - print(getDbList()) - elif func == 'set_db_backup': - print(setDbBackup()) - elif func == 'import_db_backup': - print(importDbBackup()) - elif func == 'delete_db_backup': - print(deleteDbBackup()) - elif func == 'get_db_backup_list': - print(getDbBackupList()) - 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()) - elif func == 'set_user_pwd': - print(setUserPwd()) - elif func == 'get_db_access': - print(getDbAccess()) - elif func == 'set_db_access': - print(setDbAccess()) - 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_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 == '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 == '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 == '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()) - elif func == 'dump_mysql_data': - print(dumpMysqlData(version)) - else: - print('error') diff --git a/plugins/op_waf/t/cc.py b/plugins/op_waf/t/cc.py new file mode 100644 index 0000000000..3ad1ef97db --- /dev/null +++ b/plugins/op_waf/t/cc.py @@ -0,0 +1,7 @@ +# coding:utf-8 + +import sys +import io +import os +import time +import json diff --git a/plugins/op_waf/t/index.py b/plugins/op_waf/t/index.py new file mode 100644 index 0000000000..b0cccb57a4 --- /dev/null +++ b/plugins/op_waf/t/index.py @@ -0,0 +1,19 @@ +# coding:utf-8 + +import sys +import io +import os +import time +import json + + +TEST_URL = "t1.cn" + + +def run(): + print('op lua run ok') + +if __name__ == "__main__": + if len(sys.argv) > 1: + if action == "run": + run() diff --git a/plugins/op_waf/t/readme.md b/plugins/op_waf/t/readme.md new file mode 100755 index 0000000000..e69de29bb2 diff --git a/plugins/op_waf/t/test.sh b/plugins/op_waf/t/test.sh new file mode 100755 index 0000000000..1916180157 --- /dev/null +++ b/plugins/op_waf/t/test.sh @@ -0,0 +1,7 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH + +python3 index.py + + diff --git a/plugins/op_waf/tool_task.py b/plugins/op_waf/tool_task.py new file mode 100644 index 0000000000..8c6b6321cd --- /dev/null +++ b/plugins/op_waf/tool_task.py @@ -0,0 +1,158 @@ +# coding:utf-8 + +import sys +import io +import os +import time +import json + +sys.path.append(os.getcwd() + "/class/core") +import mw + + +app_debug = False +if mw.isAppleSystem(): + app_debug = True + + +def getPluginName(): + return 'op_waf' + + +def getPluginDir(): + return mw.getPluginDir() + '/' + getPluginName() + + +def getServerDir(): + return mw.getServerDir() + '/' + getPluginName() + + +def getTaskConf(): + conf = getServerDir() + "/task_config.json" + return conf + + +def getConfigData(): + try: + return json.loads(mw.readFile(getTaskConf())) + except: + pass + return [] + + +def getConfigTpl(): + tpl = { + "name": "", + "task_id": -1, + } + return tpl + + +def createBgTask(): + removeBgTask() + args = { + "period": "minute-n", + "minute-n": "3", + } + createBgTaskByName(getPluginName(), args) + + +def createBgTaskByName(name, args): + cfg = getConfigTpl() + _name = "[勿删]OP防火墙后台任务[" + name + "]" + res = mw.M("crontab").field("id, name").where("name=?", (_name,)).find() + if res: + return True + + if "task_id" in cfg.keys() and cfg["task_id"] > 0: + res = mw.M("crontab").field("id, name").where( + "id=?", (cfg["task_id"],)).find() + if res and res["id"] == cfg["task_id"]: + print("计划任务已经存在!") + return True + import crontab_api + api = crontab_api.crontab_api() + + period = args['period'] + _hour = '' + _minute = '' + _where1 = '' + _type_day = "day" + if period == 'day': + _type_day = 'day' + _hour = args['hour'] + _minute = args['minute'] + elif period == 'minute-n': + _type_day = 'minute-n' + _where1 = args['minute-n'] + _minute = '' + + cmd = ''' +rname=%s +plugin_path=%s +script_path=%s +logs_file=$plugin_path/${rname}.log +''' % (name, getServerDir(), getPluginDir()) + cmd += 'echo "★【`date +"%Y-%m-%d %H:%M:%S"`】 STSRT★" >> $logs_file' + "\n" + cmd += 'echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" >> $logs_file' + "\n" + cmd += 'echo "python3 $script_path/tool_task.py run >> $logs_file 2>&1"' + "\n" + cmd += 'python3 $script_path/tool_task.py run >> $logs_file 2>&1' + "\n" + cmd += 'echo "【`date +"%Y-%m-%d %H:%M:%S"`】 END★" >> $logs_file' + "\n" + cmd += 'echo "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" >> $logs_file' + "\n" + + params = { + 'name': _name, + 'type': _type_day, + 'week': "", + 'where1': _where1, + 'hour': _hour, + 'minute': _minute, + 'save': "", + 'backup_to': "", + 'stype': "toShell", + 'sname': '', + 'sbody': cmd, + 'urladdress': '', + } + + task_id = api.add(params) + if task_id > 0: + cfg["task_id"] = task_id + cfg["name"] = name + + _dd = getConfigData() + _dd.append(cfg) + mw.writeFile(getTaskConf(), json.dumps(_dd)) + + +def removeBgTask(): + cfg_list = getConfigData() + for x in range(len(cfg_list)): + cfg = cfg_list[x] + if "task_id" in cfg.keys() and cfg["task_id"] > 0: + res = mw.M("crontab").field("id, name").where( + "id=?", (cfg["task_id"],)).find() + if res and res["id"] == cfg["task_id"]: + import crontab_api + api = crontab_api.crontab_api() + data = api.delete(cfg["task_id"]) + if data[0]: + cfg["task_id"] = -1 + cfg_list[x] = cfg + mw.writeFile(getTaskConf(), '[]') + return True + return False + + +def run(): + print('op lua run ok') + +if __name__ == "__main__": + if len(sys.argv) > 1: + action = sys.argv[1] + if action == "remove": + removeBgTask() + elif action == "add": + createBgTask() + elif action == "run": + run() diff --git a/plugins/openresty/bak/index_2022_6_17.py b/plugins/openresty/bak/index_2022_6_17.py deleted file mode 100755 index 490e06417e..0000000000 --- a/plugins/openresty/bak/index_2022_6_17.py +++ /dev/null @@ -1,309 +0,0 @@ -# coding:utf-8 - -import sys -import io -import os -import time -import subprocess - -sys.path.append(os.getcwd() + "/class/core") -import mw - - -app_debug = False - -if mw.isAppleSystem(): - app_debug = True - - -def getPluginName(): - return 'openresty' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def getInitDFile(): - if app_debug: - return '/tmp/' + getPluginName() - return '/etc/init.d/' + getPluginName() - - -def getArgs(): - args = sys.argv[2:] - tmp = {} - args_len = len(args) - - if args_len == 1: - t = args[0].strip('{').strip('}') - t = t.split(':') - tmp[t[0]] = t[1] - elif args_len > 1: - for i in range(len(args)): - t = args[i].split(':') - tmp[t[0]] = t[1] - - return tmp - - -def clearTemp(): - path_bin = getServerDir() + "/nginx" - mw.execShell('rm -rf ' + path_bin + '/client_body_temp') - mw.execShell('rm -rf ' + path_bin + '/fastcgi_temp') - mw.execShell('rm -rf ' + path_bin + '/proxy_temp') - mw.execShell('rm -rf ' + path_bin + '/scgi_temp') - mw.execShell('rm -rf ' + path_bin + '/uwsgi_temp') - - -def getConf(): - path = getServerDir() + "/nginx/conf/nginx.conf" - return path - - -def getConfTpl(): - path = getPluginDir() + '/conf/nginx.conf' - return path - - -def getOs(): - data = {} - data['os'] = mw.getOs() - ng_exe_bin = getServerDir() + "/nginx/sbin/nginx" - if checkAuthEq(ng_exe_bin, 'root'): - data['auth'] = True - else: - data['auth'] = False - return mw.getJson(data) - - -def getInitDTpl(): - path = getPluginDir() + "/init.d/nginx.tpl" - return path - - -def makeConf(): - vhost = getServerDir() + '/nginx/conf/vhost' - if not os.path.exists(vhost): - os.mkdir(vhost) - php_status = getServerDir() + '/nginx/conf/php_status' - if not os.path.exists(php_status): - os.mkdir(php_status) - - -def getFileOwner(filename): - import pwd - stat = os.lstat(filename) - uid = stat.st_uid - pw = pwd.getpwuid(uid) - return pw.pw_name - - -def checkAuthEq(file, owner='root'): - fowner = getFileOwner(file) - if (fowner == owner): - return True - return False - - -def confReplace(): - service_path = os.path.dirname(os.getcwd()) - content = mw.readFile(getConfTpl()) - content = content.replace('{$SERVER_PATH}', service_path) - - user = 'www' - user_group = 'www' - - if mw.getOs() == 'darwin': - # macosx do - user = mw.execShell( - "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() - # user = 'root' - user_group = 'staff' - content = content.replace('{$EVENT_MODEL}', 'kqueue') - else: - content = content.replace('{$EVENT_MODEL}', 'epoll') - - content = content.replace('{$OS_USER}', user) - content = content.replace('{$OS_USER_GROUP}', user_group) - - nconf = getServerDir() + '/nginx/conf/nginx.conf' - - __content = mw.readFile(nconf) - if __content.find('#user'): - mw.writeFile(getServerDir() + '/nginx/conf/nginx.conf', content) - - # give nginx root permission - ng_exe_bin = getServerDir() + "/nginx/sbin/nginx" - if not checkAuthEq(ng_exe_bin, 'root'): - args = getArgs() - sudoPwd = args['pwd'] - cmd_own = 'chown -R ' + 'root:' + user_group + ' ' + ng_exe_bin - os.system('echo %s|sudo -S %s' % (sudoPwd, cmd_own)) - cmd_mod = 'chmod 755 ' + ng_exe_bin - os.system('echo %s|sudo -S %s' % (sudoPwd, cmd_mod)) - cmd_s = 'chmod u+s ' + ng_exe_bin - os.system('echo %s|sudo -S %s' % (sudoPwd, cmd_s)) - - -def initDreplace(): - - file_tpl = getInitDTpl() - service_path = os.path.dirname(os.getcwd()) - - initD_path = getServerDir() + '/init.d' - - # Openresty is not installed - if not os.path.exists(getServerDir()): - print("ok") - exit(0) - - file_bin = initD_path + '/' + getPluginName() - if not os.path.exists(initD_path): - os.mkdir(initD_path) - - # initd replace - content = mw.readFile(file_tpl) - content = content.replace('{$SERVER_PATH}', service_path) - mw.writeFile(file_bin, content) - mw.execShell('chmod +x ' + file_bin) - - # config replace - confReplace() - - # make nginx vhost or other - makeConf() - - return file_bin - - -def status(): - data = mw.execShell( - "ps -ef|grep nginx |grep -v grep | grep -v python | awk '{print $2}'") - if data[0] == '': - return 'stop' - return 'start' - - -def start(): - file = initDreplace() - data = mw.execShell(file + ' start') - if data[1] == '': - return 'ok' - return data[1] - - -def stop(): - file = initDreplace() - data = mw.execShell(file + ' stop') - clearTemp() - if data[1] == '': - return 'ok' - return data[1] - - -def restart(): - file = initDreplace() - data = mw.execShell(file + ' restart') - if data[1] == '': - return 'ok' - return data[1] - - -def reload(): - file = initDreplace() - data = mw.execShell(file + ' reload') - if data[1] == '': - return 'ok' - return data[1] - - -def initdStatus(): - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - initd_bin = getInitDFile() - if os.path.exists(initd_bin): - return 'ok' - return 'fail' - - -def initdInstall(): - import shutil - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - - source_bin = initDreplace() - initd_bin = getInitDFile() - shutil.copyfile(source_bin, initd_bin) - mw.execShell('chmod +x ' + initd_bin) - mw.execShell('chkconfig --add ' + getPluginName()) - return 'ok' - - -def initdUinstall(): - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mw.execShell('chkconfig --del ' + getPluginName()) - initd_bin = getInitDFile() - os.remove(initd_bin) - return 'ok' - - -def runInfo(): - # 取Openresty负载状态 - try: - result = mw.httpGet('http://127.0.0.1/nginx_status') - tmp = result.split() - data = {} - data['active'] = tmp[2] - data['accepts'] = tmp[9] - data['handled'] = tmp[7] - data['requests'] = tmp[8] - data['Reading'] = tmp[11] - data['Writing'] = tmp[13] - data['Waiting'] = tmp[15] - return mw.getJson(data) - except Exception as e: - return 'oprenresty not started' - - -def errorLogPath(): - return getServerDir() + '/nginx/logs/error.log' - - -if __name__ == "__main__": - func = sys.argv[1] - if func == 'status': - print(status()) - elif func == 'start': - print(start()) - elif func == 'stop': - print(stop()) - elif func == 'restart': - print(restart()) - elif func == 'reload': - print(reload()) - elif func == 'initd_status': - print(initdStatus()) - elif func == 'initd_install': - print(initdInstall()) - elif func == 'initd_uninstall': - print(initdUinstall()) - elif func == 'conf': - print(getConf()) - elif func == 'get_os': - print(getOs()) - elif func == 'run_info': - print(runInfo()) - elif func == 'error_log': - print(errorLogPath()) - else: - print('error') diff --git a/plugins/php/bak/index_2022_6_18.py b/plugins/php/bak/index_2022_6_18.py deleted file mode 100755 index d07bb81957..0000000000 --- a/plugins/php/bak/index_2022_6_18.py +++ /dev/null @@ -1,725 +0,0 @@ -# coding:utf-8 - -import sys -import io -import os -import time -import re -import json -import shutil - -# reload(sys) -# sys.setdefaultencoding('utf8') - -sys.path.append(os.getcwd() + "/class/core") -# sys.path.append("/usr/local/lib/python3.6/site-packages") - -import 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 'php' - - -def getPluginDir(): - return mw.getPluginDir() + '/' + getPluginName() - - -def getServerDir(): - return mw.getServerDir() + '/' + getPluginName() - - -def getInitDFile(version): - if app_debug: - return '/tmp/' + getPluginName() - return '/etc/init.d/' + getPluginName() + version - - -def getArgs(): - args = sys.argv[3:] - tmp = {} - args_len = len(args) - - if args_len == 1: - t = args[0].strip('{').strip('}') - t = t.split(':') - tmp[t[0]] = t[1] - elif args_len > 1: - for i in range(len(args)): - t = args[i].split(':') - 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 getConf(version): - path = getServerDir() + '/' + version + '/etc/php.ini' - return path - - -def status(version): - cmd = "ps -ef|grep 'php/" + version + \ - "' |grep -v grep | grep -v python | awk '{print $2}'" - data = mw.execShell(cmd) - if data[0] == '': - return 'stop' - return 'start' - - -def contentReplace(content, version): - service_path = mw.getServerDir() - content = content.replace('{$ROOT_PATH}', mw.getRootDir()) - content = content.replace('{$SERVER_PATH}', service_path) - content = content.replace('{$PHP_VERSION}', version) - content = content.replace('{$LOCAL_IP}', mw.getLocalIp()) - - if mw.isAppleSystem(): - # user = mw.execShell( - # "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip() - content = content.replace('{$PHP_USER}', 'nobody') - content = content.replace('{$PHP_GROUP}', 'nobody') - - rep = 'listen.owner\s*=\s*(.+)\r?\n' - val = ';listen.owner = nobody\n' - content = re.sub(rep, val, content) - - rep = 'listen.group\s*=\s*(.+)\r?\n' - val = ';listen.group = nobody\n' - content = re.sub(rep, val, content) - - rep = 'user\s*=\s*(.+)\r?\n' - val = ';user = nobody\n' - content = re.sub(rep, val, content) - - rep = r'[^\.]group\s*=\s*(.+)\r?\n' - val = ';group = nobody\n' - content = re.sub(rep, val, content) - - else: - content = content.replace('{$PHP_USER}', 'www') - content = content.replace('{$PHP_GROUP}', 'www') - return content - - -def makeOpenrestyConf(): - phpversions = ['00', '52', '53', '54', '55', '56', - '70', '71', '72', '73', '74', '80', '81'] - if mw.isInstalledWeb(): - sdir = mw.getServerDir() - d_pathinfo = sdir + '/openresty/nginx/conf/pathinfo.conf' - if not os.path.exists(d_pathinfo): - s_pathinfo = getPluginDir() + '/conf/pathinfo.conf' - shutil.copyfile(s_pathinfo, d_pathinfo) - - info = getPluginDir() + '/info.json' - content = mw.readFile(info) - content = json.loads(content) - versions = content['versions'] - tpl = getPluginDir() + '/conf/enable-php.conf' - tpl_content = mw.readFile(tpl) - for x in phpversions: - dfile = sdir + '/openresty/nginx/conf/enable-php-' + x + '.conf' - if not os.path.exists(dfile): - if x == '00': - mw.writeFile(dfile, '') - else: - w_content = contentReplace(tpl_content, x) - mw.writeFile(dfile, w_content) - - # php-fpm status - for version in phpversions: - dfile = sdir + '/openresty/nginx/conf/php_status/phpfpm_status_' + version + '.conf' - tpl = getPluginDir() + '/conf/phpfpm_status.conf' - if not os.path.exists(dfile): - content = mw.readFile(tpl) - content = contentReplace(content, version) - mw.writeFile(dfile, content) - mw.restartWeb() - - -def phpPrependFile(version): - app_start = getServerDir() + '/app_start.php' - if not os.path.exists(app_start): - tpl = getPluginDir() + '/conf/app_start.php' - content = mw.readFile(tpl) - content = contentReplace(content, version) - mw.writeFile(app_start, content) - - -def phpFpmReplace(version): - desc_php_fpm = getServerDir() + '/' + version + '/etc/php-fpm.conf' - if not os.path.exists(desc_php_fpm): - tpl_php_fpm = getPluginDir() + '/conf/php-fpm.conf' - content = mw.readFile(tpl_php_fpm) - content = contentReplace(content, version) - mw.writeFile(desc_php_fpm, content) - else: - if version == '52': - tpl_php_fpm = tpl_php_fpm = getPluginDir() + '/conf/php-fpm-52.conf' - content = mw.readFile(tpl_php_fpm) - mw.writeFile(desc_php_fpm, content) - - -def phpFpmWwwReplace(version): - service_php_fpm_dir = getServerDir() + '/' + version + '/etc/php-fpm.d/' - - if not os.path.exists(service_php_fpm_dir): - os.mkdir(service_php_fpm_dir) - - service_php_fpmwww = service_php_fpm_dir + '/www.conf' - if not os.path.exists(service_php_fpmwww): - tpl_php_fpmwww = getPluginDir() + '/conf/www.conf' - content = mw.readFile(tpl_php_fpmwww) - content = contentReplace(content, version) - mw.writeFile(service_php_fpmwww, content) - - -def makePhpIni(version): - d_ini = mw.getServerDir() + '/php/' + version + '/etc/php.ini' - if not os.path.exists(d_ini): - s_ini = getPluginDir() + '/conf/php' + version[0:1] + '.ini' - # shutil.copyfile(s_ini, d_ini) - content = mw.readFile(s_ini) - if version == '52': - content = content + "auto_prepend_file=/www/server/php/app_start.php" - mw.writeFile(d_ini, content) - - -def initReplace(version): - makeOpenrestyConf() - makePhpIni(version) - - initD_path = getServerDir() + '/init.d' - if not os.path.exists(initD_path): - os.mkdir(initD_path) - - file_bin = initD_path + '/php' + version - if not os.path.exists(file_bin): - file_tpl = getPluginDir() + '/init.d/php.tpl' - - if version == '52': - file_tpl = getPluginDir() + '/init.d/php52.tpl' - - content = mw.readFile(file_tpl) - content = contentReplace(content, version) - - mw.writeFile(file_bin, content) - mw.execShell('chmod +x ' + file_bin) - - phpPrependFile(version) - phpFpmWwwReplace(version) - phpFpmReplace(version) - - session_path = '/tmp/session' - if not os.path.exists(session_path): - os.mkdir(session_path) - if not mw.isAppleSystem(): - mw.execShell('chown -R www:www ' + session_path) - - upload_path = '/tmp/upload' - if not os.path.exists(upload_path): - os.mkdir(upload_path) - if not mw.isAppleSystem(): - mw.execShell('chown -R www:www ' + upload_path) - return file_bin - - -def phpOp(version, method): - file = initReplace(version) - data = mw.execShell(file + ' ' + method) - if data[1] == '': - return 'ok' - return data[1] - - -def start(version): - return phpOp(version, 'start') - - -def stop(version): - return phpOp(version, 'stop') - - -def restart(version): - return phpOp(version, 'restart') - - -def reload(version): - return phpOp(version, 'reload') - - -def initdStatus(version): - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - initd_bin = getInitDFile(version) - if os.path.exists(initd_bin): - return 'ok' - return 'fail' - - -def initdInstall(version): - import shutil - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - - source_bin = initReplace(version) - initd_bin = getInitDFile(version) - shutil.copyfile(source_bin, initd_bin) - mw.execShell('chmod +x ' + initd_bin) - mw.execShell('chkconfig --add ' + getPluginName() + version) - return 'ok' - - -def initdUinstall(version): - if not app_debug: - if mw.isAppleSystem(): - return "Apple Computer does not support" - - mw.execShell('chkconfig --del ' + getPluginName()) - initd_bin = getInitDFile(version) - os.remove(initd_bin) - return 'ok' - - -def fpmLog(version): - return getServerDir() + '/' + version + '/var/log/php-fpm.log' - - -def fpmSlowLog(version): - return getServerDir() + '/' + version + '/var/log/www-slow.log' - - -def getPhpConf(version): - gets = [ - {'name': 'short_open_tag', 'type': 1, 'ps': '短标签支持'}, - {'name': 'asp_tags', 'type': 1, 'ps': 'ASP标签支持'}, - {'name': 'max_execution_time', 'type': 2, 'ps': '最大脚本运行时间'}, - {'name': 'max_input_time', 'type': 2, 'ps': '最大输入时间'}, - {'name': 'max_input_var', 'type': 2, 'ps': '最大输入数量'}, - {'name': 'memory_limit', 'type': 2, 'ps': '脚本内存限制'}, - {'name': 'post_max_size', 'type': 2, 'ps': 'POST数据最大尺寸'}, - {'name': 'file_uploads', 'type': 1, 'ps': '是否允许上传文件'}, - {'name': 'upload_max_filesize', 'type': 2, 'ps': '允许上传文件的最大尺寸'}, - {'name': 'max_file_uploads', 'type': 2, 'ps': '允许同时上传文件的最大数量'}, - {'name': 'default_socket_timeout', 'type': 2, 'ps': 'Socket超时时间'}, - {'name': 'error_reporting', 'type': 3, 'ps': '错误级别'}, - {'name': 'display_errors', 'type': 1, 'ps': '是否输出详细错误信息'}, - {'name': 'cgi.fix_pathinfo', 'type': 0, 'ps': '是否开启pathinfo'}, - {'name': 'date.timezone', 'type': 3, 'ps': '时区'} - ] - phpini = mw.readFile(getServerDir() + '/' + version + '/etc/php.ini') - result = [] - for g in gets: - rep = g['name'] + '\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)' - tmp = re.search(rep, phpini) - if not tmp: - continue - g['value'] = tmp.groups()[0] - result.append(g) - return mw.getJson(result) - - -def submitPhpConf(version): - gets = ['display_errors', 'cgi.fix_pathinfo', 'date.timezone', 'short_open_tag', - 'asp_tags', 'max_execution_time', 'max_input_time', 'memory_limit', - 'post_max_size', 'file_uploads', 'upload_max_filesize', 'max_file_uploads', - 'default_socket_timeout', 'error_reporting'] - args = getArgs() - filename = getServerDir() + '/' + version + '/etc/php.ini' - phpini = mw.readFile(filename) - for g in gets: - if g in args: - rep = g + '\s*=\s*(.+)\r?\n' - val = g + ' = ' + args[g] + '\n' - phpini = re.sub(rep, val, phpini) - mw.writeFile(filename, phpini) - mw.execShell(getServerDir() + '/init.d/php' + version + ' reload') - return mw.returnJson(True, '设置成功') - - -def getLimitConf(version): - fileini = getServerDir() + "/" + version + "/etc/php.ini" - phpini = mw.readFile(fileini) - filefpm = getServerDir() + "/" + version + "/etc/php-fpm.conf" - phpfpm = mw.readFile(filefpm) - - # print fileini, filefpm - data = {} - try: - rep = "upload_max_filesize\s*=\s*([0-9]+)M" - tmp = re.search(rep, phpini).groups() - data['max'] = tmp[0] - except: - data['max'] = '50' - - try: - rep = "request_terminate_timeout\s*=\s*([0-9]+)\n" - tmp = re.search(rep, phpfpm).groups() - data['maxTime'] = tmp[0] - except: - data['maxTime'] = 0 - - try: - rep = r"\n;*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n" - tmp = re.search(rep, phpini).groups() - - if tmp[0] == '1': - data['pathinfo'] = True - else: - data['pathinfo'] = False - except: - data['pathinfo'] = False - - return mw.getJson(data) - - -def setMaxTime(version): - args = getArgs() - data = checkArgs(args, ['time']) - if not data[0]: - return data[1] - - time = args['time'] - if int(time) < 30 or int(time) > 86400: - return mw.returnJson(False, '请填写30-86400间的值!') - - filefpm = getServerDir() + "/" + version + "/etc/php-fpm.conf" - conf = mw.readFile(filefpm) - rep = "request_terminate_timeout\s*=\s*([0-9]+)\n" - conf = re.sub(rep, "request_terminate_timeout = " + time + "\n", conf) - mw.writeFile(filefpm, conf) - - fileini = getServerDir() + "/" + version + "/etc/php.ini" - phpini = mw.readFile(fileini) - rep = "max_execution_time\s*=\s*([0-9]+)\r?\n" - phpini = re.sub(rep, "max_execution_time = " + time + "\n", phpini) - rep = "max_input_time\s*=\s*([0-9]+)\r?\n" - phpini = re.sub(rep, "max_input_time = " + time + "\n", phpini) - mw.writeFile(fileini, phpini) - return mw.returnJson(True, '设置成功!') - - -def setMaxSize(version): - args = getArgs() - if not 'max' in args: - return 'missing time args!' - max = args['max'] - if int(max) < 2: - return mw.returnJson(False, '上传大小限制不能小于2MB!') - - path = getServerDir() + '/' + version + '/etc/php.ini' - conf = mw.readFile(path) - rep = u"\nupload_max_filesize\s*=\s*[0-9]+M" - conf = re.sub(rep, u'\nupload_max_filesize = ' + max + 'M', conf) - rep = u"\npost_max_size\s*=\s*[0-9]+M" - conf = re.sub(rep, u'\npost_max_size = ' + max + 'M', conf) - mw.writeFile(path, conf) - - msg = mw.getInfo('设置PHP-{1}最大上传大小为[{2}MB]!', (version, max,)) - mw.writeLog('插件管理[PHP]', msg) - return mw.returnJson(True, '设置成功!') - - -def getFpmConfig(version): - - filefpm = getServerDir() + '/' + version + '/etc/php-fpm.d/www.conf' - conf = mw.readFile(filefpm) - data = {} - rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*" - tmp = re.search(rep, conf).groups() - data['max_children'] = tmp[0] - - rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*" - tmp = re.search(rep, conf).groups() - data['start_servers'] = tmp[0] - - rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*" - tmp = re.search(rep, conf).groups() - data['min_spare_servers'] = tmp[0] - - rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*" - tmp = re.search(rep, conf).groups() - data['max_spare_servers'] = tmp[0] - - rep = "\s*pm\s*=\s*(\w+)\s*" - tmp = re.search(rep, conf).groups() - data['pm'] = tmp[0] - return mw.getJson(data) - - -def setFpmConfig(version): - args = getArgs() - # if not 'max' in args: - # return 'missing time args!' - - version = args['version'] - max_children = args['max_children'] - start_servers = args['start_servers'] - min_spare_servers = args['min_spare_servers'] - max_spare_servers = args['max_spare_servers'] - pm = args['pm'] - - file = getServerDir() + '/' + version + '/etc/php-fpm.d/www.conf' - conf = mw.readFile(file) - - rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*" - conf = re.sub(rep, "\npm.max_children = " + max_children, conf) - - rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*" - conf = re.sub(rep, "\npm.start_servers = " + start_servers, conf) - - rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*" - conf = re.sub(rep, "\npm.min_spare_servers = " + - min_spare_servers, conf) - - rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*" - conf = re.sub(rep, "\npm.max_spare_servers = " + - max_spare_servers + "\n", conf) - - rep = "\s*pm\s*=\s*(\w+)\s*" - conf = re.sub(rep, "\npm = " + pm + "\n", conf) - - mw.writeFile(file, conf) - reload(version) - - msg = mw.getInfo('设置PHP-{1}并发设置,max_children={2},start_servers={3},min_spare_servers={4},max_spare_servers={5}', (version, max_children, - start_servers, min_spare_servers, max_spare_servers,)) - mw.writeLog('插件管理[PHP]', msg) - return mw.returnJson(True, '设置成功!') - - -def checkFpmStatusFile(version): - if mw.isInstalledWeb(): - sdir = mw.getServerDir() - dfile = sdir + '/openresty/nginx/conf/php_status/phpfpm_status_' + version + '.conf' - if not os.path.exists(dfile): - tpl = getPluginDir() + '/conf/phpfpm_status.conf' - content = mw.readFile(tpl) - content = contentReplace(content, version) - mw.writeFile(dfile, content) - mw.restartWeb() - - -def getFpmStatus(version): - checkFpmStatusFile(version) - result = mw.httpGet( - 'http://127.0.0.1/phpfpm_status_' + version + '?json') - tmp = json.loads(result) - fTime = time.localtime(int(tmp['start time'])) - tmp['start time'] = time.strftime('%Y-%m-%d %H:%M:%S', fTime) - return mw.getJson(tmp) - - -def getDisableFunc(version): - filename = mw.getServerDir() + '/php/' + version + '/etc/php.ini' - if not os.path.exists(filename): - return mw.returnJson(False, '指定PHP版本不存在!') - - phpini = mw.readFile(filename) - data = {} - rep = "disable_functions\s*=\s{0,1}(.*)\n" - tmp = re.search(rep, phpini).groups() - data['disable_functions'] = tmp[0] - return mw.getJson(data) - - -def setDisableFunc(version): - filename = mw.getServerDir() + '/php/' + version + '/etc/php.ini' - if not os.path.exists(filename): - return mw.returnJson(False, '指定PHP版本不存在!') - - args = getArgs() - disable_functions = args['disable_functions'] - - phpini = mw.readFile(filename) - rep = "disable_functions\s*=\s*.*\n" - phpini = re.sub(rep, 'disable_functions = ' + - disable_functions + "\n", phpini) - - msg = mw.getInfo('修改PHP-{1}的禁用函数为[{2}]', (version, disable_functions,)) - mw.writeLog('插件管理[PHP]', msg) - mw.writeFile(filename, phpini) - reload(version) - return mw.returnJson(True, '设置成功!') - - -def checkPhpinfoFile(v): - if mw.isInstalledWeb(): - sdir = mw.getServerDir() - dfile = sdir + '/openresty/nginx/conf/php_status/phpinfo_' + v + '.conf' - if not os.path.exists(dfile): - tpl = getPluginDir() + '/conf/phpinfo.conf' - content = mw.readFile(tpl) - content = contentReplace(content, v) - mw.writeFile(dfile, content) - mw.restartWeb() - - -def getPhpinfo(v): - checkPhpinfoFile(v) - sPath = mw.getRootDir() + '/phpinfo/' + v - mw.execShell("rm -rf " + mw.getRootDir() + '/phpinfo') - mw.execShell("mkdir -p " + sPath) - mw.writeFile(sPath + '/phpinfo.php', '') - url = 'http://127.0.0.1/' + v + '/phpinfo.php' - phpinfo = mw.httpGet(url) - os.system("rm -rf " + mw.getRootDir() + '/phpinfo') - return phpinfo - - -def get_php_info(args): - return getPhpinfo(args['version']) - - -def getLibConf(version): - fname = mw.getServerDir() + '/php/' + version + '/etc/php.ini' - if not os.path.exists(fname): - return mw.returnJson(False, '指定PHP版本不存在!') - - phpini = mw.readFile(fname) - - libpath = getPluginDir() + '/versions/phplib.conf' - phplib = json.loads(mw.readFile(libpath)) - - libs = [] - tasks = mw.M('tasks').where( - "status!=?", ('1',)).field('status,name').select() - for lib in phplib: - lib['task'] = '1' - for task in tasks: - tmp = mw.getStrBetween('[', ']', task['name']) - if not tmp: - continue - tmp1 = tmp.split('-') - if tmp1[0].lower() == lib['name'].lower(): - lib['task'] = task['status'] - lib['phpversions'] = [] - lib['phpversions'].append(tmp1[1]) - if phpini.find(lib['check']) == -1: - lib['status'] = False - else: - lib['status'] = True - libs.append(lib) - return mw.returnJson(True, 'OK!', libs) - - -def installLib(version): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - name = args['name'] - execstr = "cd " + getPluginDir() + '/versions/' + version + " && /bin/bash " + \ - name + '.sh' + ' install ' + version - - rettime = time.strftime('%Y-%m-%d %H:%M:%S') - insert_info = (None, '安装[' + name + '-' + version + ']', - 'execshell', '0', rettime, execstr) - mw.M('tasks').add('id,name,type,status,addtime,execstr', insert_info) - return mw.returnJson(True, '已将下载任务添加到队列!') - - -def uninstallLib(version): - args = getArgs() - data = checkArgs(args, ['name']) - if not data[0]: - return data[1] - - name = args['name'] - execstr = "cd " + getPluginDir() + '/versions/' + version + " && /bin/bash " + \ - name + '.sh' + ' uninstall ' + version - - data = mw.execShell(execstr) - if data[0] == '' and data[1] == '': - return mw.returnJson(True, '已经卸载成功!') - else: - return mw.returnJson(False, '卸载信息![通道0]:' + data[0] + "[通道0]:" + data[1]) - - -def getConfAppStart(): - pstart = mw.getServerDir() + '/php/app_start.php' - return pstart - -if __name__ == "__main__": - - if len(sys.argv) < 3: - print('missing parameters') - exit(0) - - func = sys.argv[1] - version = sys.argv[2] - - 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(version)) - elif func == 'initd_install': - print(initdInstall(version)) - elif func == 'initd_uninstall': - print(initdUinstall(version)) - elif func == 'fpm_log': - print(fpmLog(version)) - elif func == 'fpm_slow_log': - print(fpmSlowLog(version)) - elif func == 'conf': - print(getConf(version)) - elif func == 'app_start': - print(getConfAppStart()) - elif func == 'get_php_conf': - print(getPhpConf(version)) - elif func == 'submit_php_conf': - print(submitPhpConf(version)) - elif func == 'get_limit_conf': - print(getLimitConf(version)) - elif func == 'set_max_time': - print(setMaxTime(version)) - elif func == 'set_max_size': - print(setMaxSize(version)) - elif func == 'get_fpm_conf': - print(getFpmConfig(version)) - elif func == 'set_fpm_conf': - print(setFpmConfig(version)) - elif func == 'get_fpm_status': - print(getFpmStatus(version)) - elif func == 'get_disable_func': - print(getDisableFunc(version)) - elif func == 'set_disable_func': - print(setDisableFunc(version)) - elif func == 'get_phpinfo': - print(getPhpinfo(version)) - elif func == 'get_lib_conf': - print(getLibConf(version)) - elif func == 'install_lib': - print(installLib(version)) - elif func == 'uninstall_lib': - print(uninstallLib(version)) - else: - print("fail") diff --git a/plugins/php/versions/53/install.sh b/plugins/php/versions/53/install.sh index 9591042247..b2c66938a3 100755 --- a/plugins/php/versions/53/install.sh +++ b/plugins/php/versions/53/install.sh @@ -56,6 +56,28 @@ if [ "$IS_64BIT" == "64" ];then OPTIONS="${OPTIONS} --with-libdir=lib64" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ if [ ! -d $serverPath/php/53/bin ];then cd $sourcePath/php/php${PHP_VER} && ./configure \ @@ -88,7 +110,7 @@ if [ ! -d $serverPath/php/53/bin ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi diff --git a/plugins/php/versions/54/install.sh b/plugins/php/versions/54/install.sh index 9d042dd0fe..0e23981f6c 100755 --- a/plugins/php/versions/54/install.sh +++ b/plugins/php/versions/54/install.sh @@ -48,6 +48,29 @@ if [ "$IS_64BIT" == "64" ];then OPTIONS="${OPTIONS} --with-libdir=lib64" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + if [ ! -d $serverPath/php/${PHP_VER} ];then cd $sourcePath/php/php${PHP_VER} && ./configure \ @@ -73,7 +96,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then $OPTIONS \ --enable-fpm - make clean && make + make clean && make -j${cpuCore} #debian11,没有生成php54 man if [ ! -f sapi/cli/php.1 ];then diff --git a/plugins/php/versions/55/install.sh b/plugins/php/versions/55/install.sh index a801717b93..e067c67543 100755 --- a/plugins/php/versions/55/install.sh +++ b/plugins/php/versions/55/install.sh @@ -47,6 +47,29 @@ if [ "$IS_64BIT" == "64" ];then OPTIONS="${OPTIONS} --with-libdir=lib64" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + if [ ! -d $serverPath/php/55 ];then cd $sourcePath/php/php${PHP_VER} && ./configure \ --prefix=$serverPath/php/55 \ @@ -71,7 +94,7 @@ if [ ! -d $serverPath/php/55 ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# diff --git a/plugins/php/versions/56/install.sh b/plugins/php/versions/56/install.sh index 3d185c01b1..af7e2ee7e8 100755 --- a/plugins/php/versions/56/install.sh +++ b/plugins/php/versions/56/install.sh @@ -47,6 +47,29 @@ if [ "$IS_64BIT" == "64" ];then OPTIONS="${OPTIONS} --with-libdir=lib64" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + if [ ! -d $serverPath/php/56 ];then cd $sourcePath/php/php${PHP_VER} && ./configure \ @@ -74,7 +97,7 @@ if [ ! -d $serverPath/php/56 ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# diff --git a/plugins/php/versions/70/install.sh b/plugins/php/versions/70/install.sh index df569d2ff1..06c3f9470b 100755 --- a/plugins/php/versions/70/install.sh +++ b/plugins/php/versions/70/install.sh @@ -64,6 +64,10 @@ if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then else cpuCore="1" fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi # ----- cpu end ------ if [ ! -d $serverPath/php/70 ];then diff --git a/plugins/php/versions/71/install.sh b/plugins/php/versions/71/install.sh index 9c4c0ac4bf..b4542cb8ec 100755 --- a/plugins/php/versions/71/install.sh +++ b/plugins/php/versions/71/install.sh @@ -44,6 +44,29 @@ if [ "$IS_64BIT" == "64" ];then OPTIONS="${OPTIONS} --with-libdir=lib64" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + if [ ! -d $serverPath/php/71 ];then cd $sourcePath/php/php${PHP_VER} && ./configure \ --prefix=$serverPath/php/71 \ @@ -67,7 +90,7 @@ if [ ! -d $serverPath/php/71 ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# diff --git a/plugins/php/versions/72/install.sh b/plugins/php/versions/72/install.sh index 4f814f83ba..e49e08cc26 100755 --- a/plugins/php/versions/72/install.sh +++ b/plugins/php/versions/72/install.sh @@ -46,6 +46,29 @@ if [ "$IS_64BIT" == "64" ];then OPTIONS="${OPTIONS} --with-libdir=lib64" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + if [ ! -d $serverPath/php/72 ];then cd $sourcePath/php/php${PHP_VER} && ./configure \ --prefix=$serverPath/php/72 \ @@ -69,7 +92,7 @@ if [ ! -d $serverPath/php/72 ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# diff --git a/plugins/php/versions/73/install.sh b/plugins/php/versions/73/install.sh index cb05afe83a..3467376c06 100755 --- a/plugins/php/versions/73/install.sh +++ b/plugins/php/versions/73/install.sh @@ -60,6 +60,29 @@ if version_lt "$libzip_version" "0.11.0" ;then ZIP_OPTION="--with-libzip=$serverPath/lib/libzip" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + if [ ! -d $serverPath/php/73 ];then cd $sourcePath/php/php${PHP_VER} && ./configure \ --prefix=$serverPath/php/73 \ @@ -83,7 +106,7 @@ if [ ! -d $serverPath/php/73 ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# diff --git a/plugins/php/versions/74/install.sh b/plugins/php/versions/74/install.sh index a09ffe377f..82430997ae 100755 --- a/plugins/php/versions/74/install.sh +++ b/plugins/php/versions/74/install.sh @@ -76,6 +76,28 @@ if version_lt "$libzip_version" "0.11.0" ;then ZIP_OPTION="--with-zip=$serverPath/lib/libzip" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ if [ ! -d $serverPath/php/${PHP_VER} ];then cd $sourcePath/php/php${PHP_VER} && make clean @@ -102,7 +124,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# } diff --git a/plugins/php/versions/80/install.sh b/plugins/php/versions/80/install.sh index 941b12c832..7a33694483 100755 --- a/plugins/php/versions/80/install.sh +++ b/plugins/php/versions/80/install.sh @@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; } -version=8.0.23 +version=8.0.24 PHP_VER=80 Install_php() { @@ -67,6 +67,29 @@ if version_lt "$libzip_version" "0.11.0" ;then ZIP_OPTION="--with-zip=$serverPath/lib/libzip" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + echo "$sourcePath/php/php${PHP_VER}" if [ ! -d $serverPath/php/${PHP_VER} ];then @@ -94,7 +117,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# } diff --git a/plugins/php/versions/81/install.sh b/plugins/php/versions/81/install.sh index 50b72ebd78..56c4237d4b 100755 --- a/plugins/php/versions/81/install.sh +++ b/plugins/php/versions/81/install.sh @@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; } -version=8.1.10 +version=8.1.11 PHP_VER=81 Install_php() { @@ -61,6 +61,28 @@ if version_lt "$libzip_version" "0.11.0" ;then ZIP_OPTION="--with-zip=$serverPath/lib/libzip" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ echo "$sourcePath/php/php${PHP_VER}" @@ -89,7 +111,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# } diff --git a/plugins/php/versions/82/install.sh b/plugins/php/versions/82/install.sh index b12362d3ee..f199b1b491 100755 --- a/plugins/php/versions/82/install.sh +++ b/plugins/php/versions/82/install.sh @@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; } -version=8.2.0RC2 +version=8.2.0RC3 PHP_VER=82 Install_php() { @@ -32,7 +32,7 @@ cd ${rootPath}/plugins/php/lib && /bin/bash zlib.sh if [ ! -d $sourcePath/php/php${PHP_VER} ];then if [ ! -f $sourcePath/php/php-${version}.tar.xz ];then - wget --no-check-certificate -O $sourcePath/php/php-${version}.tar.xz https://downloads.php.net/~sergey/php-${version}.tar.xz + wget --no-check-certificate -O $sourcePath/php/php-${version}.tar.xz https://downloads.php.net/~pierrick/php-${version}.tar.xz fi cd $sourcePath/php && tar -Jxf $sourcePath/php/php-${version}.tar.xz @@ -55,6 +55,29 @@ if [ "$IS_64BIT" == "64" ];then OPTIONS="${OPTIONS} --with-libdir=lib64" fi +# ----- cpu start ------ +if [ -z "${cpuCore}" ]; then + cpuCore="1" +fi + +if [ -f /proc/cpuinfo ];then + cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l` +fi + +MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}') +if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then + if [ "${cpuCore}" -gt "${MEM_INFO}" ];then + cpuCore="${MEM_INFO}" + fi +else + cpuCore="1" +fi + +if [ "$cpuCore" -gt "1" ];then + cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'` +fi +# ----- cpu end ------ + ZIP_OPTION='--with-zip' libzip_version=`pkg-config libzip --modversion` if version_lt "$libzip_version" "0.11.0" ;then @@ -90,7 +113,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then --disable-fileinfo \ $OPTIONS \ --enable-fpm - make clean && make && make install && make clean + make clean && make -j${cpuCore} && make install && make clean fi #------------------------ install end ------------------------------------# } diff --git a/plugins/php/versions/common/openssl.sh b/plugins/php/versions/common/openssl.sh index 7fdf987f7f..ea36ced7a0 100755 --- a/plugins/php/versions/common/openssl.sh +++ b/plugins/php/versions/common/openssl.sh @@ -46,6 +46,11 @@ Install_lib() cd ${rootPath}/plugins/php/lib && /bin/bash openssl_10.sh fi + if [ "$sysName" == "Darwin" ] ;then + LIB_DEPEND_DIR=`brew info openssl@1.1 | grep /usr/local/Cellar/openssl | cut -d \ -f 1 | awk 'END {print}'` + export PKG_CONFIG_PATH=$LIB_DEPEND_DIR/lib/pkgconfig + fi + if [ ! -f "$extFile" ];then if [ ! -d $sourcePath/php${version}/ext ];then diff --git a/plugins/php/versions/phplib.conf b/plugins/php/versions/phplib.conf index 3862c4a685..2e4d3b4ce9 100755 --- a/plugins/php/versions/phplib.conf +++ b/plugins/php/versions/phplib.conf @@ -584,6 +584,18 @@ { "name": "zip", "versions": [ + "53", + "54", + "55", + "56", + "70", + "71", + "72", + "73", + "74", + "80", + "81", + "82" ], "type": "压缩", "msg": "压缩组件", @@ -592,7 +604,20 @@ }, { "name": "zlib", - "versions": [], + "versions": [ + "53", + "54", + "55", + "56", + "70", + "71", + "72", + "73", + "74", + "80", + "81", + "82" + ], "type": "压缩", "msg": "压缩组件", "shell": "zlib.sh", diff --git a/plugins/swap/index.html b/plugins/swap/index.html index 89601d38f6..93bf2b0e4e 100755 --- a/plugins/swap/index.html +++ b/plugins/swap/index.html @@ -3,7 +3,7 @@

服务

自启动

- +

配置调整

说明

@@ -11,15 +11,9 @@
- \ No newline at end of file diff --git a/plugins/swap/index.py b/plugins/swap/index.py index ebad366016..c8cc2b8747 100755 --- a/plugins/swap/index.py +++ b/plugins/swap/index.py @@ -53,6 +53,13 @@ def getArgs(): 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 status(): data = mw.execShell("free -m|grep Swap|awk '{print $2}'") if data[0].strip() == '0': @@ -158,6 +165,35 @@ def initdUinstall(): mw.execShell('systemctl disable swap') return 'ok' + +def swapStatus(): + sfile = getServerDir() + '/swapfile' + + if os.path.exists(sfile): + size = os.path.getsize(sfile) / 1024 / 1024 + else: + size = '218' + data = {'size': size} + return mw.returnJson(True, "ok", data) + + +def changeSwap(): + args = getArgs() + data = checkArgs(args, ['size']) + if not data[0]: + return data[1] + + size = args['size'] + swapOp('stop') + os.system('dd if=/dev/zero of=' + getServerDir() + + '/swapfile bs=1M count=' + size) + + os.system('mkswap ' + getServerDir() + '/swapfile') + os.system('chmod 600 ' + getServerDir() + '/swapfile') + swapOp('start') + + return mw.returnJson(True, "修改成功!") + if __name__ == "__main__": func = sys.argv[1] if func == 'status': @@ -178,5 +214,9 @@ def initdUinstall(): print(initdUinstall()) elif func == 'conf': print(getConf()) + elif func == "swap_status": + print(swapStatus()) + elif func == "change_swap": + print(changeSwap()) else: print('error') diff --git a/plugins/swap/install.sh b/plugins/swap/install.sh index eb7bba95c6..f87c28757a 100755 --- a/plugins/swap/install.sh +++ b/plugins/swap/install.sh @@ -22,7 +22,7 @@ Install_swap() if [ "$sysName" == "Darwin" ];then pass else - dd if=/dev/zero of=$serverPath/swap/swapfile bs=1M count=2048 + dd if=/dev/zero of=$serverPath/swap/swapfile bs=1M count=1024 chmod 600 $serverPath/swap/swapfile mkswap $serverPath/swap/swapfile swapon $serverPath/swap/swapfile diff --git a/plugins/swap/js/swap.js b/plugins/swap/js/swap.js new file mode 100755 index 0000000000..a78e2db072 --- /dev/null +++ b/plugins/swap/js/swap.js @@ -0,0 +1,81 @@ + + +function swapPost(method, version, args,callback){ + var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); + + var req_data = {}; + req_data['name'] = 'swap'; + req_data['func'] = method; + req_data['version'] = version; + + if (typeof(args) == 'string'){ + req_data['args'] = JSON.stringify(toArrayObject(args)); + } else { + req_data['args'] = JSON.stringify(args); + } + + $.post('/plugins/run', req_data, function(data) { + layer.close(loadT); + if (!data.status){ + //错误展示10S + layer.msg(data.msg,{icon:0,time:2000,shade: [10, '#000']}); + return; + } + + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + + +function swapStatus() { + swapPost('swap_status', '', {}, function(data){ + var rdata = $.parseJSON(data.data); + var size = rdata.data['size']; + + var spCon = '
\ +
最大使用交换分区: \ + \ + 当前: MB\ +
\ +

修改MB

\ +
\ +
'; + + $(".soft-man-con").html(spCon); + + $(".conf_p select[name='swap_set']").change(function() { + var swap_size = $(this).val(); + if (swap_size.indexOf('GB')>-1){ + swap_size = parseInt(swap_size)*1024; + } else{ + swap_size = parseInt(swap_size); + } + $("input[name='cur_size']").val(swap_size); + $("input[name='size']").val(swap_size); + }); + }); +} + +function submitSwap(){ + var size = $("input[name='size']").val(); + swapPost('change_swap', '',{"size":size}, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + }); +} + +function readme(){ + var readme = ''; + $('.soft-man-con').html(readme); +} diff --git a/route/static/app/crontab.js b/route/static/app/crontab.js index c2d2235e90..b0c695b00e 100755 --- a/route/static/app/crontab.js +++ b/route/static/app/crontab.js @@ -54,14 +54,28 @@ function getCronData(page){ '正常' :'停用'; + + var cron_save = '--'; + if (rdata.data[i]['save'] != ''){ + cron_save = rdata.data[i]['save']+'份'; + } + + var cron_backupto = '-'; + if (rdata.data[i]['stype'] == 'site' || rdata.data[i]['stype']=='database' ){ + cron_backupto = '本地磁盘'; + if (rdata.data[i]['backup_to'] != 'localhost'){ + cron_backupto = rdata.data[i]['backup_to']; + } + } + cbody += "\ \ "+rdata.data[i].name+"\ "+status+"\ "+rdata.data[i].type+"\ "+rdata.data[i].cycle+"\ - -\ - --\ + "+cron_save +"\ + "+cron_backupto+"\ "+rdata.data[i].addtime+"\ \
执行 | \ diff --git a/route/static/app/public.js b/route/static/app/public.js index c2a1f072ee..3ff15253e8 100755 --- a/route/static/app/public.js +++ b/route/static/app/public.js @@ -1598,6 +1598,18 @@ function remove_ssh_menu() { } /*** 其中功能,针对插件通过库使用 start ***/ + +//字符串转数组对象 +function toArrayObject(str){ + var data = {}; + kv = str.split('&'); + for(i in kv){ + v = kv[i].split('='); + data[v[0]] = v[1]; + } + return data; +} + function pluginService(_name, version){ var data = {name:_name, func:'status'} if ( typeof(version) != 'undefined' ){ diff --git a/route/static/app/soft.js b/route/static/app/soft.js index 674822dc1c..826d28a03f 100755 --- a/route/static/app/soft.js +++ b/route/static/app/soft.js @@ -6,15 +6,18 @@ function resetPluginWinWidth(width){ } //软件管理窗口 -function softMain(name, version) { +function softMain(name, title, version) { + + var _title = title.replace('-'+version,'') + var loadT = layer.msg("正在处理,请稍后...", { icon: 16, time: 0, shade: [0.3, '#000'] }); $.get('/plugins/setting?name='+name, function(rdata) { layer.close(loadT); layer.open({ type: 1, area: '640px', - title: name + '-' + version + "管理", - closeBtn: 2, + title: _title + '【' + version + "】管理", + closeBtn: 1, shift: 0, content: rdata }); @@ -104,8 +107,8 @@ function getSList(isdisplay) { var mupdate = '';//(plugin.versions[n] == plugin.updates[n]) '' : '更新 | '; // if (plugin.versions[n] == '') mupdate = ''; - handle = mupdate + '设置 | 卸载'; - titleClick = 'onclick="softMain(\'' + plugin.name + '\',\'' + plugin.setup_version + '\')" style="cursor:pointer"'; + handle = mupdate + '设置 | 卸载'; + titleClick = 'onclick="softMain(\'' + plugin.name + '\',\'' + plugin.title + '\',\'' + plugin.setup_version + '\')" style="cursor:pointer"'; softPath = ''; if (plugin.coexist){ @@ -335,19 +338,11 @@ function indexListHtml(callback){ name = plugin.title + ' '; data_id = plugin.name + '-' + plugin.versions; } - - // con += '
\ - // \ - //
\ - //
\ - //
' + name + state + '
\ - //
\ - //
'; con += '
\ \ -
\ -
\ +
\ +
\
' + name + state + '
\
\
'; diff --git a/scripts/init.d/mw.tpl b/scripts/init.d/mw.tpl index 6d3092d1e1..748e227ea5 100755 --- a/scripts/init.d/mw.tpl +++ b/scripts/init.d/mw.tpl @@ -114,6 +114,7 @@ mw_stop_panel() kill -9 $p &>/dev/null done + pidfile=${mw_path}/logs/mw.pid if [ -f $pidfile ];then rm -f $pidfile fi @@ -244,4 +245,7 @@ case "$1" in echo -e "\033[33mrelease the following port (${show_panel_ip}888|80|443|22) in the security group.\033[0m" echo -e "==================================================================" ;; + *) + cd $mw_path && python3 $mw_path/tools.py cli $1 + ;; esac diff --git a/scripts/install.sh b/scripts/install.sh index 3962e1e2fa..36f454d6ea 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -83,10 +83,13 @@ fi echo "use system version: ${OSNAME}" cd /www/server/mdserver-web && bash scripts/install/${OSNAME}.sh -chmod +x /www/server/mdserver-web/mw-cli -if [ ! -e /usr/bin/mw-cli ]; then - ln -s /www/server/mdserver-web/mw-cli /usr/bin/mw-cli + +if [ ! -e /usr/bin/mw ]; then + if [ -f /etc/init.d/mw ];then + ln -s /etc/init.d/mw /usr/bin/mw + fi fi + endTime=`date +%s` ((outTime=(${endTime}-${startTime})/60)) echo -e "Time consumed:\033[32m $outTime \033[0mMinute!" diff --git a/scripts/install/debian.sh b/scripts/install/debian.sh index 33144e7bd0..368e7feeea 100644 --- a/scripts/install/debian.sh +++ b/scripts/install/debian.sh @@ -30,7 +30,7 @@ apt install -y expect apt install -y locate locale-gen en_US.UTF-8 localedef -v -c -i en_US -f UTF-8 en_US.UTF-8 -# sudo localedef -i en_US -f UTF-8 en_US.UTF-8 +sudo localedef -i en_US -f UTF-8 en_US.UTF-8 if [ ! -d /root/.acme.sh ];then curl https://get.acme.sh | sh diff --git a/scripts/install/ubuntu.sh b/scripts/install/ubuntu.sh index aa180c3257..407b229ebd 100644 --- a/scripts/install/ubuntu.sh +++ b/scripts/install/ubuntu.sh @@ -76,6 +76,7 @@ apt install -y patchelf VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` if [ "${VERSION_ID}" == "22.04" ];then + apt install -y python3-cffi pip3 install -U --force-reinstall --no-binary :all: gevent fi @@ -87,6 +88,7 @@ else fi if [ "${VERSION_ID}" == "22.04" ];then + apt install -y python3-cffi pip3 install -U --force-reinstall --no-binary :all: gevent fi diff --git a/scripts/install_dev.sh b/scripts/install_dev.sh index 4f1a8f4986..919435e1fa 100755 --- a/scripts/install_dev.sh +++ b/scripts/install_dev.sh @@ -71,15 +71,12 @@ if [ $OSNAME != "macos" ];then fi echo "use system version: ${OSNAME}" - - -# cd /www/server/mdserver-web && bash ./scripts/install/debian.sh cd /www/server/mdserver-web && bash scripts/install/${OSNAME}.sh -# curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/install/${OSNAME}.sh | bash -chmod +x /www/server/mdserver-web/mw-cli -if [ ! -e /usr/bin/mw-cli ]; then - ln -s /www/server/mdserver-web/mw-cli /usr/bin/mw-cli +if [ ! -e /usr/bin/mw ]; then + if [ -f /etc/init.d/mw ];then + ln -s /etc/init.d/mw /usr/bin/mw + fi fi endTime=`date +%s` diff --git a/scripts/update.sh b/scripts/update.sh index cd10fd0953..72010bc789 100755 --- a/scripts/update.sh +++ b/scripts/update.sh @@ -67,6 +67,12 @@ rm -rf /tmp/mdserver-web-master echo "use system version: ${OSNAME}" cd /www/server/mdserver-web && bash scripts/update/${OSNAME}.sh +if [ ! -e /usr/bin/mw ]; then + if [ ! -f /usr/bin/mw ];then + ln -s /etc/init.d/mw /usr/bin/mw + fi +fi + endTime=`date +%s` ((outTime=($endTime-$startTime)/60)) echo -e "Time consumed:\033[32m $outTime \033[0mMinute!" \ No newline at end of file diff --git a/scripts/update_dev.sh b/scripts/update_dev.sh index 82219145f4..df4f21c109 100755 --- a/scripts/update_dev.sh +++ b/scripts/update_dev.sh @@ -65,9 +65,13 @@ rm -rf /tmp/mdserver-web-dev #pip uninstall public echo "use system version: ${OSNAME}" -# cd /www/server/mdserver-web && bash ./scripts/install/debian.sh cd /www/server/mdserver-web && bash scripts/update/${OSNAME}.sh -# curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/update/${OSNAME}.sh | bash + +if [ ! -e /usr/bin/mw ]; then + if [ ! -f /usr/bin/mw ];then + ln -s /etc/init.d/mw /usr/bin/mw + fi +fi endTime=`date +%s` ((outTime=($endTime-$startTime)/60)) diff --git a/tools.py b/tools.py index bf4e22dd8a..79760d6948 100755 --- a/tools.py +++ b/tools.py @@ -14,6 +14,68 @@ # p = "/usr/local/lib/" + info[0].strip() + "/site-packages" # sys.path.append(p) +INIT_DIR = "/etc/init.d" +if mw.isAppleSystem(): + INIT_DIR = mw.getRunDir() + "/scripts/init.d" + +INIT_CMD = INIT_DIR + "/mw" + + +def mwcli(mw_input=0): + raw_tip = "======================================================" + if not mw_input: + print("===============mdserver-web cli tools=================") + print("(1) 重启面板服务") + print("(2) 停止面板服务") + print("(3) 启动面板服务") + print("(4) 重载面板服务") + print("(10) 查看面板默认信息") + print("(11) 修改面板密码") + print("(12) 修改面板用户名") + print("(13) 显示面板错误日志") + print("(0) 取消") + print(raw_tip) + try: + mw_input = input("请输入命令编号:") + if sys.version_info[0] == 3: + mw_input = int(mw_input) + except: + mw_input = 0 + + nums = [1, 2, 3, 4, 10, 11, 12, 13] + if not mw_input in nums: + print(raw_tip) + print("已取消!") + exit() + + if mw_input == 1: + os.system(INIT_CMD + " restart") + elif mw_input == 2: + os.system(INIT_CMD + " stop") + elif mw_input == 3: + os.system(INIT_CMD + " start") + elif mw_input == 4: + os.system(INIT_CMD + " reload") + elif mw_input == 10: + os.system(INIT_CMD + " default") + elif mw_input == 11: + if sys.version_info[0] == 2: + input_pwd = raw_input("请输入新的面板密码:") + else: + input_pwd = input("请输入新的面板密码:") + if len(input_pwd.strip()) < 5: + print("|-错误,密码长度不能小于5位") + return + set_panel_pwd(input_pwd.strip(), True) + elif mw_input == 12: + if sys.version_info[0] == 2: + input_user = raw_input("请输入新的面板用户名(>3位):") + else: + input_user = input("请输入新的面板用户名(>3位):") + set_panel_username(input_user.strip()) + elif mw_input == 13: + os.system('tail -100 ' + mw.getRunDir() + '/logs/error.log') + def set_panel_pwd(password, ncli=False): # 设置面板密码 @@ -60,15 +122,23 @@ def getServerIp(): if __name__ == "__main__": - type = sys.argv[1] - if type == 'panel': + method = sys.argv[1] + if method == 'panel': set_panel_pwd(sys.argv[2]) - elif type == 'username': + elif method == 'username': if len(sys.argv) > 2: set_panel_username(sys.argv[2]) else: set_panel_username() - elif type == 'getServerIp': + elif method == 'getServerIp': getServerIp() + elif method == "cli": + clinum = 0 + try: + if len(sys.argv) > 2: + clinum = int(sys.argv[2]) if sys.argv[2][:6] else sys.argv[2] + except: + clinum = sys.argv[2] + mwcli(clinum) else: print('ERROR: Parameter error')