prometheus

This commit is contained in:
dami 2025-08-02 19:22:14 +08:00
parent 4d4f43fa93
commit 8ea34d5736
8 changed files with 538 additions and 0 deletions

BIN
plugins/prometheus/ico.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

31
plugins/prometheus/index.html Executable file
View File

@ -0,0 +1,31 @@
<style>
.overflow_hide {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
</style>
<div class="bt-form">
<div class='plugin_version'></div>
<div class="bt-w-main">
<div class="bt-w-menu">
<p class="bgw" onclick="pluginService('prometheus');">服务</p>
<p onclick="pluginInitD('prometheus');">自启动</p>
<p onclick="gCommonFunc($('.plugin_version').attr('version'));">常用功能</p>
<p onclick="pluginConfig('prometheus',$('.plugin_version').attr('version'),'conf');">配置</p>
<p onclick="pluginLogs('prometheus','','run_log');">运行日志</p>
<p onclick="gReadme();">相关说明</p>
</div>
<div class="bt-w-con pd15">
<div class="soft-man-con" style="height: 520px; overflow: auto;"></div>
</div>
</div>
</div>
<script type="text/javascript">
$.getScript( "/plugins/file?name=prometheus&f=js/prometheus.js", function(){
pluginService('prometheus', $('.plugin_version').attr('version'));
});
</script>

235
plugins/prometheus/index.py Executable file
View File

@ -0,0 +1,235 @@
# coding:utf-8
import sys
import io
import os
import time
import re
web_dir = os.getcwd() + "/web"
if os.path.exists(web_dir):
sys.path.append(web_dir)
os.chdir(web_dir)
import core.mw as mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'prometheus'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getInitDFile():
current_os = mw.getOs()
if current_os == 'darwin':
return '/tmp/' + getPluginName()
if current_os.startswith('freebsd'):
return '/etc/rc.d/' + getPluginName()
return '/etc/init.d/' + getPluginName()
def getConf():
path = getServerDir() + "/conf/defaults.ini"
return path
def getInitDTpl():
path = getPluginDir() + "/init.d/" + getPluginName() + ".tpl"
return path
def getArgs():
args = sys.argv[3:]
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
if t.strip() == '':
tmp = []
else:
t = t.split(':')
tmp[t[0]] = t[1]
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 getPidFile():
file = getConf()
content = mw.readFile(file)
rep = r'pidfile\s*(.*)'
tmp = re.search(rep, content)
return tmp.groups()[0].strip()
def status():
cmd = "ps aux|grep grafana |grep -v grep | grep -v python | grep -v mdserver-web | awk '{print $2}'"
data = mw.execShell(cmd)
if data[0] == '':
return 'stop'
return 'start'
def getInstallVerion():
version_pl = getServerDir() + "/version.pl"
version = mw.readFile(version_pl).strip()
return version
def contentReplace(content):
service_path = mw.getServerDir()
content = content.replace('{$ROOT_PATH}', mw.getFatherDir())
content = content.replace('{$SERVER_PATH}', service_path)
return content
def openPort():
try:
from utils.firewall import Firewall as MwFirewall
MwFirewall.instance().addAcceptPort('3000', 'grafana', 'port')
return port
except Exception as e:
return "Release failed {}".format(e)
return True
def initDreplace():
# 初始化OP配置
init_file = getServerDir() + '/init.pl'
if not os.path.exists(init_file):
openPort()
mw.writeFile(init_file, 'ok')
# systemd
systemDir = mw.systemdCfgDir()
systemService = systemDir + '/' + getPluginName() + '.service'
if os.path.exists(systemDir) and not os.path.exists(systemService):
systemServiceTpl = getPluginDir() + '/init.d/' + getPluginName() + '.service.tpl'
service_path = mw.getServerDir()
content = mw.readFile(systemServiceTpl)
content = content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(systemService, content)
mw.execShell('systemctl daemon-reload')
return True
def gOp(method):
initDreplace()
data = mw.execShell('systemctl ' + method + ' '+getPluginName())
mw.execShell('systemctl ' + method + ' '+getPluginName())
if data[1] == '':
return 'ok'
return data[1]
def start():
return gOp('start')
def stop():
return gOp('stop')
def restart():
return gOp('restart')
def reload():
return gOp('reload')
def initdStatus():
current_os = mw.getOs()
if current_os == 'darwin':
return "Apple Computer does not support"
shell_cmd = 'systemctl status grafana|grep loaded|grep "enabled;"'
data = mw.execShell(shell_cmd)
if data[0] == '':
return 'fail'
return 'ok'
def initdInstall():
current_os = mw.getOs()
if current_os == 'darwin':
return "Apple Computer does not support"
data = mw.execShell('systemctl enable grafana')
if data[1] != '':
return data[1]
return 'ok'
def initdUinstall():
current_os = mw.getOs()
if current_os == 'darwin':
return "Apple Computer does not support"
data = mw.execShell('systemctl disable grafana')
if data[1] != '':
return data[1]
return 'ok'
def runLog():
return getServerDir() + "/data/log/grafana.log"
def grafanaUrl():
ip = mw.getLocalIp()
return 'http://'+ip+':'+"3000"
def installPreInspection():
return 'ok'
def uninstallPreInspection():
return 'ok'
if __name__ == "__main__":
func = sys.argv[1]
if func == 'status':
print(status())
elif func == 'start':
print(start())
elif func == 'stop':
print(stop())
elif func == 'restart':
print(restart())
elif func == 'reload':
print(reload())
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())
elif func == 'uninstall_pre_inspection':
print(uninstallPreInspection())
elif func == 'conf':
print(getConf())
elif func == 'run_log':
print(runLog())
elif func == 'grafana_url':
print(grafanaUrl())
else:
print('error')

17
plugins/prometheus/info.json Executable file
View File

@ -0,0 +1,17 @@
{
"sort": 7,
"ps": "监控系统与时间序列数据库",
"name": "prometheus",
"title": "prometheus",
"shell": "install.sh",
"versions":["3.5.0"],
"tip": "soft",
"checks": "server/prometheus",
"path": "server/prometheus",
"display": 1,
"author": "midoks",
"date": "2025-08-02",
"home": "https://prometheus.io/download/",
"type": 0,
"pid": "5"
}

View File

@ -0,0 +1,13 @@
[Unit]
Description=Grafana instance
Documentation=http://docs.grafana.org
After=network-online.target
[Service]
Type=simple
User=grafana
Group=grafana
Restart=on-failure
ExecStart={$SERVER_PATH}/bin/grafana server --config={$SERVER_PATH}/grafana/conf/defa.defaults --homepath={$SERVER_PATH}/grafana
[Install]
WantedBy=multi-user.target

85
plugins/prometheus/install.sh Executable file
View File

@ -0,0 +1,85 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin:/opt/homebrew/bin
export PATH
# https://www.cnblogs.com/n00dle/p/16916044.html
# cd /www/server/mdserver-web/plugins/grafana && /bin/bash install.sh install 12.1.0
# cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/grafana/index.py start
curPath=`pwd`
rootPath=$(dirname "$curPath")
rootPath=$(dirname "$rootPath")
serverPath=$(dirname "$rootPath")
VERSION=$2
sysArch=`arch`
sysName=`uname`
echo "use system: ${sysName}"
OSNAME=`bash ${rootPath}/scripts/getos.sh`
if [ "" == "$OSNAME" ];then
OSNAME=`cat ${rootPath}/data/osname.pl`
fi
if [ "macos" == "$OSNAME" ];then
echo "不支持Macox"
exit
fi
if [ -f ${rootPath}/bin/activate ];then
source ${rootPath}/bin/activate
fi
# if id prometheus &> /dev/null ;then
# echo "prometheus uid is `id -u prometheus`"
# echo "prometheus shell is `grep "^prometheus:" /etc/passwd |cut -d':' -f7 `"
# else
# groupadd prometheus
# useradd -g prometheus -s /bin/bash prometheus
# fi
Install_App()
{
echo '正在安装脚本文件...'
mkdir -p $serverPath/source/prometheus
mkdir -p $serverPath/prometheus
echo "${VERSION}" > $serverPath/prometheus/version.pl
shell_file=${curPath}/versions/${VERSION}/linux.sh
if [ -f $shell_file ];then
bash -x $shell_file install ${VERSION}
else
echo '不支持...'
exit 1
fi
#初始化
cd ${rootPath} && python3 ${rootPath}/plugins/prometheus/index.py start
cd ${rootPath} && python3 ${rootPath}/plugins/prometheus/index.py initd_install
echo 'Prometheus安装完成'
}
Uninstall_App()
{
shell_file=${curPath}/versions/${VERSION}/linux.sh
if [ -f $shell_file ];then
bash -x $shell_file uninstall ${VERSION}
fi
cd ${rootPath} && python3 ${rootPath}/plugins/prometheus/index.py stop
cd ${rootPath} && python3 ${rootPath}/plugins/prometheus/index.py initd_uninstall
rm -rf $serverPath/prometheus
echo 'Prometheus卸载完成'
}
action=$1
if [ "${1}" == 'install' ];then
Install_App
else
Uninstall_App
fi

View File

@ -0,0 +1,97 @@
function gPost(method, version, args,callback){
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
var req_data = {};
req_data['name'] = 'grafana';
req_data['func'] = method;
req_data['version'] = version;
if (typeof(args) == 'string'){
req_data['args'] = JSON.stringify(toArrayObject(args));
} else {
req_data['args'] = JSON.stringify(args);
}
$.post('/plugins/run', req_data, function(data) {
layer.close(loadT);
if (!data.status){
//错误展示10S
layer.msg(data.msg,{icon:0,time:2000,shade: [10, '#000']});
return;
}
if(typeof(callback) == 'function'){
callback(data);
}
},'json');
}
function gPostCallbak(method, version, args,callback){
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
var req_data = {};
req_data['name'] = 'grafana';
req_data['func'] = method;
args['version'] = version;
if (typeof(args) == 'string'){
req_data['args'] = JSON.stringify(toArrayObject(args));
} else {
req_data['args'] = JSON.stringify(args);
}
$.post('/plugins/callback', req_data, function(data) {
layer.close(loadT);
if (!data.status){
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
return;
}
if(typeof(callback) == 'function'){
callback(data);
}
},'json');
}
function gCommonFunc(){
var con = '<hr/><p class="conf_p" style="text-align:center;">\
<button id="grafana_url" class="btn btn-default btn-sm">获取连接地址</button>\
</p>';
$(".soft-man-con").html(con);
$('#grafana_url').click(function(){
gPost('grafana_url', '', {}, function(rdata){
layer.open({
title: "Grafana连接",
area: ['600px', '180px'],
type:1,
closeBtn: 1,
shadeClose: false,
btn:["复制","取消"],
content: '<div class="pd15">\
<div class="divtable">\
<pre class="layui-code">'+rdata.data+'</pre>\
</div>\
</div>',
success:function(){
copyText(rdata.data);
},
yes:function(){
copyText(rdata.data);
}
});
});
});
}
function gReadme(){
var readme = '<ul class="help-info-text c7">';
readme += '<li>初始化账户:admin/admin</li>';
readme += '<li>https://grafana.com/grafana/download</li>';
readme += '</ul>';
$('.soft-man-con').html(readme);
}

View File

@ -0,0 +1,60 @@
#!/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")
sourcePath=${serverPath}/source
sysName=`uname`
SYS_VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'`
VERSION=$2
sysArch=`arch`
sysName=`uname`
ARCH_NAME=amd64
if [ "$sysArch" == "arm64" ];then
ARCH_NAME=arm64
elif [ "$sysArch" == "x86_64" ]; then
ARCH_NAME=amd64
elif [ "$sysArch" == "aarch64" ]; then
ARCH_NAME=aarch64
fi
FILE_TGZ=prometheus-${VERSION}.linux-${ARCH_NAME}.tar.gz
# 检查是否通
Install_App()
{
SourceDir=$serverPath/source/grafana
InstallDir=$serverPath/grafana
mkdir -p ${SourceDir}
mkdir -p ${InstallDir}
if [ ! -f ${SourceDir}/${FILE_TGZ} ];then
wget --no-check-certificate -O ${SourceDir}/${FILE_TGZ} https://github.com/prometheus/prometheus/releases/download/v${VERSION}/${FILE_TGZ}
fi
if [ ! -d $InstallDir/bin/grafana ];then
cd ${SourceDir} && tar -zxvf ${FILE_TGZ}
cd ${SourceDir}/grafana-v*
cp -rf ./* $InstallDir
fi
}
Uninstall_App()
{
echo "卸载成功"
}
action=${1}
if [ "${1}" == 'install' ];then
Install_App
else
Uninstall_App
fi