diff --git a/plugins/nezha/index.html b/plugins/nezha/index.html
index 7e27470a7..40c159ea9 100755
--- a/plugins/nezha/index.html
+++ b/plugins/nezha/index.html
@@ -4,9 +4,11 @@
diff --git a/plugins/nezha/index.py b/plugins/nezha/index.py
index 93b8dc94e..05af3ba72 100755
--- a/plugins/nezha/index.py
+++ b/plugins/nezha/index.py
@@ -20,16 +20,13 @@ if mw.isAppleSystem():
class App:
__setupPath = '/www/server/nezha'
- __SR = ''
+ __cfg = ''
+ __agent_cfg = ''
def __init__(self):
self.__setupPath = self.getServerDir()
-
- self.__SR = '''#!/bin/bash
- PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
- export PATH
- export USER=%s
- export HOME=%s && ''' % ( self.getRunUser(), self.getHomeDir())
+ self.__cfg = self.__setupPath + '/nezha.cfg'
+ self.__agent_cfg = self.__setupPath + '/agent.cfg'
def getArgs(self):
args = sys.argv[3:]
@@ -38,15 +35,21 @@ class App:
if args_len == 1:
t = args[0].strip('{').strip('}')
- t = t.split(':')
+ t = t.split(':', 1)
tmp[t[0]] = t[1]
elif args_len > 1:
for i in range(len(args)):
- t = args[i].split(':')
+ t = args[i].split(':', 1)
tmp[t[0]] = t[1]
return tmp
+ def checkArgs(self, 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 __release_port(self, port):
from collections import namedtuple
try:
@@ -74,6 +77,10 @@ class App:
path = self.getPluginDir() + "/init.d/nezha.tpl"
return path
+ def getInitdAgentConfTpl(self):
+ path = self.getPluginDir() + "/init.d/nezha-agent.tpl"
+ return path
+
def getHomeDir(self):
if mw.isAppleSystem():
user = mw.execShell(
@@ -146,32 +153,49 @@ class App:
return file_bin
+ def contentAgentReplace(self, content):
+ path = self.__agent_cfg
+ if os.path.exists(path):
+ data = self.get_agent_cfg()
+ content = content.replace('{$APP_HOST}', data['host'])
+ content = content.replace('{$APP_SECRET}', data['secret'])
+
+ return content
+
def initDAgent(self):
+ file_tpl = self.getInitdAgentConfTpl()
+
initD_path = self.getServerDir() + '/init.d'
if not os.path.exists(initD_path):
os.mkdir(initD_path)
file_agent_bin = initD_path + '/nezha-agent'
- if not os.path.exists(file_agent_bin):
- content = mw.readFile(file_tpl)
- content = self.contentReplace(content)
- mw.writeFile(file_agent_bin, content)
- mw.execShell('chmod +x ' + file_agent_bin)
+
+ content = mw.readFile(file_tpl)
+ content = self.contentReplace(content)
+ content = self.contentAgentReplace(content)
+ mw.writeFile(file_agent_bin, content)
+ mw.execShell('chmod +x ' + file_agent_bin)
# systemd
sysDir = mw.systemdCfgDir()
sysService = sysDir + '/nezha-agent.service'
sysServiceTpl = self.getPluginDir() + '/init.d/nezha-agent.service.tpl'
- if os.path.exists(sysDir) and not os.path.exists(sysService):
- service_path = mw.getServerDir()
- content = mw.readFile(sysServiceTpl)
- content = self.contentReplace(content)
- mw.writeFile(sysService, content)
- mw.execShell('systemctl daemon-reload')
+ service_path = mw.getServerDir()
+ content = mw.readFile(sysServiceTpl)
+ content = self.contentReplace(content)
+ content = self.contentAgentReplace(content)
+ mw.writeFile(sysService, content)
+ mw.execShell('systemctl daemon-reload')
return file_agent_bin
def imOp(self, method):
+
+ path = self.__agent_cfg
+ if not os.path.exists(path):
+ return '请先设置Agent配置!'
+
file = self.initDreplace()
if not mw.isAppleSystem():
@@ -243,12 +267,70 @@ class App:
def conf(self):
return self.getServerDir() + '/dashboard/data/config.yaml'
- def run_log(self):
- ilog = self.getServerDir() + '/logs/imail.log'
- if not os.path.exists(ilog):
- return mw.returnJson(False, "请先安装初始化!
默认地址:http://" + mw.getLocalIp() + ":1080")
+ def nezha_cfg(self):
+ path = self.__cfg
+ if not os.path.exists(path):
+ d = {}
+ cmd_un = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -u ""'
+ td = mw.execShell(cmd_un)
+ d['username'] = td[0].strip()
- return self.getServerDir() + '/logs/imail.log'
+ pwd = mw.getRandomString(16)
+ cmd_pwd = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -u "" -p ' + pwd
+ td = mw.execShell(cmd_pwd)
+ d['password'] = pwd
+
+ mw.writeFile(path, mw.enDoubleCrypt('nezha', mw.getJson(d)))
+
+ info = mw.readFile(path)
+ info = mw.deDoubleCrypt('nezha', info)
+
+ info = json.loads(info)
+ return mw.returnJson(True, 'ok', info)
+
+ def nezha_save_cfg(self):
+ args = self.getArgs()
+ data = self.checkArgs(args, ['username', 'password'])
+ if not data[0]:
+ return data[1]
+ path = self.__cfg
+
+ cmd = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -u "' + \
+ args['username'] + '" -p ' + args['password']
+ t = mw.execShell(cmd)
+ # print(t)
+ mw.writeFile(path, mw.enDoubleCrypt('nezha', mw.getJson(args)))
+ return mw.returnJson(True, '修改成功!')
+
+ def get_agent_cfg(self):
+ path = self.__agent_cfg
+ info = mw.readFile(path)
+ info = mw.deDoubleCrypt('agent', info)
+ info = json.loads(info)
+ return info
+
+ def agent_cfg(self):
+ path = self.__agent_cfg
+ if not os.path.exists(path):
+ d = {}
+ d['host'] = '127.0.0.1:5555'
+ d['secret'] = 'secret'
+ mw.writeFile(path, mw.enDoubleCrypt('agent', mw.getJson(d)))
+
+ info = self.get_agent_cfg()
+ return mw.returnJson(True, 'ok', info)
+
+ def agent_save_cfg(self):
+ args = self.getArgs()
+ data = self.checkArgs(args, ['host', 'secret'])
+ if not data[0]:
+ return data[1]
+ path = self.__agent_cfg
+ mw.writeFile(path, mw.enDoubleCrypt('agent', mw.getJson(args)))
+ return mw.returnJson(True, '修改成功!')
+
+ def run_log(self):
+ return self.getServerDir() + '/logs/nezha.log'
if __name__ == "__main__":
diff --git a/plugins/nezha/init.d/nezha-agent.service.tpl b/plugins/nezha/init.d/nezha-agent.service.tpl
index ee2d5dc00..4d36207c8 100644
--- a/plugins/nezha/init.d/nezha-agent.service.tpl
+++ b/plugins/nezha/init.d/nezha-agent.service.tpl
@@ -14,8 +14,8 @@ After=syslog.target
Type=simple
User=root
Group=root
-WorkingDirectory=/opt/nezha/agent/
-ExecStart=/opt/nezha/agent/nezha-agent -s nz_grpc_host:nz_grpc_port -p nz_client_secret
+WorkingDirectory={$SERVER_PATH}/nezha/agent/
+ExecStart={$SERVER_PATH}/nezha/agent/nezha-agent -s {$APP_HOST} -p {$APP_SECRET}
Restart=always
#Environment=DEBUG=true
diff --git a/plugins/nezha/init.d/nezha-agent.tpl b/plugins/nezha/init.d/nezha-agent.tpl
index 2b053d938..d6dd23fd9 100644
--- a/plugins/nezha/init.d/nezha-agent.tpl
+++ b/plugins/nezha/init.d/nezha-agent.tpl
@@ -1,15 +1,15 @@
#!/bin/bash
# chkconfig: 2345 55 25
-# description: Nezha Service
+# description: Nezha Agent Service
### BEGIN INIT INFO
-# Provides: Nezha
+# Provides: Nezha Agent
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
-# Short-Description: starts Nezha
-# Description: starts the Nezha
+# Short-Description: starts Nezha Agent
+# Description: starts the Nezha Agent
### END INIT INFO
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
@@ -22,22 +22,25 @@ if [ -f /etc/rc.d/init.d/functions ];then
. /etc/rc.d/init.d/functions
fi
-SERVICENAME=nezha-agnet
-LOG_PATH={$SERVER_PATH}/${SERVICENAME}/logs
-APP_PATH={$SERVER_PATH}/${SERVICENAME}/agent
+SERVICENAME=nezha-agent
+LOG_PATH={$SERVER_PATH}/nezha/logs
+APP_PATH={$SERVER_PATH}/nezha/agent
+APP_HOST={$APP_HOST}
+APP_SECRET={$APP_SECRET}
app_start(){
- isStart=`ps -ef|grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
+ isStart=`ps -ef|grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
if [ "$isStart" == '' ];then
echo -e "Starting ${SERVICENAME}... \c"
- cd $APP_PATH && exec nohup ${APP_PATH}/${SERVICENAME} web >> ${LOG_PATH}/${SERVICENAME}.log 2>&1 &
+ cd $APP_PATH
+ exec nohup ${APP_PATH}/${SERVICENAME} -d -s ${APP_HOST} -p ${APP_SECRET} >> ${LOG_PATH}/${SERVICENAME}.log 2>&1 &
isStart=""
while [[ "$isStart" == "" ]];
do
echo -e ".\c"
sleep 0.5
- isStart=$(ps -ef|grep "${SERVICENAME} web" |grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}')
+ isStart=$(ps -ef|grep "${SERVICENAME}" |grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}')
let n+=1
if [ $n -gt 15 ];then
break;
@@ -54,7 +57,7 @@ app_start(){
}
app_stop(){
- pids=`ps -ef | grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" |awk '{print $2}'`
+ pids=`ps -ef | grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" |awk '{print $2}'`
arr=($pids)
echo -e "Stopping ${SERVICENAME}... \c"
for p in ${arr[@]}
@@ -66,7 +69,7 @@ app_stop(){
}
app_status(){
- isStart=`ps -ef | grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
+ isStart=`ps -ef | grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
if [ "$isStart" == '' ];then
echo -e "${SERVICENAME} not running"
else
diff --git a/plugins/nezha/init.d/nezha.service.tpl b/plugins/nezha/init.d/nezha.service.tpl
index 02a9af58e..0752b3eb5 100644
--- a/plugins/nezha/init.d/nezha.service.tpl
+++ b/plugins/nezha/init.d/nezha.service.tpl
@@ -14,8 +14,8 @@ After=mariadb.service mysqld.service postgresql.service memcached.service redis.
Type=simple
#User=root
#Group=root
-WorkingDirectory=/opt/nezha/dashboard/
-ExecStart=/opt/nezha/dashboard/nezha web
+WorkingDirectory={$SERVER_PATH}/nezha/dashboard/
+ExecStart={$SERVER_PATH}/nezha/dashboard/nezha web
Restart=always
#Environment=DEBUG=true
diff --git a/plugins/nezha/js/nezha.js b/plugins/nezha/js/nezha.js
index 8a0862bfc..c6715c0ff 100755
--- a/plugins/nezha/js/nezha.js
+++ b/plugins/nezha/js/nezha.js
@@ -3,16 +3,6 @@ var nezha = {
init: function () {
var _this = this;
},
-
- str2Obj:function(str){
- var data = {};
- kv = str.split('&');
- for(i in kv){
- v = kv[i].split('=');
- data[v[0]] = v[1];
- }
- return data;
- },
send:function(info){
var tips = info['tips'];
@@ -28,7 +18,7 @@ var nezha = {
data['version'] = $('.plugin_version').attr('version');
if (typeof(args) == 'string'){
- data['args'] = JSON.stringify(this.str2Obj(args));
+ data['args'] = JSON.stringify(toArrayObject(args));
} else {
data['args'] = JSON.stringify(args);
}
@@ -54,6 +44,7 @@ var nezha = {
}
},'json');
},
+
postCallback:function(info){
var tips = info['tips'];
var method = info['method'];
@@ -68,13 +59,12 @@ var nezha = {
data['version'] = $('.plugin_version').attr('version');
if (typeof(args) == 'string'){
- data['args'] = JSON.stringify(this.str2Obj(args));
+ data['args'] = JSON.stringify(toArrayObject(args));
} else {
data['args'] = JSON.stringify(args);
}
$.post('/plugins/callback', data, function(res) {
-
layer.close(loadT);
if (!res.status){
layer.msg(res.msg,{icon:2,time:10000});
@@ -91,5 +81,95 @@ var nezha = {
callback(res);
}
},'json');
+ },
+
+ repeatPwd:function (a, id) {
+ $("#"+id).val(randomStrPwd(a))
+ },
+
+ save_cfg:function(version){
+ var username = $("input[name='username']").val();
+ var password = $("input[name='password']").val();
+
+ this.send({
+ tips:'正在设置中...',
+ data:{'username':username,'password':password},
+ method:'nezha_save_cfg',
+ success:function(rdata){
+ layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
+ }
+ });
+ },
+
+ cfg:function(version){
+ this.send({
+ tips:'正在获取中...',
+ method:'nezha_cfg',
+ success:function(data){
+ var d = data.data;
+ var value = '
\
+ 用户名\
+ \
+ ,\
+
';
+
+ value += '
\
+ 密码\
+ \
+ ,\
+
';
+ var conf = '
\
+ ' + value + '\
+
\
+ \
+ \
+
\
+
'
+ $(".soft-man-con").html(conf);
+ }
+ });
+ },
+
+ agent_save_cfg:function(version){
+ var host = $("input[name='host']").val();
+ var secret = $("input[name='secret']").val();
+
+ this.send({
+ tips:'正在设置中...',
+ data:{'host':host,'secret':secret},
+ method:'agent_save_cfg',
+ success:function(rdata){
+ layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
+ }
+ });
+ },
+
+ agent_cfg:function(version){
+ this.send({
+ tips:'正在获取中...',
+ method:'agent_cfg',
+ success:function(data){
+ var d = data.data;
+ var value = '
\
+ 地址\
+ \
+ ,如1.1.1.1:5444\
+
';
+
+ value += '
\
+ 密钥\
+ \
+ ,密钥\
+
';
+ var conf = '
\
+ ' + value + '\
+
\
+ \
+ \
+
\
+
'
+ $(".soft-man-con").html(conf);
+ }
+ });
}
}