Exemplo n.º 1
0
def pool_datatable(request, id_vip):

    try:

        auth = AuthSession(request.session)
        client = auth.get_clientFactory()

        column_index_name_map = {
            0: 'identifier',
            1: 'default_port',
            2: 'healthcheck__healthcheck_type',
            3: 'environment',
            4: 'pool_created',
            5: ''
        }

        dtp = DataTablePaginator(request, column_index_name_map)

        dtp.build_server_side_list()

        dtp.searchable_columns = [
            'identifier',
            'default_port',
            'pool_created',
            'healthcheck__healthcheck_type',
        ]

        pagination = Pagination(
            dtp.start_record,
            dtp.end_record,
            dtp.asorting_cols,
            dtp.searchable_columns,
            dtp.custom_search
        )

        pools = client.create_pool().list_all_by_reqvip(id_vip, pagination)

        return dtp.build_response(
            pools["pools"],
            pools["total"],
            templates.VIPREQUEST_POOL_DATATABLE,
            request
        )

    except NetworkAPIClientError, e:
        logger.error(e.error)
        return render_message_json(e.error, messages.ERROR)
Exemplo n.º 2
0
def list_all(request):
    try:

        lists = dict()
        lists['form'] = DeleteForm()

        auth = AuthSession(request.session)
        client = auth.get_clientFactory()

        column_index_name_map = {
            0: '',
            1: 'id',
            2: 'divisao_dc__nome',
            3: 'vrf',
            4: 'dcroom__dc__dcname',
            5: ''
        }

        dtp = DataTablePaginator(request, column_index_name_map)

        dtp.build_server_side_list()

        dtp.searchable_columns = [
            'grupo_l3__nome', 'ambiente_logico__nome', 'divisao_dc__nome',
            'vrf', 'dcroom__dc__dcname', 'dcroom__name'
        ]

        dtp.end_record = 10000

        pagination = Pagination(dtp.start_record, dtp.end_record,
                                dtp.asorting_cols, dtp.searchable_columns,
                                dtp.custom_search)

        extends_search = dict()
        extends_search["father_environment__isnull"] = True

        data = dict()
        data["start_record"] = pagination.start_record
        data["end_record"] = pagination.end_record
        data["asorting_cols"] = [
            'divisao_dc__nome', 'ambiente_logico__nome', 'grupo_l3__nome'
        ]
        data["searchable_columns"] = pagination.searchable_columns
        data["custom_search"] = pagination.custom_search or ""
        data["extends_search"] = [extends_search] if extends_search else []

        environment = client.create_api_environment().search(fields=[
            'id', 'children__basic', 'vrf', 'name', 'configs__details',
            'dcroom__details'
        ],
                                                             search=data)

        lists['envs'] = json.dumps(environment.get("environments"))

    except NetworkAPIClientError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
Exemplo n.º 3
0
def pool_datatable(request, id_vip):

    try:

        auth = AuthSession(request.session)
        client = auth.get_clientFactory()

        column_index_name_map = {
            0: 'identifier',
            1: 'default_port',
            2: 'healthcheck__healthcheck_type',
            3: 'environment',
            4: 'pool_created',
            5: ''
        }

        dtp = DataTablePaginator(request, column_index_name_map)

        dtp.build_server_side_list()

        dtp.searchable_columns = [
            'identifier',
            'default_port',
            'pool_created',
            'healthcheck__healthcheck_type',
        ]

        pagination = Pagination(dtp.start_record, dtp.end_record,
                                dtp.asorting_cols, dtp.searchable_columns,
                                dtp.custom_search)

        pools = client.create_pool().list_all_by_reqvip(id_vip, pagination)

        return dtp.build_response(pools["pools"], pools["total"],
                                  templates.VIPREQUEST_POOL_DATATABLE, request)

    except NetworkAPIClientError, e:
        logger.error(e.error)
        return render_message_json(e.error, messages.ERROR)
Exemplo n.º 4
0
def ajax_get_individual_permissions(request, id_ugroup, id_type_obj):

    try:
        # If form was submited
        if request.method == "GET":

            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            column_index_name_map = {
                0: '',
                1: 'id',
                2: 'read',
                3: 'write',
                4: 'change_config',
                5: 'delete',
                6: ''
            }

            dtp = DataTablePaginator(request, column_index_name_map)

            # Make params
            dtp.build_server_side_list()

            # Set params in simple Pagination class
            pagination = Pagination(
                dtp.start_record,
                dtp.end_record,
                dtp.asorting_cols,
                dtp.searchable_columns,
                dtp.custom_search)

            data_search = {
                'start_record': pagination.start_record,
                'end_record': pagination.end_record,
                'asorting_cols': pagination.asorting_cols,
                'searchable_columns': pagination.searchable_columns,
                'custom_search': pagination.custom_search,
                'extends_search': [{
                    'user_group': int(id_ugroup),
                    'object_type': int(id_type_obj)
                }]
            }

            kind = ['basic']
            fields = ['id', 'read', 'write', 'change_config', 'delete',
                      'object_value']

            perms = client. \
                create_api_object_group_permission(). \
                search(search=data_search, kind=kind, fields=fields)
            lists = dict()
            lists['id_ugroup'] = id_ugroup
            lists['id_type_obj'] = id_type_obj
            lists['type_obj'] = client.create_api_object_type().get(
                [id_type_obj])['ots'][0]['name']

            # Returns JSON
            return dtp.build_response(
                perms['ogps'],
                perms['total'],
                USERGROUP_AJAX_INDIVIDUAL_PERMISSIONS,
                request,
                lists
            )

    except NetworkAPIClientError, error:
        logger.error(error)
        return HttpResponseServerError(error, mimetype='application/javascript')
Exemplo n.º 5
0
def ajax_list_all(request, search_term=None):
    try:

        lists = dict()
        lists['form'] = DeleteForm()

        auth = AuthSession(request.session)
        client = auth.get_clientFactory()

        column_index_name_map = {
            0: '',
            1: 'id',
            2: 'divisao_dc__nome',
            3: 'vrf',
            4: 'dcroom__dc__dcname',
            5: ''
        }

        dtp = DataTablePaginator(request, column_index_name_map)

        dtp.build_server_side_list()

        dtp.searchable_columns = [
            'grupo_l3__nome',
            'ambiente_logico__nome',
            'divisao_dc__nome',
            'vrf',
            'dcroom__dc__dcname',
            'dcroom__name'
        ]

        dtp.end_record = 10000

        fields = [
            "divisao_dc__nome__icontains",
            "ambiente_logico__nome__icontains",
            "grupo_l3__nome__icontains"
        ]

        extends_search_dict = dict()

        if search_term:
            term = search_term.split("+")
            term_len = len(term)
            if term_len > 1:
                for i in xrange(len(term)):
                    extends_search_dict.update({fields[i]: term[i]})
            else:
                dtp.custom_search = term[0]

        pagination = Pagination(
            dtp.start_record,
            dtp.end_record,
            dtp.asorting_cols,
            dtp.searchable_columns,
            dtp.custom_search
        )

        data = dict()
        data["start_record"] = pagination.start_record
        data["end_record"] = pagination.end_record
        data["asorting_cols"] = ['divisao_dc__nome','ambiente_logico__nome','grupo_l3__nome']
        data["searchable_columns"] = pagination.searchable_columns
        data["custom_search"] = pagination.custom_search or ""
        data["extends_search"] = [extends_search_dict] if extends_search_dict else []

        environment = client.create_api_environment().search(fields=['id',
                                                                     'children__basic',
                                                                     'vrf',
                                                                     'name',
                                                                     'configs__details',
                                                                     'dcroom__details'],
                                                             search=data)

        lists['envs'] = json.dumps(environment.get("environments"))

        return render_to_response(ENVIRONMENT_LIST, lists, context_instance=RequestContext(request))

    except NetworkAPIClientError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
Exemplo n.º 6
0
def ajax_list_logs(request):
    try:

        # If form was submited
        if request.method == 'GET':

            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            # Pagination
            columnIndexNameMap = {0: '', 1: '', 2: '', 3: '', 4: '', 5: ''}
            dtp = DataTablePaginator(request, columnIndexNameMap)

            # Make params
            dtp.build_server_side_list()

            # Set params in simple Pagination class
            pag = Pagination(dtp.start_record, dtp.end_record,
                             dtp.asorting_cols, dtp.searchable_columns, dtp.custom_search)

            user_name = ''
            first_date = ''
            start_time = ''
            last_date = ''
            end_time = ''
            action = ''
            functionality = ''
            parameter = ''

            choices_map = client.create_log().get_choices()
            usuarios = choices_map['usuario']
            acoes = choices_map['acao']
            funcionalidades = choices_map['funcionalidade']

            search_form = SearchFormLog(
                usuarios, acoes, funcionalidades, request.GET)
            if search_form.is_valid():
                user_name = search_form.cleaned_data['user']
                first_date = search_form.cleaned_data['first_date']
                start_time = search_form.cleaned_data['start_time']
                last_date = search_form.cleaned_data['last_date']
                end_time = search_form.cleaned_data['end_time']
                action = search_form.cleaned_data['action']
                functionality = search_form.cleaned_data['functionality']
                parameter = search_form.cleaned_data['parameter']

            else:
                # Remake search form
                lists = dict()
                lists["search_form"] = search_form

                # Returns HTML
                response = HttpResponse(loader.render_to_string(
                    SEARCH_FORM_ERRORS, lists, context_instance=RequestContext(request)))
                # Send response status with error
                response.status_code = 412
                return response

            # Call API passing all params
            logs = client.create_log().find_logs(user_name, first_date, start_time,
                                                 last_date, end_time, action, functionality, parameter, pag)

            if not logs.has_key("eventlog"):
                logs["eventlog"] = []

            # Returns JSON
            return dtp.build_response(logs["eventlog"], logs["total"], AJAX_LOG_LIST, request)

    except NetworkAPIClientError, e:
        logger.error(e)
        return HttpResponseServerError(e, mimetype='application/javascript')
Exemplo n.º 7
0
def ajax_list_all(request, search_term=None):
    try:

        lists = dict()
        lists['form'] = DeleteForm()

        auth = AuthSession(request.session)
        client = auth.get_clientFactory()

        column_index_name_map = {
            0: '',
            1: 'id',
            2: 'divisao_dc__nome',
            3: 'vrf',
            4: 'dcroom__dc__dcname',
            5: ''
        }

        dtp = DataTablePaginator(request, column_index_name_map)

        dtp.build_server_side_list()

        dtp.searchable_columns = [
            'grupo_l3__nome',
            'ambiente_logico__nome',
            'divisao_dc__nome',
            'vrf',
            'dcroom__dc__dcname',
            'dcroom__name'
        ]

        dtp.end_record = 10000

        fields = [
            "divisao_dc__nome__icontains",
            "ambiente_logico__nome__icontains",
            "grupo_l3__nome__icontains"
        ]

        extends_search_dict = dict()

        if search_term:
            term = search_term.split("+")
            term_len = len(term)
            if term_len > 1:
                for i in xrange(len(term)):
                    extends_search_dict.update({fields[i]: term[i]})
            else:
                dtp.custom_search = term[0]

        pagination = Pagination(
            dtp.start_record,
            dtp.end_record,
            dtp.asorting_cols,
            dtp.searchable_columns,
            dtp.custom_search
        )

        data = dict()
        data["start_record"] = pagination.start_record
        data["end_record"] = pagination.end_record
        data["asorting_cols"] = ['divisao_dc__nome','ambiente_logico__nome','grupo_l3__nome']
        data["searchable_columns"] = pagination.searchable_columns
        data["custom_search"] = pagination.custom_search or ""
        data["extends_search"] = [extends_search_dict] if extends_search_dict else []

        environment = client.create_api_environment().search(fields=['id',
                                                                     'children__basic',
                                                                     'vrf',
                                                                     'name',
                                                                     'configs__details',
                                                                     'dcroom__details'],
                                                             search=data)

        lists['envs'] = json.dumps(environment.get("environments"))

        return render_to_response(ENVIRONMENT_LIST, lists, context_instance=RequestContext(request))

    except NetworkAPIClientError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
Exemplo n.º 8
0
def list_all(request):
    try:

        lists = dict()
        lists['form'] = DeleteForm()

        auth = AuthSession(request.session)
        client = auth.get_clientFactory()

        column_index_name_map = {
            0: '',
            1: 'id',
            2: 'divisao_dc__nome',
            3: 'vrf',
            4: 'dcroom__dc__dcname',
            5: ''
        }

        dtp = DataTablePaginator(request, column_index_name_map)

        dtp.build_server_side_list()

        dtp.searchable_columns = [
            'grupo_l3__nome',
            'ambiente_logico__nome',
            'divisao_dc__nome',
            'vrf',
            'dcroom__dc__dcname',
            'dcroom__name'
        ]

        dtp.end_record = 10000

        pagination = Pagination(
            dtp.start_record,
            dtp.end_record,
            dtp.asorting_cols,
            dtp.searchable_columns,
            dtp.custom_search
        )

        extends_search = dict()
        extends_search["father_environment__isnull"] = True

        data = dict()
        data["start_record"] = pagination.start_record
        data["end_record"] = pagination.end_record
        data["asorting_cols"] = ['divisao_dc__nome','ambiente_logico__nome','grupo_l3__nome']
        data["searchable_columns"] = pagination.searchable_columns
        data["custom_search"] = pagination.custom_search or ""
        data["extends_search"] = [extends_search] if extends_search else []

        environment = client.create_api_environment().search(fields=['id',
                                                                     'children__basic',
                                                                     'vrf',
                                                                     'name',
                                                                     'configs__details',
                                                                     'dcroom__details'],
                                                             search=data)

        lists['envs'] = json.dumps(environment.get("environments"))

    except NetworkAPIClientError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
Exemplo n.º 9
0
def ajax_list_vlans(request, id_vlan="0", sf_number='0', sf_name='0', sf_environment='0', sf_nettype='0', sf_subnet='0', sf_ipversion='0', sf_network='0', sf_iexact='0', sf_acl='0'):

    try:

        # If form was submited
        if request.method == "GET":

            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            # Get all environments from NetworkAPI
            env_list = client.create_ambiente().list_all()
            # Get all network types from NetworkAPI
            net_list = client.create_tipo_rede().listar()

            search_form = SearchVlanForm(env_list, net_list, request.GET)

            if search_form.is_valid():
                number = search_form.cleaned_data["number"]
                name = search_form.cleaned_data["name"]
                iexact = search_form.cleaned_data["iexact"]
                environment = search_form.cleaned_data["environment"]
                net_type = search_form.cleaned_data["net_type"]
                ip_version = search_form.cleaned_data["ip_version"]
                networkv4 = search_form.cleaned_data["networkv4"]
                networkv6 = search_form.cleaned_data["networkv6"]
                subnet = search_form.cleaned_data["subnet"]
                acl = search_form.cleaned_data["acl"]

                if len(networkv4) > 0:
                    network = networkv4
                elif len(networkv6) > 0:
                    network = networkv6
                else:
                    network = None

                if id_vlan == '1':
                    if not sf_number == '0':
                        number = sf_number
                    if not sf_name == '0':
                        name = sf_name
                    if sf_iexact == '0':
                        sf_iexact = False
                    elif sf_iexact == '1':
                        sf_iexact = True
                    iexact = sf_iexact
                    if not sf_environment == '0':
                        environment = sf_environment
                    if not sf_nettype == '0':
                        net_type = sf_nettype
                    if not sf_ipversion == '0':
                        ip_version = sf_ipversion
                    if not sf_network == '0':
                        if (sf_network.count('_') == 4):  # ipv4
                            sf_network = sf_network.replace("_", ".", 3)
                        else:  # ipv6
                            sf_network = sf_network.replace("_", ":", 7)
                        sf_network = sf_network.replace("_", "/")
                        network = sf_network
                    if not sf_subnet == '0':
                        subnet = sf_subnet
                    if sf_acl == '0':
                        sf_acl = False
                    elif sf_acl == '1':
                        sf_acl = True
                    acl = search_form.cleaned_data["acl"]

                if environment == "0":
                    environment = None
                if net_type == "0":
                    net_type = None

                # Pagination
                columnIndexNameMap = {0: '', 1: '', 2: 'num_vlan', 3: 'nome', 4: 'ambiente',
                                      5: 'tipo_rede', 6: 'network', 7: '', 8: 'acl_file_name', 9: 'acl_file_name_v6'}
                dtp = DataTablePaginator(request, columnIndexNameMap)

                # Make params
                dtp.build_server_side_list()

                # Set params in simple Pagination class
                pag = Pagination(dtp.start_record, dtp.end_record,
                                 dtp.asorting_cols, dtp.searchable_columns, dtp.custom_search)
                '', False, None, None, None, 2, 0, False
                # Call API passing all params
                vlans = client.create_vlan().find_vlans(
                    number, name, iexact, environment, net_type, network, ip_version, subnet, acl, pag)

                if "vlan" not in vlans:
                    vlans["vlan"] = []

                request_var = dict()

                if number is None:
                    number = '0'
                request_var["number"] = number
                if name == '':
                    name = '0'
                request_var["name"] = name
                if environment is None:
                    environment = '0'
                request_var["environment"] = environment
                if net_type is None:
                    net_type = '0'
                request_var["nettype"] = net_type
                if subnet is None:
                    subnet = '0'
                request_var["subnet"] = subnet
                if ip_version is None:
                    ip_version = '0'
                request_var["ipversion"] = ip_version
                if network is None:
                    network = '0'
                else:
                    network = network.replace(".", "_")
                    network = network.replace(":", "_")
                    network = network.replace("/", "_")
                request_var["network"] = network
                if iexact is False:
                    iexact = '0'
                elif iexact is True:
                    iexact = '1'
                request_var["iexact"] = iexact
                if acl is False:
                    acl = '0'
                elif acl is True:
                    acl = '1'
                request_var["acl"] = acl

                # Returns JSON
                return dtp.build_response(vlans["vlan"], vlans["total"], AJAX_VLAN_LIST, request, request_var)

            else:
                # Remake search form
                lists = dict()
                lists["search_form"] = search_form

                # Returns HTML
                response = HttpResponse(loader.render_to_string(
                    SEARCH_FORM_ERRORS, lists, context_instance=RequestContext(request)))
                # Send response status with error
                response.status_code = 412
                return response

    except NetworkAPIClientError, e:
        logger.error(e)
        return HttpResponseServerError(e, mimetype='application/javascript')
Exemplo n.º 10
0
def ajax_list_logs(request):
    try:

        # If form was submited
        if request.method == 'GET':

            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            # Pagination
            columnIndexNameMap = {0: '', 1: '', 2: '', 3: '', 4: '', 5: ''}
            dtp = DataTablePaginator(request, columnIndexNameMap)

            # Make params
            dtp.build_server_side_list()

            # Set params in simple Pagination class
            pag = Pagination(dtp.start_record, dtp.end_record,
                             dtp.asorting_cols, dtp.searchable_columns,
                             dtp.custom_search)

            user_name = ''
            first_date = ''
            start_time = ''
            last_date = ''
            end_time = ''
            action = ''
            functionality = ''
            parameter = ''

            choices_map = client.create_log().get_choices()
            usuarios = choices_map['usuario']
            acoes = choices_map['acao']
            funcionalidades = choices_map['funcionalidade']

            search_form = SearchFormLog(usuarios, acoes, funcionalidades,
                                        request.GET)
            if search_form.is_valid():
                user_name = search_form.cleaned_data['user']
                first_date = search_form.cleaned_data['first_date']
                start_time = search_form.cleaned_data['start_time']
                last_date = search_form.cleaned_data['last_date']
                end_time = search_form.cleaned_data['end_time']
                action = search_form.cleaned_data['action']
                functionality = search_form.cleaned_data['functionality']
                parameter = search_form.cleaned_data['parameter']

            else:
                # Remake search form
                lists = dict()
                lists["search_form"] = search_form

                # Returns HTML
                response = HttpResponse(
                    loader.render_to_string(
                        SEARCH_FORM_ERRORS,
                        lists,
                        context_instance=RequestContext(request)))
                # Send response status with error
                response.status_code = 412
                return response

            # Call API passing all params
            logs = client.create_log().find_logs(user_name, first_date,
                                                 start_time, last_date,
                                                 end_time, action,
                                                 functionality, parameter, pag)

            if not logs.has_key("eventlog"):
                logs["eventlog"] = []

            # Returns JSON
            return dtp.build_response(logs["eventlog"], logs["total"],
                                      AJAX_LOG_LIST, request)

    except NetworkAPIClientError, e:
        logger.error(e)
        return HttpResponseServerError(e, mimetype='application/javascript')
Exemplo n.º 11
0
def ajax_list_equips(request):

    try:

        # If form was submited
        if request.method == 'GET':
            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            # Get all environments from NetworkAPI
            env_list = client.create_ambiente().list_all()
            # Get all equipment types from NetworkAPI
            type_equip_list = client.create_tipo_equipamento().listar()
            # Get all groups from NetworkAPI
            group_list = client.create_grupo_equipamento().listar()

            search_form = SearchEquipmentForm(env_list, type_equip_list,
                                              group_list, request.GET)

            if search_form.is_valid():

                name = search_form.cleaned_data['name']
                iexact = search_form.cleaned_data['iexact']
                environment = search_form.cleaned_data['environment']
                equip_type = search_form.cleaned_data['type_equip']
                group = search_form.cleaned_data['group']
                ipv4 = search_form.cleaned_data['ipv4']
                ipv6 = search_form.cleaned_data['ipv6']

                if environment == '0':
                    environment = None
                if equip_type == '0':
                    equip_type = None
                if group == '0':
                    group = None

                if len(ipv4) > 0:
                    ip = ipv4
                elif len(ipv6) > 0:
                    ip = ipv6
                else:
                    ip = None

                # Pagination
                columnIndexNameMap = {
                    0: '',
                    1: 'nome',
                    2: 'tipo_equipamento',
                    3: 'grupos',
                    4: 'ip',
                    5: 'vlan',
                    6: 'ambiente',
                    7: ''
                }
                dtp = DataTablePaginator(request, columnIndexNameMap)

                # Make params
                dtp.build_server_side_list()

                # Set params in simple Pagination class
                pag = Pagination(dtp.start_record, dtp.end_record,
                                 dtp.asorting_cols, dtp.searchable_columns,
                                 dtp.custom_search)

                # Call API passing all params
                equips = client.create_equipamento().find_equips(
                    name, iexact, environment, equip_type, group, ip, pag)

                if 'equipamento' not in equips:
                    equips['equipamento'] = []

                # Returns JSON
                return dtp.build_response(equips['equipamento'],
                                          equips['total'], AJAX_EQUIP_LIST,
                                          request)

            else:
                # Remake search form
                lists = dict()
                lists['search_form'] = search_form

                # Returns HTML
                response = HttpResponse(
                    loader.render_to_string(
                        SEARCH_FORM_ERRORS,
                        lists,
                        context_instance=RequestContext(request)))
                # Send response status with error
                response.status_code = 412
                return response

    except NetworkAPIClientError, e:
        logger.error(e)
        return HttpResponseServerError(e, mimetype='application/javascript')
Exemplo n.º 12
0
def ajax_list_vips(request):
    '''
        Return list of vip request by search field
    '''

    try:

        # If form was submited
        if request.method == "GET":

            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            search_form = forms.SearchVipRequestForm(request.GET)

            if search_form.is_valid():

                id_vip = search_form.cleaned_data['id_request']
                ipv4 = search_form.cleaned_data["ipv4"]
                ipv6 = search_form.cleaned_data["ipv6"]
                vip_created = search_form.cleaned_data["vip_created"]
                vip_with_onwer = search_form.cleaned_data["vip_with_onwer"]
                hostname = search_form.cleaned_data["hostname"]

                extends_search = dict()
                if hostname:
                    extends_search.update(prepare_hostname(hostname))
                elif len(ipv4) > 0:
                    if request.GET["oct1"]:
                        extends_search.update({'ipv4__oct1': request.GET["oct1"]})
                    if request.GET["oct2"]:
                        extends_search.update({'ipv4__oct2': request.GET["oct2"]})
                    if request.GET["oct3"]:
                        extends_search.update({'ipv4__oct3': request.GET["oct3"]})
                    if request.GET["oct4"]:
                        extends_search.update({'ipv4__oct4': request.GET["oct4"]})
                elif len(ipv6) > 0:
                    if request.GET["oct1"]:
                        extends_search.update({'ipv6__block1__iexact': request.GET["oct1"]})
                    if request.GET["oct2"]:
                        extends_search.update({'ipv6__block2__iexact': request.GET["oct2"]})
                    if request.GET["oct3"]:
                        extends_search.update({'ipv6__block3__iexact': request.GET["oct3"]})
                    if request.GET["oct4"]:
                        extends_search.update({'ipv6__block4__iexact': request.GET["oct4"]})
                    if request.GET["oct5"]:
                        extends_search.update({'ipv6__block5__iexact': request.GET["oct5"]})
                    if request.GET["oct6"]:
                        extends_search.update({'ipv6__block6__iexact': request.GET["oct6"]})
                    if request.GET["oct7"]:
                        extends_search.update({'ipv6__block7__iexact': request.GET["oct7"]})
                    if request.GET["oct8"]:
                        extends_search.update({'ipv6__block8__iexact': request.GET["oct8"]})

                if vip_created:
                    extends_search.update({'created': vip_created})
                if id_vip:
                    extends_search.update({"id": id_vip})
                if vip_with_onwer:
                    user = auth.get_user().get_id()
                    extends_search.update({'viprequestgrouppermission__user_group__usuario': user})

                # Pagination
                column_index_name_map = {
                    0: '',
                    1: 'id',
                    2: 'ipv4',
                    4: 'description',
                    3: 'ipv6',
                    5: 'description',
                    6: 'equipamento',
                    7: 'ambiente',
                    8: 'criado',
                    9: ''}
                dtp = DataTablePaginator(request, column_index_name_map)

                # Make params
                dtp.build_server_side_list()

                # Set params in simple Pagination class
                pagination = Pagination(
                    dtp.start_record,
                    dtp.end_record,
                    dtp.asorting_cols,
                    dtp.searchable_columns,
                    dtp.custom_search)

                # Call API passing all params
                # vips = client.create_vip().list_vip_requests(
                #     id_vip, ip, pag, vip_create)

                data = dict()
                data["start_record"] = pagination.start_record
                data["end_record"] = pagination.end_record
                data["asorting_cols"] = pagination.asorting_cols
                data["searchable_columns"] = pagination.searchable_columns
                data["custom_search"] = pagination.custom_search or ""
                data["extends_search"] = [extends_search] if extends_search else []

                vips = client.create_api_vip_request().search(
                    search=data,
                    kind='details',
                    fields=['id', 'name', 'environmentvip', 'ipv4',
                            'ipv6', 'equipments', 'created'])

                # Returns JSON
                return dtp.build_response(
                    vips["vips"],
                    vips["total"],
                    templates.AJAX_VIPREQUEST_LIST,
                    request
                )

            else:
                # Remake search form
                lists = dict()
                lists["search_form"] = search_form

                # Returns HTML
                response = HttpResponse(
                    loader.render_to_string(
                        templates.SEARCH_FORM_ERRORS,
                        lists,
                        context_instance=RequestContext(request)
                    )
                )
                # Send response status with error
                response.status_code = 412
                return response

    except NetworkAPIClientError, error:
        logger.error(error)
        return HttpResponseServerError(error, mimetype='application/javascript')
Exemplo n.º 13
0
def ajax_list_vips(request):
    '''
        Return list of vip request by search field
    '''

    try:

        # If form was submited
        if request.method == "GET":

            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            search_form = forms.SearchVipRequestForm(request.GET)

            if search_form.is_valid():

                id_vip = search_form.cleaned_data['id_request']
                ipv4 = search_form.cleaned_data["ipv4"]
                ipv6 = search_form.cleaned_data["ipv6"]
                vip_created = search_form.cleaned_data["vip_created"]
                vip_with_onwer = search_form.cleaned_data["vip_with_onwer"]
                hostname = search_form.cleaned_data["hostname"]

                extends_search = dict()
                if hostname:
                    extends_search.update(prepare_hostname(hostname))
                elif len(ipv4) > 0:
                    if request.GET["oct1"]:
                        extends_search.update(
                            {'ipv4__oct1': request.GET["oct1"]})
                    if request.GET["oct2"]:
                        extends_search.update(
                            {'ipv4__oct2': request.GET["oct2"]})
                    if request.GET["oct3"]:
                        extends_search.update(
                            {'ipv4__oct3': request.GET["oct3"]})
                    if request.GET["oct4"]:
                        extends_search.update(
                            {'ipv4__oct4': request.GET["oct4"]})
                elif len(ipv6) > 0:
                    if request.GET["oct1"]:
                        extends_search.update(
                            {'ipv6__block1__iexact': request.GET["oct1"]})
                    if request.GET["oct2"]:
                        extends_search.update(
                            {'ipv6__block2__iexact': request.GET["oct2"]})
                    if request.GET["oct3"]:
                        extends_search.update(
                            {'ipv6__block3__iexact': request.GET["oct3"]})
                    if request.GET["oct4"]:
                        extends_search.update(
                            {'ipv6__block4__iexact': request.GET["oct4"]})
                    if request.GET["oct5"]:
                        extends_search.update(
                            {'ipv6__block5__iexact': request.GET["oct5"]})
                    if request.GET["oct6"]:
                        extends_search.update(
                            {'ipv6__block6__iexact': request.GET["oct6"]})
                    if request.GET["oct7"]:
                        extends_search.update(
                            {'ipv6__block7__iexact': request.GET["oct7"]})
                    if request.GET["oct8"]:
                        extends_search.update(
                            {'ipv6__block8__iexact': request.GET["oct8"]})

                if vip_created:
                    extends_search.update({'created': vip_created})
                if id_vip:
                    extends_search.update({"id": id_vip})
                if vip_with_onwer:
                    user = auth.get_user().get_id()
                    extends_search.update({
                        'viprequestgrouppermission__user_group__usuario':
                        user
                    })

                # Pagination
                column_index_name_map = {
                    0: '',
                    1: 'id',
                    2: 'ipv4',
                    4: 'description',
                    3: 'ipv6',
                    5: 'description',
                    6: 'equipamento',
                    7: 'ambiente',
                    8: 'criado',
                    9: ''
                }
                dtp = DataTablePaginator(request, column_index_name_map)

                # Make params
                dtp.build_server_side_list()

                # Set params in simple Pagination class
                pagination = Pagination(dtp.start_record, dtp.end_record,
                                        dtp.asorting_cols,
                                        dtp.searchable_columns,
                                        dtp.custom_search)

                # Call API passing all params
                # vips = client.create_vip().list_vip_requests(
                #     id_vip, ip, pag, vip_create)

                data = dict()
                data["start_record"] = pagination.start_record
                data["end_record"] = pagination.end_record
                data["asorting_cols"] = pagination.asorting_cols
                data["searchable_columns"] = pagination.searchable_columns
                data["custom_search"] = pagination.custom_search or ""
                data["extends_search"] = [extends_search
                                          ] if extends_search else []

                vips = client.create_api_vip_request().search(
                    search=data,
                    kind='details',
                    fields=[
                        'id', 'name', 'environmentvip', 'ipv4', 'ipv6',
                        'equipments', 'created'
                    ])

                # Returns JSON
                return dtp.build_response(vips["vips"], vips["total"],
                                          templates.AJAX_VIPREQUEST_LIST,
                                          request)

            else:
                # Remake search form
                lists = dict()
                lists["search_form"] = search_form

                # Returns HTML
                response = HttpResponse(
                    loader.render_to_string(
                        templates.SEARCH_FORM_ERRORS,
                        lists,
                        context_instance=RequestContext(request)))
                # Send response status with error
                response.status_code = 412
                return response

    except NetworkAPIClientError, error:
        logger.error(error)
        return HttpResponseServerError(error,
                                       mimetype='application/javascript')
Exemplo n.º 14
0
def ajax_get_objects(request):

    try:

        # If form was submited
        if request.method == "GET":

            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            column_index_name_map = {
                0: '',
                1: 'id',
                2: 'name'
            }

            dtp = DataTablePaginator(request, column_index_name_map)

            # Make params
            dtp.build_server_side_list()

            # Set params in simple Pagination class
            pagination = Pagination(
                dtp.start_record,
                dtp.end_record,
                dtp.asorting_cols,
                dtp.searchable_columns,
                dtp.custom_search)

            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            search = request.GET.get('search')

            if not search:
                raise Exception(u'Empty search')

            id_type_obj = [request.GET.get('id_type_obj')]

            type_obj = client.create_api_object_type(). \
                get(id_type_obj)['ots'][0]['name']

            lists = dict()
            if type_obj == VIPREQUEST_OBJ_TYPE:
                objs = facade.get_vips_request(client, search, pagination, None)

            elif type_obj == SERVERPOOL_OBJ_TYPE:
                objs = facade.get_server_pools(client, search, pagination, None)

            elif type_obj == VLAN_OBJ_TYPE:
                objs = facade.get_vlans(client, search, pagination, None)

            lists['type_obj'] = type_obj

            # Returns JSON
            return dtp.build_response(
                objs['objs'],
                objs['total'],
                templates.USERGROUP_AJAX_OBJECTS,
                request,
                lists
            )

    except NetworkAPIClientError, error:
        logger.error(error)
        return HttpResponseServerError(error, mimetype='application/javascript')
Exemplo n.º 15
0
def ajax_confirm_vlan(request):
    lists = dict()
    try:

        auth = AuthSession(request.session)
        client = auth.get_clientFactory()
        message_confirm = ''
        message_confirm_numbers = ''
        is_number = int(request.GET['is_number'])

        network = None
        ip_version = 2
        number = None
        subnet = 0

        # Check in vlan insert/update
        if is_number == 1:
            number = request.GET['number']
            id_environment = request.GET['id_environment']
            id_vlan = request.GET['id_vlan']
        # Check in net insert
        else:
            netipv4 = request.GET['netipv4']
            netipv6 = request.GET['netipv6']
            id_vlan = request.GET['id_vlan']

            if netipv4 == '':
                ip_version = 1
                network = netipv6
            else:
                ip_version = 0
                network = netipv4
            subnet = 1

        """Filter vlans by number or network subnet"""
        # Pagination
        columnIndexNameMap = {0: '', 1: '', 2: 'num_vlan', 3: 'nome', 4: 'ambiente',
                              5: 'tipo_rede', 6: 'network', 7: '', 8: 'acl_file_name', 9: 'acl_file_name_v6'}
        dtp = DataTablePaginator(request, columnIndexNameMap)

        # Make params
        dtp.build_server_side_list()

        # Set params in simple Pagination class
        pag = Pagination(
            0, 100, dtp.asorting_cols, dtp.searchable_columns, dtp.custom_search)

        # Call API passing all params
        vlans = client.create_vlan().find_vlans(
            number, '', False, None, None, network, ip_version, subnet, False, pag)
        """Filter end"""

        if 'vlan' in vlans:
            for vlan in vlans.get('vlan'):
                # Ignore the same Vlan for validation
                if vlan['id'] != id_vlan:
                    # is_number means that validation is with number vlan
                    # (number used in another environment)
                    if is_number == 1:
                        if int(vlan['ambiente']) != int(id_environment):
                            needs_confirmation = client.create_vlan().confirm_vlan(
                                number, id_environment).get('needs_confirmation')
                            if needs_confirmation == 'True':
                                message_confirm = "a vlan de número " + \
                                    str(number) + " já existe no ambiente " + \
                                    str(vlan['ambiente_name'])
                        else:
                            message_confirm = ''
                            break
                    # else the validation is with network
                    else:
                        network_confirm = network.replace('/', 'net_replace')
                        needs_confirmation = client.create_vlan().confirm_vlan(
                            network_confirm, id_vlan, ip_version).get('needs_confirmation')
                        if needs_confirmation == 'True':
                            message_confirm = "A rede compatível " + str(network) + " já existe no ambiente " + str(
                                vlan['ambiente_name']) + ". Deseja alocar essa rede mesmo assim?"
                        else:
                            message_confirm = ''
                            break

        # also validate if the number is in valid range
        if is_number:
            has_numbers_availables = client.create_vlan().check_number_available(
                id_environment, number, id_vlan).get('has_numbers_availables')
            has_numbers_availables = convert_string_to_boolean(
                has_numbers_availables)
            if not has_numbers_availables:
                message_confirm_numbers = 'O número está fora do range definido'

        # The number is in another environment and the number isn't in right
        # range, so concatenate the messages
        if message_confirm and message_confirm_numbers:
            message_confirm = message_confirm_numbers + \
                ' e a ' + message_confirm
        # Only the number isn't in right range
        elif not message_confirm and message_confirm_numbers:
            message_confirm = message_confirm_numbers

        # Concatenate the question in message
        if is_number and message_confirm:
            message_confirm += '. Deseja criar essa vlan mesmo assim?'

        # Upcase only first letter in message and add to dict
        lists['confirm_message'] = upcase_first_letter(message_confirm)

        # Returns HTML
        response = HttpResponse(loader.render_to_string(
            AJAX_CONFIRM_VLAN, lists, context_instance=RequestContext(request)))
        # Send response status with error
        response.status_code = 200
        return response

    except:

        lists['confirm_message'] = ''
        # Returns HTML
        response = HttpResponse(loader.render_to_string(
            AJAX_CONFIRM_VLAN, lists, context_instance=RequestContext(request)))
        # Send response status with error
        response.status_code = 200
        return response
Exemplo n.º 16
0
def search_environment(request):
    """
    Function to list all environments.
    """

    auth = AuthSession(request.session)
    client = auth.get_clientFactory()
    lists = dict()
    try:
        if request.method == 'GET':
            column_index_name_map = {
                0: '',
                1: 'id',
                2: 'divisao_dc__nome',
                3: 'vrf',
                4: 'dcroom__dc__dcname',
                5: ''
            }

            dtp = DataTablePaginator(request, column_index_name_map)

            dtp.build_server_side_list()

            dtp.searchable_columns = [
                'grupo_l3__nome', 'ambiente_logico__nome', 'divisao_dc__nome',
                'vrf', 'dcroom__dc__dcname', 'dcroom__name'
            ]

            dtp.end_record = 10000

            pagination = Pagination(dtp.start_record, dtp.end_record,
                                    dtp.asorting_cols, dtp.searchable_columns,
                                    dtp.custom_search)

            data = dict()
            data["start_record"] = pagination.start_record
            data["end_record"] = pagination.end_record
            data["asorting_cols"] = [
                'divisao_dc__nome', 'ambiente_logico__nome', 'grupo_l3__nome'
            ]
            data["searchable_columns"] = pagination.searchable_columns
            data["custom_search"] = pagination.custom_search or ""
            data["extends_search"] = []

            fields = [
                'id', 'children__basic', 'vrf', 'name', 'father_environment',
                'configs__details'
            ]

            envs = client.create_api_environment().search(search=data,
                                                          fields=fields)

            lists["envs"] = yaml.safe_load(json.dumps(
                envs.get('environments')))

    except NetworkAPIClientError as e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
    except BaseException as e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)

    return render_to_response(templates.ENVIRONMENT_LIST_V3,
                              lists,
                              context_instance=RequestContext(request))
Exemplo n.º 17
0
def ajax_list_equips(request):

    try:

        # If form was submited
        if request.method == 'GET':
            # Get user auth
            auth = AuthSession(request.session)
            client = auth.get_clientFactory()

            # Get all environments from NetworkAPI
            env_list = client.create_ambiente().list_all()
            # Get all equipment types from NetworkAPI
            type_equip_list = client.create_tipo_equipamento().listar()
            # Get all groups from NetworkAPI
            group_list = client.create_grupo_equipamento().listar()

            search_form = SearchEquipmentForm(
                env_list, type_equip_list, group_list, request.GET)

            if search_form.is_valid():

                name = search_form.cleaned_data['name']
                iexact = search_form.cleaned_data['iexact']
                environment = search_form.cleaned_data['environment']
                equip_type = search_form.cleaned_data['type_equip']
                group = search_form.cleaned_data['group']
                ipv4 = search_form.cleaned_data['ipv4']
                ipv6 = search_form.cleaned_data['ipv6']

                if environment == '0':
                    environment = None
                if equip_type == '0':
                    equip_type = None
                if group == '0':
                    group = None

                if len(ipv4) > 0:
                    ip = ipv4
                elif len(ipv6) > 0:
                    ip = ipv6
                else:
                    ip = None

                # Pagination
                columnIndexNameMap = {
                    0: '', 1: 'nome', 2: 'tipo_equipamento', 3: 'grupos', 4: 'ip', 5: 'vlan', 6: 'ambiente', 7: ''}
                dtp = DataTablePaginator(request, columnIndexNameMap)

                # Make params
                dtp.build_server_side_list()

                # Set params in simple Pagination class
                pag = Pagination(dtp.start_record, dtp.end_record,
                                 dtp.asorting_cols, dtp.searchable_columns, dtp.custom_search)

                # Call API passing all params
                equips = client.create_equipamento().find_equips(
                    name, iexact, environment, equip_type, group, ip, pag)

                if 'equipamento' not in equips:
                    equips['equipamento'] = []

                # Returns JSON
                return dtp.build_response(equips['equipamento'], equips['total'], AJAX_EQUIP_LIST, request)

            else:
                # Remake search form
                lists = dict()
                lists['search_form'] = search_form

                # Returns HTML
                response = HttpResponse(loader.render_to_string(
                    SEARCH_FORM_ERRORS, lists, context_instance=RequestContext(request)))
                # Send response status with error
                response.status_code = 412
                return response

    except NetworkAPIClientError, e:
        logger.error(e)
        return HttpResponseServerError(e, mimetype='application/javascript')