Ejemplo n.º 1
0
def get_dict_v6_to_use_in_configuration_deploy(user, networkipv6, equipment_list):
    """Generate dictionary with vlan an IP information to be used to generate
    template dict for equipment configuration

    Args: networkipv4 NetworkIPv4 object
    equipment_list: Equipamento objects list

    Returns: 2-dimension dictionary with equipments information for template rendering
    """

    try:
        gateway_ip = Ipv6.get_by_blocks_and_net(
            '{0:0{1}x}'.format(int(networkipv6.block1, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block2, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block3, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block4, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block5, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block6, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block7, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block8, 16) + 1, 4),
            networkipv6)
    except IpNotFoundError:
        log.error('Equipment IPs not correctly registered. \
            Router equipments should have first IP of network allocated for them.')
        raise exceptions.IncorrectRedundantGatewayRegistryException()

    ips = Ipv6Equipament.objects.filter(
        ip=gateway_ip, equipamento__in=equipment_list)
    if len(ips) != len(equipment_list):
        log.error('Equipment IPs not correctly registered. \
            Router equipments should have first IP of network allocated for them.')
        raise exceptions.IncorrectRedundantGatewayRegistryException()

    dict_ips = dict()
    if networkipv6.vlan.vrf is not None and networkipv6.vlan.vrf is not '':
        dict_ips['vrf'] = networkipv6.vlan.vrf
    elif networkipv6.vlan.ambiente.vrf is not None:
        dict_ips['vrf'] = networkipv6.vlan.ambiente.vrf

    dict_ips['gateway'] = '%s:%s:%s:%s:%s:%s:%s:%s' % (gateway_ip.block1, gateway_ip.block2, gateway_ip.block3,
                                                       gateway_ip.block4, gateway_ip.block5, gateway_ip.block6, gateway_ip.block7, gateway_ip.block8)
    dict_ips['ip_version'] = 'IPV6'
    dict_ips['equipments'] = dict()
    dict_ips['vlan_num'] = networkipv6.vlan.num_vlan
    dict_ips['vlan_name'] = networkipv6.vlan.nome
    dict_ips['cidr_block'] = networkipv6.block
    dict_ips['mask'] = '%s:%s:%s:%s:%s:%s:%s:%s' % (networkipv6.mask1, networkipv6.mask2, networkipv6.mask3,
                                                    networkipv6.mask4, networkipv6.mask5, networkipv6.mask6, networkipv6.mask7, networkipv6.mask8)
    dict_ips['wildmask'] = 'Not used'

    if _has_active_network_in_vlan(networkipv6.vlan):
        dict_ips['first_network'] = False
    else:
        dict_ips['first_network'] = True

    # Check IPs for routers when there are multiple gateways
    if len(equipment_list) > 1:
        dict_ips['gateway_redundancy'] = True
        equip_number = 0
        for equipment in equipment_list:
            ip_equip = Ipv6Equipament.objects.filter(equipamento=equipment, ip__networkipv6=networkipv6).exclude(ip=gateway_ip)\
                .select_related('ip')
            if ip_equip == []:
                log.error('Error: Equipment IPs not correctly registered. \
                    In case of multiple gateways, they should have an IP other than the gateway registered.')
                raise exceptions.IncorrectNetworkRouterRegistryException()
            ip = ip_equip[0].ip
            dict_ips[equipment] = dict()
            dict_ips[equipment]['ip'] = '%s:%s:%s:%s:%s:%s:%s:%s' % (
                ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8)
            dict_ips[equipment]['prio'] = 100 + equip_number
            equip_number += 1
    else:
        dict_ips['gateway_redundancy'] = False
        dict_ips[equipment_list[0]] = dict()
        dict_ips[equipment_list[0]]['ip'] = dict_ips['gateway']
        dict_ips[equipment_list[0]]['prio'] = 100

    return dict_ips
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to add an IP6 and associate it to an equipment.

        URL: ipv6/save/
        '''

        self.log.info('Add an IP6 and associate it to an equipment')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip6 = ip_map.get('ip6')

            # Valid equip_id
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'Parameter equip_id is invalid. Value: %s.', equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            # Valid network_ipv4_id
            if not is_valid_int_greater_zero_param(network_ipv6_id):
                self.log.error(
                    u'Parameter network_ipv6_id is invalid. Value: %s.', network_ipv6_id)
                raise InvalidValueError(
                    None, 'network_ipv6_id', network_ipv6_id)

            # Description can NOT be greater than 100
            if not is_valid_string_maxsize(ip6, 39):
                self.log.error(u'Parameter ip6 is invalid. Value: %s.', ip6)
                raise InvalidValueError(None, 'ip6', ip6)

            if description is not None:
                if not is_valid_string_maxsize(description, 100) or not is_valid_string_minsize(description, 3):
                    self.log.error(
                        u'Parameter description is invalid. Value: %s.', description)
                    raise InvalidValueError(None, 'description', description)

            # User permission
            if not has_perm(user,
                            AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP
            ipv6 = Ipv6()

            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Caso haja erro para retornar o ip corretamente
                ip_error = ip6
                ip6 = ip6.split(":")

                # Ip informado de maneira incorreta
                if len(ip6) is not 8:
                    raise InvalidValueError(None, 'ip6', ip_error)

                ipv6.description = description
                ipv6.block1 = ip6[0]
                ipv6.block2 = ip6[1]
                ipv6.block3 = ip6[2]
                ipv6.block4 = ip6[3]
                ipv6.block5 = ip6[4]
                ipv6.block6 = ip6[5]
                ipv6.block7 = ip6[6]
                ipv6.block8 = ip6[7]
                # Persist

                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan

                ambiente_aux = None
                vlan_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                            ## Filter case 3 - end ##

                            if flag_vlan_error:

                                vlan_aux = vlan
                                ambiente_aux = vlan.ambiente
                                nome_ambiente = "%s - %s - %s" % (
                                    vlan.ambiente.divisao_dc.nome, vlan.ambiente.ambiente_logico.nome, vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(None,
                                                                  '''O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s), 
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente,
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    ''' % (equip.nome, nome_ambiente, ambiente_aux.id, vlan_aux.id, vlan_atual.num_vlan))

                ipv6.save_ipv6(equip_id, user, net)

                list_ip = []
                lequips = list()

                if ipv6.id is None:
                    ipv6 = Ipv6.get_by_blocks_and_net(
                        ipv6.block1, ipv6.block2, ipv6.block3, ipv6.block4, ipv6.block5, ipv6.block6, ipv6.block7, ipv6.block8, net.id)

                equips = Ipv6Equipament.list_by_ip6(ipv6.id)
                ip_maps = dict()
                ip_maps['id'] = ipv6.id
                ip_maps['block1'] = ipv6.block1
                ip_maps['block2'] = ipv6.block2
                ip_maps['block3'] = ipv6.block3
                ip_maps['block4'] = ipv6.block4
                ip_maps['block5'] = ipv6.block5
                ip_maps['block6'] = ipv6.block6
                ip_maps['block7'] = ipv6.block7
                ip_maps['block8'] = ipv6.block8
                ip_maps['descricao'] = ipv6.description

                list_id_equip = []

                for equip in equips:
                    list_id_equip.append(equip.equipamento.id)
                    equip = Equipamento.get_by_pk(equip.equipamento.id)
                    lequips.append(model_to_dict(equip))
                ip_maps['equipamento'] = lequips
                list_ip.append(ip_maps)

                network_map = dict()
                network_map['ipv6'] = list_ip

                # Delete vlan's cache
                destroy_cache_function([net.vlan_id])

                # Delete equipment's cache
                destroy_cache_function(list_id_equip, True)

                return self.response(dumps_networkapi(network_map))

        except IpRangeAlreadyAssociation, e:
            return self.response_error(347)
Ejemplo n.º 3
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to add an IP6 and associate it to an equipment.

        URL: ipv6/save/
        """

        self.log.info('Add an IP6 and associate it to an equipment')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip6 = ip_map.get('ip6')

            # Valid equip_id
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(u'Parameter equip_id is invalid. Value: %s.',
                               equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            # Valid network_ipv4_id
            if not is_valid_int_greater_zero_param(network_ipv6_id):
                self.log.error(
                    u'Parameter network_ipv6_id is invalid. Value: %s.',
                    network_ipv6_id)
                raise InvalidValueError(None, 'network_ipv6_id',
                                        network_ipv6_id)

            # Description can NOT be greater than 100
            if not is_valid_string_maxsize(ip6, 39):
                self.log.error(u'Parameter ip6 is invalid. Value: %s.', ip6)
                raise InvalidValueError(None, 'ip6', ip6)

            if description is not None:
                if not is_valid_string_maxsize(
                        description, 100) or not is_valid_string_minsize(
                            description, 3):
                    self.log.error(
                        u'Parameter description is invalid. Value: %s.',
                        description)
                    raise InvalidValueError(None, 'description', description)

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION, None, equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None,
                    u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP
            ipv6 = Ipv6()

            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Caso haja erro para retornar o ip corretamente
                ip_error = ip6
                ip6 = ip6.split(':')

                # Ip informado de maneira incorreta
                if len(ip6) is not 8:
                    raise InvalidValueError(None, 'ip6', ip_error)

                ipv6.description = description
                ipv6.block1 = ip6[0]
                ipv6.block2 = ip6[1]
                ipv6.block3 = ip6[2]
                ipv6.block4 = ip6[3]
                ipv6.block5 = ip6[4]
                ipv6.block6 = ip6[5]
                ipv6.block7 = ip6[6]
                ipv6.block8 = ip6[7]
                # Persist

                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan

                ambiente_aux = None
                vlan_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                            ## Filter case 3 - end ##

                            if flag_vlan_error:

                                vlan_aux = vlan
                                ambiente_aux = vlan.ambiente
                                nome_ambiente = '%s - %s - %s' % (
                                    vlan.ambiente.divisao_dc.nome,
                                    vlan.ambiente.ambiente_logico.nome,
                                    vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(
                                    None,
                                    """O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s),
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente,
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    """ %
                                    (equip.nome, nome_ambiente,
                                     ambiente_aux.id, vlan_aux.id,
                                     vlan_atual.num_vlan))

                ipv6.save_ipv6(equip_id, user, net)

                list_ip = []
                lequips = list()

                if ipv6.id is None:
                    ipv6 = Ipv6.get_by_blocks_and_net(ipv6.block1, ipv6.block2,
                                                      ipv6.block3, ipv6.block4,
                                                      ipv6.block5, ipv6.block6,
                                                      ipv6.block7, ipv6.block8,
                                                      net.id)

                equips = Ipv6Equipament.list_by_ip6(ipv6.id)
                ip_maps = dict()
                ip_maps['id'] = ipv6.id
                ip_maps['block1'] = ipv6.block1
                ip_maps['block2'] = ipv6.block2
                ip_maps['block3'] = ipv6.block3
                ip_maps['block4'] = ipv6.block4
                ip_maps['block5'] = ipv6.block5
                ip_maps['block6'] = ipv6.block6
                ip_maps['block7'] = ipv6.block7
                ip_maps['block8'] = ipv6.block8
                ip_maps['descricao'] = ipv6.description

                list_id_equip = []

                for equip in equips:
                    list_id_equip.append(equip.equipamento.id)
                    equip = Equipamento.get_by_pk(equip.equipamento.id)
                    lequips.append(model_to_dict(equip))
                ip_maps['equipamento'] = lequips
                list_ip.append(ip_maps)

                network_map = dict()
                network_map['ipv6'] = list_ip

                # Delete vlan's cache
                destroy_cache_function([net.vlan_id])

                # Delete equipment's cache
                destroy_cache_function(list_id_equip, True)

                return self.response(dumps_networkapi(network_map))

        except IpRangeAlreadyAssociation, e:
            return self.response_error(347)
Ejemplo n.º 4
0
def get_dict_v6_to_use_in_configuration_deploy(user, networkipv6,
                                               equipment_list):
    """Generate dictionary with vlan an IP information to be used to generate
    template dict for equipment configuration

    Args: networkipv4 NetworkIPv4 object
    equipment_list: Equipamento objects list

    Returns: 2-dimension dictionary with equipments information for template rendering
    """

    try:
        gateway_ip = Ipv6.get_by_blocks_and_net(
            '{0:0{1}x}'.format(int(networkipv6.block1, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block2, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block3, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block4, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block5, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block6, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block7, 16), 4),
            '{0:0{1}x}'.format(int(networkipv6.block8, 16) + 1,
                               4), networkipv6)
    except IpNotFoundError:
        log.error('Equipment IPs not correctly registered. \
            Router equipments should have first IP of network allocated for them.'
                  )
        raise exceptions.IncorrectRedundantGatewayRegistryException()

    ips = Ipv6Equipament.objects.filter(ip=gateway_ip,
                                        equipamento__in=equipment_list)
    if len(ips) != len(equipment_list):
        log.error('Equipment IPs not correctly registered. \
            Router equipments should have first IP of network allocated for them.'
                  )
        raise exceptions.IncorrectRedundantGatewayRegistryException()

    dict_ips = dict()
    if networkipv6.vlan.vrf is not None and networkipv6.vlan.vrf is not '':
        dict_ips['vrf'] = networkipv6.vlan.vrf
    elif networkipv6.vlan.ambiente.vrf is not None:
        dict_ips['vrf'] = networkipv6.vlan.ambiente.vrf

    dict_ips['gateway'] = '%s:%s:%s:%s:%s:%s:%s:%s' % (
        gateway_ip.block1, gateway_ip.block2, gateway_ip.block3,
        gateway_ip.block4, gateway_ip.block5, gateway_ip.block6,
        gateway_ip.block7, gateway_ip.block8)
    dict_ips['ip_version'] = 'IPV6'
    dict_ips['equipments'] = dict()
    dict_ips['vlan_num'] = networkipv6.vlan.num_vlan
    dict_ips['vlan_name'] = networkipv6.vlan.nome
    dict_ips['cidr_block'] = networkipv6.block
    dict_ips['mask'] = '%s:%s:%s:%s:%s:%s:%s:%s' % (
        networkipv6.mask1, networkipv6.mask2, networkipv6.mask3,
        networkipv6.mask4, networkipv6.mask5, networkipv6.mask6,
        networkipv6.mask7, networkipv6.mask8)
    dict_ips['wildmask'] = 'Not used'

    if _has_active_network_in_vlan(networkipv6.vlan):
        dict_ips['first_network'] = False
    else:
        dict_ips['first_network'] = True

    # Check IPs for routers when there are multiple gateways
    if len(equipment_list) > 1:
        dict_ips['gateway_redundancy'] = True
        equip_number = 0
        for equipment in equipment_list:
            ip_equip = Ipv6Equipament.objects.filter(equipamento=equipment, ip__networkipv6=networkipv6).exclude(ip=gateway_ip)\
                .select_related('ip')
            if ip_equip == []:
                log.error('Error: Equipment IPs not correctly registered. \
                    In case of multiple gateways, they should have an IP other than the gateway registered.'
                          )
                raise exceptions.IncorrectNetworkRouterRegistryException()
            ip = ip_equip[0].ip
            dict_ips[equipment] = dict()
            dict_ips[equipment]['ip'] = '%s:%s:%s:%s:%s:%s:%s:%s' % (
                ip.block1, ip.block2, ip.block3, ip.block4, ip.block5,
                ip.block6, ip.block7, ip.block8)
            dict_ips[equipment]['prio'] = 100 + equip_number
            equip_number += 1
    else:
        dict_ips['gateway_redundancy'] = False
        dict_ips[equipment_list[0]] = dict()
        dict_ips[equipment_list[0]]['ip'] = dict_ips['gateway']
        dict_ips[equipment_list[0]]['prio'] = 100

    return dict_ips