Simple Linux Panel
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mdserver-web/plugins/php/index.py

1095 lines
34 KiB

7 years ago
# coding:utf-8
import sys
import io
import os
import time
6 years ago
import re
6 years ago
import json
import shutil
6 years ago
4 years ago
# reload(sys)
# sys.setdefaultencoding('utf8')
7 years ago
sys.path.append(os.getcwd() + "/class/core")
import mw
7 years ago
4 years ago
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)
7 years ago
app_debug = False
if mw.isAppleSystem():
7 years ago
app_debug = True
def getPluginName():
7 years ago
return 'php'
7 years ago
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
7 years ago
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
7 years ago
6 years ago
def getInitDFile(version):
2 years ago
current_os = mw.getOs()
2 years ago
if current_os == 'darwin':
7 years ago
return '/tmp/' + getPluginName()
2 years ago
if current_os.startswith('freebsd'):
return '/etc/rc.d/' + getPluginName()
6 years ago
return '/etc/init.d/' + getPluginName() + version
7 years ago
7 years ago
7 years ago
def getArgs():
6 years ago
args = sys.argv[3:]
7 years ago
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
2 years ago
if t.strip() == '':
tmp = []
else:
t = t.split(':', 1)
tmp[t[0]] = t[1]
7 years ago
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
6 years ago
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'))
6 years ago
7 years ago
def getConf(version):
6 years ago
path = getServerDir() + '/' + version + '/etc/php.ini'
7 years ago
return path
def getFpmConfFile(version, pool='www'):
return getServerDir() + '/' + version + '/etc/php-fpm.d/'+pool+'.conf'
3 years ago
1 year ago
def getFpmFile(version):
return getServerDir() + '/' + version + '/etc/php-fpm.conf'
3 years ago
3 years ago
def status_progress(version):
3 years ago
# ps -ef|grep 'php/81' |grep -v grep | grep -v python | awk '{print $2}
2 years ago
cmd = "ps aux|grep 'php/" + version + \
7 years ago
"' |grep -v grep | grep -v python | awk '{print $2}'"
data = mw.execShell(cmd)
7 years ago
if data[0] == '':
return 'stop'
return 'start'
3 years ago
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'
7 years ago
def contentReplace(content, version):
service_path = mw.getServerDir()
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
7 years ago
content = content.replace('{$SERVER_PATH}', service_path)
content = content.replace('{$PHP_VERSION}', version)
5 years ago
content = content.replace('{$LOCAL_IP}', mw.getLocalIp())
3 years ago
content = content.replace('{$SSL_CRT}', mw.getSslCrt())
6 years ago
if mw.isAppleSystem():
# user = mw.execShell(
6 years ago
# "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
content = content.replace('{$PHP_USER}', 'nobody')
content = content.replace('{$PHP_GROUP}', 'nobody')
6 years ago
rep = 'listen.owner\s*=\s*(.+)\r?\n'
val = ';listen.owner = nobody\n'
content = re.sub(rep, val, content)
rep = 'listen.group\s*=\s*(.+)\r?\n'
val = ';listen.group = nobody\n'
content = re.sub(rep, val, content)
6 years ago
rep = 'user\s*=\s*(.+)\r?\n'
val = ';user = nobody\n'
content = re.sub(rep, val, content)
6 years ago
rep = r'[^\.]group\s*=\s*(.+)\r?\n'
6 years ago
val = ';group = nobody\n'
content = re.sub(rep, val, content)
6 years ago
6 years ago
else:
content = content.replace('{$PHP_USER}', 'www')
content = content.replace('{$PHP_GROUP}', 'www')
7 years ago
return content
6 years ago
def makeOpenrestyConf():
5 years ago
phpversions = ['00', '52', '53', '54', '55', '56',
2 years ago
'70', '71', '72', '73', '74', '80', '81', '82', '83']
sdir = mw.getServerDir()
dst_dir = sdir + '/web_conf/php'
dst_dir_conf = sdir + '/web_conf/php/conf'
if not os.path.exists(dst_dir):
mw.execShell('mkdir -p ' + dst_dir)
if not os.path.exists(dst_dir_conf):
mw.execShell('mkdir -p ' + dst_dir_conf)
d_pathinfo = sdir + '/web_conf/php/pathinfo.conf'
if not os.path.exists(d_pathinfo):
s_pathinfo = getPluginDir() + '/conf/pathinfo.conf'
shutil.copyfile(s_pathinfo, d_pathinfo)
info = getPluginDir() + '/info.json'
content = mw.readFile(info)
content = json.loads(content)
versions = content['versions']
tpl = getPluginDir() + '/conf/enable-php.conf'
tpl_content = mw.readFile(tpl)
for x in phpversions:
dfile = sdir + '/web_conf/php/conf/enable-php-' + x + '.conf'
if not os.path.exists(dfile):
if x == '00':
3 years ago
mw.writeFile(dfile, 'set $PHP_ENV 0;')
else:
w_content = contentReplace(tpl_content, x)
mw.writeFile(dfile, w_content)
# php-fpm status
# for version in phpversions:
# dfile = sdir + '/web_conf/php/status/phpfpm_status_' + version + '.conf'
# tpl = getPluginDir() + '/conf/phpfpm_status.conf'
# if not os.path.exists(dfile):
# content = mw.readFile(tpl)
# content = contentReplace(content, version)
# mw.writeFile(dfile, content)
6 years ago
6 years ago
5 years ago
def phpPrependFile(version):
app_start = getServerDir() + '/app_start.php'
if not os.path.exists(app_start):
tpl = getPluginDir() + '/conf/app_start.php'
content = mw.readFile(tpl)
content = contentReplace(content, version)
mw.writeFile(app_start, content)
7 years ago
def phpFpmReplace(version):
6 years ago
desc_php_fpm = getServerDir() + '/' + version + '/etc/php-fpm.conf'
if not os.path.exists(desc_php_fpm):
tpl_php_fpm = getPluginDir() + '/conf/php-fpm.conf'
content = mw.readFile(tpl_php_fpm)
6 years ago
content = contentReplace(content, version)
mw.writeFile(desc_php_fpm, content)
5 years ago
else:
if version == '52':
5 years ago
tpl_php_fpm = tpl_php_fpm = getPluginDir() + '/conf/php-fpm-52.conf'
content = mw.readFile(tpl_php_fpm)
5 years ago
mw.writeFile(desc_php_fpm, content)
7 years ago
def phpFpmWwwReplace(version):
7 years ago
service_php_fpm_dir = getServerDir() + '/' + version + '/etc/php-fpm.d/'
6 years ago
7 years ago
if not os.path.exists(service_php_fpm_dir):
os.mkdir(service_php_fpm_dir)
6 years ago
service_php_fpmwww = service_php_fpm_dir + '/www.conf'
if not os.path.exists(service_php_fpmwww):
6 years ago
tpl_php_fpmwww = getPluginDir() + '/conf/www.conf'
content = mw.readFile(tpl_php_fpmwww)
6 years ago
content = contentReplace(content, version)
mw.writeFile(service_php_fpmwww, content)
7 years ago
6 years ago
def makePhpIni(version):
3 years ago
dst_ini = getConf(version)
if not os.path.exists(dst_ini):
src_ini = getPluginDir() + '/conf/php' + version[0:1] + '.ini'
5 years ago
# shutil.copyfile(s_ini, d_ini)
content = mw.readFile(src_ini)
5 years ago
if version == '52':
5 years ago
content = content + "auto_prepend_file=/www/server/php/app_start.php"
3 years ago
content = contentReplace(content, version)
mw.writeFile(dst_ini, content)
6 years ago
6 years ago
def initReplace(version):
makeOpenrestyConf()
6 years ago
makePhpIni(version)
7 years ago
7 years ago
initD_path = getServerDir() + '/init.d'
if not os.path.exists(initD_path):
os.mkdir(initD_path)
6 years ago
file_bin = initD_path + '/php' + version
if not os.path.exists(file_bin):
6 years ago
file_tpl = getPluginDir() + '/init.d/php.tpl'
if version == '52':
file_tpl = getPluginDir() + '/init.d/php52.tpl'
content = mw.readFile(file_tpl)
6 years ago
content = contentReplace(content, version)
7 years ago
mw.writeFile(file_bin, content)
mw.execShell('chmod +x ' + file_bin)
7 years ago
5 years ago
phpPrependFile(version)
7 years ago
phpFpmWwwReplace(version)
7 years ago
phpFpmReplace(version)
7 years ago
3 years ago
session_path = getServerDir() + '/tmp/session'
6 years ago
if not os.path.exists(session_path):
3 years ago
mw.execShell('mkdir -p ' + session_path)
mw.execShell('chown -R www:www ' + session_path)
5 years ago
3 years ago
upload_path = getServerDir() + '/tmp/upload'
5 years ago
if not os.path.exists(upload_path):
3 years ago
mw.execShell('mkdir -p ' + upload_path)
mw.execShell('chown -R www:www ' + upload_path)
# systemd
3 years ago
systemDir = mw.systemdCfgDir()
systemService = systemDir + '/php' + version + '.service'
if os.path.exists(systemDir) and not os.path.exists(systemService):
2 years ago
systemServiceTpl = getPluginDir() + '/init.d/php.service.tpl'
if version == '52':
systemServiceTpl = getPluginDir() + '/init.d/php.service.52.tpl'
service_path = mw.getServerDir()
se_content = mw.readFile(systemServiceTpl)
se_content = se_content.replace('{$VERSION}', version)
se_content = se_content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(systemService, se_content)
mw.execShell('systemctl daemon-reload')
7 years ago
return file_bin
def phpOp(version, method):
6 years ago
file = initReplace(version)
2 years ago
current_os = mw.getOs()
if current_os == "darwin":
data = mw.execShell(file + ' ' + method)
if data[1] == '':
return 'ok'
return data[1]
3 years ago
2 years ago
if current_os.startswith("freebsd"):
data = mw.execShell('service php' + version + ' ' + method)
if data[1] == '':
return 'ok'
3 years ago
return data[1]
2 years ago
if method == 'stop' or method == 'restart':
mw.execShell(file + ' ' + 'stop')
data = mw.execShell('systemctl ' + method + ' php' + version)
7 years ago
if data[1] == '':
7 years ago
return 'ok'
6 years ago
return data[1]
7 years ago
7 years ago
def start(version):
2 years ago
mw.execShell(
'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/www/server/lib/icu/lib')
7 years ago
return phpOp(version, 'start')
def stop(version):
3 years ago
status = phpOp(version, 'stop')
if version == '52':
file = initReplace(version)
data = mw.execShell(file + ' ' + 'stop')
3 years ago
if data[1] == '':
return 'ok'
3 years ago
return status
7 years ago
7 years ago
7 years ago
def restart(version):
return phpOp(version, 'restart')
7 years ago
7 years ago
def reload(version):
3 years ago
if version == '52':
return phpOp(version, 'restart')
return phpOp(version, 'reload')
7 years ago
7 years ago
6 years ago
def initdStatus(version):
2 years ago
current_os = mw.getOs()
2 years ago
if current_os == 'darwin':
return "Apple Computer does not support"
2 years ago
if current_os.startswith('freebsd'):
2 years ago
initd_bin = getInitDFile(version)
2 years ago
if os.path.exists(initd_bin):
return 'ok'
3 years ago
shell_cmd = 'systemctl status php' + version + ' | grep loaded | grep "enabled;"'
data = mw.execShell(shell_cmd)
if data[0] == '':
return 'fail'
return 'ok'
6 years ago
def initdInstall(version):
2 years ago
current_os = mw.getOs()
2 years ago
if current_os == 'darwin':
return "Apple Computer does not support"
2 years ago
if current_os.startswith('freebsd'):
import shutil
2 years ago
source_bin = initReplace(version)
2 years ago
initd_bin = getInitDFile(version)
2 years ago
shutil.copyfile(source_bin, initd_bin)
mw.execShell('chmod +x ' + initd_bin)
return 'ok'
3 years ago
mw.execShell('systemctl enable php' + version)
6 years ago
return 'ok'
def initdUinstall(version):
2 years ago
current_os = mw.getOs()
2 years ago
if current_os == 'darwin':
return "Apple Computer does not support"
6 years ago
2 years ago
if current_os.startswith('freebsd'):
2 years ago
initd_bin = getInitDFile(version)
2 years ago
os.remove(initd_bin)
return 'ok'
3 years ago
mw.execShell('systemctl disable php' + version)
6 years ago
return 'ok'
6 years ago
def fpmLog(version):
return getServerDir() + '/' + version + '/var/log/php-fpm.log'
def fpmSlowLog(version):
6 years ago
return getServerDir() + '/' + version + '/var/log/www-slow.log'
6 years ago
6 years ago
def getPhpConf(version):
gets = [
{'name': 'short_open_tag', 'type': 1, 'ps': '短标签支持'},
{'name': 'asp_tags', 'type': 1, 'ps': 'ASP标签支持'},
{'name': 'max_execution_time', 'type': 2, 'ps': '最大脚本运行时间'},
{'name': 'max_input_time', 'type': 2, 'ps': '最大输入时间'},
{'name': 'max_input_vars', 'type': 2, 'ps': '最大输入数量'},
6 years ago
{'name': 'memory_limit', 'type': 2, 'ps': '脚本内存限制'},
{'name': 'post_max_size', 'type': 2, 'ps': 'POST数据最大尺寸'},
{'name': 'file_uploads', 'type': 1, 'ps': '是否允许上传文件'},
{'name': 'upload_max_filesize', 'type': 2, 'ps': '允许上传文件的最大尺寸'},
{'name': 'max_file_uploads', 'type': 2, 'ps': '允许同时上传文件的最大数量'},
{'name': 'default_socket_timeout', 'type': 2, 'ps': 'Socket超时时间'},
{'name': 'error_reporting', 'type': 3, 'ps': '错误级别'},
{'name': 'display_errors', 'type': 1, 'ps': '是否输出详细错误信息'},
{'name': 'cgi.fix_pathinfo', 'type': 0, 'ps': '是否开启pathinfo'},
{'name': 'date.timezone', 'type': 3, 'ps': '时区'}
7 years ago
]
3 years ago
phpini = mw.readFile(getConf(version))
6 years ago
result = []
for g in gets:
rep = g['name'] + '\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)'
tmp = re.search(rep, phpini)
if not tmp:
7 years ago
continue
6 years ago
g['value'] = tmp.groups()[0]
result.append(g)
return mw.getJson(result)
7 years ago
6 years ago
def submitPhpConf(version):
gets = ['display_errors', 'cgi.fix_pathinfo', 'date.timezone', 'short_open_tag',
'asp_tags', 'max_execution_time', 'max_input_time', 'max_input_vars', 'memory_limit',
6 years ago
'post_max_size', 'file_uploads', 'upload_max_filesize', 'max_file_uploads',
'default_socket_timeout', 'error_reporting']
args = getArgs()
filename = getServerDir() + '/' + version + '/etc/php.ini'
phpini = mw.readFile(filename)
6 years ago
for g in gets:
if g in args:
rep = g + '\s*=\s*(.+)\r?\n'
val = g + ' = ' + args[g] + '\n'
phpini = re.sub(rep, val, phpini)
mw.writeFile(filename, phpini)
# mw.execShell(getServerDir() + '/init.d/php' + version + ' reload')
reload(version)
return mw.returnJson(True, '设置成功')
6 years ago
def getLimitConf(version):
3 years ago
fileini = getConf(version)
phpini = mw.readFile(fileini)
3 years ago
filefpm = getFpmConfFile(version)
phpfpm = mw.readFile(filefpm)
# print fileini, filefpm
data = {}
try:
rep = "upload_max_filesize\s*=\s*([0-9]+)M"
tmp = re.search(rep, phpini).groups()
data['max'] = tmp[0]
except:
data['max'] = '50'
try:
rep = "request_terminate_timeout\s*=\s*([0-9]+)\n"
tmp = re.search(rep, phpfpm).groups()
data['maxTime'] = tmp[0]
except:
data['maxTime'] = 0
try:
rep = r"\n;*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n"
tmp = re.search(rep, phpini).groups()
if tmp[0] == '1':
data['pathinfo'] = True
else:
data['pathinfo'] = False
except:
data['pathinfo'] = False
return mw.getJson(data)
def setMaxTime(version):
args = getArgs()
6 years ago
data = checkArgs(args, ['time'])
if not data[0]:
return data[1]
time = args['time']
if int(time) < 30 or int(time) > 86400:
return mw.returnJson(False, '请填写30-86400间的值!')
3 years ago
filefpm = getFpmConfFile(version)
conf = mw.readFile(filefpm)
rep = "request_terminate_timeout\s*=\s*([0-9]+)\n"
conf = re.sub(rep, "request_terminate_timeout = " + time + "\n", conf)
mw.writeFile(filefpm, conf)
fileini = getServerDir() + "/" + version + "/etc/php.ini"
phpini = mw.readFile(fileini)
rep = "max_execution_time\s*=\s*([0-9]+)\r?\n"
phpini = re.sub(rep, "max_execution_time = " + time + "\n", phpini)
rep = "max_input_time\s*=\s*([0-9]+)\r?\n"
phpini = re.sub(rep, "max_input_time = " + time + "\n", phpini)
mw.writeFile(fileini, phpini)
return mw.returnJson(True, '设置成功!')
def setMaxSize(version):
args = getArgs()
3 years ago
data = checkArgs(args, ['max'])
if not data[0]:
return data[1]
maxVal = args['max']
if int(maxVal) < 2:
return mw.returnJson(False, '上传大小限制不能小于2MB!')
3 years ago
path = getConf(version)
conf = mw.readFile(path)
rep = u"\nupload_max_filesize\s*=\s*[0-9]+M"
3 years ago
conf = re.sub(rep, u'\nupload_max_filesize = ' + maxVal + 'M', conf)
rep = u"\npost_max_size\s*=\s*[0-9]+M"
3 years ago
conf = re.sub(rep, u'\npost_max_size = ' + maxVal + 'M', conf)
mw.writeFile(path, conf)
3 years ago
msg = mw.getInfo('设置PHP-{1}最大上传大小为[{2}MB]!', (version, maxVal,))
mw.writeLog('插件管理[PHP]', msg)
return mw.returnJson(True, '设置成功!')
6 years ago
def getFpmConfig(version):
filefpm = getServerDir() + '/' + version + '/etc/php-fpm.d/www.conf'
conf = mw.readFile(filefpm)
6 years ago
data = {}
rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['max_children'] = tmp[0]
rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['start_servers'] = tmp[0]
rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['min_spare_servers'] = tmp[0]
rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['max_spare_servers'] = tmp[0]
rep = "\s*pm\s*=\s*(\w+)\s*"
tmp = re.search(rep, conf).groups()
data['pm'] = tmp[0]
return mw.getJson(data)
6 years ago
def setFpmConfig(version):
args = getArgs()
# if not 'max' in args:
# return 'missing time args!'
version = args['version']
max_children = args['max_children']
start_servers = args['start_servers']
min_spare_servers = args['min_spare_servers']
max_spare_servers = args['max_spare_servers']
pm = args['pm']
file = getServerDir() + '/' + version + '/etc/php-fpm.d/www.conf'
conf = mw.readFile(file)
6 years ago
rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.max_children = " + max_children, conf)
rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.start_servers = " + start_servers, conf)
rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.min_spare_servers = " +
min_spare_servers, conf)
rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.max_spare_servers = " +
max_spare_servers + "\n", conf)
rep = "\s*pm\s*=\s*(\w+)\s*"
conf = re.sub(rep, "\npm = " + pm + "\n", conf)
mw.writeFile(file, conf)
6 years ago
reload(version)
msg = mw.getInfo('设置PHP-{1}并发设置,max_children={2},start_servers={3},min_spare_servers={4},max_spare_servers={5}', (version, max_children,
start_servers, min_spare_servers, max_spare_servers,))
mw.writeLog('插件管理[PHP]', msg)
return mw.returnJson(True, '设置成功!')
6 years ago
# def checkFpmStatusFile(version):
# if not mw.isInstalledWeb():
# return False
3 years ago
# dfile = getServerDir() + '/nginx/conf/php_status/phpfpm_status_' + version + '.conf'
# if not os.path.exists(dfile):
# tpl = getPluginDir() + '/conf/phpfpm_status.conf'
# content = mw.readFile(tpl)
# content = contentReplace(content, version)
# mw.writeFile(dfile, content)
# mw.restartWeb()
# return True
def getFpmAddress(version):
fpm_address = '/tmp/php-cgi-{}.sock'.format(version)
php_fpm_file = getFpmConfFile(version)
try:
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
6 years ago
6 years ago
def getFpmStatus(version):
3 years ago
if version == '52':
return mw.returnJson(False, 'PHP[' + version + ']不支持!!!')
stat = status(version)
if stat == 'stop':
return mw.returnJson(False, 'PHP[' + version + ']未启动!!!')
sock_file = getFpmAddress(version)
try:
sock_data = mw.requestFcgiPHP(
sock_file, '/phpfpm_status_' + version + '?json')
3 years ago
except Exception as e:
return mw.returnJson(False, str(e))
# print(data)
result = str(sock_data, encoding='utf-8')
data = json.loads(result)
fTime = time.localtime(int(data['start time']))
data['start time'] = time.strftime('%Y-%m-%d %H:%M:%S', fTime)
return mw.returnJson(True, "OK", data)
6 years ago
6 years ago
def getSessionConf(version):
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
rep = r'session.save_handler\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)'
save_handler = re.search(rep, phpini)
if save_handler:
save_handler = save_handler.group(1)
else:
save_handler = "files"
reppath = r'\nsession.save_path\s*=\s*"tcp\:\/\/([\d\.]+):(\d+).*\r?\n'
passrep = r'\nsession.save_path\s*=\s*"tcp://[\w\.\?\:]+=(.*)"\r?\n'
memcached = r'\nsession.save_path\s*=\s*"([\d\.]+):(\d+)"'
save_path = re.search(reppath, phpini)
if not save_path:
save_path = re.search(memcached, phpini)
passwd = re.search(passrep, phpini)
port = ""
if passwd:
passwd = passwd.group(1)
else:
passwd = ""
if save_path:
port = save_path.group(2)
save_path = save_path.group(1)
else:
save_path = ""
data = {"save_handler": save_handler, "save_path": save_path,
"passwd": passwd, "port": port}
return mw.returnJson(True, 'ok', data)
def setSessionConf(version):
args = getArgs()
ip = args['ip']
port = args['port']
passwd = args['passwd']
save_handler = args['save_handler']
3 years ago
if save_handler != "files":
iprep = r"(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})"
if not re.search(iprep, ip):
return mw.returnJson(False, '请输入正确的IP地址')
try:
port = int(port)
if port >= 65535 or port < 1:
return mw.returnJson(False, '请输入正确的端口号')
except:
return mw.returnJson(False, '请输入正确的端口号')
prep = r"[\~\`\/\=]"
if re.search(prep, passwd):
return mw.returnJson(False, '请不要输入以下特殊字符 " ~ ` / = "')
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
session_tmp = getServerDir() + "/tmp/session"
rep = r'session.save_handler\s*=\s*(.+)\r?\n'
val = r'session.save_handler = ' + save_handler + '\n'
phpini = re.sub(rep, val, phpini)
if save_handler == "memcached":
if not re.search("memcached.so", phpini):
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
if save_handler == "memcache":
if not re.search("memcache.so", phpini):
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
if save_handler == "redis":
if not re.search("redis.so", phpini):
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
if passwd:
passwd = "?auth=" + passwd
else:
passwd = ""
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "tcp://%s:%s%s"\n' % (ip, port, passwd)
res = re.search(rep, phpini)
if res:
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
3 years ago
if save_handler == "files":
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "' + session_tmp + '"\n'
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
mw.writeFile(filename, phpini)
reload(version)
return mw.returnJson(True, '设置成功!')
def getSessionCount_Origin(version):
session_tmp = getServerDir() + "/tmp/session"
d = [session_tmp]
count = 0
for i in d:
if not os.path.exists(i):
mw.execShell('mkdir -p %s' % i)
list = os.listdir(i)
for l in list:
if os.path.isdir(i + "/" + l):
l1 = os.listdir(i + "/" + l)
for ll in l1:
if "sess_" in ll:
count += 1
continue
if "sess_" in l:
count += 1
s = "find /tmp -mtime +1 |grep 'sess_' | wc -l"
old_file = int(mw.execShell(s)[0].split("\n")[0])
s = "find " + session_tmp + " -mtime +1 |grep 'sess_'|wc -l"
old_file += int(mw.execShell(s)[0].split("\n")[0])
return {"total": count, "oldfile": old_file}
def getSessionCount(version):
data = getSessionCount_Origin(version)
return mw.returnJson(True, 'ok!', data)
def cleanSessionOld(version):
s = "find /tmp -mtime +1 |grep 'sess_'|xargs rm -f"
mw.execShell(s)
session_tmp = getServerDir() + "/tmp/session"
s = "find " + session_tmp + " -mtime +1 |grep 'sess_' |xargs rm -f"
mw.execShell(s)
old_file_conf = getSessionCount_Origin(version)["oldfile"]
if old_file_conf == 0:
return mw.returnJson(True, '清理成功')
else:
return mw.returnJson(True, '清理失败')
6 years ago
def getDisableFunc(version):
3 years ago
filename = getConf(version)
6 years ago
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
6 years ago
phpini = mw.readFile(filename)
6 years ago
data = {}
rep = "disable_functions\s*=\s{0,1}(.*)\n"
tmp = re.search(rep, phpini).groups()
data['disable_functions'] = tmp[0]
return mw.getJson(data)
6 years ago
def setDisableFunc(version):
3 years ago
filename = getConf(version)
6 years ago
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
6 years ago
args = getArgs()
disable_functions = args['disable_functions']
phpini = mw.readFile(filename)
6 years ago
rep = "disable_functions\s*=\s*.*\n"
6 years ago
phpini = re.sub(rep, 'disable_functions = ' +
disable_functions + "\n", phpini)
6 years ago
msg = mw.getInfo('修改PHP-{1}的禁用函数为[{2}]', (version, disable_functions,))
mw.writeLog('插件管理[PHP]', msg)
mw.writeFile(filename, phpini)
6 years ago
reload(version)
return mw.returnJson(True, '设置成功!')
6 years ago
def getPhpinfo(version):
stat = status(version)
if stat == 'stop':
3 years ago
return 'PHP[' + version + ']未启动,不可访问!!!'
6 years ago
sock_file = getFpmAddress(version)
root_dir = mw.getRootDir() + '/phpinfo'
mw.execShell("rm -rf " + root_dir)
mw.execShell("mkdir -p " + root_dir)
mw.writeFile(root_dir + '/phpinfo.php', '<?php phpinfo(); ?>')
sock_data = mw.requestFcgiPHP(sock_file, '/phpinfo.php', root_dir)
3 years ago
os.system("rm -rf " + root_dir)
phpinfo = str(sock_data, encoding='utf-8')
return phpinfo
6 years ago
def get_php_info(args):
return getPhpinfo(args['version'])
def libConfCommon(version):
3 years ago
fname = getConf(version)
6 years ago
if not os.path.exists(fname):
return mw.returnJson(False, '指定PHP版本不存在!')
6 years ago
phpini = mw.readFile(fname)
6 years ago
libpath = getPluginDir() + '/versions/phplib.conf'
phplib = json.loads(mw.readFile(libpath))
6 years ago
libs = []
tasks = mw.M('tasks').where(
6 years ago
"status!=?", ('1',)).field('status,name').select()
for lib in phplib:
lib['task'] = '1'
for task in tasks:
tmp = mw.getStrBetween('[', ']', task['name'])
6 years ago
if not tmp:
continue
tmp1 = tmp.split('-')
if tmp1[0].lower() == lib['name'].lower():
lib['task'] = task['status']
lib['phpversions'] = []
lib['phpversions'].append(tmp1[1])
if phpini.find(lib['check']) == -1:
lib['status'] = False
else:
lib['status'] = True
libs.append(lib)
return libs
def get_lib_conf(data):
libs = libConfCommon(data['version'])
# print(libs)
return mw.returnData(True, 'OK!', libs)
def getLibConf(version):
libs = libConfCommon(version)
return mw.returnJson(True, 'OK!', libs)
6 years ago
6 years ago
def installLib(version):
6 years ago
args = getArgs()
6 years ago
data = checkArgs(args, ['name'])
6 years ago
if not data[0]:
return data[1]
name = args['name']
execstr = "cd " + getPluginDir() + "/versions && /bin/bash common.sh " + \
3 years ago
version + ' install ' + name
6 years ago
rettime = time.strftime('%Y-%m-%d %H:%M:%S')
3 years ago
insert_info = (None, '安装[' + name + '-' + version + ']',
6 years ago
'execshell', '0', rettime, execstr)
mw.M('tasks').add('id,name,type,status,addtime,execstr', insert_info)
3 years ago
mw.triggerTask()
return mw.returnJson(True, '已将下载任务添加到队列!')
6 years ago
6 years ago
def uninstallLib(version):
6 years ago
args = getArgs()
data = checkArgs(args, ['name'])
if not data[0]:
return data[1]
name = args['name']
3 years ago
execstr = "cd " + getPluginDir() + "/versions && /bin/bash common.sh " + \
3 years ago
version + ' uninstall ' + name
6 years ago
data = mw.execShell(execstr)
# data[0] == '' and
if data[1] == '':
return mw.returnJson(True, '已经卸载成功!')
6 years ago
else:
return mw.returnJson(False, '卸载信息![通道0]:' + data[0] + "[通道0]:" + data[1])
6 years ago
6 years ago
5 years ago
def getConfAppStart():
pstart = mw.getServerDir() + '/php/app_start.php'
return pstart
3 years ago
def installPreInspection(version):
3 years ago
# 仅对PHP52检查
if version != '52':
return 'ok'
sys = mw.execShell(
"cat /etc/*-release | grep PRETTY_NAME |awk -F = '{print $2}' | awk -F '\"' '{print $2}'| awk '{print $1}'")
if sys[1] != '':
return '不支持改系统'
sys_id = mw.execShell(
"cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F '\"' '{print $2}'")
sysName = sys[0].strip().lower()
sysId = sys_id[0].strip()
if sysName == 'ubuntu':
3 years ago
return 'ubuntu已经安装不了'
3 years ago
3 years ago
if sysName == 'debian' and int(sysId) > 10:
3 years ago
return 'debian10可以安装'
3 years ago
3 years ago
if sysName == 'centos' and int(sysId) > 8:
3 years ago
return 'centos[{}]不可以安装'.format(sysId)
3 years ago
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)
3 years ago
return 'ok'
3 years ago
7 years ago
if __name__ == "__main__":
6 years ago
if len(sys.argv) < 3:
4 years ago
print('missing parameters')
6 years ago
exit(0)
7 years ago
func = sys.argv[1]
7 years ago
version = sys.argv[2]
if func == 'status':
4 years ago
print(status(version))
7 years ago
elif func == 'start':
4 years ago
print(start(version))
7 years ago
elif func == 'stop':
4 years ago
print(stop(version))
7 years ago
elif func == 'restart':
4 years ago
print(restart(version))
7 years ago
elif func == 'reload':
4 years ago
print(reload(version))
3 years ago
elif func == 'install_pre_inspection':
print(installPreInspection(version))
6 years ago
elif func == 'initd_status':
4 years ago
print(initdStatus(version))
6 years ago
elif func == 'initd_install':
4 years ago
print(initdInstall(version))
6 years ago
elif func == 'initd_uninstall':
4 years ago
print(initdUinstall(version))
6 years ago
elif func == 'fpm_log':
4 years ago
print(fpmLog(version))
6 years ago
elif func == 'fpm_slow_log':
4 years ago
print(fpmSlowLog(version))
7 years ago
elif func == 'conf':
4 years ago
print(getConf(version))
5 years ago
elif func == 'app_start':
4 years ago
print(getConfAppStart())
6 years ago
elif func == 'get_php_conf':
4 years ago
print(getPhpConf(version))
3 years ago
elif func == 'get_fpm_conf_file':
print(getFpmConfFile(version))
1 year ago
elif func == 'get_fpm_file':
print(getFpmFile(version))
6 years ago
elif func == 'submit_php_conf':
4 years ago
print(submitPhpConf(version))
elif func == 'get_limit_conf':
4 years ago
print(getLimitConf(version))
elif func == 'set_max_time':
4 years ago
print(setMaxTime(version))
elif func == 'set_max_size':
4 years ago
print(setMaxSize(version))
6 years ago
elif func == 'get_fpm_conf':
4 years ago
print(getFpmConfig(version))
6 years ago
elif func == 'set_fpm_conf':
4 years ago
print(setFpmConfig(version))
6 years ago
elif func == 'get_fpm_status':
4 years ago
print(getFpmStatus(version))
elif func == 'get_session_conf':
print(getSessionConf(version))
elif func == 'set_session_conf':
print(setSessionConf(version))
elif func == 'get_session_count':
print(getSessionCount(version))
elif func == 'clean_session_old':
print(cleanSessionOld(version))
6 years ago
elif func == 'get_disable_func':
4 years ago
print(getDisableFunc(version))
6 years ago
elif func == 'set_disable_func':
4 years ago
print(setDisableFunc(version))
6 years ago
elif func == 'get_phpinfo':
4 years ago
print(getPhpinfo(version))
6 years ago
elif func == 'get_lib_conf':
4 years ago
print(getLibConf(version))
6 years ago
elif func == 'install_lib':
4 years ago
print(installLib(version))
6 years ago
elif func == 'uninstall_lib':
4 years ago
print(uninstallLib(version))
7 years ago
else:
4 years ago
print("fail")