mdserver-web/plugins/openresty/index.py

701 lines
20 KiB
Python
Raw Permalink Normal View History

2018-12-05 01:00:31 -05:00
# coding:utf-8
import sys
import io
import os
import time
2022-09-11 06:59:16 -04:00
import threading
2018-12-16 10:29:35 -05:00
import subprocess
2022-10-28 14:46:27 -04:00
import re
2018-12-05 01:00:31 -05:00
2024-11-04 14:29:36 -05:00
web_dir = os.getcwd() + "/web"
2024-11-09 10:25:16 -05:00
if os.path.exists(web_dir):
sys.path.append(web_dir)
os.chdir(web_dir)
2024-11-04 14:29:36 -05:00
import core.mw as mw
2018-12-05 01:00:31 -05:00
2018-12-07 06:12:18 -05:00
app_debug = False
2020-07-10 03:57:25 -04:00
if mw.isAppleSystem():
2018-12-07 06:12:18 -05:00
app_debug = True
def getPluginName():
return 'openresty'
def getPluginDir():
2020-07-10 03:57:25 -04:00
return mw.getPluginDir() + '/' + getPluginName()
2018-12-07 06:12:18 -05:00
def getServerDir():
2020-07-10 03:57:25 -04:00
return mw.getServerDir() + '/' + getPluginName()
2018-12-07 06:12:18 -05:00
def getInitDFile():
2023-08-24 03:02:20 -04:00
current_os = mw.getOs()
2023-08-24 09:02:36 -04:00
if current_os == 'darwin':
2018-12-07 06:12:18 -05:00
return '/tmp/' + getPluginName()
2023-08-24 03:02:20 -04:00
if current_os.startswith('freebsd'):
return '/etc/rc.d/' + getPluginName()
2018-12-07 06:12:18 -05:00
return '/etc/init.d/' + getPluginName()
2018-12-16 10:29:35 -05:00
def getArgs():
args = sys.argv[2:]
2024-11-04 14:29:36 -05:00
# print(args)
2018-12-16 10:29:35 -05:00
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
2024-11-04 14:29:36 -05:00
t = t.split(':',2)
2018-12-16 10:29:35 -05:00
tmp[t[0]] = t[1]
elif args_len > 1:
for i in range(len(args)):
2024-11-04 14:29:36 -05:00
t = args[i].split(':',2)
2018-12-16 10:29:35 -05:00
tmp[t[0]] = t[1]
2024-11-04 14:29:36 -05:00
# print(tmp)
2018-12-16 10:29:35 -05:00
return tmp
2022-10-28 14:46:27 -04:00
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'))
2018-12-07 23:42:02 -05:00
def clearTemp():
path_bin = getServerDir() + "/nginx"
2020-07-10 03:57:25 -04:00
mw.execShell('rm -rf ' + path_bin + '/client_body_temp')
mw.execShell('rm -rf ' + path_bin + '/fastcgi_temp')
mw.execShell('rm -rf ' + path_bin + '/proxy_temp')
mw.execShell('rm -rf ' + path_bin + '/scgi_temp')
mw.execShell('rm -rf ' + path_bin + '/uwsgi_temp')
2018-12-07 23:42:02 -05:00
2018-12-07 06:12:18 -05:00
def getConf():
2019-02-09 23:43:24 -05:00
path = getServerDir() + "/nginx/conf/nginx.conf"
2018-12-07 06:12:18 -05:00
return path
2019-02-25 02:18:08 -05:00
def getConfTpl():
path = getPluginDir() + '/conf/nginx.conf'
return path
2018-12-16 22:06:58 -05:00
def getOs():
data = {}
2020-07-10 03:57:25 -04:00
data['os'] = mw.getOs()
2018-12-16 22:06:58 -05:00
ng_exe_bin = getServerDir() + "/nginx/sbin/nginx"
2023-10-09 06:43:48 -04:00
2023-11-08 12:32:59 -05:00
# if mw.isAppleSystem():
# data['auth'] = True
# return mw.getJson(data)
2023-10-09 06:43:48 -04:00
2018-12-16 22:06:58 -05:00
if checkAuthEq(ng_exe_bin, 'root'):
data['auth'] = True
else:
data['auth'] = False
2020-07-10 03:57:25 -04:00
return mw.getJson(data)
2018-12-16 22:06:58 -05:00
2018-12-07 06:12:18 -05:00
def getInitDTpl():
path = getPluginDir() + "/init.d/nginx.tpl"
return path
2023-08-24 03:28:10 -04:00
def getPidFile():
file = getConf()
content = mw.readFile(file)
2024-07-24 00:30:50 -04:00
rep = r'pid\s*(.*);'
2023-08-24 03:28:10 -04:00
tmp = re.search(rep, content)
return tmp.groups()[0].strip()
2018-12-16 22:06:58 -05:00
def getFileOwner(filename):
import pwd
stat = os.lstat(filename)
uid = stat.st_uid
pw = pwd.getpwuid(uid)
return pw.pw_name
def checkAuthEq(file, owner='root'):
fowner = getFileOwner(file)
if (fowner == owner):
return True
return False
2018-12-07 06:12:18 -05:00
def confReplace():
2024-11-09 10:25:16 -05:00
service_path = mw.getServerDir()
2020-07-10 03:57:25 -04:00
content = mw.readFile(getConfTpl())
2018-12-07 06:12:18 -05:00
content = content.replace('{$SERVER_PATH}', service_path)
2018-12-08 02:47:40 -05:00
user = 'www'
user_group = 'www'
2018-12-16 22:06:58 -05:00
2023-08-22 06:25:46 -04:00
current_os = mw.getOs()
if current_os == 'darwin':
2018-12-16 22:06:58 -05:00
# macosx do
2023-11-08 12:32:59 -05:00
# user = mw.execShell(
# "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
user = 'midoks'
2018-12-08 02:47:40 -05:00
user_group = 'staff'
2018-12-07 23:42:02 -05:00
content = content.replace('{$EVENT_MODEL}', 'kqueue')
2023-08-22 06:25:46 -04:00
elif current_os.startswith('freebsd'):
content = content.replace('{$EVENT_MODEL}', 'kqueue')
2018-12-07 06:12:18 -05:00
else:
2018-12-07 23:42:02 -05:00
content = content.replace('{$EVENT_MODEL}', 'epoll')
2018-12-08 02:47:40 -05:00
content = content.replace('{$OS_USER}', user)
content = content.replace('{$OS_USER_GROUP}', user_group)
2018-12-07 06:12:18 -05:00
2023-01-07 02:55:56 -05:00
# ng_conf_md5 = ''
# ng_conf_md5_file = getServerDir() + '/nginx_conf.md5'
# if not os.path.exists(ng_conf_md5_file):
# ng_conf_md5 = mw.md5(content)
# mw.writeFile(ng_conf_md5_file, ng_conf_md5)
# else:
# ng_conf_md5 = mw.writeFile(ng_conf_md5_file).strip()
# 主配置文件
2019-04-23 12:15:01 -04:00
nconf = getServerDir() + '/nginx/conf/nginx.conf'
2023-01-07 02:49:37 -05:00
mw.writeFile(nconf, content)
2023-01-06 23:23:50 -05:00
# lua配置
lua_conf_dir = mw.getServerDir() + '/web_conf/nginx/lua'
if not os.path.exists(lua_conf_dir):
mw.execShell('mkdir -p ' + lua_conf_dir)
lua_conf = lua_conf_dir + '/lua.conf'
2023-02-13 01:35:14 -05:00
lua_conf_tpl = getPluginDir() + '/conf/lua.conf'
lua_content = mw.readFile(lua_conf_tpl)
lua_content = lua_content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(lua_conf, lua_content)
2023-01-06 23:23:50 -05:00
empty_lua = lua_conf_dir + '/empty.lua'
if not os.path.exists(empty_lua):
mw.writeFile(empty_lua, '')
2023-02-13 02:56:41 -05:00
mw.opLuaMakeAll()
2023-02-10 13:51:17 -05:00
# 静态配置
2022-06-28 12:42:16 -04:00
php_conf = mw.getServerDir() + '/web_conf/php/conf'
if not os.path.exists(php_conf):
mw.execShell('mkdir -p ' + php_conf)
static_conf = mw.getServerDir() + '/web_conf/php/conf/enable-php-00.conf'
2022-06-22 01:44:35 -04:00
if not os.path.exists(static_conf):
2022-07-04 21:26:52 -04:00
mw.writeFile(static_conf, 'set $PHP_ENV 0;')
2018-12-07 06:12:18 -05:00
2023-08-04 08:27:20 -04:00
# vhost
vhost_dir = mw.getServerDir() + '/web_conf/nginx/vhost'
vhost_tpl_dir = getPluginDir() + '/conf/vhost'
2024-11-30 12:40:56 -05:00
if not os.path.exists(vhost_dir):
2024-11-30 12:23:14 -05:00
mw.execShell('mkdir -p ' + vhost_dir)
2023-08-04 08:27:20 -04:00
vhost_list = ['0.websocket.conf', '0.nginx_status.conf']
for f in vhost_list:
a_conf = vhost_dir + '/' + f
a_conf_tpl = vhost_tpl_dir + '/' + f
if not os.path.exists(a_conf):
mw.writeFile(a_conf, mw.readFile(a_conf_tpl))
2025-12-04 15:11:16 -05:00
# copy resty lib
2025-12-04 15:15:42 -05:00
src_resty_dir = getPluginDir()+'/resty/*'
2025-12-04 15:11:16 -05:00
dst_resty_dir = getServerDir()+'/lualib/resty'
2025-12-04 15:13:51 -05:00
mw.execShell('cp -rf ' + src_resty_dir + ' ' + dst_resty_dir)
2025-12-04 15:11:16 -05:00
2018-12-07 06:12:18 -05:00
def initDreplace():
file_tpl = getInitDTpl()
2024-11-29 05:09:33 -05:00
service_path = mw.getServerDir()
2018-12-07 06:12:18 -05:00
initD_path = getServerDir() + '/init.d'
2020-06-02 11:05:53 -04:00
2022-06-18 00:55:27 -04:00
# OpenResty is not installed
2020-06-02 11:05:53 -04:00
if not os.path.exists(getServerDir()):
2021-05-09 12:13:32 -04:00
print("ok")
2020-06-02 11:05:53 -04:00
exit(0)
2022-06-18 00:55:27 -04:00
# init.d
2020-07-10 13:24:54 -04:00
file_bin = initD_path + '/' + getPluginName()
2018-12-07 06:12:18 -05:00
if not os.path.exists(initD_path):
os.mkdir(initD_path)
2020-07-10 13:24:54 -04:00
# initd replace
content = mw.readFile(file_tpl)
content = content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(file_bin, content)
mw.execShell('chmod +x ' + file_bin)
2018-12-07 06:12:18 -05:00
2023-02-16 02:49:55 -05:00
# config replace
confReplace()
2018-12-07 06:12:18 -05:00
2023-11-08 12:32:59 -05:00
# give nginx root permission
ng_exe_bin = getServerDir() + "/nginx/sbin/nginx"
if not checkAuthEq(ng_exe_bin, 'root'):
user = 'www'
user_group = 'www'
current_os = mw.getOs()
if current_os == 'darwin':
user = 'root'
user_group = 'staff'
args = getArgs()
if not 'pwd' in args:
print("权限不足,需要认证启动!")
exit(0)
sudoPwd = args['pwd']
cmd_own = 'chown -R ' + user+':' + user_group + ' ' + ng_exe_bin
mw.execShell('echo %s|sudo -S %s' % (sudoPwd, cmd_own))
cmd_mod = 'chmod 755 ' + ng_exe_bin
mw.execShell('echo %s|sudo -S %s' % (sudoPwd, cmd_mod))
cmd_s = 'chmod u+s ' + ng_exe_bin
mw.execShell('echo %s|sudo -S %s' % (sudoPwd, cmd_s))
2022-06-18 00:55:27 -04:00
# systemd
2022-07-11 02:02:52 -04:00
# /usr/lib/systemd/system
2022-07-11 01:49:25 -04:00
systemDir = mw.systemdCfgDir()
2022-06-18 00:55:27 -04:00
systemService = systemDir + '/openresty.service'
if os.path.exists(systemDir) and not os.path.exists(systemService):
2023-08-24 02:39:32 -04:00
systemServiceTpl = getPluginDir() + '/init.d/openresty.service.tpl'
2022-06-18 00:55:27 -04:00
se_content = mw.readFile(systemServiceTpl)
se_content = se_content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(systemService, se_content)
mw.execShell('systemctl daemon-reload')
2018-12-07 06:12:18 -05:00
return file_bin
2018-12-05 01:00:31 -05:00
def status():
2023-08-24 03:28:10 -04:00
pid_file = getPidFile()
if not os.path.exists(pid_file):
2018-12-05 01:00:31 -05:00
return 'stop'
return 'start'
2022-06-19 01:55:54 -04:00
def restyOp(method):
2022-06-19 01:56:23 -04:00
file = initDreplace()
2022-06-18 01:37:38 -04:00
2022-06-28 14:22:43 -04:00
# 启动时,先检查一下配置文件
check = getServerDir() + "/bin/openresty -t"
check_data = mw.execShell(check)
2022-07-27 02:19:30 -04:00
if not check_data[1].find('test is successful') > -1:
2022-06-28 14:22:43 -04:00
return check_data[1]
2023-08-24 06:09:16 -04:00
current_os = mw.getOs()
if current_os == "darwin":
2023-08-24 06:10:07 -04:00
data = mw.execShell(file + ' ' + method)
2022-06-18 01:37:38 -04:00
if data[1] == '':
return 'ok'
2022-07-05 22:42:54 -04:00
return data[1]
2022-06-18 01:37:38 -04:00
2023-08-24 06:09:16 -04:00
if current_os.startswith("freebsd"):
data = mw.execShell('service openresty ' + method)
if data[1] == '':
return 'ok'
return data[1]
2023-08-24 06:10:07 -04:00
data = mw.execShell('systemctl ' + method + ' openresty')
2018-12-07 06:12:18 -05:00
if data[1] == '':
2018-12-05 01:00:31 -05:00
return 'ok'
2018-12-20 00:29:05 -05:00
return data[1]
2018-12-05 01:00:31 -05:00
def op_submit_systemctl_restart():
2023-08-24 06:09:16 -04:00
current_os = mw.getOs()
if current_os.startswith("freebsd"):
mw.execShell('service openresty restart')
2023-08-24 06:33:48 -04:00
return True
2023-08-24 06:09:16 -04:00
2022-09-11 06:45:44 -04:00
mw.execShell('systemctl restart openresty')
2023-08-24 06:33:48 -04:00
return True
2022-09-11 06:45:44 -04:00
def op_submit_init_restart(file):
2022-09-11 06:45:44 -04:00
mw.execShell(file + ' restart')
2022-09-11 06:45:44 -04:00
def restyOp_restart():
file = initDreplace()
# 启动时,先检查一下配置文件
check = getServerDir() + "/bin/openresty -t"
check_data = mw.execShell(check)
if not check_data[1].find('test is successful') > -1:
2022-10-28 14:46:27 -04:00
return 'ERROR: 配置出错<br><a style="color:red;">' + check_data[1].replace("\n", '<br>') + '</a>'
2022-09-11 06:45:44 -04:00
if not mw.isAppleSystem():
2023-12-29 14:21:13 -05:00
threading.Timer(2, op_submit_systemctl_restart).start()
2022-09-11 06:45:44 -04:00
return 'ok'
threading.Timer(2, op_submit_init_restart, args=(file,)).start()
2022-09-11 06:45:44 -04:00
return 'ok'
2018-12-05 01:00:31 -05:00
2022-06-18 02:40:06 -04:00
def start():
2022-06-19 01:54:44 -04:00
return restyOp('start')
2022-06-18 01:37:38 -04:00
2022-06-18 02:40:06 -04:00
def stop():
2023-08-24 06:03:23 -04:00
r = restyOp('stop')
pid_file = getPidFile()
if os.path.exists(pid_file):
os.remove(pid_file)
return r
2018-12-07 06:12:18 -05:00
2025-05-29 06:45:55 -04:00
def restart():
2022-09-11 06:45:44 -04:00
return restyOp_restart()
2018-12-05 01:00:31 -05:00
def reload():
2023-08-04 08:27:20 -04:00
confReplace()
2022-06-19 01:54:44 -04:00
return restyOp('reload')
2018-12-07 06:12:18 -05:00
def initdStatus():
2023-08-24 02:41:58 -04:00
current_os = mw.getOs()
2023-08-24 09:00:47 -04:00
if current_os == 'darwin':
2022-06-18 00:55:27 -04:00
return "Apple Computer does not support"
2023-08-24 02:41:58 -04:00
if current_os.startswith('freebsd'):
initd_bin = getInitDFile()
if os.path.exists(initd_bin):
return 'ok'
2022-06-18 00:55:27 -04:00
shell_cmd = 'systemctl status openresty | grep loaded | grep "enabled;"'
data = mw.execShell(shell_cmd)
if data[0] == '':
return 'fail'
return 'ok'
2018-12-05 01:00:31 -05:00
2018-12-07 06:12:18 -05:00
def initdInstall():
2023-08-24 02:39:32 -04:00
current_os = mw.getOs()
2023-08-24 09:00:47 -04:00
if current_os == 'darwin':
2022-06-18 00:55:27 -04:00
return "Apple Computer does not support"
2023-08-24 02:39:32 -04:00
# freebsd initd install
if current_os.startswith('freebsd'):
2023-08-24 02:44:59 -04:00
import shutil
2023-08-24 02:39:32 -04:00
source_bin = initDreplace()
initd_bin = getInitDFile()
shutil.copyfile(source_bin, initd_bin)
mw.execShell('chmod +x ' + initd_bin)
2023-08-24 08:05:08 -04:00
mw.execShell('sysrc ' + getPluginName() + '_enable="YES"')
2023-08-24 06:56:19 -04:00
return 'ok'
2023-08-24 02:39:32 -04:00
2022-06-18 00:55:27 -04:00
mw.execShell('systemctl enable openresty')
2018-12-07 06:12:18 -05:00
return 'ok'
def initdUinstall():
2023-08-24 02:47:01 -04:00
current_os = mw.getOs()
2023-08-24 09:00:47 -04:00
if current_os == 'darwin':
2022-06-18 00:55:27 -04:00
return "Apple Computer does not support"
2019-04-23 12:15:01 -04:00
2023-08-24 02:47:01 -04:00
if current_os.startswith('freebsd'):
initd_bin = getInitDFile()
os.remove(initd_bin)
2023-08-24 08:05:08 -04:00
mw.execShell('sysrc ' + getPluginName() + '_enable="NO"')
2023-08-24 06:56:19 -04:00
return 'ok'
2023-08-24 02:47:01 -04:00
2022-06-18 00:55:27 -04:00
mw.execShell('systemctl disable openresty')
2018-12-07 06:12:18 -05:00
return 'ok'
2018-12-05 07:15:00 -05:00
2024-11-04 14:29:36 -05:00
def getNgxStatusPort():
ngx_status_file = mw.getServerDir() + '/web_conf/nginx/vhost/0.nginx_status.conf'
content = mw.readFile(ngx_status_file)
rep = r'listen\s*(.*);'
tmp = re.search(rep, content)
port = tmp.groups()[0].strip()
return port
2018-12-05 07:15:00 -05:00
2018-12-08 03:24:36 -05:00
def runInfo():
2024-09-09 10:56:52 -04:00
op_status = status()
if op_status == 'stop':
return mw.returnJson(False, "未启动!")
2024-11-04 14:29:36 -05:00
port = getNgxStatusPort()
2018-12-08 03:24:36 -05:00
# 取Openresty负载状态
2018-12-10 02:10:07 -05:00
try:
2024-11-04 14:29:36 -05:00
url = 'http://127.0.0.1:%s/nginx_status' % port
result = mw.httpGet(url, timeout=3)
2018-12-10 02:10:07 -05:00
tmp = result.split()
data = {}
data['active'] = tmp[2]
data['accepts'] = tmp[9]
data['handled'] = tmp[7]
data['requests'] = tmp[8]
data['Reading'] = tmp[11]
data['Writing'] = tmp[13]
data['Waiting'] = tmp[15]
2020-07-10 03:57:25 -04:00
return mw.getJson(data)
2018-12-10 02:10:07 -05:00
except Exception as e:
2025-04-15 11:49:42 -04:00
try:
url = 'http://' + mw.getHostAddr() + ':%s/nginx_status' % port
result = mw.httpGet(url)
tmp = result.split()
data = {}
data['active'] = tmp[2]
data['accepts'] = tmp[9]
data['handled'] = tmp[7]
data['requests'] = tmp[8]
data['Reading'] = tmp[11]
data['Writing'] = tmp[13]
data['Waiting'] = tmp[15]
return mw.getJson(data)
except Exception as e:
return mw.returnJson(False, "oprenresty异常!")
2022-06-22 15:20:45 -04:00
except Exception as e:
2024-09-09 11:04:09 -04:00
return mw.returnJson(False, "oprenresty not started!")
2018-12-08 03:24:36 -05:00
2018-12-09 22:42:13 -05:00
def errorLogPath():
return getServerDir() + '/nginx/logs/error.log'
2022-10-28 14:46:27 -04:00
def getCfg():
cfg = getConf()
content = mw.readFile(cfg)
unitrep = "[kmgKMG]"
cfg_args = [
{"name": "worker_processes", "ps": "处理进程,auto表示自动,数字表示进程数", 'type': 2},
{"name": "worker_connections", "ps": "最大并发链接数", 'type': 2},
{"name": "keepalive_timeout", "ps": "连接超时时间", 'type': 2},
2026-04-07 03:16:08 -04:00
{"name": "zstd", "ps": "是否开启zstd压缩传输", 'type': 1},
{"name": "brotli", "ps": "是否开启brotli压缩传输", 'type': 1},
{"name": "gzip", "ps": "是否开启gzip压缩传输", 'type': 1},
2022-10-28 14:46:27 -04:00
{"name": "gzip_min_length", "ps": "最小压缩文件", 'type': 2},
{"name": "gzip_comp_level", "ps": "压缩率", 'type': 2},
{"name": "client_max_body_size", "ps": "最大上传文件", 'type': 2},
{"name": "server_names_hash_bucket_size",
"ps": "服务器名字的hash表大小", 'type': 2},
{"name": "client_header_buffer_size", "ps": "客户端请求头buffer大小", 'type': 2},
]
# {"name": "client_body_buffer_size", "ps": "请求主体缓冲区"}
rdata = []
for i in cfg_args:
2024-07-24 00:30:50 -04:00
rep = r"(%s)\s+(\w+)" % i["name"]
2022-10-28 14:46:27 -04:00
k = re.search(rep, content)
if not k:
return mw.returnJson(False, "获取 key {} 失败".format(k))
k = k.group(1)
v = re.search(rep, content)
if not v:
return mw.returnJson(False, "获取 value {} 失败".format(v))
v = v.group(2)
if re.search(unitrep, v):
u = str.upper(v[-1])
v = v[:-1]
if len(u) == 1:
psstr = u + "B" + i["ps"]
else:
psstr = u + "" + i["ps"]
else:
u = ""
kv = {"name": k, "value": v, "unit": u,
"ps": i["ps"], "type": i["type"]}
rdata.append(kv)
return mw.returnJson(True, "ok", rdata)
2025-01-24 02:42:51 -05:00
def replaceChar(value, index, new_char):
return value[:index] + new_char + value[index+1:]
def makeWorkerCpuAffinity(val):
if val == "auto":
return "auto"
if mw.isNumber(val):
core_num = int(val)
default_core_str = "0"*core_num
core_num_arr = []
for x in range(core_num):
t = replaceChar(default_core_str, x , "1")
core_num_arr.append(t)
return " ".join(core_num_arr)
return 'auto'
2022-10-28 14:46:27 -04:00
def setCfg():
args = getArgs()
data = checkArgs(args, [
2026-04-07 03:23:08 -04:00
'worker_processes', 'worker_connections', 'keepalive_timeout','zstd','brotli',
2022-10-28 14:46:27 -04:00
'gzip', 'gzip_min_length', 'gzip_comp_level', 'client_max_body_size',
'server_names_hash_bucket_size', 'client_header_buffer_size'
])
if not data[0]:
return data[1]
cfg = getConf()
mw.backFile(cfg)
content = mw.readFile(cfg)
unitrep = "[kmgKMG]"
cfg_args = [
{"name": "worker_processes", "ps": "处理进程,auto表示自动,数字表示进程数", 'type': 2},
{"name": "worker_connections", "ps": "最大并发链接数", 'type': 2},
{"name": "keepalive_timeout", "ps": "连接超时时间", 'type': 2},
2026-04-07 03:18:28 -04:00
{"name": "zstd", "ps": "是否开启zstd压缩传输", 'type': 1},
{"name": "brotli", "ps": "是否开启brotli压缩传输", 'type': 1},
2022-10-28 14:46:27 -04:00
{"name": "gzip", "ps": "是否开启压缩传输", 'type': 1},
{"name": "gzip_min_length", "ps": "最小压缩文件", 'type': 2},
{"name": "gzip_comp_level", "ps": "压缩率", 'type': 2},
{"name": "client_max_body_size", "ps": "最大上传文件", 'type': 2},
{"name": "server_names_hash_bucket_size",
"ps": "服务器名字的hash表大小", 'type': 2},
{"name": "client_header_buffer_size", "ps": "客户端请求头buffer大小", 'type': 2},
]
# print(args)
for k, v in args.items():
# print(k, v)
2024-07-24 00:30:50 -04:00
rep = r"%s\s+[^kKmMgG\;\n]+" % k
2022-10-28 14:46:27 -04:00
if k == "worker_processes" or k == "gzip":
2024-07-24 00:33:44 -04:00
if not re.search(r"auto|on|off|\d+", v):
2022-10-28 14:46:27 -04:00
return mw.returnJson(False, '参数值错误')
2026-04-07 03:27:00 -04:00
elif k == "zstd" or k == "brotli":
2026-04-07 03:24:46 -04:00
if not re.search(r"auto|on|off|\d+", v):
return mw.returnJson(False, '参数值错误')
2022-10-28 14:46:27 -04:00
else:
2024-07-24 00:30:50 -04:00
if not re.search(r"\d+", v):
2022-10-28 14:46:27 -04:00
return mw.returnJson(False, '参数值错误,请输入数字整数')
2026-04-22 12:12:57 -04:00
if k == "brotli":
if v == "on":
2026-04-22 12:19:46 -04:00
# 批量替换所有以 #brotli 等开头的指令为 brotli
rep_var = r"#+brotli[\w_]*\s+[^\;\n]+"
2026-04-22 12:12:57 -04:00
newconf = lambda m: m.group(0).lstrip('#')
content = re.sub(rep_var, newconf, content)
if v == "off":
# 批量替换所有以 brotli 开头且没有 # 前缀的指令为 #brotli
rep_var = r"(?<!#)brotli[\w_]*\s+[^\;\n]+"
newconf = lambda m: '#' + m.group(0)
content = re.sub(rep_var, newconf, content)
if k == "zstd":
if v == "on":
# 批量替换所有以 #zstd 开头的指令为 zstd
2026-04-22 12:19:46 -04:00
rep_var = r"#+zstd[\w_]*\s+[^\;\n]+"
2026-04-22 12:12:57 -04:00
newconf = lambda m: m.group(0).lstrip('#')
content = re.sub(rep_var, newconf, content)
if v == "off":
# 批量替换所有以 zstd 开头且没有 # 前缀的指令为 #zstd
rep_var = r"(?<!#)zstd[\w_]*\s+[^\;\n]+"
newconf = lambda m: '#' + m.group(0)
content = re.sub(rep_var, newconf, content)
2025-01-24 02:42:51 -05:00
if k == "worker_processes" :
k_wca = "worker_cpu_affinity"
rep_wca = r"%s\s+[^\;\n]+" % k_wca
v_wca = makeWorkerCpuAffinity(v)
newconf = "%s %s" % (k_wca, v_wca)
content = re.sub(rep_wca, newconf, content)
2022-10-28 14:46:27 -04:00
if re.search(rep, content):
newconf = "%s %s" % (k, v)
content = re.sub(rep, newconf, content)
elif re.search(rep, content):
newconf = "%s %s" % (k, v)
content = re.sub(rep, newconf, content)
mw.writeFile(cfg, content)
isError = mw.checkWebConfig()
if (isError != True):
mw.restoreFile(cfg)
return mw.returnJson(False, 'ERROR: 配置出错<br><a style="color:red;">' + isError.replace("\n", '<br>') + '</a>')
mw.restartWeb()
return mw.returnJson(True, '设置成功')
2025-09-15 13:21:17 -04:00
def cronAddCheck():
try:
import tool_task
tool_task.createBgTask()
return mw.returnJson(True, '添加检查任务成功')
except Exception as e:
return mw.returnJson(False, '添加检查任务失败:'+str(e))
def cronDelCheck():
try:
import tool_task
tool_task.removeBgTask()
return mw.returnJson(True, '删除检查任务成功')
except Exception as e:
return mw.returnJson(False, '删除检查任务失败:'+str(e))
def cronCheck():
return 'ok'
2022-08-12 00:07:08 -04:00
def installPreInspection():
return 'ok'
2018-12-05 01:00:31 -05:00
if __name__ == "__main__":
2024-11-29 05:14:02 -05:00
version = '1.27.1'
2024-11-04 14:29:36 -05:00
version_pl = getServerDir() + "/version.pl"
2024-11-29 05:14:02 -05:00
if os.path.exists(version_pl):
version = mw.readFile(version_pl)
2024-11-04 14:29:36 -05:00
2018-12-05 01:00:31 -05:00
func = sys.argv[1]
if func == 'status':
2021-05-01 05:42:19 -04:00
print(status())
2018-12-05 01:00:31 -05:00
elif func == 'start':
2021-05-01 05:42:19 -04:00
print(start())
2018-12-05 01:00:31 -05:00
elif func == 'stop':
2021-05-01 05:42:19 -04:00
print(stop())
2018-12-07 23:42:02 -05:00
elif func == 'restart':
2021-05-01 05:42:19 -04:00
print(restart())
2018-12-05 01:00:31 -05:00
elif func == 'reload':
2021-05-01 05:42:19 -04:00
print(reload())
2018-12-07 06:12:18 -05:00
elif func == 'initd_status':
2021-05-01 05:42:19 -04:00
print(initdStatus())
2018-12-07 06:12:18 -05:00
elif func == 'initd_install':
2021-05-01 05:42:19 -04:00
print(initdInstall())
2018-12-07 06:12:18 -05:00
elif func == 'initd_uninstall':
2021-05-01 05:42:19 -04:00
print(initdUinstall())
2022-08-12 00:07:08 -04:00
elif func == 'install_pre_inspection':
print(installPreInspection())
2018-12-05 07:15:00 -05:00
elif func == 'conf':
2021-05-01 05:42:19 -04:00
print(getConf())
2018-12-16 10:29:35 -05:00
elif func == 'get_os':
2021-05-01 05:42:19 -04:00
print(getOs())
2018-12-08 03:24:36 -05:00
elif func == 'run_info':
2021-05-01 05:42:19 -04:00
print(runInfo())
2018-12-09 22:42:13 -05:00
elif func == 'error_log':
2021-05-01 05:42:19 -04:00
print(errorLogPath())
2022-10-28 14:46:27 -04:00
elif func == 'get_cfg':
print(getCfg())
elif func == 'set_cfg':
print(setCfg())
2025-09-15 13:21:17 -04:00
elif func == 'check':
print(cronCheck())
elif func == 'cron_add_check':
print(cronAddCheck())
elif func == 'cron_del_check':
print(cronDelCheck())
2018-12-05 01:00:31 -05:00
else:
2021-05-01 05:42:19 -04:00
print('error')