def get_default_groups(log, client, room, user, zapi):
    try:
        groups = mbl.get_env(user, "zabbix_groups")
        if groups != None:
            return groups

        groups = [59]  # по-умолчанию - ВЭФ ИБП
        zabbix_login = mbl.get_env(user, "zabbix_login")
        if zabbix_login != None:
            groups = zabbix_get_hosts_groups_by_user(log, zapi, zabbix_login)
            if groups == None:
                log.error("error zabbix_get_hosts_groups_by_user('%s')" %
                          zabbix_login)
                mbl.bot_fault(log, client, room)
                mbl.go_to_main_menu(log, logic, client, room, user)
                return None
        else:
            if mba.send_notice(
                    log, client, room,
                    u"По умолчанию формирую статистику для группы ВЭФ ИБП (установите zabbix_login для индивидуальных настроек в главном меню)"
            ) == False:
                log.error("send_notice() to user %s" % user)
                return None
        mbl.set_env(user, "zabbix_groups", groups)
        return groups
    except Exception as e:
        log.error(get_exception_traceback_descr(e))
        return False
def zabbix_get_version(log, logic, client, room, user, data, source_message,
                       cmd):
    try:
        log.info("zabbix_get_version()")
        zapi = zabbix_init(log)
        if zapi == None:
            log.error("zabbix_init()")
            return False
        answer = zapi.do_request('apiinfo.version')
        log.debug("zabbix version: %s" % answer['result'])
        if mba.send_message(log, client, room,
                            u"Версия ZABBIX: %s" % answer['result']) == False:
            log.error("send_message() to user")
            mbl.bot_fault(log, client, room)
            return False
        if mba.send_notice(
                log, client, room,
                u"возвращаюсь в начальное меню. Отправьте 'помощь' или '1' для получения справки."
        ) == False:
            log.error("send_notice() to user %s" % user)
        mbl.set_state(user, logic)
        return True
    except Exception as e:
        log.error(get_exception_traceback_descr(e))
        return False
Пример #3
0
def go_to_main_menu(log, logic, client, room, user):
    log.debug("go_to_main_menu()")
    log.info("return to main menu in logic")
    if mba.send_notice(
            log, client, room,
            u"возвращаюсь в начальное меню. Отправьте 'помощь' или '1' для получения справки."
    ) == False:
        log.error("send_notice() to user %s" % user)
    reset_user_memmory(user)
    set_state(user, logic)
    return True
def zabbix_show_groups(log, logic, client, room, user, data, source_message,
                       cmd):
    try:
        log.info("zabbix_show_groups()")

        zapi = zabbix_init(log)
        if zapi == None:
            log.error("zabbix_init()")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        groups = get_default_groups(log, client, room, user, zapi)
        if groups == None:
            log.debug("error get_default_groups() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        groups_names = zabbix_get_hosts_groups_names(log, zapi, groups)
        if groups_names == None:
            log.debug(
                "error zabbix_get_hosts_groups_names() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        zabbix_login = mbl.get_env(user, "zabbix_login")
        if zabbix_login == None:
            zabbix_login = "******"
        text = "<p>Текущий пользователь: <strong>%s</strong></p>" % zabbix_login
        text += "<p><strong>Список текущих групп:</strong></p><ol>"
        for name in groups_names:
            text += "<li>%s</li> " % name
        text += "</ol>"
        if mba.send_html(log, client, room, text) == False:
            log.error("send_html() to user %s" % user)
            return False
        # Завершаем текущий этап и переходим в главное меню:
        if mba.send_notice(
                log, client, room,
                u"возвращаюсь в начальное меню. Отправьте 'помощь' или '1' для получения справки."
        ) == False:
            log.error("send_notice() to user %s" % user)
        mbl.set_state(user, logic)
        return True
    except Exception as e:
        log.error(get_exception_traceback_descr(e))
        return False
def rm_goto_zayavka_num_enter(log, logic, client, room, user, data, message,
                              cmd):
    log.info("rm_goto_zayavka_num_enter()")
    return_to_zayavka_enter = mbl.get_env(user, "return_to_zayavka_enter")
    if return_to_zayavka_enter != None:
        log.debug("set return_to_zayavka_enter")
        mbl.set_state(user, return_to_zayavka_enter)
    else:
        log.debug("no return_to_zayavka_enter - reset state")
        if mba.send_notice(
                log, client, room,
                u"внутренняя ошибка бота - возвращаюсь в начальное меню. Отправьте 'помощь' или '1' для получения справки."
        ) == False:
            log.error("send_notice() to user %s" % user)
        mbl.set_state(user, logic)
        return False
def rm_pre_select_zayavka(log, memmory, logic, client, room, user, data,
                          message, cmd):
    log.debug("rm_pre_select_zayavka()")
    # сохраняем раздел для возможного повторного вопроса о номере заявки:
    state = mbl.get_state(log, user)
    if state == None:
        log.error("mbl.get_state(log,%s)" % user)
        return False
    log.debug("1: state=")
    log.debug(state)
    log.info("save cur_state to return_to_zayavka_enter")
    mbl.set_env(user, "return_to_zayavka_enter", state["answer"])
    return True

    if mba.send_notice(
            log, client, room,
            u"Перехожу в меню ввода номера заявки. Вы можете выбрать другой номер заявки или 0, для выхода в главное меню."
    ) == False:
        log.error("send_notice() to user %s" % user)
        return False
    return True
def zabbix_show_triggers(log, logic, client, room, user, data, source_message,
                         cmd):
    try:
        log.info("zabbix_show_triggers()")
        zabbix_priority = mbl.get_env(user, "zabbix_priority")
        if zabbix_priority == None:
            log.debug("error get_env zabbix_priority - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        zapi = zabbix_init(log)
        if zapi == None:
            log.error("zabbix_init()")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        groups = get_default_groups(log, client, room, user, zapi)
        if groups == None:
            log.debug("error get_default_groups() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        if mba.send_notice(log, client, room,
                           u"формирую статистику...") == False:
            log.error("send_notice() to user %s" % user)
            return False

        #Get List of problems
        problems = zapi.problem.get(\
            groupids=groups,\
            output=['eventid','objectid','clock','ns','name','severity'],\
            source=0,\
            object=0, # тип проблем - триггеры\
            sortfield=['eventid'], preservekeys=1,limit=100,recent=1,evaltype=0,\
            severities=zabbix_priority,\
            sortorder='DESC',\
            selectSuppressionData=['maintenanceid','suppress_until']\
            )
        if problems == None:
            log.error("error zapi.problems.get() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        triggerids = []
        for problemid in problems:
            problem = problems[problemid]
            triggerids.append(problem['objectid'])

        #Get List of triggers
        triggers = zapi.trigger.get(\
            output=['priority','expression','recovery_mode','recovery_expression','comments','url'],\
            selectHosts=['hostid'],\
            triggerids=triggerids,\
            monitored=1,skipDependent=1,preservekeys=1,\
            selectItems=['itemid','hostid','name','key_','value_type','units','valuemapid']\
            )
        if triggers == None:
            log.error("error zapi.trigger.get() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        hostids = []
        for triggerid in triggers:
            trigger = triggers[triggerid]
            for item in trigger['hosts']:
                hostids.append(item['hostid'])

        #Get List of hosts
        hosts = zapi.host.get(hostids=hostids,
                              output=[
                                  'hostid', 'name', 'maintenanceid',
                                  'maintenance_status', 'maintenance_type'
                              ])
        if hosts == None:
            log.error("error zapi.host.get() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        priority = u"среднего"
        if zabbix_priority == "5":
            priority = u"критического"
        elif zabbix_priority == "4":
            priority = u"важного"

        text = "<p>Список активных триггеров <strong>%s</strong> уровня:</p><ol>" % priority
        for problemid in problems:
            problem = problems[problemid]
            triggerid = problem['objectid']
            if triggerid not in triggers:
                continue
            trigger = triggers[triggerid]
            hostid = int(trigger['hosts'][0]['hostid'])
            host = get_host_by_id(log, hosts, hostid)
            if host == None:
                #log.debug("skip unknown host")
                #        log.debug(hosts)
                continue
            data = get_time_str_from_unix_time(problem['clock'])
            period = get_period_str_from_ns(problem['clock'])
            #  print("номер: %d, дата наступления события: %s (продолжительность: %s), описание: '%s', хост: '%s'"%(index,data,period,problem['name'],host['name']))

            text += "<li>"
            text += "<strong>" + problem['name'] + "</strong>"
            text += ", <em>устройство:</em> <strong>%s</strong>" % host['name']
            text += ", <em>время события:</em> <strong>%s</strong>" % data
            text += ", <em>продолжительность:</em> <strong>%s</strong>" % period
            text += "</li>"
        text += "</ol>"
        if mba.send_html(log, client, room, text) == False:
            log.error("send_html() to user %s" % user)
            return False

        #mbl.go_to_main_menu(log,logic,client,room,user)
        if mba.send_notice(
                log, client, room,
                u"можете выбрать просмотр триггеров иной важности (1 - критические, 2 - важные, 3 - средние) или 0 - для выхода"
        ) == False:
            log.error("send_notice() to user %s" % user)
            return False
        return True
    except Exception as e:
        log.error(get_exception_traceback_descr(e))
        return False
def zabbix_show_stat(log, logic, client, room, user, data, source_message,
                     cmd):
    try:
        log.info("zabbix_show_triggers()")

        zapi = zabbix_init(log)
        if zapi == None:
            log.error("zabbix_init()")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        groups = get_default_groups(log, client, room, user, zapi)
        if groups == None:
            log.debug("error get_default_groups() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False

        if mba.send_notice(log, client, room,
                           u"формирую статистику...") == False:
            log.error("send_notice() to user %s" % user)
            return False

        triggers = zapi.trigger.get(groupids=groups,
                                    only_true="1",
                                    active="1",
                                    min_severity=3,
                                    output="extend",
                                    selectFunctions="extend",
                                    expandDescription="True")
        if triggers == None:
            log.debug("error zapi.trigger.get() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False
        priority_3_num = len(triggers)

        triggers = zapi.trigger.get(groupids=groups,
                                    only_true="1",
                                    active="1",
                                    min_severity=4,
                                    output="extend",
                                    selectFunctions="extend",
                                    expandDescription="True")
        if triggers == None:
            log.debug("error zapi.trigger.get() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False
        priority_4_num = len(triggers)

        triggers = zapi.trigger.get(groupids=groups,
                                    only_true="1",
                                    active="1",
                                    min_severity=5,
                                    output="extend",
                                    selectFunctions="extend",
                                    expandDescription="True")
        if triggers == None:
            log.debug("error zapi.trigger.get() - return to main menu")
            mbl.bot_fault(log, client, room)
            mbl.go_to_main_menu(log, logic, client, room, user)
            return False
        priority_5_num = len(triggers)

        sev_5_num = priority_5_num
        sev_4_num = priority_4_num - sev_5_num
        sev_3_num = priority_3_num - priority_4_num

        zabbix_login = mbl.get_env(user, "zabbix_login")
        if zabbix_login == None:
            zabbix_login = "******"
        text = "<p>Текущий пользователь: <strong>%s</strong></p>" % zabbix_login
        text += "<p><strong>Список проблем для выбранных групп, сгруппированных по важности:</strong></p><br><ol>"
        text += "<li>Критических проблем - %d шт.</li> " % sev_5_num
        text += "<li>Важных проблем - %d шт.</li> " % sev_4_num
        text += "<li>Средних проблем - %d шт.</li> " % sev_3_num
        text += "</ol>"
        if mba.send_html(log, client, room, text) == False:
            log.error("send_html() to user %s" % user)
            return False
        # Завершаем текущий этап и ждём ответа от пользователя:
        mbl.set_state(user, data["answer"])
        return True
    except Exception as e:
        log.error(get_exception_traceback_descr(e))
        return False