Exemple #1
0
async def instance(api, args):
    pp = pprint.PrettyPrinter(indent=2, compact=True, width=60)

    if not check_subcommand(args.action, ACTIONS): return

    available, _ = check_args(vars(args), ACTIONS[args.action])
    if not available: return

    if args.action == 'help':
        pp.pprint(HELP)
        return

    if args.action == 'create':

        data_post = {
            "name": args.instance_name,
            "service": None if args.iservice_id == 0 else args.iservice_id,
            "host": None if args.ihost_id == 0 else args.ihost_id,
            "database": args.idatabase,
            "private_ip": args.iprivate_ip
        }

        if args.json:
            print(json.dumps(data_post))

        response = None
        try:
            response = await api.post_json('/api/cmdb/instance/', data_post)
            pp.pprint(response)
        except aiohttp.client_exceptions.ClientConnectorError:
            print('ops, API offline ou você não tem conexão com a internet...')

        return True if isinstance(response, dict) else False

    elif args.action == 'list':
        response = await api.get_json('/api/cmdb/instance/')
        [pp.pprint(_) for _ in response] if isinstance(
            response, list) else pp.pprint(response)

    elif args.action == 'update':
        instance = await api.get_json('/api/cmdb/instance/%s/' %
                                      args.instanceid)
        print('change %s=%s to %s=%s' %
              (args.key, instance[args.key], args.key, args.value))
        icontinue = input('Tem certeza que deseja continuar? (Y/n) ') or 'Y'
        if icontinue != 'Y':
            return False

        instance.update({args.key: int(args.value)})

        response = None
        try:
            response = await api.put_json(
                '/api/cmdb/instance/%s/' % args.instanceid, instance)
            pp.pprint(response)
        except aiohttp.client_exceptions.ClientConnectorError:
            print('ops, API offline ou você não tem conexão com a internet...')
        return True if isinstance(response, dict) else False

    return True
async def environment(api, args):
    pp = pprint.PrettyPrinter(indent=2, compact=True, width=60)

    if not check_subcommand(args.action, ACTIONS): return

    available, _ = check_args(vars(args), ACTIONS[args.action])
    if not available: return

    if args.action == 'help':
        pp.pprint(HELP)
        return

    if args.action == 'create':

        data_post = {"name": args.env_name, "inventory": args.inventoryid}

        if args.json:
            print(json.dumps(data_post))

        response = None
        try:
            response = await api.post_json('/api/cmdb/environment/', data_post)
            pp.pprint(response)
        except aiohttp.client_exceptions.ClientConnectorError:
            print('ops, API offline ou você não tem conexão com a internet...')

        return True if isinstance(response, dict) else False

    elif args.action == 'list':
        response = await api.get_json('/api/cmdb/environment/')
        [pp.pprint(_) for _ in response] if isinstance(
            response, list) else pp.pprint(response)

    return True
async def host(api, args):
    pp = pprint.PrettyPrinter(indent=2, compact=True, width=71)

    if not check_subcommand(args.action, ACTIONS): return

    available, _ = check_args(vars(args), ACTIONS[args.action])
    if not available: return

    if args.action == 'help':
        pp.pprint(HELP)
        return

    if args.action == 'create':
        data_post = get_machine_infos()
        data_post['enterprise'] = args.inventory

        if args.json:
            print(json.dumps(data_post))

        response = None
        try:
            response = await api.post_json('/api/cmdb/host/', data_post)
            pp.pprint(response)
        except aiohttp.client_exceptions.ClientConnectorError:
            print('ops, API offline ou você não tem conexão com a internet...')
        return True if isinstance(response, dict) else False

    elif args.action == 'list':
        response = await api.get_json('/api/cmdb/host/')
        [pp.pprint(_) for _ in response] if isinstance(
            response, list) else pp.pprint(response)

    elif args.action == 'update':
        host = await api.get_json('/api/cmdb/host/%s/' % args.hostid)
        print('change %s=%s to %s=%s' %
              (args.key, host[args.key], args.key, args.value))
        icontinue = input('Tem certeza que deseja continuar? (Y/n) ') or 'Y'
        if icontinue != 'Y':
            return False

        host.update({args.key: int(args.value)})

        response = None
        try:
            response = await api.put_json('/api/cmdb/host/%s/' % args.hostid,
                                          host)
            pp.pprint(response)
        except aiohttp.client_exceptions.ClientConnectorError:
            print('ops, API offline ou você não tem conexão com a internet...')
        return True if isinstance(response, dict) else False

    return True
Exemple #4
0
async def charts(api, args):
    pp = pprint.PrettyPrinter(indent=2, compact=True, width=71)

    if args.action == 'help':
        console = Console()
        with open(Path(__file__).parent.joinpath('../', '../', 'resources', 'CHARTS_HELP.md'), encoding="utf-8") as readme:
            markdown = Markdown(readme.read())
        console.print(markdown)
        return


    if not check_subcommand(args.action, ACTIONS): return

    available, _ = check_args(vars(args), ACTIONS[args.action])
    if not available: return
    
    if args.action == 'help':
        pp.pprint(HELP)
        return
    
    if args.action == 'create':

        step_uid = str(uuid.uuid4()).split('-')[1]
        step_name = args.chart_name[:10].replace(' ', '_')

        strf = '-'.join('%'+i for i in args.format.split('-'))
        if ' ' in strf:
            day, hour = strf.split(' ')
            nhour = ':'.join('%'+i for i in hour.split(':'))
            strf = ' '.join([day, nhour])

        re_data = re.compile(r'^%m')
        if re_data.match(strf):
            strf = '%Y-'+strf

        chart_json_data = {
            "client": args.clientid,
            "uid": '%s_%s' % (step_uid, step_name),
            "caption_text": args.title,
            "yAxis_plot_value": args.plot_value,
            "yAxis_plot_type": args.yAxis_plot_type,
            "yAxis_title": args.chart_name,
            "yAxis_format_prefix": args.prefix,
            "max_height": args.max_height,
            "max_width": args.max_width,
            "schema": '[{"name":"Time","type":"date","format":"%s"},{"name":"%s","type":"%s"}]' % \
                (strf, args.about, args.type_data),
            "columns": args.columns
        }

        pp.pprint(chart_json_data)
        continue_post = input('\nAs informações estão corretas? (Y/n) ') or 'Y'

        response = None
        if continue_post == 'Y':
            try:
                response = await api.post_json('/api/charts/charts/', chart_json_data)
                pp.pprint(response)
            except aiohttp.client_exceptions.ClientConnectorError:
                print('ops, API offline ou você não tem conexão com a internet...')

        return True if isinstance(response, dict) else False
    
    elif args.action == 'put':
        if (not args.file_with_data) and (not args.new_value):
            print('Você deve utilizar a opção --value ou --file com os dados.')
            return False

        re_data = re.compile(r'\d{4}-\d{1,2}-\d{1,2}')

        if args.new_value:
            for rexp in reXP:
                raw_data = re.findall(rexp, args.new_value)
                if raw_data: break
        else:
            path = Path(args.file_with_data)
            for rexp in reXP:
                raw_data = re.findall(rexp, open(path).read())
                if raw_data: break

        pp = pprint.PrettyPrinter(indent=2, compact=False)
        again = '[!] falha ao enviar valor %s, deseja tentar novamente ou continuar? (T)ry / (C)ontinue '

        try:
            chart_filter = {'value': int(args.chartid_to_put), 'key': 'chartid'}
        except ValueError:
            chart_filter = {'key': 'chartuid', 'value': args.chartid_to_put}

        if args.fix_index == 0:
            response = await api.get_json('/api/charts/data/filter/', [(chart_filter.get('key'), chart_filter.get('value'))])

            index = response[-1].get('index') + 1 if response else  0
            # if response:
            #    index = response[-1].get('index') + 1
            # else:
            #    index = 1
        else:
            index = args.fix_index

        failed = set()

        async def send_data(data):
            response = await api.post_json('/api/charts/data/', data)
            if response:
                return True
            else:
                failed.add(json.dumps(data))

        """
        async def try_again(response):
            if response:
                return
            choice = input(again % data) or 'T'
            if choice.lower() == 'c':
                failed.add(json.dumps(data_json))
                return
            response = await send_data('/api/charts/data/', data_json)
            return await try_again(response)
        """
        funcs = []

        for data in raw_data:
            if not re_data.match(data):
                # mudar para pegar ano atual
                data = '2020-'+data
            data_json = {
                "index": index,
                "value": data,
                "chart": int(args.chartid_to_put)
            }
            # response = await send_data('/api/charts/data/', data_json)
            # funcs.append(partial(send_data, data=data_json))
            funcs.append(data_json)

            # await try_again(response)s
            index += 1

        # print(tuple(funcs))
        # await asyncio.gather(
        #     *tuple(funcs)
        # )
        # completed, pending = await asyncio.wait(funcs)
        # loop = asyncio.get_event_loop()

        # for data in funcs:
        #     loop.create_task(send_data(data))

        # pending = asyncio.all_tasks()
        # group = asyncio.gather(*pending, return_exceptions=True)
        # results = loop.run_until_complete(group)
        MAX_CONN = 10

        def chunks(lista, n):
            for i in range(0, len(lista), n):
                yield lista[i:i + n]

        for raw_data in list(chunks(funcs, MAX_CONN)):
            coroutines = [send_data(data) for data in raw_data]
            completed, pending = await asyncio.wait(coroutines)

            for item in completed:
                pass

        if failed:
            coroutines = [send_data(json.loads(data)) for data in failed]
            completed, pending = await asyncio.wait(coroutines)
        else:
            print('[+] dados enviado com sucesso!')

    elif args.action == 'list':
        response = await api.get_json('/api/charts/charts/')
        [pp.pprint(_) for _ in response] if isinstance(response, list) else pp.pprint(response)

    return True