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/mongodb/index.py

398 lines
9.8 KiB

4 years ago
# coding:utf-8
import sys
import io
import os
import time
import re
1 year ago
import json
import datetime
4 years ago
sys.path.append(os.getcwd() + "/class/core")
import mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
4 years ago
# /usr/lib/systemd/system/mongod.service
# /var/lib/mongo
4 years ago
def getPluginName():
return 'mongodb'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getInitDFile():
if app_debug:
return '/tmp/' + getPluginName()
return '/etc/init.d/' + getPluginName()
def getConf():
2 years ago
path = getServerDir() + "/mongodb.conf"
return path
4 years ago
def getConfTpl():
path = getPluginDir() + "/config/mongodb.conf"
return path
def getInitDTpl():
path = getPluginDir() + "/init.d/" + getPluginName() + ".tpl"
return path
def getConfPort():
file = getConf()
content = mw.readFile(file)
rep = 'port\s*=\s*(.*)'
tmp = re.search(rep, content)
return tmp.groups()[0].strip()
4 years ago
def getArgs():
args = sys.argv[2:]
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
t = t.split(':')
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 status():
data = mw.execShell(
1 year ago
"ps -ef|grep mongod |grep -v grep | grep -v /Applications | grep -v python | grep -v mdserver-web | awk '{print $2}'")
4 years ago
if data[0] == '':
return 'stop'
return 'start'
def initDreplace():
file_tpl = getInitDTpl()
service_path = os.path.dirname(os.getcwd())
initD_path = getServerDir() + '/init.d'
if not os.path.exists(initD_path):
os.mkdir(initD_path)
file_bin = initD_path + '/' + getPluginName()
2 years ago
logs_dir = getServerDir() + '/logs'
if not os.path.exists(logs_dir):
os.mkdir(logs_dir)
data_dir = getServerDir() + '/data'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
install_ok = getServerDir() + "/install.lock"
if os.path.exists(install_ok):
return file_bin
mw.writeFile(install_ok, 'ok')
4 years ago
# 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)
# config replace
conf_content = mw.readFile(getConfTpl())
conf_content = conf_content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(getServerDir() + '/mongodb.conf', conf_content)
2 years ago
# systemd
systemDir = mw.systemdCfgDir()
systemService = systemDir + '/mongodb.service'
systemServiceTpl = getPluginDir() + '/init.d/mongodb.service.tpl'
if os.path.exists(systemDir) and not os.path.exists(systemService):
service_path = mw.getServerDir()
se_content = mw.readFile(systemServiceTpl)
se_content = se_content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(systemService, se_content)
mw.execShell('systemctl daemon-reload')
4 years ago
return file_bin
3 years ago
def mgOp(method):
file = initDreplace()
4 years ago
if mw.isAppleSystem():
3 years ago
data = mw.execShell(file + ' ' + method)
1 year ago
# print(data)
4 years ago
if data[1] == '':
return 'ok'
3 years ago
return data[1]
2 years ago
data = mw.execShell('systemctl ' + method + ' ' + getPluginName())
if data[1] == '':
return 'ok'
2 years ago
return 'fail'
4 years ago
3 years ago
def start():
2 years ago
mw.execShell(
2 years ago
'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/www/server/lib/openssl11/lib')
3 years ago
return mgOp('start')
4 years ago
3 years ago
3 years ago
def stop():
return mgOp('stop')
4 years ago
def reload():
3 years ago
return mgOp('reload')
3 years ago
def restart():
if os.path.exists("/tmp/mongodb-27017.sock"):
mw.execShell('rm -rf ' + "/tmp/mongodb-27017.sock")
4 years ago
3 years ago
return mgOp('restart')
4 years ago
def runInfo():
import pymongo
1 year ago
port = getConfPort()
client = pymongo.MongoClient(host='127.0.0.1', port=int(port), directConnection=True)
4 years ago
db = client.admin
serverStatus = db.command('serverStatus')
4 years ago
listDbs = client.list_database_names()
1 year ago
1 year ago
result = {}
result["host"] = serverStatus['host']
result["version"] = serverStatus['version']
result["uptime"] = serverStatus['uptime']
result['db_path'] = getServerDir() + "/data"
result["connections"] = serverStatus['connections']['current']
result["collections"] = len(listDbs)
pf = serverStatus['opcounters']
result['pf'] = pf
return mw.getJson(result)
def runDocInfo():
import pymongo
port = getConfPort()
client = pymongo.MongoClient(host='127.0.0.1', port=int(port), directConnection=True)
1 year ago
db = client.admin
serverStatus = db.command('serverStatus')
4 years ago
1 year ago
listDbs = client.list_database_names()
4 years ago
showDbList = []
1 year ago
result = {}
4 years ago
for x in range(len(listDbs)):
mongd = client[listDbs[x]]
stats = mongd.command({"dbstats": 1})
1 year ago
if 'operationTime' in stats:
del stats['operationTime']
4 years ago
1 year ago
if '$clusterTime' in stats:
del stats['$clusterTime']
showDbList.append(stats)
4 years ago
4 years ago
result["dbs"] = showDbList
4 years ago
return mw.getJson(result)
1 year ago
def runReplInfo():
import pymongo
port = getConfPort()
client = pymongo.MongoClient(host='127.0.0.1', port=int(port), directConnection=True)
1 year ago
db = client.admin
serverStatus = db.command('serverStatus')
result = {}
result['status'] = ''
result['doc_name'] = ''
if 'repl' in serverStatus:
repl = serverStatus['repl']
# print(repl)
result['status'] = ''
if 'ismaster' in repl and repl['ismaster']:
1 year ago
result['status'] = ''
if 'secondary' in repl and not repl['secondary']:
result['status'] = ''
1 year ago
result['setName'] = repl['setName']
result['primary'] = repl['primary']
result['me'] = repl['me']
1 year ago
hosts = repl['hosts']
result['hosts'] = ','.join(hosts)
1 year ago
return mw.returnJson(True, 'OK', result)
1 year ago
def test():
# https://pymongo.readthedocs.io/en/stable/examples/high_availability.html
import pymongo
from pymongo import ReadPreference
port = getConfPort()
client = pymongo.MongoClient(host='127.0.0.1', port=int(port), directConnection=True)
1 year ago
db = client.admin
# config = {
# '_id': 'test',
# 'members': [
# {'_id': 1, 'host': '127.0.0.1:27018','priority': 10 },
# {'_id': 2, 'host': '127.0.0.1:27019','priority': 1 },
# {'_id': 3, 'host': '127.0.0.1:27020','priority': 0 },
# # {'_id': 2, 'host': 'localhost:27019'}
# ]
# }
# rsStatus = client.admin.command("replSetInitiate", config)
# 需要通过命令行操作
1 year ago
# -> rs.initiate({
# _id: 'test',
# members: [{
# _id: 1,
# host: '127.0.0.1:27018',
# priority: 2 // 这个priority不设置为1,值越高,当主库故障的时候会优先被选举成主库
# }, {
# _id: 2,
# host: '127.0.0.1:27019',
# priority: 0 //设置为0则不能成为主库
# }, {
# _id: 3,
# host: '127.0.0.1:27020',
# priority: 1
# }]
# });
# > rs.status(); // 查询状态
# // "stateStr" : "PRIMARY", 主节点
# // "stateStr" : "SECONDARY", 副本节点
# > rs.add({"_id":3, "host":"127.0.0.1:27318","priority":0,"votes":0});
serverStatus = db.command('serverStatus')
print(serverStatus)
# return mw.returnJson(True, 'OK', result)
4 years ago
def initdStatus():
4 years ago
if mw.isAppleSystem():
3 years ago
return "Apple Computer does not support"
4 years ago
2 years ago
shell_cmd = 'systemctl status mongodb | grep loaded | grep "enabled;"'
4 years ago
data = mw.execShell(shell_cmd)
if data[0] == '':
return 'fail'
return 'ok'
4 years ago
def initdInstall():
4 years ago
if mw.isAppleSystem():
3 years ago
return "Apple Computer does not support"
4 years ago
2 years ago
mw.execShell('systemctl enable mongodb')
4 years ago
return 'ok'
def initdUinstall():
4 years ago
if mw.isAppleSystem():
3 years ago
return "Apple Computer does not support"
4 years ago
2 years ago
mw.execShell('systemctl disable mongodb')
4 years ago
return 'ok'
def runLog():
2 years ago
f = getServerDir() + '/logs/mongodb.log'
if os.path.exists(f):
return f
return getServerDir() + '/logs.pl'
4 years ago
3 years ago
def installPreInspection(version):
2 years ago
if mw.isAppleSystem():
return 'ok'
3 years ago
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()
2 years ago
supportOs = ['centos', 'ubuntu', 'debian', 'opensuse']
if not sysName in supportOs:
return '暂时仅支持{}'.format(','.join(supportOs))
3 years ago
return 'ok'
4 years ago
if __name__ == "__main__":
func = sys.argv[1]
3 years ago
version = "4.4"
if (len(sys.argv) > 2):
version = sys.argv[2]
4 years ago
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())
3 years ago
elif func == 'install_pre_inspection':
print(installPreInspection(version))
4 years ago
elif func == 'initd_status':
print(initdStatus())
elif func == 'initd_install':
print(initdInstall())
elif func == 'initd_uninstall':
print(initdUinstall())
elif func == 'run_info':
print(runInfo())
1 year ago
elif func == 'run_doc_info':
print(runDocInfo())
1 year ago
elif func == 'run_repl_info':
print(runReplInfo())
4 years ago
elif func == 'conf':
print(getConf())
elif func == 'run_log':
print(runLog())
1 year ago
elif func == 'test':
print(test())
4 years ago
else:
print('error')