Exemplo n.º 1
0
 def __init__(self):
     sys_config = SysConfig().sys_config
     self.MAIL_REVIEW_SMTP_SERVER = sys_config.get('mail_smtp_server')
     if sys_config.get('mail_smtp_port'):
         self.MAIL_REVIEW_SMTP_PORT = int(sys_config.get('mail_smtp_port'))
     else:
         self.MAIL_REVIEW_SMTP_PORT = 25
     self.MAIL_REVIEW_FROM_ADDR = sys_config.get('mail_smtp_user')
     self.MAIL_REVIEW_FROM_PASSWORD = sys_config.get('mail_smtp_password')
Exemplo n.º 2
0
def loginAuthenticate(username, password):
    """登录认证,包含一个登录失败计数器,5分钟内连续失败5次的账号,会被锁定5分钟"""
    sys_config = SysConfig().sys_config
    if sys_config.get('lock_cnt_threshold'):
        lockCntThreshold = int(sys_config.get('lock_cnt_threshold'))
    else:
        lockCntThreshold = 5
    if sys_config.get('lock_time_threshold'):
        lockTimeThreshold = int(sys_config.get('lock_time_threshold'))
    else:
        lockTimeThreshold = 300

    # 服务端二次验证参数
    if username == "" or password == "" or username is None or password is None:
        result = {'status': 2, 'msg': '登录用户名或密码为空,请重新输入!', 'data': ''}
    elif username in login_failure_counter and login_failure_counter[username][
            "cnt"] >= lockCntThreshold and (
                datetime.datetime.now() - login_failure_counter[username]
                ["last_failure_time"]).seconds <= lockTimeThreshold:
        log_mail_record(
            'user:{},login failed, account locking...'.format(username))
        result = {'status': 3, 'msg': '登录失败超过5次,该账号已被锁定5分钟!', 'data': ''}
    else:
        # 登录
        user = authenticate(username=username, password=password)
        print(type(user))
        # 登录成功
        if user:
            # 如果登录失败计数器中存在该用户名,则清除之
            if username in login_failure_counter:
                login_failure_counter.pop(username)
            result = {'status': 0, 'msg': 'ok', 'data': user}
        # 登录失败
        else:
            if username not in login_failure_counter:
                # 第一次登录失败,登录失败计数器中不存在该用户,则创建一个该用户的计数器
                login_failure_counter[username] = {
                    "cnt": 1,
                    "last_failure_time": datetime.datetime.now()
                }
            else:
                if (datetime.datetime.now() -
                        login_failure_counter[username]["last_failure_time"]
                    ).seconds <= lockTimeThreshold:
                    login_failure_counter[username]["cnt"] += 1
                else:
                    # 上一次登录失败时间早于5分钟前,则重新计数。以达到超过5分钟自动解锁的目的。
                    login_failure_counter[username]["cnt"] = 1
                login_failure_counter[username][
                    "last_failure_time"] = datetime.datetime.now()
            log_mail_record('user:{},login failed, fail count:{}'.format(
                username, login_failure_counter[username]["cnt"]))
            result = {'status': 1, 'msg': '用户名或密码错误,请重新输入!', 'data': ''}
    return result
Exemplo n.º 3
0
    def __init__(self):
        try:
            sys_config = SysConfig().sys_config
            self.MAIL_REVIEW_SMTP_SERVER = sys_config.get('mail_smtp_server')
            if sys_config.get('mail_smtp_port'):
                self.MAIL_REVIEW_SMTP_PORT = int(
                    sys_config.get('mail_smtp_port'))
            else:
                self.MAIL_REVIEW_SMTP_PORT = 25
            self.MAIL_REVIEW_FROM_ADDR = sys_config.get('mail_smtp_user')
            self.MAIL_REVIEW_FROM_PASSWORD = sys_config.get(
                'mail_smtp_password')

        except AttributeError as a:
            print("Error: %s" % a)
        except ValueError as v:
            print("Error: %s" % v)
Exemplo n.º 4
0
def send_msg(workflowDetail, url):
    mailSender = MailSender()
    sys_config = SysConfig().sys_config
    # 获取当前审批和审批流程
    audit_auth_group, current_audit_auth_group = Workflow.review_info(workflowDetail.id, 2)
    # 如果执行完毕了,则根据配置决定是否给提交者和DBA一封邮件提醒,DBA需要知晓审核并执行过的单子
    msg_title = "[{}]工单{}#{}".format(WorkflowDict.workflow_type['sqlreview_display'], workflowDetail.status,
                                     workflowDetail.id)
    msg_content = '''发起人:{}\n审批流程:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
        workflowDetail.engineer_display, audit_auth_group, workflowDetail.workflow_name, url,
        workflowDetail.sql_content[0:500])

    if sys_config.get('mail') == 'true':
        # 邮件通知申请人,审核人,抄送DBA
        notify_users = workflowDetail.review_man.split(',')
        notify_users.append(workflowDetail.engineer)
        listToAddr = [email['email'] for email in Users.objects.filter(username__in=notify_users).values('email')]
        listCcAddr = [email['email'] for email in
                      auth_group_users(auth_group_names=['DBA'], group_id=workflowDetail.group_id).values('email')]
        mailSender.send_email(msg_title, msg_content, listToAddr, listCcAddr=listCcAddr)
    if sys_config.get('ding') == 'true':
        # 钉钉通知申请人,审核人,抄送DBA
        webhook_url = SqlGroup.objects.get(group_id=workflowDetail.group_id).ding_webhook
    MailSender.send_ding(webhook_url, msg_title + '\n' + msg_content)
Exemplo n.º 5
0
def _send(audit_id, msg_type, **kwargs):
    msg_sender = MailSender()
    sys_config = SysConfig().sys_config
    audit_info = WorkflowAudit.objects.get(audit_id=audit_id)
    workflow_id = audit_info.workflow_id
    workflow_type = audit_info.workflow_type
    status = audit_info.current_status
    workflow_title = audit_info.workflow_title
    workflow_from = audit_info.create_user_display
    workflow_url = kwargs.get('workflow_url')
    webhook_url = SqlGroup.objects.get(group_id=audit_info.group_id).ding_webhook

    audit_info = WorkflowAudit.objects.get(workflow_id=workflow_id, workflow_type=workflow_type)
    if audit_info.audit_auth_groups == '':
        workflow_auditors = '无需审批'
    else:
        try:
            workflow_auditors = '->'.join([Group.objects.get(id=auth_group_id).name for auth_group_id in
                                           audit_info.audit_auth_groups.split(',')])
        except Exception:
            workflow_auditors = audit_info.audit_auth_groups
    if audit_info.current_audit == '-1':
        current_workflow_auditors = None
    else:
        try:
            current_workflow_auditors = Group.objects.get(id=audit_info.current_audit).name
        except Exception:
            current_workflow_auditors = audit_info.current_audit

    # 准备消息内容
    if workflow_type == WorkflowDict.workflow_type['query']:
        workflow_type_display = WorkflowDict.workflow_type['query_display']
        workflow_detail = QueryPrivilegesApply.objects.get(apply_id=workflow_id)
        workflow_audit_remark = ''
        if workflow_detail.priv_type == 1:
            workflow_content = '''数据库清单:{}\n授权截止时间:{}\n结果集:{}\n'''.format(
                workflow_detail.db_list,
                datetime.datetime.strftime(workflow_detail.valid_date, '%Y-%m-%d %H:%M:%S'),
                workflow_detail.limit_num)
        elif workflow_detail.priv_type == 2:
            workflow_content = '''数据库:{}\n表清单:{}\n授权截止时间:{}\n结果集:{}\n'''.format(
                workflow_detail.db_list,
                workflow_detail.table_list,
                datetime.datetime.strftime(workflow_detail.valid_date, '%Y-%m-%d %H:%M:%S'),
                workflow_detail.limit_num)
    elif workflow_type == WorkflowDict.workflow_type['sqlreview']:
        workflow_type_display = WorkflowDict.workflow_type['sqlreview_display']
        workflow_detail = SqlWorkflow.objects.get(pk=workflow_id)
        workflow_audit_remark = workflow_detail.audit_remark
        workflow_content = workflow_detail.sql_content
    else:
        raise Exception('工单类型不正确')

    # 准备消息格式
    if status == WorkflowDict.workflow_status['audit_wait']:  # 申请阶段
        msg_title = "[{}]新的工单申请#{}".format(workflow_type_display, audit_id)
        # 接收人,发送给该项目组内对应权限组所有的用户
        auth_group_names = Group.objects.get(id=audit_info.current_audit).name
        msg_email_reciver = [user.email for user in
                             auth_group_users([auth_group_names], audit_info.group_id)]
        # 抄送对象
        email_cc = kwargs.get('email_cc', [])
        msg_email_cc = email_cc
        msg_content = '''发起人:{}\n审批流程:{}\n当前审批:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
            workflow_from,
            workflow_auditors,
            current_workflow_auditors,
            workflow_title,
            workflow_url,
            workflow_content)
    elif status == WorkflowDict.workflow_status['audit_success']:  # 审核通过
        msg_title = "[{}]工单审核通过#{}".format(workflow_type_display, audit_id)
        # 接收人
        msg_email_reciver = [Users.objects.get(username=audit_info.create_user).email]
        # 抄送对象
        msg_email_cc = kwargs.get('email_cc', [])
        msg_content = '''发起人:{}\n审批流程:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
            workflow_from,
            workflow_auditors,
            workflow_title,
            workflow_url,
            workflow_content)
    elif status == WorkflowDict.workflow_status['audit_reject']:  # 审核驳回
        msg_title = "[{}]工单被驳回#{}".format(workflow_type_display, audit_id)
        # 接收人
        msg_email_reciver = [Users.objects.get(username=audit_info.create_user).email]
        msg_email_cc = []
        msg_content = '''工单名称:{}\n工单地址:{}\n驳回原因:{}\n提醒:此工单被审核不通过,请按照驳回原因进行修改!'''.format(
            workflow_title,
            workflow_url,
            workflow_audit_remark)
    elif status == WorkflowDict.workflow_status['audit_abort']:  # 审核取消,通知所有审核人
        msg_title = "[{}]提交人主动终止工单#{}".format(workflow_type_display, audit_id)
        # 接收人,发送给该项目组内对应权限组所有的用户
        auth_group_names = [Group.objects.get(id=auth_group_id).name for auth_group_id in
                            audit_info.audit_auth_groups.split(',')]
        msg_email_reciver = [user.email for user in auth_group_users(auth_group_names, audit_info.group_id)]
        msg_email_cc = []
        msg_content = '''发起人:{}\n工单名称:{}\n工单地址:{}\n提醒:提交人主动终止流程'''.format(
            workflow_from,
            workflow_title,
            workflow_url)
    else:
        raise Exception('工单状态不正确')

    if isinstance(msg_email_reciver, str):
        msg_email_reciver = [msg_email_reciver]
    if isinstance(msg_email_cc, str):
        msg_email_cc = [msg_email_cc]

    # 判断是发送钉钉还是发送邮件
    try:
        if msg_type == 0:
            if sys_config.get('mail') == 'true':
                msg_sender.send_email(msg_title, msg_content, msg_email_reciver, listCcAddr=msg_email_cc)
            if sys_config.get('ding') == 'true':
                msg_sender.send_ding(webhook_url, msg_title + '\n' + msg_content)
        if msg_type == 1:
            if sys_config.get('mail') == 'true':
                msg_sender.send_email(msg_title, msg_content, msg_email_reciver, listCcAddr=msg_email_cc)
        elif msg_type == 2:
            if sys_config.get('ding') == 'true':
                msg_sender.send_ding(webhook_url, msg_title + '\n' + msg_content)
    except Exception:
        logger.error(traceback.format_exc())
Exemplo n.º 6
0
class InceptionDao(object):
    def __init__(self):
        self.sys_config = SysConfig().sys_config
        self.inception_host = self.sys_config.get('inception_host')
        if self.sys_config.get('inception_port'):
            self.inception_port = int(self.sys_config.get('inception_port'))
        else:
            self.inception_port = 6669

        self.inception_remote_backup_host = self.sys_config.get(
            'inception_remote_backup_host')
        if self.sys_config.get('inception_remote_backup_port'):
            self.inception_remote_backup_port = int(
                self.sys_config.get('inception_remote_backup_port'))
        else:
            self.inception_remote_backup_port = 3306
        self.inception_remote_backup_user = self.sys_config.get(
            'inception_remote_backup_user')
        self.inception_remote_backup_password = self.sys_config.get(
            'inception_remote_backup_password')
        self.prpCryptor = Prpcrypt()

    def criticalDDL(self, sqlContent):
        '''
        识别DROP DATABASE, DROP TABLE, TRUNCATE PARTITION, TRUNCATE TABLE等高危DDL操作,因为对于这些操作,inception在备份时只能备份METADATA,而不会备份数据!
        如果识别到包含高危操作,则返回“审核不通过”
        '''
        resultList = []
        criticalSqlFound = 0
        critical_ddl_regex = self.sys_config.get('critical_ddl_regex')
        p = re.compile(critical_ddl_regex)
        # 删除注释语句
        sqlContent = ''.join(
            map(
                lambda x: re.compile(r'(^--\s+.*|^/\*.*\*/;\s*$)').sub(
                    '', x, count=1), sqlContent.splitlines(1))).strip()

        for row in sqlContent.rstrip(';').split(';'):
            if p.match(row.strip().lower()):
                result = ('', '', 2, '驳回高危SQL',
                          '禁止提交匹配' + critical_ddl_regex + '条件的语句!', row, '',
                          '', '', '')
                criticalSqlFound = 1
            else:
                result = ('', '', 0, '', 'None', row, '', '', '', '')
            resultList.append(result)
        if criticalSqlFound == 1:
            return resultList
        else:
            return None

    def preCheck(self, sqlContent):
        '''
        在提交给inception之前,预先识别一些Inception不能正确审核的SQL,比如"alter table t1;"或"alter table test.t1;" 以免导致inception core dump
        '''
        resultList = []
        syntaxErrorSqlFound = 0
        for row in sqlContent.rstrip(';').split(';'):
            if re.match(
                    r"(\s*)alter(\s+)table(\s+)(\S+)(\s*);|(\s*)alter(\s+)table(\s+)(\S+)\.(\S+)(\s*);",
                    row.lower() + ";"):
                result = ('', '', 2, 'SQL语法错误', 'ALTER TABLE 必须带有选项', row, '',
                          '', '', '')
                syntaxErrorSqlFound = 1
            else:
                result = ('', '', 0, '', 'None', row, '', '', '', '')
            resultList.append(result)
        if syntaxErrorSqlFound == 1:
            return resultList
        else:
            return None

    def sqlautoReview(self, sqlContent, instance_name, db_name, isSplit="no"):
        '''
        将sql交给inception进行自动审核,并返回审核结果。
        '''
        listMasters = Instance.objects.filter(instance_name=instance_name)
        masterHost = listMasters[0].host
        masterPort = listMasters[0].port
        masterUser = listMasters[0].user
        masterPassword = self.prpCryptor.decrypt(listMasters[0].password)

        # 高危SQL检查
        if self.sys_config.get('critical_ddl_regex', '') != '':
            criticalDDL_check = self.criticalDDL(sqlContent)
        else:
            criticalDDL_check = None

        if criticalDDL_check is not None:
            result = criticalDDL_check
        else:
            preCheckResult = self.preCheck(sqlContent)
            if preCheckResult is not None:
                result = preCheckResult
            else:
                if isSplit == "yes":
                    # 这种场景只给osc进度功能使用
                    # 如果一个工单中同时包含DML和DDL,那么执行时被split后的SQL与提交的SQL会不一样(会在每条语句前面加use database;),导致osc进度更新取不到正确的SHA1值。
                    # 请参考inception文档中--enable-split参数的说明

                    sqlSplit = "/*--user=%s; --password=%s; --host=%s; --enable-execute;--port=%s; --enable-ignore-warnings;--enable-split;*/\
                         inception_magic_start;\
                         use %s;\
                         %s\
                         inception_magic_commit;" % (
                        masterUser, masterPassword, masterHost,
                        str(masterPort), db_name, sqlContent)
                    splitResult = self._fetchall(sqlSplit, self.inception_host,
                                                 self.inception_port, '', '',
                                                 '')
                    tmpList = []
                    for splitRow in splitResult:
                        sqlTmp = splitRow[1]
                        sql = "/*--user=%s;--password=%s;--host=%s;--enable-check;--port=%s; --enable-ignore-warnings;*/\
                                inception_magic_start;\
                                %s\
                                inception_magic_commit;" % (
                            masterUser, masterPassword, masterHost,
                            str(masterPort), sqlTmp)
                        reviewResult = self._fetchall(sql, self.inception_host,
                                                      self.inception_port, '',
                                                      '', '')
                        tmpList.append(reviewResult)

                    # 二次加工一下
                    finalList = []
                    for splitRow in tmpList:
                        for sqlRow in splitRow:
                            finalList.append(list(sqlRow))
                    result = finalList
                else:
                    # 工单审核使用
                    sql = "/*--user=%s;--password=%s;--host=%s;--enable-check=1;--port=%s;*/\
                      inception_magic_start;\
                      use %s;\
                      %s\
                      inception_magic_commit;" % (masterUser, masterPassword,
                                                  masterHost, str(masterPort),
                                                  db_name, sqlContent)
                    result = self._fetchall(sql, self.inception_host,
                                            self.inception_port, '', '', '')
        return result

    def executeFinal(self, workflowDetail, dictConn):
        '''
        将sql交给inception进行最终执行,并返回执行结果。
        '''
        strBackup = ""
        if workflowDetail.is_backup == '是':
            strBackup = "--enable-remote-backup;"
        else:
            strBackup = "--disable-remote-backup;"

        # 根据inception的要求,执行之前最好先split一下
        sqlSplit = "/*--user=%s; --password=%s; --host=%s; --enable-execute;--port=%s; --enable-ignore-warnings;--enable-split;*/\
             inception_magic_start;\
             use %s;\
             %s\
             inception_magic_commit;" % (
            dictConn['masterUser'], dictConn['masterPassword'],
            dictConn['masterHost'], str(dictConn['masterPort']),
            workflowDetail.db_name, workflowDetail.sql_content)
        splitResult = self._fetchall(sqlSplit, self.inception_host,
                                     self.inception_port, '', '', '')

        tmpList = []
        # 对于split好的结果,再次交给inception执行.这里无需保持在长连接里执行,短连接即可.
        for splitRow in splitResult:
            sqlTmp = splitRow[1]
            sqlExecute = "/*--user=%s;--password=%s;--host=%s;--enable-execute;--port=%s; --enable-ignore-warnings;%s*/\
                    inception_magic_start;\
                    %s\
                    inception_magic_commit;" % (
                dictConn['masterUser'], dictConn['masterPassword'],
                dictConn['masterHost'], str(
                    dictConn['masterPort']), strBackup, sqlTmp)

            executeResult = self._fetchall(sqlExecute, self.inception_host,
                                           self.inception_port, '', '', '')
            for sqlRow in executeResult:
                tmpList.append(sqlRow)
            # 每执行一次,就将执行结果更新到工单的execute_result,便于获取osc进度时对比
            workflowDetail.execute_result = json.dumps(tmpList)
            try:
                workflowDetail.save()
            except Exception:
                # 关闭后重新获取连接,防止超时
                connection.close()
                workflowDetail.save()

        # 二次加工一下,目的是为了和sqlautoReview()函数的return保持格式一致,便于在detail页面渲染.
        finalStatus = "已正常结束"
        finalList = []
        for sqlRow in tmpList:
            # 如果发现任何一个行执行结果里有errLevel为1或2,并且stagestatus列没有包含Execute Successfully字样,则判断最终执行结果为有异常.
            if (sqlRow[2] == 1 or sqlRow[2] == 2) and re.match(
                    r"\w*Execute Successfully\w*", sqlRow[3]) is None:
                finalStatus = "执行有异常"
            finalList.append(list(sqlRow))

        return (finalStatus, finalList)

    def getRollbackSqlList(self, workflowId):
        workflowDetail = SqlWorkflow.objects.get(id=workflowId)
        listExecuteResult = json.loads(workflowDetail.execute_result)
        # 回滚数据倒序展示
        listExecuteResult.reverse()
        listBackupSql = []
        for row in listExecuteResult:
            try:
                # 获取backup_dbname
                if row[8] == 'None':
                    continue
                backupDbName = row[8]
                sequence = row[7]
                sql = row[5]
                opidTime = sequence.replace("'", "")
                sqlTable = "select tablename from %s.$_$Inception_backup_information$_$ where opid_time='%s';" % (
                    backupDbName, opidTime)
                listTables = self._fetchall(
                    sqlTable, self.inception_remote_backup_host,
                    self.inception_remote_backup_port,
                    self.inception_remote_backup_user,
                    self.inception_remote_backup_password, '')
                if listTables:
                    tableName = listTables[0][0]
                    sqlBack = "select rollback_statement from %s.%s where opid_time='%s'" % (
                        backupDbName, tableName, opidTime)
                    listBackup = self._fetchall(
                        sqlBack, self.inception_remote_backup_host,
                        self.inception_remote_backup_port,
                        self.inception_remote_backup_user,
                        self.inception_remote_backup_password, '')
                    block_rollback_sql_list = [sql]
                    block_rollback_sql = '\n'.join(
                        [back_info[0] for back_info in listBackup])
                    block_rollback_sql_list.append(block_rollback_sql)
                    listBackupSql.append(block_rollback_sql_list)
            except Exception as e:
                raise Exception(e)
        return listBackupSql

    def _fetchall(self, sql, paramHost, paramPort, paramUser, paramPasswd,
                  paramDb):
        '''
        封装mysql连接和获取结果集方法
        '''
        result = None
        conn = None
        cur = None

        try:
            conn = MySQLdb.connect(host=paramHost,
                                   user=paramUser,
                                   passwd=paramPasswd,
                                   db=paramDb,
                                   port=paramPort,
                                   charset='utf8')
            cur = conn.cursor()
            ret = cur.execute(sql)
            result = cur.fetchall()
        except Exception as e:
            raise Exception(e)
        finally:
            if cur is not None:
                cur.close()
            if conn is not None:
                conn.close()
        return result

    def getOscPercent(self, sqlSHA1):
        """已知SHA1值,去inception里查看OSC进度"""
        sqlStr = "inception get osc_percent '%s'" % sqlSHA1
        result = self._fetchall(sqlStr, self.inception_host,
                                self.inception_port, '', '', '')
        if len(result) > 0:
            percent = result[0][3]
            timeRemained = result[0][4]
            pctResult = {
                "status": 0,
                "msg": "ok",
                "data": {
                    "percent": percent,
                    "timeRemained": timeRemained
                }
            }
        else:
            pctResult = {
                "status": 1,
                "msg": "没找到该SQL的进度信息,是否已经执行完毕?",
                "data": {
                    "percent": -100,
                    "timeRemained": -100
                }
            }
        return pctResult

    def stopOscProgress(self, sqlSHA1):
        """已知SHA1值,调用inception命令停止OSC进程,涉及的Inception命令和注意事项,请参考http://mysql-inception.github.io/inception-document/osc/"""
        sqlStr = "inception stop alter '%s'" % sqlSHA1
        result = self._fetchall(sqlStr, self.inception_host,
                                self.inception_port, '', '', '')
        if result is not None:
            optResult = {
                "status": 0,
                "msg": "已成功停止OSC进程,请注意清理触发器和临时表,先清理触发器再删除临时表",
                "data": ""
            }
        else:
            optResult = {
                "status": 1,
                "msg": "ERROR 2624 (HY000):未找到OSC执行进程,可能已经执行完成",
                "data": ""
            }
        return optResult

    def query_print(self, sqlContent, instance_name, dbName):
        '''
        将sql交给inception打印语法树。
        '''
        instance_info = Instance.objects.get(instance_name=instance_name)
        Host = instance_info.host
        Port = instance_info.port
        User = instance_info.user
        Password = self.prpCryptor.decrypt(instance_info.password)

        # 工单审核使用
        sql = "/*--user=%s;--password=%s;--host=%s;--port=%s;--enable-query-print;*/\
                          inception_magic_start;\
                          use %s;\
                          %s\
                          inception_magic_commit;" % (
            User, Password, Host, str(Port), dbName, sqlContent)
        result = self._fetchall(sql, self.inception_host, self.inception_port,
                                '', '', '')
        return result

    # inception执行情况统计
    def statistic(self):
        sql = '''
             select
                 sum(deleting)     deleting,
                 sum(inserting)    inserting,
                 sum(updating)     updating,
                 sum(selecting)    selecting,
                 sum(altertable)   altertable,
                 sum(renaming)     renaming,
                 sum(createindex)  createindex,
                 sum(dropindex)    dropindex,
                 sum(addcolumn)    addcolumn,
                 sum(dropcolumn)   dropcolumn,
                 sum(changecolumn) changecolumn,
                 sum(alteroption)  alteroption,
                 sum(alterconvert) alterconvert,
                 sum(createtable)  createtable,
                 sum(droptable)    droptable,
                 sum(createdb)     createdb,
                 sum(truncating)   truncating
               from statistic;'''
        try:
            return Dao(
                host=self.inception_remote_backup_host,
                user=self.inception_remote_backup_user,
                port=self.inception_remote_backup_port,
                password=self.inception_remote_backup_password).mysql_query(
                    'inception', sql)
        except Exception:
            return {'column_list': [], 'rows': [], 'effect_row': 0}
Exemplo n.º 7
0
def menu():
    sys_config = SysConfig().sys_config
    if sys_config.get(
            'sqladvisor') == '' or sys_config.get('sqladvisor') is None:
        sqladvisor_display = 'false'
    else:
        sqladvisor_display = 'true'
    leftMenuBtnsCommon = (
        {
            'key': 'sqlworkflow',
            'name': 'SQL上线工单',
            'url': '/sqlworkflow/',
            'class': 'glyphicon glyphicon-home',
            'display': 'true'
        },
        {
            'key': 'sqlquery',
            'name': 'SQL在线查询',
            'url': '/sqlquery/',
            'class': 'glyphicon glyphicon-search',
            'display': sys_config.get('query')
        },
        {
            'key': 'slowquery',
            'name': 'SQL慢查日志',
            'url': '/slowquery/',
            'class': 'glyphicon glyphicon-align-right',
            'display': sys_config.get('slowquery')
        },
        {
            'key': 'sqladvisor',
            'name': 'SQL优化工具',
            'url': '/sqladvisor/',
            'class': 'glyphicon glyphicon-wrench',
            'display': sqladvisor_display
        },
        {
            'key': 'queryapply',
            'name': '查询权限管理',
            'url': '/queryapplylist/',
            'class': 'glyphicon glyphicon-eye-open',
            'display': sys_config.get('query')
        },
        {
            'key': 'diagnosis',
            'name': '主库会话管理',
            'url': '/diagnosis_process/',
            'class': 'glyphicon  glyphicon-scissors',
            'display': sys_config.get('db_process_manage')
        },
    )

    leftMenuBtnsSuper = (
        {
            'key': 'config',
            'name': '系统配置管理',
            'url': '/config/',
            'class': 'glyphicon glyphicon glyphicon-option-horizontal',
            'display': 'true'
        },
        {
            'key': 'admin',
            'name': '后台数据管理',
            'url': '/admin/',
            'class': 'glyphicon glyphicon-list',
            'display': 'true'
        },
    )

    leftMenuBtnsDoc = (
        {
            'key': 'dbaprinciples',
            'name': 'SQL审核必读',
            'url': '/dbaprinciples/',
            'class': 'glyphicon glyphicon-book',
            'display': 'true'
        },
        {
            'key': 'charts',
            'name': '统计图表展示',
            'url': '/charts/',
            'class': 'glyphicon glyphicon-file',
            'display': 'true'
        },
    )
    return leftMenuBtnsCommon, leftMenuBtnsSuper, leftMenuBtnsDoc