예제 #1
0
async def zabbixWanDelChannel(request):
    post_data = await request.json()
    user_id = await get_jwt_info(request, 'user_id')
    zabbix = post_data['zabbix']
    channel_id = str(post_data['channel_id'])
    api = await async_zabbix_conn(zabbix, 'net')
    try:
        channel_info = await api.host.get(hostids=[channel_id],
                                          output=['name', 'host'])
        await api.host.delete(channel_id)
        await api.close()
        request.app['zabbix_wan_logger'].info(
            f'USER ({user_id})| Info in app: del channel {channel_info}')
        return json_response({
            'result': True,
            'text': f"Канал удалён {channel_id}"
        })
    except Exception as err:
        await api.close()
        request.app['zabbix_wan_logger'].error(
            f'USER ({user_id})|Error in app: {str(err)}')
        return json_response({
            'result': False,
            'text': f"Канал не существует {channel_id} {err}"
        })
예제 #2
0
async def get_log(request):
    try:
        post_data = await request.json()
        limit = int(post_data['limit']) if post_data['limit'] else 100
        conf = request.app['app_config']
        engine = sa.create_engine(
            f"mysql+pymysql://{conf['database']['user']}:{conf['database']['password']}@"
            f"{conf['database']['ip']}/selfportal")
        with engine.connect() as conn:
            res = conn.execute(tbl_app_config.select().with_only_columns(
                [tbl_app_config.c.value]).where(
                    sa.and_(tbl_app_config.c.keyword == post_data['source'],
                            tbl_app_config.c.type == 'logging')))
            result = res.fetchall()
        path = result[0][0]
        count = 0
        result = []
        if post_data['source'] in allowed_logs:
            for line in readlines_reverse(path):
                if count < limit:
                    if re.findall(post_data['filter'], line):
                        datetime = ' '.join(line.split()[:2]).split(',')[0]
                        msg = ' '.join(line.split()[6:])
                        result.append({'datetime': datetime, 'msg': msg})
                        count += 1
                else:
                    break
        return json_response({'result': True, 'rows': result})
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})
예제 #3
0
async def get_history(request):
    try:
        post_data = await request.json()
        time = post_data['time']
        hosts = post_data['hosts']
        hosts_by_source = {}
        result = {}
        for host in hosts:
            if host['source'] not in hosts_by_source:
                result[host['source']] = {}
                hosts_by_source[host['source']] = set()
            hosts_by_source[host['source']].add(host['host'])
        for source in hosts_by_source:
            zapi = await async_zabbix_conn(source)
            zabbix_hosts = await zapi.host.get(
                output=['hostid', 'host'],
                filter={'host': list(hosts_by_source[source])})
            hostids = {host['hostid']: host['host'] for host in zabbix_hosts}
            host_history = await zapi.event.get(
                value='1',
                hostids=list(hostids.keys()),
                selectHosts=['extend'],
                time_from=int(
                    (datetime.datetime.now() -
                     datetime.timedelta(seconds=int(time))).timestamp()))
            await zapi.close()
            for event in host_history:
                if hostids[event['hosts'][0]['hostid']] not in result[source]:
                    result[source][hostids[event['hosts'][0]['hostid']]] = []
                result[source][hostids[event['hosts'][0]['hostid']]].append(
                    event)
        return json_response({'result': True, 'events': result})
    except BaseException as e:
        request.app['eventdashboard_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #4
0
async def add_maintenance_lite(request):
    post_data = await request.json()
    token = request.headers.get('authorization', None).split()[1]
    jwtd = jwt.decode(token,
                      JWT_SECRET,
                      algorithms=[JWT_ALGORITHM],
                      options={'verify_exp': False})
    try:
        zapi = await async_zabbix_conn(post_data['source'], 'net')
        host = await zapi.host.get(
            output=['host', 'hostid'],
            filter={'name': post_data['value']['hostname']},
            limit=1)
        now = int(time.time())
        res = await zapi.maintenance.create(
            name=jwtd['user_id'] + '_h' + host[0]['hostid'] + '_' + str(now),
            hostids=[host[0]['hostid']],
            timeperiods=[{
                "timeperiod_type": 0,
                "period": post_data['value']['time']
            }],
            active_since=now,
            active_till=now + int(post_data['value']['time']),
            description=post_data['value']['description'])
        await zapi.close()
        request.app['maintenance_logger'].info(
            f"Created simple maintenance on {post_data['source']} by {jwtd['user_id']} for hostid {host[0]['hostid']} with period from now for {int(post_data['value']['time'])} seconds"
        )
        return json_response({'result': True})
    except BaseException as e:
        request.app['maintenance_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #5
0
async def update_event(request):
    try:
        post_data = await request.json()
        token = request.headers.get('authorization', None).split()[1]
        jwtd = jwt.decode(token,
                          JWT_SECRET,
                          algorithms=[JWT_ALGORITHM],
                          options={'verify_exp': False})
        ids = post_data['ids']
        action = post_data['action']
        message = post_data['message']
        ids_by_source = {}
        result = {}
        errors = []
        for id in ids:
            if id['source'] not in ids_by_source:
                ids_by_source[id['source']] = {}
                ids_by_source[id['source']] = set()
            ids_by_source[id['source']].add(id['id'])
        for source in ids_by_source:
            zapi = await async_zabbix_conn(source)
            try:
                await zapi.event.acknowledge(
                    action=action,
                    eventids=list(ids_by_source[source]),
                    message=jwtd['user_id'] + ': ' + message)
            except BaseException as e:
                errors.append(str(e))
            await zapi.close()
        return json_response({'result': True, 'errors': errors})
    except BaseException as e:
        request.app['eventdashboard_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #6
0
async def change_power(request):
    try:
        post_data = await request.json()
        ip = post_data['ip']
        env = post_data['env']
        tag = post_data['tag']
        status = post_data['status']
        token = request.headers.get('authorization', None).split()[1]
        jwtd = jwt.decode(token,
                          JWT_SECRET,
                          algorithms=[JWT_ALGORITHM],
                          options={'verify_exp': False})
        result, text = await change_power_di(
            ip, env, tag, status, jwtd['user_id'],
            request.app['monitoring_add_logger'])
        if result:
            request.app['monitoring_add_logger'].info(
                f"User {jwtd['user_id']} change power for host with ip {ip},env: {env},tag: {tag}. Status: {status}"
            )
            return json_response({'result': True, 'ids': text})
        else:
            return json_response({'result': False, 'text': text})
    except BaseException as e:
        request.app['monitoring_add_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #7
0
async def get_user_params(request):
    try:
        post_data = await request.json()
        username = post_data['username']
        source = post_data['source']
        engine = await db_connect()
        async with engine.acquire() as conn:
            res = await conn.execute(
                tbl_users.select().where(tbl_users.c.login == username))
            result = await res.fetchall()
        engine.close()
        if len(result) > 0:
            result = result[0]
            allowed_groups = await get_allowed_grps(source)
            sigmamail = ''
            alphamail = ''
            for mail in result.as_tuple()[4:6]:
                if '@sberbank.ru' in mail:
                    sigmamail = mail
                else:
                    alphamail = mail
            params = dict(mail=alphamail,
                          mail_sigma=sigmamail,
                          allowed_groups=allowed_groups)
            return json_response({'result': True, 'params': params})
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})
예제 #8
0
async def add_maintanance(_, request):
    try:
        post_data = await request.json()
        iplist = post_data['iplist']
        env, tag, os = post_data['env'], post_data['tag'], post_data['os']
        token = request.headers.get('authorization', None).split()[1]
        jwtd = jwt.decode(token,
                          JWT_SECRET,
                          algorithms=[JWT_ALGORITHM],
                          options={'verify_exp': False})

        source = await get_source(env, tag, os)
        post_data['active_since'] = post_data[
            'start_main'] if 'start_main' in post_data else float(time.time())
        period = post_data['period']
        post_data['period'] = float(period) * 60 * 60
        post_data['active_till'] = post_data['active_since'] + period

        radd(
            source, {
                'post_data': post_data,
                'iplist': iplist,
                'method': 'add_maintanance',
                'source': source,
                'user': jwtd['user_id']
            })

        return json_response({'result': True})
    except BaseException as e:
        request.app['monitoring_add_logger'].error(
            f'Error in app: {str(e)}, data {post_data}')
        return json_response({'result': False, 'text': str(e)})
예제 #9
0
async def zabbixWanCreateChannels(request):
    user_id = await get_jwt_info(request, 'user_id')
    request['user_id'] = user_id
    post_data = await request.json()
    zabbix = post_data['zabbix']
    chanel = post_data['chanel']
    try:
        api = await async_zabbix_conn(zabbix, 'net')
        host, group = await get_scheme_to_send(i=chanel,
                                               zapi=api,
                                               zabbix=zabbix,
                                               proxy_balanser=1,
                                               request=request)
        hostid = await api.host.create(host)
        await update_chanel(api=api, SM_HOSTID=hostid['hostids'][0])
        await api.close()
        await update_cnl_num(db='configs', group=group, zabbix=zabbix)
        chanel.pop('_showDetails', None)
        request.app['zabbix_wan_logger'].info(
            f'USER ({user_id})|Info in app: create channel {chanel}')
        return json_response({
            'result': True,
            'text': f"Данные отправлены успешно"
        })
    except Exception as err:
        await api.close()
        if str(err) == 'list index out of range':
            err = 'Обязательные поля не заполненны'
        request.app['app_logger'].error(f'Error in app: {str(err)}')
        request.app['zabbix_wan_logger'].error(
            f'USER ({user_id})|Error in app: {str(err)}')
        return json_response({'result': False, 'text': f"{err}"})
예제 #10
0
async def user_exist_check(request):
    try:
        post_data = await request.json()
        username = post_data['username']
        source = post_data['source']
        zapi = await async_zabbix_conn(source)
        user = await zapi.user.get(
            output='extend',
            filter={'alias': username},
            selectMedias=['mediatypeid', 'sendto', 'active'],
            selectMediatype='extend',
            selectUsrgrps=['name'])
        await zapi.close()
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False})
    else:
        if len(user) > 0:
            user = user[0]
            ZabbixConfig = await get_zabbix_conf()
            if '(' in user['surname']:
                res = re.findall('(.*)\((.+)\)', user['surname'])[0]
                user['surname'] = res[0]
                user['sigma_login'] = res[1]
            else:
                user['sigma_login'] = ''

            user['phonemedia'] = {'sendto': '', 'active': 1}
            user['sigmamailmedia'] = {'sendto': '', 'active': 1}
            user['mailmedia'] = {'sendto': '', 'active': 1}
            for media in user['medias']:
                if media['mediatypeid'] == str(
                        ZabbixConfig[source]['phone_media_type']):
                    user['phonemedia'] = media
                elif media['mediatypeid'] == str(
                        ZabbixConfig[source]['email_media_type']):
                    str_for_chechk = media['sendto'] if isinstance(
                        media['sendto'], str) else media['sendto'][0]
                    if '@sberbank.ru' in str_for_chechk:
                        user['sigmamailmedia'] = media
                    else:
                        user['mailmedia'] = media
            allowed_groups = await get_allowed_grps(source, with_id=True)
            user['selected_grps'] = []
            for grp in user['usrgrps']:
                if grp['name'] in allowed_groups:
                    user['selected_grps'].append(grp['name'])
                elif grp['name'].split('_')[-1] in allowed_groups.values():
                    user['selected_grps'].append(
                        list(allowed_groups.keys())[list(
                            allowed_groups.values()).index(
                                grp['name'].split('_')[-1])])
            return json_response({
                'result': True,
                'user': user,
                'allowed_groups': list(allowed_groups.keys())
            })
        else:
            return json_response({'result': False})
예제 #11
0
async def run_inventory_task(request):
    try:
        post_data = await request.json()
        config_name = post_data['source']
        run_update_inventory(config_name)
        return json_response({'result': True})
    except:
        return json_response({'result': False})
예제 #12
0
async def run_task(request):
    try:
        post_data = await request.json()
        config_name = post_data['source']
        task_name = post_data['task']
        tasks[task_name](config_name)
        return json_response({'result': True})
    except:
        return json_response({'result': False})
예제 #13
0
async def get_hostlist_expert(request):
    post_data = await request.json()
    try:
        hostlist = await get_hostlist(post_data['mode'], post_data['value'],
                                      post_data['source'])
        return json_response({'result': True, 'hostnamelist': hostlist})
    except BaseException as e:
        request.app['maintenance_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #14
0
async def new_problem(request):
    try:
        post_data = await request.json()
        asyncio.get_event_loop().create_task(new_problem_generate(request))
        return json_response({'result': True})
    except BaseException as e:
        request.app['eventdashboard_logger'].error(
            f'Error {str(type(e))}in app: {str(e)}, header: {post_data["id"]}, msg:{post_data["msg"]}'
        )
    return json_response({'result': False})
예제 #15
0
async def zabbixWanUpdateChannel(request):
    post_data = await request.json()
    user_id = await get_jwt_info(request, 'user_id')
    request['user_id'] = user_id
    zabbix = post_data['zabbix']
    chanel = post_data['chanel']
    host_id = chanel['hostid']
    host_name = chanel['host']
    api = await async_zabbix_conn(zabbix, 'net')
    try:
        host, group = await get_scheme_to_send(i=chanel,
                                               zapi=api,
                                               zabbix=zabbix,
                                               proxy_balanser=1,
                                               request=request)
        host['host'] = host_name
        host["hostid"] = host_id
        hostinterface = await api.host.get(hostids=[host_id],
                                           selectInterfaces=["interfaceid"],
                                           output=['interfaces'])
        host['interfaces'][0]['interfaceid'] = hostinterface[0]['interfaces'][
            0]['interfaceid']
        await api.host.update(host)
        macros = await api.usermacro.get(hostids=[host_id])
        macros.extend([{
            'macro': '{$SM_HOSTID}',
            'value': host_id
        }, {
            'macro':
            '{$SCREEN_LINK}',
            'value':
            f'https://zabbix-cssm.sigma.sbrf.ru/zabbix_wan/'
            f'zabbix.php?action=problem.view&page=1&filter_'
            f'show=1&filter_hostids[]={host_id}&filter_se'
            f'verity=2&filter_set=1'
        }])

        await api.host.update({'hostid': host_id, 'macros': macros})
        await api.close()
        host_info = host
        request.app['zabbix_wan_logger'].info(
            f'USER ({user_id})|Info in app: update channel {chanel}')
        return json_response({
            'result': True,
            'text': f"Данные ({host_name}) успешно обновлены"
        })
    except Exception as err:
        await api.close()
        request.app['zabbix_wan_logger'].error(
            f'USER ({user_id})|Error in app: {str(err)}')
        return json_response({'result': False, 'text': f"{err}"})
예제 #16
0
async def get_templateslist(request):
    post_data = await request.json()
    try:
        zapi = await async_zabbix_conn(post_data['source'])
        search_query = {}
        if post_data['hostname']:
            search_query = {'host': post_data['hostname']}
        res = await zapi.template.get(output=['name'], search=search_query)
        hostlist = [host['name'] for host in res]
        await zapi.close()
        return json_response({'result': True, 'templatenamelist': hostlist})
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #17
0
async def save_filter(request):
    try:
        token = request.headers.get('authorization', None).split()[1]
        jwtd = jwt.decode(token,
                          JWT_SECRET,
                          algorithms=[JWT_ALGORITHM],
                          options={'verify_exp': False})
        post_data = await request.json()
        filters = post_data['filters']
        engine = await db_connect('configs')
        async with engine.acquire() as conn:
            try:
                await conn.execute(tbl_eventdashboard_filters.insert().values(
                    author=jwtd['user_id'],
                    name=filters['name'],
                    query=filters['query'],
                    time=filters['time'],
                    row_count=filters['row_count'],
                    severities=json.dumps(filters['severities'],
                                          ensure_ascii=False),
                    selected_cols=json.dumps(filters['selected_cols'],
                                             ensure_ascii=False),
                    colors=json.dumps(filters['colors'], ensure_ascii=False),
                    width=json.dumps(filters['width'], ensure_ascii=False)))
                await conn.execute("commit")
            except pymysql.err.IntegrityError:
                await conn.execute(tbl_eventdashboard_filters.update().values(
                    query=filters['query'],
                    time=filters['time'],
                    row_count=filters['row_count'],
                    severities=json.dumps(filters['severities'],
                                          ensure_ascii=False),
                    selected_cols=json.dumps(filters['selected_cols'],
                                             ensure_ascii=False),
                    colors=json.dumps(filters['colors'], ensure_ascii=False),
                    width=json.dumps(
                        filters['width'], ensure_ascii=False)).where(
                            sa.and_(
                                tbl_eventdashboard_filters.c.name ==
                                filters['name'],
                                tbl_eventdashboard_filters.c.author ==
                                jwtd['user_id'])))
                await conn.execute("commit")

        engine.close()
        return json_response({'result': True})
    except BaseException as e:
        request.app['eventdashboard_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #18
0
async def create_host_view(_, request):
    try:
        post_data = await request.json()
        token = request.headers.get('authorization', None).split()[1]
        jwtd = jwt.decode(token,
                          JWT_SECRET,
                          algorithms=[JWT_ALGORITHM],
                          options={'verify_exp': False})
        res = await create_host(post_data, jwtd,
                                request.app['monitoring_add_logger'])
        return json_response(res)
    except BaseException as e:
        request.app['monitoring_add_logger'].error(
            f'Error in app: {str(e)}, data {post_data}')
        return json_response({'result': False, 'text': str(e)})
예제 #19
0
async def get_select(request):
    try:
        params = await get_showed_zabbix()
        dict_params = {}
        for arr in params:
            dict_params[arr[0]] = {
                'url': arr[1],
                'name': arr[2],
                'search_url': arr[3],
                'zabbixType': arr[4]
            }
        return json_response({'result': True, 'params': dict_params})
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})
예제 #20
0
async def add_maintenance_expert(request):
    post_data = await request.json()
    token = request.headers.get('authorization', None).split()[1]
    jwtd = jwt.decode(token,
                      JWT_SECRET,
                      algorithms=[JWT_ALGORITHM],
                      options={'verify_exp': False})
    try:
        zapi = await async_zabbix_conn(post_data['source'], 'net')
        if post_data['value']['mode'] == 'host':
            res = await zapi.host.get(
                output=['hostid'],
                filter={'name': post_data['value']['value']},
                limit=30)
            objid = [host['hostid'] for host in res]
            objkey = 'hostids'
            mode_str = '_h'
        else:
            res = await zapi.hostgroup.get(
                output=['groupid'],
                filter={'name': post_data['value']['value']},
                limit=30)
            objid = [host['groupid'] for host in res]
            objkey = 'groupids'
            mode_str = '_g'
        fromtime = int(post_data['value']['date'] / 1000)
        res = await zapi.maintenance.create(
            name=jwtd['user_id'] + mode_str + objid[0] + '_' + str(fromtime),
            **{objkey: objid},
            timeperiods=[{
                "timeperiod_type": 0,
                "start_date": fromtime,
                "period": post_data['value']['time']
            }],
            active_since=fromtime,
            active_till=fromtime + int(post_data['value']['time']),
            tags_evaltype=0
            if post_data['value']['tags_mode'] == 'And/Or' else 2,
            tags=post_data['value']['tags'],
            description=post_data['value']['description'])
        await zapi.close()
        request.app['maintenance_logger'].info(
            f"Created maintenance on {post_data['source']} by {jwtd['user_id']} for object {mode_str + objid[0]} with period from {fromtime} for {int(post_data['value']['time'])} seconds"
        )
        return json_response({'result': True})
    except BaseException as e:
        request.app['maintenance_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #21
0
async def get_csv(request):
    post_data = await request.json()
    query_filter = post_data['params']['filter'] if post_data['params'][
        'filter'] else ''
    if query_filter:
        for key in column_mapping:
            query_filter = query_filter.replace(f"'{key}'",
                                                column_mapping[key].lower())
            query_filter = query_filter.replace(f"'{key.lower()}'",
                                                column_mapping[key].lower())
        query_filter = 'where ' + query_filter
    try:
        engine = await db_connect('configs')
        async with engine.acquire() as conn:
            res = await conn.execute(
                f"select * from configs.sm_report {query_filter}")
            result = await res.fetchall()
        engine.close()
        csv = 'CI;hostname;dnsname;IP;dnsdomain;OS;env;admingroup;zabbix\n'
        for line in result:
            csv += ';'.join(line.as_tuple()) + '\n'
        resp = web.Response(
            body=csv,
            headers=aiohttp.multipart.CIMultiDict({
                'CONTENT-DISPOSITION':
                'attachment; filename:"sm_report_%s"' %
                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }))
        resp.content_type = 'text/csv'
        return resp
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})
예제 #22
0
async def update_user(request):
    post_data = await request.json()
    row = post_data['row']
    try:
        engine = await db_connect()
        async with engine.acquire() as conn:
            await conn.execute(
                tbl_users.update().values(groups=row['groups'],
                                          enable=row['enable']).where(tbl_users.c.login == row['login'].lower()))
            await conn.execute("commit")

        engine.close()
        return json_response({'result': 'True'})
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})
예제 #23
0
async def delete_filter(request):
    try:
        post_data = await request.json()
        author, name = post_data['key'].split(':')
        engine = await db_connect('configs')
        async with engine.acquire() as conn:
            await conn.execute(tbl_eventdashboard_filters.delete().where(
                sa.and_(tbl_eventdashboard_filters.c.name == name,
                        tbl_eventdashboard_filters.c.author == author)))
            await conn.execute("commit")
        engine.close()

        return json_response({'result': True})
    except BaseException as e:
        request.app['eventdashboard_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})
예제 #24
0
async def get_user_list(request):
    engine = await db_connect()
    async with engine.acquire() as conn:
        res = await conn.execute(tbl_users.select())
        result = await res.fetchall()
    engine.close()
    return json_response({'result': 'True','rows': [dict(r) for r in result]})
예제 #25
0
async def refresht(request):
    post_data = await request.json()
    try:
        jwtd = jwt.decode(post_data['token'], JWT_SECRET,
                                         algorithms=[JWT_ALGORITHM],options={'verify_exp': False})
        engine = await db_connect()
        async with engine.acquire() as conn:
            res = await conn.execute(tbl_users.select().where(tbl_users.c.login == jwtd['user_id']))
            result = await res.fetchone()
        engine.close()
        if (jwtd['exp'] < jwtd['orig_iat']) and (get_role(request.app['app_config'],result[6]) == jwtd['role']) and (result[7] == True):
            jwtd['exp'] = int(time.time()) + JWT_EXP_DELTA_SECONDS
            jwt_token = jwt.encode(jwtd, JWT_SECRET, JWT_ALGORITHM)
            return json_response({'token': jwt_token.decode('utf-8')})
    except Exception as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False}, status=400)
예제 #26
0
async def get_time(request):
    try:
        engine = await db_connect('configs')
        async with engine.acquire() as conn:
            res_time = await conn.execute(
                "select time from report_date where reportname='sm_report'")
            time = await res_time.fetchall()
            time = time[0][0]
            if time > datetime.datetime.now() - datetime.timedelta(days=1):
                color = 'green'
            else:
                color = 'red'
            time = datetime.datetime.strftime(time, '%Y-%m-%d %H:%M:%S')
        return json_response({'result': 'True', 'time': time, 'color': color})
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})
예제 #27
0
async def delete_maintenance(request):
    post_data = await request.json()
    token = request.headers.get('authorization', None).split()[1]
    jwtd = jwt.decode(token,
                      JWT_SECRET,
                      algorithms=[JWT_ALGORITHM],
                      options={'verify_exp': False})
    try:
        zapi = await async_zabbix_conn(post_data['source'], 'net')
        await zapi.maintenance.delete(post_data['data']['maintenanceid'])
        await zapi.close()
        request.app['maintenance_logger'].info(
            f"Deleted maintenance on {post_data['source']} by {jwtd['user_id']} with name {post_data['data']['name']}"
        )
        return json_response({'result': True})
    except BaseException as e:
        request.app['maintenance_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #28
0
async def get_data(request):
    post_data = await request.json()
    page_length = int(post_data['params']['page_length']
                      ) if post_data['params']['page_length'] else 10
    page_number = int(post_data['params']['page_number']
                      ) if post_data['params']['page_number'] > 0 else 1
    query_filter = post_data['params']['filter'] if post_data['params'][
        'filter'] else ''
    if query_filter:
        for key in column_mapping:
            query_filter = query_filter.replace(f"'{key}'",
                                                column_mapping[key].lower())
            query_filter = query_filter.replace(f"'{key.lower()}'",
                                                column_mapping[key].lower())
        query_filter = 'where ' + query_filter
    try:
        engine = await db_connect('configs')
        async with engine.acquire() as conn:
            res_count = await conn.execute(
                f'select count(*) from configs.sm_report {query_filter}')
            result_count = await res_count.fetchall()
            result_count = result_count[0][0]
            result_count = result_count if result_count > 0 else 1
            res = await conn.execute(
                f"select * from configs.sm_report {query_filter} limit {(page_number-1) * page_length},{page_length}"
            )
            columns = [column[0] for column in res.cursor.description]
            result = await res.fetchall()
        engine.close()
        result_temp = []
        for index in range(len(result)):
            tmp_dict = {}
            for col_index in range(len(columns)):
                tmp_dict[columns[col_index]] = result[index][col_index]
            result_temp.append(tmp_dict)
        return json_response({
            'result': 'True',
            'rows': result_temp,
            'pages': result_count
        })
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'rows': [], 'pages': 1})
예제 #29
0
async def get_maintenance(request):
    post_data = await request.json()
    try:
        zapi = await async_zabbix_conn(post_data['source'], 'net')
        if post_data['type'] == 'host':
            host = await zapi.host.get(output=['host', 'hostid'],
                                       selectGroups=['groupid'],
                                       filter={'name': post_data['value']},
                                       limit=1)
            host_grps = [group['groupid'] for group in host[0]['groups']]
            maintenances = await zapi.maintenance.get(
                hostids=host[0]['hostid'],
                groupids=host_grps,
                selectTags='extend',
                selectHosts=['host', 'name'],
                selectGroups=['name'],
                selectTimeperiods='extend',
                limit=30)
            maintenances = [
                maintenance for maintenance in maintenances
                if int(maintenance['active_till']) > int(time.time())
            ]
        else:
            grp = await zapi.hostgroup.get(output=['groupid'],
                                           filter={'name': post_data['value']},
                                           limit=1)
            maintenances = await zapi.maintenance.get(
                groupids=grp[0]['groupid'],
                selectTags='extend',
                selectHosts=['host', 'name'],
                selectGroups=['name'],
                selectTimeperiods='extend',
                limit=30)
            maintenances = [
                maintenance for maintenance in maintenances
                if int(maintenance['active_till']) > int(time.time())
            ]
        await zapi.close()
        return json_response({'result': True, 'maintenances': maintenances})
    except BaseException as e:
        request.app['maintenance_logger'].error(f'Error in app: {str(e)}')
        return json_response({'result': False, 'text': str(e)})
예제 #30
0
async def check_stand(request):
    try:
        post_data = await request.json()
        # source = post_data['source']
        ZabbixConfig = await get_zabbix_conf()
        engine = await db_connect('configs')
        async with engine.acquire() as conn:
            res = await conn.execute(
                f"select * from configs.databases where name='ORACLESM'")
            db_config = await res.fetchall()
        engine.close()
        db_config = db_config[0].as_tuple()
        func_for_execute = partial(getsearch, post_data['query'], ZabbixConfig,
                                   post_data['source'], db_config)
        search_result = await asyncio.get_event_loop().run_in_executor(
            None, func_for_execute)
        return json_response({'result': True, 'rows': search_result})
    except BaseException as e:
        request.app['app_logger'].error(f'Error in app: {str(e)}')
    return json_response({'result': False})