Merge pull request #149 from midoks/dev

mysql的优化 经典模式和GTID主从支持
pull/159/head
Mr Chen 3 years ago committed by GitHub
commit 8051a274d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 16
      README.md
  2. 5
      class/core/config_api.py
  3. 18
      class/core/mw.py
  4. 35
      class/core/site_api.py
  5. 27
      class/plugin/orm.py
  6. 0
      plugins/mariadb/conf/classic.cnf
  7. 4
      plugins/mariadb/conf/gtid.cnf
  8. 15
      plugins/mariadb/conf/mariadb.sql
  9. 15
      plugins/mariadb/conf/my.cnf
  10. 1
      plugins/mariadb/index.html
  11. 704
      plugins/mariadb/index.py
  12. 24
      plugins/mariadb/init.d/mariadb.tpl
  13. 1000
      plugins/mariadb/js/mariadb.js
  14. 125
      plugins/mariadb/scripts/backup.py
  15. 10
      plugins/mariadb/versions/10.6/install.sh
  16. 4
      plugins/mariadb/versions/10.7/install.sh
  17. 4
      plugins/mariadb/versions/10.8/install.sh
  18. 0
      plugins/mysql/conf/classic.cnf
  19. 4
      plugins/mysql/conf/gtid.cnf
  20. 34
      plugins/mysql/conf/my.cnf
  21. 34
      plugins/mysql/conf/my5.7.cnf
  22. 35
      plugins/mysql/conf/my8.0.cnf
  23. 3
      plugins/mysql/conf/mysql.sql
  24. 9
      plugins/mysql/index.html
  25. 656
      plugins/mysql/index.py
  26. 3
      plugins/mysql/init.d/mysql.tpl
  27. 3
      plugins/mysql/init.d/mysql8.0.tpl
  28. 507
      plugins/mysql/js/mysql.js
  29. 4
      plugins/mysql/versions/5.5/install.sh
  30. 4
      plugins/mysql/versions/5.6/install.sh
  31. 4
      plugins/mysql/versions/5.7/install.sh
  32. 4
      plugins/mysql/versions/8.0/install.sh
  33. 17
      plugins/op_waf/waf/lua/init.lua
  34. 18
      plugins/php-apt/versions/phplib.conf
  35. 107
      plugins/php/versions/common/bcmath.sh
  36. 2
      plugins/php/versions/common/gd.sh
  37. 2
      plugins/php/versions/common/gd_old.sh
  38. 2
      plugins/php/versions/common/yaf.sh
  39. 3
      plugins/php/versions/lib.sh
  40. 21
      plugins/php/versions/phplib.conf
  41. 5
      plugins/phpmyadmin/conf/phpmyadmin.conf
  42. 12
      plugins/phpmyadmin/index.py
  43. 5
      plugins/phpmyadmin/install.sh
  44. 43
      plugins/postgresql/conf/pgsql.sql
  45. BIN
      plugins/postgresql/ico.png
  46. 32
      plugins/postgresql/index.html
  47. 724
      plugins/postgresql/index.py
  48. 18
      plugins/postgresql/info.json
  49. 16
      plugins/postgresql/init.d/postgresql.service.tpl
  50. 66
      plugins/postgresql/init.d/postgresql.tpl
  51. 42
      plugins/postgresql/install.sh
  52. 1969
      plugins/postgresql/js/postgresql.js
  53. 101
      plugins/postgresql/versions/14.4/install.sh
  54. 2
      route/static/app/crontab.js
  55. 12
      scripts/backup.py
  56. 2
      scripts/init.d/mw.tpl
  57. 12
      scripts/install.sh
  58. 4
      scripts/lib.sh
  59. 10
      scripts/update.sh

@ -10,6 +10,7 @@
![Fedora](https://img.shields.io/badge/LINUX-Fedora-blue?style=for-the-badge&logo=Fedora)
[![Wiki](https://img.shields.io/badge/MW-Wiki-red?style=for-the-badge&logo=wiki)](https://github.com/midoks/mdserver-web/wiki)
[![](https://data.jsdelivr.com/v1/package/gh/midoks/mdserver-web/badge?style=for-the-badge)](https://www.jsdelivr.com/package/gh/midoks/mdserver-web)
* SSH终端工具
* 面板收藏功能
@ -59,6 +60,19 @@ docker run -itd --name mw-server --privileged=true -p 7200:7200 -p 80:80 -p 443:
* mysql主从配置。
* swap插件[虚拟内存]。
### jsdelivr [ 发布新版本生效 ]
- 初始安装
```
curl -fsSL https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/install.sh | bash
```
- 更新
```
curl -fsSL https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/update.sh | bash
```
### GW使用
@ -90,7 +104,7 @@ curl -fsSL https://gitee.com/midoks/mdserver-web/raw/master/scripts/update_cn.s
### 通用安装
### 通用软件安装
```
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/quick/app.sh | bash

@ -15,9 +15,8 @@ from flask import request
class config_api:
# 进行中.
# 兼容主流Linux系统
__version = '0.8.6.13'
# mariadb 优化
__version = '0.8.6.16'
def __init__(self):
pass

@ -98,7 +98,12 @@ def systemdCfgDir():
return cfg_dir
# debian,centos
return "/usr/lib/systemd/system"
cfg_dir = '/usr/lib/systemd/system'
if os.path.exists(cfg_dir):
return cfg_dir
# local test
return "/tmp"
def getOs():
@ -261,6 +266,17 @@ def getRandomString(length):
return str
def getUniqueId():
"""
根据时间生成唯一ID
:return:
"""
current_time = datetime.datetime.now()
str_time = current_time.strftime('%Y%m%d%H%M%S%f')[:-3]
unique_id = "{0}".format(str_time)
return unique_id
def getJson(data):
import json
return json.dumps(data)

@ -727,14 +727,14 @@ class site_api:
file = self.getHostConf(siteName)
conf = mw.readFile(file)
if conf:
# if conf.find('ssl_certificate') == -1:
# return mw.returnJson(False, '当前未开启SSL')
if conf.find('ssl_certificate') == -1:
return mw.returnJson(False, '当前未开启SSL')
to = """#error_page 404/404.html;
# HTTP_TO_HTTPS_START
#HTTP_TO_HTTPS_START
if ($server_port !~ 443){
rewrite ^(/.*)$ https://$host$1 permanent;
}
# HTTP_TO_HTTPS_END"""
#HTTP_TO_HTTPS_END"""
conf = conf.replace('#error_page 404/404.html;', to)
mw.writeFile(file, conf)
@ -2141,20 +2141,21 @@ location ^~ {from} {
content = content.replace('{$LOGPATH}', logsPath)
mw.writeFile(vhost_file, content)
rewrite_content = '''
location /{
if ($PHP_ENV != "1"){
break;
}
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php/$1 last;
break;
}
}
'''
# 和反代配置冲突 && 默认伪静态为空
# rewrite_content = '''
# location /{
# if ($PHP_ENV != "1"){
# break;
# }
# if (!-e $request_filename) {
# rewrite ^(.*)$ /index.php/$1 last;
# break;
# }
# }
# '''
rewrite_file = self.rewritePath + '/' + self.siteName + '.conf'
mw.writeFile(rewrite_file, rewrite_content)
mw.writeFile(rewrite_file, '')
def add(self, webname, port, ps, path, version):
siteMenu = json.loads(webname)

@ -24,13 +24,26 @@ class ORM:
'''连接数据库'''
try:
try:
self.__DB_CONN = pymysql.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS,
port=int(self.__DB_PORT), charset=self.__DB_CHARSET, connect_timeout=1, cursorclass=pymysql.cursors.DictCursor)
except Exception as e:
self.__DB_HOST = '127.0.0.1'
self.__DB_CONN = pymysql.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS,
port=int(self.__DB_PORT), charset=self.__DB_CHARSET, connect_timeout=1, cursorclass=pymysql.cursors.DictCursor)
if os.path.exists(self.__DB_SOCKET):
try:
self.__DB_CONN = pymysql.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS,
port=int(self.__DB_PORT), charset=self.__DB_CHARSET, connect_timeout=1,
unix_socket=self.__DB_SOCKET, cursorclass=pymysql.cursors.DictCursor)
except Exception as e:
self.__DB_HOST = '127.0.0.1'
self.__DB_CONN = pymysql.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS,
port=int(self.__DB_PORT), charset=self.__DB_CHARSET, connect_timeout=1,
unix_socket=self.__DB_SOCKET, cursorclass=pymysql.cursors.DictCursor)
else:
try:
self.__DB_CONN = pymysql.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS,
port=int(self.__DB_PORT), charset=self.__DB_CHARSET, connect_timeout=1,
cursorclass=pymysql.cursors.DictCursor)
except Exception as e:
self.__DB_HOST = '127.0.0.1'
self.__DB_CONN = pymysql.connect(host=self.__DB_HOST, user=self.__DB_USER, passwd=self.__DB_PASS,
port=int(self.__DB_PORT), charset=self.__DB_CHARSET, connect_timeout=1,
cursorclass=pymysql.cursors.DictCursor)
self.__DB_CUR = self.__DB_CONN.cursor()
return True

@ -0,0 +1,4 @@
[mysqld]
# SHOW GLOBAL VARIABLES LIKE '%gtid%'
gtid_mode=ON
enforce_gtid_consistency=ON

@ -12,9 +12,11 @@ CREATE TABLE IF NOT EXISTS `databases` (
`username` TEXT,
`password` TEXT,
`accept` TEXT,
`rw` TEXT DEFAULT 'rw',
`ps` TEXT,
`addtime` TEXT
);
-- ALTER TABLE `databases` ADD COLUMN `rw` TEXT DEFAULT 'rw';
CREATE TABLE IF NOT EXISTS `master_replication_user` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
@ -25,4 +27,17 @@ CREATE TABLE IF NOT EXISTS `master_replication_user` (
`addtime` TEXT
);
-- 从库配置主库的[ssh private key]
-- drop table `slave_id_rsa`;
CREATE TABLE IF NOT EXISTS `slave_id_rsa` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`ip` TEXT,
`port` TEXT,
`user` TEXT,
`db_user` TEXT,
`id_rsa` TEXT,
`ps` TEXT,
`addtime` TEXT
);

@ -5,6 +5,9 @@ port = 33106
socket = {$SERVER_APP_PATH}/mysql.sock
[mysqld]
!include {$SERVER_APP_PATH}/etc/mode/classic.cnf
pid-file = {$SERVER_APP_PATH}/data/mysql.pid
user = mysql
port = 33106
@ -12,7 +15,10 @@ 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
server-id = {$SERVER_ID}
default_storage_engine = InnoDB
key_buffer_size = 8M
max_allowed_packet = 100M
table_open_cache = 32
@ -30,8 +36,8 @@ max_connections = 500
max_connect_errors = 100
open_files_limit = 65535
skip-name-resolve = on
#skip-networking
#skip-name-resolve
#skip-external-locking
#loose-skip-innodb
#skip-grant-tables
@ -39,7 +45,6 @@ open_files_limit = 65535
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
@ -64,7 +69,7 @@ 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
@ -75,7 +80,7 @@ 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_write_io_threads = 2
innodb_file_per_table=1

@ -13,6 +13,7 @@
<p onclick="myLogs();">日志</p>
<p onclick="pluginLogs('mariadb',$('.plugin_version').attr('version'),'show_log');">慢日志</p>
<p onclick="dbList()">管理列表</p>
<p onclick="masterOrSlaveConf($('.plugin_version').attr('version'))">主从配置</p>
</div>
<div class="bt-w-con pd15">
<div class="soft-man-con"></div>

File diff suppressed because it is too large Load Diff

@ -1,4 +1,8 @@
#!/bin/sh
# chkconfig: 2345 55 25
# Description: mysql service
# distro. For CentOS/Redhat run: 'chkconfig --add mysql'
# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
# This file is public domain and comes with NO WARRANTY of any kind
@ -25,7 +29,7 @@
# 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
# If you install MySQL on some other places than /www/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
@ -110,7 +114,7 @@ mode=$1 # start or stop
[ $# -ge 1 ] && shift
other_args="$*" # uncommon, but needed when called from an RPM upgrade action
other_args=--sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" # 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.
@ -234,6 +238,11 @@ extra_args=""
if test -r "$basedir/my.cnf"
then
extra_args="-e $basedir/my.cnf"
else
if test -r "$datadir/my.cnf"
then
extra_args="-e $datadir/my.cnf"
fi
fi
parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server`
@ -241,9 +250,10 @@ parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server m
#
# Set pid file if not given
#
found_pid=`cd $datadir && ls |grep '.pid'`
if test -z "$mysqld_pid_file_path"
then
mysqld_pid_file_path=$datadir/`hostname`.pid
mysqld_pid_file_path=$datadir/$found_pid
else
case "$mysqld_pid_file_path" in
/* ) ;;
@ -251,6 +261,7 @@ else
esac
fi
#ulimit -s unlimited
case "$mode" in
'start')
# Start daemon
@ -263,7 +274,7 @@ case "$mode" in
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 &
$bindir/mysqld_safe --defaults-file=$basedir/etc/my.cnf --datadir="$datadir" $other_args >/dev/null &
wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?
# Make lock for RedHat / SuSE
@ -284,9 +295,6 @@ case "$mode" in
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)
@ -345,7 +353,7 @@ case "$mode" in
fi
else
# Try to find appropriate mysqld process
mysqld_pid=`pgrep -d' ' -f $libexecdir/mysqld`
mysqld_pid=`pidof $libexecdir/mysqld`
# test if multiple pids exist
pid_count=`echo $mysqld_pid | wc -w`

File diff suppressed because it is too large Load Diff

@ -0,0 +1,125 @@
# coding: utf-8
#-----------------------------
# 网站备份工具
#-----------------------------
import sys
import os
if sys.platform != 'darwin':
os.chdir('/www/server/mdserver-web')
chdir = os.getcwd()
sys.path.append(chdir + '/class/core')
# reload(sys)
# sys.setdefaultencoding('utf-8')
import mw
import db
import time
class backupTools:
def backupDatabase(self, name, count):
db_path = mw.getServerDir() + '/mariadb'
db_name = 'mysql'
name = mw.M('databases').dbPos(db_path, 'mysql').where(
'name=?', (name,)).getField('name')
startTime = time.time()
if not name:
endDate = time.strftime('%Y/%m/%d %X', time.localtime())
log = "数据库[" + name + "]不存在!"
print("★[" + endDate + "] " + log)
print(
"----------------------------------------------------------------------------")
return
backup_path = mw.getRootDir() + '/backup/database'
if not os.path.exists(backup_path):
mw.execShell("mkdir -p " + backup_path)
filename = backup_path + "/db_" + name + "_" + \
time.strftime('%Y%m%d_%H%M%S', time.localtime()) + ".sql.gz"
import re
mysql_root = mw.M('config').dbPos(db_path, db_name).where(
"id=?", (1,)).getField('mysql_root')
mycnf = mw.readFile(db_path + '/etc/my.cnf')
rep = "\[mysqldump\]\nuser=root"
sea = "[mysqldump]\n"
subStr = sea + "user=root\npassword=" + mysql_root + "\n"
mycnf = mycnf.replace(sea, subStr)
if len(mycnf) > 100:
mw.writeFile(db_path + '/etc/my.cnf', mycnf)
# mw.execShell(db_path + "/bin/mysqldump --opt --default-character-set=utf8 " +
# name + " | gzip > " + filename)
# mw.execShell(db_path + "/bin/mysqldump --skip-lock-tables --default-character-set=utf8 " +
# name + " | gzip > " + filename)
mw.execShell(db_path + "/bin/mysqldump --single-transaction --quick --default-character-set=utf8 " +
name + " | gzip > " + filename)
if not os.path.exists(filename):
endDate = time.strftime('%Y/%m/%d %X', time.localtime())
log = "数据库[" + name + "]备份失败!"
print("★[" + endDate + "] " + log)
print(
"----------------------------------------------------------------------------")
return
mycnf = mw.readFile(db_path + '/etc/my.cnf')
mycnf = mycnf.replace(subStr, sea)
if len(mycnf) > 100:
mw.writeFile(db_path + '/etc/my.cnf', mycnf)
endDate = time.strftime('%Y/%m/%d %X', time.localtime())
outTime = time.time() - startTime
pid = mw.M('databases').dbPos(db_path, db_name).where(
'name=?', (name,)).getField('id')
mw.M('backup').add('type,name,pid,filename,addtime,size', (1, os.path.basename(
filename), pid, filename, endDate, os.path.getsize(filename)))
log = "数据库[" + name + "]备份成功,用时[" + str(round(outTime, 2)) + "]秒"
mw.writeLog('计划任务', log)
print("★[" + endDate + "] " + log)
print("|---保留最新的[" + count + "]份备份")
print("|---文件名:" + filename)
# 清理多余备份
backups = mw.M('backup').where(
'type=? and pid=?', ('1', pid)).field('id,filename').select()
num = len(backups) - int(count)
if num > 0:
for backup in backups:
mw.execShell("rm -f " + backup['filename'])
mw.M('backup').where('id=?', (backup['id'],)).delete()
num -= 1
print("|---已清理过期备份文件:" + backup['filename'])
if num < 1:
break
def backupDatabaseAll(self, save):
db_path = mw.getServerDir() + '/mariadb'
db_name = 'mysql'
databases = mw.M('databases').dbPos(
db_path, db_name).field('name').select()
for database in databases:
self.backupDatabase(database['name'], save)
if __name__ == "__main__":
backup = backupTools()
type = sys.argv[1]
if type == 'database':
if sys.argv[2] == 'ALL':
backup.backupDatabaseAll(sys.argv[3])
else:
backup.backupDatabase(sys.argv[2], sys.argv[3])

@ -51,6 +51,10 @@ Install_app()
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -f ${mariadbDir}/mariadb-${MY_VER}.tar.gz ];then
@ -63,6 +67,11 @@ Install_app()
cd ${mariadbDir} && tar -zxvf ${mariadbDir}/mariadb-${MY_VER}.tar.gz
fi
OPTIONS=''
if [ "$sysName" == "Darwin" ];then
OPTIONS='-DPLUGIN_TOKUDB=NO'
fi
if [ ! -d $serverPath/mariadb ];then
cd ${mariadbDir}/mariadb-${MY_VER} && cmake \
@ -75,6 +84,7 @@ Install_app()
-DWITH_MEMORY_STORAGE_ENGINE=1 \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
$OPTIONS \
-DEXTRA_CHARSETS=all \
-DDEFAULT_CHARSET=utf8mb4 \
-DDEFAULT_COLLATION=utf8mb4_general_ci \

@ -51,6 +51,10 @@ Install_app()
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -f ${mariadbDir}/mariadb-${MY_VER}.tar.gz ];then

@ -51,6 +51,10 @@ Install_app()
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -f ${mariadbDir}/mariadb-${MY_VER}.tar.gz ];then

@ -0,0 +1,4 @@
[mysqld]
# SHOW GLOBAL VARIABLES LIKE '%gtid%'
gtid_mode=ON
enforce_gtid_consistency=ON

@ -5,6 +5,11 @@ port = 3306
socket = {$SERVER_APP_PATH}/mysql.sock
[mysqld]
!include {$SERVER_APP_PATH}/etc/mode/classic.cnf
sha256_password_private_key_path=mysql.pem
sha256_password_public_key_path=mysql.pub
pid-file = {$SERVER_APP_PATH}/data/mysql.pid
user = mysql
port = 3306
@ -12,9 +17,13 @@ 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
server-id = {$SERVER_ID}
default_storage_engine = InnoDB
key_buffer_size = 8M
max_allowed_packet = 100M
table_open_cache = 32
sort_buffer_size = 256K
net_buffer_length = 4K
@ -22,7 +31,7 @@ read_buffer_size = 128K
read_rnd_buffer_size = 256K
myisam_sort_buffer_size = 4M
thread_cache_size = 4
lower_case_table_names=1
lower_case_table_names=0
query_cache_size = 4M
tmp_table_size = 8M
@ -30,22 +39,21 @@ max_connections = 500
max_connect_errors = 100
open_files_limit = 65535
skip-name-resolve=1
#skip-grant-tables
#skip-networking
#skip-name-resolve
#skip-external-locking
#loose-skip-innodb
#skip-grant-tables
skip-ssl
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
long_query_time=10
#log_queries_not_using_indexes=on
#log_slow_admin_statements=1
#log_slow_slave_statements=1
expire_logs_days=30
relay-log=mdserver
relay-log-index=mdserver
@ -58,14 +66,15 @@ binlog-ignore-db = information_schema
binlog-ignore-db = performance_schema
#slave
log-slave-updates
log-slave-updates = 1
skip-slave-start = 1
#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
@ -73,12 +82,13 @@ innodb_buffer_pool_size = 16M
innodb_additional_mem_pool_size = 2M
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_flush_log_at_trx_commit = 2
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
innodb_large_prefix = 1
secure-file-priv={$SERVER_APP_PATH}/tmp

@ -6,6 +6,11 @@ socket = {$SERVER_APP_PATH}/mysql.sock
default-character-set = UTF8MB4
[mysqld]
!include {$SERVER_APP_PATH}/etc/mode/classic.cnf
;sha256_password_private_key_path=mysql.pem
;sha256_password_public_key_path=mysql.pub
pid-file = {$SERVER_APP_PATH}/data/mysql.pid
user = mysql
port = 3306
@ -13,7 +18,9 @@ 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
server-id = {$SERVER_ID}
default_storage_engine = InnoDB
key_buffer_size = 8M
table_open_cache = 32
@ -32,20 +39,21 @@ max_connect_errors = 100
open_files_limit = 2560
max_allowed_packet = 128M
skip_name_resolve = 1
#skip-networking
#skip-external-locking
#skip-grant-tables
#loose-skip-innodb
#skip-networking
#skip-name-resolve
skip-ssl
#skip-grant-tables
log-bin=mysql-bin
binlog_format=mixed
server-id = 1
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
long_query_time=10
#log_queries_not_using_indexes=1
#log_slow_admin_statements=1
#log_slow_slave_statements=1
expire_logs_days=30
relay-log=mdserver
relay-log-index=mdserver
@ -58,26 +66,28 @@ binlog-ignore-db = information_schema
binlog-ignore-db = performance_schema
#slave
log-slave-updates
log-slave-updates = 1
skip-slave-start = 1
#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_flush_log_at_trx_commit = 2
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
innodb_file_per_table = 1
innodb_large_prefix = 1
secure-file-priv={$SERVER_APP_PATH}/tmp

@ -6,7 +6,12 @@ socket = {$SERVER_APP_PATH}/mysql.sock
default-character-set = UTF8MB4
[mysqld]
default_authentication_plugin=mysql_native_password
!include {$SERVER_APP_PATH}/etc/mode/classic.cnf
sha256_password_private_key_path=mysql.pem
sha256_password_public_key_path=mysql.pub
authentication_policy=mysql_native_password
pid-file = {$SERVER_APP_PATH}/data/mysql.pid
user = mysql
port = 3306
@ -14,7 +19,9 @@ 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
server-id = {$SERVER_ID}
default_storage_engine = InnoDB
key_buffer_size = 8M
table_open_cache = 32
@ -33,21 +40,21 @@ max_connect_errors = 100
open_files_limit = 2560
max_allowed_packet = 128M
skip_name_resolve = 1
#skip-networking
#skip-external-locking
#skip-grant-tables
#loose-skip-innodb
#skip-networking
#skip-name-resolve
skip-ssl
#skip-grant-tables
log-bin=mysql-bin
binlog_format=mixed
server-id = 1
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
long_query_time=10
#log_queries_not_using_indexes=1
#log_slow_admin_statements=1
#log_slow_replica_statements=1
binlog_expire_logs_seconds=2592000
relay-log=mdserver
relay-log-index=mdserver
@ -60,27 +67,27 @@ binlog-ignore-db = information_schema
binlog-ignore-db = performance_schema
#slave
log_replica_updates
log_replica_updates = 1
skip_replica_start = 1
#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_flush_log_at_trx_commit = 2
innodb_lock_wait_timeout = 120
innodb_max_dirty_pages_pct = 90
innodb_read_io_threads = 1
innodb_write_io_threads = 1
innodb_file_per_table=1
binlog_expire_logs_seconds=2592000
secure-file-priv={$SERVER_APP_PATH}/tmp

@ -12,9 +12,11 @@ CREATE TABLE IF NOT EXISTS `databases` (
`username` TEXT,
`password` TEXT,
`accept` TEXT,
`rw` TEXT DEFAULT 'rw',
`ps` TEXT,
`addtime` TEXT
);
-- ALTER TABLE `databases` ADD COLUMN `rw` TEXT DEFAULT 'rw';
CREATE TABLE IF NOT EXISTS `master_replication_user` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
@ -32,6 +34,7 @@ CREATE TABLE IF NOT EXISTS `slave_id_rsa` (
`ip` TEXT,
`port` TEXT,
`user` TEXT,
`db_user` TEXT,
`id_rsa` TEXT,
`ps` TEXT,
`addtime` TEXT

@ -2,7 +2,7 @@
<div class='plugin_version'></div>
<div class="bt-w-main">
<div class="bt-w-menu">
<script type="text/javascript">console.log($('.plugin_version').attr('version'));</script>
<!-- <script type="text/javascript">console.log($('.plugin_version').attr('version'));</script> -->
<p class="bgw" onclick="pluginService('mysql', $('.plugin_version').attr('version'));">服务</p>
<p onclick="pluginInitD('mysql', $('.plugin_version').attr('version'));">自启动</p>
<p onclick="pluginConfig('mysql', $('.plugin_version').attr('version'));">配置文件</p>
@ -49,6 +49,13 @@
#db_tools button:last-child{
margin-right: 0;
}
.conf_p span {
display: inline-block;
margin-right: 10px;
width: 95px;
text-align: right;
}
</style>
<script type="text/javascript">
resetPluginWinWidth(800);

File diff suppressed because it is too large Load Diff

@ -250,9 +250,10 @@ parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server m
#
# Set pid file if not given
#
found_pid=`cd $datadir && ls |grep '.pid'`
if test -z "$mysqld_pid_file_path"
then
mysqld_pid_file_path=$datadir/`hostname`.pid
mysqld_pid_file_path=$datadir/$found_pid
else
case "$mysqld_pid_file_path" in
/* ) ;;

@ -241,9 +241,10 @@ parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server m
#
# Set pid file if not given
#
found_pid=`cd $datadir && ls |grep '.pid'`
if test -z "$mysqld_pid_file_path"
then
mysqld_pid_file_path=$datadir/`hostname`.pid
mysqld_pid_file_path=$datadir/$found_pid
else
case "$mysqld_pid_file_path" in
/* ) ;;

@ -526,6 +526,17 @@ function checkSelect(){
},5)
}
function setDbRw(id,username,val){
myPost('get_db_rw',{id:id,username:username,rw:val}, function(data){
var rdata = $.parseJSON(data.data);
// layer.msg(rdata.msg,{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']});
showMsg(rdata.msg, function(){
dbList();
},{icon:rdata.status ? 1 : 5,shade: [0.3, '#000']}, 2000);
});
}
function setDbAccess(username){
myPost('get_db_access','username='+username, function(data){
var rdata = $.parseJSON(data.data);
@ -540,8 +551,9 @@ function setDbAccess(username){
title: '设置数据库权限',
closeBtn: 1,
shift: 5,
btn:["提交","取消"],
shadeClose: true,
content: "<form class='bt-form pd20 pb70' id='set_db_access'>\
content: "<form class='bt-form pd20' id='set_db_access'>\
<div class='line'>\
<span class='tname'>访问权限</span>\
<div class='info-r '>\
@ -552,65 +564,54 @@ function setDbAccess(username){
</select>\
</div>\
</div>\
<div class='bt-form-submit-btn'>\
<button id='my_mod_close' type='button' class='btn btn-danger btn-sm btn-title'>关闭</button>\
<button id='my_mod_save' type='button' class='btn btn-success btn-sm btn-title'>提交</button>\
</div>\
</form>",
});
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("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true);
$('select[name="dataAccess"]').after("<input value='"+rdata.msg+"' id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
}
});
$('#my_mod_close').click(function(){
$('.layui-layer-close1').click();
});
$('select[name="dataAccess"]').change(function(){
var v = $(this).val();
if (v == 'ip'){
$(this).after("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('#dataAccess_subid').remove();
}
});
success:function(){
if (rdata.msg == '127.0.0.1'){
$('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true);
} else if (rdata.msg == '%'){
$('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true);
} else if ( rdata.msg == 'ip' ){
$('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true);
$('select[name="dataAccess"]').after("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true);
$('select[name="dataAccess"]').after("<input value='"+rdata.msg+"' id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
}
$('#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;
$('select[name="dataAccess"]').change(function(){
var v = $(this).val();
if (v == 'ip'){
$(this).after("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('#dataAccess_subid').remove();
}
});
},
yes:function(index){
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['access'] = dataObj['address'];
}
dataObj['username'] = username;
myPost('set_db_access', dataObj, function(data){
var rdata = $.parseJSON(data.data);
showMsg(rdata.msg,function(){
layer.close(index);
dbList();
},{icon: rdata.status ? 1 : 2});
});
}
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});
});
});
});
}
@ -618,13 +619,13 @@ function setDbPass(id, username, password){
var index = layer.open({
type: 1,
skin: 'demo-class',
area: '500px',
title: '修改数据库密码',
closeBtn: 1,
shift: 5,
shadeClose: true,
content: "<form class='bt-form pd20 pb70' id='mod_pwd'>\
btn:["提交","关闭"],
content: "<form class='bt-form pd20' id='mod_pwd'>\
<div class='line'>\
<span class='tname'>用户名</span>\
<div class='info-r'><input readonly='readonly' name=\"name\" class='bt-input-text mr5' type='text' style='width:330px;outline:none;' value='"+username+"' /></div>\
@ -634,26 +635,17 @@ function setDbPass(id, username, password){
<div class='info-r'><input class='bt-input-text mr5' type='text' name='password' id='MyPassword' style='width:330px' value='"+password+"' /><span title='随机密码' class='glyphicon glyphicon-repeat cursor' onclick='repeatPwd(16)'></span></div>\
</div>\
<input type='hidden' name='id' value='"+id+"'>\
<div class='bt-form-submit-btn'>\
<button id='my_mod_close' type='button' class='btn btn-danger btn-sm btn-title'>关闭</button>\
<button id='my_mod_save' type='button' class='btn btn-success btn-sm btn-title'>提交</button>\
</div>\
</form>",
});
$('#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});
});
yes:function(index){
var data = $("#mod_pwd").serialize();
myPost('set_user_pwd', data, function(data){
var rdata = $.parseJSON(data.data);
showMsg(rdata.msg,function(){
layer.close(index);
dbList();
},{icon: rdata.status ? 1 : 2});
});
}
});
}
@ -968,9 +960,28 @@ function dbList(page, search){
list += '<a href="javascript:;" class="btlink" class="btlink" onclick="setBackup(\''+rdata.data[i]['name']+'\',this)" title="数据库备份">'+(rdata.data[i]['is_backup']?'备份':'未备份') +'</a> | ';
var rw = '';
var rw_change = 'all';
if (typeof(rdata.data[i]['rw'])!='undefined'){
var rw_val = '读写';
if (rdata.data[i]['rw'] == 'all'){
rw_val = "所有";
rw_change = 'rw';
} else if (rdata.data[i]['rw'] == 'rw'){
rw_val = "读写";
rw_change = 'r';
} else if (rdata.data[i]['rw'] == 'r'){
rw_val = "只读";
rw_change = 'all';
}
rw = '<a href="javascript:;" class="btlink" onclick="setDbRw(\''+rdata.data[i]['id']+'\',\''+rdata.data[i]['name']+'\',\''+rw_change+'\')" title="设置读写">'+rw_val+'</a> | ';
}
list += '<a href="javascript:;" class="btlink" onclick="openPhpmyadmin(\''+rdata.data[i]['name']+'\',\''+rdata.data[i]['username']+'\',\''+rdata.data[i]['password']+'\')" title="数据库管理">管理</a> | ' +
'<a href="javascript:;" class="btlink" onclick="repTools(\''+rdata.data[i]['name']+'\')" title="MySQL优化修复工具">工具</a> | ' +
'<a href="javascript:;" class="btlink" onclick="setDbAccess(\''+rdata.data[i]['username']+'\')" title="设置数据库权限">权限</a> | ' +
rw +
'<a href="javascript:;" class="btlink" onclick="setDbPass('+rdata.data[i]['id']+',\''+ rdata.data[i]['username'] +'\',\'' + rdata.data[i]['password'] + '\')">改密</a> | ' +
'<a href="javascript:;" class="btlink" onclick="delDb(\''+rdata.data[i]['id']+'\',\''+rdata.data[i]['name']+'\')" title="删除数据库">删除</a>' +
'</td>';
@ -1034,9 +1045,9 @@ function myLogs(){
var line_status = ""
if (rdata.status){
line_status = '<button class="btn btn-success btn-xs btn-bin va0">关闭</button>\
<button class="btn btn-success btn-xs clean-btn-bin va0">清理BINLOG日志</button>'
<button class="btn btn-success btn-xs clean-btn-bin va0">清理BINLOG日志</button>';
} else {
line_status = '<button class="btn btn-success btn-xs btn-bin va0">开启</button>'
line_status = '<button class="btn btn-success btn-xs btn-bin va0">开启</button>';
}
var limitCon = '<p class="conf_p">\
@ -1044,7 +1055,7 @@ function myLogs(){
'+line_status+'\
<p class="f14 c6 mtb10" style="border-top:#ddd 1px solid; padding:10px 0">错误日志<button class="btn btn-default btn-clear btn-xs" style="float:right;" >清理日志</button></p>\
<textarea readonly style="margin: 0px;width: 100%;height: 440px;background-color: #333;color:#fff; padding:0 5px" id="error_log"></textarea>\
</p>'
</p>';
$(".soft-man-con").html(limitCon);
//设置二进制日志
@ -1081,7 +1092,7 @@ function myLogs(){
} else {
error_body = rdata.msg;
}
$("#error_log").text(error_body);
$("#error_log").html(error_body);
var ob = document.getElementById('error_log');
ob.scrollTop = ob.scrollHeight;
});
@ -1253,78 +1264,57 @@ function setDbSlave(name){
function addMasterRepSlaveUser(){
var index = layer.open({
layer.open({
type: 1,
skin: 'demo-class',
area: '500px',
title: '添加同步账户',
closeBtn: 1,
shift: 5,
shadeClose: true,
content: "<form class='bt-form pd20 pb70' id='add_master'>\
btn:["提交","取消"],
content: "<form class='bt-form pd20' id='add_master'>\
<div class='line'><span class='tname'>用户名</span><div class='info-r'><input name='username' class='bt-input-text mr5' placeholder='' type='text' style='width:330px;' value='"+(randomStrPwd(6))+"'></div></div>\
<div class='line'>\
<span class='tname'>密码</span>\
<div class='info-r'><input class='bt-input-text mr5' type='text' name='password' id='MyPassword' style='width:330px' value='"+(randomStrPwd(16))+"' /><span title='随机密码' class='glyphicon glyphicon-repeat cursor' onclick='repeatPwd(16)'></span></div>\
</div>\
<input type='hidden' name='ps' value='' />\
<div class='bt-form-submit-btn'>\
<button id='my_mod_close' type='button' class='btn btn-danger btn-sm btn-title'>关闭</button>\
<button type='button' class='btn btn-success btn-sm btn-title' id='submit_add_master' >提交</button>\
</div>\
</form>",
});
// <div class='line'>\
// <span class='tname'>访问权限</span>\
// <div class='info-r '>\
// <select class='bt-input-text mr5' name='dataAccess' style='width:100px'>\
// <option value='127.0.0.1'>本地服务器</option>\
// <option value=\"%\">所有人</option>\
// <option value='ip'>指定IP</option>\
// </select>\
// </div>\
// </div>\
success:function(){
$("input[name='name']").keyup(function(){
var v = $(this).val();
$("input[name='db_user']").val(v);
$("input[name='ps']").val(v);
});
$("input[name='name']").keyup(function(){
var v = $(this).val();
$("input[name='db_user']").val(v);
$("input[name='ps']").val(v);
});
$('select[name="dataAccess"]').change(function(){
var v = $(this).val();
if (v == 'ip'){
$(this).after("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('#dataAccess_subid').remove();
}
});
},
yes:function(index){
var data = $("#add_master").serialize();
data = decodeURIComponent(data);
var dataObj = str2Obj(data);
if(!dataObj['address']){
dataObj['address'] = dataObj['dataAccess'];
}
$('#my_mod_close').click(function(){
$('.layui-layer-close1').click();
});
$('select[name="dataAccess"]').change(function(){
var v = $(this).val();
if (v == 'ip'){
$(this).after("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('#dataAccess_subid').remove();
myPost('add_master_rep_slave_user', dataObj, function(data){
var rdata = $.parseJSON(data.data);
showMsg(rdata.msg,function(){
layer.close(index);
if (rdata.status){
getMasterRepSlaveList();
}
},{icon: rdata.status ? 1 : 2},600);
});
}
});
$('#submit_add_master').click(function(){
var data = $("#add_master").serialize();
data = decodeURIComponent(data);
var dataObj = str2Obj(data);
if(!dataObj['address']){
dataObj['address'] = dataObj['dataAccess'];
}
// console.log(dataObj);
myPost('add_master_rep_slave_user', dataObj, function(data){
var rdata = $.parseJSON(data.data);
showMsg(rdata.msg,function(){
if (rdata.status){
getMasterRepSlaveList();
}
$('.layui-layer-close1').click();
},{icon: rdata.status ? 1 : 2},600);
});
});
}
@ -1376,22 +1366,24 @@ function getMasterRepSlaveUserCmd(username, db=''){
return;
}
var cmd = rdata.data['cmd'];
var loadOpen = layer.open({
type: 1,
title: '同步命令',
area: '500px',
content:"<form class='bt-form pd20 pb70' id='add_master'>\
<div class='line'>"+rdata.data+"</div>\
<div class='line'>"+cmd+"</div>\
<div class='bt-form-submit-btn'>\
<button type='button' class='btn btn-success btn-sm btn-title class-copy-cmd'>复制</button>\
</div>\
</form>",
});
copyPass(rdata.data);
copyPass(cmd);
$('.class-copy-cmd').click(function(){
copyPass(rdata.data);
copyPass(cmd);
});
});
}
@ -1409,6 +1401,84 @@ function delMasterRepSlaveUser(username){
});
}
function setDbMasterAccess(username){
myPost('get_db_access','username='+username, function(data){
var rdata = $.parseJSON(data.data);
if (!rdata.status){
layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']});
return;
}
var index = layer.open({
type: 1,
area: '500px',
title: '设置数据库权限',
closeBtn: 1,
shift: 5,
btn:["提交","取消"],
shadeClose: true,
content: "<form class='bt-form pd20' id='set_db_access'>\
<div class='line'>\
<span class='tname'>访问权限</span>\
<div class='info-r '>\
<select class='bt-input-text mr5' name='dataAccess' style='width:100px'>\
<option value='127.0.0.1'>本地服务器</option>\
<option value=\"%\">所有人</option>\
<option value='ip'>指定IP</option>\
</select>\
</div>\
</div>\
</form>",
success:function(){
if (rdata.msg == '127.0.0.1'){
$('select[name="dataAccess"]').find("option[value='127.0.0.1']").attr("selected",true);
} else if (rdata.msg == '%'){
$('select[name="dataAccess"]').find('option[value="%"]').attr("selected",true);
} else if ( rdata.msg == 'ip' ){
$('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true);
$('select[name="dataAccess"]').after("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('select[name="dataAccess"]').find('option[value="ip"]').attr("selected",true);
$('select[name="dataAccess"]').after("<input value='"+rdata.msg+"' id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
}
$('select[name="dataAccess"]').change(function(){
var v = $(this).val();
if (v == 'ip'){
$(this).after("<input id='dataAccess_subid' class='bt-input-text mr5' type='text' name='address' placeholder='多个IP使用逗号(,)分隔' style='width: 230px; display: inline-block;'>");
} else {
$('#dataAccess_subid').remove();
}
});
},
yes:function(index){
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;
myPost('set_dbmaster_access', dataObj, function(data){
var rdata = $.parseJSON(data.data);
showMsg(rdata.msg,function(){
layer.close(index);
},{icon: rdata.status ? 1 : 2});
});
}
});
});
}
function getMasterRepSlaveList(){
var _data = {};
if (typeof(page) =='undefined'){
@ -1436,30 +1506,37 @@ function getMasterRepSlaveList(){
<td>\
<a class="btlink" onclick="updateMasterRepSlaveUser(\''+name+'\');">修改</a> | \
<a class="btlink" onclick="delMasterRepSlaveUser(\''+name+'\');">删除</a> | \
<a class="btlink" onclick="setDbMasterAccess(\''+name+'\');">权限</a> | \
<a class="btlink" onclick="getMasterRepSlaveUserCmd(\''+name+'\');">从库同步命令</a>\
</td>\
</tr>';
}
var page = '<div class="dataTables_paginate_4 dataTables_paginate paging_bootstrap page" style="margin-top:0px;"></div>';
page += '<div class="table_toolbar" style="left:0px;"><span class="sync btn btn-default btn-sm" onclick="addMasterRepSlaveUser()" title="">添加同步账户</span></div>';
$('#get_master_rep_slave_list_page tbody').html(list);
$('.dataTables_paginate_4').html(rdata['page']);
});
}
var loadOpen = layer.open({
type: 1,
title: '同步账户列表',
area: '500px',
content:"<div class='bt-form pd20 c6'>\
<div class='divtable mtb10'>\
<div><table class='table table-hover'>\
<thead><tr><th>用户名</th><th></th><th></th></tr></thead>\
<tbody>" + list + "</tbody>\
</table></div>\
"+page +"\
</div>\
</div>"
});
function getMasterRepSlaveListPage(){
var page = '<div class="dataTables_paginate_4 dataTables_paginate paging_bootstrap page" style="margin-top:0px;"></div>';
page += '<div class="table_toolbar" style="left:0px;"><span class="sync btn btn-default btn-sm" onclick="addMasterRepSlaveUser()" title="">添加同步账户</span></div>';
$('.dataTables_paginate_4').html(rdata['page']);
var loadOpen = layer.open({
type: 1,
title: '同步账户列表',
area: '500px',
content:"<div class='bt-form pd20 c6'>\
<div class='divtable mtb10' id='get_master_rep_slave_list_page'>\
<div><table class='table table-hover'>\
<thead><tr><th>用户名</th><th></th><th></th></tr></thead>\
<tbody></tbody>\
</table></div>\
"+page +"\
</div>\
</div>",
success:function(){
getMasterRepSlaveList();
}
});
}
@ -1467,11 +1544,9 @@ function getMasterRepSlaveList(){
function deleteSlave(){
myPost('delete_slave', {}, function(data){
var rdata = $.parseJSON(data.data);
layer.msg(rdata['msg']);
setTimeout(function(){
showMsg(rdata['msg'], function(){
masterOrSlaveConf();
}, 3000);
},{},3000);
});
}
@ -1537,16 +1612,18 @@ function addSlaveSSH(ip=''){
var ip = '127.0.0.1';
var port = "22";
var id_rsa = '';
var db_user ='';
if (rdata.data.length>0){
ip = rdata.data[0]['ip'];
port = rdata.data[0]['port'];
id_rsa = rdata.data[0]['id_rsa'];
db_user = rdata.data[0]['db_user'];
}
var index = layer.open({
type: 1,
area: ['500px','400px'],
area: ['500px','480px'],
title: '添加SSH',
closeBtn: 1,
shift: 5,
@ -1554,19 +1631,24 @@ function addSlaveSSH(ip=''){
btn:["确认","取消"],
content: "<form class='bt-form pd20'>\
<div class='line'><span class='tname'>IP</span><div class='info-r'><input name='ip' class='bt-input-text mr5' type='text' style='width:330px;' value='"+ip+"'></div></div>\
<div class='line'><span class='tname'>端口</span><div class='info-r'><input name='port' class='bt-input-text mr5' type='text' style='width:330px;' value='"+port+"'></div></div>\
<div class='line'><span class='tname'>端口</span><div class='info-r'><input name='port' class='bt-input-text mr5' type='number' style='width:330px;' value='"+port+"'></div></div>\
<div class='line'><span class='tname'>同步账户[DB]</span><div class='info-r'><input name='db_user' placeholder='!' class='bt-input-text mr5' type='text' style='width:330px;' value='"+db_user+"'></div></div>\
<div class='line'>\
<span class='tname'>ID_RSA</span>\
<div class='info-r'><textarea class='bt-input-text mr5' row='20' cols='50' name='id_rsa' style='width:330px;height:200px;'>"+id_rsa+"</textarea></div>\
<div class='info-r'><textarea class='bt-input-text mr5' row='20' cols='50' name='id_rsa' style='width:330px;height:200px;'></textarea></div>\
</div>\
<input type='hidden' name='ps' value='' />\
</form>",
success:function(){},
success:function(){
$('textarea[name="id_rsa"]').html(id_rsa);
},
yes:function(index){
var ip = $('input[name="ip"]').val();
var port = $('input[name="port"]').val();
var db_user = $('input[name="db_user"]').val();
var id_rsa = $('textarea[name="id_rsa"]').val();
var data = {ip:ip,port:port,id_rsa:id_rsa};
var data = {ip:ip,port:port,id_rsa:id_rsa,db_user:db_user};
myPost('add_slave_ssh', data, function(data){
layer.close(index);
var rdata = $.parseJSON(data.data);
@ -1608,9 +1690,21 @@ function getSlaveSSHPage(page=1){
for (i in ssh_list) {
var ip = ssh_list[i]['ip'];
var port = ssh_list[i]['port'];
var id_rsa = '未设置';
if ( ssh_list[i]['port'] != ''){
id_rsa = '已设置';
}
var db_user = '未设置';
if ( ssh_list[i]['db_user'] != ''){
db_user = ssh_list[i]['db_user'];
}
list += '<tr><td>'+ip+'</td>\
<td>'+port+'</td>\
<td>OK</td>\
<td>'+db_user+'</td>\
<td>'+id_rsa+'</td>\
<td>\
<a class="btlink" onclick="addSlaveSSH(\''+ip+'\');">修改</a> | \
<a class="btlink" onclick="delSlaveSSH(\''+ip+'\');">删除</a>\
@ -1636,23 +1730,22 @@ function getSlaveSSHList(page=1){
content:"<div class='bt-form pd20 c6'>\
<div class='divtable mtb10'>\
<div><table class='table table-hover get-slave-ssh-list'>\
<thead><tr><th>IP</th><th>PORT</th><th>SSH</th><th></th></tr></thead>\
<thead><tr><th>IP</th><th>PORT</th><th></th><th>SSH</th><th></th></tr></thead>\
<tbody></tbody>\
</table></div>\
"+page +"\
</div>\
</div>",
success:function(){
getSlaveSSHPage(1);
}
});
getSlaveSSHPage(1);
}
function handlerRun(){
myPostN('get_slave_sync_cmd', {}, function(data){
var rdata = $.parseJSON(data.data);
var cmd = rdata.data;
var cmd = rdata['data'];
var loadOpen = layer.open({
type: 1,
title: '手动执行',
@ -1671,6 +1764,17 @@ function handlerRun(){
});
}
function initSlaveStatus(){
myPost('init_slave_status', '', function(data){
var rdata = $.parseJSON(data.data);
showMsg(rdata.msg,function(){
if (rdata.status){
masterOrSlaveConf();
}
},{icon:rdata.status?1:2},2000);
});
}
function masterOrSlaveConf(version=''){
function getMasterDbList(){
@ -1709,7 +1813,7 @@ function masterOrSlaveConf(version=''){
</div>\
<div id="databasePage" class="dataTables_paginate paging_bootstrap page"></div>\
<div class="table_toolbar" style="left:0px;">\
<span class="sync btn btn-default btn-sm" onclick="getMasterRepSlaveList()" title="">同步账户列表</span>\
<span class="sync btn btn-default btn-sm" onclick="getMasterRepSlaveListPage()" title="">同步账户列表</span>\
</div>\
</div>';
@ -1813,7 +1917,6 @@ function masterOrSlaveConf(version=''){
<div class="table_toolbar" style="left:0px;">\
<span class="sync btn btn-default btn-sm" onclick="handlerRun()" title="免登录设置后,需要手动执行一下!">手动命令</span>\
<span class="sync btn btn-default btn-sm" onclick="getFullSyncStatus(\'ALL\')" title="全量同步">全量同步</span>\
<span class="sync btn btn-default btn-sm" onclick="getSlaveSSHList()" title="[主]SSH配置">[]SSH配置</span>\
</div>\
</div>';
@ -1822,20 +1925,36 @@ function masterOrSlaveConf(version=''){
});
}
function getMasterStatus(){
myPost('get_master_status', '', function(data){
var rdata = $.parseJSON(data.data);
var limitCon = '<p class="conf_p">\
// console.log('mode:',rdata.data);
var rdata = rdata.data;
var limitCon = '\
<p class="conf_p">\
<span class="f14 c6 mr20">主从同步模式</span><span class="f14 c6 mr20"></span>\
<button class="btn '+(!(rdata.mode == "classic") ? 'btn-danger' : 'btn-success')+' btn-xs db-mode btn-classic">经典</button>\
<button class="btn '+(!(rdata.mode == "gtid") ? 'btn-danger' : 'btn-success')+' btn-xs db-mode btn-gtid">GTID</button>\
</p>\
<hr/>\
<p class="conf_p">\
<span class="f14 c6 mr20">Master[]配置</span><span class="f14 c6 mr20"></span>\
<button class="btn '+(!rdata.status ? 'btn-danger' : 'btn-success')+' btn-xs btn-master va0">'+(!rdata.status ? '未开启' : '已开启') +'</button><hr/>\
<button class="btn '+(!rdata.status ? 'btn-danger' : 'btn-success')+' btn-xs btn-master">'+(!rdata.status ? '未开启' : '已开启') +'</button>\
</p>\
<hr/>\
<!-- master list -->\
<div class="safe bgw table_master_list"></div>\
<hr/>\
<!-- class="conf_p" -->\
<p class="conf_p">\
<span class="f14 c6 mr20">Slave[]配置</span><span class="f14 c6 mr20"></span>\
<button class="btn '+(!rdata.data.slave_status ? 'btn-danger' : 'btn-success')+' btn-xs btn-slave va0">'+(!rdata.data.slave_status ? '未启动' : '已启动') +'</button><hr/>\
<button class="btn '+(!rdata.slave_status ? 'btn-danger' : 'btn-success')+' btn-xs btn-slave">'+(!rdata.slave_status ? '未启动' : '已启动') +'</button>\
<button class="btn btn-success btn-xs" onclick="getSlaveSSHList()" >[]SSH配置</button>\
<button class="btn btn-success btn-xs" onclick="initSlaveStatus()" >初始化</button>\
</p>\
<hr/>\
<!-- slave status list -->\
<div class="safe bgw table_slave_status_list"></div>\
<!-- slave list -->\
@ -1864,11 +1983,49 @@ function masterOrSlaveConf(version=''){
});
});
$('.db-mode').click(function(){
if ($(this).hasClass('btn-success')){
//no action
return;
}
var mode = 'classic';
if ($(this).hasClass('btn-gtid')){
mode = 'gtid';
}
layer.open({
type:1,
title:"MySQL主从模式切换",
shadeClose:false,
btnAlign: 'c',
btn: ['切换并重启', '切换不重启'],
yes: function(index, layero){
this.change(index,mode,"yes");
},
btn2: function(index, layero){
this.change(index,mode,"no");
return false;
},
change:function(index,mode,reload){
console.log(index,mode,reload);
myPost('set_dbrun_mode',{'mode':mode,'reload':reload},function(data){
layer.close(index);
var rdata = $.parseJSON(data.data);
showMsg(rdata.msg ,function(){
getMasterStatus();
},{ icon: rdata.status ? 1 : 5 });
});
}
});
});
if (rdata.status){
getMasterDbList();
}
if (rdata.data.slave_status){
if (rdata.slave_status){
getAsyncMasterDbList();
getAsyncDataList()
}

@ -50,6 +50,10 @@ Install_mysql()
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -f ${mysqlDir}/mysql-5.5.62.tar.gz ];then

@ -53,6 +53,10 @@ Install_mysql()
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------

@ -55,6 +55,10 @@ Install_mysql()
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
cd $serverPath/mdserver-web/plugins/mysql/lib && /bin/bash rpcgen.sh

@ -92,6 +92,10 @@ Install_mysql()
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
cd $serverPath/mdserver-web/plugins/mysql/lib && /bin/bash rpcgen.sh

@ -214,16 +214,15 @@ function cc()
insert_ip_list(ip,lock_time,os.time(),server_name)
end
-- ngx.exit(config['cc']['status'])
-- return true
-- else
-- ngx.shared.limit:incr(token,1)
-- end
-- else
-- ngx.shared.limit:set(token,1,cycle)
-- end
-- end
ngx.exit(config['cc']['status'])
return true
else
ngx.shared.limit:incr(token,1)
end
else
ngx.shared.limit:set(token,1,cycle)
end
end
--强制验证是否使用正常浏览器访问网站
function waf_cc_increase()

@ -126,6 +126,24 @@
"shell": "mcrypt.sh",
"check": "mcrypt"
},
{
"name": "bcmath",
"versions": [
"56",
"70",
"71",
"72",
"73",
"74",
"80",
"81",
"82"
],
"type": "通用扩展",
"msg": "高精度计算!",
"shell": "bcmath.sh",
"check": "bcmath.so"
},
{
"name": "fileinfo",
"versions": [

@ -0,0 +1,107 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
curPath=`pwd`
appPath=$(dirname "$curPath")
rootPath=$(dirname "$curPath")
rootPath=$(dirname "$rootPath")
rootPath=$(dirname "$rootPath")
rootPath=$(dirname "$rootPath")
serverPath=$(dirname "$rootPath")
sourcePath=${serverPath}/source/php
actionType=$1
version=$2
LIBNAME=bcmath
LIBV=0
LIB_PATH_NAME=lib/php
if [ -d $serverPath/php/${version}/lib64 ];then
LIB_PATH_NAME=lib64
fi
NON_ZTS_FILENAME=`ls $serverPath/php/${version}/${LIB_PATH_NAME}/extensions | grep no-debug-non-zts`
extFile=$serverPath/php/${version}/${LIB_PATH_NAME}/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so
sysName=`uname`
if [ "$sysName" == "Darwin" ];then
BAK='_bak'
else
BAK=''
fi
# export PKG_CONFIG_PATH=/www/server/lib/libzip/lib/pkgconfig
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
./configure --with-php-config=$serverPath/php/$version/bin/php-config
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
bash ${rootPath}/plugins/php/versions/lib.sh $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

@ -79,7 +79,7 @@ Install_lib()
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
bash ${rootPath}/plugins/php/versions/lib.sh $version restart
echo '==========================================================='
echo 'successful!'
}

@ -89,7 +89,7 @@ Install_lib()
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
bash ${rootPath}/plugins/php/versions/lib.sh $version restart
echo '==========================================================='
echo 'successful!'
}

@ -109,7 +109,7 @@ Uninstall_lib()
sed -i $BAK "/${LIBNAME}.use_namespace/d" $serverPath/php/$version/etc/php.ini
sed -i $BAK "/\[${LIBNAME}\]/d" $serverPath/php/$version/etc/php.ini
rm -f $extFile
rm -rf $extFile
bash ${rootPath}/plugins/php/versions/lib.sh $version restart
echo '==============================================='
echo 'successful!'

@ -6,6 +6,7 @@ curPath=`pwd`
rootPath=$(dirname "$curPath")
rootPath=$(dirname "$rootPath")
rootPath=$(dirname "$rootPath")
rootPath=$(dirname "$rootPath")
serverPath=$(dirname "$rootPath")
version=$1
@ -13,7 +14,7 @@ action=$2
if [ -f /lib/systemd/system/php${version}.service ];then
systemctl ${action} php${version}
elif [[ -f /usr/lib/systemd/system/php${version}.service ]]; then
elif [ -f /usr/lib/systemd/system/php${version}.service ]; then
systemctl ${action} php${version}
else
$serverPath/php/init.d/php${version} ${action}

@ -98,6 +98,27 @@
"shell": "mcrypt.sh",
"check": "mcrypt.so"
},
{
"name": "bcmath",
"versions": [
"53",
"54",
"55",
"56",
"70",
"71",
"72",
"73",
"74",
"80",
"81",
"82"
],
"type": "通用扩展",
"msg": "高精度计算!",
"shell": "bcmath.sh",
"check": "bcmath.so"
},
{
"name": "pcntl",
"versions": [

@ -18,6 +18,11 @@ server
expires 12h;
}
location ~ /.*\.log$ {
deny all;
}
location ~ /\.
{
deny all;

@ -139,6 +139,14 @@ def start():
centent = contentReplace(centent)
mw.writeFile(conf_run, centent)
log_a = accessLog()
log_e = errorLog()
for i in [log_a, log_e]:
if os.path.exists(i):
cmd = "echo '' > " + i
mw.execShell(cmd)
mw.restartWeb()
return 'ok'
@ -217,11 +225,11 @@ def setPmaPort():
def accessLog():
return getServerDir() + '/phpmyadmin/access.log'
return getServerDir() + '/access.log'
def errorLog():
return getServerDir() + '/phpmyadmin/error.log'
return getServerDir() + '/error.log'
def Version():

@ -35,13 +35,14 @@ Install_phpmyadmin()
mkdir -p ${serverPath}/source/phpmyadmin
VER=$1
FILE=phpMyAdmin-${VER}-all-languages.tar.gz
FDIR=phpMyAdmin-${VER}-all-languages
FILE=phpMyAdmin-${VER}-all-languages.tar.gz
DOWNLOAD=https://files.phpmyadmin.net/phpMyAdmin/${VER}/$FILE
if [ ! -f $serverPath/source/phpmyadmin/$FILE ];then
wget -O $serverPath/source/phpmyadmin/$FILE $DOWNLOAD
wget --no-check-certificate -O $serverPath/source/phpmyadmin/$FILE $DOWNLOAD
fi
if [ ! -d $serverPath/source/phpmyadmin/$FDIR ];then

@ -0,0 +1,43 @@
CREATE TABLE IF NOT EXISTS `config` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`mysql_root` TEXT
);
INSERT INTO `config` (`id`, `mysql_root`) VALUES (1, 'admin');
CREATE TABLE IF NOT EXISTS `databases` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pid` INTEGER,
`name` TEXT,
`username` TEXT,
`password` TEXT,
`accept` TEXT,
`rw` TEXT DEFAULT 'rw',
`ps` TEXT,
`addtime` TEXT
);
-- ALTER TABLE `databases` ADD COLUMN `rw` TEXT DEFAULT 'rw';
CREATE TABLE IF NOT EXISTS `master_replication_user` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`username` TEXT,
`password` TEXT,
`accept` TEXT,
`ps` TEXT,
`addtime` TEXT
);
-- 从库配置主库的[ssh private key]
-- drop table `slave_id_rsa`;
CREATE TABLE IF NOT EXISTS `slave_id_rsa` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`ip` TEXT,
`port` TEXT,
`user` TEXT,
`db_user` TEXT,
`id_rsa` TEXT,
`ps` TEXT,
`addtime` TEXT
);

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

@ -0,0 +1,32 @@
<div class="bt-form">
<div class='plugin_version'></div>
<div class="bt-w-main">
<div class="bt-w-menu">
<!-- <script type="text/javascript">console.log($('.plugin_version').attr('version'));</script> -->
<p class="bgw" onclick="pluginService('postgresql', $('.plugin_version').attr('version'));">服务</p>
<p onclick="pluginInitD('postgresql', $('.plugin_version').attr('version'));">自启动</p>
<p onclick="pluginConfig('postgresql', $('.plugin_version').attr('version'));">配置文件</p>
<!--<p onclick="myDbPos();">存储位置</p> -->
<p onclick="pgPort();">端口</p>
<!-- <p onclick="runInfo();">当前状态</p>
<p onclick="myPerfOpt();">性能优化</p> -->
<p onclick="pluginLogs('postgresql',$('.plugin_version').attr('version'),'run_log');">日志</p>
<!--<p onclick="pluginLogs('postgresql',$('.plugin_version').attr('version'),'show_log');">慢日志</p>-->
<p onclick="dbList()">管理列表</p>
<!--<p onclick="masterOrSlaveConf($('.plugin_version').attr('version'))">主从配置</p> -->
</div>
<div class="bt-w-con pd15">
<div class="soft-man-con" style="height: 530px; overflow: auto;"></div>
</div>
</div>
</div>
<script type="text/javascript">
resetPluginWinWidth(800);
var loading = layer.msg("资源加载中...", { icon: 16, time: 0, shade: 0.3 });
$.getScript( "/plugins/file?name=postgresql&f=js/postgresql.js", function(){
layer.close(loading);
pluginService('postgresql',$('.plugin_version').attr('version'));
});
</script>

@ -0,0 +1,724 @@
# 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 'postgresql'
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() + '/data/postgresql.conf'
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/postgresql.tpl'
if not os.path.exists(path):
path = getPluginDir() + '/init.d/postgresql.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('{$APP_PATH}', service_path + '/postgresql')
return content
def pSqliteDb(dbname='databases'):
file = getServerDir() + '/pgsql.db'
name = 'pgsql'
if not os.path.exists(file):
conn = mw.M(dbname).dbPos(getServerDir(), name)
csql = mw.readFile(getPluginDir() + '/conf/pgsql.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():
# pymysql
db = mw.getMyORM()
# MySQLdb |
# db = mw.getMyORMDb()
db.setPort(getDbPort())
db.setSocket(getSocketFile())
# db.setCharset("utf8")
db.setPwd(pSqliteDb('config').where('id=?', (1,)).getField('mysql_root'))
return db
def initDreplace(version=''):
conf_dir = getServerDir() + '/etc'
log_dir = getServerDir() + "/logs"
conf_list = [
conf_dir,
log_dir
]
for c in conf_list:
if not os.path.exists(c):
os.mkdir(c)
# my_conf = conf_dir + '/my.cnf'
# if not os.path.exists(my_conf):
# tpl = getPluginDir() + '/conf/my.cnf'
# content = mw.readFile(tpl)
# content = contentReplace(content)
# mw.writeFile(my_conf, content)
# systemd
system_dir = mw.systemdCfgDir()
service = system_dir + '/postgresql.service'
if os.path.exists(system_dir) and not os.path.exists(service):
tpl = getPluginDir() + '/init.d/postgresql.service.tpl'
service_path = mw.getServerDir()
content = mw.readFile(tpl)
content = contentReplace(content)
mw.writeFile(service, content)
mw.execShell('systemctl daemon-reload')
if not mw.isAppleSystem():
mw.execShell('chown -R postgresql:postgresql ' + getServerDir())
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):
initd_tpl = getInitdTpl(version)
content = mw.readFile(initd_tpl)
content = contentReplace(content)
mw.writeFile(file_bin, content)
mw.execShell('chmod +x ' + file_bin)
return file_bin
def status(version=''):
data = mw.execShell(
"ps -ef|grep postgres |grep -v grep | grep -v python | grep -v mdserver-web | awk '{print $2}'")
if data[0] == '':
return 'stop'
return 'start'
def getDataDir():
file = getConf()
content = mw.readFile(file)
rep = 'datadir\s*=\s*(.*)'
tmp = re.search(rep, content)
return tmp.groups()[0].strip()
def getPidFile():
file = getConf()
content = mw.readFile(file)
rep = 'pid-file\s*=\s*(.*)'
tmp = re.search(rep, content)
return tmp.groups()[0].strip()
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 'postgresql'
def initPgData():
serverdir = getServerDir()
if not os.path.exists(serverdir + '/postgresql'):
cmd = 'cd ' + serverdir + ' && ./bin/initdb -D ' + serverdir + "/data"
mw.execShell(cmd)
return False
return True
def initPgPwd():
serverdir = getServerDir()
pwd = mw.getRandomString(16)
cmd_pass = "echo \"create user root with superuser password '" + pwd + "'\" | "
cmd_pass = cmd_pass + serverdir + '/bin/psql -d postgres'
data = mw.execShell(cmd_pass)
print(cmd_pass)
print(data)
pSqliteDb('config').where('id=?', (1,)).save('pg_root', (pwd,))
return True
def myOp(version, method):
# import commands
init_file = initDreplace()
cmd = init_file + ' ' + method
# print(cmd)
try:
isInited = initPgData()
if not isInited:
if mw.isAppleSystem():
cmd_init_start = init_file + ' start'
subprocess.Popen(cmd_init_start, stdout=subprocess.PIPE, shell=True,
bufsize=4096, stderr=subprocess.PIPE)
time.sleep(6)
else:
mw.execShell('systemctl start postgresql')
initPgPwd()
if mw.isAppleSystem():
cmd_init_stop = init_file + ' stop'
subprocess.Popen(cmd_init_stop, stdout=subprocess.PIPE, shell=True,
bufsize=4096, stderr=subprocess.PIPE)
time.sleep(3)
else:
mw.execShell('systemctl stop postgresql')
if mw.isAppleSystem():
sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True,
bufsize=4096, stderr=subprocess.PIPE)
sub.wait(5)
else:
mw.execShell('systemctl ' + method + ' postgresql')
return 'ok'
except Exception as e:
# raise
return method + ":" + 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 postgresql | 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 postgresql')
return 'ok'
def initdUinstall():
if mw.isAppleSystem():
return "Apple Computer does not support"
mw.execShell('systemctl disable postgresql')
return 'ok'
def getMyDbPos():
file = getConf()
content = mw.readFile(file)
rep = 'datadir\s*=\s*(.*)'
tmp = re.search(rep, content)
return tmp.groups()[0].strip()
def setMyDbPos():
args = getArgs()
data = checkArgs(args, ['datadir'])
if not data[0]:
return data[1]
s_datadir = getMyDbPos()
t_datadir = args['datadir']
if t_datadir == s_datadir:
return mw.returnJson(False, '与当前存储目录相同,无法迁移文件!')
if not os.path.exists(t_datadir):
mw.execShell('mkdir -p ' + t_datadir)
# mw.execShell('/etc/init.d/mysqld stop')
stop()
mw.execShell('cp -rf ' + s_datadir + '/* ' + t_datadir + '/')
mw.execShell('chown -R mysql mysql ' + t_datadir)
mw.execShell('chmod -R 755 ' + t_datadir)
mw.execShell('rm -f ' + t_datadir + '/*.pid')
mw.execShell('rm -f ' + t_datadir + '/*.err')
path = getServerDir()
myfile = path + '/etc/my.cnf'
mycnf = mw.readFile(myfile)
mw.writeFile(path + '/etc/my_backup.cnf', mycnf)
mycnf = mycnf.replace(s_datadir, t_datadir)
mw.writeFile(myfile, mycnf)
start()
result = mw.execShell(
'ps aux|grep mysqld| grep -v grep|grep -v python')
if len(result[0]) > 10:
mw.writeFile('data/datadir.pl', t_datadir)
return mw.returnJson(True, '存储目录迁移成功!')
else:
mw.execShell('pkill -9 mysqld')
mw.writeFile(myfile, mw.readFile(path + '/etc/my_backup.cnf'))
start()
return mw.returnJson(False, '文件迁移失败!')
def getPgPort():
file = getConf()
content = mw.readFile(file)
rep = 'port\s*=\s*(.*)'
tmp = re.search(rep, content)
return tmp.groups()[0].strip()
def setPgPort():
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, 'PG未启动', [])
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']
result = {}
# print(data)
for d in data:
vname = d["Variable_name"]
for g in gets:
if vname == g:
result[g] = d["Value"]
# print(result, int(result['Uptime']))
result['Run'] = int(time.time()) - int(result['Uptime'])
tmp = db.query('show master status')
try:
result['File'] = tmp[0]["File"]
result['Position'] = tmp[0]["Position"]
except:
result['File'] = 'OFF'
result['Position'] = 'OFF'
return mw.getJson(result)
def runLog():
return getServerDir() + "/logs/server.log"
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:
vname = d['Variable_name']
for g in gets:
# print(g)
if vname == g:
result['mem'][g] = d["Value"]
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 __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/mysql/bin/mysql -uroot -p' + pwd + \
' ' + name + ' < ' + file_path_sql
# print(mysql_cmd)
os.system(mysql_cmd)
return mw.returnJson(True, 'ok')
def deleteDbBackup():
args = getArgs()
data = checkArgs(args, ['filename'])
if not data[0]:
return data[1]
bkDir = mw.getRootDir() + '/backup/database'
os.remove(bkDir + '/' + args['filename'])
return mw.returnJson(True, 'ok')
def getDbBackupList():
args = getArgs()
data = checkArgs(args, ['name'])
if not data[0]:
return data[1]
r = getDbBackupListFunc(args['name'])
bkDir = mw.getRootDir() + '/backup/database'
rr = []
for x in range(0, len(r)):
p = bkDir + '/' + r[x]
data = {}
data['name'] = r[x]
rsize = os.path.getsize(p)
data['size'] = mw.toSize(rsize)
t = os.path.getctime(p)
t = time.localtime(t)
data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t)
rr.append(data)
data['file'] = p
return mw.returnJson(True, 'ok', rr)
def getDbList():
args = getArgs()
page = 1
page_size = 10
search = ''
data = {}
if 'page' in args:
page = int(args['page'])
if 'page_size' in args:
page_size = int(args['page_size'])
if 'search' in args:
search = args['search']
conn = pSqliteDb('databases')
limit = str((page - 1) * page_size) + ',' + str(page_size)
condition = ''
if not search == '':
condition = "name like '%" + search + "%'"
field = 'id,pid,name,username,password,accept,rw,ps,addtime'
clist = conn.where(condition, ()).field(
field).limit(limit).order('id desc').select()
for x in range(0, len(clist)):
dbname = clist[x]['name']
blist = getDbBackupListFunc(dbname)
# print(blist)
clist[x]['is_backup'] = False
if len(blist) > 0:
clist[x]['is_backup'] = True
count = conn.where(condition, ()).count()
_page = {}
_page['count'] = count
_page['p'] = page
_page['row'] = page_size
_page['tojs'] = 'dbList'
data['page'] = mw.getPage(_page)
data['data'] = clist
info = {}
info['root_pwd'] = pSqliteDb('config').where(
'id=?', (1,)).getField('mysql_root')
data['info'] = info
return mw.getJson(data)
def installPreInspection(version):
return 'ok'
def uninstallPreInspection(version):
# return "请手动删除MySQL[{}]".format(version)
return 'ok'
if __name__ == "__main__":
func = sys.argv[1]
version = "14.4"
version_pl = getServerDir() + "/version.pl"
if os.path.exists(version_pl):
version = mw.readFile(version_pl).strip()
if func == 'status':
print(status(version))
elif func == 'start':
print(start(version))
elif func == 'stop':
print(stop(version))
elif func == 'restart':
print(restart(version))
elif func == 'reload':
print(reload(version))
elif func == 'initd_status':
print(initdStatus())
elif func == 'initd_install':
print(initdInstall())
elif func == 'initd_uninstall':
print(initdUinstall())
elif func == 'install_pre_inspection':
print(installPreInspection(version))
elif func == 'uninstall_pre_inspection':
print(uninstallPreInspection(version))
elif func == 'conf':
print(getConf())
elif func == 'run_info':
print(runInfo())
elif func == 'run_log':
print(runLog())
elif func == 'pg_port':
print(getPgPort())
elif func == 'set_pg_port':
print(setPgPort())
elif func == 'get_db_list':
print(getDbList())
else:
print('error')

@ -0,0 +1,18 @@
{
"title":"PostgreSQL",
"tip":"soft",
"name":"postgresql",
"type":"运行环境",
"ps":"[DEV]功能强大的开源数据库",
"coexist": false,
"install_pre_inspection":true,
"uninstall_pre_inspection":true,
"versions":["14.4"],
"shell":"install.sh",
"checks":"server/postgresql",
"path":"server/postgresql",
"author":"postgresql",
"home":"https://www.postgresql.org/",
"date":"2022-08-07",
"pid": "2"
}

@ -0,0 +1,16 @@
[Unit]
Description=PostgreSQL: a powerful open source database
After=network.target
[Service]
Type=forking
User=postgres
Group=postgres
WorkingDirectory={$APP_PATH}
ExecStart={$APP_PATH}/pg_ctl start -D {$APP_PATH}/data
ExecReload={$APP_PATH}/pg_ctl restart -D {$APP_PATH}/data
ExecStop={$APP_PATH}/pg_ctl stop -D {$APP_PATH}/data
PrivateTmp=false
[Install]
WantedBy=multi-user.target

@ -0,0 +1,66 @@
#!/bin/bash
# chkconfig: 2345 55 25
# description: PostgreSQL Service
### BEGIN INIT INFO
# Provides: Midoks
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts PostgreSQL
# Description: starts the PostgreSQL
### END INIT INFO
PATH=/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export LC_ALL="en_US.UTF-8"
MW_PATH={$SERVER_PATH}
PATH=$PATH:$MW_PATH/bin
if [ -f $MW_PATH/bin/activate ];then
source $MW_PATH/bin/activate
fi
pg_start()
{
touch {$APP_PATH}/logs/server.log
{$APP_PATH}/bin/pg_ctl -D {$APP_PATH}/data -l {$APP_PATH}/logs/server.log start
}
pg_stop()
{
{$APP_PATH}/bin/pg_ctl -D {$APP_PATH}/data -l {$APP_PATH}/logs/server.log stop
}
pg_status()
{
isStart=$(ps aux |grep 'postgres'|grep -v grep|awk '{print $2}')
if [ "$isStart" != '' ];then
echo -e "\033[32mPostgreSQL (pid $isStart) already running\033[0m"
else
echo -e "\033[31mPostgreSQL not running\033[0m"
fi
}
pg_reload()
{
pg_stop
pg_start
}
case "$1" in
'start') pg_start;;
'stop') pg_stop;;
'reload') pg_reload;;
'restart')
pg_stop
pg_start;;
esac

@ -0,0 +1,42 @@
#!/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/postgresql.service ] || [ -f /lib/systemd/system/postgresql.service ];then
# systemctl stop postgresql
# systemctl disable postgresql
# rm -rf /usr/lib/systemd/system/postgresql.service
# rm -rf /lib/systemd/system/postgresql.service
# systemctl daemon-reload
# fi
# fi
sh -x $curPath/versions/$2/install.sh $1
# if [ "${action}" == "install" ] && [ -d $serverPath/postgresql ];then
# #初始化
# cd ${rootPath} && python3 ${rootPath}/plugins/postgresql/index.py start ${type}
# cd ${rootPath} && python3 ${rootPath}/plugins/postgresql/index.py initd_install ${type}
# fi

File diff suppressed because it is too large Load Diff

@ -0,0 +1,101 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#https://www.postgresql.org/ftp/source/
curPath=`pwd`
rootPath=$(dirname "$curPath")
rootPath=$(dirname "$rootPath")
serverPath=$(dirname "$rootPath")
sysName=`uname`
install_tmp=${rootPath}/tmp/mw_install.pl
postgreDir=${serverPath}/source/postgresql
VERSION=14.4
Install_App()
{
mkdir -p ${postgreDir}
echo '正在安装脚本文件...' > $install_tmp
if id postgresql &> /dev/null ;then
echo "postgresql UID is `id -u postgresql`"
echo "postgresql Shell is `grep "^postgresql:" /etc/passwd |cut -d':' -f7 `"
else
groupadd postgresql
useradd -g postgresql postgresql
fi
if [ "$sysName" != "Darwin" ];then
mkdir -p /var/log/mariadb
touch /var/log/mariadb/mariadb.log
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
# for stable installation
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -f ${postgreDir}/postgresql-${VERSION}.tar.bz2 ];then
wget --no-check-certificate -O ${postgreDir}/postgresql-${VERSION}.tar.bz2 --tries=3 https://ftp.postgresql.org/pub/source/v${VERSION}/postgresql-${VERSION}.tar.bz2
fi
if [ ! -d ${postgreDir}/postgresql-${VERSION} ];then
cd ${postgreDir} && tar -jxvf ${postgreDir}/postgresql-${VERSION}.tar.bz2
fi
if [ ! -d $serverPath/postgresql ];then
cd ${postgreDir}/postgresql-${VERSION} && ./configure \
--prefix=$serverPath/postgresql
# --with-openssl \
# --with-pgport=33206
echo "cd ${postgreDir}/postgresql-${VERSION} && ./configure \
--prefix=$serverPath/postgresql"
# --with-openssl \
# --with-pgport=33206
make -j${cpuCore} && make install && make clean
fi
if [ -d $serverPath/postgresql ];then
echo "${VERSION}" > $serverPath/postgresql/version.pl
echo 'install successful' > $install_tmp
else
echo 'install fail' > $install_tmp
fi
}
Uninstall_App()
{
rm -rf $serverPath/postgresql
echo '卸载完成' > $install_tmp
}
action=$1
if [ "${1}" == "install" ];then
Install_App
else
Uninstall_App
fi

@ -35,7 +35,7 @@ function getLogs(id){
});
setTimeout(function(){
$("#crontab-log").text(rdata.msg);
$("#crontab-log").html(rdata.msg);
},200);
},'json');
}

@ -112,8 +112,14 @@ class backupTools:
if len(mycnf) > 100:
mw.writeFile(db_path + '/etc/my.cnf', mycnf)
mw.execShell(
db_path + "/bin/mysqldump --opt --default-character-set=utf8 " + name + " | gzip > " + filename)
# mw.execShell(db_path + "/bin/mysqldump --opt --default-character-set=utf8 " +
# name + " | gzip > " + filename)
# mw.execShell(db_path + "/bin/mysqldump --skip-lock-tables --default-character-set=utf8 " +
# name + " | gzip > " + filename)
mw.execShell(db_path + "/bin/mysqldump --single-transaction --quick --default-character-set=utf8 " +
name + " | gzip > " + filename)
if not os.path.exists(filename):
endDate = time.strftime('%Y/%m/%d %X', time.localtime())
@ -135,7 +141,7 @@ class backupTools:
mw.M('backup').add('type,name,pid,filename,addtime,size', (1, os.path.basename(
filename), pid, filename, endDate, os.path.getsize(filename)))
log = "数据库[" + name + "]备份成功,用时[" + str(round(outTime, 2)) + u"]秒"
log = "数据库[" + name + "]备份成功,用时[" + str(round(outTime, 2)) + "]秒"
mw.writeLog('计划任务', log)
print("★[" + endDate + "] " + log)
print("|---保留最新的[" + count + "]份备份")

@ -3,7 +3,7 @@
# description: MW Cloud Service
### BEGIN INIT INFO
# Provides: bt
# Provides: Midoks
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5

@ -58,8 +58,18 @@ if [ $OSNAME != "macos" ];then
mkdir -p /www/backup/database
mkdir -p /www/backup/site
# https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/install.sh
if [ ! -d /www/server/mdserver-web ];then
wget -O /tmp/master.zip https://codeload.github.com/midoks/mdserver-web/zip/master
cn=$(curl -fsSL -m 10 http://ipinfo.io/json | grep "\"country\": \"CN\"")
if [ ! -z "$cn" ];then
wget -O /tmp/master.zip https://gitee.com/midoks/mdserver-web/repository/archive/master.zip
else
wget -O /tmp/master.zip https://codeload.github.com/midoks/mdserver-web/zip/master
fi
cd /tmp && unzip /tmp/master.zip
mv -f /tmp/mdserver-web-master /www/server/mdserver-web
rm -rf /tmp/master.zip

@ -113,7 +113,7 @@ cd /www/server/mdserver-web && pip3 install -r /www/server/mdserver-web/requirem
pip3 install gevent-websocket==0.10.1
pip3 install flask-caching==1.10.1
pip3 install mysqlclient
# pip3 install mysqlclient
if [ ! -f /www/server/mdserver-web/bin/activate ];then
@ -129,5 +129,5 @@ pip3 install -r /www/server/mdserver-web/requirements.txt
pip3 install gevent-websocket==0.10.1
pip3 install flask-caching==1.10.1
pip3 install mysqlclient
# pip3 install mysqlclient

@ -46,7 +46,15 @@ else
OSNAME='unknow'
fi
wget -O /tmp/master.zip https://codeload.github.com/midoks/mdserver-web/zip/master
cn=$(curl -fsSL -m 10 http://ipinfo.io/json | grep "\"country\": \"CN\"")
if [ ! -z "$cn" ];then
wget -O /tmp/master.zip https://gitee.com/midoks/mdserver-web/repository/archive/master.zip
else
wget -O /tmp/master.zip https://codeload.github.com/midoks/mdserver-web/zip/master
fi
cd /tmp && unzip /tmp/master.zip
/usr/bin/cp -rf /tmp/mdserver-web-master/* /www/server/mdserver-web
rm -rf /tmp/master.zip

Loading…
Cancel
Save