增加自建mysql接入

pull/42/head
StarsL.cn 2 years ago
parent fd33d23576
commit fd1d58921b

@ -7,7 +7,7 @@ skey_path = 'ConsulManager/assets/secret/skey'
if consul_kv.get_kv_dict(skey_path) == {}: if consul_kv.get_kv_dict(skey_path) == {}:
consul_kv.put_kv(skey_path,{'sk':''.join(str(uuid.uuid4()).split('-'))}) consul_kv.put_kv(skey_path,{'sk':''.join(str(uuid.uuid4()).split('-'))})
from views import login, blackbox, consul, jobs, nodes, selfnode, avd, exp, jms, edit_cloud from views import login, blackbox, consul, jobs, nodes, selfnode, selfrds, avd, exp, jms, edit_cloud
from views.prom import cloud_mysql_metrics from views.prom import cloud_mysql_metrics
from units.cloud import huaweicloud,alicloud,tencent_cloud from units.cloud import huaweicloud,alicloud,tencent_cloud
from units.avd import avd_list from units.avd import avd_list
@ -23,6 +23,7 @@ app.register_blueprint(consul.blueprint)
app.register_blueprint(jobs.blueprint) app.register_blueprint(jobs.blueprint)
app.register_blueprint(nodes.blueprint) app.register_blueprint(nodes.blueprint)
app.register_blueprint(selfnode.blueprint) app.register_blueprint(selfnode.blueprint)
app.register_blueprint(selfrds.blueprint)
app.register_blueprint(avd.blueprint) app.register_blueprint(avd.blueprint)
app.register_blueprint(exp.blueprint) app.register_blueprint(exp.blueprint)
app.register_blueprint(jms.blueprint) app.register_blueprint(jms.blueprint)

@ -0,0 +1,72 @@
import requests,json
import sys
sys.path.append("..")
from config import consul_token,consul_url
headers = {'X-Consul-Token': consul_token}
def get_all_list(vendor,account,region,group):
vendor = f'and Meta.vendor=="{vendor}"' if vendor != '' else f'and Meta.vendor != ""'
account = f'and Meta.account=="{account}"' if account != '' else f'and Meta.account != ""'
region = f'and Meta.region=="{region}"' if region != '' else f'and Meta.region != ""'
group = f'and Meta.group=="{group}"' if group != '' else f'and Meta.group != ""'
url = f'{consul_url}/agent/services?filter=Service == selfrds_exporter {vendor} {account} {region} {group}'
response = requests.get(url, headers=headers)
if response.status_code == 200:
info = response.json()
all_list = [i['Meta'] for i in info.values()]
vendor_list = sorted(list(set([i['vendor'] for i in all_list])))
account_list = sorted(list(set([i['account'] for i in all_list])))
region_list = sorted(list(set([i['region'] for i in all_list])))
group_list = sorted(list(set([i['group'] for i in all_list])))
return {'code': 20000,'all_list':all_list,'vendor_list':vendor_list,
'account_list':account_list,'region_list':region_list,'group_list':group_list}
else:
return {'code': 50000, 'data': f'{response.status_code}:{response.text}'}
def get_service():
response = requests.get(f'{consul_url}/agent/services?filter=Service == selfrds_exporter', headers=headers)
if response.status_code == 200:
info = response.json()
all_list = [i['Meta'] for i in info.values()]
vendor_list = sorted(list(set([i['vendor'] for i in all_list])))
account_list = sorted(list(set([i['account'] for i in all_list])))
region_list = sorted(list(set([i['region'] for i in all_list])))
group_list = sorted(list(set([i['group'] for i in all_list])))
return {'code': 20000,'all_list':all_list,'vendor_list':vendor_list,
'account_list':account_list,'region_list':region_list,'group_list':group_list}
else:
return {'code': 50000, 'data': f'{response.status_code}:{response.text}'}
def add_service(vendor,account,region,group,name,ip,port,os):
if port is None or name is None:
return {"code": 50000, "data": f"名称或IP不能为空"}
sid = f"{vendor}/{account}/{region}/{group}@{name}"
instance = f'{ip}:{port}'
if '//' in sid or sid.startswith('/') or sid.endswith('/'):
return {"code": 50000, "data": f"服务ID【{sid}】首尾不能包含'/',并且不能包含两个连续的'/'"}
data = {
"id": sid,
"name": 'selfrds_exporter',
'Address': ip,
'port': int(port),
"tags": [vendor,os],
"Meta": {'vendor':vendor,'account':account,'region':region,'group':group,
'name':name,'instance':instance,'os':os},
"check": {"tcp": instance,"interval": "60s"}
}
reg = requests.put(f'{consul_url}/agent/service/register', headers=headers, data=json.dumps(data))
if reg.status_code == 200:
return {"code": 20000, "data": f"{sid}】增加成功!"}
else:
return {"code": 50000, "data": f"{reg.status_code}{sid}{reg.text}"}
def del_service(vendor,account,region,group,name):
sid = f"{vendor}/{account}/{region}/{group}@{name}"
reg = requests.put(f'{consul_url}/agent/service/deregister/{sid}', headers=headers)
if reg.status_code == 200:
return {"code": 20000, "data": f"{sid}】删除成功!"}
else:
print(f"{reg.status_code}{sid}{reg.text}")
return {"code": 50000, "data": f"{reg.status_code}{sid}{reg.text}"}

@ -31,6 +31,22 @@ def importconsul(row,imptype):
'name':name,'instance':instance,'os':os}, 'name':name,'instance':instance,'os':os},
"check": {"tcp": instance,"interval": "60s"} "check": {"tcp": instance,"interval": "60s"}
} }
elif imptype == 'selfrds':
vendor,account,region,group,name,instance,os = row
print(row)
sid = f"{vendor}/{account}/{region}/{group}@{name}"
ip = instance.split(':')[0]
port = instance.split(':')[1]
data = {
"id": sid,
"name": 'selfrds_exporter',
'Address': ip,
'port': int(port),
"tags": [vendor,os],
"Meta": {'vendor':vendor,'account':account,'region':region,'group':group,
'name':name,'instance':instance,'os':os},
"check": {"tcp": instance,"interval": "60s"}
}
except Exception as e: except Exception as e:
print("【import】导入失败",e,flush=True) print("【import】导入失败",e,flush=True)
return {"code": 50000, "data": f"导入内容格式异常!{row}"} return {"code": 50000, "data": f"导入内容格式异常!{row}"}

@ -0,0 +1,69 @@
from flask import Blueprint
from flask_restful import reqparse, Resource, Api
import sys
sys.path.append("..")
from units import token_auth,selfrds_manager
from werkzeug.datastructures import FileStorage
from units import upload
blueprint = Blueprint('selfrds',__name__)
api = Api(blueprint)
parser = reqparse.RequestParser()
parser.add_argument('vendor',type=str)
parser.add_argument('account',type=str)
parser.add_argument('region',type=str)
parser.add_argument('group',type=str)
parser.add_argument('name',type=str)
parser.add_argument('ip',type=str)
parser.add_argument('port',type=str)
parser.add_argument('os',type=str)
parser.add_argument('del_dict',type=dict)
parser.add_argument('up_dict',type=dict)
parser.add_argument('file',type=FileStorage, location="files", help="File is wrong.")
class Upload(Resource):
@token_auth.auth.login_required
def post(self):
file = parser.parse_args().get("file")
try:
return upload.read_execl(file.read(),'selfrds')
except Exception as e:
print("【selfrds】导入失败",e,flush=True)
return {"code": 50000, "data": f"导入失败!"}
class GetAllList(Resource):
@token_auth.auth.login_required
def get(self):
args = parser.parse_args()
return selfrds_manager.get_all_list(args['vendor'],args['account'],args['region'],args['group'])
class SelfrdsApi(Resource):
decorators = [token_auth.auth.login_required]
def get(self):
return selfrds_manager.get_service()
def post(self):
args = parser.parse_args()
print('=======\n',args,flush=True)
return selfrds_manager.add_service(args['vendor'],args['account'],args['region'],
args['group'],args['name'],args['ip'],args['port'],args['os'])
def put(self):
args = parser.parse_args()
del_dict = args['del_dict']
up_dict = args['up_dict']
resp_del = selfrds_manager.del_service(del_dict['vendor'],del_dict['account'],
del_dict['region'],del_dict['group'],del_dict['name'])
resp_add = selfrds_manager.add_service(up_dict['vendor'],up_dict['account'],up_dict['region'],
up_dict['group'],up_dict['name'],up_dict['ip'],
up_dict['port'],up_dict['os'])
if resp_del["code"] == 20000 and resp_add["code"] == 20000:
return {"code": 20000, "data": f"更新成功!"}
else:
return {"code": 50000, "data": f"更新失败!"}
def delete(self):
args = parser.parse_args()
return selfrds_manager.del_service(args['vendor'],args['account'],args['region'],args['group'],args['name'])
api.add_resource(GetAllList,'/api/selfrds/alllist')
api.add_resource(SelfrdsApi, '/api/selfrds/service')
api.add_resource(Upload,'/api/selfrds/upload')

@ -0,0 +1,37 @@
import request from '@/utils/request-ops'
export function getAllList(vendor, account, region, group) {
return request({
url: '/api/selfrds/alllist',
method: 'get',
params: { vendor, account, region, group }
})
}
export function getAllInfo() {
return request({
url: '/api/selfrds/service',
method: 'get'
})
}
export function addService(data) {
return request({
url: '/api/selfrds/service',
method: 'post',
data
})
}
export function updateService(del_dict, up_dict) {
return request({
url: '/api/selfrds/service',
method: 'put',
data: { del_dict, up_dict }
})
}
export function delService(data) {
return request({
url: '/api/selfrds/service',
method: 'delete',
data
})
}

@ -46,7 +46,7 @@ Object.keys(filters).forEach(key => {
}) })
Vue.config.productionTip = false Vue.config.productionTip = false
Vue.prototype.VER = 'v0.9.5' Vue.prototype.VER = 'v0.9.6'
new Vue({ new Vue({
el: '#app', el: '#app',

@ -157,14 +157,12 @@ export const constantRoutes = [
component: () => import('@/views/rds/lists'), component: () => import('@/views/rds/lists'),
meta: { title: '云MySQL列表', icon: 'el-icon-cloudy' } meta: { title: '云MySQL列表', icon: 'el-icon-cloudy' }
}, },
/**
{ {
path: 'self', path: 'self',
name: '自建MySQL管理', name: '自建MySQL管理',
component: () => import('@/views/rds/self'), component: () => import('@/views/rds/self'),
meta: { title: '自建MySQL管理', icon: 'el-icon-s-platform' } meta: { title: '自建MySQL管理', icon: 'el-icon-s-platform' }
}, },
*/
{ {
path: 'pconfig', path: 'pconfig',
name: 'rds-pconfig', name: 'rds-pconfig',

@ -52,6 +52,7 @@ export default {
this.listLoading = true this.listLoading = true
getRdsServicesList().then(response => { getRdsServicesList().then(response => {
this.services_list = response.services_list this.services_list = response.services_list
this.services_list.push('selfrds_exporter')
}) })
getJobRds().then(response => { getJobRds().then(response => {
this.jobrds_list = response.jobrds this.jobrds_list = response.jobrds

@ -25,7 +25,7 @@
<el-upload <el-upload
style="margin-right: 9px;" style="margin-right: 9px;"
class="upload-demo" class="upload-demo"
action="/api/selfnode/upload" action="/api/selfrds/upload"
:headers="myHeaders" :headers="myHeaders"
:on-success="success" :on-success="success"
:on-error="error" :on-error="error"
@ -93,7 +93,7 @@
<span>{{ row.instance }}</span> <span>{{ row.instance }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column prop="os" label="系统" sortable align="center" width="80"> <el-table-column prop="os" label="主机系统" sortable align="center" width="80">
<template slot-scope="{row}"> <template slot-scope="{row}">
<span>{{ row.os }}</span> <span>{{ row.os }}</span>
</template> </template>
@ -131,7 +131,7 @@
<el-form-item label="名称" prop="name"> <el-form-item label="名称" prop="name">
<el-input v-model="temp.name" placeholder="请输入" clearable /> <el-input v-model="temp.name" placeholder="请输入" clearable />
</el-form-item> </el-form-item>
<el-form-item label="系统" prop="os"> <el-form-item label="主机" prop="os">
<el-select v-model="temp.os" placeholder="请选择" style="width: 130px;" @change="temp.port=osport[temp.os]"> <el-select v-model="temp.os" placeholder="请选择" style="width: 130px;" @change="temp.port=osport[temp.os]">
<el-option label="linux" value="linux" /> <el-option label="linux" value="linux" />
<el-option label="windows" value="windows" /> <el-option label="windows" value="windows" />
@ -165,7 +165,7 @@
import waves from '@/directive/waves' // waves directive import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getAllList, getAllInfo, addService, updateService, delService } from '@/api/selfnode' import { getAllList, getAllInfo, addService, updateService, delService } from '@/api/selfrds'
export default { export default {
name: 'ComplexTable', name: 'ComplexTable',
components: { Pagination }, components: { Pagination },
@ -214,7 +214,7 @@ export default {
region_list: [], region_list: [],
multipleSelection: [], multipleSelection: [],
del_dict: {}, del_dict: {},
osport: { linux: '9100', windows: '9182' }, osport: { linux: '3306', windows: '3306' },
temp: { temp: {
vendor: '', vendor: '',
account: '', account: '',
@ -394,7 +394,7 @@ export default {
region: this.listQuery.region, region: this.listQuery.region,
group: this.listQuery.group, group: this.listQuery.group,
os: 'linux', os: 'linux',
port: '9100' port: '3306'
} }
this.temp = Object.assign({}, this.temp, newone) this.temp = Object.assign({}, this.temp, newone)
this.dialogStatus = 'create' this.dialogStatus = 'create'
@ -435,7 +435,7 @@ export default {
region: this.temp.region, region: this.temp.region,
group: this.temp.group, group: this.temp.group,
os: 'linux', os: 'linux',
port: '9100' port: '3306'
} }
this.resetTemp() this.resetTemp()
this.temp = Object.assign({}, this.temp, newtemp) this.temp = Object.assign({}, this.temp, newtemp)
@ -526,13 +526,13 @@ export default {
handleDownload() { handleDownload() {
this.downloadLoading = true this.downloadLoading = true
import('@/vendor/Export2Excel').then(excel => { import('@/vendor/Export2Excel').then(excel => {
const tHeader = ['机房/公司', '租户/部门', '区域/项目', '分组/环境', '名称', '实例(IP:端口)', '系统(linux/windows)'] const tHeader = ['机房/公司', '租户/部门', '区域/项目', '分组/环境', '名称', '实例(IP:端口)', '主机系统(linux/windows)']
const filterVal = ['vendor', 'account', 'region', 'group', 'name', 'instance', 'os'] const filterVal = ['vendor', 'account', 'region', 'group', 'name', 'instance', 'os']
const data = this.formatJson(filterVal) const data = this.formatJson(filterVal)
excel.export_json_to_excel({ excel.export_json_to_excel({
header: tHeader, header: tHeader,
data, data,
filename: 'selfnode-list' filename: 'selfrds-list'
}) })
this.downloadLoading = false this.downloadLoading = false
}) })

Loading…
Cancel
Save