示例#1
0
def __send(msg_title, msg_content, msg_to, msg_cc=None, **kwargs):
    """
    按照通知配置发送通知消息
    :param msg_title: 通知标题
    :param msg_content: 通知内容
    :param msg_to:  通知人user list
    :return:
    """
    sys_config = SysConfig()
    msg_sender = MsgSender()
    msg_cc = msg_cc if msg_cc else []
    webhook_url = kwargs.get('webhook_url')
    msg_to_email = [user.email for user in msg_to if user.email]
    msg_cc_email = [user.email for user in msg_cc if user.email]
    msg_to_ding_user = [
        user.ding_user_id for user in chain(msg_to, msg_cc)
        if user.ding_user_id
    ]
    msg_to_wx_user = [
        user.wx_user_id if user.wx_user_id else user.username
        for user in chain(msg_to, msg_cc)
    ]
    if sys_config.get('mail'):
        msg_sender.send_email(msg_title,
                              msg_content,
                              msg_to_email,
                              list_cc_addr=msg_cc_email)
    if sys_config.get('ding') and webhook_url:
        msg_sender.send_ding(webhook_url, msg_title + '\n' + msg_content)
    if sys_config.get('ding_to_person'):
        msg_sender.send_ding2user(msg_to_ding_user,
                                  msg_title + '\n' + msg_content)
    if sys_config.get('wx'):
        msg_sender.send_wx2user(msg_title + '\n' + msg_content, msg_to_wx_user)
示例#2
0
def __send(msg_title, msg_content, msg_to, **kwargs):
    """
    按照通知配置发送通知消息
    :param msg_title: 通知标题
    :param msg_content: 通知内容
    :param msg_to:  通知人user list
    :return:
    """
    sys_config = SysConfig()
    msg_sender = MsgSender()
    webhook_url = kwargs.get('webhook_url')
    msg_to_email = [user.email for user in msg_to if user.email]
    msg_to_ding_user = [
        user.ding_user_id for user in msg_to if user.ding_user_id
    ]
    if sys_config.get('mail'):
        msg_sender.send_email(msg_title, msg_content, msg_to_email)
    if sys_config.get('ding') and webhook_url:
        msg_sender.send_ding(webhook_url, msg_title + '\n' + msg_content)
    if sys_config.get('ding_to_person'):
        msg_sender.send_ding2user(msg_to_ding_user,
                                  msg_title + '\n' + msg_content)
    if sys_config.get('wx'):
        msg_to_wx_user = []
        for user in msg_to:
            if user.wx_user_id:
                msg_to_wx_user.append(user.wx_user_id)
            else:
                msg_to_wx_user.append(user.username)
        msg_sender.send_wx2user(msg_title + '\n' + msg_content, msg_to_wx_user)
示例#3
0
 def testSenderInit(self):
     sender = MsgSender()
     self.assertEqual(sender.MAIL_REVIEW_SMTP_PORT, self.smtp_port)
     archer_config = SysConfig()
     archer_config.set('mail_smtp_port', '')
     sender = MsgSender()
     self.assertEqual(sender.MAIL_REVIEW_SMTP_PORT, 465)
     archer_config.set('mail_ssl', False)
     sender = MsgSender()
     self.assertEqual(sender.MAIL_REVIEW_SMTP_PORT, 25)
示例#4
0
 def testSSLSendMail(self, _quit, sendmail, login, _):
     """SSL 测试"""
     some_sub = 'test_subject'
     some_body = 'mail_body'
     some_to = ['mail_to']
     archer_config = SysConfig()
     archer_config.set('mail_ssl', True)
     sender = MsgSender()
     sender.send_email(some_sub, some_body, some_to)
     sendmail.assert_called_with(self.smtp_user, some_to, ANY)
     _quit.assert_called_once()
示例#5
0
    def testNoPasswordSendMail(self, _quit, sendmail, login, _):
        """无密码测试"""
        some_sub = 'test_subject'
        some_body = 'mail_body'
        some_to = ['mail_to']
        archer_config = SysConfig()
        archer_config.set('mail_ssl', '')

        archer_config.set('mail_smtp_password', '')
        sender2 = MsgSender()
        sender2.send_email(some_sub, some_body, some_to)
        login.assert_not_called()
示例#6
0
def email(request):
    result = {'status': 0, 'msg': 'ok', 'data': []}
    mail = True if request.POST.get('mail', '') == 'true' else False
    mail_ssl = True if request.POST.get('mail_ssl') == 'true' else False
    mail_smtp_server = request.POST.get('mail_smtp_server', '')
    mail_smtp_port = request.POST.get('mail_smtp_port', '')
    mail_smtp_user = request.POST.get('mail_smtp_user', '')
    mail_smtp_addr = request.POST.get('mail_smtp_addr', '')
    mail_smtp_password = request.POST.get('mail_smtp_password', '')
    if not mail:
        result['status'] = 1
        result['msg'] = '请先开启邮件通知!'
        # 返回结果
        return HttpResponse(json.dumps(result),
                            content_type='application/json')
    try:
        mail_smtp_port = int(mail_smtp_port)
        if mail_smtp_port < 0:
            raise ValueError
    except ValueError:
        result['status'] = 1
        result['msg'] = '端口号只能为正整数'
        return HttpResponse(json.dumps(result),
                            content_type='application/json')
    if not request.user.email:
        result['status'] = 1
        result['msg'] = '请先完善当前用户邮箱信息!'
        return HttpResponse(json.dumps(result),
                            content_type='application/json')
    bd = 'Archery 邮件发送测试...'
    subj = 'Archery 邮件发送测试'
    sender = MsgSender(server=mail_smtp_server,
                       port=mail_smtp_port,
                       user=mail_smtp_user,
                       password=mail_smtp_password,
                       addr=mail_smtp_addr,
                       ssl=mail_ssl)
    sender_response = sender.send_email(subj, bd, [request.user.email])
    if sender_response != 'success':
        result['status'] = 1
        result['msg'] = sender_response
        return HttpResponse(json.dumps(result),
                            content_type='application/json')
    return HttpResponse(json.dumps(result), content_type='application/json')
示例#7
0
def notify_for_binlog2sql(task):
    """
    binlog2sql执行结束的通知,仅支持邮件
    :param task:
    :return:
    """
    # 判断是否开启消息通知,未开启直接返回
    sys_config = SysConfig()
    if not sys_config.get('mail') and not sys_config.get('ding'):
        logger.info('未开启消息通知,可在系统设置中开启')
        return None

    # 发送邮件通知
    if task.success:
        msg_title = '[Archery 通知]Binlog2SQL 执行结束'
        msg_content = f'解析的SQL文件为{task.result[1]},请到指定目录查看'
        msg_to = [task.result[0].email]
        MsgSender().send_email(msg_title, msg_content, msg_to)
示例#8
0
 def testDing(self, post):
     sender = MsgSender()
     post.return_value.json.return_value = {'errcode': 0}
     with self.assertLogs('default', level='DEBUG') as lg:
         sender.send_ding(self.url, self.content)
         post.assert_called_once_with(url=self.url, json={
             'msgtype': 'text',
             'text': {
                 'content': self.content
             }
         })
         self.assertIn('钉钉Webhook推送成功', lg.output[0])
     post.return_value.json.return_value = {'errcode': 1, 'errmsg': 'test_error'}
     with self.assertLogs('default', level='ERROR') as lg:
         sender.send_ding(self.url, self.content)
         self.assertIn('test_error', lg.output[0])
示例#9
0
def __send(msg_title, msg_content, msg_to, msg_cc=None, **kwargs):
    """
    按照通知配置发送通知消息
    :param msg_title: 通知标题
    :param msg_content: 通知内容
    :param msg_to:  通知人user list
    :return:
    """
    sys_config = SysConfig()
    msg_sender = MsgSender()
    msg_cc = msg_cc if msg_cc else []
    dingding_webhook = kwargs.get('dingding_webhook')
    feishu_webhook = kwargs.get('feishu_webhook')
    qywx_webhook = kwargs.get('qywx_webhook')
    msg_to_email = [user.email for user in msg_to if user.email]
    msg_cc_email = [user.email for user in msg_cc if user.email]
    msg_to_ding_user = [user.ding_user_id for user in chain(msg_to, msg_cc) if user.ding_user_id]
    msg_to_wx_user = [user.wx_user_id if user.wx_user_id else user.username for user in chain(msg_to, msg_cc)]
    logger.info(f'{msg_to_email}{msg_cc_email}{msg_to_wx_user}{chain(msg_to, msg_cc)}')
    if sys_config.get('mail'):
        msg_sender.send_email(msg_title, msg_content, msg_to_email, list_cc_addr=msg_cc_email)
    if sys_config.get('ding') and dingding_webhook:
        msg_sender.send_ding(dingding_webhook, msg_title + '\n' + msg_content)
    if sys_config.get('ding_to_person'):
        msg_sender.send_ding2user(msg_to_ding_user, msg_title + '\n' + msg_content)
    if sys_config.get('wx'):
        msg_sender.send_wx2user(msg_title + '\n' + msg_content, msg_to_wx_user)
    if sys_config.get("feishu_webhook") and feishu_webhook:
        msg_sender.send_feishu_webhook(feishu_webhook, msg_title, msg_content)
    if sys_config.get("feishu"):
        open_id = [user.feishu_open_id for user in chain(msg_to, msg_cc) if user.feishu_open_id]
        user_mail = [user.email for user in chain(msg_to, msg_cc) if not user.feishu_open_id]
        msg_sender.send_feishu_user(msg_title, msg_content, open_id, user_mail)
    if sys_config.get('qywx_webhook') and qywx_webhook:
        msg_sender.send_qywx_webhook(qywx_webhook, msg_title + '\n' + msg_content)
示例#10
0
def notify_for_audit(audit_id, **kwargs):
    """
    工作流消息通知,不包含工单执行结束的通知
    :param audit_id:
    :param kwargs:
    :return:
    """
    # 判断是否开启消息通知,未开启直接返回
    sys_config = SysConfig()
    if not sys_config.get('mail') and not sys_config.get('ding'):
        logger.info('未开启消息通知,可在系统设置中开启')
        return None
    # 获取审核信息
    audit_detail = Audit.detail(audit_id=audit_id)
    audit_id = audit_detail.audit_id
    workflow_audit_remark = kwargs.get('audit_remark', '')
    base_url = sys_config.get('archery_base_url',
                              'http://127.0.0.1:8000').rstrip('/')
    workflow_url = "{base_url}/workflow/{audit_id}".format(
        base_url=base_url, audit_id=audit_detail.audit_id)
    msg_cc_email = kwargs.get('email_cc', [])
    workflow_id = audit_detail.workflow_id
    workflow_type = audit_detail.workflow_type
    status = audit_detail.current_status
    workflow_title = audit_detail.workflow_title
    workflow_from = audit_detail.create_user_display
    group_name = audit_detail.group_name
    webhook_url = ResourceGroup.objects.get(
        group_id=audit_detail.group_id).ding_webhook

    # 获取当前审批和审批流程
    workflow_auditors, current_workflow_auditors = Audit.review_info(
        audit_detail.workflow_id, audit_detail.workflow_type)

    # 准备消息内容
    if workflow_type == WorkflowDict.workflow_type['query']:
        workflow_type_display = WorkflowDict.workflow_type['query_display']
        workflow_detail = QueryPrivilegesApply.objects.get(
            apply_id=workflow_id)
        instance = workflow_detail.instance.instance_name
        db_name = ''
        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:
            db_name = workflow_detail.db_list
            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)
        else:
            workflow_content = ''
    elif workflow_type == WorkflowDict.workflow_type['sqlreview']:
        workflow_type_display = WorkflowDict.workflow_type['sqlreview_display']
        workflow_detail = SqlWorkflow.objects.get(pk=workflow_id)
        instance = workflow_detail.instance.instance_name
        db_name = workflow_detail.db_name
        workflow_content = re.sub(
            '[\r\n\f]{2,}', '\n',
            workflow_detail.sqlworkflowcontent.sql_content[0:500].replace(
                '\r', ''))
    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_detail.current_audit).name
        msg_to = auth_group_users([auth_group_names], audit_detail.group_id)
        # 消息内容
        msg_content = '''发起时间:{}\n发起人:{}\n组:{}\n目标实例:{}\n数据库:{}\n审批流程:{}\n当前审批:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
            workflow_detail.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            workflow_from, group_name, instance, db_name, 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_to = [Users.objects.get(username=audit_detail.create_user)]
        # 消息内容
        msg_content = '''发起时间:{}\n发起人:{}\n组:{}\n目标实例:{}\n数据库:{}\n审批流程:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
            workflow_detail.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            workflow_from, group_name, instance, db_name, workflow_auditors,
            workflow_title, workflow_url, workflow_content)
    elif status == WorkflowDict.workflow_status['audit_reject']:  # 审核驳回
        msg_title = "[{}]工单被驳回#{}".format(workflow_type_display, audit_id)
        # 接收人,仅发送给申请人
        msg_to = [Users.objects.get(username=audit_detail.create_user)]
        # 消息内容
        msg_content = '''发起时间:{}\n目标实例:{}\n数据库:{}\n工单名称:{}\n工单地址:{}\n驳回原因:{}\n提醒:此工单被审核不通过,请按照驳回原因进行修改!'''.format(
            workflow_detail.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            instance, db_name, 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_detail.audit_auth_groups.split(',')
        ]
        msg_to = auth_group_users(auth_group_names, audit_detail.group_id)
        # 消息内容
        msg_content = '''发起时间:{}\n发起人:{}\n组:{}\n目标实例:{}\n数据库:{}\n工单名称:{}\n工单地址:{}\n终止原因:{}'''.format(
            workflow_detail.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            workflow_from, group_name, instance, db_name, workflow_title,
            workflow_url, workflow_audit_remark)
    else:
        raise Exception('工单状态不正确')

    # 处理接收人信息
    msg_to_email = [user.email for user in msg_to if user.email]
    # 发送通知
    msg_sender = MsgSender()
    if sys_config.get('mail'):
        msg_sender.send_email(msg_title,
                              msg_content,
                              msg_to_email,
                              list_cc_addr=msg_cc_email)
    if sys_config.get('ding'):
        if webhook_url:
            msg_sender.send_ding(webhook_url, msg_title + '\n' + msg_content)
示例#11
0
def notify_for_execute(workflow):
    """
    工单执行结束的通知
    :param workflow:
    :return:
    """
    # 判断是否开启消息通知,未开启直接返回
    sys_config = SysConfig()
    if not sys_config.get('mail') and not sys_config.get('ding'):
        logger.info('未开启消息通知,可在系统设置中开启')
        return None
    # 获取当前审批和审批流程
    base_url = sys_config.get('archery_base_url',
                              'http://127.0.0.1:8000').rstrip('/')
    audit_auth_group, current_audit_auth_group = Audit.review_info(
        workflow.id, 2)
    audit_id = Audit.detail_by_workflow_id(workflow.id, 2).audit_id
    url = "{base_url}/workflow/{audit_id}".format(base_url=base_url,
                                                  audit_id=audit_id)
    msg_title = "[{}]工单{}#{}".format(
        WorkflowDict.workflow_type['sqlreview_display'],
        workflow.get_status_display(), audit_id)
    msg_content = '''发起人:{}\n组:{}\n审批流程:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
        workflow.engineer_display, workflow.group_name, audit_auth_group,
        workflow.workflow_name, url,
        re.sub(
            '[\r\n\f]{2,}', '\n',
            workflow.sqlworkflowcontent.sql_content[0:500].replace('\r', '')))

    # 邮件通知申请人,抄送DBA
    msg_to = Users.objects.filter(username=workflow.engineer)
    msg_cc = auth_group_users(auth_group_names=['DBA'],
                              group_id=workflow.group_id)

    # 处理接收人信息
    msg_to_email = [user.email for user in msg_to if user.email]
    msg_cc_email = [user.email for user in msg_cc if user.email]

    # 判断是发送钉钉还是发送邮件
    msg_sender = MsgSender()
    if sys_config.get('mail'):
        msg_sender.send_email(msg_title,
                              msg_content,
                              msg_to_email,
                              list_cc_addr=msg_cc_email)
    if sys_config.get('ding'):
        # 钉钉通知申请人,审核人,抄送DBA
        webhook_url = ResourceGroup.objects.get(
            group_id=workflow.group_id).ding_webhook
        if webhook_url:
            MsgSender.send_ding(webhook_url, msg_title + '\n' + msg_content)

    # DDL通知
    if sys_config.get('mail') and sys_config.get(
            'ddl_notify_auth_group') and workflow.status == 'workflow_finish':
        # 判断上线语句是否存在DDL,存在则通知相关人员
        if workflow.syntax_type == 1:
            # 消息内容通知
            msg_title = '[Archery]有新的DDL语句执行完成#{}'.format(audit_id)
            msg_content = '''发起人:{}\n变更组:{}\n变更实例:{}\n变更数据库:{}\n工单名称:{}\n工单地址:{}\n工单预览:{}\n'''.format(
                Users.objects.get(username=workflow.engineer).display,
                workflow.group_name, workflow.instance.instance_name,
                workflow.db_name, workflow.workflow_name, url,
                workflow.sqlworkflowcontent.sql_content[0:500])
            # 获取通知成员ddl_notify_auth_group
            msg_to = Users.objects.filter(
                groups__name=sys_config.get('ddl_notify_auth_group'))
            # 处理接收人信息
            msg_to_email = [user.email for user in msg_to]

            # 发送
            msg_sender.send_email(msg_title, msg_content, msg_to_email)
示例#12
0
def send_msg(workflow_detail):
    mail_sender = MsgSender()
    sys_config = SysConfig()
    # 获取当前审批和审批流程
    base_url = sys_config.get('archery_base_url',
                              'http://127.0.0.1:8000').rstrip('/')
    audit_auth_group, current_audit_auth_group = Audit.review_info(
        workflow_detail.id, 2)
    audit_id = Audit.detail_by_workflow_id(workflow_detail.id, 2).audit_id
    url = "{base_url}/workflow/{audit_id}".format(base_url=base_url,
                                                  audit_id=audit_id)
    msg_title = "[{}]工单{}#{}".format(
        WorkflowDict.workflow_type['sqlreview_display'],
        workflow_detail.status, audit_id)
    msg_content = '''发起人:{}\n组:{}\n审批流程:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
        workflow_detail.engineer_display, workflow_detail.group_name,
        audit_auth_group, workflow_detail.workflow_name, url,
        re.sub('[\r\n\f]{2,}', '\n',
               workflow_detail.sql_content[0:500].replace('\r', '')))

    if sys_config.get('mail'):
        # 邮件通知申请人,抄送DBA
        list_to_addr = [
            email['email'] for email in Users.objects.filter(
                username=workflow_detail.engineer).values('email')
        ]
        list_cc_addr = [
            email['email'] for email in
            auth_group_users(auth_group_names=['DBA'],
                             group_id=workflow_detail.group_id).values('email')
        ]
        logger.debug('发送执行结果通知,消息audit_id={}'.format(audit_id))
        logger.debug('消息标题:{}\n通知对象:{}\n消息内容:{}'.format(
            msg_title, list_to_addr + list_cc_addr, msg_content))
        mail_sender.send_email(msg_title,
                               msg_content,
                               list_to_addr,
                               list_cc_addr=list_cc_addr)
    if sys_config.get('ding'):
        # 钉钉通知申请人,审核人,抄送DBA
        webhook_url = ResourceGroup.objects.get(
            group_id=workflow_detail.group_id).ding_webhook
        MsgSender.send_ding(webhook_url, msg_title + '\n' + msg_content)

    # DDL通知
    if sys_config.get('mail') and sys_config.get('ddl_notify_auth_group', None) \
            and workflow_detail.status == '已正常结束':
        # 判断上线语句是否存在DDL,存在则通知相关人员
        sql_content = workflow_detail.sql_content
        # 删除注释语句
        sql_content = ''.join(
            map(
                lambda x: re.compile(r'(^--\s+.*|^/\*.*\*/;\s*$)').sub(
                    '', x, count=1), sql_content.splitlines(1))).strip()
        # 去除空行
        sql_content = re.sub('[\r\n\f]{2,}', '\n', sql_content)

        # 匹配DDL语句CREATE、ALTER(排除索引变更)、DROP、TRUNCATE、RENAME
        send = 0
        for statement in sqlparse.split(sql_content):
            # alter语法
            if re.match(
                    r"^alter\s+table\s+\S+\s+(add|alter|change|drop|rename|modify)\s+(?!.*(index|key|unique))",
                    statement.strip().lower()):
                send = 1
                break
            # create语法
            elif re.match(r"^create\s+(temporary\s+)?(database|schema|table)",
                          statement.strip().lower()):
                send = 1
                break
            # drop语法
            elif re.match(r"^drop|^rename|^truncate",
                          statement.strip().lower()):
                send = 1
                break

        if send == 1:
            # 消息内容通知
            msg_title = '[archery]有新的DDL语句执行完成#{}'.format(audit_id)
            msg_content = '''发起人:{}\n变更组:{}\n变更实例:{}\n变更数据库:{}\n工单名称:{}\n工单地址:{}\n工单预览:{}\n'''.format(
                Users.objects.get(username=workflow_detail.engineer).display,
                workflow_detail.group_name, workflow_detail.instance_name,
                workflow_detail.db_name, workflow_detail.workflow_name, url,
                workflow_detail.sql_content[0:500])
            # 获取通知成员
            msg_to = [
                email['email']
                for email in Users.objects.filter(groups__name=sys_config.get(
                    'ddl_notify_auth_group')).values('email')
            ]

            # 发送
            logger.debug('发送DDL通知,消息audit_id={}'.format(audit_id))
            logger.debug('消息标题:{}\n通知对象:{}\n消息内容:{}'.format(
                msg_title, msg_to, msg_content))
            mail_sender.send_email(msg_title, msg_content, msg_to)
示例#13
0
def notify(audit_info, msg_type=0, **kwargs):
    audit_id = audit_info.audit_id
    workflow_audit_remark = kwargs.get('audit_remark', '')
    workflow_url = kwargs.get('workflow_url', '')
    msg_email_cc = kwargs.get('email_cc', [])
    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
    group_name = audit_info.group_name
    webhook_url = ResourceGroup.objects.get(
        group_id=audit_info.group_id).ding_webhook

    # 获取当前审批和审批流程
    from sql.utils.workflow_audit import Audit
    workflow_auditors, current_workflow_auditors = Audit.review_info(
        audit_info.workflow_id, audit_info.workflow_type)

    # 准备消息内容
    if workflow_type == WorkflowDict.workflow_type['query']:
        workflow_type_display = WorkflowDict.workflow_type['query_display']
        workflow_detail = QueryPrivilegesApply.objects.get(
            apply_id=workflow_id)
        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)
        else:
            workflow_content = ''
    elif workflow_type == WorkflowDict.workflow_type['sqlreview']:
        workflow_type_display = WorkflowDict.workflow_type['sqlreview_display']
        workflow_detail = SqlWorkflow.objects.get(pk=workflow_id)
        workflow_content = re.sub(
            '[\r\n\f]{2,}', '\n',
            workflow_detail.sql_content[0:500].replace('\r', ''))
    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)
        ]
        # 消息内容
        msg_content = '''发起人:{}\n组:{}\n审批流程:{}\n当前审批:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
            workflow_from, group_name, 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_content = '''发起人:{}\n组:{}\n审批流程:{}\n工单名称:{}\n工单地址:{}\n工单详情预览:{}\n'''.format(
            workflow_from, group_name, 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_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_content = '''发起人:{}\n组:{}\n工单名称:{}\n工单地址:{}\n提醒:提交人主动终止流程'''.format(
            workflow_from, group_name, workflow_title, workflow_url)
    else:
        raise Exception('工单状态不正确')

    # 判断是发送钉钉还是发送邮件
    msg_sender = MsgSender()
    logger.debug('发送消息通知,消息audit_id={}'.format(audit_id))
    logger.debug('消息标题:{}\n通知对象:{}\n消息内容:{}'.format(msg_title,
                                                    msg_email_reciver,
                                                    msg_content))
    if msg_type == 0:
        sys_config = SysConfig()
        if sys_config.get('mail'):
            msg_sender.send_email(msg_title,
                                  msg_content,
                                  msg_email_reciver,
                                  list_cc_addr=msg_email_cc)
        if sys_config.get('ding'):
            msg_sender.send_ding(webhook_url, msg_title + '\n' + msg_content)
    elif msg_type == 1:
        msg_sender.send_email(msg_title,
                              msg_content,
                              msg_email_reciver,
                              list_cc_addr=msg_email_cc)
    elif msg_type == 2:
        msg_sender.send_ding(webhook_url, msg_title + '\n' + msg_content)