所有的json调用均返回错误值和错误信息,方便定位问题。

pull/32/head
apexliu 2017-04-23 18:02:38 +08:00
parent 94aebc3277
commit 3c3703d9a9
9 changed files with 287 additions and 364 deletions

View File

@ -9,8 +9,6 @@ from eom_common.eomcore.logger import *
from .base import TPBaseHandler, TPBaseUserAuthHandler, TPBaseJsonHandler, TPBaseUserAuthJsonHandler
from eom_app.app.util import gen_captcha
cfg = app_cfg()
class LoginHandler(TPBaseHandler):
def get(self):
@ -37,8 +35,7 @@ class VerifyUser(TPBaseJsonHandler):
def post(self):
code = self.get_session('captcha')
if code is None:
self.write_json(-1, '验证码已失效')
return
return self.write_json(-1, '验证码已失效')
self.del_session('captcha')
@ -50,23 +47,20 @@ class VerifyUser(TPBaseJsonHandler):
userpwd = args['userpwd']
remember = args['remember']
else:
self.write_json(-1, '系统内部错误')
return
return self.write_json(-1, '参数错误')
if code.lower() != captcha.lower():
self.write_json(-1, '验证码错误')
return
return self.write_json(-1, '验证码错误')
try:
user_id, account_type, nickname, locked = user.verify_user(username, userpwd)
if locked == 1:
return self.write_json(-1, '账号被锁定,请联系管理员!')
if user_id == 0:
if cfg.app_mode == APP_MODE_MAINTENANCE:
self.write_json(-2, '系统维护中,请稍候再试!')
if app_cfg().app_mode == APP_MODE_MAINTENANCE:
return self.write_json(-2, '系统维护中,请稍候再试!')
else:
self.write_json(-1, '用户名/密码错误!')
return
return self.write_json(-1, '用户名/密码错误!')
_user = self.get_session('user')
if _user is None:
@ -94,7 +88,7 @@ class VerifyUser(TPBaseJsonHandler):
except:
log.e('can not set session.')
self.write_json(-1, '无法记录用户登录状态')
return self.write_json(-1, '发生异常,无法登录!')
class LogoutHandler(TPBaseUserAuthHandler):
@ -118,22 +112,19 @@ class VerifyCaptchaHandler(TPBaseJsonHandler):
def post(self):
code = self.get_session('captcha')
if code is None:
self.write_json(-1)
return
return self.write_json(-1, '验证码已失效')
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
captcha = args['captcha']
else:
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
if code.lower() != captcha.lower():
self.write_json(-1)
return
return self.write_json(-1, '验证码错误')
self.write_json(0)
return self.write_json(0)
class ModifyPwd(TPBaseUserAuthJsonHandler):
@ -142,19 +133,20 @@ class ModifyPwd(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-11)
return
return self.write_json(-11, '参数错误')
_old_pwd = args['o_pwd']
_new_pwd = args['n_pwd']
if _old_pwd is None or _new_pwd is None:
self.write_json(-12)
return
return self.write_json(-12, '参数错误')
user_info = self.get_current_user()
try:
ret = user.modify_pwd(_old_pwd, _new_pwd, user_info['id'])
self.write_json(ret)
if 0 == ret:
return self.write_json(0)
else:
return self.write_json(-14, '数据库操作错误errcode{}'.format(ret))
except:
log.e('modify password failed.')
self.write_json(-13)
return self.write_json(-13, '发生异常')

View File

@ -45,7 +45,7 @@ class IndexHandler(TPBaseUserAuthHandler):
self.render('host/common_index.mako', page_param=json.dumps(param))
class UploadAndImportHandler(TPBaseAdminAuthJsonHandler):
class UploadAndImportHandler(TPBaseAdminAuthHandler):
# TODO: 导入操作可能会比较耗时,应该分离导入和获取导入状态两个过程,在页面上可以呈现导入进度,并列出导出成功/失败的项
@tornado.gen.coroutine
@ -62,11 +62,12 @@ class UploadAndImportHandler(TPBaseAdminAuthJsonHandler):
"""
ret = dict()
ret['code'] = 0
ret['msg'] = list() # 记录跳过的行(格式不正确,或者数据重复等)
ret['message'] = ''
ret['data'] = {}
ret['data']['msg'] = list() # 记录跳过的行(格式不正确,或者数据重复等)
csv_filename = ''
try:
# upload_path = os.path.join(os.path.dirname(__file__), 'csv-files') # 文件的暂存路径
upload_path = os.path.join(cfg.data_path, 'tmp') # 文件的暂存路径
if not os.path.exists(upload_path):
os.mkdir(upload_path)
@ -75,34 +76,35 @@ class UploadAndImportHandler(TPBaseAdminAuthJsonHandler):
now = time.localtime(time.time())
tmp_name = 'upload-{:04d}{:02d}{:02d}{:02d}{:02d}{:02d}.csv'.format(now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
csv_filename = os.path.join(upload_path, tmp_name)
with open(csv_filename, 'wb') as up:
up.write(meta['body'])
with open(csv_filename, 'wb') as f:
f.write(meta['body'])
# file encode maybe utf8 or gbk... check it out.
file_encode = None
with open(csv_filename, encoding='gbk') as up:
with open(csv_filename, encoding='gbk') as f:
try:
up.readlines()
f.readlines()
file_encode = 'gbk'
except:
log.e('open file:{} -1\n'.format(csv_filename))
pass
if file_encode is None:
with open(csv_filename, encoding='utf8') as up:
with open(csv_filename, encoding='utf8') as f:
try:
up.readlines()
f.readlines()
file_encode = 'utf8'
except:
log.e('open file:{} -2\n'.format(csv_filename))
pass
if file_encode is None:
os.remove(csv_filename)
self.write_json(-2)
log.e('file {} unknown encode.\n'.format(csv_filename))
return
log.e('file `{}` unknown encode, neither GBK nor UTF8.\n'.format(csv_filename))
ret['code'] = -2
ret['message'] = 'upload csv file is neither gbk nor utf8 encode.'
return self.write(json.dumps(ret).encode('utf8'))
with open(csv_filename, encoding=file_encode) as up:
csv_reader = csv.reader(up)
with open(csv_filename, encoding=file_encode) as f:
csv_reader = csv.reader(f)
is_first_line = True
for csv_recorder in csv_reader:
# 跳过第一行,那是格式说明
@ -119,9 +121,6 @@ class UploadAndImportHandler(TPBaseAdminAuthJsonHandler):
ret['msg'].append({'reason': '格式错误', 'line': ', '.join(csv_recorder)})
continue
# pro_type = int(line[6])
# host_port = int(line[3])
host_args = dict()
user_args = dict()
# 分组ID, 操作系统, IP地址, 端口, 协议, 状态, 描述, 系统用户, 系统密码, 是否加密,附加参数, 密钥ID, 认证类型
@ -142,26 +141,28 @@ class UploadAndImportHandler(TPBaseAdminAuthJsonHandler):
user_args['host_id'] = host_id
user_args['user_name'] = csv_recorder[7]
user_pswd = csv_recorder[8]
is_encrpty = int(csv_recorder[9])
is_encrypt = int(csv_recorder[9])
user_args['user_param'] = csv_recorder[10].replace('\\n', '\n')
user_args['cert_id'] = int(csv_recorder[11])
auth_mode = int(csv_recorder[12])
user_args['auth_mode'] = auth_mode
user_args['user_pswd'] = ''
ret_code = 0
if auth_mode == 0:
pass
elif auth_mode == 1:
try:
if is_encrpty == 0:
# ret_code, tmp_pswd = get_enc_data(user_pswd)
if is_encrypt == 0:
_yr = async_enc(user_pswd)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
ret['code'] = -3
ret['message'] = 'can not encrypt by core server.'
return self.write(json.dumps(ret).encode('utf8'))
if 'code' not in return_data or return_data['code'] != 0:
return self.write_json(-1)
ret['code'] = -4
ret['message'] = 'invalid result from encrypt by core server.'
return self.write(json.dumps(ret).encode('utf8'))
tmp_pswd = return_data['data']
@ -170,38 +171,33 @@ class UploadAndImportHandler(TPBaseAdminAuthJsonHandler):
user_args['user_pswd'] = tmp_pswd
except Exception:
ret_code = -1
log.e('get_enc_data() failed.\n')
if 0 != ret_code:
ret['msg'].append({'reason': '加密用户密码失败可能原因Teleport核心服务未启动', 'line': ', '.join(csv_recorder)})
log.e('get_enc_data() failed, error={}\n'.format(ret_code))
continue
except:
log.e('can not encrypt user password.\n')
ret['code'] = -5
ret['message'] = '发生异常'
return self.write(json.dumps(ret).encode('utf8'))
elif auth_mode == 2:
pass
# user_args['cert_id'] = int(csv_recorder[7])
else:
ret['msg'].append({'reason': '未知的认证模式', 'line': ', '.join(csv_recorder)})
ret['data']['msg'].append({'reason': '未知的认证模式', 'line': ', '.join(csv_recorder)})
log.e('auth_mode unknown\n')
continue
uid = host.sys_user_add(user_args)
if uid < 0:
if uid == -100:
ret['msg'].append({'reason': '添加登录账号失败,账号已存在', 'line': ', '.join(csv_recorder)})
ret['data']['msg'].append({'reason': '添加登录账号失败,账号已存在', 'line': ', '.join(csv_recorder)})
else:
ret['msg'].append({'reason': '添加登录账号失败,操作数据库失败', 'line': ', '.join(csv_recorder)})
# log.e('sys_user_add() failed.\n')
ret['data']['msg'].append({'reason': '添加登录账号失败,操作数据库失败', 'line': ', '.join(csv_recorder)})
ret = json.dumps(ret).encode('utf8')
self.write(ret)
ret['code'] = 0
return self.write(json.dumps(ret).encode('utf8'))
except:
log.e('error\n')
ret['code'] = -1
ret = json.dumps(ret).encode('utf8')
self.write(ret)
ret['code'] = -6
ret['message'] = '发生异常.'
return self.write(json.dumps(ret).encode('utf8'))
finally:
if os.path.exists(csv_filename):
@ -210,15 +206,11 @@ class UploadAndImportHandler(TPBaseAdminAuthJsonHandler):
class GetListHandler(TPBaseUserAuthJsonHandler):
def post(self):
_user = self.get_session('user')
_user = self.get_current_user()
if _user is None:
return self.write(-1)
_type = _user['type']
_uname = _user['name']
return self.write_json(-1, '尚未登录')
filter = dict()
user = self.get_current_user()
order = dict()
order['name'] = 'host_id'
order['asc'] = True
@ -264,19 +256,17 @@ class GetListHandler(TPBaseUserAuthJsonHandler):
if _order is not None:
order['name'] = _order['k']
order['asc'] = _order['v']
if _type == 100:
if _user['type'] == 100:
_total, _hosts = host.get_all_host_info_list(filter, order, limit)
else:
filter['account_name'] = _uname
filter['account_name'] = _user['name']
_total, _hosts = host.get_host_info_list_by_user(filter, order, limit)
# print(_hosts)
ret = dict()
ret['page_index'] = limit['page_index']
ret['total'] = _total
ret['data'] = _hosts
self.write_json(0, data=ret)
# self.write(json_encode(data))
class GetGrouplist(TPBaseUserAuthJsonHandler):
@ -290,25 +280,18 @@ class UpdateHandler(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
if 'host_id' not in args or 'kv' not in args:
# ret = {'code':-2}
self.write_json(-2)
return
# _host_id = args['host_id']
self.write_json(-2, '缺少必要参数')
_ret = host.update(args['host_id'], args['kv'])
if _ret:
self.write_json(0)
else:
self.write_json(-1)
self.write_json(-3, '数据库操作失败')
class AddHost(TPBaseUserAuthJsonHandler):
@ -316,22 +299,18 @@ class AddHost(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
try:
ret = host.add_host(args)
if ret > 0:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(ret)
return
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
except:
self.write_json(-1)
return
log.e('add host failed.\n')
return self.write_json(-3, '发生异常')
class LockHost(TPBaseUserAuthJsonHandler):
@ -339,24 +318,20 @@ class LockHost(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
host_id = args['host_id']
lock = args['lock']
try:
ret = host.lock_host(host_id, lock)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
except:
self.write_json(-1)
return
log.e('lock host failed.\n')
return self.write_json(-3, '发生异常')
class DeleteHost(TPBaseUserAuthJsonHandler):
@ -364,22 +339,19 @@ class DeleteHost(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
host_list = args['host_list']
try:
ret = host.delete_host(host_list)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
except:
self.write_json(-1)
return
log.e('delete host failed.\n')
return self.write_json(-3, '发生异常')
class ExportHostHandler(TPBaseAdminAuthHandler):
@ -455,11 +427,9 @@ class GetCertList(TPBaseUserAuthJsonHandler):
def post(self):
_certs = host.get_cert_list()
if _certs is None or len(_certs) == 0:
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
else:
self.write_json(0, data=_certs)
return
return self.write_json(0, data=_certs)
class AddCert(TPBaseUserAuthJsonHandler):
@ -469,24 +439,22 @@ class AddCert(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
cert_pub = args['cert_pub']
cert_pri = args['cert_pri']
cert_name = args['cert_name']
if len(cert_pri) == 0:
self.write_json(-1)
return
return self.write_json(-2, '参数错误,数据不完整')
_yr = async_enc(cert_pri)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-3, '调用核心服务加密失败')
if 'code' not in return_data or return_data['code'] != 0:
return self.write_json(-1)
return self.write_json(-4, '核心服务加密返回错误')
cert_pri = return_data['data']
@ -495,9 +463,10 @@ class AddCert(TPBaseUserAuthJsonHandler):
if ret:
return self.write_json(0)
else:
return self.write_json(-1)
return self.write_json(-5, '数据库操作失败errcode:{}'.format(ret))
except:
return self.write_json(-1)
log.e('add cert failed.\n')
return self.write_json(-6, '发生异常')
class DeleteCert(TPBaseUserAuthJsonHandler):
@ -506,7 +475,7 @@ class DeleteCert(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
return self.write_json(-1)
return self.write_json(-1, '参数错误')
cert_id = args['cert_id']
@ -515,9 +484,10 @@ class DeleteCert(TPBaseUserAuthJsonHandler):
if ret:
return self.write_json(0)
else:
return self.write_json(-2)
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
except:
return self.write_json(-3)
log.e('add cert failed.\n')
return self.write_json(-3, '发生异常')
class UpdateCert(TPBaseUserAuthJsonHandler):
@ -526,11 +496,9 @@ class UpdateCert(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
cert_id = args['cert_id']
cert_pub = args['cert_pub']
cert_pri = args['cert_pri']
@ -540,23 +508,23 @@ class UpdateCert(TPBaseUserAuthJsonHandler):
_yr = async_enc(cert_pri)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-2, '调用核心服务加密失败')
if 'code' not in return_data or return_data['code'] != 0:
return self.write_json(-1)
return self.write_json(-3, '核心服务加密返回错误')
cert_pri = return_data['data']
try:
ret = host.update_cert(cert_id, cert_pub, cert_pri, cert_name)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return self.write_json(-4, '数据库操作失败errcode:{}'.format(ret))
return
except:
self.write_json(-1)
return
log.e('update cert failed.\n')
return self.write_json(-5, '发生异常')
class AddGroup(TPBaseUserAuthJsonHandler):
@ -564,22 +532,19 @@ class AddGroup(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
group_name = args['group_name']
try:
ret = host.add_group(group_name)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
except:
self.write_json(-1)
return
log.e('add group failed.\n')
return self.write_json(-3, '发生异常')
class UpdateGroup(TPBaseUserAuthJsonHandler):
@ -587,23 +552,20 @@ class UpdateGroup(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
group_id = args['group_id']
group_name = args['group_name']
try:
ret = host.update_group(group_id, group_name)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
except:
self.write_json(-1)
return
log.e('update group failed.\n')
return self.write_json(-3, '发生异常')
class DeleteGroup(TPBaseUserAuthJsonHandler):
@ -611,22 +573,19 @@ class DeleteGroup(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
group_id = args['group_id']
try:
ret = host.delete_group(group_id)
if ret == 0:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(ret)
return
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
except:
self.write_json(-1)
return
log.e('delete group failed.\n')
return self.write_json(-3, '发生异常')
class AddHostToGroup(TPBaseUserAuthJsonHandler):
@ -634,11 +593,9 @@ class AddHostToGroup(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
host_list = args['host_list']
group_id = args['group_id']
try:
@ -646,11 +603,11 @@ class AddHostToGroup(TPBaseUserAuthJsonHandler):
if ret:
self.write_json(0)
else:
self.write_json(-1)
return self.write_json(-2, '数据库操作失败errcode:{}'.format(ret))
return
except:
self.write_json(-1)
return
log.e('add host to group failed.\n')
return self.write_json(-3, '发生异常')
class GetSessionId(TPBaseUserAuthJsonHandler):
@ -659,33 +616,31 @@ class GetSessionId(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
if 'auth_id' not in args:
self.write_json(-1)
return
return self.write_json(-1, '参数缺失')
auth_id = args['auth_id']
req = {'method': 'request_session', 'param': {'authid': auth_id}}
_yr = async_post_http(req)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-2, '调用核心服务获取会话ID失败')
if 'code' not in return_data:
return self.write_json(-1)
return self.write_json(-3, '核心服务获取会话ID时返回错误数据')
_code = return_data['code']
if _code != 0:
return self.write_json(_code)
return self.write_json(-4, '核心服务获取会话ID时返回错误 {}'.format(_code))
try:
session_id = return_data['data']['sid']
except IndexError:
return self.write_json(-1)
return self.write_json(-5, '核心服务获取会话ID时返回错误数据')
data = dict()
data['session_id'] = session_id
@ -700,12 +655,10 @@ class AdminGetSessionId(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
if 'host_auth_id' not in args:
self.write_json(-1)
return
return self.write_json(-1, '参数缺失')
_host_auth_id = int(args['host_auth_id'])
@ -716,8 +669,7 @@ class AdminGetSessionId(TPBaseUserAuthJsonHandler):
tmp_auth_info = host.get_host_auth_info(_host_auth_id)
if tmp_auth_info is None:
self.write_json(-1)
return
return self.write_json(-2, '指定数据不存在')
tmp_auth_info['account_lock'] = 0
tmp_auth_info['account_name'] = user['name']
@ -734,19 +686,19 @@ class AdminGetSessionId(TPBaseUserAuthJsonHandler):
_yr = async_post_http(req)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-3, '调用核心服务获取会话ID失败')
if 'code' not in return_data:
return self.write_json(-1)
return self.write_json(-4, '核心服务获取会话ID时返回错误数据')
_code = return_data['code']
if _code != 0:
return self.write_json(_code)
return self.write_json(-5, '核心服务获取会话ID时返回错误 {}'.format(_code))
try:
session_id = return_data['data']['sid']
except IndexError:
return self.write_json(-1)
return self.write_json(-5, '核心服务获取会话ID时返回错误数据')
data = dict()
data['session_id'] = session_id
@ -761,8 +713,7 @@ class AdminFastGetSessionId(TPBaseAdminAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
user = self.get_current_user()
@ -784,8 +735,7 @@ class AdminFastGetSessionId(TPBaseAdminAuthJsonHandler):
tmp_auth_info['account_lock'] = 0
tmp_auth_info['account_name'] = user['name']
except IndexError:
self.write_json(-2)
return
return self.write_json(-2, '参数缺失')
if tmp_auth_info['auth_mode'] == 1:
if len(_user_pswd) == 0: # 修改登录用户信息时可能不会修改密码,因此页面上可能不会传来密码,需要从数据库中直接读取
@ -796,21 +746,21 @@ class AdminFastGetSessionId(TPBaseAdminAuthJsonHandler):
_yr = async_post_http(req)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-3, '调用核心服务加密失败')
if 'code' not in return_data or return_data['code'] != 0:
return self.write_json(-1)
return self.write_json(-3, '核心服务加密返回错误')
tmp_auth_info['user_auth'] = return_data['data']['c']
elif tmp_auth_info['auth_mode'] == 2:
tmp_auth_info['user_auth'] = host.get_cert_info(_cert_id)
if tmp_auth_info['user_auth'] is None:
self.write_json(-100)
self.write_json(-100, '指定私钥不存在')
return
elif tmp_auth_info['auth_mode'] == 0:
tmp_auth_info['user_auth'] = ''
else:
self.write_json(-101)
self.write_json(-101, '认证类型未知')
return
with tmp_auth_id_lock:
@ -824,19 +774,19 @@ class AdminFastGetSessionId(TPBaseAdminAuthJsonHandler):
_yr = async_post_http(req)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-3, '调用核心服务获取会话ID失败')
if 'code' not in return_data:
return self.write_json(-1)
return self.write_json(-4, '核心服务获取会话ID时返回错误数据')
_code = return_data['code']
if _code != 0:
return self.write_json(_code)
return self.write_json(-5, '核心服务获取会话ID时返回错误 {}'.format(_code))
try:
session_id = return_data['data']['sid']
except IndexError:
return self.write_json(-1)
return self.write_json(-5, '核心服务获取会话ID时返回错误数据')
data = dict()
data['session_id'] = session_id
@ -850,13 +800,12 @@ class SysUserList(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
try:
host_id = args['host_id']
except Exception as e:
self.write_json(-2)
return
except:
return self.write_json(-1, '参数缺失')
data = host.sys_user_list(host_id)
return self.write_json(0, data=data)
@ -869,26 +818,26 @@ class SysUserAdd(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
return self.write_json(-1)
return self.write_json(-1, '参数错误')
try:
auth_mode = args['auth_mode']
user_pswd = args['user_pswd']
cert_id = args['cert_id']
except IndexError:
return self.write_json(-2)
except:
return self.write_json(-1, '参数缺失')
if auth_mode == 1:
if 0 == len(args['user_pswd']):
return self.write_json(-1)
return self.write_json(-2, '参数缺失')
_yr = async_enc(user_pswd)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-3, '调用核心服务加密失败')
if 'code' not in return_data or return_data['code'] != 0:
return self.write_json(-1)
return self.write_json(-3, '核心服务加密返回错误')
args['user_pswd'] = return_data['data']
@ -909,19 +858,14 @@ class SysUserUpdate(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
if 'host_auth_id' not in args or 'kv' not in args:
# ret = {'code':-2}
self.write_json(-2)
return
return self.write_json(-2, '参数缺失')
kv = args['kv']
if 'auth_mode' not in kv or 'user_pswd' not in kv or 'cert_id' not in kv:
self.write_json(-3)
return
return self.write_json(-3, '参数缺失')
auth_mode = kv['auth_mode']
if 'user_pswd' in kv:
@ -937,17 +881,17 @@ class SysUserUpdate(TPBaseUserAuthJsonHandler):
_yr = async_enc(user_pswd)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-4, '调用核心服务加密失败')
if 'code' not in return_data or return_data['code'] != 0:
return self.write_json(-1)
return self.write_json(-5, '核心服务加密返回错误')
args['kv']['user_pswd'] = return_data['data']
if host.sys_user_update(args['host_auth_id'], args['kv']):
return self.write_json(0)
return self.write_json(-1)
return self.write_json(-6, '数据库操作失败')
class SysUserDelete(TPBaseUserAuthJsonHandler):
@ -956,15 +900,14 @@ class SysUserDelete(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-2)
return
return self.write_json(-1, '参数错误')
try:
host_auth_id = args['host_auth_id']
except IndexError:
self.write_json(-2)
return
return self.write_json(-2, '参数缺失')
if host.sys_user_delete(host_auth_id):
return self.write_json(0)
return self.write_json(-1)
return self.write_json(-3, '数据库操作失败')

View File

@ -155,19 +155,18 @@ class RpcHandler(TPBaseAdminAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-1)
return
return self.write_json(-1, '参数错误')
cmd = args['cmd']
if cmd == 'create_db':
if not get_db().need_create:
return self.write_json(-1)
return self.write_json(-1, '无需创建')
task_id = thread_mgr.create_db()
return self.write_json(0, data={"task_id": task_id})
if cmd == 'upgrade_db':
if not get_db().need_upgrade:
return self.write_json(-1)
return self.write_json(-1, '无需升级')
task_id = thread_mgr.upgrade_db()
return self.write_json(0, data={"task_id": task_id})

View File

@ -99,14 +99,18 @@ class RecordGetHeader(TPBaseAdminAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
else:
return self.write_json(-1, '参数错误')
record_id = args['id']
header = record.read_record_head(record_id)
if header is None:
return self.write_json(-1)
return self.write_json(-3, '操作失败')
ret = dict()
ret['header'] = header
self.write_json(0, data=ret)
return self.write_json(0, data=ret)
class RecordGetInfo(TPBaseAdminAuthJsonHandler):
@ -114,12 +118,17 @@ class RecordGetInfo(TPBaseAdminAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
else:
return self.write_json(-1, '参数错误')
record_id = args['id']
file_id = args['file_id']
data = record.read_record_info(record_id, file_id)
if data is None:
return self.write_json(-1)
self.write_json(0, data=data)
return self.write_json(-3, '操作失败')
return self.write_json(0, data=data)
class DeleteLog(TPBaseAdminAuthJsonHandler):
@ -128,10 +137,15 @@ class DeleteLog(TPBaseAdminAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
log_list = args['log_list']
else:
return self.write_json(-1, '参数错误')
log_list = args['log_list']
if not record.delete_log(log_list):
return self.write_json(-1)
self.write_json(0)
return self.write_json(-3, '操作失败')
return self.write_json(0)
class LogList(TPBaseAdminAuthJsonHandler):
@ -189,4 +203,4 @@ class LogList(TPBaseAdminAuthJsonHandler):
ret['total'] = total
ret['data'] = log_list
self.write_json(0, data=ret)
return self.write_json(0, data=ret)

View File

@ -17,8 +17,7 @@ class RpcHandler(TPBaseJsonHandler):
def get(self):
_uri = self.request.uri.split('?', 1)
if len(_uri) != 2:
self.write_json(-1, message='need request param.')
return
return self.write_json(-1, message='need request param.')
yield self._dispatch(urllib.parse.unquote(_uri[1]))
@ -26,8 +25,7 @@ class RpcHandler(TPBaseJsonHandler):
def post(self):
req = self.request.body.decode('utf-8')
if req == '':
self.write_json(-1, message='need request param.')
return
return self.write_json(-1, message='need request param.')
yield self._dispatch(req)
@ -37,11 +35,9 @@ class RpcHandler(TPBaseJsonHandler):
_req = json.loads(req)
if 'method' not in _req or 'param' not in _req:
self.write_json(-1, message='invalid request format.')
return
return self.write_json(-1, message='invalid request format.')
except:
self.write_json(-1, message='invalid json format.')
return
return self.write_json(-1, message='invalid json format.')
if 'get_auth_info' == _req['method']:
return self._get_auth_info(_req['param'])
@ -56,26 +52,25 @@ class RpcHandler(TPBaseJsonHandler):
else:
log.e('WEB-JSON-RPC got unknown method: `{}`.\n'.format(_req['method']))
self.write_json(-1, message='invalid method.')
return self.write_json(-1, message='invalid method.')
def _get_auth_info(self, param):
# 如果是页面上进行连接测试增加或修改主机和用户时信息并不写入数据库而是在内存中存在传递给core服务的
# 应该是负数形式的authid。本接口支持区分这两种认证ID。
if 'authid' not in param:
self.write_json(-1, message='invalid request.')
return
return self.write_json(-1, message='invalid request.')
authid = param['authid']
if authid > 0:
# 根据authid从数据库中查询对应的数据然后返回给调用者
x = host.get_auth_info(param['authid'])
self.write_json(0, data=x)
return self.write_json(0, data=x)
elif authid < 0:
x = web_session().taken('tmp-auth-info-{}'.format(authid), None)
self.write_json(0, data=x)
return self.write_json(0, data=x)
else:
self.write_json(-1, message='invalid auth id.')
return self.write_json(-1, message='invalid auth id.')
def _session_begin(self, param):
if 'sid' not in param:
@ -95,26 +90,25 @@ class RpcHandler(TPBaseJsonHandler):
record_id = record.session_begin(_sid, _acc_name, _host_ip, _sys_type, _host_port, _auth_mode, _user_name, _protocol)
if record_id <= 0:
self.write_json(-1, message='can not write database.')
return self.write_json(-1, message='can not write database.')
else:
self.write_json(0, data={'rid': record_id})
return self.write_json(0, data={'rid': record_id})
def _session_end(self, param):
if 'rid' not in param or 'code' not in param:
self.write_json(-1, message='invalid request.')
return
return self.write_json(-1, message='invalid request.')
if not record.session_end(param['rid'], param['code']):
self.write_json(-1)
return self.write_json(-1, 'can not write database.')
else:
self.write_json(0)
return self.write_json(0)
def _register_core(self, param):
# 因为core服务启动了之前可能非正常终止了做一下数据库中会话状态的修复操作
record.session_fix()
if 'rpc' not in param:
return self.write_json(-1)
return self.write_json(-1, 'invalid param.')
app_cfg().core_server_rpc = param['rpc']
@ -123,16 +117,16 @@ class RpcHandler(TPBaseJsonHandler):
_yr = async_post_http(req)
return_data = yield _yr
if return_data is None:
return self.write_json(-1)
return self.write_json(-1, 'get config from core service failed.')
if 'code' not in return_data:
return self.write_json(-2)
return self.write_json(-2, 'get config from core service return invalid data.')
if return_data['code'] != 0:
return self.write_json(return_data['code'])
return self.write_json(-3, 'get config from core service return code: {}'.format(return_data['code']))
app_cfg().update_core(return_data['data'])
self.write_json(0)
return self.write_json(0)
def _exit(self):
# set exit flag.
self.write_json(0)
return self.write_json(0)

View File

@ -1,9 +1,11 @@
# -*- coding: utf-8 -*-
import json
from eom_app.app.configs import app_cfg
from eom_app.module import host
from eom_app.module import user
from eom_common.eomcore.logger import *
from .base import TPBaseUserAuthJsonHandler, TPBaseAdminAuthHandler, TPBaseAdminAuthJsonHandler
cfg = app_cfg()
@ -38,22 +40,19 @@ class DeleteUser(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param')
user_id = args['user_id']
try:
ret = user.delete_user(user_id)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return
return self.write_json(-2, 'database op failed.')
except:
self.write_json(-1)
return
log.e('delete user failed.\n')
return self.write_json(-3, 'got exception.')
class ModifyUser(TPBaseUserAuthJsonHandler):
@ -61,11 +60,8 @@ class ModifyUser(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param.')
user_id = args['user_id']
user_desc = args['user_desc']
@ -75,11 +71,11 @@ class ModifyUser(TPBaseUserAuthJsonHandler):
if ret:
self.write_json(0)
else:
self.write_json(-1)
self.write_json(-2, 'database op failed.')
return
except:
self.write_json(-1)
return
log.e('modify user failed.\n')
self.write_json(-3, 'got exception.')
class AddUser(TPBaseUserAuthJsonHandler):
@ -87,11 +83,9 @@ class AddUser(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param.')
user_name = args['user_name']
user_pwd = '123456'
user_desc = args['user_desc']
@ -99,11 +93,13 @@ class AddUser(TPBaseUserAuthJsonHandler):
user_desc = ''
try:
ret = user.add_user(user_name, user_pwd, user_desc)
self.write_json(ret)
return
if 0 == ret:
return self.write_json(0)
else:
return self.write_json(-2, 'database op failed. errcode={}'.format(ret))
except:
self.write_json(-1)
return
log.e('add user failed.\n')
return self.write_json(-3, 'got exception.')
class LockUser(TPBaseUserAuthJsonHandler):
@ -111,24 +107,21 @@ class LockUser(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param.')
user_id = args['user_id']
lock_status = args['lock_status']
try:
ret = user.lock_user(user_id, lock_status)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return
return self.write_json(-2, 'database op failed.')
except:
self.write_json(-1)
return
log.e('lock user failed.\m')
return self.write_json(-3, 'got exception.')
class ResetUser(TPBaseUserAuthJsonHandler):
@ -136,30 +129,26 @@ class ResetUser(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param.')
user_id = args['user_id']
# lock_status = args['lock_status']
try:
ret = user.reset_user(user_id)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return
return self.write_json(-2, 'database op failed.')
except:
self.write_json(-1)
return
log.e('reset user failed.\n')
return self.write_json(-3, 'got exception.')
class HostList(TPBaseUserAuthJsonHandler):
def post(self):
filter = dict()
# user = self.get_current_user()
order = dict()
order['name'] = 'host_id'
order['asc'] = True
@ -170,7 +159,6 @@ class HostList(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
tmp = list()
_filter = args['filter']
@ -191,7 +179,6 @@ class HostList(TPBaseUserAuthJsonHandler):
del _filter[i]
filter.update(_filter)
# print('filter', filter)
_limit = args['limit']
if _limit['page_index'] < 0:
@ -207,7 +194,7 @@ class HostList(TPBaseUserAuthJsonHandler):
if _order is not None:
order['name'] = _order['k']
order['asc'] = _order['v']
# filter['account_name'] = user['name']
_total, _hosts = host.get_host_info_list_by_user(filter, order, limit)
ret = dict()
@ -222,21 +209,20 @@ class AllocHost(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param.')
user_name = args['user_name']
host_list = args['host_list']
try:
ret = user.alloc_host(user_name, host_list)
if ret:
self.write_json(0)
return self.write_json(0)
else:
self.write_json(-1)
return self.write_json(-2, 'database op failed.')
except:
self.write_json(-2)
log.e('alloc host failed.')
self.write_json(-3, 'got exception.')
class AllocHostUser(TPBaseUserAuthJsonHandler):
@ -244,11 +230,9 @@ class AllocHostUser(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param.')
user_name = args['user_name']
host_auth_id_list = args['host_list']
try:
@ -256,9 +240,10 @@ class AllocHostUser(TPBaseUserAuthJsonHandler):
if ret:
self.write_json(0)
else:
self.write_json(-1)
self.write_json(-2, 'database op failed.')
except:
self.write_json(-2)
log.e('alloc host for user failed.\n')
self.write_json(-3, 'got exception.')
class DeleteHost(TPBaseUserAuthJsonHandler):
@ -266,21 +251,21 @@ class DeleteHost(TPBaseUserAuthJsonHandler):
args = self.get_argument('args', None)
if args is not None:
args = json.loads(args)
# print('args', args)
else:
# ret = {'code':-1}
self.write_json(-1)
return
return self.write_json(-1, 'invalid param.')
user_name = args['user_name']
host_list = args['host_list']
try:
ret = user.delete_host(user_name, host_list)
if ret:
self.write_json(0)
else:
self.write_json(-1)
self.write_json(-2, 'database op failed.')
except:
self.write_json(-2)
log.e('delete host failed.\n')
self.write_json(-3, 'got exception.')
class DeleteHostUser(TPBaseUserAuthJsonHandler):
@ -289,15 +274,17 @@ class DeleteHostUser(TPBaseUserAuthJsonHandler):
if args is not None:
args = json.loads(args)
else:
self.write_json(-1)
return
self.write_json(-1, 'invalid param.')
user_name = args['user_name']
auth_id_list = args['auth_id_list']
try:
ret = user.delete_host_user(user_name, auth_id_list)
if ret:
self.write_json(0)
else:
self.write_json(-1)
self.write_json(-2, 'database op failed.')
except:
self.write_json(-2)
log.e('delete host for user failed.\n')
self.write_json(-3, 'got exception.')

View File

@ -43,8 +43,6 @@ def get_all_host_info_list(_filter, order, limit, with_pwd=False):
field_a = ['host_id', 'host_lock', 'host_ip', 'host_port', 'protocol', 'host_desc', 'group_id', 'host_sys_type']
field_b = ['group_name']
# field_c = ['id', 'auth_mode', 'user_name']
sql = 'SELECT COUNT(*) ' \
'FROM `{}host_info` AS a ' \
'LEFT JOIN `{}group` AS b ON `a`.`group_id`=`b`.`group_id` ' \

View File

@ -256,17 +256,15 @@ class EomLogger:
self._console_set_color(CR_ERROR)
self._do_log(LOG_ERROR, *args, **kwargs)
if self._trace_error == self.TRACE_ERROR_NONE:
return
s = traceback.extract_stack()
c = len(s)
for i in range(c - 1):
if i >= self._trace_error:
break
if s[c - 2 - i][0].startswith('<frozen '):
continue
self._do_log(LOG_ERROR, ' %s(%d)\n' % (s[c - 2 - i][0], s[c - 2 - i][1]))
if self._trace_error != self.TRACE_ERROR_NONE:
s = traceback.extract_stack()
c = len(s)
for i in range(c - 1):
if i >= self._trace_error:
break
if s[c - 2 - i][0].startswith('<frozen '):
continue
self._do_log(LOG_ERROR, ' %s(%d)\n' % (s[c - 2 - i][0], s[c - 2 - i][1]))
_type, _value, _tb = sys.exc_info()
if _type is not None:

View File

@ -28,19 +28,17 @@ ywl.do_upload_file = function () {
data: param,
success: function (data) {
$('#upload-file').remove();
var obj = JSON.parse(data);
if (obj.code === TPE_OK) {
var ret = JSON.parse(data);
if (ret.code === TPE_OK) {
g_host_table.reload();
ywl.notify_success('批量导入主机成功!');
console.log('msg', obj);
if (obj.msg.length > 0) {
console.log(obj.msg);
if (ret.data.msg.length > 0) {
var html = [];
html.push('<ul>');
for (var i = 0, cnt = obj.msg.length; i < cnt; ++i) {
for (var i = 0, cnt = ret.data.msg.length; i < cnt; ++i) {
html.push('<li>');
html.push('<span style="font-weight:bold;color:#993333;">' + obj.msg[i].reason + '</span><br/>');
html.push(obj.msg[i].line);
html.push('<span style="font-weight:bold;color:#993333;">' + ret.data.msg[i].reason + '</span><br/>');
html.push(ret.data.msg[i].line);
html.push('</li>');
}
html.push('</ul>');
@ -49,10 +47,10 @@ ywl.do_upload_file = function () {
$('#dialog_batch_add_host').modal({backdrop: 'static'});
}
} else {
ywl.notify_error('批量导入主机失败! 错误号:' + obj.code);
ywl.notify_error('批量导入主机失败! 错误号:' + ret.code);
}
},
error: function (data, status, e) { // 相当于java中catch语句块的用法
error: function () {
$('#upload-file').remove();
ywl.notify_error('网络故障,批量导入主机失败!');
}