diff --git a/.gitignore b/.gitignore index 0b3bf380e..777de65c3 100644 --- a/.gitignore +++ b/.gitignore @@ -122,6 +122,7 @@ data/datadir.pl data/502Task.pl data/default.pl data/backup.pl +data/default_site.pl lib/python* bin @@ -144,3 +145,4 @@ plugins/gdrive plugins/mtproxy debug.out + diff --git a/class/core/config_api.py b/class/core/config_api.py index 3f9d4ed36..af2938df8 100755 --- a/class/core/config_api.py +++ b/class/core/config_api.py @@ -17,7 +17,7 @@ class config_api: # 进行中. # 兼容主流Linux系统 - __version = '0.8.6.6' + __version = '0.8.6.7' def __init__(self): pass diff --git a/class/core/mw.py b/class/core/mw.py index a760e5458..4f706e9e9 100755 --- a/class/core/mw.py +++ b/class/core/mw.py @@ -516,8 +516,9 @@ def getLastLine(inputfile, lineNum): result += lastre[num] + "\n" num -= 1 return result - except: - return getMsg('TASK_SLEEP') + except Exception as e: + return str(e) + # return getMsg('TASK_SLEEP') def getNumLines(path, num, p=1): @@ -1003,3 +1004,13 @@ def requestFcgiPHP(sock, uri, document_root='/tmp', method='GET', pdata=b''): pdata = url_encode(pdata) result = p.load_url_public(uri, pdata, method) return result + + +def getMyORM(): + ''' + 获取MySQL资源的ORM + ''' + sys.path.append(os.getcwd() + "/class/plugin") + import orm + o = orm.ORM() + return o diff --git a/class/core/plugins_api.py b/class/core/plugins_api.py index 04c0180ba..d989ff5ff 100755 --- a/class/core/plugins_api.py +++ b/class/core/plugins_api.py @@ -290,7 +290,7 @@ class plugins_api: except: mw.execShell("rm -rf " + tmp_path) return mw.returnJson(False, '在压缩包中没有找到插件信息,请检查插件包!') - protectPlist = ('openresty', 'mysql', 'php', 'redis', + protectPlist = ('openresty', 'mysql', 'php', 'redis', 'memcached' 'mongodb', 'swap', 'gogs', 'pureftp') if data['name'] in protectPlist: return mw.returnJson(False, '[' + data['name'] + '],重要插件不可修改!') diff --git a/class/core/task_api.py b/class/core/task_api.py index 53b8023a1..83742f3c6 100755 --- a/class/core/task_api.py +++ b/class/core/task_api.py @@ -61,8 +61,7 @@ class task_api: if not len(find): return mw.returnJson(False, '当前没有任务队列在执行-2!') - isTask = os.getcwd() + '/tmp/panelTask.pl' - mw.writeFile(isTask, 'True') + mw.triggerTask() echoMsg = {} echoMsg['name'] = find['name'] diff --git a/class/plugin/orm.py b/class/plugin/orm.py new file mode 100755 index 000000000..b38e8683a --- /dev/null +++ b/class/plugin/orm.py @@ -0,0 +1,92 @@ +# coding: utf-8 + +import re +import os +import sys + +from mysql import connector + + +class ORM: + __DB_PASS = None + __DB_USER = 'root' + __DB_PORT = 3306 + __DB_HOST = 'localhost' + __DB_CONN = None + __DB_CUR = None + __DB_ERR = None + __DB_CNF = '/etc/my.cnf' + __DB_SOCKET = '/www/server/mysql/mysql.sock' + + def __Conn(self): + '''连接MYSQL数据库''' + try: + + if os.path.exists(self.__DB_SOCKET): + try: + self.__DB_CONN = connector.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, + port=self.__DB_PORT, charset="utf8", connect_timeout=1, unix_socket=self.__DB_SOCKET) + except Exception as e: + self.__DB_HOST = '127.0.0.1' + self.__DB_CONN = connector.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, + port=self.__DB_PORT, charset="utf8", connect_timeout=1, unix_socket=self.__DB_SOCKET) + else: + try: + self.__DB_CONN = connector.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, + port=self.__DB_PORT, charset="utf8", connect_timeout=1) + except Exception as e: + self.__DB_HOST = '127.0.0.1' + self.__DB_CONN = connector.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, + port=self.__DB_PORT, charset="utf8", connect_timeout=1) + + self.__DB_CUR = self.__DB_CONN.cursor() + return True + except Exception as e: + self.__DB_ERR = e + return False + + def setDbConf(self, conf): + self.__DB_CNF = conf + + def setSocket(self, sock): + self.__DB_SOCKET = sock + + def setPort(self, port): + self.__DB_PORT = port + + def setPwd(self, pwd): + self.__DB_PASS = pwd + + def getPwd(self): + return self.__DB_PASS + + def execute(self, sql): + # 执行SQL语句返回受影响行 + if not self.__Conn(): + return self.__DB_ERR + try: + result = self.__DB_CUR.execute(sql) + self.__DB_CONN.commit() + self.__Close() + return result + except Exception as ex: + return ex + + def query(self, sql): + # 执行SQL语句返回数据集 + if not self.__Conn(): + return self.__DB_ERR + try: + self.__DB_CUR.execute(sql) + result = self.__DB_CUR.fetchall() + # 将元组转换成列表 + # data = list(map(list, result)) + self.__Close() + return result + except Exception as ex: + return ex + + def __Close(self): + # 关闭连接 + self.__DB_CUR.close() + self.__DB_CONN.close() diff --git a/compatibility.md b/compatibility.md index 16a3ab446..7f18c493e 100644 --- a/compatibility.md +++ b/compatibility.md @@ -42,8 +42,8 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh | Ubuntu 20.04 |:x: |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ | | Ubuntu 22.04 |:x: |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ | | Fedora 31 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ | -| Fedora 32 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ | -| AlmaLinix 9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ | +| Fedora 32 |:x: |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ | +| AlmaLinix 9 |:x: |✅ |✅ |:x: |:x: |:x: |:x: |:x: |✅ |:x: |:x: |:x: | | RockyLinux 8.6 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ | | openSUSE 15.4 |:x: |:x: |:x: |:x: |:x: |:x: |:x: |:x: |:x: |:x: |:x: |:x: | @@ -57,12 +57,12 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh | CentOS 9 Stream |✅ |:x: |:x: |:x: | | Debian 10.3 |✅ |✅ |✅ |:x: | | Debian 11.3 |✅ |✅ |✅ |✅ | -| Ubuntu 18.04 |✅ |✅ |✅ |✅ | -| Ubuntu 20.04 |✅ |✅ |✅ |✅ | +| Ubuntu 18.04 |✅ |✅ |✅ |:x: | +| Ubuntu 20.04 |✅ |✅ |✅ |:x: | | Ubuntu 22.04 |✅ |✅ |✅ |✅ | | Fedora 31 |✅ |✅ |✅ |✅ | | Fedora 32 |✅ |✅ |✅ |✅ | -| AlmaLinix 9 |✅ |✅ |✅ |✅ | +| AlmaLinix 9 |✅ |:x: |:x: |:x: | | RockyLinux 8.6 |✅ |✅ |✅ |✅ | | openSUSE 15.4 |:x: |:x: |:x: |:x: | diff --git a/plugins/gogs/index.py b/plugins/gogs/index.py index c5ee31848..76b8edb3a 100755 --- a/plugins/gogs/index.py +++ b/plugins/gogs/index.py @@ -216,8 +216,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) @@ -383,6 +386,10 @@ def postReceiveLog(): def getGogsConf(): + conf = getConf() + if not os.path.exists(conf): + return mw.returnJson(False, "请先安装初始化!") + gets = [ {'name': 'DOMAIN', 'type': -1, 'ps': '服务器域名'}, {'name': 'ROOT_URL', 'type': -1, 'ps': '公开的完整URL路径'}, @@ -403,7 +410,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: @@ -413,7 +420,7 @@ def getGogsConf(): continue g['value'] = tmp.groups()[0] result.append(g) - return mw.getJson(result) + return mw.returnJson(True, 'OK', result) def submitGogsConf(): @@ -445,6 +452,11 @@ def submitGogsConf(): def userList(): + + conf = getConf() + if not os.path.exists(conf): + return mw.returnJson(False, "请先安装初始化!") + import math args = getArgs() @@ -607,11 +619,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' @@ -628,11 +638,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 + \ diff --git a/plugins/gogs/js/gogs.js b/plugins/gogs/js/gogs.js index 0792201c0..e6318cc8c 100755 --- a/plugins/gogs/js/gogs.js +++ b/plugins/gogs/js/gogs.js @@ -39,9 +39,12 @@ function gogsPost(method,args,callback, title){ function gogsSetConfig(){ gogsPost('get_gogs_conf', '', function(data){ - // console.log(data); - var rdata = $.parseJSON(data.data); - // console.log(rdata); + 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'; @@ -141,7 +144,10 @@ function gogsUserList(page, search) { gogsPost('user_list', _data, function(data){ var rdata = $.parseJSON(data.data); - // console.log(rdata); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } content = '
'; content += '
'; diff --git a/plugins/mariadb/conf/mariadb.sql b/plugins/mariadb/conf/mariadb.sql new file mode 100755 index 000000000..38b822738 --- /dev/null +++ b/plugins/mariadb/conf/mariadb.sql @@ -0,0 +1,28 @@ +CREATE TABLE IF NOT EXISTS `config` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `mysql_root` TEXT +); + +INSERT INTO `config` (`id`, `mysql_root`) VALUES (1, 'admin'); + +CREATE TABLE IF NOT EXISTS `databases` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `pid` INTEGER, + `name` TEXT, + `username` TEXT, + `password` TEXT, + `accept` TEXT, + `ps` TEXT, + `addtime` TEXT +); + +CREATE TABLE IF NOT EXISTS `master_replication_user` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `username` TEXT, + `password` TEXT, + `accept` TEXT, + `ps` TEXT, + `addtime` TEXT +); + + diff --git a/plugins/mariadb/conf/my.cnf b/plugins/mariadb/conf/my.cnf new file mode 100644 index 000000000..4fd989170 --- /dev/null +++ b/plugins/mariadb/conf/my.cnf @@ -0,0 +1,98 @@ +[client] +user = root +#password = your_password +port = 33106 +socket = {$SERVER_APP_PATH}/mysql.sock + +[mysqld] +pid-file = {$SERVER_APP_PATH}/data/mysql.pid +user = mysql +port = 33106 +socket = {$SERVER_APP_PATH}/mysql.sock +basedir = {$SERVER_APP_PATH} +datadir = {$SERVER_APP_PATH}/data +log-error = {$SERVER_APP_PATH}/data/error.log +default_storage_engine = MyISAM +key_buffer_size = 8M +max_allowed_packet = 100M +table_open_cache = 32 +sort_buffer_size = 256K +net_buffer_length = 4K +read_buffer_size = 128K +read_rnd_buffer_size = 256K +myisam_sort_buffer_size = 4M +thread_cache_size = 4 +lower_case_table_names=1 +query_cache_size = 4M +tmp_table_size = 8M + +max_connections = 500 +max_connect_errors = 100 +open_files_limit = 65535 + +#skip-networking +#skip-name-resolve +#skip-external-locking +#loose-skip-innodb +#skip-grant-tables + + +log-bin=mysql-bin +binlog_format=mixed +server-id = 1 +expire_logs_days = 10 +slow_query_log=1 +slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log +long_query_time=3 +#log_queries_not_using_indexes=on + +relay-log=mdserver +relay-log-index=mdserver + +#master +#binlog-do-db +binlog-ignore-db = test +binlog-ignore-db = mysql +binlog-ignore-db = information_schema +binlog-ignore-db = performance_schema + +#slave +log-slave-updates +#replicate-do-db +replicate-ignore-db = information_schema +replicate-ignore-db = performance_schema +replicate-ignore-db = mysql +replicate-ignore-db = test + +default_storage_engine = InnoDB +innodb_data_home_dir = {$SERVER_APP_PATH}/data +innodb_data_file_path = ibdata1:10M:autoextend +innodb_log_group_home_dir = {$SERVER_APP_PATH}/data +innodb_buffer_pool_size = 16M +innodb_log_file_size = 5M +innodb_log_buffer_size = 8M +innodb_flush_log_at_trx_commit = 1 +innodb_lock_wait_timeout = 120 +innodb_max_dirty_pages_pct = 90 +innodb_read_io_threads = 1 +innodb_write_io_threads = 1 +innodb_file_per_table=1 + + +secure-file-priv={$SERVER_APP_PATH}/tmp + +[mysqldump] +quick +max_allowed_packet = 16M + +[mysql] +no-auto-rehash + +[myisamchk] +key_buffer_size = 20M +sort_buffer_size = 20M +read_buffer = 2M +write_buffer = 2M + +[mysqlhotcopy] +interactive-timeout \ No newline at end of file diff --git a/plugins/mariadb/ico.png b/plugins/mariadb/ico.png new file mode 100644 index 000000000..8a9f3b314 Binary files /dev/null and b/plugins/mariadb/ico.png differ diff --git a/plugins/mariadb/index.html b/plugins/mariadb/index.html new file mode 100755 index 000000000..80a73bb58 --- /dev/null +++ b/plugins/mariadb/index.html @@ -0,0 +1,60 @@ +
+
+
+
+ +

服务

+

自启动

+

配置文件

+

存储位置

+

端口

+

当前状态

+

性能优化

+

日志

+

慢日志

+

管理列表

+
+
+
+
+
+ +
+ + + + \ No newline at end of file diff --git a/plugins/mariadb/index.py b/plugins/mariadb/index.py new file mode 100755 index 000000000..0cdf6c9a7 --- /dev/null +++ b/plugins/mariadb/index.py @@ -0,0 +1,1344 @@ +# 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 'mariadb' + + +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 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 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/mariadb' + version + '.tpl' + if not os.path.exists(path): + path = getPluginDir() + '/init.d/mariadb.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 + '/mariadb') + return content + + +def pSqliteDb(dbname='databases'): + file = getServerDir() + '/mariadb.db' + name = 'mysql' + if not os.path.exists(file): + conn = mw.M(dbname).dbPos(getServerDir(), name) + csql = mw.readFile(getPluginDir() + '/conf/mariadb.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 = mw.getMyORM() + + db.setDbConf(getConf()) + + db.setPort(getDbPort()) + db.setSocket(getSocketFile()) + + pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root') + db.setPwd(pwd) + return db + + +def initDreplace(version=''): + initd_tpl = getInitdTpl(version) + + 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.cnf' + content = mw.readFile(mysql_conf_tpl) + content = contentReplace(content) + mw.writeFile(mysql_conf, content) + + 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_tmp = getServerDir() + '/tmp' + if not os.path.exists(mysql_tmp): + os.mkdir(mysql_tmp) + mw.execShell("chown -R mysql:mysql " + mysql_tmp) + + # systemd + systemDir = mw.systemdCfgDir() + systemService = systemDir + '/mariadb.service' + systemServiceTpl = getPluginDir() + '/init.d/mariadb.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=''): + try: + pid = getPidFile() + if os.path.exists(pid): + return 'start' + except Exception as e: + return 'stop' + return 'stop' + + +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() + myconf = serverdir + "/etc/my.cnf" + user = pGetDbUser() + cmd = 'cd ' + serverdir + ' && ./scripts/mariadb-install-db ' + \ + ' --defaults-file=' + myconf + 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/mysql -S ' + serverdir + '/mysql.sock -uroot -e' + cmd_pass = cmd_pass + \ + "\"grant all privileges on *.* to 'root'@'localhost' identified by '" + pwd + "';" + cmd_pass = cmd_pass + "flush privileges;\"" + + data = mw.execShell(cmd_pass) + if data[1].find("ERROR"): + print("init mariadb db fail") + exit(1) + + # print(data) + 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 mariadb') + initMysqlPwd() + mw.execShell('systemctl stop mariadb') + + mw.execShell('systemctl ' + method + ' mariadb') + return 'ok' + except Exception as e: + return str(e) + + +def appCMD(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 mariadb | 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 mariadb') + return 'ok' + + +def initdUinstall(): + if mw.isAppleSystem(): + return "Apple Computer does not support" + + mw.execShell('systemctl disable mariadb') + 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) + + 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, 'mariadb 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(data): + # 检测数据库执行错误 + errMsg = str(data) + if "2002" in errMsg: + return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') + if "2003" in errMsg: + return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)") + if "1698" in errMsg: + return mw.returnJson(False, "Access denied for user 'root'@'localhost'") + if "1045" in errMsg: + return mw.returnJson(False, "Access denied for user 'root'@'localhost' (using password: YES)") + if "using password:" in errMsg: + return mw.returnJson(False, '数据库管理密码错误!') + if "Connection refused" in errMsg: + return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!') + if "1133" in errMsg: + return mw.returnJson(False, '数据库用户不存在!') + if "1007" in errMsg: + 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 = getPluginDir() + '/scripts/backup.py' + + cmd = 'python3 ' + 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/mariadb/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 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 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' + + +def uninstallPreInspection(version): + # return "请手动删除MySQL[{}]".format(version) + return 'ok' + +if __name__ == "__main__": + func = sys.argv[1] + + version = "10.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 == '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 == '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()) + else: + print('error') diff --git a/plugins/mariadb/info.json b/plugins/mariadb/info.json new file mode 100755 index 000000000..e0b2692c7 --- /dev/null +++ b/plugins/mariadb/info.json @@ -0,0 +1,18 @@ +{ + "title":"MariaDB", + "tip":"soft", + "name":"mariadb", + "type":"运行环境", + "ps":"一种关系数据库管理系统!", + "uninstall_pre_inspection":true, + "checks": "server/mariadb", + "path": "server/mariadb", + "versions":["10.6","10.7","10.8"], + "shell":"install.sh", + "checks":"server/mariadb", + "path":"server/mariadb", + "author":"mariadb", + "home":"https://mariadb.org/", + "date":"2022-07-12", + "pid": "2" +} \ No newline at end of file diff --git a/plugins/mariadb/init.d/mariadb.service.tpl b/plugins/mariadb/init.d/mariadb.service.tpl new file mode 100644 index 000000000..c27e9596c --- /dev/null +++ b/plugins/mariadb/init.d/mariadb.service.tpl @@ -0,0 +1,22 @@ +[Unit] +Description=MariaDB Server: The open source relational database +Documentation=https://mariadb.org/download/?t=mariadb +After=network.service +After=syslog.target + +[Service] +User=mysql +Group=mysql +Type=simple +ExecStart={$SERVER_PATH}/mariadb/bin/mysqld --defaults-file={$SERVER_PATH}/mariadb/etc/my.cnf +ExecReload=/bin/kill -USR2 $MAINPID +PermissionsStartOnly=true +LimitNOFILE=5000 +Restart=on-failure +RestartSec=10 +RestartPreventExitStatus=1 +PrivateTmp=false + + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/plugins/mariadb/init.d/mariadb.tpl b/plugins/mariadb/init.d/mariadb.tpl new file mode 100755 index 000000000..c14f5ad3a --- /dev/null +++ b/plugins/mariadb/init.d/mariadb.tpl @@ -0,0 +1,376 @@ +#!/bin/sh +# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB +# This file is public domain and comes with NO WARRANTY of any kind + +# MySQL daemon start/stop script. + +# Usually this is put in /etc/init.d (at least on machines SYSV R4 based +# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql. +# When this is done the mysql server will be started when the machine is +# started and shut down when the systems goes down. + +# Comments to support chkconfig on RedHat Linux +# chkconfig: 2345 64 36 +# description: A very fast and reliable SQL database engine. + +# Comments to support LSB init script conventions +### BEGIN INIT INFO +# Provides: mysql +# Required-Start: $local_fs $network $remote_fs +# Should-Start: ypbind nscd ldap ntpd xntpd +# Required-Stop: $local_fs $network $remote_fs +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: start and stop MySQL +# Description: MySQL is a very fast and reliable SQL database engine. +### END INIT INFO + +# If you install MySQL on some other places than /Users/midoks/Desktop/fwww/server/mysql, then you +# have to do one of the following things for this script to work: +# +# - Run this script from within the MySQL installation directory +# - Create a /etc/my.cnf file with the following information: +# [mysqld] +# basedir= +# - Add the above to any other configuration file (for example ~/.my.ini) +# and copy my_print_defaults to /usr/bin +# - Add the path to the mysql-installation-directory to the basedir variable +# below. +# +# If you want to affect other MySQL variables, you should make your changes +# in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files. + +# If you change base dir, you must also change datadir. These may get +# overwritten by settings in the MySQL configuration files. + +basedir= +datadir= + +# Default value, in seconds, afterwhich the script should timeout waiting +# for server start. +# Value here is overriden by value in my.cnf. +# 0 means don't wait at all +# Negative numbers mean to wait indefinitely +service_startup_timeout=900 + +# Lock directory for RedHat / SuSE. +lockdir='/var/lock/subsys' +lock_file_path="$lockdir/mysql" + +# The following variables are only set for letting mysql.server find things. + +# Set some defaults +mysqld_pid_file_path= +if test -z "$basedir" +then + basedir={$SERVER_APP_PATH} + bindir={$SERVER_APP_PATH}/bin + if test -z "$datadir" + then + datadir={$SERVER_APP_PATH}/data + fi + sbindir={$SERVER_APP_PATH}/bin + libexecdir={$SERVER_APP_PATH}/bin +else + bindir="$basedir/bin" + if test -z "$datadir" + then + datadir="$basedir/data" + fi + sbindir="$basedir/sbin" + libexecdir="$basedir/libexec" +fi + +# datadir_set is used to determine if datadir was set (and so should be +# *not* set inside of the --basedir= handler.) +datadir_set= + +# +# Use LSB init script functions for printing messages, if possible +# +lsb_functions="/lib/lsb/init-functions" +if test -f $lsb_functions ; then + . $lsb_functions +else + log_success_msg() + { + echo " SUCCESS! $@" + } + log_failure_msg() + { + echo " ERROR! $@" + } +fi + +PATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin" +export PATH + +mode=$1 # start or stop + +[ $# -ge 1 ] && shift + + +other_args="$*" # uncommon, but needed when called from an RPM upgrade action + # Expected: "--skip-networking --skip-grant-tables" + # They are not checked here, intentionally, as it is the resposibility + # of the "spec" file author to give correct arguments only. + +case `echo "testing\c"`,`echo -n testing` in + *c*,-n*) echo_n= echo_c= ;; + *c*,*) echo_n=-n echo_c= ;; + *) echo_n= echo_c='\c' ;; +esac + +parse_server_arguments() { + for arg do + case "$arg" in + --basedir=*) basedir=`echo "$arg" | sed -e 's/^[^=]*=//'` + bindir="$basedir/bin" + if test -z "$datadir_set"; then + datadir="$basedir/data" + fi + sbindir="$basedir/sbin" + libexecdir="$basedir/libexec" + ;; + --datadir=*) datadir=`echo "$arg" | sed -e 's/^[^=]*=//'` + datadir_set=1 + ;; + --pid-file=*) mysqld_pid_file_path=`echo "$arg" | sed -e 's/^[^=]*=//'` ;; + --service-startup-timeout=*) service_startup_timeout=`echo "$arg" | sed -e 's/^[^=]*=//'` ;; + esac + done +} + +wait_for_pid () { + verb="$1" # created | removed + pid="$2" # process ID of the program operating on the pid-file + pid_file_path="$3" # path to the PID file. + + i=0 + avoid_race_condition="by checking again" + + while test $i -ne $service_startup_timeout ; do + + case "$verb" in + 'created') + # wait for a PID-file to pop into existence. + test -s "$pid_file_path" && i='' && break + ;; + 'removed') + # wait for this PID-file to disappear + test ! -s "$pid_file_path" && i='' && break + ;; + *) + echo "wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path" + exit 1 + ;; + esac + + # if server isn't running, then pid-file will never be updated + if test -n "$pid"; then + if kill -0 "$pid" 2>/dev/null; then + : # the server still runs + else + # The server may have exited between the last pid-file check and now. + if test -n "$avoid_race_condition"; then + avoid_race_condition="" + continue # Check again. + fi + + # there's nothing that will affect the file. + log_failure_msg "The server quit without updating PID file ($pid_file_path)." + return 1 # not waiting any more. + fi + fi + + echo $echo_n ".$echo_c" + i=`expr $i + 1` + sleep 1 + + done + + if test -z "$i" ; then + log_success_msg + return 0 + else + log_failure_msg + return 1 + fi +} + +# Get arguments from the my.cnf file, +# the only group, which is read from now on is [mysqld] +if test -x "$bindir/my_print_defaults"; then + print_defaults="$bindir/my_print_defaults" +else + # Try to find basedir in /etc/my.cnf + conf=/etc/my.cnf + print_defaults= + if test -r $conf + then + subpat='^[^=]*basedir[^=]*=\(.*\)$' + dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf` + for d in $dirs + do + d=`echo $d | sed -e 's/[ ]//g'` + if test -x "$d/bin/my_print_defaults" + then + print_defaults="$d/bin/my_print_defaults" + break + fi + done + fi + + # Hope it's in the PATH ... but I doubt it + test -z "$print_defaults" && print_defaults="my_print_defaults" +fi + +# +# Read defaults file from 'basedir'. If there is no defaults file there +# check if it's in the old (depricated) place (datadir) and read it from there +# + +extra_args="" +if test -r "$basedir/my.cnf" +then + extra_args="-e $basedir/my.cnf" +fi + +parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server` + +# +# Set pid file if not given +# +if test -z "$mysqld_pid_file_path" +then + mysqld_pid_file_path=$datadir/`hostname`.pid +else + case "$mysqld_pid_file_path" in + /* ) ;; + * ) mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;; + esac +fi + +case "$mode" in + 'start') + # Start daemon + + # Safeguard (relative paths, core dumps..) + cd $basedir + + echo $echo_n "Starting MySQL" + if test -x $bindir/mysqld_safe + then + # Give extra arguments to mysqld with the my.cnf file. This script + # may be overwritten at next upgrade. + $bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null & + wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$? + + # Make lock for RedHat / SuSE + if test -w "$lockdir" + then + touch "$lock_file_path" + fi + + exit $return_value + else + log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)" + fi + ;; + + 'stop') + # Stop daemon. We use a signal here to avoid having to know the + # root password. + + if test -s "$mysqld_pid_file_path" + then + # signal mysqld_safe that it needs to stop + touch "$mysqld_pid_file_path.shutdown" + + mysqld_pid=`cat "$mysqld_pid_file_path"` + + if (kill -0 $mysqld_pid 2>/dev/null) + then + echo $echo_n "Shutting down MySQL" + kill $mysqld_pid + # mysqld should remove the pid file when it exits, so wait for it. + wait_for_pid removed "$mysqld_pid" "$mysqld_pid_file_path"; return_value=$? + else + log_failure_msg "MySQL server process #$mysqld_pid is not running!" + rm "$mysqld_pid_file_path" + fi + + # Delete lock for RedHat / SuSE + if test -f "$lock_file_path" + then + rm -f "$lock_file_path" + fi + exit $return_value + else + log_failure_msg "MySQL server PID file could not be found!" + fi + ;; + + 'restart') + # Stop the service and regardless of whether it was + # running or not, start it again. + if $0 stop $other_args; then + $0 start $other_args + else + log_failure_msg "Failed to stop running server, so refusing to try to start." + exit 1 + fi + ;; + + 'reload'|'force-reload') + if test -s "$mysqld_pid_file_path" ; then + read mysqld_pid < "$mysqld_pid_file_path" + kill -HUP $mysqld_pid && log_success_msg "Reloading service MySQL" + touch "$mysqld_pid_file_path" + else + log_failure_msg "MySQL PID file could not be found!" + exit 1 + fi + ;; + 'status') + # First, check to see if pid file exists + if test -s "$mysqld_pid_file_path" ; then + read mysqld_pid < "$mysqld_pid_file_path" + if kill -0 $mysqld_pid 2>/dev/null ; then + log_success_msg "MySQL running ($mysqld_pid)" + exit 0 + else + log_failure_msg "MySQL is not running, but PID file exists" + exit 1 + fi + else + # Try to find appropriate mysqld process + mysqld_pid=`pgrep -d' ' -f $libexecdir/mysqld` + + # test if multiple pids exist + pid_count=`echo $mysqld_pid | wc -w` + if test $pid_count -gt 1 ; then + log_failure_msg "Multiple MySQL running but PID file could not be found ($mysqld_pid)" + exit 5 + elif test -z $mysqld_pid ; then + if test -f "$lock_file_path" ; then + log_failure_msg "MySQL is not running, but lock file ($lock_file_path) exists" + exit 2 + fi + log_failure_msg "MySQL is not running" + exit 3 + else + log_failure_msg "MySQL is running but PID file could not be found" + exit 4 + fi + fi + ;; + *) + # usage + basename=`basename "$0"` + echo "Usage: $basename {start|stop|restart|reload|force-reload|status} [ MySQL server options ]" + exit 1 + ;; +esac + +exit 0 diff --git a/plugins/mariadb/install.sh b/plugins/mariadb/install.sh new file mode 100755 index 000000000..def4d2865 --- /dev/null +++ b/plugins/mariadb/install.sh @@ -0,0 +1,44 @@ +#!/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 + + +action=$1 +type=$2 + +if [ "${2}" == "" ];then + echo '缺少安装脚本...' > $install_tmp + exit 0 +fi + +if [ ! -d $curPath/versions/$2 ];then + echo '缺少安装脚本2...' > $install_tmp + exit 0 +fi + +if [ "${action}" == "uninstall" ];then + + if [ -f /usr/lib/systemd/system/mariadb.service ] || [ -f /lib/systemd/system/mariadb.service ];then + systemctl stop mariadb + systemctl disable mariadb + rm -rf /usr/lib/systemd/system/mariadb.service + rm -rf /lib/systemd/system/mariadb.service + systemctl daemon-reload + fi +fi + +sh -x $curPath/versions/$2/install.sh $1 + +if [ "${action}" == "install" ] && [ -d $serverPath/mariadb ];then + #初始化 + cd ${rootPath} && python3 ${rootPath}/plugins/mariadb/index.py start ${type} + cd ${rootPath} && python3 ${rootPath}/plugins/mariadb/index.py initd_install ${type} +fi diff --git a/plugins/mariadb/js/mariadb.js b/plugins/mariadb/js/mariadb.js new file mode 100755 index 000000000..6873ffe08 --- /dev/null +++ b/plugins/mariadb/js/mariadb.js @@ -0,0 +1,1221 @@ +function str2Obj(str){ + var data = {}; + kv = str.split('&'); + for(i in kv){ + v = kv[i].split('='); + data[v[0]] = v[1]; + } + return data; +} + +function myPost(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:'mariadb', func:method, args:_args}, function(data) { + layer.close(loadT); + if (!data.status){ + layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function myPostN(method,args,callback, title){ + + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(str2Obj(args)); + } else { + _args = JSON.stringify(args); + } + + var _title = '正在获取...'; + if (typeof(title) != 'undefined'){ + _title = title; + } + $.post('/plugins/run', {name:'mariadb', func:method, args:_args}, function(data) { + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function myAsyncPost(method,args){ + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(str2Obj(args)); + } else { + _args = JSON.stringify(args); + } + + var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); + return syncPost('/plugins/run', {name:'mariadb', func:method, args:_args}); +} + +function runInfo(){ + myPost('run_info','',function(data){ + + var rdata = $.parseJSON(data.data); + if (typeof(rdata['status']) != 'undefined'){ + layer.msg(rdata['msg'],{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + var cache_size = ((parseInt(rdata.Qcache_hits) / (parseInt(rdata.Qcache_hits) + parseInt(rdata.Qcache_inserts))) * 100).toFixed(2) + '%'; + if (cache_size == 'NaN%') cache_size = 'OFF'; + var Con = '
\ + \ + \ + \ + \ + \ + \ +
启动时间' + getLocalTime(rdata.Run) + '每秒查询' + parseInt(rdata.Questions / rdata.Uptime) + '
总连接次数' + rdata.Connections + '每秒事务' + parseInt((parseInt(rdata.Com_commit) + parseInt(rdata.Com_rollback)) / rdata.Uptime) + '
发送' + toSize(rdata.Bytes_sent) + 'File' + rdata.File + '
接收' + toSize(rdata.Bytes_received) + 'Position' + rdata.Position + '
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
活动/峰值连接数' + rdata.Threads_running + '/' + rdata.Max_used_connections + '若值过大,增加max_connections
线程缓存命中率' + ((1 - rdata.Threads_created / rdata.Connections) * 100).toFixed(2) + '%若过低,增加thread_cache_size
索引命中率' + ((1 - rdata.Key_reads / rdata.Key_read_requests) * 100).toFixed(2) + '%若过低,增加key_buffer_size
Innodb索引命中率' + ((1 - rdata.Innodb_buffer_pool_reads / rdata.Innodb_buffer_pool_read_requests) * 100).toFixed(2) + '%若过低,增加innodb_buffer_pool_size
查询缓存命中率' + cache_size + '' + lan.soft.mysql_status_ps5 + '
创建临时表到磁盘' + ((rdata.Created_tmp_disk_tables / rdata.Created_tmp_tables) * 100).toFixed(2) + '%若过大,尝试增加tmp_table_size
已打开的表' + rdata.Open_tables + '若过大,增加table_cache_size
没有使用索引的量' + rdata.Select_full_join + '若不为0,请检查数据表的索引是否合理
没有索引的JOIN量' + rdata.Select_range_check + '若不为0,请检查数据表的索引是否合理
排序后的合并次数' + rdata.Sort_merge_passes + '若值过大,增加sort_buffer_size
锁表次数' + rdata.Table_locks_waited + '若值过大,请考虑增加您的数据库性能
'; + $(".soft-man-con").html(Con); + }); +} + + +function myDbPos(){ + myPost('my_db_pos','',function(data){ + var con = '
\ +
\ + \ + \ + \ +
'; + $(".soft-man-con").html(con); + + $('#btn_change_path').click(function(){ + var datadir = $("input[name='datadir']").val(); + myPost('set_db_pos','datadir='+datadir,function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,time:2000,shade: [0.3, '#000']}); + }); + }); + }); +} + +function myPort(){ + myPost('my_port','',function(data){ + var con = '
\ +
\ + \ + \ +
'; + $(".soft-man-con").html(con); + + $('#btn_change_port').click(function(){ + var port = $("input[name='port']").val(); + myPost('set_my_port','port='+port,function(data){ + var rdata = $.parseJSON(data.data); + if (rdata.status){ + layer.msg('修改成功!',{icon:1,time:2000,shade: [0.3, '#000']}); + } else { + layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']}); + } + }); + }); + }); +} + + +//数据库存储信置 +function changeMySQLDataPath(act) { + if (act != undefined) { + layer.confirm(lan.soft.mysql_to_msg, { closeBtn: 2, icon: 3 }, function() { + var datadir = $("#datadir").val(); + var data = 'datadir=' + datadir; + var loadT = layer.msg(lan.soft.mysql_to_msg1, { icon: 16, time: 0, shade: [0.3, '#000'] }); + $.post('/database?action=SetDataDir', data, function(rdata) { + layer.close(loadT) + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + }); + }); + return; + } + + $.post('/database?action=GetMySQLInfo', '', function(rdata) { + var LimitCon = '

\ + \ + \ +

'; + $(".soft-man-con").html(LimitCon); + }); +} + + + + +//数据库配置状态 +function myPerfOpt() { + //获取MySQL配置 + myPost('db_status','',function(data){ + var rdata = $.parseJSON(data.data); + // console.log(rdata); + var key_buffer_size = toSizeM(rdata.mem.key_buffer_size); + var query_cache_size = toSizeM(rdata.mem.query_cache_size); + var tmp_table_size = toSizeM(rdata.mem.tmp_table_size); + var innodb_buffer_pool_size = toSizeM(rdata.mem.innodb_buffer_pool_size); + var innodb_additional_mem_pool_size = toSizeM(rdata.mem.innodb_additional_mem_pool_size); + var innodb_log_buffer_size = toSizeM(rdata.mem.innodb_log_buffer_size); + + var sort_buffer_size = toSizeM(rdata.mem.sort_buffer_size); + var read_buffer_size = toSizeM(rdata.mem.read_buffer_size); + var read_rnd_buffer_size = toSizeM(rdata.mem.read_rnd_buffer_size); + var join_buffer_size = toSizeM(rdata.mem.join_buffer_size); + var thread_stack = toSizeM(rdata.mem.thread_stack); + var binlog_cache_size = toSizeM(rdata.mem.binlog_cache_size); + + var a = key_buffer_size + query_cache_size + tmp_table_size + innodb_buffer_pool_size + innodb_additional_mem_pool_size + innodb_log_buffer_size; + var b = sort_buffer_size + read_buffer_size + read_rnd_buffer_size + join_buffer_size + thread_stack + binlog_cache_size; + var memSize = a + rdata.mem.max_connections * b; + + + var memCon = '
\ +
最大使用内存: \ + \ + ' + lan.soft.mysql_set_maxmem + ': MB\ +
\ +

key_buffer_sizeMB, ' + lan.soft.mysql_set_key_buffer_size + '

\ +

query_cache_sizeMB, ' + lan.soft.mysql_set_query_cache_size + '

\ +

tmp_table_sizeMB, ' + lan.soft.mysql_set_tmp_table_size + '

\ +

innodb_buffer_pool_sizeMB, ' + lan.soft.mysql_set_innodb_buffer_pool_size + '

\ +

innodb_log_buffer_sizeMB, ' + lan.soft.mysql_set_innodb_log_buffer_size + '

\ +

innodb_additional_mem_pool_sizeMB

\ +

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

\ +

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

\ +

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

\ +

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

\ +

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

\ +

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

\ +

thread_cache_size ' + lan.soft.mysql_set_thread_cache_size + '

\ +

table_open_cache ' + lan.soft.mysql_set_table_open_cache + '

\ +

max_connections ' + lan.soft.mysql_set_max_connections + '

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

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

\ +
\ + root密码\ +
\ +
\ +
\ + \ + \ +
\ +
", + }); + + $('#my_mod_close').click(function(){ + $('.layui-layer-close1').click(); + }); +} + +function showHidePass(obj){ + var a = "glyphicon-eye-open"; + var b = "glyphicon-eye-close"; + + if($(obj).hasClass(a)){ + $(obj).removeClass(a).addClass(b); + $(obj).prev().text($(obj).prev().attr('data-pw')) + } + else{ + $(obj).removeClass(b).addClass(a); + $(obj).prev().text('***'); + } +} + +function copyPass(password){ + var clipboard = new ClipboardJS('#bt_copys'); + clipboard.on('success', function (e) { + layer.msg('复制成功',{icon:1,time:2000}); + }); + + clipboard.on('error', function (e) { + layer.msg('复制失败,浏览器不兼容!',{icon:2,time:2000}); + }); + $("#bt_copys").attr('data-clipboard-text',password); + $("#bt_copys").click(); +} + +function checkSelect(){ + setTimeout(function () { + var num = $('input[type="checkbox"].check:checked').length; + // console.log(num); + if (num == 1) { + $('button[batch="true"]').hide(); + $('button[batch="false"]').show(); + }else if (num>1){ + $('button[batch="true"]').show(); + $('button[batch="false"]').show(); + }else{ + $('button[batch="true"]').hide(); + $('button[batch="false"]').hide(); + } + },5) +} + +function setDbAccess(username){ + myPost('get_db_access','username='+username, function(data){ + var rdata = $.parseJSON(data.data); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); + return; + } + + var index = layer.open({ + type: 1, + area: '500px', + title: '设置数据库权限', + closeBtn: 1, + shift: 5, + shadeClose: true, + content: "
\ +
\ + 访问权限\ +
\ + \ +
\ +
\ +
\ + \ + \ +
\ +
", + }); + + layer.ready(function(){ + if (rdata.msg == '127.0.0.1'){ + $('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true); + } else if (rdata.msg == '%'){ + $('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true); + } else if ( rdata.msg == 'ip' ){ + $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); + $('select[name="dataAccess"]').after(""); + } else { + $('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true); + $('select[name="dataAccess"]').after(""); + } + }); + + $('#my_mod_close').click(function(){ + $('.layui-layer-close1').click(); + }); + + + $('select[name="dataAccess"]').change(function(){ + var v = $(this).val(); + if (v == 'ip'){ + $(this).after(""); + } else { + $('#dataAccess_subid').remove(); + } + }); + + $('#my_mod_save').click(function(){ + var data = $("#set_db_access").serialize(); + data = decodeURIComponent(data); + var dataObj = str2Obj(data); + if(!dataObj['access']){ + dataObj['access'] = dataObj['dataAccess']; + if ( dataObj['dataAccess'] == 'ip'){ + if (dataObj['address']==''){ + layer.msg('IP地址不能空!',{icon:2,shade: [0.3, '#000']}); + return; + } + dataObj['access'] = dataObj['address']; + } + } + dataObj['username'] = username; + // console.log(data,dataObj); + myPost('set_db_access', dataObj, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + dbList(); + $('.layui-layer-close1').click(); + },{icon: rdata.status ? 1 : 2}); + }); + }); + }); +} + +function setDbPass(id, username, password){ + + var index = layer.open({ + type: 1, + skin: 'demo-class', + area: '500px', + title: '修改数据库密码', + closeBtn: 1, + shift: 5, + shadeClose: true, + content: "
\ +
\ + 用户名\ +
\ +
\ +
\ + 密码\ +
\ +
\ + \ +
\ + \ + \ +
\ +
", + }); + + $('#my_mod_close').click(function(){ + $('.layui-layer-close1').click(); + }); + + $('#my_mod_save').click(function(){ + var data = $("#mod_pwd").serialize(); + myPost('set_user_pwd', data, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + dbList(); + $('.layui-layer-close1').click(); + },{icon: rdata.status ? 1 : 2}); + }); + }); +} + +function addDatabase(type){ + if (type==1){ + var data = $("#add_db").serialize(); + data = decodeURIComponent(data); + var dataObj = str2Obj(data); + if(!dataObj['address']){ + dataObj['address'] = dataObj['dataAccess']; + } + myPost('add_db', dataObj, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + if (rdata.status){ + dbList(); + } + $('.layui-layer-close1').click(); + },{icon: rdata.status ? 1 : 2},600); + }); + return; + } + var index = layer.open({ + type: 1, + skin: 'demo-class', + area: '500px', + title: '添加数据库', + closeBtn: 1, + shift: 5, + shadeClose: true, + content: "
\ +
\ + 数据库名\ +
\ + \ +
\ +
\ +
用户名
\ +
\ + 密码\ +
\ +
\ +
\ + 访问权限\ +
\ + \ +
\ +
\ + \ +
\ + \ + \ +
\ +
", + }); + + $("input[name='name']").keyup(function(){ + var v = $(this).val(); + $("input[name='db_user']").val(v); + $("input[name='ps']").val(v); + }); + + $('#my_mod_close').click(function(){ + $('.layui-layer-close1').click(); + }); + $('select[name="dataAccess"]').change(function(){ + var v = $(this).val(); + if (v == 'ip'){ + $(this).after(""); + } else { + $('#dataAccess_subid').remove(); + } + }); +} + +function delDb(id, name){ + safeMessage('删除['+name+']','您真的要删除['+name+']吗?',function(){ + var data='id='+id+'&name='+name + myPost('del_db', data, function(data){ + var rdata = $.parseJSON(data.data); + showMsg(rdata.msg,function(){ + dbList(); + $('.layui-layer-close1').click(); + },{icon: rdata.status ? 1 : 2}, 600); + }); + }); +} + +function delDbBatch(){ + var arr = []; + $('input[type="checkbox"].check:checked').each(function () { + var _val = $(this).val(); + var _name = $(this).parent().next().text(); + if (!isNaN(_val)) { + arr.push({'id':_val,'name':_name}); + } + }); + + safeMessage('批量删除数据库','您共选择了[2]个数据库,删除后将无法恢复,真的要删除吗?',function(){ + var i = 0; + $(arr).each(function(){ + var data = myAsyncPost('del_db', this); + var rdata = $.parseJSON(data.data); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:2,time:2000,shade: [0.3, '#000']}); + } + i++; + }); + + var msg = '成功删除['+i+']个数据库!'; + showMsg(msg,function(){ + dbList(); + },{icon: 1}, 600); + }); +} + + +function setDbPs(id, name, obj) { + var _span = $(obj); + var _input = $(""); + _span.hide().after(_input); + _input.focus(); + _input.blur(function(){ + $(this).remove(); + var ps = _input.val(); + _span.text(ps).show(); + var data = {name:name,id:id,ps:ps}; + myPost('set_db_ps', data, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + }); + }); + _input.keyup(function(){ + if(event.keyCode == 13){ + _input.trigger('blur'); + } + }); +} + +function openPhpmyadmin(name,username,password){ + + data = syncPost('/plugins/check',{'name':'phpmyadmin'}); + + + if (!data.status){ + layer.msg(data.msg,{icon:2,shade: [0.3, '#000']}); + return; + } + + data = syncPost('/plugins/run',{'name':'phpmyadmin','func':'status'}); + if (data.data != 'start'){ + layer.msg('phpMyAdmin未启动',{icon:2,shade: [0.3, '#000']}); + return; + } + // console.log(data); + data = syncPost('/plugins/run',{'name':'phpmyadmin','func':'get_home_page'}); + var rdata = $.parseJSON(data.data); + if (!rdata.status){ + layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']}); + return; + } + $("#toPHPMyAdmin").attr('action',rdata.data); + + if($("#toPHPMyAdmin").attr('action').indexOf('phpmyadmin') == -1){ + layer.msg('请先安装phpMyAdmin',{icon:2,shade: [0.3, '#000']}); + setTimeout(function(){ window.location.href = '/soft'; },3000); + return; + } + + //检查版本 + data = syncPost('/plugins/run',{'name':'phpmyadmin','func':'version'}); + bigVer = data.data.split('.')[0] + if (bigVer>=5){ + + setTimeout(function(){ + $("#toPHPMyAdmin").submit(); + },3000); + layer.msg('phpMyAdmin['+data.data+']需要手动登录😭',{icon:16,shade: [0.3, '#000'],time:4000}); + + } else{ + var murl = $("#toPHPMyAdmin").attr('action'); + $("#pma_username").val(username); + $("#pma_password").val(password); + $("#db").val(name); + + layer.msg('正在打开phpMyAdmin',{icon:16,shade: [0.3, '#000'],time:2000}); + + setTimeout(function(){ + $("#toPHPMyAdmin").submit(); + },3000); + } +} + +function delBackup(filename,name){ + myPost('delete_db_backup',{filename:filename},function(){ + layer.msg('执行成功!'); + setTimeout(function(){ + $('.layui-layer-close2').click(); + setBackup(name); + },2000); + }); +} + +function downloadBackup(file){ + window.open('/files/download?filename='+encodeURIComponent(file)); +} + +function importBackup(file,name){ + myPost('import_db_backup',{file:file,name:name}, function(data){ + // console.log(data); + layer.msg('执行成功!'); + }); +} + +function setBackup(db_name,obj){ + myPost('get_db_backup_list', {name:db_name}, function(data){ + + var rdata = $.parseJSON(data.data); + var tbody = ''; + for (var i = 0; i < rdata.data.length; i++) { + tbody += '\ + ' + rdata.data[i]['name'] + '\ + ' + rdata.data[i]['size'] + '\ + ' + rdata.data[i]['time'] + '\ + \ + 导入 | \ + 下载 | \ + 删除\ + \ + '; + } + + var s = layer.open({ + type: 1, + title: "数据库备份详情", + area: ['600px', '280px'], + closeBtn: 2, + shadeClose: false, + content: '
\ +
\ + \ +
\ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + ' + tbody + '\ +
文件名称文件大小备份时间操作
\ +
\ +
\ +
' + }); + + $('#btn_backup').click(function(){ + myPost('set_db_backup',{name:db_name}, function(data){ + layer.msg('执行成功!'); + + setTimeout(function(){ + layer.close(s); + setBackup(db_name,obj); + },2000); + }); + }); + }); +} + + +function dbList(page, search){ + var _data = {}; + if (typeof(page) =='undefined'){ + var page = 1; + } + + _data['page'] = page; + _data['page_size'] = 10; + if(typeof(search) != 'undefined'){ + _data['search'] = search; + } + myPost('get_db_list', _data, function(data){ + var rdata = $.parseJSON(data.data); + var list = ''; + for(i in rdata.data){ + list += ''; + list +=''; + list += '' + rdata.data[i]['name'] +''; + list += '' + rdata.data[i]['username'] +''; + list += '' + + '***' + + ''+ + ''+ + ''; + + + list += ''+rdata.data[i]['ps']+''; + list += ''; + + list += ''+(rdata.data[i]['is_backup']?'备份':'未备份') +' | '; + + list += '管理 | ' + + '工具 | ' + + '权限 | ' + + '改密 | ' + + '删除' + + ''; + list += ''; + } + + // + var con = '
\ + \ + \ + \ + \ + \ + \ + \ +
\ +
\ + \ + \ + \ + \ + \ + '+ + // ''+ + '\ + \ + \ + '+ list +'\ +
数据库名用户名密码备份备注操作
\ +
\ +
\ +
\ + 同步选中\ + 同步所有\ + 从服务器获取\ +
\ +
\ +
'; + + con += ''; + + $(".soft-man-con").html(con); + $('#databasePage').html(rdata.page); + + readerTableChecked(); + }); +} + + +function myLogs(){ + + myPost('bin_log', {status:1}, function(data){ + var rdata = $.parseJSON(data.data); + + var limitCon = '

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

错误日志

\ + \ +

' + $(".soft-man-con").html(limitCon); + + //设置二进制日志 + $(".btn-bin").click(function () { + myPost('bin_log', 'close=change', function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + + setTimeout(function(){ + myLogs(); + }, 2000); + }); + }); + + //清空日志 + $(".btn-clear").click(function () { + myPost('error_log', 'close=1', function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 }); + + setTimeout(function(){ + myLogs(); + }, 2000); + }); + }) + + myPost('error_log', 'p=1', function(data){ + var rdata = $.parseJSON(data.data); + var error_body = ''; + if (rdata.status){ + error_body = rdata.data; + } else { + error_body = rdata.msg; + } + $("#error_log").text(error_body); + var ob = document.getElementById('error_log'); + ob.scrollTop = ob.scrollHeight; + }); + }); +} + + +function repCheckeds(tables) { + var dbs = [] + if (tables) { + dbs.push(tables) + } else { + var db_tools = $("input[value^='dbtools_']"); + for (var i = 0; i < db_tools.length; i++) { + if (db_tools[i].checked) dbs.push(db_tools[i].value.replace('dbtools_', '')); + } + } + + if (dbs.length < 1) { + layer.msg('请至少选择一张表!', { icon: 2 }); + return false; + } + return dbs; +} + +function repDatabase(db_name, tables) { + dbs = repCheckeds(tables); + + myPost('repair_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + repTools(db_name, true); + },'已送修复指令,请稍候...'); +} + + +function optDatabase(db_name, tables) { + dbs = repCheckeds(tables); + + myPost('opt_table', { db_name: db_name, tables: JSON.stringify(dbs) }, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + repTools(db_name, true); + },'已送优化指令,请稍候...'); +} + +function toDatabaseType(db_name, tables, type){ + dbs = repCheckeds(tables); + myPost('alter_table', { db_name: db_name, tables: JSON.stringify(dbs),table_type: type }, function(data){ + var rdata = $.parseJSON(data.data); + layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 }); + repTools(db_name, true); + }, '已送引擎转换指令,请稍候...'); +} + + +function selectedTools(my_obj, db_name) { + var is_checked = false + + if (my_obj) is_checked = my_obj.checked; + var db_tools = $("input[value^='dbtools_']"); + var n = 0; + for (var i = 0; i < db_tools.length; i++) { + if (my_obj) db_tools[i].checked = is_checked; + if (db_tools[i].checked) n++; + } + if (n > 0) { + var my_btns = '\ + \ + \ + ' + $("#db_tools").html(my_btns); + } else { + $("#db_tools").html(''); + } +} + +function repTools(db_name, res){ + myPost('get_db_info', {name:db_name}, function(data){ + var rdata = $.parseJSON(data.data); + var types = { InnoDB: "MyISAM", MyISAM: "InnoDB" }; + var tbody = ''; + for (var i = 0; i < rdata.tables.length; i++) { + if (!types[rdata.tables[i].type]) continue; + tbody += '\ + \ + ' + rdata.tables[i].table_name + '\ + ' + rdata.tables[i].type + '\ + ' + rdata.tables[i].collation + '\ + ' + rdata.tables[i].rows_count + '\ + ' + rdata.tables[i].data_size + '\ + \ + 修复 |\ + 优化 |\ + 转为' + types[rdata.tables[i].type] + '\ + \ + ' + } + + if (res) { + $(".gztr").html(tbody); + $("#db_tools").html(''); + $("input[type='checkbox']").attr("checked", false); + $(".tools_size").html('大小:' + rdata.data_size); + return; + } + + layer.open({ + type: 1, + title: "MySQL工具箱【" + db_name + "】", + area: ['780px', '580px'], + closeBtn: 2, + shadeClose: false, + content: '
\ + \ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + ' + tbody + '\ +
表名引擎字符集行数大小操作
\ +
\ +
\ +
' + }); + tableFixed('database_fix'); + }); +} + diff --git a/plugins/mariadb/scripts/test.py b/plugins/mariadb/scripts/test.py new file mode 100644 index 000000000..b4ef50fd2 --- /dev/null +++ b/plugins/mariadb/scripts/test.py @@ -0,0 +1,66 @@ +# coding:utf-8 + +import sys +import io +import os +import time +import subprocess +import re +import json + +cur_dir = os.getcwd() +plugin_dir = os.path.dirname(cur_dir) + +# print(plugin_dir) +root_dir = os.path.dirname(os.path.dirname(plugin_dir)) +# print(root_dir) + +sys.path.append(root_dir + "/class/core") +import mw + +os.chdir(root_dir) + + +def getPluginName(): + return 'mariadb' + + +def getPluginDir(): + return root_dir + '/plugins/' + getPluginName() + + +def getServerDir(): + return os.path.dirname(root_dir) + '/' + getPluginName() + + +def pSqliteDb(dbname='databases'): + file = getServerDir() + '/mariadb.db' + name = 'mysql' + if not os.path.exists(file): + conn = mw.M(dbname).dbPos(getServerDir(), name) + csql = mw.readFile(getPluginDir() + '/conf/mariadb.sql') + csql_list = csql.split(';') + for index in range(len(csql_list)): + conn.execute(csql_list[index], ()) + else: + conn = mw.M(dbname).dbPos(getServerDir(), name) + return conn + + +def getConf(): + path = getServerDir() + '/etc/my.cnf' + return path + + +def pMysqlDb(): + db = mw.getMyORM() + db.setDbConf(getConf()) + db.__DB_SOCKET = mw.getServerDir() + '/mysql/mysql.socket' + + print(mw.getServerDir() + '/mysql/mysql.socket') + db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')) + return db + +if __name__ == '__main__': + p = pMysqlDb() + print(p.query("select User,Host from mysql.user where User!='root' AND Host!='localhost' AND Host!=''")) diff --git a/plugins/mariadb/scripts/tools.py b/plugins/mariadb/scripts/tools.py new file mode 100755 index 000000000..025cef105 --- /dev/null +++ b/plugins/mariadb/scripts/tools.py @@ -0,0 +1,69 @@ +# coding: utf-8 + +import sys +import os +import json +import time + +sys.path.append(os.getcwd() + "/class/core") +import mw +import db + +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) + + +def set_mysql_root(password): + # 设置MySQL密码 + import db + import os + sql = db.Sql() + + root_mysql = '''#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +pwd=$1 +${server}/init.d/mysql stop +${server}/bin/mysqld_safe --skip-grant-tables& +echo '正在修改密码...'; +echo 'The set password...'; +sleep 6 +m_version=$(cat ${server}/version.pl|grep -E "(5.1.|5.5.|5.6.|mariadb)") +if [ "$m_version" != "" ];then + ${server}/bin/mysql -uroot -e "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')" + ${server}/bin/mysql -uroot -e "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')" + ${server}/bin/mysql -uroot -e "UPDATE mysql.user SET password=PASSWORD('${pwd}') WHERE user='root'"; +else + ${server}/bin/mysql -uroot -e "UPDATE mysql.user SET authentication_string='' WHERE user='root'"; + ${server}/bin/mysql -uroot -e "FLUSH PRIVILEGES"; + ${server}/bin/mysql -uroot -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${pwd}';"; +fi +${server} -uroot -e "FLUSH PRIVILEGES"; +pkill -9 mysqld_safe +pkill -9 mysqld +sleep 2 +${server}/init.d/mysql start + +echo '===========================================' +echo "root密码成功修改为: ${pwd}" +echo "The root password set ${pwd} successuful"''' + + server = mw.getServerDir() + '/mariadb' + root_mysql = root_mysql.replace('${server}', server) + mw.writeFile('mysql_root.sh', root_mysql) + os.system("/bin/bash mysql_root.sh " + password) + os.system("rm -f mysql_root.sh") + + pos = mw.getServerDir() + '/mariadb' + result = sql.table('config').dbPos(pos, 'mysql').where( + 'id=?', (1,)).setField('mysql_root', password) + + +if __name__ == "__main__": + type = sys.argv[1] + if type == 'root': + set_mysql_root(sys.argv[2]) + else: + print('ERROR: Parameter error') diff --git a/plugins/mariadb/versions/10.6/install.sh b/plugins/mariadb/versions/10.6/install.sh new file mode 100755 index 000000000..857815354 --- /dev/null +++ b/plugins/mariadb/versions/10.6/install.sh @@ -0,0 +1,87 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH + +#https://dev.mysql.com/downloads/mysql/5.5.html#downloads +#https://dev.mysql.com/downloads/file/?id=480541 + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +install_tmp=${rootPath}/tmp/mw_install.pl +mariadbDir=${serverPath}/source/mariadb + +MY_VER=10.6.8 + +Install_app() +{ + mkdir -p ${mariadbDir} + echo '正在安装脚本文件...' > $install_tmp + + if id mysql &> /dev/null ;then + echo "mysql UID is `id -u www`" + echo "mysql Shell is `grep "^www:" /etc/passwd |cut -d':' -f7 `" + else + groupadd mysql + useradd -g mysql mysql + fi + + if [ "$sysName" != "Darwin" ];then + mkdir -p /var/log/mariadb + touch /var/log/mariadb/mariadb.log + fi + + if [ ! -f ${mariadbDir}/mariadb-${MY_VER}.tar.gz ];then + wget -O ${mariadbDir}/mariadb-${MY_VER}.tar.gz --tries=3 https://downloads.mariadb.org/interstitial/mariadb-${MY_VER}/source/mariadb-${MY_VER}.tar.gz + fi + + if [ ! -d ${mariadbDir}/mariadb-${MY_VER} ];then + cd ${mariadbDir} && tar -zxvf ${mariadbDir}/mariadb-${MY_VER}.tar.gz + fi + + + if [ ! -d $serverPath/mariadb ];then + cd ${mariadbDir}/mariadb-${MY_VER} && cmake \ + -DCMAKE_INSTALL_PREFIX=$serverPath/mariadb \ + -DMYSQL_DATADIR=$serverPath/mariadb/data/ \ + -DMYSQL_USER=mysql \ + -DMYSQL_UNIX_ADDR=$serverPath/mariadb/mysql.sock \ + -DWITH_MYISAM_STORAGE_ENGINE=1 \ + -DWITH_INNOBASE_STORAGE_ENGINE=1 \ + -DWITH_MEMORY_STORAGE_ENGINE=1 \ + -DENABLED_LOCAL_INFILE=1 \ + -DWITH_PARTITION_STORAGE_ENGINE=1 \ + -DEXTRA_CHARSETS=all \ + -DDEFAULT_CHARSET=utf8mb4 \ + -DDEFAULT_COLLATION=utf8mb4_general_ci \ + -DCMAKE_C_COMPILER=/usr/bin/gcc \ + -DCMAKE_CXX_COMPILER=/usr/bin/g++ + make && make install && make clean + + if [ -d $serverPath/mariadb ];then + echo '10.6' > $serverPath/mariadb/version.pl + echo '安装完成' > $install_tmp + else + # rm -rf ${mariadbDir}/mariadb-${MY_VER} + echo '安装失败' > $install_tmp + echo 'install fail'>&2 + exit 1 + fi + fi +} + +Uninstall_app() +{ + rm -rf $serverPath/mariadb + echo '卸载完成' > $install_tmp +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_app +else + Uninstall_app +fi diff --git a/plugins/mariadb/versions/10.7/install.sh b/plugins/mariadb/versions/10.7/install.sh new file mode 100755 index 000000000..2368f96f0 --- /dev/null +++ b/plugins/mariadb/versions/10.7/install.sh @@ -0,0 +1,87 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH + +#https://dev.mysql.com/downloads/mysql/5.5.html#downloads +#https://dev.mysql.com/downloads/file/?id=480541 + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +install_tmp=${rootPath}/tmp/mw_install.pl +mariadbDir=${serverPath}/source/mariadb + +MY_VER=10.7.4 + +Install_app() +{ + mkdir -p ${mariadbDir} + echo '正在安装脚本文件...' > $install_tmp + + if id mysql &> /dev/null ;then + echo "mysql UID is `id -u www`" + echo "mysql Shell is `grep "^www:" /etc/passwd |cut -d':' -f7 `" + else + groupadd mysql + useradd -g mysql mysql + fi + + if [ "$sysName" != "Darwin" ];then + mkdir -p /var/log/mariadb + touch /var/log/mariadb/mariadb.log + fi + + if [ ! -f ${mariadbDir}/mariadb-${MY_VER}.tar.gz ];then + wget -O ${mariadbDir}/mariadb-${MY_VER}.tar.gz --tries=3 https://downloads.mariadb.org/interstitial/mariadb-${MY_VER}/source/mariadb-${MY_VER}.tar.gz + fi + + if [ ! -d ${mariadbDir}/mariadb-${MY_VER} ];then + cd ${mariadbDir} && tar -zxvf ${mariadbDir}/mariadb-${MY_VER}.tar.gz + fi + + + if [ ! -d $serverPath/mariadb ];then + cd ${mariadbDir}/mariadb-${MY_VER} && cmake \ + -DCMAKE_INSTALL_PREFIX=$serverPath/mariadb \ + -DMYSQL_DATADIR=$serverPath/mariadb/data/ \ + -DMYSQL_USER=mysql \ + -DMYSQL_UNIX_ADDR=$serverPath/mariadb/mysql.sock \ + -DWITH_MYISAM_STORAGE_ENGINE=1 \ + -DWITH_INNOBASE_STORAGE_ENGINE=1 \ + -DWITH_MEMORY_STORAGE_ENGINE=1 \ + -DENABLED_LOCAL_INFILE=1 \ + -DWITH_PARTITION_STORAGE_ENGINE=1 \ + -DEXTRA_CHARSETS=all \ + -DDEFAULT_CHARSET=utf8mb4 \ + -DDEFAULT_COLLATION=utf8mb4_general_ci \ + -DCMAKE_C_COMPILER=/usr/bin/gcc \ + -DCMAKE_CXX_COMPILER=/usr/bin/g++ + make && make install && make clean + + if [ -d $serverPath/mariadb ];then + echo '10.7' > $serverPath/mariadb/version.pl + echo '安装完成' > $install_tmp + else + # rm -rf ${mariadbDir}/mariadb-${MY_VER} + echo '安装失败' > $install_tmp + echo 'install fail'>&2 + exit 1 + fi + fi +} + +Uninstall_app() +{ + rm -rf $serverPath/mariadb + echo '卸载完成' > $install_tmp +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_app +else + Uninstall_app +fi diff --git a/plugins/mariadb/versions/10.8/install.sh b/plugins/mariadb/versions/10.8/install.sh new file mode 100755 index 000000000..b17e9c2bc --- /dev/null +++ b/plugins/mariadb/versions/10.8/install.sh @@ -0,0 +1,87 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH + +#https://dev.mysql.com/downloads/mysql/5.5.html#downloads +#https://dev.mysql.com/downloads/file/?id=480541 + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sysName=`uname` + +install_tmp=${rootPath}/tmp/mw_install.pl +mariadbDir=${serverPath}/source/mariadb + +MY_VER=10.8.3 + +Install_app() +{ + mkdir -p ${mariadbDir} + echo '正在安装脚本文件...' > $install_tmp + + if id mysql &> /dev/null ;then + echo "mysql UID is `id -u www`" + echo "mysql Shell is `grep "^www:" /etc/passwd |cut -d':' -f7 `" + else + groupadd mysql + useradd -g mysql mysql + fi + + if [ "$sysName" != "Darwin" ];then + mkdir -p /var/log/mariadb + touch /var/log/mariadb/mariadb.log + fi + + if [ ! -f ${mariadbDir}/mariadb-${MY_VER}.tar.gz ];then + wget -O ${mariadbDir}/mariadb-${MY_VER}.tar.gz --tries=3 https://downloads.mariadb.org/interstitial/mariadb-${MY_VER}/source/mariadb-${MY_VER}.tar.gz + fi + + if [ ! -d ${mariadbDir}/mariadb-${MY_VER} ];then + cd ${mariadbDir} && tar -zxvf ${mariadbDir}/mariadb-${MY_VER}.tar.gz + fi + + + if [ ! -d $serverPath/mariadb ];then + cd ${mariadbDir}/mariadb-${MY_VER} && cmake \ + -DCMAKE_INSTALL_PREFIX=$serverPath/mariadb \ + -DMYSQL_DATADIR=$serverPath/mariadb/data/ \ + -DMYSQL_USER=mysql \ + -DMYSQL_UNIX_ADDR=$serverPath/mariadb/mysql.sock \ + -DWITH_MYISAM_STORAGE_ENGINE=1 \ + -DWITH_INNOBASE_STORAGE_ENGINE=1 \ + -DWITH_MEMORY_STORAGE_ENGINE=1 \ + -DENABLED_LOCAL_INFILE=1 \ + -DWITH_PARTITION_STORAGE_ENGINE=1 \ + -DEXTRA_CHARSETS=all \ + -DDEFAULT_CHARSET=utf8mb4 \ + -DDEFAULT_COLLATION=utf8mb4_general_ci \ + -DCMAKE_C_COMPILER=/usr/bin/gcc \ + -DCMAKE_CXX_COMPILER=/usr/bin/g++ + make && make install && make clean + + if [ -d $serverPath/mariadb ];then + echo '10.7' > $serverPath/mariadb/version.pl + echo '安装完成' > $install_tmp + else + # rm -rf ${mariadbDir}/mariadb-${MY_VER} + echo '安装失败' > $install_tmp + echo 'install fail'>&2 + exit 1 + fi + fi +} + +Uninstall_app() +{ + rm -rf $serverPath/mariadb + echo '卸载完成' > $install_tmp +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_app +else + Uninstall_app +fi diff --git a/plugins/mongodb/index.py b/plugins/mongodb/index.py index ee80ea48e..7e551167a 100755 --- a/plugins/mongodb/index.py +++ b/plugins/mongodb/index.py @@ -238,8 +238,8 @@ def installPreInspection(version): sysName = sys[0].strip().lower() sysId = sys_id[0].strip() - if not sysName in ('centos', 'ubuntu', 'debian'): - return '暂时仅支持centos,ubuntu,debian' + if not sysName in ('centos', 'fedora', 'ubuntu', 'debian'): + return '暂时仅不支持{}'.format(sysName) if sysName == 'debian': if version > 10: diff --git a/plugins/mysql-yum/class/mysqlDb.py b/plugins/mysql-yum/class/mysqlDb.py deleted file mode 100755 index 6f5d74ecc..000000000 --- a/plugins/mysql-yum/class/mysqlDb.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - -import re -import os -import sys - -# sys.path.append("/usr/local/lib/python3.9/site-packages") - -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) - - -class mysqlDb: - __DB_PASS = None - __DB_USER = 'root' - __DB_PORT = 3306 - __DB_HOST = 'localhost' - __DB_CONN = None - __DB_CUR = None - __DB_ERR = None - __DB_CNF = '/etc/my.cnf' - - def __Conn(self): - '''连接MYSQL数据库''' - try: - import mw - socket = '/www/server/mysql-ya/mysql.sock' - try: - import MySQLdb - except Exception as ex: - # print('dd') - self.__DB_ERR = ex - return False - try: - myconf = mw.readFile(self.__DB_CNF) - rep = "port\s*=\s*([0-9]+)" - self.__DB_PORT = int(re.search(rep, myconf).groups()[0]) - except: - self.__DB_PORT = 3306 - # print self.__DB_PASS - #self.__DB_PASS = mw.M('config').where('id=?', (1,)).getField('mysql_root') - try: - self.__DB_CONN = MySQLdb.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, - port=self.__DB_PORT, charset="utf8", connect_timeout=1, unix_socket=socket) - except MySQLdb.Error as e: - self.__DB_HOST = '127.0.0.1' - self.__DB_CONN = MySQLdb.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, - port=self.__DB_PORT, charset="utf8", connect_timeout=1, unix_socket=socket) - self.__DB_CUR = self.__DB_CONN.cursor() - return True - except MySQLdb.Error as e: - self.__DB_ERR = e - return False - - def setDbConf(self, conf): - self.__DB_CNF = conf - - def setPwd(self, pwd): - self.__DB_PASS = pwd - - def getPwd(self): - return self.__DB_PASS - - def execute(self, sql): - # 执行SQL语句返回受影响行 - if not self.__Conn(): - return self.__DB_ERR - try: - result = self.__DB_CUR.execute(sql) - self.__DB_CONN.commit() - self.__Close() - return result - except Exception as ex: - return ex - - def query(self, sql): - # 执行SQL语句返回数据集 - if not self.__Conn(): - return self.__DB_ERR - try: - self.__DB_CUR.execute(sql) - result = self.__DB_CUR.fetchall() - # 将元组转换成列表 - # data = list(map(list, result)) - self.__Close() - return result - except Exception as ex: - return ex - - # 关闭连接 - def __Close(self): - self.__DB_CUR.close() - self.__DB_CONN.close() diff --git a/plugins/mysql-yum/index.py b/plugins/mysql-yum/index.py index cbcbae301..d1fc6dea1 100755 --- a/plugins/mysql-yum/index.py +++ b/plugins/mysql-yum/index.py @@ -35,39 +35,14 @@ def getPluginName(): def getPluginDir(): return mw.getPluginDir() + '/' + getPluginName() -sys.path.append(getPluginDir() + "/class") -import mysqlDb - def getServerDir(): return mw.getServerDir() + '/' + getPluginName() -def is_number(s): - try: - float(s) - return True - except ValueError: - pass - - try: - import unicodedata - unicodedata.numeric(s) - return True - except (TypeError, ValueError): - pass - - return False - - def getArgs(): args = sys.argv[2:] - # print(args) - - # if is_number(args): - # args = sys.argv[3:] - tmp = {} args_len = len(args) @@ -95,6 +70,38 @@ def getConf(): return path +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 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 contentReplace(content): service_path = mw.getServerDir() content = content.replace('{$ROOT_PATH}', mw.getRootDir()) @@ -125,11 +132,11 @@ def pSqliteDb(dbname='databases'): def pMysqlDb(): - db = mysqlDb.mysqlDb() + db = mw.getMyORM() db.__DB_CNF = getConf() - db.setDbConf(getConf()) - db.setPwd(pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root')) + db.setPort(getDbPort()) + db.setSocket(getSocketFile()) + db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')) return db @@ -174,22 +181,6 @@ def status(version=''): 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() diff --git a/plugins/mysql-yum/info.json b/plugins/mysql-yum/info.json index ae5fda0f6..10a6b391c 100755 --- a/plugins/mysql-yum/info.json +++ b/plugins/mysql-yum/info.json @@ -3,7 +3,7 @@ "tip":"soft", "name":"mysql-yum", "type":"运行环境", - "ps":"[开发中..不要使用]一种关系数据库管理系统(极速安装)[YUM]!", + "ps":"一种关系数据库管理系统(极速安装)[YUM]!", "todo_versions":["5.7","8.0"], "versions":["5.7","8.0"], "shell":"install.sh", diff --git a/plugins/mysql/class/mysqlDb.py b/plugins/mysql/class/mysqlDb.py deleted file mode 100755 index 867d3f3d7..000000000 --- a/plugins/mysql/class/mysqlDb.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - -import re -import os -import sys - -# sys.path.append("/usr/local/lib/python3.9/site-packages") - -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) - - -class mysqlDb: - __DB_PASS = None - __DB_USER = 'root' - __DB_PORT = 3306 - __DB_HOST = 'localhost' - __DB_CONN = None - __DB_CUR = None - __DB_ERR = None - __DB_CNF = '/etc/my.cnf' - - def __Conn(self): - '''连接MYSQL数据库''' - try: - import mw - socket = '/www/server/mysql/mysql.sock' - try: - import MySQLdb - except Exception as ex: - # print('dd') - self.__DB_ERR = ex - return False - try: - myconf = mw.readFile(self.__DB_CNF) - rep = "port\s*=\s*([0-9]+)" - self.__DB_PORT = int(re.search(rep, myconf).groups()[0]) - except: - self.__DB_PORT = 3306 - # print self.__DB_PASS - #self.__DB_PASS = mw.M('config').where('id=?', (1,)).getField('mysql_root') - try: - self.__DB_CONN = MySQLdb.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, - port=self.__DB_PORT, charset="utf8", connect_timeout=1, unix_socket=socket) - except MySQLdb.Error as e: - self.__DB_HOST = '127.0.0.1' - self.__DB_CONN = MySQLdb.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS, - port=self.__DB_PORT, charset="utf8", connect_timeout=1, unix_socket=socket) - self.__DB_CUR = self.__DB_CONN.cursor() - return True - except MySQLdb.Error as e: - self.__DB_ERR = e - return False - - def setDbConf(self, conf): - self.__DB_CNF = conf - - def setPwd(self, pwd): - self.__DB_PASS = pwd - - def getPwd(self): - return self.__DB_PASS - - def execute(self, sql): - # 执行SQL语句返回受影响行 - if not self.__Conn(): - return self.__DB_ERR - try: - result = self.__DB_CUR.execute(sql) - self.__DB_CONN.commit() - self.__Close() - return result - except Exception as ex: - return ex - - def query(self, sql): - # 执行SQL语句返回数据集 - if not self.__Conn(): - return self.__DB_ERR - try: - self.__DB_CUR.execute(sql) - result = self.__DB_CUR.fetchall() - # 将元组转换成列表 - # data = list(map(list, result)) - self.__Close() - return result - except Exception as ex: - return ex - - # 关闭连接 - def __Close(self): - self.__DB_CUR.close() - self.__DB_CONN.close() diff --git a/plugins/mysql/index.py b/plugins/mysql/index.py index 5645b06ae..d157d5db3 100755 --- a/plugins/mysql/index.py +++ b/plugins/mysql/index.py @@ -35,9 +35,6 @@ def getPluginName(): def getPluginDir(): return mw.getPluginDir() + '/' + getPluginName() -sys.path.append(getPluginDir() + "/class") -import mysqlDb - def getServerDir(): return mw.getServerDir() + '/' + getPluginName() @@ -49,31 +46,9 @@ def getInitDFile(): 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) @@ -101,6 +76,22 @@ def getConf(): 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): @@ -143,11 +134,10 @@ def pSqliteDb(dbname='databases'): def pMysqlDb(): - db = mysqlDb.mysqlDb() - db.__DB_CNF = getConf() - db.setDbConf(getConf()) - db.setPwd(pSqliteDb('config').where( - 'id=?', (1,)).getField('mysql_root')) + db = mw.getMyORM() + db.setPort(getDbPort()) + db.setSocket(getSocketFile()) + db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')) return db @@ -198,11 +188,6 @@ def initDreplace(version=''): def status(version=''): - data = mw.execShell( - "ps -ef|grep mysqld |grep -v grep | grep -v python | awk '{print $2}'") - if data[0] == '': - return 'stop' - pid = getPidFile() if not os.path.exists(pid): return 'stop' @@ -322,6 +307,9 @@ def initMysqlData(): 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() @@ -329,8 +317,8 @@ def initMysql57Data(): user = pGetDbUser() cmd = 'cd ' + serverdir + ' && ./bin/mysqld --defaults-file=' + myconf + \ ' --initialize-insecure --explicit_defaults_for_timestamp' - # print(mw.execShell(cmd)) - + data = mw.execShell(cmd) + # print(data) return False return True @@ -347,7 +335,8 @@ def initMysql8Data(): datadir + ' --initialize-insecure' # print(cmd) - mw.execShell(cmd) + data = mw.execShell(cmd) + # print(data) return False return True @@ -356,10 +345,21 @@ def initMysqlPwd(): time.sleep(5) serverdir = getServerDir() - pwd = mw.getRandomString(16) - cmd_pass = serverdir + '/bin/mysqladmin -uroot password ' + pwd - mw.execShell(cmd_pass) + # 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(data) pSqliteDb('config').where('id=?', (1,)).save('mysql_root', (pwd,)) return True @@ -371,6 +371,10 @@ def initMysql8Pwd(): 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 + \ diff --git a/plugins/mysql/install.sh b/plugins/mysql/install.sh index 69d99bcb0..51a3f3c15 100755 --- a/plugins/mysql/install.sh +++ b/plugins/mysql/install.sh @@ -26,10 +26,11 @@ fi if [ "${action}" == "uninstall" ];then - if [ -f /usr/lib/systemd/system/mysql.service ];then + if [ -f /usr/lib/systemd/system/mysql.service ] || [ -f /lib/systemd/system/mysql.service ];then systemctl stop mysql systemctl disable mysql rm -rf /usr/lib/systemd/system/mysql.service + rm -rf /lib/systemd/system/mysql.service systemctl daemon-reload fi fi diff --git a/plugins/mysql/js/mysql.js b/plugins/mysql/js/mysql.js index 78926c7f5..9f704fb61 100755 --- a/plugins/mysql/js/mysql.js +++ b/plugins/mysql/js/mysql.js @@ -835,7 +835,7 @@ function openPhpmyadmin(name,username,password){ //检查版本 data = syncPost('/plugins/run',{'name':'phpmyadmin','func':'version'}); bigVer = data.data.split('.')[0] - if (bigVer>=5){ + if (bigVer>=4.5){ setTimeout(function(){ $("#toPHPMyAdmin").submit(); diff --git a/plugins/mysql/lib/rpcgen.sh b/plugins/mysql/lib/rpcgen.sh new file mode 100644 index 000000000..b00af73c2 --- /dev/null +++ b/plugins/mysql/lib/rpcgen.sh @@ -0,0 +1,29 @@ +#!/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") +rootPath=$(dirname "$rootPath") +rootPath=$(dirname "$rootPath") + +# echo $rootPath + +SERVER_ROOT=$rootPath/lib +SOURCE_ROOT=$rootPath/source/lib + +which rpcgen +if [ "$?" != "0" ];then + + if [ ! -f ${SOURCE_ROOT}/rpcsvc-proto-1.4.tar.gz ];then + wget -O ${SOURCE_ROOT}/rpcsvc-proto-1.4.tar.gz https://github.com/thkukuk/rpcsvc-proto/releases/download/v1.4/rpcsvc-proto-1.4.tar.gz + fi + + if [ ! -d ${SERVER_ROOT}/rpcsvc-proto-1.4 ];then + cd ${SOURCE_ROOT} && tar -zxvf rpcsvc-proto-1.4.tar.gz + cd ${SOURCE_ROOT}/rpcsvc-proto-1.4 + ./configure && make && make install + fi + +fi \ No newline at end of file diff --git a/plugins/mysql/versions/5.5/install.sh b/plugins/mysql/versions/5.5/install.sh index 110dc6454..9cf5f5f1b 100755 --- a/plugins/mysql/versions/5.5/install.sh +++ b/plugins/mysql/versions/5.5/install.sh @@ -66,6 +66,7 @@ Install_mysql() else rm -rf ${mysqlDir}/mysql-5.5.62 echo '安装失败' > $install_tmp + echo 'install fail'>&2 exit 1 fi fi diff --git a/plugins/mysql/versions/5.6/install.sh b/plugins/mysql/versions/5.6/install.sh index 1e0540780..c3aad718d 100755 --- a/plugins/mysql/versions/5.6/install.sh +++ b/plugins/mysql/versions/5.6/install.sh @@ -82,6 +82,7 @@ Install_mysql() else rm -rf ${mysqlDir}/mysql-5.6.50 echo '安装失败' > $install_tmp + echo 'install fail'>&2 exit 1 fi fi diff --git a/plugins/mysql/versions/5.7/install.sh b/plugins/mysql/versions/5.7/install.sh index 8e3cd819c..85629889e 100755 --- a/plugins/mysql/versions/5.7/install.sh +++ b/plugins/mysql/versions/5.7/install.sh @@ -38,6 +38,7 @@ Install_mysql() touch /var/log/mariadb/mariadb.log fi + cd $serverPath/mdserver-web/plugins/mysql/lib && /bin/bash rpcgen.sh if [ ! -f ${mysqlDir}/mysql-boost-${VERSION}.tar.gz ];then wget -O ${mysqlDir}/mysql-boost-${VERSION}.tar.gz --tries=3 https://cdn.mysql.com/Downloads/MySQL-5.7/mysql-boost-${VERSION}.tar.gz @@ -95,8 +96,9 @@ Install_mysql() echo '5.7' > $serverPath/mysql/version.pl echo '安装完成' > $install_tmp else - rm -rf ${mysqlDir}/mysql-${VERSION} + # rm -rf ${mysqlDir}/mysql-${VERSION} echo '安装失败' > $install_tmp + echo 'install fail'>&2 exit 1 fi fi diff --git a/plugins/mysql/versions/8.0/install.sh b/plugins/mysql/versions/8.0/install.sh index 57a9f7ea3..acd58a003 100755 --- a/plugins/mysql/versions/8.0/install.sh +++ b/plugins/mysql/versions/8.0/install.sh @@ -75,6 +75,8 @@ Install_mysql() useradd -g mysql mysql fi + cd $serverPath/mdserver-web/plugins/mysql/lib && /bin/bash rpcgen.sh + INSTALL_CMD=cmake # check cmake version CMAKE_VERSION=`cmake -version | grep version | awk '{print $3}' | awk -F '.' '{print $1}'` @@ -154,8 +156,9 @@ Install_mysql() echo '8.0' > $serverPath/mysql/version.pl echo '安装完成' > $install_tmp else - rm -rf ${mysqlDir}/mysql-${VERSION} + # rm -rf ${mysqlDir}/mysql-${VERSION} echo '安装失败' > $install_tmp + echo 'install fail'>&2 exit 1 fi fi diff --git a/plugins/op_waf/index.py b/plugins/op_waf/index.py index 4141dfeb3..c435ad7a0 100755 --- a/plugins/op_waf/index.py +++ b/plugins/op_waf/index.py @@ -186,7 +186,7 @@ def status(): def contentReplace(content): service_path = mw.getServerDir() - waf_path = mw.getServerDir() + "/openresty/nginx/conf/waf" + waf_path = getServerDir() + "/waf" content = content.replace('{$ROOT_PATH}', mw.getRootDir()) content = content.replace('{$SERVER_PATH}', service_path) content = content.replace('{$WAF_PATH}', waf_path) @@ -195,20 +195,21 @@ def contentReplace(content): def initDreplace(): - path = mw.getServerDir() + "/openresty/nginx/conf" + path = getServerDir() if not os.path.exists(path + '/waf'): sdir = getPluginDir() + '/waf' cmd = 'cp -rf ' + sdir + ' ' + path mw.execShell(cmd) - config = mw.getServerDir() + '/openresty/nginx/conf/waf/config.json' + config = path + '/waf/config.json' content = mw.readFile(config) content = json.loads(content) - content['reqfile_path'] = mw.getServerDir( - ) + "/openresty/nginx/conf/waf/html" + + wfDir = path + "/waf/html" + content['reqfile_path'] = wfDir mw.writeFile(config, mw.getJson(content)) - config = mw.getServerDir() + "/openresty/nginx/conf/waf/lua/init.lua" + config = path + "/waf/lua/init.lua" content = mw.readFile(config) content = contentReplace(content) mw.writeFile(config, content) @@ -230,18 +231,13 @@ def start(): path = getConf() conf = mw.readFile(path) conf = conf.replace('#include luawaf.conf;', "include luawaf.conf;") - mw.writeFile(path, conf) + mw.restartWeb() return 'ok' def stop(): - path = mw.getServerDir() + "/openresty/nginx/conf/waf" - if os.path.exists(path): - cmd = 'rm -rf ' + path - mw.execShell(cmd) - path = getConf() conf = mw.readFile(path) conf = conf.replace('include luawaf.conf;', "#include luawaf.conf;") @@ -265,12 +261,12 @@ def reload(): def getJsonPath(name): - path = mw.getServerDir() + "/openresty/nginx/conf/waf/" + name + ".json" + path = getServerDir() + "/waf/" + name + ".json" return path def getRuleJsonPath(name): - path = mw.getServerDir() + "/openresty/nginx/conf/waf/rule/" + name + ".json" + path = getServerDir() + "/waf/rule/" + name + ".json" return path diff --git a/plugins/op_waf/install.sh b/plugins/op_waf/install.sh index d29ae27b7..e4a6e9a97 100755 --- a/plugins/op_waf/install.sh +++ b/plugins/op_waf/install.sh @@ -16,9 +16,6 @@ Install_of(){ echo '正在安装脚本文件...' > $install_tmp mkdir -p $serverPath/op_waf - if [ -f $serverPath/openresty ];then - mkdir -p $serverPath/openresty/nginx/conf/waf - fi echo '0.1' > $serverPath/op_waf/version.pl echo 'install ok' > $install_tmp } diff --git a/plugins/php-yum/install.sh b/plugins/php-yum/install.sh index 0412dffc1..8d30ca522 100755 --- a/plugins/php-yum/install.sh +++ b/plugins/php-yum/install.sh @@ -32,6 +32,26 @@ if [ ! -d $curPath/versions/$2 ];then fi + +#获取信息和版本 +# bash /www/server/mdsever-web/scripts/getos.sh +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + + +if [ "$OSNAME" == "centos" ];then + rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-${VERSION_ID}.rpm +fi + + +# rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-31.rpm +if [ "$OSNAME" == "fedora" ];then + rpm -Uvh http://rpms.remirepo.net/fedora/remi-release-${VERSION_ID}.rpm +fi + + + if [ "${action}" == "uninstall" ] && [ -d ${serverPath}/php-yum/${type} ];then #初始化 cd ${rootPath} && python3 ${rootPath}/plugins/php-yum/index.py stop ${type} diff --git a/plugins/php-yum/versions/74/install.sh b/plugins/php-yum/versions/74/install.sh index ef8f50566..87abd097b 100755 --- a/plugins/php-yum/versions/74/install.sh +++ b/plugins/php-yum/versions/74/install.sh @@ -10,13 +10,6 @@ sourcePath=${serverPath}/source sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl - -#获取信息和版本 -# bash /www/server/mdsever-web/scripts/getos.sh -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - version=7.4.x PHP_VER=74 @@ -25,11 +18,7 @@ Install_php() { #------------------------ install start ------------------------------------# -### centos start ################ -rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-${VERSION_ID}.rpm -yum install -y php74 php74-php-fpm -### centos start ################ - +yum install -y php74 php74-php-fpm if [ "$?" == "0" ];then mkdir -p $serverPath/php-yum/${PHP_VER} fi diff --git a/plugins/php-yum/versions/80/install.sh b/plugins/php-yum/versions/80/install.sh index 99361224b..c3e0b37f0 100755 --- a/plugins/php-yum/versions/80/install.sh +++ b/plugins/php-yum/versions/80/install.sh @@ -11,12 +11,6 @@ sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl -#获取信息和版本 -# bash /www/server/mdsever-web/scripts/getos.sh -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - version=8.0.x PHP_VER=80 @@ -25,11 +19,8 @@ Install_php() { #------------------------ install start ------------------------------------# -### centos start ################ -rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-${VERSION_ID}.rpm -yum install -y php80 php80-php-fpm -### centos start ################ +yum install -y php80 php80-php-fpm if [ "$?" == "0" ];then mkdir -p $serverPath/php-yum/${PHP_VER} fi diff --git a/plugins/php-yum/versions/81/install.sh b/plugins/php-yum/versions/81/install.sh index f60ec2b71..2e6236c0a 100755 --- a/plugins/php-yum/versions/81/install.sh +++ b/plugins/php-yum/versions/81/install.sh @@ -11,12 +11,6 @@ sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl -#获取信息和版本 -# bash /www/server/mdsever-web/scripts/getos.sh -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - version=8.1.x PHP_VER=81 @@ -24,12 +18,7 @@ PHP_VER=81 Install_php() { #------------------------ install start ------------------------------------# - -### centos start ################ -rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-${VERSION_ID}.rpm -yum install -y php81 php81-php-fpm -### centos start ################ - +yum install -y php81 php81-php-fpm if [ "$?" == "0" ];then mkdir -p $serverPath/php-yum/${PHP_VER} fi diff --git a/plugins/php-yum/versions/82/install.sh b/plugins/php-yum/versions/82/install.sh index 100542c2b..fdb66d5a0 100755 --- a/plugins/php-yum/versions/82/install.sh +++ b/plugins/php-yum/versions/82/install.sh @@ -11,12 +11,6 @@ sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl -#获取信息和版本 -# bash /www/server/mdsever-web/scripts/getos.sh -bash ${rootPath}/scripts/getos.sh -OSNAME=`cat ${rootPath}/data/osname.pl` -VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` - version=8.2.x PHP_VER=82 @@ -24,12 +18,7 @@ PHP_VER=82 Install_php() { #------------------------ install start ------------------------------------# - -### centos start ################ -rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-${VERSION_ID}.rpm yum install -y php82 php82-php-fpm -### centos start ################ - if [ "$?" == "0" ];then mkdir -p $serverPath/php-yum/${PHP_VER} fi @@ -39,7 +28,7 @@ fi Uninstall_php() { - # $serverPath/php-ya/init.d/php${PHP_VER} stop + # $serverPath/php-yum/init.d/php${PHP_VER} stop rm -rf $serverPath/php-yum/${PHP_VER} echo "卸载php-${version}..." > $install_tmp } diff --git a/plugins/php/index.py b/plugins/php/index.py index e6532ccef..c20038b8d 100755 --- a/plugins/php/index.py +++ b/plugins/php/index.py @@ -78,7 +78,7 @@ def getFpmConfFile(version): return getServerDir() + '/' + version + '/etc/php-fpm.d/www.conf' -def status(version): +def status_progress(version): # ps -ef|grep 'php/81' |grep -v grep | grep -v python | awk '{print $2} cmd = "ps -ef|grep 'php/" + version + \ "' |grep -v grep | grep -v python | awk '{print $2}'" @@ -88,6 +88,27 @@ def status(version): return 'start' +def getPhpSocket(version): + path = getFpmConfFile(version) + content = mw.readFile(path) + rep = 'listen\s*=\s*(.*)' + tmp = re.search(rep, content) + return tmp.groups()[0].strip() + + +def status(version): + ''' + sock文件判断是否启动 + ''' + sock = getPhpSocket(version) + if sock.find(':'): + return status_progress(version) + + if not os.path.exists(sock): + return 'stop' + return 'start' + + def contentReplace(content, version): service_path = mw.getServerDir() content = content.replace('{$ROOT_PATH}', mw.getRootDir()) @@ -705,7 +726,7 @@ def installLib(version): name = args['name'] execstr = "cd " + getPluginDir() + "/versions && /bin/bash common.sh " + \ - version + ' install ' + ' ' + name + version + ' install ' + name rettime = time.strftime('%Y-%m-%d %H:%M:%S') insert_info = (None, '安装[' + name + '-' + version + ']', @@ -724,7 +745,7 @@ def uninstallLib(version): name = args['name'] execstr = "cd " + getPluginDir() + "/versions && /bin/bash common.sh " + \ - version + ' uninstall ' + ' ' + name + version + ' uninstall ' + name data = mw.execShell(execstr) # data[0] == '' and @@ -759,8 +780,15 @@ def installPreInspection(version): if sysName == 'ubuntu': return 'ubuntu已经安装不了' - if sysName == 'debian' and sys_id > 10: + if sysName == 'debian' and sysId > 10: return 'debian10可以安装' + + if sysName == 'fedora': + sys_id = mw.execShell( + "cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}'") + sysId = sys_id[0].strip() + if int(sysId) > 31: + return 'fedora[{}]不可安装'.format(sysId) return 'ok' if __name__ == "__main__": diff --git a/plugins/php/info.json b/plugins/php/info.json index dc1b12cb5..6b165ba48 100755 --- a/plugins/php/info.json +++ b/plugins/php/info.json @@ -5,8 +5,8 @@ "name": "php", "title": "PHP", "coexist": true, - "versions": ["52","53","54","55","56","70","71","72","73","74","80","81"], - "updates": ["5.2.17","5.3.29","5.4.45","5.6.36","7.0.30","7.1.33","7.2.32","7.3.20","7.4.8","8.0.13","8.1.0"], + "versions": ["52","53","54","55","56","70","71","72","73","74","80","81","82"], + "updates": ["5.2.17","5.3.29","5.4.45","5.6.36","7.0.30","7.1.33","7.2.32","7.3.20","7.4.30","8.0.30","8.1.8","8.2.0"], "tip": "soft", "install_pre_inspection":true, "checks": "server/php/VERSION/bin/php", diff --git a/plugins/php/lib/libmemcached.sh b/plugins/php/lib/libmemcached.sh index 76297d853..2dca0bf21 100644 --- a/plugins/php/lib/libmemcached.sh +++ b/plugins/php/lib/libmemcached.sh @@ -15,14 +15,27 @@ rootPath=$(dirname "$rootPath") SERVER_ROOT=$rootPath/lib SOURCE_ROOT=$rootPath/source/lib +#----------------------------- libmemcached start -------------------------# +# if [ ! -d ${SERVER_ROOT}/libmemcached ];then +# cd ${SOURCE_ROOT} +# if [ ! -f ${SOURCE_ROOT}/libmemcached-1.0.4.tar.gz ];then +# wget -O libmemcached-1.0.4.tar.gz https://launchpad.net/libmemcached/1.0/1.0.4/+download/libmemcached-1.0.4.tar.gz -T 20 +# fi +# tar -zxf libmemcached-1.0.4.tar.gz +# cd libmemcached-1.0.4 +# ./configure --prefix=${SERVER_ROOT}/libmemcached -with-memcached && make && make install +# fi +#----------------------------- libmemcached end -------------------------# + + #----------------------------- libmemcached start -------------------------# if [ ! -d ${SERVER_ROOT}/libmemcached ];then cd ${SOURCE_ROOT} - if [ ! -f ${SOURCE_ROOT}/libmemcached-1.0.4.tar.gz ];then - wget -O libmemcached-1.0.4.tar.gz https://launchpad.net/libmemcached/1.0/1.0.4/+download/libmemcached-1.0.4.tar.gz -T 20 + if [ ! -f ${SOURCE_ROOT}/libmemcached-1.0.18.tar.gz ];then + wget -O libmemcached-1.0.18.tar.gz https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz -T 20 fi - tar -zxf libmemcached-1.0.4.tar.gz - cd libmemcached-1.0.4 + tar -zxf libmemcached-1.0.18.tar.gz + cd libmemcached-1.0.18 ./configure --prefix=${SERVER_ROOT}/libmemcached -with-memcached && make && make install fi #----------------------------- libmemcached end -------------------------# \ No newline at end of file diff --git a/plugins/php/lib/oniguruma.sh b/plugins/php/lib/oniguruma.sh new file mode 100644 index 000000000..9168410e9 --- /dev/null +++ b/plugins/php/lib/oniguruma.sh @@ -0,0 +1,25 @@ +#!/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") +rootPath=$(dirname "$rootPath") +rootPath=$(dirname "$rootPath") + +# echo $rootPath + +SERVER_ROOT=$rootPath/lib +SOURCE_ROOT=$rootPath/source/lib + +which onig-config +if [ "$?" != "0" ];then + cd ${SOURCE_ROOT} + if [ ! -f ${SOURCE_ROOT}/oniguruma-6.9.4.tar.gz ];then + wget -O ${SOURCE_ROOT}/oniguruma-6.9.4.tar.gz https://github.com/kkos/oniguruma/archive/v6.9.4.tar.gz + fi + cd ${SOURCE_ROOT} && tar -zxvf oniguruma-6.9.4.tar.gz + cd ${SOURCE_ROOT}/oniguruma-6.9.4 && ./autogen.sh && ./configure --prefix=/usr && make && make install +fi + diff --git a/plugins/php/versions/52/gd.sh b/plugins/php/versions/52/gd.sh index 56564ca6a..aab4f988b 100755 --- a/plugins/php/versions/52/gd.sh +++ b/plugins/php/versions/52/gd.sh @@ -57,10 +57,17 @@ Install_lib() fi - if [ "$OSNAME" == "debian" ] && [ "$OSNAME" == "ubuntu" ];then + # cp -frp /usr/lib64/libldap* /usr/lib/ + + # ln -s /usr/lib64/libjpeg.so /usr/lib/libjpeg.so + # ln -s /usr/lib64/libpng.so /usr/lib/libpng.so + + if [ ! -f /usr/lib/libjpeg.so ];then ln -s /usr/lib64/libjpeg.so /usr/lib/libjpeg.so - ln -s /usr/lib64/libpng.so /usr/lib/ - cp -frp /usr/lib64/libldap* /usr/lib/ + fi + + if [ ! -f /usr/lib/libpng.so ];then + ln -s /usr/lib64/libpng.so /usr/lib/libpng.so fi diff --git a/plugins/php/versions/53/install.sh b/plugins/php/versions/53/install.sh index aad347ab3..e81cb2edc 100755 --- a/plugins/php/versions/53/install.sh +++ b/plugins/php/versions/53/install.sh @@ -21,7 +21,6 @@ echo "安装php-5.3.29 ..." > $install_tmp mkdir -p $sourcePath/php mkdir -p $serverPath/php -cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash freetype_old.sh cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash libiconv.sh cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash zlib.sh @@ -39,6 +38,9 @@ if [ -f $serverPath/php/53/bin/php ];then return fi +# OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" +# OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" +# OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS='' if [ $sysName == 'Darwin' ]; then OPTIONS='--without-iconv' @@ -46,9 +48,6 @@ if [ $sysName == 'Darwin' ]; then OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" fi diff --git a/plugins/php/versions/54/install.sh b/plugins/php/versions/54/install.sh index 5cff9c5c6..1fc23cfce 100755 --- a/plugins/php/versions/54/install.sh +++ b/plugins/php/versions/54/install.sh @@ -20,7 +20,7 @@ echo "安装php-${version} ..." > $install_tmp mkdir -p $sourcePath/php mkdir -p $serverPath/php -cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash freetype_old.sh + cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash libiconv.sh cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash zlib.sh @@ -40,9 +40,6 @@ if [ $sysName == 'Darwin' ]; then OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" fi diff --git a/plugins/php/versions/55/install.sh b/plugins/php/versions/55/install.sh index 2025cf53c..1d171d275 100755 --- a/plugins/php/versions/55/install.sh +++ b/plugins/php/versions/55/install.sh @@ -39,9 +39,6 @@ if [ $sysName == 'Darwin' ]; then OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" fi diff --git a/plugins/php/versions/56/install.sh b/plugins/php/versions/56/install.sh index 0a86dd34f..cadfffe39 100755 --- a/plugins/php/versions/56/install.sh +++ b/plugins/php/versions/56/install.sh @@ -39,9 +39,6 @@ if [ $sysName == 'Darwin' ]; then OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" fi diff --git a/plugins/php/versions/70/install.sh b/plugins/php/versions/70/install.sh index 21a772193..8ab98b059 100755 --- a/plugins/php/versions/70/install.sh +++ b/plugins/php/versions/70/install.sh @@ -39,9 +39,6 @@ if [ $sysName == 'Darwin' ]; then OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" fi diff --git a/plugins/php/versions/71/install.sh b/plugins/php/versions/71/install.sh index d1d690fa8..d9fc1d99f 100755 --- a/plugins/php/versions/71/install.sh +++ b/plugins/php/versions/71/install.sh @@ -38,9 +38,6 @@ if [ $sysName == 'Darwin' ]; then OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" fi diff --git a/plugins/php/versions/72/install.sh b/plugins/php/versions/72/install.sh index 796eb83a4..1d358ec7a 100755 --- a/plugins/php/versions/72/install.sh +++ b/plugins/php/versions/72/install.sh @@ -39,9 +39,6 @@ if [ $sysName == 'Darwin' ]; then OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" fi diff --git a/plugins/php/versions/73/install.sh b/plugins/php/versions/73/install.sh index ee80cff87..21f742e8d 100755 --- a/plugins/php/versions/73/install.sh +++ b/plugins/php/versions/73/install.sh @@ -43,9 +43,6 @@ if [ $sysName == 'Darwin' ]; then # OPTIONS="${OPTIONS} --enable-zip" else OPTIONS="--with-iconv=${serverPath}/lib/libiconv" - OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" - OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" - OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" OPTIONS="${OPTIONS} --with-curl" OPTIONS="${OPTIONS} --with-libzip=${serverPath}/lib/libzip" fi diff --git a/plugins/php/versions/74/install.sh b/plugins/php/versions/74/install.sh index a111ad05a..ede715e75 100755 --- a/plugins/php/versions/74/install.sh +++ b/plugins/php/versions/74/install.sh @@ -11,7 +11,7 @@ sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl -version=7.4.26 +version=7.4.30 PHP_VER=74 Install_php() { diff --git a/plugins/php/versions/80/install.sh b/plugins/php/versions/80/install.sh index 5e7b859ed..38dcd912e 100755 --- a/plugins/php/versions/80/install.sh +++ b/plugins/php/versions/80/install.sh @@ -11,7 +11,7 @@ sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl -version=8.0.20 +version=8.0.21 PHP_VER=80 Install_php() { diff --git a/plugins/php/versions/81/install.sh b/plugins/php/versions/81/install.sh index 177ae1d1f..fb8000c24 100755 --- a/plugins/php/versions/81/install.sh +++ b/plugins/php/versions/81/install.sh @@ -11,7 +11,7 @@ sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl -version=8.1.7 +version=8.1.8 PHP_VER=81 Install_php() { diff --git a/plugins/php/versions/82/install.sh b/plugins/php/versions/82/install.sh new file mode 100755 index 000000000..6ceed4984 --- /dev/null +++ b/plugins/php/versions/82/install.sh @@ -0,0 +1,97 @@ +#!/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") +sourcePath=${serverPath}/source +sysName=`uname` +install_tmp=${rootPath}/tmp/mw_install.pl + + +version=8.2.0alpha2 +PHP_VER=82 +Install_php() +{ +#------------------------ install start ------------------------------------# +echo "安装php-${version} ..." > $install_tmp +mkdir -p $sourcePath/php +mkdir -p $serverPath/php + +cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash freetype_new.sh +cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash libiconv.sh +cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash zlib.sh +cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash libzip.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/~pierrick/php-8.2.0alpha2.tar.xz + fi + + cd $sourcePath/php && tar -Jxf $sourcePath/php/php-${version}.tar.xz + mv $sourcePath/php/php-${version} $sourcePath/php/php${PHP_VER} +fi + +cd $sourcePath/php/php${PHP_VER} + +OPTIONS='' +if [ $sysName == 'Darwin' ]; then + OPTIONS='--without-iconv' + OPTIONS="${OPTIONS} --with-curl=${serverPath}/lib/curl" + # OPTIONS="${OPTIONS} --enable-zip" +else + OPTIONS="--with-iconv=${serverPath}/lib/libiconv" + OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype" + OPTIONS="${OPTIONS} --with-curl" + OPTIONS="${OPTIONS} --with-libzip=${serverPath}/lib/libzip" +fi + + +echo "$sourcePath/php/php${PHP_VER}" + +if [ ! -d $serverPath/php/${PHP_VER} ];then + cd $sourcePath/php/php${PHP_VER} + ./buildconf --force + ./configure \ + --prefix=$serverPath/php/${PHP_VER} \ + --exec-prefix=$serverPath/php/${PHP_VER} \ + --with-config-file-path=$serverPath/php/${PHP_VER}/etc \ + --enable-mysqlnd \ + --with-mysqli=mysqlnd \ + --with-pdo-mysql=mysqlnd \ + --enable-mbstring \ + --with-zlib-dir=$serverPath/lib/zlib \ + --enable-ftp \ + --enable-sockets \ + --enable-simplexml \ + --enable-soap \ + --enable-posix \ + --enable-sysvmsg \ + --enable-sysvsem \ + --enable-sysvshm \ + --disable-intl \ + --disable-fileinfo \ + $OPTIONS \ + --enable-fpm + make clean && make && make install && make clean +fi +#------------------------ install end ------------------------------------# +} + +Uninstall_php() +{ + $serverPath/php/init.d/php${PHP_VER} stop + rm -rf $serverPath/php/${PHP_VER} + echo "卸载php-${version}..." > $install_tmp +} + +action=${1} +if [ "${1}" == 'install' ];then + Install_php +else + Uninstall_php +fi diff --git a/plugins/php/versions/all_test.sh b/plugins/php/versions/all_test.sh index 8b0af6dd7..352c7a402 100644 --- a/plugins/php/versions/all_test.sh +++ b/plugins/php/versions/all_test.sh @@ -6,13 +6,7 @@ ROOT_DIR=$(cd "$(dirname "$0")"; pwd) # cd /www/server/mdserver-web/scripts/quick && bash debug.sh # cd /www/server/mdserver-web/plugins/php/versions && /bin/bash all_test.sh - -# cd /www/server/mdserver-web/plugins/php && bash install.sh install 71 -# cd /www/server/mdserver-web/plugins/php/versions/52/ && bash gd.sh install 52 - -# cd /www/server/mdserver-web/plugins/php/versions/52/ && bash openssl.sh install 52 -# cd /www/server/mdserver-web/plugins/php/versions/81/ && bash imagemagick.sh install 81 -# cd /www/server/mdserver-web/plugins/php/versions/70/ && bash imagemagick.sh install 70 +# cd /www/server/mdserver-web/plugins/php/versions/common && bash swoole.sh install 81 # PHP_VER=52 @@ -30,7 +24,7 @@ ROOT_DIR=$(cd "$(dirname "$0")"; pwd) # echo "php${PHP_VER} -- end" -PHP_VER_LIST=(53 54 55 56 70 71 72 73 74 80 81) +PHP_VER_LIST=(53 54 55 56 70 71 72 73 74 80 81 82) # PHP_VER_LIST=(81) for PHP_VER in ${PHP_VER_LIST[@]}; do echo "php${PHP_VER} -- start" @@ -41,7 +35,7 @@ for PHP_VER in ${PHP_VER_LIST[@]}; do done cd $DIR -PHP_VER_LIST=(53 54 55 56 70 71 72 73 74 80 81) +PHP_VER_LIST=(53 54 55 56 70 71 72 73 74 80 81 82) PHP_EXT_LIST=(ioncube ZendGuardLoader pdo mysqlnd sqlite3 openssl pcntl opcache mcrypt fileinfo \ exif gd intl memcache memcached redis imagemagick xdebug xhprof \ swoole yaf yar yac apc mongo mongodb solr seaslog mbstring zip) @@ -49,6 +43,11 @@ PHP_EXT_LIST=(ioncube ZendGuardLoader pdo mysqlnd sqlite3 openssl pcntl opcache for PHP_VER in ${PHP_VER_LIST[@]}; do echo "php${PHP_VER} -- start" + if [ ! -d /www/server/php/${PHP_VER} ];then + echo "php${PHP_VER} is not install!" + break; + fi + NON_ZTS_FILENAME=`ls /www/server/php/${PHP_VER}/lib/php/extensions | grep no-debug-non-zts` for EXT in ${PHP_EXT_LIST[@]}; do extFile=/www/server/php/${PHP_VER}/lib/php/extensions/${NON_ZTS_FILENAME}/${EXT}.so diff --git a/plugins/php/versions/common.sh b/plugins/php/versions/common.sh index bff62a9bf..e2812378e 100644 --- a/plugins/php/versions/common.sh +++ b/plugins/php/versions/common.sh @@ -36,9 +36,9 @@ fi if [ "$action" == 'uninstall' ];then if [ -f $FILE ];then - cd ${curPath}/${version} && bash ${extName}.sh install ${version} + cd ${curPath}/${version} && bash ${extName}.sh uninstall ${version} elif [ -f $FILE_COMMON ];then - cd ${curPath}/common && bash ${extName}.sh install ${version} + cd ${curPath}/common && bash ${extName}.sh uninstall ${version} else echo 'no such extension' fi @@ -46,5 +46,5 @@ fi echo "cd ${curPath}/common && bash ${extName}.sh install ${version}" echo "cd ${curPath}/${version} && bash ${extName}.sh install ${version}" -echo "cd ${curPath}/common && bash ${extName}.sh uinstall ${version}" -echo "cd ${curPath}/${version} && bash ${extName}.sh uinstall ${version}" +echo "cd ${curPath}/common && bash ${extName}.sh uninstall ${version}" +echo "cd ${curPath}/${version} && bash ${extName}.sh uninstall ${version}" diff --git a/plugins/php/versions/common/exif.sh b/plugins/php/versions/common/exif.sh index 6c3961b0f..d45cb90f7 100755 --- a/plugins/php/versions/common/exif.sh +++ b/plugins/php/versions/common/exif.sh @@ -59,8 +59,7 @@ Install_lib() sed -i $BAK 's/CFLAGS \=/CFLAGS \= -std=c99/g' Makefile fi - - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/fileinfo.sh b/plugins/php/versions/common/fileinfo.sh index 23c9269fd..3270c8374 100755 --- a/plugins/php/versions/common/fileinfo.sh +++ b/plugins/php/versions/common/fileinfo.sh @@ -57,7 +57,7 @@ Install_lib() sed -i $BAK 's/CFLAGS \=/CFLAGS \= -std=c99/g' Makefile fi - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/gd.sh b/plugins/php/versions/common/gd.sh index 38fcf30ea..79862e1fe 100755 --- a/plugins/php/versions/common/gd.sh +++ b/plugins/php/versions/common/gd.sh @@ -19,8 +19,8 @@ LIBV=0 if [ "$version" -lt "74" ];then - echo "not need!" - exit 1 + bash $curPath/gd_old.sh $1 $2 + exit 0 fi diff --git a/plugins/php/versions/common/gd_old.sh b/plugins/php/versions/common/gd_old.sh new file mode 100755 index 000000000..7754151e1 --- /dev/null +++ b/plugins/php/versions/common/gd_old.sh @@ -0,0 +1,117 @@ +#!/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") +rootPath=$(dirname "$rootPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") +sourcePath=${serverPath}/source/php + +actionType=$1 +version=$2 + +LIBNAME=gd +LIBV=0 + + +# if [ "$version" -lt "74" ];then +# echo "not need!" +# exit 1 +# fi + + +NON_ZTS_FILENAME=`ls $serverPath/php/${version}/lib/php/extensions | grep no-debug-non-zts` +extFile=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so + +sysName=`uname` +if [ "$sysName" == "Darwin" ];then + BAK='_bak' +else + BAK='' +fi + + +# cd $serverPath/mdserver-web/plugins/php/lib && /bin/bash freetype_old.sh +# OPTIONS="${OPTIONS} --with-freetype-dir=${serverPath}/lib/freetype_old" +# OPTIONS="${OPTIONS} --with-gd --enable-gd-native-ttf" +# OPTIONS="${OPTIONS} --with-jpeg --with-jpeg-dir=/usr/lib" + + +Install_lib() +{ + + isInstall=`cat $serverPath/php/$version/etc/php.ini|grep "${LIBNAME}.so"` + if [ "${isInstall}" != "" ];then + echo "php-$version 已安装${LIBNAME},请选择其它版本!" + return + fi + + if [ ! -f "$extFile" ];then + + if [ ! -d $sourcePath/php${version}/ext ];then + cd $serverPath/mdserver-web/plugins/php && /bin/bash install.sh install ${version} + fi + + cd $sourcePath/php${version}/ext/${LIBNAME} + + $serverPath/php/$version/bin/phpize + + #--with-xpm + ./configure --with-php-config=$serverPath/php/$version/bin/php-config \ + --with-gd \ + --with-jpeg \ + --with-freetype \ + --enable-gd-jis-conv \ + --enable-gd-native-ttf + make clean && make && make install && make clean + + fi + + if [ ! -f "$extFile" ];then + echo "ERROR!" + return + fi + + echo "" >> $serverPath/php/$version/etc/php.ini + echo "[${LIBNAME}]" >> $serverPath/php/$version/etc/php.ini + echo "extension=${LIBNAME}.so" >> $serverPath/php/$version/etc/php.ini + + $serverPath/php/init.d/php${version} restart + echo '===========================================================' + echo 'successful!' +} + + +Uninstall_lib() +{ + if [ ! -f "$serverPath/php/$version/bin/php-config" ];then + echo "php-$version 未安装,请选择其它版本!" + return + fi + + if [ ! -f "$extFile" ];then + echo "php-$version 未安装${LIBNAME},请选择其它版本!" + return + fi + + echo $serverPath/php/$version/etc/php.ini + sed -i $BAK "/${LIBNAME}.so/d" $serverPath/php/$version/etc/php.ini + sed -i $BAK "/${LIBNAME}/d" $serverPath/php/$version/etc/php.ini + + rm -f $extFile + bash ${rootPath}/plugins/php/versions/lib.sh $version restart + echo '===============================================' + echo 'successful!' +} + + + +if [ "$actionType" == 'install' ];then + Install_lib +elif [ "$actionType" == 'uninstall' ];then + Uninstall_lib +fi \ No newline at end of file diff --git a/plugins/php/versions/common/imagemagick.sh b/plugins/php/versions/common/imagemagick.sh index 874982610..e29de8fc2 100755 --- a/plugins/php/versions/common/imagemagick.sh +++ b/plugins/php/versions/common/imagemagick.sh @@ -53,8 +53,8 @@ Install_lib() cd $php_lib/${LIBNAME}-${LIBV} $serverPath/php/$version/bin/phpize - ./configure --with-php-config=$serverPath/php/$version/bin/php-config \ - && make clean && make && make install && make clean + ./configure --with-php-config=$serverPath/php/$version/bin/php-config + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/intl.sh b/plugins/php/versions/common/intl.sh index b1ca3f906..d7883437d 100755 --- a/plugins/php/versions/common/intl.sh +++ b/plugins/php/versions/common/intl.sh @@ -53,8 +53,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config $OPTIONS - - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/mcrypt.sh b/plugins/php/versions/common/mcrypt.sh index 30707fefc..be7bc4a23 100755 --- a/plugins/php/versions/common/mcrypt.sh +++ b/plugins/php/versions/common/mcrypt.sh @@ -45,7 +45,7 @@ Install_lib() php_lib=$sourcePath/php_lib mkdir -p $php_lib - if [ ! -f $php_lib/${LIBNAME}-${LIBV} ];then + if [ ! -f $php_lib/${LIBNAME}-${LIBV}.tgz ];then wget -O $php_lib/${LIBNAME}-${LIBV}.tgz http://pecl.php.net/get/${LIBNAME}-${LIBV}.tgz cd $php_lib tar xvf ${LIBNAME}-${LIBV}.tgz @@ -54,7 +54,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/memcache.sh b/plugins/php/versions/common/memcache.sh index eabf42bcc..39562af5d 100755 --- a/plugins/php/versions/common/memcache.sh +++ b/plugins/php/versions/common/memcache.sh @@ -50,7 +50,7 @@ Install_lib() cd ${LIBNAME}-${LIBV} $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config --enable-memcache --with-zlib-dir - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/memcached.sh b/plugins/php/versions/common/memcached.sh index 9a6e90333..aa4b52db9 100755 --- a/plugins/php/versions/common/memcached.sh +++ b/plugins/php/versions/common/memcached.sh @@ -21,6 +21,10 @@ if [ "$version" -lt "70" ];then LIBV=2.2.0 fi +if [ "$version" -eq "70" ] || [ "$version" -eq "71" ];then + LIBV=3.1.5 +fi + NON_ZTS_FILENAME=`ls $serverPath/php/${version}/lib/php/extensions | grep no-debug-non-zts` extFile=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so @@ -37,26 +41,24 @@ Install_lib() echo "php-$version 已安装${LIBNAME},请选择其它版本!" return fi - + if [ ! -f "$extFile" ];then php_lib=$sourcePath/php_lib mkdir -p $php_lib - rm -rf $php_lib/${LIBNAME}-${LIBV} - - if [ ! -d $php_lib/${LIBNAME}-${LIBV} ];then + if [ ! -f $php_lib/${LIBNAME}-${LIBV}.tgz ];then wget -O $php_lib/${LIBNAME}-${LIBV}.tgz http://pecl.php.net/get/${LIBNAME}-${LIBV}.tgz cd $php_lib && tar xvf ${LIBNAME}-${LIBV}.tgz fi cd $php_lib/${LIBNAME}-${LIBV} - sed -i '_bak' "3237,3238s#ulong#zend_ulong#g" $php_lib/${LIBNAME}-${LIBV}/php_memcached.c + # sed -i '_bak' "3237,3238s#ulong#zend_ulong#g" $php_lib/${LIBNAME}-${LIBV}/php_memcached.c $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config \ --enable-memcached \ - --disable-memcached-sasl && \ + --disable-memcached-sasl make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/mongo.sh b/plugins/php/versions/common/mongo.sh index 4ba5ba6fa..1d6c8137d 100755 --- a/plugins/php/versions/common/mongo.sh +++ b/plugins/php/versions/common/mongo.sh @@ -58,8 +58,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config $OPTIONS - - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/mongodb.sh b/plugins/php/versions/common/mongodb.sh index 221a7860a..4052b1e4e 100755 --- a/plugins/php/versions/common/mongodb.sh +++ b/plugins/php/versions/common/mongodb.sh @@ -67,8 +67,8 @@ Install_lib() cd $php_lib/${LIBNAME}-${LIBV} $serverPath/php/$version/bin/phpize - ./configure --with-php-config=$serverPath/php/$version/bin/php-config \ - && make clean && make && make install && make clean + ./configure --with-php-config=$serverPath/php/$version/bin/php-config + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/redis.sh b/plugins/php/versions/common/redis.sh index 97511276e..15c497ade 100755 --- a/plugins/php/versions/common/redis.sh +++ b/plugins/php/versions/common/redis.sh @@ -27,7 +27,7 @@ fi NON_ZTS_FILENAME=`ls $serverPath/php/${version}/lib/php/extensions | grep no-debug-non-zts` -extDir=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/ +extFile=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so if [ "$sysName" == "Darwin" ];then BAK='_bak' @@ -37,13 +37,13 @@ fi Install_lib() { - isInstall=`cat $serverPath/php/$version/etc/php.ini|grep "${LIBNAME}.so"` + isInstall=`cat $serverPath/php/${version}/etc/php.ini|grep "${LIBNAME}.so"` if [ "${isInstall}" != "" ];then echo "php-$version 已安装${LIBNAME},请选择其它版本!" return fi - extFile=$extDir${LIBNAME}.so + if [ ! -f "$extFile" ];then php_lib=$sourcePath/php_lib @@ -56,7 +56,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config - make && make install && make clean + make clean && make && make install && make clean fi @@ -80,8 +80,7 @@ Uninstall_lib() echo "php-$version 未安装,请选择其它版本!" return fi - - extFile=$extDir${LIBNAME}.so + if [ ! -f "$extFile" ];then echo "php-$version 未安装${LIBNAME},请选择其它版本!" echo "php-$version not install memcache, Plese select other version!" diff --git a/plugins/php/versions/common/seaslog.sh b/plugins/php/versions/common/seaslog.sh index b31603e48..c15e4804e 100755 --- a/plugins/php/versions/common/seaslog.sh +++ b/plugins/php/versions/common/seaslog.sh @@ -24,7 +24,7 @@ if [ "$version" -lt "72" ];then fi NON_ZTS_FILENAME=`ls $serverPath/php/${version}/lib/php/extensions | grep no-debug-non-zts` -extDir=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/ +extFile=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/${_LIBNAME}.so if [ "$sysName" == "Darwin" ];then BAK='_bak' @@ -40,7 +40,7 @@ Install_lib() return fi - extFile=$extDir${_LIBNAME}.so + if [ ! -f "$extFile" ];then OPTIONS='' @@ -58,7 +58,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config - make && make install && make clean + make clean && make && make install && make clean fi sleep 1 @@ -85,12 +85,12 @@ Uninstall_lib() return fi - extFile=$extDir${_LIBNAME}.so if [ ! -f "$extFile" ];then echo "php-$version 未安装${LIBNAME},请选择其它版本!" echo "php-$version not install ${LIBNAME}, Plese select other version!" return fi + _LIBNAME=$(echo $LIBNAME | tr '[A-Z]' '[a-z]') sed -i $BAK "/${_LIBNAME}.so/d" $serverPath/php/$version/etc/php.ini sed -i $BAK "/${_LIBNAME}/d" $serverPath/php/$version/etc/php.ini diff --git a/plugins/php/versions/common/solr.sh b/plugins/php/versions/common/solr.sh index 7f200319c..82f5ca13e 100755 --- a/plugins/php/versions/common/solr.sh +++ b/plugins/php/versions/common/solr.sh @@ -57,7 +57,7 @@ Install_lib() cd $php_lib/${LIBNAME}-${LIBV} $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config $OPTIONS - make && make install && make clean + make clean && make && make install && make clean fi sleep 1 if [ ! -f "$extFile" ];then diff --git a/plugins/php/versions/common/swoole.sh b/plugins/php/versions/common/swoole.sh index a1cc27c6c..826b27559 100755 --- a/plugins/php/versions/common/swoole.sh +++ b/plugins/php/versions/common/swoole.sh @@ -27,6 +27,11 @@ else echo '72+' fi +if [ "$version" -eq "82" ];then + echo "not need" + exit 1 +fi + NON_ZTS_FILENAME=`ls $serverPath/php/${version}/lib/php/extensions | grep no-debug-non-zts` extFile=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so @@ -62,7 +67,7 @@ Install_lib() --enable-openssl \ --with-openssl-dir=$serverPath/lib/openssl \ --enable-sockets - make && make install && make clean + make clean && make && make install && make clean fi while [[ ! -f "$extFile" ]]; diff --git a/plugins/php/versions/common/xdebug.sh b/plugins/php/versions/common/xdebug.sh index 5911fcf7a..ccc6ccf0c 100755 --- a/plugins/php/versions/common/xdebug.sh +++ b/plugins/php/versions/common/xdebug.sh @@ -25,6 +25,11 @@ if [ "$version" -eq "70" ] || [ "$version" -eq "71" ];then LIBV=2.7.0 fi +if [ "$version" -eq "82" ];then + echo "not need" + exit 1 +fi + NON_ZTS_FILENAME=`ls $serverPath/php/${version}/lib/php/extensions | grep no-debug-non-zts` extFile=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so @@ -36,7 +41,7 @@ fi Install_lib() { - isInstall=`cat $serverPath/php/$version/etc/php.ini|grep "${LIBNAME}.so"` + isInstall=`cat $serverPath/php/${version}/etc/php.ini|grep "${LIBNAME}.so"` if [ "${isInstall}" != "" ];then echo "php-$version 已安装${LIBNAME},请选择其它版本!" return @@ -56,7 +61,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/xhprof.sh b/plugins/php/versions/common/xhprof.sh index e4b97d0ad..771826a29 100755 --- a/plugins/php/versions/common/xhprof.sh +++ b/plugins/php/versions/common/xhprof.sh @@ -51,7 +51,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --enable-xhprof \ --with-php-config=$serverPath/php/$version/bin/php-config - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/yac.sh b/plugins/php/versions/common/yac.sh index cadcacc3e..947c2d590 100755 --- a/plugins/php/versions/common/yac.sh +++ b/plugins/php/versions/common/yac.sh @@ -47,7 +47,7 @@ Install_lib() php_lib=$sourcePath/php_lib mkdir -p $php_lib - if [ ! -f $php_lib/${LIBNAME}-${LIBV} ];then + if [ ! -f $php_lib/${LIBNAME}-${LIBV}.tgz ];then wget -O $php_lib/${LIBNAME}-${LIBV}.tgz http://pecl.php.net/get/${LIBNAME}-${LIBV}.tgz cd $php_lib tar xvf ${LIBNAME}-${LIBV}.tgz @@ -56,7 +56,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config - make && make install && make clean + make clean && make && make install && make clean cd .. fi diff --git a/plugins/php/versions/common/yaf.sh b/plugins/php/versions/common/yaf.sh index 7a8ace7d1..affe7ab66 100755 --- a/plugins/php/versions/common/yaf.sh +++ b/plugins/php/versions/common/yaf.sh @@ -23,6 +23,19 @@ if [ "$version" -lt "70" ];then LIBV=2.3.5 fi +if [ "$version" -eq "70" ] || [ "$version" -eq "71" ];then + LIBV=3.2.5 +fi + +if [ "$version" -eq "72" ] || [ "$version" -eq "73" ];then + LIBV=3.2.5 +fi + +if [ "$version" -eq "82" ];then + echo "not need" + exit 1 +fi + NON_ZTS_FILENAME=`ls $serverPath/php/${version}/lib/php/extensions | grep no-debug-non-zts` extFile=$serverPath/php/${version}/lib/php/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so @@ -54,7 +67,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/yar.sh b/plugins/php/versions/common/yar.sh index 961ac0fd5..e387d6462 100755 --- a/plugins/php/versions/common/yar.sh +++ b/plugins/php/versions/common/yar.sh @@ -54,7 +54,7 @@ Install_lib() $serverPath/php/$version/bin/phpize ./configure --with-php-config=$serverPath/php/$version/bin/php-config \ --with-curl=$serverPath/lib/curl - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/common/zip.sh b/plugins/php/versions/common/zip.sh index dc877acbe..8ca5d2e05 100755 --- a/plugins/php/versions/common/zip.sh +++ b/plugins/php/versions/common/zip.sh @@ -52,7 +52,7 @@ Install_lib() ./configure --with-php-config=$serverPath/php/$version/bin/php-config \ --with-zip - make && make install && make clean + make clean && make && make install && make clean fi diff --git a/plugins/php/versions/phplib.conf b/plugins/php/versions/phplib.conf index 2f99083b6..ef232bfd4 100755 --- a/plugins/php/versions/phplib.conf +++ b/plugins/php/versions/phplib.conf @@ -53,7 +53,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "缓存器", "msg": "用于加速PHP脚本!", @@ -73,7 +74,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "SSL!", @@ -88,7 +90,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "加密软件!", @@ -108,7 +111,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "缓存器", "msg": "用于信号控制!", @@ -127,7 +131,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "用于FILE!", @@ -146,7 +151,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "用于图像文件格式!", @@ -157,9 +163,18 @@ "name": "gd", "versions": [ "52", + "53", + "54", + "55", + "56", + "70", + "71", + "72", + "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "通用GD库!", @@ -180,7 +195,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "提供国际化支持", @@ -214,7 +230,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "缓存器", "msg": "强大的内容缓存器,支持集群", @@ -235,7 +252,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "缓存器", "msg": "更强大的内容缓存器,支持集群", @@ -265,7 +283,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "比GD更强大的图形库", @@ -284,7 +303,9 @@ "72", "73", "74", - "80" + "80", + "81", + "82" ], "type": "调试器", "msg": "不多说,不了解的不要安装", @@ -305,7 +326,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "性能分析", "msg": "不多说,不了解的不要安装!", @@ -324,7 +346,9 @@ "72", "73", "74", - "80" + "80", + "81", + "82" ], "type": "通用扩展", "msg": "异步、并行、高性能网络通信引擎", @@ -355,7 +379,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "框架", "msg": "Yaf是一个C语言编写的PHP框架", @@ -375,7 +400,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "框架", "msg": "Yar是一个RPC框架", @@ -406,7 +432,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "通用扩展", "msg": "Mongodb数据库连接驱动", @@ -422,7 +449,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "缓存器", "msg": "高性能无锁共享内存Cache", @@ -442,7 +470,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "大数据", "msg": "SOLR全文搜索服务", @@ -462,7 +491,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "日志", "msg": "SeasLog高性能日志记录", @@ -478,7 +508,8 @@ "73", "74", "80", - "81" + "81", + "82" ], "type": "压缩", "msg": "压缩组件", diff --git a/plugins/phpmyadmin/info.json b/plugins/phpmyadmin/info.json index e810898a6..33307f86c 100755 --- a/plugins/phpmyadmin/info.json +++ b/plugins/phpmyadmin/info.json @@ -5,8 +5,8 @@ "type":"运行环境", "ps":"著名Web端MySQL管理工具", "to_ver":["4.8.4"], - "versions":["4.4.15","5.2.0"], - "updates":["4.4.15","5.2.0"], + "versions":["4.4.15","4.9.10","5.2.0"], + "updates":["4.4.15","4.9.10","5.2.0"], "shell":"install.sh", "checks":"server/phpmyadmin", "path": "server/phpmyadmin", diff --git a/plugins/pureftp/install.sh b/plugins/pureftp/install.sh index 83860e62c..9c8607d71 100755 --- a/plugins/pureftp/install.sh +++ b/plugins/pureftp/install.sh @@ -51,8 +51,10 @@ Install_pureftp() VER=$1 DOWNLOAD=https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-${VER}.tar.gz + # curl -sSLo pure-ftpd-1.0.49.tar.gz https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.49.tar.gz if [ ! -f $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz ];then - wget --no-check-certificate -O $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz $DOWNLOAD + # wget --no-check-certificate -O $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz $DOWNLOAD + curl -sSLo $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz $DOWNLOAD fi #检测文件是否损坏. @@ -64,7 +66,7 @@ Install_pureftp() else # 重新下载 rm -rf $serverPath/source/pureftp/pure-ftpd-${VER} - wget --no-check-certificate -O $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz $DOWNLOAD + curl -sSLo $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz $DOWNLOAD fi fi diff --git a/plugins/rsyncd/install.sh b/plugins/rsyncd/install.sh index b901b4342..6b420bfb4 100755 --- a/plugins/rsyncd/install.sh +++ b/plugins/rsyncd/install.sh @@ -23,8 +23,10 @@ Install_rsyncd() echo '正在安装脚本文件...' > $install_tmp mkdir -p $serverPath/rsyncd - if [ $OSNAME == 'debian' ];then + if [ "$OSNAME" == "debian'" ] || [ "$OSNAME" == "ubuntu'" ];then apt install -y rsync + else + yum install -y rsync fi @@ -36,10 +38,11 @@ Install_rsyncd() Uninstall_rsyncd() { - if [ -f /usr/lib/systemd/system/rsyncd.service ];then + if [ -f /usr/lib/systemd/system/rsyncd.service ] || [ -f /lib/systemd/system/rsyncd.service ];then systemctl stop rsyncd systemctl disable rsyncd rm -rf /usr/lib/systemd/system/rsyncd.service + rm -rf /lib/systemd/system/rsyncd.service systemctl daemon-reload fi diff --git a/plugins/sphinx/install.sh b/plugins/sphinx/install.sh index 49ca46742..7373c4dd2 100755 --- a/plugins/sphinx/install.sh +++ b/plugins/sphinx/install.sh @@ -11,32 +11,16 @@ sysName=`uname` install_tmp=${rootPath}/tmp/mw_install.pl -sysName=`uname` -echo "use system: ${sysName}" +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +OSNAME_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` -if [ ${sysName} == "Darwin" ]; then - OSNAME='macos' -elif grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then - OSNAME='centos' -elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then - OSNAME='fedora' -elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then - OSNAME='debian' -elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then - OSNAME='ubuntu' -elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then - OSNAME='raspbian' -else - OSNAME='unknow' -fi - -if [ ${OSNAME} == "centos" ] || [ ${OSNAME} == "fedora" ]; then +if [ ${OSNAME} == "centos" ] || + [ ${OSNAME} == "fedora" ] || + [ ${OSNAME} == "alma" ]; then yum install -y postgresql-libs unixODBC fi - - - Install_sphinx() { @@ -44,18 +28,26 @@ Install_sphinx() mkdir -p $serverPath/sphinx SPHINX_DIR=${serverPath}/source/sphinx - mkdir -p $SPHINX_DIR if [ ! -f ${SPHINX_DIR}/sphinx-3.1.1.tar.gz ];then if [ $sysName == 'Darwin' ]; then wget -O ${SPHINX_DIR}/sphinx-3.1.1.tar.gz http://sphinxsearch.com/files/sphinx-3.1.1-612d99f-darwin-amd64.tar.gz else - wget -O ${SPHINX_DIR}/sphinx-3.1.1.tar.gz http://sphinxsearch.com/files/sphinx-3.1.1-612d99f-linux-amd64.tar.gz + curl -sSLo ${SPHINX_DIR}/sphinx-3.1.1.tar.gz http://sphinxsearch.com/files/sphinx-3.1.1-612d99f-linux-amd64.tar.gz fi fi - cd ${SPHINX_DIR} && tar -zxvf sphinx-3.1.1.tar.gz - cp -rf ${SPHINX_DIR}/sphinx-3.1.1/ $serverPath/sphinx/bin + if [ ! -f ${SPHINX_DIR}/sphinx-3.1.1.tar.gz ];then + curl -sSLo ${SPHINX_DIR}/sphinx-3.1.1.tar.gz https://github.com/midoks/mdserver-web/releases/download/init/sphinx-3.1.1.tar.gz + fi + + cd ${SPHINX_DIR} && tar -zxvf sphinx-3.1.1.tar.gz + + if [ "$?" == "0" ];then + mkdir -p $SPHINX_DIR + cp -rf ${SPHINX_DIR}/sphinx-3.1.1/ $serverPath/sphinx/bin + fi + if [ -d $serverPath/sphinx ];then echo '3.1.1' > $serverPath/sphinx/version.pl echo '安装完成' > $install_tmp @@ -66,10 +58,11 @@ Install_sphinx() Uninstall_sphinx() { - if [ -f /usr/lib/systemd/system/sphinx.service ];then + if [ -f /usr/lib/systemd/system/sphinx.service ] || [ -f /lib/systemd/system/sphinx.service ];then systemctl stop sphinx systemctl disable sphinx rm -rf /usr/lib/systemd/system/sphinx.service + rm -rf /lib/systemd/system/sphinx.service systemctl daemon-reload fi diff --git a/plugins/varnish/install.sh b/plugins/varnish/install.sh index 671e4adea..fa1e5c7b7 100755 --- a/plugins/varnish/install.sh +++ b/plugins/varnish/install.sh @@ -7,27 +7,14 @@ rootPath=$(dirname "$curPath") rootPath=$(dirname "$rootPath") serverPath=$(dirname "$rootPath") - install_tmp=${rootPath}/tmp/mw_install.pl - VERSION=$2 -_os=`uname` -if [ ${_os} == "Darwin" ]; then - OSNAME='macos' -elif grep -Eq "openSUSE" /etc/*-release; then - OSNAME='opensuse' -elif grep -Eq "CentOS" /etc/*-release; then - OSNAME='centos' -elif grep -Eq "Fedora" /etc/*-release; then - OSNAME='fedora' -elif grep -Eq "Debian" /etc/*-release; then - OSNAME='debian' -elif grep -Eq "Ubuntu" /etc/*-release; then - OSNAME='ubuntu' -else - OSNAME='unknow' -fi + +bash ${rootPath}/scripts/getos.sh +OSNAME=`cat ${rootPath}/data/osname.pl` +OSNAME_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'` + Install_varnish() { @@ -36,7 +23,7 @@ Install_varnish() if [ "${OSNAME}" == "macos" ]; then brew install varnish - elif [ "${OSNAME}" == "centos" ]; then + elif [ "${OSNAME}" == "centos" ] || [ "${OSNAME}" == "fedora" ] || [ "${OSNAME}" == "alma" ] || [ "${OSNAME}" == "rocky" ]; then yum install varnish -y elif [ "${OSNAME}" == "debian" ] || [ "${OSNAME}" == "ubuntu" ]; then apt install varnish -y @@ -62,7 +49,7 @@ Uninstall_varnish() if [ "${OSNAME}" == "macos" ]; then brew uninstall varnish - elif [ "${OSNAME}" == "centos" ]; then + elif [ "${OSNAME}" == "centos" ] || [ "${OSNAME}" == "fedora" ] || [ "${OSNAME}" == "alma" ] || [ "${OSNAME}" == "rocky" ]; then yum remove varnish -y elif [ "${OSNAME}" == "debian" ] || [ "${OSNAME}" == "ubuntu" ]; then apt remove varnish -y diff --git a/route/static/app/config.js b/route/static/app/config.js index 226707a3e..0b546395c 100755 --- a/route/static/app/config.js +++ b/route/static/app/config.js @@ -281,7 +281,7 @@ function getPanelSSL(){ \ \ \ ' diff --git a/route/static/app/public.js b/route/static/app/public.js index 5681b16f7..643a9edd5 100755 --- a/route/static/app/public.js +++ b/route/static/app/public.js @@ -1107,6 +1107,31 @@ function execLog(){ }); } +/** + * 获取时分秒 + * @param {Number} seconds 总秒数 + * @param {String} dateFormat 返回的日期格式,默认为'H:i:s' + */ +function getSFM(seconds, dateFormat = 'H:i:s') { + var obj = {}; + obj.H = Number.parseInt(seconds / 3600); + obj.i = Number.parseInt((seconds - obj.H * 3600) / 60); + obj.s = Number.parseInt(seconds - obj.H * 3600 - obj.i * 60); + if (obj.H < 10) { + obj.H = '0' + obj.H; + } + if (obj.i < 10) { + obj.i = '0' + obj.i; + } + if (obj.s < 10) { + obj.s = '0' + obj.s; + } + + // 3.解析 + var rs = dateFormat.replace('H', obj.H).replace('i', obj.i).replace('s', obj.s); + return rs; +} + function remind(a){ a = a == undefined ? 1 : a; $.post("/task/list", "table=tasks&result=2,4,6,8&limit=10&p=" + a, function(g) { @@ -1117,9 +1142,9 @@ function remind(a){ for(var d = 0; d < g.data.length; d++) { if(g.data[d].status != '1'){ task_count++; - e += '
'+g.data[d].name+'【'+lan.bt.task_the+'】'+ lan.bt.time + (g.data[d].end - g.data[d].start) + lan.bt.s+'
'+g.data[d].addtime+'' + e += '
'+g.data[d].name+'【'+lan.bt.task_the+'】耗时['+ getSFM(g.data[d].end - g.data[d].start) +']
'+g.data[d].addtime+'' } else{ - e += '
'+g.data[d].name+'【'+lan.bt.task_ok+'】'+ lan.bt.time + (g.data[d].end - g.data[d].start) + lan.bt.s+'
'+g.data[d].addtime+''; + e += '
'+g.data[d].name+'【'+lan.bt.task_ok+'】耗时['+ getSFM(g.data[d].end - g.data[d].start) +']
'+g.data[d].addtime+''; } } var con = '
\ diff --git a/route/static/language/Simplified_Chinese/lan.js b/route/static/language/Simplified_Chinese/lan.js index aabb15abb..bcc28814c 100755 --- a/route/static/language/Simplified_Chinese/lan.js +++ b/route/static/language/Simplified_Chinese/lan.js @@ -108,17 +108,17 @@ var lan = { }, "config":{ - "close_panel_msg":"关闭面板会导致您无法访问面板 ,您真的要关闭宝塔Linux面板吗?", + "close_panel_msg":"关闭面板会导致您无法访问面板 ,您真的要关闭Linux面板吗?", "close_panel_title":"关闭面板", "config_save":"正在保存配置...", "config_sync":"正在同步时间...", - "config_user_binding":"绑定宝塔帐号", - "config_user_edit":"修改绑定宝塔账号", + "config_user_binding":"绑定帐号", + "config_user_edit":"修改绑定账号", "binding":"绑定", "token_get":"正在获取密钥...", - "user_bt":"宝塔官网账户", - "pass_bt":"宝塔官网密码", - "binding_un_msg":"您确定要解除绑定宝塔帐号码?", + "user_bt":"官网账户", + "pass_bt":"官网密码", + "binding_un_msg":"您确定要解除绑定帐号码?", "binding_un_title":"解除绑定", "binding_un":"解绑", "ssl_close_msg":"关闭SSL后,必需使用http协议访问面板,继续吗?", @@ -333,7 +333,7 @@ var lan = { "install_ok":"已将安装请求添加到安装器", "task_add":"已添加到队列", "panel_open":"正在打开面板...", - "panel_add":"关联宝塔面板", + "panel_add":"关联面板", "panel_edit":"修改关联", "panel_err_format":"面板地址格式不正确,示例:", "panel_err_empty":"面板资料不能为空", @@ -890,7 +890,7 @@ var lan = { "enable_301":"启用301", "to301_help_1":"选择[整站]时请不要将目标URL设为同一站点下的域名.", "to301_help_2":"取消301重定向后,需清空浏览器缓存才能看到生效结果.", - "bt_ssl":"宝塔SSL", + "bt_ssl":"SSL", "lets_ssl":"Let\'s Encrypt免费证书", "other":"其它", "other_ssl":"其他证书", @@ -901,23 +901,23 @@ var lan = { "ssl_key":"密钥(KEY)", "ssl_crt":"证书(PEM格式)", "ssl_close":"关闭SSL", - "bt_bind_no":"未绑定宝塔账号,请注册绑定,绑定宝塔账号(非论坛账号)可实现一键部署SSL", - "bt_user":"宝塔账号", + "bt_bind_no":"未绑定账号,请注册绑定,绑定账号(非论坛账号)可实现一键部署SSL", + "bt_user":"账号", "login":"登录", - "bt_reg":"注册宝塔账号", - "bt_ssl_help_1":"宝塔SSL证书为亚洲诚信证书,需要实名认证才能申请使用", - "bt_ssl_help_2":"已有宝塔账号请登录绑定", - "bt_ssl_help_3":"宝塔SSL申请的是TrustAsia DV SSL CA - G5 原价:1900元/1年,宝塔用户免费!", + "bt_reg":"注册账号", + "bt_ssl_help_1":"SSL证书为亚洲诚信证书,需要实名认证才能申请使用", + "bt_ssl_help_2":"已有账号请登录绑定", + "bt_ssl_help_3":"SSL申请的是TrustAsia DV SSL CA - G5 原价:1900元/1年,用户免费!", "bt_ssl_help_4":"一年满期后免费颁发。", "btapply":"申请", "endtime":"到期时间", "status":"状态", "bt_ssl_help_5":"申请之前,请确保域名已解析,如未解析会导致审核失败", - "bt_ssl_help_6":"宝塔SSL申请的是免费版TrustAsia DV SSL CA - G5证书,仅支持单个域名申请", + "bt_ssl_help_6":"SSL申请的是免费版TrustAsia DV SSL CA - G5证书,仅支持单个域名申请", "bt_ssl_help_7":"有效期1年,不支持续签,到期后需要重新申请", "bt_ssl_help_8":"Let\'s Encrypt免费证书,有效期3个月,支持多域名。默认会自动续签", "bt_ssl_help_9":"若您的站点使用了CDN或301重定向会导致续签失败", - "bt_ssl_help_10":"粘贴您的*.key以及*.pem内容,然后保存即可[帮助]。", + "bt_ssl_help_10":"粘贴您的*.key以及*.pem内容,然后保存即可。", "phone_input":"请输入手机号码", "ssl_apply_1":"正在提交订单,请稍后..", "ssl_apply_2":"正在校验域名,请稍后..", diff --git a/scripts/getos.sh b/scripts/getos.sh index e98e89fba..13f8af9d5 100755 --- a/scripts/getos.sh +++ b/scripts/getos.sh @@ -14,6 +14,8 @@ elif grep -Eqi "Arch" /etc/issue || grep -Eq "Arch" /etc/*-release; then OSNAME='arch' elif grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then OSNAME='centos' +elif grep -Eqi "AlmaLinux" /etc/issue || grep -Eq "AlmaLinux" /etc/*-release; then + OSNAME='alma' elif grep -Eqi "Rocky" /etc/issue || grep -Eq "Rocky" /etc/*-release; then OSNAME='rocky' elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then diff --git a/scripts/install/alma.sh b/scripts/install/alma.sh index 1e70f2e15..85f078dc9 100755 --- a/scripts/install/alma.sh +++ b/scripts/install/alma.sh @@ -81,6 +81,10 @@ for yumPack in make cmake gcc gcc-c++ gcc-g77 flex bison file libtool libtool-li do yum -y install $yumPack;done +# findLD=`cat /etc/ld.so.conf | grep '/usr/local/lib64'` +# echo "/usr/local/lib64" >> /etc/ld.so.conf + + cd /www/server/mdserver-web/scripts && bash lib.sh chmod 755 /www/server/mdserver-web/data @@ -99,11 +103,9 @@ do fi done + cd /www/server/mdserver-web && /etc/init.d/mw stop cd /www/server/mdserver-web && /etc/init.d/mw start cd /www/server/mdserver-web && /etc/init.d/mw default - - - diff --git a/scripts/install/fedora.sh b/scripts/install/fedora.sh index fbba069c6..86eef8531 100644 --- a/scripts/install/fedora.sh +++ b/scripts/install/fedora.sh @@ -70,8 +70,9 @@ yum -y install epel-release yum install -y libevent libevent-devel libxslt* libjpeg* libpng* gd* zip libmcrypt libmcrypt-devel yum install -y gcc libffi-devel python-devel openssl-devel +yum install -y curl-devel libmcrypt libmcrypt-devel python3-devel -yum -y install wget python-devel python-imaging libicu-devel unzip bzip2-devel gcc libxml2 libxml2-dev libjpeg-devel libpng-devel libwebp libwebp-devel lsof pcre pcre-devel vixie-cron crontabs +yum -y install wget python-devel python-imaging libicu-devel unzip bzip2-devel gcc libxml2 libxml2-devel libjpeg-devel libpng-devel libwebp libwebp-devel lsof pcre pcre-devel crontabs yum -y install net-tools yum -y install ncurses-devel mysql-devel cmake yum -y install python-devel @@ -81,6 +82,8 @@ yum -y install python3-devel for yumPack in make cmake gcc gcc-c++ gcc-g77 flex bison file libtool libtool-libs autoconf kernel-devel patch wget libjpeg libjpeg-devel libpng libpng-devel libpng10 libpng10-devel gd gd-devel libxml2 libxml2-devel zlib zlib-devel glib2 glib2-devel tar bzip2 bzip2-devel libevent libevent-devel ncurses ncurses-devel curl curl-devel libcurl libcurl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel vim-minimal gettext gettext-devel ncurses-devel gmp-devel pspell-devel libcap diffutils ca-certificates net-tools libc-client-devel psmisc libXpm-devel git-core c-ares-devel libicu-devel libxslt libxslt-devel zip unzip glibc.i686 libstdc++.so.6 cairo-devel bison-devel ncurses-devel libaio-devel perl perl-devel perl-Data-Dumper lsof vixie-cron crontabs expat-devel readline-devel; do yum -y install $yumPack;done +dnf install libxml2 libxml2-devel -y + cd /www/server/mdserver-web/scripts && bash lib.sh chmod 755 /www/server/mdserver-web/data diff --git a/scripts/install/rocky.sh b/scripts/install/rocky.sh index c4cbcf1b5..f0cba70db 100644 --- a/scripts/install/rocky.sh +++ b/scripts/install/rocky.sh @@ -13,11 +13,11 @@ fi setenforce 0 sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config -yum install -y wget lsof crontabs +yum install -y wget lsof yum install -y python3-devel yum install -y python-devel -yum install -y vixie-cron - +yum install -y crontabs +yum install -y curl curl-devel libcurl libcurl-devel #https need if [ ! -d /root/.acme.sh ];then @@ -76,8 +76,17 @@ yum install -y lsof net-tools yum install -y ncurses-devel mysql-devel cmake yum install -y MySQL-python -for yumPack in make cmake gcc gcc-c++ gcc-g77 flex bison file libtool libtool-libs autoconf kernel-devel patch wget libjpeg libjpeg-devel libpng libpng-devel libpng10 libpng10-devel gd gd-devel libxml2 libxml2-devel zlib zlib-devel glib2 glib2-devel tar bzip2 bzip2-devel libevent libevent-devel ncurses ncurses-devel curl curl-devel libcurl libcurl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel vim-minimal gettext gettext-devel ncurses-devel gmp-devel pspell-devel libcap diffutils ca-certificates net-tools libc-client-devel psmisc libXpm-devel git-core c-ares-devel libicu-devel libxslt libxslt-devel zip unzip glibc.i686 libstdc++.so.6 cairo-devel bison-devel ncurses-devel libaio-devel perl perl-devel perl-Data-Dumper lsof vixie-cron crontabs expat-devel readline-devel; -do yum -y install $yumPack;done +for yumPack in make cmake gcc gcc-c++ flex bison file libtool libtool-libs autoconf kernel-devel patch wget libjpeg libjpeg-devel libpng libpng-devel gd gd-devel libxml2 libxml2-devel zlib zlib-devel glib2 glib2-devel tar bzip2 bzip2-devel libevent libevent-devel ncurses ncurses-devel curl curl-devel libcurl libcurl-devel e2fsprogs e2fsprogs-devel libidn libidn-devel vim-minimal gettext gettext-devel ncurses-devel gmp-devel libcap diffutils ca-certificates net-tools libc-client-devel psmisc libXpm-devel git-core c-ares-devel libicu-devel libxslt libxslt-devel zip unzip glibc.i686 libstdc++.so.6 cairo-devel bison-devel ncurses-devel libaio-devel perl perl-devel perl-Data-Dumper lsof crontabs expat-devel readline-devel; +do dnf --enablerepo=powertools install -y $yumPack;done + +yum install -y libtirpc libtirpc-devel + +dnf install boost-locale + +dnf --enablerepo=powertools install -y libmemcached libmemcached-devel +dnf --enablerepo=powertools install -y rpcgen +dnf --enablerepo=powertools install -y oniguruma oniguruma-devel +dnf --enablerepo=powertools install -y re2c bison cd /www/server/mdserver-web/scripts && bash lib.sh chmod 755 /www/server/mdserver-web/data diff --git a/scripts/lib.sh b/scripts/lib.sh index 8c16c5330..2ddedb25d 100755 --- a/scripts/lib.sh +++ b/scripts/lib.sh @@ -109,11 +109,6 @@ else yum install -y mysql-devel yum install -y oniguruma oniguruma-devel yum install -y ImageMagick ImageMagick-devel - - if [ "$OSNAME" == "fedora" ]; then - dnf install libxml2 libxml2-devel -y - - fi fi @@ -128,13 +123,10 @@ pip3 install --upgrade setuptools cd /www/server/mdserver-web && pip3 install -r /www/server/mdserver-web/requirements.txt pip3 install gevent-websocket==0.10.1 -pip3 install requests==2.20.0 pip3 install flask-caching==1.10.1 pip3 install flask-session==0.3.2 -pip3 install pymongo -pip3 install psutil pip3 install flask-socketio==5.2.0 -pip3 install mysqlclient +# pip3 install mysqlclient if [ ! -f /www/server/mdserver-web/bin/activate ];then @@ -149,11 +141,8 @@ pip3 install --upgrade setuptools pip3 install -r /www/server/mdserver-web/requirements.txt pip3 install gevent-websocket==0.10.1 -pip3 install requests==2.20.0 pip3 install flask-caching==1.10.1 pip3 install flask-session==0.3.2 -pip3 install pymongo -pip3 install psutil pip3 install flask-socketio==5.2.0 -pip3 install mysqlclient +# pip3 install mysqlclient diff --git a/scripts/update/fedora.sh b/scripts/update/fedora.sh index 231c2d532..353291eaa 100644 --- a/scripts/update/fedora.sh +++ b/scripts/update/fedora.sh @@ -11,8 +11,6 @@ fi sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config -yum install -y curl-devel libmcrypt libmcrypt-devel python36-devel - cd /www/server/mdserver-web/scripts && bash lib.sh chmod 755 /www/server/mdserver-web/data diff --git a/task.py b/task.py index 4989153d5..98e3cbe6b 100755 --- a/task.py +++ b/task.py @@ -392,7 +392,7 @@ def startPHPVersion(version): try: # system - phpService = '/lib/systemd/system/php' + version + '.service' + phpService = mw.systemdCfgDir() + '/php' + version + '.service' if os.path.exists(phpService): mw.execShell("systemctl restart php" + version) if checkPHPVersion(version): @@ -439,17 +439,40 @@ def startPHPVersion(version): return True -# 检查指定PHP版本 -def checkPHPVersion(version): +def getFpmConfFile(version): + return mw.getServerDir() + '/php/' + version + '/etc/php-fpm.d/www.conf' + + +def getFpmAddress(version): + fpm_address = '/tmp/php-cgi-{}.sock'.format(version) + php_fpm_file = getFpmConfFile(version) try: - url = 'http://127.0.0.1/phpfpm_status_' + version - result = mw.httpGet(url, 1) - if result.find('timed out'): - raise + content = readFile(php_fpm_file) + tmp = re.findall(r"listen\s*=\s*(.+)", content) + if not tmp: + return fpm_address + if tmp[0].find('sock') != -1: + return fpm_address + if tmp[0].find(':') != -1: + listen_tmp = tmp[0].split(':') + if bind: + fpm_address = (listen_tmp[0], int(listen_tmp[1])) + else: + fpm_address = ('127.0.0.1', int(listen_tmp[1])) + else: + fpm_address = ('127.0.0.1', int(tmp[0])) + return fpm_address + except: + return fpm_address + + +def checkPHPVersion(version): + # 检查指定PHP版本 + try: + sock = getFpmAddress(version) + data = mw.requestFcgiPHP(sock, '/phpfpm_status_' + version + '?json') + result = str(data, encoding='utf-8') except Exception as e: - url = 'http://' + mw.getLocalIp() + '/phpfpm_status_' + version - result = mw.httpGet(url, 1) - else: result = 'Bad Gateway' # print(version,result) @@ -468,7 +491,7 @@ def checkPHPVersion(version): return True # systemd - systemd = '/lib/systemd/system/openresty.service' + systemd = mw.systemdCfgDir() + '/openresty.service' if os.path.exists(systemd): execShell('systemctl reload openresty') return True