openresty增加性能调整功能

pull/224/head
midoks 3 years ago
parent 314005e478
commit 78d3a091cd
  1. 10
      class/core/mw.py
  2. 5
      plugins/openresty/index.html
  3. 124
      plugins/openresty/index.py
  4. 77
      plugins/openresty/js/openresty.js
  5. 5
      plugins/php/js/php.js

@ -411,7 +411,7 @@ def writeFile(filename, str):
return False return False
def backFile(self, file, act=None): def backFile(file, act=None):
""" """
@name 备份配置文件 @name 备份配置文件
@param file 需要备份的文件 @param file 需要备份的文件
@ -420,10 +420,12 @@ def backFile(self, file, act=None):
file_type = "_bak" file_type = "_bak"
if act: if act:
file_type = "_def" file_type = "_def"
execShell("/usr/bin/cp -p {0} {1}".format(file, file + file_type))
# print("cp -p {0} {1}".format(file, file + file_type))
execShell("cp -p {0} {1}".format(file, file + file_type))
def restoreFile(self, file, act=None):
def restoreFile(file, act=None):
""" """
@name 还原配置文件 @name 还原配置文件
@param file 需要还原的文件 @param file 需要还原的文件
@ -432,7 +434,7 @@ def restoreFile(self, file, act=None):
file_type = "_bak" file_type = "_bak"
if act: if act:
file_type = "_def" file_type = "_def"
execShell("/usr/bin/cp -p {1} {0}".format(file, file + file_type)) execShell("cp -p {1} {0}".format(file, file + file_type))
def HttpGet(url, timeout=10): def HttpGet(url, timeout=10):

@ -4,7 +4,8 @@
<p class="bgw" onclick="orPluginService('openresty');">服务</p> <p class="bgw" onclick="orPluginService('openresty');">服务</p>
<p onclick="pluginInitD('openresty');">自启动</p> <p onclick="pluginInitD('openresty');">自启动</p>
<p onclick="pluginConfig('openresty');">配置修改</p> <p onclick="pluginConfig('openresty');">配置修改</p>
<p onclick="getOpenrestyStatus();">负载状态</p> <p onclick="getOpStatus();">负载状态</p>
<p onclick="setOpCfg();">性能调整</p>
<p onclick="pluginLogs('openresty');">错误日志</p> <p onclick="pluginLogs('openresty');">错误日志</p>
</div> </div>
<div class="bt-w-con pd15"> <div class="bt-w-con pd15">
@ -14,9 +15,7 @@
</div> </div>
<!-- <script type="text/javascript" src="/plugins/file?name=openresty&f=js/openresty.js"></script> -->
<script type="text/javascript"> <script type="text/javascript">
$.getScript( "/plugins/file?name=openresty&f=js/openresty.js", function(){ $.getScript( "/plugins/file?name=openresty&f=js/openresty.js", function(){
orPluginService('openresty'); orPluginService('openresty');
}); });

@ -6,6 +6,7 @@ import os
import time import time
import threading import threading
import subprocess import subprocess
import re
sys.path.append(os.getcwd() + "/class/core") sys.path.append(os.getcwd() + "/class/core")
import mw import mw
@ -52,6 +53,13 @@ def getArgs():
return tmp 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 clearTemp(): def clearTemp():
path_bin = getServerDir() + "/nginx" path_bin = getServerDir() + "/nginx"
mw.execShell('rm -rf ' + path_bin + '/client_body_temp') mw.execShell('rm -rf ' + path_bin + '/client_body_temp')
@ -232,7 +240,7 @@ def restyOp_restart():
check = getServerDir() + "/bin/openresty -t" check = getServerDir() + "/bin/openresty -t"
check_data = mw.execShell(check) check_data = mw.execShell(check)
if not check_data[1].find('test is successful') > -1: if not check_data[1].find('test is successful') > -1:
return check_data[1] return 'ERROR: 配置出错<br><a style="color:red;">' + check_data[1].replace("\n", '<br>') + '</a>'
if not mw.isAppleSystem(): if not mw.isAppleSystem():
threading.Timer(2, op_submit_systemctl_restart, args=()).start() threading.Timer(2, op_submit_systemctl_restart, args=()).start()
@ -291,7 +299,7 @@ def initdUinstall():
def runInfo(): def runInfo():
# 取Openresty负载状态 # 取Openresty负载状态
try: try:
url = 'http://' + mw.getHostAddr() + '/nginx_status' url = 'http://127.0.0.1/nginx_status'
result = mw.httpGet(url) result = mw.httpGet(url)
tmp = result.split() tmp = result.split()
data = {} data = {}
@ -304,7 +312,8 @@ def runInfo():
data['Waiting'] = tmp[15] data['Waiting'] = tmp[15]
return mw.getJson(data) return mw.getJson(data)
except Exception as e: except Exception as e:
url = 'http://127.0.0.1/nginx_status'
url = 'http://' + mw.getHostAddr() + '/nginx_status'
result = mw.httpGet(url) result = mw.httpGet(url)
tmp = result.split() tmp = result.split()
data = {} data = {}
@ -324,6 +333,111 @@ def errorLogPath():
return getServerDir() + '/nginx/logs/error.log' return getServerDir() + '/nginx/logs/error.log'
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},
{"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},
]
# {"name": "client_body_buffer_size", "ps": "请求主体缓冲区"}
rdata = []
for i in cfg_args:
rep = "(%s)\s+(\w+)" % i["name"]
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)
def setCfg():
args = getArgs()
data = checkArgs(args, [
'worker_processes', 'worker_connections', 'keepalive_timeout',
'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},
{"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)
rep = "%s\s+[^kKmMgG\;\n]+" % k
if k == "worker_processes" or k == "gzip":
if not re.search("auto|on|off|\d+", v):
return mw.returnJson(False, '参数值错误')
else:
if not re.search("\d+", v):
return mw.returnJson(False, '参数值错误,请输入数字整数')
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, '设置成功')
def installPreInspection(): def installPreInspection():
return 'ok' return 'ok'
@ -356,5 +470,9 @@ if __name__ == "__main__":
print(runInfo()) print(runInfo())
elif func == 'error_log': elif func == 'error_log':
print(errorLogPath()) print(errorLogPath())
elif func == 'get_cfg':
print(getCfg())
elif func == 'set_cfg':
print(setCfg())
else: else:
print('error') print('error')

@ -111,7 +111,7 @@ function orPluginOpServiceOp(a,b,c,d,a,v,request_callback){
//查看Nginx负载状态 //查看Nginx负载状态
function getOpenrestyStatus() { function getOpStatus() {
var loadT = layer.msg('正在处理,请稍后...', { icon: 16, time: 0, shade: 0.3 }); var loadT = layer.msg('正在处理,请稍后...', { icon: 16, time: 0, shade: 0.3 });
$.post('/plugins/run', {name:'openresty', func:'run_info'}, function(data) { $.post('/plugins/run', {name:'openresty', func:'run_info'}, function(data) {
layer.close(loadT); layer.close(loadT);
@ -136,3 +136,78 @@ function getOpenrestyStatus() {
} }
},'json'); },'json');
} }
function setOpCfg(){
orPost('get_cfg', {}, function(data){
var rdata = $.parseJSON(data.data);
var rdata = rdata.data;
console.log(rdata);
var mlist = '';
for (var i = 0; i < rdata.length; i++) {
var w = '70'
var ibody = '<input style="width: ' + w + 'px;" class="bt-input-text mr5" name="' + rdata[i].name + '" value="' + rdata[i].value + '" type="text" >';
switch (rdata[i].type) {
case 0:
var selected_1 = (rdata[i].value == 1) ? 'selected' : '';
var selected_0 = (rdata[i].value == 0) ? 'selected' : '';
ibody = '<select class="bt-input-text mr5" name="' + rdata[i].name + '" style="width: ' + w + 'px;">\
<option value="1" ' + selected_1 + '>开启</option>\
<option value="0" ' + selected_0 + '>关闭</option>\
</select>';
break;
case 1:
var selected_1 = (rdata[i].value == 'on') ? 'selected' : '';
var selected_0 = (rdata[i].value == 'off') ? 'selected' : '';
ibody = '<select class="bt-input-text mr5" name="' + rdata[i].name + '" style="width: ' + w + 'px;">\
<option value="on" ' + selected_1 + '>开启</option>\
<option value="off" ' + selected_0 + '>关闭</option>\
</select>';
break;
}
mlist += '<p style="margin-top:15px;"><span>' + rdata[i].name + '</span>' + ibody + "<b class='unit c9'>"+rdata[i].unit+"</b>" +', <font class="c9">' + rdata[i].ps + '</font></p>';
}
var con = '<style>.conf_p p{margin-bottom: 2px}</style><div class="conf_p" style="margin-bottom:0">\
' + mlist + '\
<div style="margin-top:10px; padding-right:15px" class="text-right">\
<button class="btn btn-success btn-sm mr5" onclick="setOpCfg()">刷新</button>\
<button class="btn btn-success btn-sm" onclick="submitConf()">保存</button>\
</div>\
</div>'
$(".soft-man-con").html(con);
});
}
function submitConf() {
var data = {
worker_processes: $("input[name='worker_processes']").val(),
worker_connections: $("input[name='worker_connections']").val(),
keepalive_timeout: $("input[name='keepalive_timeout']").val(),
gzip: $("select[name='gzip']").val() || 'on',
gzip_min_length: $("input[name='gzip_min_length']").val(),
gzip_comp_level: $("input[name='gzip_comp_level']").val(),
client_max_body_size: $("input[name='client_max_body_size']").val(),
server_names_hash_bucket_size: $("input[name='server_names_hash_bucket_size']").val(),
client_header_buffer_size: $("input[name='client_header_buffer_size']").val(),
};
// console.log(data);
orPost('set_cfg', data, function(rdata){
var rdata = $.parseJSON(rdata.data);
console.log(rdata);
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
});
}

@ -81,7 +81,10 @@ function phpSetConfig(version) {
} }
var phpCon = '<style>.conf_p p{margin-bottom: 2px}</style><div class="conf_p" style="margin-bottom:0">\ var phpCon = '<style>.conf_p p{margin-bottom: 2px}</style><div class="conf_p" style="margin-bottom:0">\
' + mlist + '\ ' + mlist + '\
<div style="margin-top:10px; padding-right:15px" class="text-right"><button class="btn btn-success btn-sm mr5" onclick="phpSetConfig(' + version + ')">刷新</button><button class="btn btn-success btn-sm" onclick="submitConf(' + version + ')"></button></div>\ <div style="margin-top:10px; padding-right:15px" class="text-right">\
<button class="btn btn-success btn-sm mr5" onclick="phpSetConfig(' + version + ')">刷新</button>\
<button class="btn btn-success btn-sm" onclick="submitConf(' + version + ')">保存</button>\
</div>\
</div>' </div>'
$(".soft-man-con").html(phpCon); $(".soft-man-con").html(phpCon);
}); });

Loading…
Cancel
Save